hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
29a74c4c8a134ec1b7a0928417e12e9836f2549e
2,484
hpp
C++
ODFAEG/extlibs/headers/MySQL/conncpp/CArray.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
null
null
null
ODFAEG/extlibs/headers/MySQL/conncpp/CArray.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
1
2020-02-14T14:19:44.000Z
2020-12-04T17:39:17.000Z
ODFAEG/extlibs/headers/MySQL/conncpp/CArray.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
2
2021-05-23T13:45:28.000Z
2021-07-24T13:36:13.000Z
/************************************************************************************ Copyright (C) 2020 MariaDB Corporation AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not see <http://www.gnu.org/licenses> or write to the Free Software Foundation, Inc., 51 Franklin St., Fifth Floor, Boston, MA 02110, USA *************************************************************************************/ #ifndef _CARRAY_H_ #define _CARRAY_H_ #include "buildconf.hpp" #include <initializer_list> #include <vector> namespace sql { /* Simple C array wrapper template for use to pass arrays from connector */ template <class T> struct CArray { T* arr; int64_t length; operator T*() { return arr; } operator const T*() const { return arr; } operator bool() { return arr != nullptr; } CArray(int64_t len); CArray(int64_t len, const T& fillValue); /* This constructor takes existing(stack?) array for "storing". Won't delete */ CArray(T _arr[], size_t len); CArray(const T _arr[], size_t len); ~CArray(); T* begin() { return arr; } T* end(); std::size_t size() const { return end() - begin(); } const T* begin() const { return arr; } const T* end() const; CArray(std::initializer_list<T> const& initList); CArray(const CArray& rhs); CArray() : arr(nullptr), length(0) {} void assign(const T* _arr, std::size_t size= 0); CArray<T>& wrap(T* _arr, std::size_t size); CArray<T>& wrap(std::vector<T>& _vector); void reserve(std::size_t size); }; MARIADB_EXTERN template struct MARIADB_EXPORTED CArray<char>; MARIADB_EXTERN template struct MARIADB_EXPORTED CArray<int32_t>; MARIADB_EXTERN template struct MARIADB_EXPORTED CArray<int64_t>; typedef CArray<char> bytes; typedef CArray<int32_t> Ints; typedef CArray<int64_t> Longs; } #endif
28.227273
86
0.635266
Mechap
29a8aac9bd73671c0164d2f753462227baaa1fdb
28,594
cpp
C++
src/core/Application.cpp
onqtam/game
08d9f2871bfd5c757d541064b77d38474123592a
[ "MIT" ]
41
2016-10-12T15:54:04.000Z
2022-01-12T04:17:20.000Z
src/core/Application.cpp
onqtam/game
08d9f2871bfd5c757d541064b77d38474123592a
[ "MIT" ]
null
null
null
src/core/Application.cpp
onqtam/game
08d9f2871bfd5c757d541064b77d38474123592a
[ "MIT" ]
10
2015-09-16T19:56:36.000Z
2021-12-27T21:12:11.000Z
#include "Application.h" #include "PluginManager.h" #include "World.h" #include "rendering/GraphicsHelpers.h" #include "rendering/Renderer.h" #include "imgui/ImGuiManager.h" #define RCRL_LIVE_DEMO 1 HA_SUPPRESS_WARNINGS #include <GLFW/glfw3.h> #include <imgui.h> #ifdef EMSCRIPTEN #include <emscripten/emscripten.h> #else // EMSCRIPTEN #if defined(__APPLE__) #define GLFW_EXPOSE_NATIVE_COCOA #define GLFW_EXPOSE_NATIVE_NSGL #elif defined(__linux__) || defined(__unix__) #define GLFW_EXPOSE_NATIVE_X11 #define GLFW_EXPOSE_NATIVE_GLX #elif defined(_WIN32) #define GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WGL #endif // platforms #if !defined(_WIN32) #include <unistd.h> // for chdir() #endif // not windows #include <GLFW/glfw3native.h> #endif // EMSCRIPTEN HA_SUPPRESS_WARNINGS_END // TODO: use a smarter allocator - the important methods here are for the mixin data class global_mixin_allocator : public dynamix::domain_allocator { char* alloc_mixin_data(size_t count, const dynamix::object*) override { return new char[count * mixin_data_size]; } void dealloc_mixin_data(char* ptr, size_t, const dynamix::object*) override { delete[] ptr; } std::pair<char*, size_t> alloc_mixin(const dynamix::basic_mixin_type_info& info, const dynamix::object*) override { size_t size = mem_size_for_mixin(info.size, info.alignment); char* buffer = new char[size]; size_t offset = mixin_offset(buffer, info.alignment); return std::make_pair(buffer, offset); } void dealloc_mixin(char* ptr, size_t, const dynamix::basic_mixin_type_info&, const dynamix::object*) override { delete[] ptr; } }; static ppk::assert::implementation::AssertAction::AssertAction assertHandler( cstr file, int line, cstr function, cstr expression, int level, cstr message) { using namespace ppk::assert::implementation; char buf[2048]; size_t num_written = snprintf(buf, HA_COUNT_OF(buf), "Assert failed!\nFile: %s\nLine: %d\nFunction: %s\nExpression: %s", file, line, function, expression); if(message) snprintf(buf + num_written, HA_COUNT_OF(buf) - num_written, "Message: %s\n", message); fprintf(stderr, "%s", buf); if(level < AssertLevel::Debug) { return static_cast<AssertAction::AssertAction>(0); } else if(AssertLevel::Debug <= level && level < AssertLevel::Error) { #ifdef _WIN32 // this might cause issues if there are multiple windows or threads int res = MessageBox(GetActiveWindow(), buf, "Assert failed! Break in the debugger?", MB_YESNO | MB_ICONEXCLAMATION); if(res == 7) return static_cast<AssertAction::AssertAction>(0); #endif return AssertAction::Break; } else if(AssertLevel::Error <= level && level < AssertLevel::Fatal) { return AssertAction::Throw; } return AssertAction::Abort; } // ================================================================================================= // == APPLICATION INPUT ============================================================================ // ================================================================================================= void Application::mouseButtonCallback(GLFWwindow* window, int button, int action, int) { Application* app = (Application*)glfwGetWindowUserPointer(window); if(action == GLFW_PRESS && button >= 0 && button < 3) app->m_mousePressed[button] = true; InputEvent ev; ev.button = {InputEvent::BUTTON, MouseButton(button), ButtonAction(action)}; Application::get().addInputEvent(ev); } void Application::scrollCallback(GLFWwindow* window, double, double yoffset) { Application* app = (Application*)glfwGetWindowUserPointer(window); #ifdef EMSCRIPTEN yoffset *= -0.01; // fix emscripten/glfw bug - probably related to this: https://github.com/kripken/emscripten/issues/3171 #endif // EMSCRIPTEN app->m_mouseWheel += float(yoffset); InputEvent ev; ev.scroll = {InputEvent::SCROLL, float(yoffset)}; Application::get().addInputEvent(ev); } bool g_console_visible = false; void Application::keyCallback(GLFWwindow*, int key, int, int action, int mods) { // calling the callback from the imgui/glfw integration only if not a dash because when writing an underscore (with shift down) // ImGuiColorTextEdit does a paste - see this for more info: https://github.com/BalazsJako/ImGuiColorTextEdit/issues/18 if(key != '-' || g_console_visible == false) { ImGuiManager::get().onGlfwKeyEvent(key, action); InputEvent ev; ev.key = {InputEvent::KEY, key, KeyAction(action), mods}; Application::get().addInputEvent(ev); } ImGuiIO& io = ImGui::GetIO(); if(g_console_visible) { // add the '\n' char when 'enter' is pressed - for ImGuiColorTextEdit if(io.WantCaptureKeyboard && key == GLFW_KEY_ENTER && !io.KeyCtrl && (action == GLFW_PRESS || action == GLFW_REPEAT)) io.AddInputCharacter((unsigned short)'\n'); } // console toggle if(!io.WantCaptureKeyboard && !io.WantTextInput && key == GLFW_KEY_GRAVE_ACCENT && (action == GLFW_PRESS || action == GLFW_REPEAT)) g_console_visible = !g_console_visible; } void Application::charCallback(GLFWwindow*, unsigned int c) { ImGuiManager::get().onCharEvent(c); } void Application::cursorPosCallback(GLFWwindow*, double x, double y) { static double last_x = 0.0; static double last_y = 0.0; InputEvent ev; ev.mouse = {InputEvent::MOUSE, float(x), float(y), float(x - last_x), float(y - last_y)}; last_x = x; last_y = y; Application::get().addInputEvent(ev); } // ================================================================================================= // == APPLICATION IMPLEMENTATION =================================================================== // ================================================================================================= HA_SINGLETON_INSTANCE(Application); void Application::addInputEventListener(InputEventListener* in) { hassert(std::find(m_inputEventListeners.begin(), m_inputEventListeners.end(), in) == m_inputEventListeners.end()); m_inputEventListeners.push_back(in); } void Application::removeInputEventListener(InputEventListener* in) { auto it = std::find(m_inputEventListeners.begin(), m_inputEventListeners.end(), in); hassert(it != m_inputEventListeners.end()); m_inputEventListeners.erase(it); } void Application::addFrameBeginEventListener(FrameBeginEventListener* in) { hassert(std::find(m_frameBeginEventListeners.begin(), m_frameBeginEventListeners.end(), in) == m_frameBeginEventListeners.end()); m_frameBeginEventListeners.push_back(in); } void Application::removeFrameBeginEventListener(FrameBeginEventListener* in) { auto it = std::find(m_frameBeginEventListeners.begin(), m_frameBeginEventListeners.end(), in); hassert(it != m_frameBeginEventListeners.end()); m_frameBeginEventListeners.erase(it); } int Application::run(int argc, char** argv) { #ifndef EMSCRIPTEN #ifdef _WIN32 #define HA_SET_DATA_CWD SetCurrentDirectory #else // _WIN32 #define HA_SET_DATA_CWD chdir #endif // _WIN32 // set cwd to data folder - this is done for emscripten with the --preload-file flag HA_SET_DATA_CWD((Utils::getPathToExe() + "../../../data").c_str()); #endif // EMSCRIPTEN ppk::assert::implementation::setAssertHandler(assertHandler); #ifdef HA_WITH_PLUGINS // load plugins first so tests in them get executed as well PluginManager pluginManager; pluginManager.init(); #endif // HA_WITH_PLUGINS // run tests doctest::Context context(argc, argv); int tests_res = context.run(); if(context.shouldExit()) return tests_res; // setup global dynamix allocator before any objects are created global_mixin_allocator alloc; dynamix::set_global_allocator(&alloc); // Initialize glfw if(!glfwInit()) return -1; #ifndef EMSCRIPTEN int num_monitors = 0; GLFWmonitor** monitors = glfwGetMonitors(&num_monitors); //GLFWmonitor* monitor = glfwGetPrimaryMonitor(); GLFWmonitor* monitor = monitors[num_monitors - 1]; const GLFWvidmode* mode = glfwGetVideoMode(monitor); m_width = mode->width * 3 / 4; m_height = mode->height * 3 / 4; glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE); glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); #endif // EMSCRIPTEN // Create a window m_window = glfwCreateWindow(width(), height(), "game", nullptr, nullptr); if(!m_window) { glfwTerminate(); return -1; } #ifndef EMSCRIPTEN // Simulating fullscreen - by placing the window in 0,0 int monitor_pos_x, monitor_pos_y; glfwGetMonitorPos(monitor, &monitor_pos_x, &monitor_pos_y); glfwSetWindowPos(m_window, monitor_pos_x, monitor_pos_y); //glfwSetWindowMonitor(m_window, monitor, 0, 0, width(), height(), mode->refreshRate); #endif // EMSCRIPTEN // Setup input callbacks glfwSetWindowUserPointer(m_window, this); glfwMakeContextCurrent(m_window); glfwSetMouseButtonCallback(m_window, mouseButtonCallback); glfwSetScrollCallback(m_window, scrollCallback); glfwSetKeyCallback(m_window, keyCallback); glfwSetCharCallback(m_window, charCallback); glfwSetCursorPosCallback(m_window, cursorPosCallback); glfwSetCursorPos(m_window, width() / 2, height() / 2); // Setup rendering #if defined(_WIN32) auto glewInitResult = glewInit(); if(glewInitResult != GLEW_OK) { fprintf(stderr, "Couldn't initialize glew. Reason: %s\n", glewGetErrorString(glewInitResult)); glfwTerminate(); return -1; } #endif glEnable(GL_DEPTH_TEST); // z buffer glEnable(GL_CULL_FACE); // cull back (CW) faces glClearColor(0.75f, 0.05f, 0.65f, 1); // Initialize the application reset(); // introduce this scope in order to control the lifetimes of managers { // resource managers should be created first and destroyed last - all // objects should be destroyed so the refcounts to the resources are 0 ShaderMan shaderMan; GeomMan geomMan; ObjectManager objectMan; World world; ImGuiManager imguiManager; Renderer renderer; #ifdef EMSCRIPTEN emscripten_set_main_loop([]() { Application::get().update(); }, 0, 1); #else // EMSCRIPTEN while(!glfwWindowShouldClose(m_window)) update(); #endif // EMSCRIPTEN // set the state to something other than EDITOR Application::get().setState(Application::State::PLAY); } glfwTerminate(); return tests_res; } void Application::processEvents() { // leave it here for now. Decide whether to replace it later... ImGuiIO& io = ImGui::GetIO(); for(size_t i = 0; i < m_inputs.size(); ++i) for(auto& curr : m_inputEventListeners) if((m_inputs[i].type == InputEvent::KEY && !io.WantCaptureKeyboard) || (m_inputs[i].type == InputEvent::MOUSE && !io.WantCaptureMouse) || (m_inputs[i].type == InputEvent::BUTTON && !io.WantCaptureMouse) || (m_inputs[i].type == InputEvent::SCROLL && !io.WantCaptureMouse)) curr->process_event(m_inputs[i]); m_inputs.clear(); } void Application::update() { #ifdef HA_WITH_PLUGINS // reload plugins PluginManager::get().update(); #endif // HA_WITH_PLUGINS m_time = float(glfwGetTime()); m_dt = m_time - m_lastTime; m_lastTime = m_time; // poll for events - also dispatches to imgui glfwPollEvents(); ImGuiManager::get().update(m_dt); // imgui ImGui::NewFrame(); // main imgui font ImGui::PushFont(ImGuiManager::get().getMainFont()); // signal for(auto& curr : m_frameBeginEventListeners) curr->on_event(); // send input events to the rest of the app processEvents(); int w, h; glfwGetWindowSize(m_window, &w, &h); // update game stuff World::get().update(); // pop main font ImGui::PopFont(); #if defined(HA_WITH_PLUGINS) && defined(_MSC_VER) void do_rcrl(int); do_rcrl(w); #endif // HA_WITH_PLUGINS && MSVC // render glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, m_width, m_height); Renderer::get().render(); ImGui::Render(); glfwSwapBuffers(m_window); // handle resizing if(uint32(w) != m_width || uint32(h) != m_height) { m_width = w; m_height = h; reset(m_reset); } } void Application::reset(uint32 flags) { m_reset = flags; } #if defined(HA_WITH_PLUGINS) && defined(_MSC_VER) #include <ImGuiColorTextEdit/TextEditor.h> #include "rcrl/rcrl.h" void do_rcrl(int window_w) { // push big font for rcrl ImGui::PushFont(ImGuiManager::get().getBigFont()); ImGuiIO& io = ImGui::GetIO(); static TextEditor history; static TextEditor compiler_output; static TextEditor program_output(compiler_output); static TextEditor editor; static int last_compiler_exitcode = 0; static bool used_default_mode = false; static rcrl::Mode default_mode = rcrl::ONCE; static bool inited = false; if(!inited) { inited = true; history.SetLanguageDefinition(TextEditor::LanguageDefinition::CPlusPlus()); history.SetReadOnly(true); history.SetText("#include \"precompiled.h\"\n"); compiler_output.SetLanguageDefinition(TextEditor::LanguageDefinition()); compiler_output.SetReadOnly(true); auto custom_palette = TextEditor::GetDarkPalette(); custom_palette[(int)TextEditor::PaletteIndex::MultiLineComment] = 0xcccccccc; // text is treated as such by default compiler_output.SetPalette(custom_palette); editor.SetLanguageDefinition(TextEditor::LanguageDefinition::CPlusPlus()); #if !RCRL_LIVE_DEMO // set some initial code editor.SetText(R"raw(// vars auto& objects = ObjectManager::get().getObjects(); // once for(auto& obj : objects) obj.second.move_local({20, 0, 0}); )raw"); #endif // RCRL_LIVE_DEMO } // console should be always fixed ImGui::SetNextWindowSize({(float)window_w, -1.f}, ImGuiCond_Always); ImGui::SetNextWindowPos({0.f, 0.f}, ImGuiCond_Always); ImGui::SetNextWindowBgAlpha(1); // sets breakpoints on the program_output instance of the text editor widget - used to highlight new output auto do_breakpoints_on_output = [&](int old_line_count, const std::string& new_output) { TextEditor::Breakpoints bps; if(old_line_count == program_output.GetTotalLines() && new_output.size()) bps.insert(old_line_count); for(auto curr_line = old_line_count; curr_line < program_output.GetTotalLines(); ++curr_line) bps.insert(curr_line); program_output.SetBreakpoints(bps); }; if(g_console_visible && ImGui::Begin("console", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { const auto text_field_height = ImGui::GetTextLineHeight() * 12; const float left_right_ratio = 0.5f; // top left part ImGui::BeginChild("history code", ImVec2(window_w * left_right_ratio, text_field_height)); auto hcpos = history.GetCursorPosition(); ImGui::Text("Executed code: %3d/%-3d %3d lines", hcpos.mLine + 1, hcpos.mColumn + 1, editor.GetTotalLines()); history.Render("History"); ImGui::EndChild(); ImGui::SameLine(); // top right part ImGui::BeginChild("compiler output", ImVec2(0, text_field_height)); auto new_output = rcrl::get_new_compiler_output(); if(new_output.size()) { auto total_output = compiler_output.GetText() + new_output; // scan for errors through the lines and highlight them with markers size_t curr_pos = 0; auto line = 1; auto first_error_marker_line = 0; TextEditor::ErrorMarkers error_markers; do { auto new_curr_pos_1 = total_output.find("error", curr_pos + 1); // add 1 to skip new lines auto new_curr_pos_2 = total_output.find("\n", curr_pos + 1); // add 1 to skip new lines if(new_curr_pos_1 < new_curr_pos_2) { error_markers.insert(std::make_pair(line, "")); if(!first_error_marker_line) first_error_marker_line = line; } if(new_curr_pos_2 < new_curr_pos_1) { line++; } curr_pos = std::min(new_curr_pos_1, new_curr_pos_2); } while(size_t(curr_pos) != std::string::npos); compiler_output.SetErrorMarkers(error_markers); // update compiler output compiler_output.SetText(move(total_output)); if(first_error_marker_line) compiler_output.SetCursorPosition({first_error_marker_line, 1}); else compiler_output.SetCursorPosition({compiler_output.GetTotalLines(), 1}); } if(last_compiler_exitcode) ImGui::TextColored({1, 0, 0, 1}, "Compiler output - ERROR!"); else ImGui::Text("Compiler output: "); ImGui::SameLine(); auto cocpos = compiler_output.GetCursorPosition(); ImGui::Text("%3d/%-3d %3d lines", cocpos.mLine + 1, cocpos.mColumn + 1, compiler_output.GetTotalLines()); compiler_output.Render("Compiler output"); ImGui::EndChild(); // bottom left part ImGui::BeginChild("source code", ImVec2(window_w * left_right_ratio, text_field_height)); auto ecpos = editor.GetCursorPosition(); ImGui::Text("RCRL Console: %3d/%-3d %3d lines | %s", ecpos.mLine + 1, ecpos.mColumn + 1, editor.GetTotalLines(), editor.CanUndo() ? "*" : " "); editor.Render("Code"); ImGui::EndChild(); ImGui::SameLine(); // bottom right part ImGui::BeginChild("program output", ImVec2(0, text_field_height)); auto ocpos = program_output.GetCursorPosition(); ImGui::Text("Program output: %3d/%-3d %3d lines", ocpos.mLine + 1, ocpos.mColumn + 1, program_output.GetTotalLines()); program_output.Render("Output"); ImGui::EndChild(); // bottom buttons ImGui::Text("Default mode:"); ImGui::SameLine(); ImGui::RadioButton("global", (int*)&default_mode, rcrl::GLOBAL); ImGui::SameLine(); ImGui::RadioButton("vars", (int*)&default_mode, rcrl::VARS); ImGui::SameLine(); ImGui::RadioButton("once", (int*)&default_mode, rcrl::ONCE); ImGui::SameLine(); auto compile = ImGui::Button("Compile and run"); ImGui::SameLine(); if(ImGui::Button("Cleanup Plugins") && !rcrl::is_compiling()) { compiler_output.SetText(""); auto output_from_cleanup = rcrl::cleanup_plugins(true); auto old_line_count = program_output.GetTotalLines(); program_output.SetText(program_output.GetText() + output_from_cleanup); program_output.SetCursorPosition({program_output.GetTotalLines(), 0}); last_compiler_exitcode = 0; history.SetText("#include \"precompiled_for_plugin.h\"\n"); // highlight the new stdout lines do_breakpoints_on_output(old_line_count, output_from_cleanup); } ImGui::SameLine(); if(ImGui::Button("Clear Output")) program_output.SetText(""); ImGui::SameLine(); ImGui::Dummy({20, 0}); ImGui::SameLine(); #if !RCRL_LIVE_DEMO ImGui::Text("Use Ctrl+Enter to submit code"); #endif // RCRL_LIVE_DEMO // if the user has submitted code for compilation #if RCRL_LIVE_DEMO extern std::list<const char*> fragments; if(!rcrl::is_compiling() && editor.GetText().size() < 2 && fragments.size() && io.KeysDown[GLFW_KEY_ENTER] && io.KeyCtrl) { editor.SetText(fragments.front()); fragments.pop_front(); } #else // RCRL_LIVE_DEMO compile |= (io.KeysDown[GLFW_KEY_ENTER] && io.KeyCtrl); #endif // RCRL_LIVE_DEMO if(compile && !rcrl::is_compiling() && editor.GetText().size() > 1) { // clear compiler output compiler_output.SetText(""); auto getCodePrefix = [&]() { #ifdef __APPLE__ // related to this: https://github.com/onqtam/rcrl/issues/4 static bool first_time_called = true; if(first_time_called) { first_time_called = false; return string("//global\n#include \"precompiled_for_plugin.h\"\n") + (default_mode == rcrl::GLOBAL ? "// global\n" : (default_mode == rcrl::VARS ? "// vars\n" : "// once\n")); } #endif return std::string(""); }; // submit to the RCRL engine if(rcrl::submit_code(getCodePrefix() + editor.GetText(), default_mode, &used_default_mode)) { // make the editor code untouchable while compiling editor.SetReadOnly(true); } else { last_compiler_exitcode = 1; } } ImGui::End(); } // if there is a spawned compiler process and it has just finished if(rcrl::try_get_exit_status_from_compile(last_compiler_exitcode)) { // we can edit the code again editor.SetReadOnly(false); if(last_compiler_exitcode) { // errors occurred - set cursor to the last line of the erroneous code editor.SetCursorPosition({editor.GetTotalLines(), 0}); } else { // append to the history and focus last line history.SetCursorPosition({history.GetTotalLines(), 1}); auto history_text = history.GetText(); // add a new line (if one is missing) to the code that will go to the history for readability if(history_text.size() && history_text.back() != '\n') history_text += '\n'; // if the default mode was used - add an extra comment before the code to the history for clarity if(used_default_mode) history_text += default_mode == rcrl::GLOBAL ? "// global\n" : (default_mode == rcrl::VARS ? "// vars\n" : "// once\n"); history.SetText(history_text + editor.GetText()); // load the new plugin auto output_from_loading = rcrl::copy_and_load_new_plugin(true); auto old_line_count = program_output.GetTotalLines(); program_output.SetText(program_output.GetText() + output_from_loading); // TODO: used for auto-scroll but the cursor in the editor is removed (unfocused) sometimes from this... //program_output.SetCursorPosition({program_output.GetTotalLines(), 0}); // highlight the new stdout lines do_breakpoints_on_output(old_line_count, output_from_loading); // clear the editor editor.SetText("\r"); // an empty string "" breaks it for some reason... editor.SetCursorPosition({0, 0}); } } // pop the big badboy font ImGui::PopFont(); } #if RCRL_LIVE_DEMO std::list<const char*> fragments = { R"raw(// vars auto& objects = ObjectManager::get().getObjects(); )raw", // =============================================== R"raw(// once for(auto& obj : objects) if(obj.second.has("mesh")) obj.second.move_local({10, 0, 0}); )raw", // =============================================== R"raw(// global #include "core/World.h" // once World::get().camera().obj().move_local({0, 30, 0}); )raw", // =============================================== R"raw(// global #include "imgui.h" #include "core/Events.h" struct Painter : public FrameBeginEventListener { void on_event() override { // called on each frame ImGui::ShowDemoWindow(); } }; // vars Painter painter; // instantiate it )raw", // =============================================== R"raw(// once JsonData state; state.startObject(); state.addKey("objects"); state.startArray(); for(auto& o : objects) { auto& curr = o.second; state.startObject(); state.addKey("id"); auto id_str = std::to_string(oid::internal_type(curr.id())); state.append(id_str.c_str(), id_str.size()); state.addComma(); state.addKey("state"); serialize(curr, state); state.addComma(); state.addKey("mixins"); state.startObject(); if(curr.implements(common::serialize_mixins_msg)) common::serialize_mixins(curr, nullptr, state); state.endObject(); state.endObject(); state.addComma(); } state.endArray(); state.endObject(); // save to a file state.prettify(); state.fwrite("level.json"); )raw", // =============================================== // DO NOT CLEAN UP PLUGINS AFTER THIS SNIPPET! WILL CRASH! // DO NOT SUBMIT ANY MORE SNIPPETS AFTER THIS! WILL CRASH! R"raw(// global #include "core/rendering/GraphicsHelpers.h" #include "core/messages/messages_rendering.h" class green_wireframe_mesh { GeomMan::Handle mesh; public: green_wireframe_mesh() { mesh = GeomMan::get().get("", createSolidBox, 0.8f, 0.8f, 0.8f, 0xFF00BB00); } void get_rendering_parts(std::vector<renderPart>& out) const { out.push_back({mesh, TempMesh(), ha_this.get_transform().as_mat()}); } AABB get_aabb() const { return mesh.get().bbox; } }; HA_MIXIN_DEFINE_WITHOUT_CODEGEN(green_wireframe_mesh, rend::get_rendering_parts_msg& rend::get_aabb_msg) // once for(auto& curr : getMixins_Local()) // not important getAllMixins()[curr.first] = curr.second; // for each object - add a green attachment for(auto& curr : objects) { auto& obj = curr.second; if(!obj.has("mesh")) continue; auto& att = ObjectManager::get().create("attachment"); att.addMixin("green_wireframe_mesh"); att.set_parent(obj.id()); att.move_local({0, 3, 0}); } )raw", // =============================================== // this should go into a separate file - to not have to scroll through the rest R"raw(// once JsonData state; state.fread("level.json"); const auto& doc = state.parse(); hassert(doc.is_valid()); // for each object auto objects_array = doc.get_root().get_object_value(0); for(size_t i = 0; i < objects_array.get_length(); ++i) { auto json_obj = objects_array.get_array_element(i); auto obj_id = oid( oid::internal_type(json_obj.get_value_of_key({"id", 2}).get_integer_value())); Object* o = nullptr; if(ObjectManager::get().has(obj_id)) { // either get it o = &ObjectManager::get().getById(obj_id); } else { // or create it o = &ObjectManager::get().createFromId( oid(int16(json_obj.get_value_of_key({"id", 2}).get_integer_value()))); } // deserialize the attibutes of the object itself deserialize(*o, json_obj.get_value_of_key({"state", 5})); // add mixins to the objects auto mixins_json = json_obj.get_value_of_key({"mixins", 6}); for(size_t k = 0; k < mixins_json.get_length(); ++k) o->addMixin(mixins_json.get_object_key(k).data()); // and deserialize the attributes of those mixins if(o->implements(common::deserialize_mixins_msg)) common::deserialize_mixins(*o, mixins_json); } )raw"}; #endif // RCRL_LIVE_DEMO #endif // HA_WITH_PLUGINS && MSVC
36.103535
131
0.612506
onqtam
29a8ab5bc3786f88708aa04a156d493e82f7dbb1
737
hpp
C++
TenNenDemon/Code/Game/CutsceneDefinition.hpp
sam830917/TenNenDemon
a5f60007b73cccc6af8675c7f3dec597008dfdb4
[ "MIT" ]
null
null
null
TenNenDemon/Code/Game/CutsceneDefinition.hpp
sam830917/TenNenDemon
a5f60007b73cccc6af8675c7f3dec597008dfdb4
[ "MIT" ]
null
null
null
TenNenDemon/Code/Game/CutsceneDefinition.hpp
sam830917/TenNenDemon
a5f60007b73cccc6af8675c7f3dec597008dfdb4
[ "MIT" ]
null
null
null
#pragma once #include "Engine/Core/XmlUtils.hpp" #include <map> #include <vector> #include <string> class Texture; struct CutsceneLines { std::string m_line = ""; std::string m_characterName = ""; Texture* m_background = nullptr; Texture* m_characterImage = nullptr; }; class CutsceneDefinition { public: static void LoadDefinitions( const std::string& folderPath ); static CutsceneDefinition* GetDefinitions( const std::string& deinitionsName ); public: CutsceneDefinition( const XmlElement& cutsceneDefElement, const std::string& name ); ~CutsceneDefinition(); private: static std::map< std::string, CutsceneDefinition* > s_definitionMap; public: std::string m_name = ""; std::vector<const CutsceneLines*> m_lines; };
21.676471
85
0.750339
sam830917
29a91c33b90e0a0097b9caae6a983e194f40b3b6
1,687
cpp
C++
C++/001_Two_Sum.cpp
stephenkid/LeetCode-Sol
8cb429652e0741ca4078b6de5f9eeaddcb8607a8
[ "MIT" ]
1,958
2015-01-30T01:19:03.000Z
2022-03-17T03:34:47.000Z
src/main/cpp/001_Two_Sum.cpp
TechnoBlogger14o3/LeetCode-Sol-Res
04621f21a76fab29909c1fa04a37417257a88f63
[ "MIT" ]
135
2016-03-03T04:53:10.000Z
2022-03-03T21:14:37.000Z
src/main/cpp/001_Two_Sum.cpp
TechnoBlogger14o3/LeetCode-Sol-Res
04621f21a76fab29909c1fa04a37417257a88f63
[ "MIT" ]
914
2015-01-27T22:27:22.000Z
2022-03-05T04:25:10.000Z
/* *Given an array of integers, return indices of the two numbers such that they add up to a specific target. *You may assume that each input would have exactly one solution. *Example: *Given nums = [2, 7, 11, 15], target = 9, *Because nums[0] + nums[1] = 2 + 7 = 9, *return [0, 1]. *UPDATE (2016/2/13): *The return format had been changed to zero-based indices. Please read the above updated description carefully *Tag: Array, Hash Table *Author: Linsen Wu */ #include "stdafx.h" #include "iostream" #include <vector> #include <unordered_map> using namespace std; class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> indexResults; unordered_map<int, int> index_map; unordered_map<int, int>::iterator it; for (int i=0; i<numbers.size(); ++i) { it = index_map.find(target-numbers[i]); if (it != index_map.end()) { indexResults.push_back(it->second); indexResults.push_back(i); return indexResults; } else { index_map[numbers[i]] = i; } } return indexResults; } }; /* Save the numbers into an unordered map when searching Time: O(n) Space: O(n) */ int _tmain(int argc, _TCHAR* argv[]) { vector<int> input, output; input.push_back(-1); input.push_back(7); input.push_back(11); input.push_back(15); Solution _solution; output = _solution.twoSum(input, 6); for(vector<int>::iterator iterator = output.begin(); iterator != output.end(); iterator++) cout<<((*iterator))<<endl; system("Pause"); return 0; }
23.430556
111
0.609366
stephenkid
29a981a9ffe71d9af92058659e721749035752b5
6,685
cpp
C++
Graphics/src/GLSLProgram.cpp
MarcoLotto/ScenaFramework
533e5149a1580080e41bfb37d5648023b6e39f6f
[ "MIT" ]
2
2019-01-21T20:47:29.000Z
2020-01-09T01:08:24.000Z
Graphics/src/GLSLProgram.cpp
MarcoLotto/ScaenaFramework
533e5149a1580080e41bfb37d5648023b6e39f6f
[ "MIT" ]
null
null
null
Graphics/src/GLSLProgram.cpp
MarcoLotto/ScaenaFramework
533e5149a1580080e41bfb37d5648023b6e39f6f
[ "MIT" ]
null
null
null
/********************************** * SCAENA FRAMEWORK * Author: Marco Andrés Lotto * License: MIT - 2016 **********************************/ #include "Mesh.h" #include "GLSLProgram.h" #include "GLSLProgramGLImplementation.h" #include "GLSLProgramGLES3Implementation.h" #include "GLSLProgramGLES2Implementation.h" #include "GLSLProgramMockImplementation.h" #include "ApiNotBindException.h" #include "ApiVariableTypeDoesNotExistException.h" int GLSLProgram::apiInUse = -1; // Indicador del API que se utiliza // Para elegir que api utilar void GLSLProgram::bindApi(int apiId){ apiInUse = apiId; } GLSLProgramInterface* GLSLProgram::createProgramImplementation(){ if(apiInUse == -1){ throw new ApiNotBindException("No se indico ningun API a usar al GLSLProgram"); } // Se deben definir en el preprocesador las opciones disponibles para la plataforma en donde se compila switch(apiInUse){ #ifdef OPENGL4 case OPENGL_API: return new GLSLProgramGLImplementation(); break; #endif #ifdef OPENGLES3 case OPENGLES_3_API: return new GLSLProgramGLES3Implementation(); break; #endif #ifdef OPENGLES2 case OPENGLES_2_API: return new GLSLProgramGLES2Implementation(); break; #endif case MOCK_API: return new GLSLProgramMockImplementation(); break; default: throw new ApiVariableTypeDoesNotExistException("El API informada al GLSLProgram no es correcta"); break; } } GLSLProgram::GLSLProgram(){ this->implementation = this->createProgramImplementation(); } GLSLProgram::~GLSLProgram(){ delete this->implementation; } //Compila el shader pasado por parametro. El segundo argumento es el tipo de shader a compilar bool GLSLProgram::compileShaderFromFile( const char * fileName, GLSLShader::GLSLShaderType type ){ return this->implementation->compileShaderFromFile(fileName, type); } //Asocia el indice "location" al nombre de variable del shader void GLSLProgram::bindAttribLocation( unsigned int location, const char * name){ this->implementation->bindAttribLocation(location, name); } //Asocia el output del fragment shader a un indice "location" void GLSLProgram::bindFragDataLocation( unsigned int location, const char * name ){ this->implementation->bindFragDataLocation(location, name); } //Linkea los shaders al programa bool GLSLProgram::link(string programBaseName){ return this->implementation->link(programBaseName); } //Empiza a usar los shaders cargados. void GLSLProgram::use(){ this->implementation->use(); } int GLSLProgram::getHandle(){ return this->implementation->getHandle(); } bool GLSLProgram::isLinked(){ return this->implementation->isLinked(); } void GLSLProgram::setUniform(GLSLUniform* uniform, float x, float y, float z){ this->implementation->setUniform(uniform, x, y, z); } void GLSLProgram::setUniform(GLSLUniform* uniform, const glm::vec2 & v){ this->implementation->setUniform(uniform, v); } void GLSLProgram::setUniform(GLSLUniform* uniform, const glm::vec3 & v){ this->implementation->setUniform(uniform, v); } void GLSLProgram::setUniform(GLSLUniform* uniform, int size, const glm::vec3 & v){ this->implementation->setUniform(uniform, v); } void GLSLProgram::setUniform(GLSLUniform* uniform, const glm::vec4 & v){ this->implementation->setUniform(uniform, v); } void GLSLProgram::setUniform(GLSLUniform* uniform, int size, const glm::vec4 & v){ this->implementation->setUniform(uniform, v); } void GLSLProgram::setUniform(GLSLUniform* uniform, const glm::mat4 &m){ this->implementation->setUniform(uniform, m); } void GLSLProgram::setUniform(GLSLUniform* uniform, const glm::mat3 & m){ this->implementation->setUniform(uniform, m); } void GLSLProgram::setUniform(GLSLUniform* uniform, const glm::mat2 & m){ this->implementation->setUniform(uniform, m); } void GLSLProgram::setUniform(GLSLUniform* uniform, int size, const glm::mat4 &m){ this->implementation->setUniform(uniform, size, m); } void GLSLProgram::setUniform(GLSLUniform* uniform, int size, const glm::mat3 & m){ this->implementation->setUniform(uniform, size, m); } void GLSLProgram::setUniform(GLSLUniform* uniform, int size, const glm::mat2 & m){ this->implementation->setUniform(uniform, size, m); } void GLSLProgram::setUniform(GLSLUniform* uniform, float val ){ this->implementation->setUniform(uniform, val); } void GLSLProgram::setUniform(GLSLUniform* uniform, int val ){ this->implementation->setUniform(uniform, val); } void GLSLProgram::setUniform(GLSLUniform* uniform, unsigned int val ){ this->implementation->setUniform(uniform, val); } void GLSLProgram::setUniform(GLSLUniform* uniform, bool val ){ this->implementation->setUniform(uniform, val); } void GLSLProgram::setVectorUniform(GLSLUniform* uniform, unsigned int size, float* vector ){ this->implementation->setVectorUniform(uniform, size, vector); } void GLSLProgram::setVectorUniform(GLSLUniform* uniform, unsigned int size, int* vector ){ this->implementation->setVectorUniform(uniform, size, vector); } void GLSLProgram::setVectorUniform(GLSLUniform* uniform, unsigned int size, unsigned int* vector ){ this->implementation->setVectorUniform(uniform, size, vector); } int GLSLProgram::getUniformLocation(const char *name){ return this->implementation->getUniformLocation(name); } void GLSLProgram::changeSubroutineInFragmentShader(const char* subroutineName){ this->implementation->changeSubroutineInFragmentShader(subroutineName); } void GLSLProgram::initialize(list<string>* inputAttributes, list<string>* outputAttributes, bool usedForFeedback){ this->implementation->initialize(inputAttributes, outputAttributes, usedForFeedback); } // Permito setear en clases hijas los nombres stages de shader que quieren usar void GLSLProgram::setVertexShaderName(string filename){ this->implementation->setVertexShaderName(filename); } void GLSLProgram::setGeometryShaderName(string filename){ this->implementation->setGeometryShaderName(filename); } void GLSLProgram::setTesselationEvaluationShaderName(string filename){ this->implementation->setTesselationEvaluationShaderName(filename); } void GLSLProgram::setTesselationControlShaderName(string filename){ this->implementation->setTesselationControlShaderName(filename); } void GLSLProgram::setComputeShaderName(string filename){ this->implementation->setComputeShaderName(filename); } void GLSLProgram::setFragmentShaderName(string filename){ this->implementation->setFragmentShaderName(filename); } // La distancia hasta el centro del objeto float GLSLProgram::getDistanceFactor(){ return this->implementation->getDistanceFactor(); } void GLSLProgram::setDistanceFactor(float distance){ this->implementation->setDistanceFactor(distance); }
32.294686
114
0.770681
MarcoLotto
29b08b9a31543499edd4949d6a60db52a6734f4e
2,312
cpp
C++
Source/RendererCore/D3D12/D3D12CommandPool.cpp
DavidTheFighter/KalosEngine
4c550114066bee1c41d08f38f5b692e567e96c27
[ "MIT" ]
1
2018-12-16T21:19:58.000Z
2018-12-16T21:19:58.000Z
Source/RendererCore/D3D12/D3D12CommandPool.cpp
DavidTheFighter/KalosEngine
4c550114066bee1c41d08f38f5b692e567e96c27
[ "MIT" ]
null
null
null
Source/RendererCore/D3D12/D3D12CommandPool.cpp
DavidTheFighter/KalosEngine
4c550114066bee1c41d08f38f5b692e567e96c27
[ "MIT" ]
null
null
null
#include "RendererCore/D3D12/D3D12CommandPool.h" #if BUILD_D3D12_BACKEND #include <RendererCore/D3D12/D3D12Renderer.h> #include <RendererCore/D3D12/D3D12CommandBuffer.h> #include <RendererCore/D3D12/D3D12Enums.h> D3D12CommandPool::D3D12CommandPool(D3D12Renderer *rendererPtr, QueueType queueType) { renderer = rendererPtr; cmdListType = queueTypeToD3D12CommandListType(queueType); DX_CHECK_RESULT(renderer->device->CreateCommandAllocator(cmdListType, IID_PPV_ARGS(&cmdAlloc))); DX_CHECK_RESULT(renderer->device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundleCmdAlloc))); } D3D12CommandPool::~D3D12CommandPool() { for (size_t i = 0; i < allocatedCmdLists.size(); i++) delete allocatedCmdLists[i]; cmdAlloc->Release(); bundleCmdAlloc->Release(); } RendererCommandBuffer *D3D12CommandPool::allocateCommandBuffer(CommandBufferLevel level) { return allocateCommandBuffers(level, 1)[0]; } std::vector<RendererCommandBuffer*> D3D12CommandPool::allocateCommandBuffers(CommandBufferLevel level, uint32_t commandBufferCount) { std::vector<RendererCommandBuffer*> cmdBuffers; for (uint32_t i = 0; i < commandBufferCount; i++) { D3D12CommandBuffer *cmdBuffer = new D3D12CommandBuffer(renderer, this, level == COMMAND_BUFFER_LEVEL_PRIMARY ? cmdListType : D3D12_COMMAND_LIST_TYPE_BUNDLE); cmdBuffers.push_back(cmdBuffer); allocatedCmdLists.push_back(cmdBuffer); } return cmdBuffers; } void D3D12CommandPool::resetCommandPoolAndFreeCommandBuffer(RendererCommandBuffer *commandBuffer) { resetCommandPoolAndFreeCommandBuffers({commandBuffer}); } void D3D12CommandPool::resetCommandPoolAndFreeCommandBuffers(const std::vector<RendererCommandBuffer*> &commandBuffers) { for (size_t i = 0; i < commandBuffers.size(); i++) { auto it = std::find(allocatedCmdLists.begin(), allocatedCmdLists.end(), static_cast<D3D12CommandBuffer*>(commandBuffers[i])); if (it != allocatedCmdLists.end()) allocatedCmdLists.erase(it); delete commandBuffers[i]; } } void D3D12CommandPool::resetCommandPool() { for (size_t i = 0; i < allocatedCmdLists.size(); i++) static_cast<D3D12CommandBuffer*>(allocatedCmdLists[i])->startedRecording = false; cmdAlloc->Reset(); bundleCmdAlloc->Reset(); } #endif
32.111111
160
0.768166
DavidTheFighter
29b2eaef2648af9c18fc65796d59851e8232b5aa
508
cpp
C++
src/Player/LocalPlayer.cpp
f0xeri/Mine-Plus-Plus
52c8323913b30e5c2837925dc88de002fe0e1b78
[ "MIT" ]
28
2021-04-04T13:55:04.000Z
2022-02-01T05:51:21.000Z
src/Player/LocalPlayer.cpp
codingwatching/Mine-Plus-Plus
7b90c904b660dd5089c44dbf34d494367d0d060b
[ "MIT" ]
1
2021-07-28T15:33:42.000Z
2021-07-28T15:33:42.000Z
src/Player/LocalPlayer.cpp
codingwatching/Mine-Plus-Plus
7b90c904b660dd5089c44dbf34d494367d0d060b
[ "MIT" ]
1
2021-07-30T04:13:14.000Z
2021-07-30T04:13:14.000Z
// // Created by Yaroslav on 20.07.2021. // #include "LocalPlayer.hpp" void LocalPlayer::update(double dt, State *state) { if (state->thirdPersonView) { state->camera->pos.y = pos.y + 3; state->camera->pos.x = pos.x + glm::sin(state->camera->rotY) * 3; state->camera->pos.z = pos.z + glm::cos(state->camera->rotY) * 3; } else { state->camera->pos = pos; } rotY = state->camera->rotY; } LocalPlayer::LocalPlayer(glm::vec3 pos) : Player(pos) { }
21.166667
73
0.574803
f0xeri
29b2fb4aa2a6d3c0667e29ca14143e155eed7eb5
6,202
cpp
C++
native/src/seal/c/keygenerator.cpp
zirconium-n/SEAL
88bbc51dd684b82a781312ff04abd235c060163e
[ "MIT" ]
1,604
2019-05-06T22:40:56.000Z
2022-03-31T14:53:33.000Z
native/src/seal/c/keygenerator.cpp
zirconium-n/SEAL
88bbc51dd684b82a781312ff04abd235c060163e
[ "MIT" ]
425
2019-05-09T08:10:10.000Z
2022-03-31T17:16:51.000Z
native/src/seal/c/keygenerator.cpp
zirconium-n/SEAL
88bbc51dd684b82a781312ff04abd235c060163e
[ "MIT" ]
468
2019-05-08T11:06:24.000Z
2022-03-30T14:30:10.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // STD #include <algorithm> #include <iterator> // SEALNet #include "seal/c/keygenerator.h" #include "seal/c/utilities.h" // SEAL #include "seal/keygenerator.h" #include "seal/util/common.h" using namespace std; using namespace seal; using namespace seal::c; using namespace seal::util; // Enables access to private members of seal::KeyGenerator. using ph = struct seal::KeyGenerator::KeyGeneratorPrivateHelper { static PublicKey create_public_key(KeyGenerator *keygen, bool save_seed) { return keygen->generate_pk(save_seed); } static RelinKeys create_relin_keys(KeyGenerator *keygen, bool save_seed) { return keygen->create_relin_keys(size_t(1), save_seed); } static GaloisKeys create_galois_keys(KeyGenerator *keygen, const vector<uint32_t> &galois_elts, bool save_seed) { return keygen->create_galois_keys(galois_elts, save_seed); } static const GaloisTool *galois_tool(KeyGenerator *keygen) { return keygen->context_.key_context_data()->galois_tool(); } static bool using_keyswitching(const KeyGenerator &keygen) { return keygen.context_.using_keyswitching(); } }; SEAL_C_FUNC KeyGenerator_Create1(void *context, void **key_generator) { const SEALContext *ctx = FromVoid<SEALContext>(context); IfNullRet(ctx, E_POINTER); IfNullRet(key_generator, E_POINTER); try { KeyGenerator *keygen = new KeyGenerator(*ctx); *key_generator = keygen; return S_OK; } catch (const invalid_argument &) { return E_INVALIDARG; } } SEAL_C_FUNC KeyGenerator_Create2(void *context, void *secret_key, void **key_generator) { const SEALContext *ctx = FromVoid<SEALContext>(context); IfNullRet(ctx, E_POINTER); SecretKey *secret_key_ptr = FromVoid<SecretKey>(secret_key); IfNullRet(secret_key_ptr, E_POINTER); IfNullRet(key_generator, E_POINTER); try { KeyGenerator *keygen = new KeyGenerator(*ctx, *secret_key_ptr); *key_generator = keygen; return S_OK; } catch (const invalid_argument &) { return E_INVALIDARG; } } SEAL_C_FUNC KeyGenerator_Destroy(void *thisptr) { KeyGenerator *keygen = FromVoid<KeyGenerator>(thisptr); IfNullRet(keygen, E_POINTER); delete keygen; return S_OK; } SEAL_C_FUNC KeyGenerator_CreateRelinKeys(void *thisptr, bool save_seed, void **relin_keys) { KeyGenerator *keygen = FromVoid<KeyGenerator>(thisptr); IfNullRet(keygen, E_POINTER); IfNullRet(relin_keys, E_POINTER); try { RelinKeys *relinKeys = new RelinKeys(ph::create_relin_keys(keygen, save_seed)); *relin_keys = relinKeys; return S_OK; } catch (const invalid_argument &) { return E_INVALIDARG; } catch (const logic_error &) { return COR_E_INVALIDOPERATION; } } SEAL_C_FUNC KeyGenerator_CreateGaloisKeysFromElts( void *thisptr, uint64_t count, uint32_t *galois_elts, bool save_seed, void **galois_keys) { KeyGenerator *keygen = FromVoid<KeyGenerator>(thisptr); IfNullRet(keygen, E_POINTER); IfNullRet(galois_elts, E_POINTER); IfNullRet(galois_keys, E_POINTER); vector<uint32_t> galois_elts_vec; copy_n(galois_elts, count, back_inserter(galois_elts_vec)); try { GaloisKeys *keys = new GaloisKeys(ph::create_galois_keys(keygen, galois_elts_vec, save_seed)); *galois_keys = keys; return S_OK; } catch (const invalid_argument &) { return E_INVALIDARG; } catch (const logic_error &) { return COR_E_INVALIDOPERATION; } } SEAL_C_FUNC KeyGenerator_CreateGaloisKeysFromSteps( void *thisptr, uint64_t count, int *steps, bool save_seed, void **galois_keys) { KeyGenerator *keygen = FromVoid<KeyGenerator>(thisptr); IfNullRet(keygen, E_POINTER); IfNullRet(steps, E_POINTER); IfNullRet(galois_keys, E_POINTER); vector<int> steps_vec; copy_n(steps, count, back_inserter(steps_vec)); vector<uint32_t> galois_elts_vec; try { galois_elts_vec = ph::galois_tool(keygen)->get_elts_from_steps(steps_vec); GaloisKeys *keys = new GaloisKeys(ph::create_galois_keys(keygen, galois_elts_vec, save_seed)); *galois_keys = keys; return S_OK; } catch (const invalid_argument &) { return E_INVALIDARG; } catch (const logic_error &) { return COR_E_INVALIDOPERATION; } } SEAL_C_FUNC KeyGenerator_CreateGaloisKeysAll(void *thisptr, bool save_seed, void **galois_keys) { KeyGenerator *keygen = FromVoid<KeyGenerator>(thisptr); IfNullRet(keygen, E_POINTER); IfNullRet(galois_keys, E_POINTER); vector<uint32_t> galois_elts_vec = ph::galois_tool(keygen)->get_elts_all(); try { GaloisKeys *keys = new GaloisKeys(ph::create_galois_keys(keygen, galois_elts_vec, save_seed)); *galois_keys = keys; return S_OK; } catch (const invalid_argument &) { return E_INVALIDARG; } catch (const logic_error &) { return COR_E_INVALIDOPERATION; } } SEAL_C_FUNC KeyGenerator_CreatePublicKey(void *thisptr, bool save_seed, void **public_key) { KeyGenerator *keygen = FromVoid<KeyGenerator>(thisptr); IfNullRet(keygen, E_POINTER); IfNullRet(public_key, E_POINTER); PublicKey *key = new PublicKey(ph::create_public_key(keygen, save_seed)); *public_key = key; return S_OK; } SEAL_C_FUNC KeyGenerator_SecretKey(void *thisptr, void **secret_key) { KeyGenerator *keygen = FromVoid<KeyGenerator>(thisptr); IfNullRet(keygen, E_POINTER); IfNullRet(secret_key, E_POINTER); SecretKey *key = new SecretKey(keygen->secret_key()); *secret_key = key; return S_OK; } SEAL_C_FUNC KeyGenerator_ContextUsingKeyswitching(void *thisptr, bool *using_keyswitching) { KeyGenerator *keygen = FromVoid<KeyGenerator>(thisptr); IfNullRet(keygen, E_POINTER); IfNullRet(using_keyswitching, E_POINTER); *using_keyswitching = ph::using_keyswitching(*keygen); return S_OK; }
26.965217
115
0.695421
zirconium-n
29b40d7dc12a0dc753ff469a0d70e4c5dc206314
438
hpp
C++
include/ssGUI/Enums/AnchorType.hpp
Neko-Box-Coder/ssGUI
25e218fd79fea105a30737a63381cf8d0be943f6
[ "Apache-2.0" ]
15
2022-01-21T10:48:04.000Z
2022-03-27T17:55:11.000Z
include/ssGUI/Enums/AnchorType.hpp
Neko-Box-Coder/ssGUI
25e218fd79fea105a30737a63381cf8d0be943f6
[ "Apache-2.0" ]
null
null
null
include/ssGUI/Enums/AnchorType.hpp
Neko-Box-Coder/ssGUI
25e218fd79fea105a30737a63381cf8d0be943f6
[ "Apache-2.0" ]
4
2022-01-21T10:48:05.000Z
2022-01-22T15:42:34.000Z
#ifndef SSGUI_ANCHOR_TYPE #define SSGUI_ANCHOR_TYPE //namespace: ssGUI::Enums namespace ssGUI::Enums { /*enum: AnchorType TOP_LEFT - Anchoring top left TOP_RIGHT - Anchoring top right BOTTOM_LEFT - Anchoring bottom left BOTTOM_RIGHT - Anchoring bottom right */ enum class AnchorType { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }; } #endif
18.25
42
0.625571
Neko-Box-Coder
29b4b8cfbb1cfe69b82dd2d5afd90d41e896bef4
218
cpp
C++
src/main.cpp
zaki0929/rosFlowLIDAR
e4e5cdcd2541c484afb28e129b7503a6c9b532a0
[ "MIT" ]
null
null
null
src/main.cpp
zaki0929/rosFlowLIDAR
e4e5cdcd2541c484afb28e129b7503a6c9b532a0
[ "MIT" ]
null
null
null
src/main.cpp
zaki0929/rosFlowLIDAR
e4e5cdcd2541c484afb28e129b7503a6c9b532a0
[ "MIT" ]
null
null
null
#include "ofMain.h" #include "ofApp.h" #include "ros/ros.h" int main(int argc, char *argv[]){ ros::init(argc, argv, "flow_lidar"); ofSetupOpenGL(1024,768,OF_WINDOW); ofApp *app = new ofApp(); ofRunApp(app); }
19.818182
38
0.66055
zaki0929
29b61c356b519494cfda48e703b5779db9816ed2
89,955
cpp
C++
src/coreclr/src/vm/syncblk.cpp
swaroop-sridhar/runtime
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
[ "MIT" ]
11
2021-10-21T07:56:23.000Z
2022-03-31T15:08:10.000Z
src/coreclr/src/vm/syncblk.cpp
swaroop-sridhar/runtime
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
[ "MIT" ]
1
2020-11-17T09:52:30.000Z
2020-11-17T09:52:30.000Z
src/coreclr/src/vm/syncblk.cpp
swaroop-sridhar/runtime
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
[ "MIT" ]
2
2021-05-17T22:12:46.000Z
2021-05-19T06:21:16.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // SYNCBLK.CPP // // // Definition of a SyncBlock and the SyncBlockCache which manages it // #include "common.h" #include "vars.hpp" #include "util.hpp" #include "class.h" #include "object.h" #include "threads.h" #include "excep.h" #include "threads.h" #include "syncblk.h" #include "interoputil.h" #include "encee.h" #include "eventtrace.h" #include "dllimportcallback.h" #include "comcallablewrapper.h" #include "eeconfig.h" #include "corhost.h" #include "comdelegate.h" #include "finalizerthread.h" #ifdef FEATURE_COMINTEROP #include "runtimecallablewrapper.h" #endif // FEATURE_COMINTEROP // Allocate 4K worth. Typically enough #define MAXSYNCBLOCK (0x1000-sizeof(void*))/sizeof(SyncBlock) #define SYNC_TABLE_INITIAL_SIZE 250 //#define DUMP_SB class SyncBlockArray { public: SyncBlockArray *m_Next; BYTE m_Blocks[MAXSYNCBLOCK * sizeof (SyncBlock)]; }; // For in-place constructor BYTE g_SyncBlockCacheInstance[sizeof(SyncBlockCache)]; SPTR_IMPL (SyncBlockCache, SyncBlockCache, s_pSyncBlockCache); #ifndef DACCESS_COMPILE #ifndef TARGET_UNIX // static SLIST_HEADER InteropSyncBlockInfo::s_InteropInfoStandbyList; #endif // !TARGET_UNIX InteropSyncBlockInfo::~InteropSyncBlockInfo() { CONTRACTL { NOTHROW; DESTRUCTOR_CHECK; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; FreeUMEntryThunkOrInterceptStub(); } #ifndef TARGET_UNIX // Deletes all items in code:s_InteropInfoStandbyList. void InteropSyncBlockInfo::FlushStandbyList() { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; PSLIST_ENTRY pEntry = InterlockedFlushSList(&InteropSyncBlockInfo::s_InteropInfoStandbyList); while (pEntry) { PSLIST_ENTRY pNextEntry = pEntry->Next; // make sure to use the global delete since the destructor has already run ::delete (void *)pEntry; pEntry = pNextEntry; } } #endif // !TARGET_UNIX void InteropSyncBlockInfo::FreeUMEntryThunkOrInterceptStub() { CONTRACTL { NOTHROW; DESTRUCTOR_CHECK; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END if (!g_fEEShutDown) { void *pUMEntryThunk = GetUMEntryThunk(); if (pUMEntryThunk != NULL) { COMDelegate::RemoveEntryFromFPtrHash((UPTR)pUMEntryThunk); UMEntryThunk::FreeUMEntryThunk((UMEntryThunk *)pUMEntryThunk); } else { #if defined(TARGET_X86) Stub *pInterceptStub = GetInterceptStub(); if (pInterceptStub != NULL) { // There may be multiple chained stubs pInterceptStub->DecRef(); } #else // TARGET_X86 // Intercept stubs are currently not used on other platforms. _ASSERTE(GetInterceptStub() == NULL); #endif // TARGET_X86 } } m_pUMEntryThunkOrInterceptStub = NULL; } #ifdef FEATURE_COMINTEROP // Returns either NULL or an RCW on which AcquireLock has been called. RCW* InteropSyncBlockInfo::GetRCWAndIncrementUseCount() { LIMITED_METHOD_CONTRACT; DWORD dwSwitchCount = 0; while (true) { RCW *pRCW = VolatileLoad(&m_pRCW); if ((size_t)pRCW <= 0x1) { // the RCW never existed or has been released return NULL; } if (((size_t)pRCW & 0x1) == 0x0) { // it looks like we have a chance, try to acquire the lock RCW *pLockedRCW = (RCW *)((size_t)pRCW | 0x1); if (InterlockedCompareExchangeT(&m_pRCW, pLockedRCW, pRCW) == pRCW) { // we have the lock on the m_pRCW field, now we can safely "use" the RCW pRCW->IncrementUseCount(); // release the m_pRCW lock VolatileStore(&m_pRCW, pRCW); // and return the RCW return pRCW; } } // somebody else holds the lock, retry __SwitchToThread(0, ++dwSwitchCount); } } // Sets the m_pRCW field in a thread-safe manner, pRCW can be NULL. void InteropSyncBlockInfo::SetRawRCW(RCW* pRCW) { LIMITED_METHOD_CONTRACT; if (pRCW != NULL) { // we never set two different RCWs on a single object _ASSERTE(m_pRCW == NULL); m_pRCW = pRCW; } else { DWORD dwSwitchCount = 0; while (true) { RCW *pOldRCW = VolatileLoad(&m_pRCW); if ((size_t)pOldRCW <= 0x1) { // the RCW never existed or has been released VolatileStore(&m_pRCW, (RCW *)0x1); return; } if (((size_t)pOldRCW & 0x1) == 0x0) { // it looks like we have a chance, set the RCW to 0x1 if (InterlockedCompareExchangeT(&m_pRCW, (RCW *)0x1, pOldRCW) == pOldRCW) { // we made it return; } } // somebody else holds the lock, retry __SwitchToThread(0, ++dwSwitchCount); } } } #endif // FEATURE_COMINTEROP #endif // !DACCESS_COMPILE PTR_SyncTableEntry SyncTableEntry::GetSyncTableEntry() { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; return (PTR_SyncTableEntry)g_pSyncTable; } #ifndef DACCESS_COMPILE SyncTableEntry*& SyncTableEntry::GetSyncTableEntryByRef() { LIMITED_METHOD_CONTRACT; return g_pSyncTable; } /* static */ SyncBlockCache*& SyncBlockCache::GetSyncBlockCache() { LIMITED_METHOD_CONTRACT; return s_pSyncBlockCache; } //---------------------------------------------------------------------------- // // ThreadQueue Implementation // //---------------------------------------------------------------------------- #endif //!DACCESS_COMPILE // Given a link in the chain, get the Thread that it represents /* static */ inline PTR_WaitEventLink ThreadQueue::WaitEventLinkForLink(PTR_SLink pLink) { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; return (PTR_WaitEventLink) (((PTR_BYTE) pLink) - offsetof(WaitEventLink, m_LinkSB)); } #ifndef DACCESS_COMPILE // Unlink the head of the Q. We are always in the SyncBlock's critical // section. /* static */ inline WaitEventLink *ThreadQueue::DequeueThread(SyncBlock *psb) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; CAN_TAKE_LOCK; } CONTRACTL_END; // Be careful, the debugger inspects the queue from out of process and just looks at the memory... // it must be valid even if the lock is held. Be careful if you change the way the queue is updated. SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache()); WaitEventLink *ret = NULL; SLink *pLink = psb->m_Link.m_pNext; if (pLink) { psb->m_Link.m_pNext = pLink->m_pNext; #ifdef _DEBUG pLink->m_pNext = (SLink *)POISONC; #endif ret = WaitEventLinkForLink(pLink); _ASSERTE(ret->m_WaitSB == psb); } return ret; } // Enqueue is the slow one. We have to find the end of the Q since we don't // want to burn storage for this in the SyncBlock. /* static */ inline void ThreadQueue::EnqueueThread(WaitEventLink *pWaitEventLink, SyncBlock *psb) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; CAN_TAKE_LOCK; } CONTRACTL_END; _ASSERTE (pWaitEventLink->m_LinkSB.m_pNext == NULL); // Be careful, the debugger inspects the queue from out of process and just looks at the memory... // it must be valid even if the lock is held. Be careful if you change the way the queue is updated. SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache()); SLink *pPrior = &psb->m_Link; while (pPrior->m_pNext) { // We shouldn't already be in the waiting list! _ASSERTE(pPrior->m_pNext != &pWaitEventLink->m_LinkSB); pPrior = pPrior->m_pNext; } pPrior->m_pNext = &pWaitEventLink->m_LinkSB; } // Wade through the SyncBlock's list of waiting threads and remove the // specified thread. /* static */ BOOL ThreadQueue::RemoveThread (Thread *pThread, SyncBlock *psb) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; BOOL res = FALSE; // Be careful, the debugger inspects the queue from out of process and just looks at the memory... // it must be valid even if the lock is held. Be careful if you change the way the queue is updated. SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache()); SLink *pPrior = &psb->m_Link; SLink *pLink; WaitEventLink *pWaitEventLink; while ((pLink = pPrior->m_pNext) != NULL) { pWaitEventLink = WaitEventLinkForLink(pLink); if (pWaitEventLink->m_Thread == pThread) { pPrior->m_pNext = pLink->m_pNext; #ifdef _DEBUG pLink->m_pNext = (SLink *)POISONC; #endif _ASSERTE(pWaitEventLink->m_WaitSB == psb); res = TRUE; break; } pPrior = pLink; } return res; } #endif //!DACCESS_COMPILE #ifdef DACCESS_COMPILE // Enumerates the threads in the queue from front to back by calling // pCallbackFunction on each one /* static */ void ThreadQueue::EnumerateThreads(SyncBlock *psb, FP_TQ_THREAD_ENUMERATION_CALLBACK pCallbackFunction, void* pUserData) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; SUPPORTS_DAC; PTR_SLink pLink = psb->m_Link.m_pNext; PTR_WaitEventLink pWaitEventLink; while (pLink != NULL) { pWaitEventLink = WaitEventLinkForLink(pLink); pCallbackFunction(pWaitEventLink->m_Thread, pUserData); pLink = pLink->m_pNext; } } #endif //DACCESS_COMPILE #ifndef DACCESS_COMPILE // *************************************************************************** // // Ephemeral Bitmap Helper // // *************************************************************************** #define card_size 32 #define card_word_width 32 size_t CardIndex (size_t card) { LIMITED_METHOD_CONTRACT; return card_size * card; } size_t CardOf (size_t idx) { LIMITED_METHOD_CONTRACT; return idx / card_size; } size_t CardWord (size_t card) { LIMITED_METHOD_CONTRACT; return card / card_word_width; } inline unsigned CardBit (size_t card) { LIMITED_METHOD_CONTRACT; return (unsigned)(card % card_word_width); } inline void SyncBlockCache::SetCard (size_t card) { WRAPPER_NO_CONTRACT; m_EphemeralBitmap [CardWord (card)] = (m_EphemeralBitmap [CardWord (card)] | (1 << CardBit (card))); } inline void SyncBlockCache::ClearCard (size_t card) { WRAPPER_NO_CONTRACT; m_EphemeralBitmap [CardWord (card)] = (m_EphemeralBitmap [CardWord (card)] & ~(1 << CardBit (card))); } inline BOOL SyncBlockCache::CardSetP (size_t card) { WRAPPER_NO_CONTRACT; return ( m_EphemeralBitmap [ CardWord (card) ] & (1 << CardBit (card))); } inline void SyncBlockCache::CardTableSetBit (size_t idx) { WRAPPER_NO_CONTRACT; SetCard (CardOf (idx)); } size_t BitMapSize (size_t cacheSize) { LIMITED_METHOD_CONTRACT; return (cacheSize + card_size * card_word_width - 1)/ (card_size * card_word_width); } // *************************************************************************** // // SyncBlockCache class implementation // // *************************************************************************** SyncBlockCache::SyncBlockCache() : m_pCleanupBlockList(NULL), m_FreeBlockList(NULL), // NOTE: CRST_UNSAFE_ANYMODE prevents a GC mode switch when entering this crst. // If you remove this flag, we will switch to preemptive mode when entering // g_criticalSection, which means all functions that enter it will become // GC_TRIGGERS. (This includes all uses of LockHolder around SyncBlockCache::GetSyncBlockCache(). // So be sure to update the contracts if you remove this flag. m_CacheLock(CrstSyncBlockCache, (CrstFlags) (CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD)), m_FreeCount(0), m_ActiveCount(0), m_SyncBlocks(0), m_FreeSyncBlock(0), m_FreeSyncTableIndex(1), m_FreeSyncTableList(0), m_SyncTableSize(SYNC_TABLE_INITIAL_SIZE), m_OldSyncTables(0), m_bSyncBlockCleanupInProgress(FALSE), m_EphemeralBitmap(0) { CONTRACTL { CONSTRUCTOR_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; } // This method is NO longer called. SyncBlockCache::~SyncBlockCache() { CONTRACTL { DESTRUCTOR_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Clear the list the fast way. m_FreeBlockList = NULL; //<TODO>@todo we can clear this fast too I guess</TODO> m_pCleanupBlockList = NULL; // destruct all arrays while (m_SyncBlocks) { SyncBlockArray *next = m_SyncBlocks->m_Next; delete m_SyncBlocks; m_SyncBlocks = next; } // Also, now is a good time to clean up all the old tables which we discarded // when we overflowed them. SyncTableEntry* arr; while ((arr = m_OldSyncTables) != 0) { m_OldSyncTables = (SyncTableEntry*)arr[0].m_Object.Load(); delete arr; } } // When the GC determines that an object is dead the low bit of the // m_Object field of SyncTableEntry is set, however it is not // cleaned up because we cant do the COM interop cleanup at GC time. // It is put on a cleanup list and at a later time (typically during // finalization, this list is cleaned up. // void SyncBlockCache::CleanupSyncBlocks() { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_MODE_COOPERATIVE; _ASSERTE(GetThread() == FinalizerThread::GetFinalizerThread()); // Set the flag indicating sync block cleanup is in progress. // IMPORTANT: This must be set before the sync block cleanup bit is reset on the thread. m_bSyncBlockCleanupInProgress = TRUE; struct Param { SyncBlockCache *pThis; SyncBlock* psb; #ifdef FEATURE_COMINTEROP RCW* pRCW; #endif } param; param.pThis = this; param.psb = NULL; #ifdef FEATURE_COMINTEROP param.pRCW = NULL; #endif EE_TRY_FOR_FINALLY(Param *, pParam, &param) { // reset the flag FinalizerThread::GetFinalizerThread()->ResetSyncBlockCleanup(); // walk the cleanup list and cleanup 'em up while ((pParam->psb = pParam->pThis->GetNextCleanupSyncBlock()) != NULL) { #ifdef FEATURE_COMINTEROP InteropSyncBlockInfo* pInteropInfo = pParam->psb->GetInteropInfoNoCreate(); if (pInteropInfo) { pParam->pRCW = pInteropInfo->GetRawRCW(); if (pParam->pRCW) { // We should have initialized the cleanup list with the // first RCW cache we created _ASSERTE(g_pRCWCleanupList != NULL); g_pRCWCleanupList->AddWrapper(pParam->pRCW); pParam->pRCW = NULL; pInteropInfo->SetRawRCW(NULL); } } #endif // FEATURE_COMINTEROP // Delete the sync block. pParam->pThis->DeleteSyncBlock(pParam->psb); pParam->psb = NULL; // pulse GC mode to allow GC to perform its work if (FinalizerThread::GetFinalizerThread()->CatchAtSafePointOpportunistic()) { FinalizerThread::GetFinalizerThread()->PulseGCMode(); } } #ifdef FEATURE_COMINTEROP // Now clean up the rcw's sorted by context if (g_pRCWCleanupList != NULL) g_pRCWCleanupList->CleanupAllWrappers(); #endif // FEATURE_COMINTEROP } EE_FINALLY { // We are finished cleaning up the sync blocks. m_bSyncBlockCleanupInProgress = FALSE; #ifdef FEATURE_COMINTEROP if (param.pRCW) param.pRCW->Cleanup(); #endif if (param.psb) DeleteSyncBlock(param.psb); } EE_END_FINALLY; } // create the sync block cache /* static */ void SyncBlockCache::Attach() { LIMITED_METHOD_CONTRACT; } // create the sync block cache /* static */ void SyncBlockCache::Start() { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; DWORD* bm = new DWORD [BitMapSize(SYNC_TABLE_INITIAL_SIZE+1)]; memset (bm, 0, BitMapSize (SYNC_TABLE_INITIAL_SIZE+1)*sizeof(DWORD)); SyncTableEntry::GetSyncTableEntryByRef() = new SyncTableEntry[SYNC_TABLE_INITIAL_SIZE+1]; #ifdef _DEBUG for (int i=0; i<SYNC_TABLE_INITIAL_SIZE+1; i++) { SyncTableEntry::GetSyncTableEntry()[i].m_SyncBlock = NULL; } #endif SyncTableEntry::GetSyncTableEntry()[0].m_SyncBlock = 0; SyncBlockCache::GetSyncBlockCache() = new (&g_SyncBlockCacheInstance) SyncBlockCache; SyncBlockCache::GetSyncBlockCache()->m_EphemeralBitmap = bm; #ifndef TARGET_UNIX InitializeSListHead(&InteropSyncBlockInfo::s_InteropInfoStandbyList); #endif // !TARGET_UNIX } // destroy the sync block cache /* static */ void SyncBlockCache::Stop() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // cache must be destroyed first, since it can traverse the table to find all the // sync blocks which are live and thus must have their critical sections destroyed. if (SyncBlockCache::GetSyncBlockCache()) { delete SyncBlockCache::GetSyncBlockCache(); SyncBlockCache::GetSyncBlockCache() = 0; } if (SyncTableEntry::GetSyncTableEntry()) { delete SyncTableEntry::GetSyncTableEntry(); SyncTableEntry::GetSyncTableEntryByRef() = 0; } } void SyncBlockCache::InsertCleanupSyncBlock(SyncBlock* psb) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // free up the threads that are waiting before we use the link // for other purposes if (psb->m_Link.m_pNext != NULL) { while (ThreadQueue::DequeueThread(psb) != NULL) continue; } #ifdef FEATURE_COMINTEROP if (psb->m_pInteropInfo) { // called during GC // so do only minorcleanup MinorCleanupSyncBlockComData(psb->m_pInteropInfo); } #endif // FEATURE_COMINTEROP // This method will be called only by the GC thread //<TODO>@todo add an assert for the above statement</TODO> // we don't need to lock here //EnterCacheLock(); psb->m_Link.m_pNext = m_pCleanupBlockList; m_pCleanupBlockList = &psb->m_Link; // we don't need a lock here //LeaveCacheLock(); } SyncBlock* SyncBlockCache::GetNextCleanupSyncBlock() { LIMITED_METHOD_CONTRACT; // we don't need a lock here, // as this is called only on the finalizer thread currently SyncBlock *psb = NULL; if (m_pCleanupBlockList) { // get the actual sync block pointer psb = (SyncBlock *) (((BYTE *) m_pCleanupBlockList) - offsetof(SyncBlock, m_Link)); m_pCleanupBlockList = m_pCleanupBlockList->m_pNext; } return psb; } // returns and removes the next free syncblock from the list // the cache lock must be entered to call this SyncBlock *SyncBlockCache::GetNextFreeSyncBlock() { CONTRACTL { INJECT_FAULT(COMPlusThrowOM()); THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; #ifdef _DEBUG // Instrumentation for OOM fault injection testing delete new char; #endif SyncBlock *psb; SLink *plst = m_FreeBlockList; m_ActiveCount++; if (plst) { m_FreeBlockList = m_FreeBlockList->m_pNext; // shouldn't be 0 m_FreeCount--; // get the actual sync block pointer psb = (SyncBlock *) (((BYTE *) plst) - offsetof(SyncBlock, m_Link)); return psb; } else { if ((m_SyncBlocks == NULL) || (m_FreeSyncBlock >= MAXSYNCBLOCK)) { #ifdef DUMP_SB // LogSpewAlways("Allocating new syncblock array\n"); // DumpSyncBlockCache(); #endif SyncBlockArray* newsyncblocks = new(SyncBlockArray); if (!newsyncblocks) COMPlusThrowOM (); newsyncblocks->m_Next = m_SyncBlocks; m_SyncBlocks = newsyncblocks; m_FreeSyncBlock = 0; } return &(((SyncBlock*)m_SyncBlocks->m_Blocks)[m_FreeSyncBlock++]); } } void SyncBlockCache::Grow() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_COOPERATIVE; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; STRESS_LOG0(LF_SYNC, LL_INFO10000, "SyncBlockCache::NewSyncBlockSlot growing SyncBlockCache \n"); NewArrayHolder<SyncTableEntry> newSyncTable (NULL); NewArrayHolder<DWORD> newBitMap (NULL); DWORD * oldBitMap; // Compute the size of the new synctable. Normally, we double it - unless // doing so would create slots with indices too high to fit within the // mask. If so, we create a synctable up to the mask limit. If we're // already at the mask limit, then caller is out of luck. DWORD newSyncTableSize; if (m_SyncTableSize <= (MASK_SYNCBLOCKINDEX >> 1)) { newSyncTableSize = m_SyncTableSize * 2; } else { newSyncTableSize = MASK_SYNCBLOCKINDEX; } if (!(newSyncTableSize > m_SyncTableSize)) // Make sure we actually found room to grow! { COMPlusThrowOM(); } newSyncTable = new SyncTableEntry[newSyncTableSize]; newBitMap = new DWORD[BitMapSize (newSyncTableSize)]; { //! From here on, we assume that we will succeed and start doing global side-effects. //! Any operation that could fail must occur before this point. CANNOTTHROWCOMPLUSEXCEPTION(); FAULT_FORBID(); newSyncTable.SuppressRelease(); newBitMap.SuppressRelease(); // We chain old table because we can't delete // them before all the threads are stoppped // (next GC) SyncTableEntry::GetSyncTableEntry() [0].m_Object = (Object *)m_OldSyncTables; m_OldSyncTables = SyncTableEntry::GetSyncTableEntry(); memset (newSyncTable, 0, newSyncTableSize*sizeof (SyncTableEntry)); memset (newBitMap, 0, BitMapSize (newSyncTableSize)*sizeof (DWORD)); CopyMemory (newSyncTable, SyncTableEntry::GetSyncTableEntry(), m_SyncTableSize*sizeof (SyncTableEntry)); CopyMemory (newBitMap, m_EphemeralBitmap, BitMapSize (m_SyncTableSize)*sizeof (DWORD)); oldBitMap = m_EphemeralBitmap; m_EphemeralBitmap = newBitMap; delete[] oldBitMap; _ASSERTE((m_SyncTableSize & MASK_SYNCBLOCKINDEX) == m_SyncTableSize); // note: we do not care if another thread does not see the new size // however we really do not want it to see the new size without seeing the new array //@TODO do we still leak here if two threads come here at the same time ? FastInterlockExchangePointer(&SyncTableEntry::GetSyncTableEntryByRef(), newSyncTable.GetValue()); m_FreeSyncTableIndex++; m_SyncTableSize = newSyncTableSize; #ifdef _DEBUG static int dumpSBOnResize = -1; if (dumpSBOnResize == -1) dumpSBOnResize = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SBDumpOnResize); if (dumpSBOnResize) { LogSpewAlways("SyncBlockCache resized\n"); DumpSyncBlockCache(); } #endif } } DWORD SyncBlockCache::NewSyncBlockSlot(Object *obj) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_COOPERATIVE; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; _ASSERTE(m_CacheLock.OwnedByCurrentThread()); // GetSyncBlock takes the lock, make sure no one else does. DWORD indexNewEntry; if (m_FreeSyncTableList) { indexNewEntry = (DWORD)(m_FreeSyncTableList >> 1); _ASSERTE ((size_t)SyncTableEntry::GetSyncTableEntry()[indexNewEntry].m_Object.Load() & 1); m_FreeSyncTableList = (size_t)SyncTableEntry::GetSyncTableEntry()[indexNewEntry].m_Object.Load() & ~1; } else if ((indexNewEntry = (DWORD)(m_FreeSyncTableIndex)) >= m_SyncTableSize) { // This is kept out of line to keep stuff like the C++ EH prolog (needed for holders) off // of the common path. Grow(); } else { #ifdef _DEBUG static int dumpSBOnNewIndex = -1; if (dumpSBOnNewIndex == -1) dumpSBOnNewIndex = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SBDumpOnNewIndex); if (dumpSBOnNewIndex) { LogSpewAlways("SyncBlockCache index incremented\n"); DumpSyncBlockCache(); } #endif m_FreeSyncTableIndex ++; } CardTableSetBit (indexNewEntry); // In debug builds the m_SyncBlock at indexNewEntry should already be null, since we should // start out with a null table and always null it out on delete. _ASSERTE(SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_SyncBlock == NULL); SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_SyncBlock = NULL; SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_Object = obj; _ASSERTE(indexNewEntry != 0); return indexNewEntry; } // free a used sync block, only called from CleanupSyncBlocks. void SyncBlockCache::DeleteSyncBlock(SyncBlock *psb) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; // clean up comdata if (psb->m_pInteropInfo) { #ifdef FEATURE_COMINTEROP CleanupSyncBlockComData(psb->m_pInteropInfo); #endif // FEATURE_COMINTEROP #ifndef TARGET_UNIX if (g_fEEShutDown) { delete psb->m_pInteropInfo; } else { psb->m_pInteropInfo->~InteropSyncBlockInfo(); InterlockedPushEntrySList(&InteropSyncBlockInfo::s_InteropInfoStandbyList, (PSLIST_ENTRY)psb->m_pInteropInfo); } #else // !TARGET_UNIX delete psb->m_pInteropInfo; #endif // !TARGET_UNIX } #ifdef EnC_SUPPORTED // clean up EnC info if (psb->m_pEnCInfo) psb->m_pEnCInfo->Cleanup(); #endif // EnC_SUPPORTED // Destruct the SyncBlock, but don't reclaim its memory. (Overridden // operator delete). delete psb; //synchronizer with the consumers, // <TODO>@todo we don't really need a lock here, we can come up // with some simple algo to avoid taking a lock </TODO> { SyncBlockCache::LockHolder lh(this); DeleteSyncBlockMemory(psb); } } // returns the sync block memory to the free pool but does not destruct sync block (must own cache lock already) void SyncBlockCache::DeleteSyncBlockMemory(SyncBlock *psb) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; FORBID_FAULT; } CONTRACTL_END m_ActiveCount--; m_FreeCount++; psb->m_Link.m_pNext = m_FreeBlockList; m_FreeBlockList = &psb->m_Link; } // free a used sync block void SyncBlockCache::GCDeleteSyncBlock(SyncBlock *psb) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Destruct the SyncBlock, but don't reclaim its memory. (Overridden // operator delete). delete psb; m_ActiveCount--; m_FreeCount++; psb->m_Link.m_pNext = m_FreeBlockList; m_FreeBlockList = &psb->m_Link; } void SyncBlockCache::GCWeakPtrScan(HANDLESCANPROC scanProc, uintptr_t lp1, uintptr_t lp2) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // First delete the obsolete arrays since we have exclusive access BOOL fSetSyncBlockCleanup = FALSE; SyncTableEntry* arr; while ((arr = m_OldSyncTables) != NULL) { m_OldSyncTables = (SyncTableEntry*)arr[0].m_Object.Load(); delete arr; } #ifdef DUMP_SB LogSpewAlways("GCWeakPtrScan starting\n"); #endif #ifdef VERIFY_HEAP if (g_pConfig->GetHeapVerifyLevel()& EEConfig::HEAPVERIFY_SYNCBLK) STRESS_LOG0 (LF_GC | LF_SYNC, LL_INFO100, "GCWeakPtrScan starting\n"); #endif if (GCHeapUtilities::GetGCHeap()->GetCondemnedGeneration() < GCHeapUtilities::GetGCHeap()->GetMaxGeneration()) { #ifdef VERIFY_HEAP //for VSW 294550: we saw stale obeject reference in SyncBlkCache, so we want to make sure the card //table logic above works correctly so that every ephemeral entry is promoted. //For verification, we make a copy of the sync table in relocation phase and promote it use the //slow approach and compare the result with the original one DWORD freeSyncTalbeIndexCopy = m_FreeSyncTableIndex; SyncTableEntry * syncTableShadow = NULL; if ((g_pConfig->GetHeapVerifyLevel()& EEConfig::HEAPVERIFY_SYNCBLK) && !((ScanContext*)lp1)->promotion) { syncTableShadow = new(nothrow) SyncTableEntry [m_FreeSyncTableIndex]; if (syncTableShadow) { memcpy (syncTableShadow, SyncTableEntry::GetSyncTableEntry(), m_FreeSyncTableIndex * sizeof (SyncTableEntry)); } } #endif //VERIFY_HEAP //scan the bitmap size_t dw = 0; while (1) { while (dw < BitMapSize (m_SyncTableSize) && (m_EphemeralBitmap[dw]==0)) { dw++; } if (dw < BitMapSize (m_SyncTableSize)) { //found one for (int i = 0; i < card_word_width; i++) { size_t card = i+dw*card_word_width; if (CardSetP (card)) { BOOL clear_card = TRUE; for (int idx = 0; idx < card_size; idx++) { size_t nb = CardIndex (card) + idx; if (( nb < m_FreeSyncTableIndex) && (nb > 0)) { Object* o = SyncTableEntry::GetSyncTableEntry()[nb].m_Object; if (o && !((size_t)o & 1)) { if (GCHeapUtilities::GetGCHeap()->IsEphemeral (o)) { clear_card = FALSE; GCWeakPtrScanElement ((int)nb, scanProc, lp1, lp2, fSetSyncBlockCleanup); } } } } if (clear_card) ClearCard (card); } } dw++; } else break; } #ifdef VERIFY_HEAP //for VSW 294550: we saw stale obeject reference in SyncBlkCache, so we want to make sure the card //table logic above works correctly so that every ephemeral entry is promoted. To verify, we make a //copy of the sync table and promote it use the slow approach and compare the result with the real one if (g_pConfig->GetHeapVerifyLevel()& EEConfig::HEAPVERIFY_SYNCBLK) { if (syncTableShadow) { for (DWORD nb = 1; nb < m_FreeSyncTableIndex; nb++) { Object **keyv = (Object **) &syncTableShadow[nb].m_Object; if (((size_t) *keyv & 1) == 0) { (*scanProc) (keyv, NULL, lp1, lp2); SyncBlock *pSB = syncTableShadow[nb].m_SyncBlock; if (*keyv != 0 && (!pSB || !pSB->IsIDisposable())) { if (syncTableShadow[nb].m_Object != SyncTableEntry::GetSyncTableEntry()[nb].m_Object) DebugBreak (); } } } delete []syncTableShadow; syncTableShadow = NULL; } if (freeSyncTalbeIndexCopy != m_FreeSyncTableIndex) DebugBreak (); } #endif //VERIFY_HEAP } else { for (DWORD nb = 1; nb < m_FreeSyncTableIndex; nb++) { GCWeakPtrScanElement (nb, scanProc, lp1, lp2, fSetSyncBlockCleanup); } } if (fSetSyncBlockCleanup) { // mark the finalizer thread saying requires cleanup FinalizerThread::GetFinalizerThread()->SetSyncBlockCleanup(); FinalizerThread::EnableFinalization(); } #if defined(VERIFY_HEAP) if (g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_GC) { if (((ScanContext*)lp1)->promotion) { for (int nb = 1; nb < (int)m_FreeSyncTableIndex; nb++) { Object* o = SyncTableEntry::GetSyncTableEntry()[nb].m_Object; if (o && ((size_t)o & 1) == 0) { o->Validate(); } } } } #endif // VERIFY_HEAP } /* Scan the weak pointers in the SyncBlockEntry and report them to the GC. If the reference is dead, then return TRUE */ BOOL SyncBlockCache::GCWeakPtrScanElement (int nb, HANDLESCANPROC scanProc, LPARAM lp1, LPARAM lp2, BOOL& cleanup) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; Object **keyv = (Object **) &SyncTableEntry::GetSyncTableEntry()[nb].m_Object; #ifdef DUMP_SB struct Param { Object **keyv; char *name; } param; param.keyv = keyv; PAL_TRY(Param *, pParam, &param) { if (! *pParam->keyv) pParam->name = "null"; else if ((size_t) *pParam->keyv & 1) pParam->name = "free"; else { pParam->name = (*pParam->keyv)->GetClass()->GetDebugClassName(); if (strlen(pParam->name) == 0) pParam->name = "<INVALID>"; } } PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { param.name = "<INVALID>"; } PAL_ENDTRY LogSpewAlways("[%4.4d]: %8.8x, %s\n", nb, *keyv, param.name); #endif if (((size_t) *keyv & 1) == 0) { #ifdef VERIFY_HEAP if (g_pConfig->GetHeapVerifyLevel () & EEConfig::HEAPVERIFY_SYNCBLK) { STRESS_LOG3 (LF_GC | LF_SYNC, LL_INFO100000, "scanning syncblk[%d, %p, %p]\n", nb, (size_t)SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock, (size_t)*keyv); } #endif (*scanProc) (keyv, NULL, lp1, lp2); SyncBlock *pSB = SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock; if ((*keyv == 0 ) || (pSB && pSB->IsIDisposable())) { #ifdef VERIFY_HEAP if (g_pConfig->GetHeapVerifyLevel () & EEConfig::HEAPVERIFY_SYNCBLK) { STRESS_LOG3 (LF_GC | LF_SYNC, LL_INFO100000, "freeing syncblk[%d, %p, %p]\n", nb, (size_t)pSB, (size_t)*keyv); } #endif if (*keyv) { _ASSERTE (pSB); GCDeleteSyncBlock(pSB); //clean the object syncblock header ((Object*)(*keyv))->GetHeader()->GCResetIndex(); } else if (pSB) { cleanup = TRUE; // insert block into cleanup list InsertCleanupSyncBlock (SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock); #ifdef DUMP_SB LogSpewAlways(" Cleaning up block at %4.4d\n", nb); #endif } // delete the entry #ifdef DUMP_SB LogSpewAlways(" Deleting block at %4.4d\n", nb); #endif SyncTableEntry::GetSyncTableEntry()[nb].m_Object = (Object *)(m_FreeSyncTableList | 1); m_FreeSyncTableList = nb << 1; SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock = NULL; return TRUE; } else { #ifdef DUMP_SB LogSpewAlways(" Keeping block at %4.4d with oref %8.8x\n", nb, *keyv); #endif } } return FALSE; } void SyncBlockCache::GCDone(BOOL demoting, int max_gen) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if (demoting && (GCHeapUtilities::GetGCHeap()->GetCondemnedGeneration() == GCHeapUtilities::GetGCHeap()->GetMaxGeneration())) { //scan the bitmap size_t dw = 0; while (1) { while (dw < BitMapSize (m_SyncTableSize) && (m_EphemeralBitmap[dw]==(DWORD)~0)) { dw++; } if (dw < BitMapSize (m_SyncTableSize)) { //found one for (int i = 0; i < card_word_width; i++) { size_t card = i+dw*card_word_width; if (!CardSetP (card)) { for (int idx = 0; idx < card_size; idx++) { size_t nb = CardIndex (card) + idx; if (( nb < m_FreeSyncTableIndex) && (nb > 0)) { Object* o = SyncTableEntry::GetSyncTableEntry()[nb].m_Object; if (o && !((size_t)o & 1)) { if (GCHeapUtilities::GetGCHeap()->WhichGeneration (o) < (unsigned int)max_gen) { SetCard (card); break; } } } } } } dw++; } else break; } } } #if defined (VERIFY_HEAP) #ifndef _DEBUG #ifdef _ASSERTE #undef _ASSERTE #endif #define _ASSERTE(c) if (!(c)) DebugBreak() #endif void SyncBlockCache::VerifySyncTableEntry() { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; for (DWORD nb = 1; nb < m_FreeSyncTableIndex; nb++) { Object* o = SyncTableEntry::GetSyncTableEntry()[nb].m_Object; // if the slot was just allocated, the object may still be null if (o && (((size_t)o & 1) == 0)) { //there is no need to verify next object's header because this is called //from verify_heap, which will verify every object anyway o->Validate(TRUE, FALSE); // // This loop is just a heuristic to try to catch errors, but it is not 100%. // To prevent false positives, we weaken our assert below to exclude the case // where the index is still NULL, but we've reached the end of our loop. // static const DWORD max_iterations = 100; DWORD loop = 0; for (; loop < max_iterations; loop++) { // The syncblock index may be updating by another thread. if (o->GetHeader()->GetHeaderSyncBlockIndex() != 0) { break; } __SwitchToThread(0, CALLER_LIMITS_SPINNING); } DWORD idx = o->GetHeader()->GetHeaderSyncBlockIndex(); _ASSERTE(idx == nb || ((0 == idx) && (loop == max_iterations))); _ASSERTE(!GCHeapUtilities::GetGCHeap()->IsEphemeral(o) || CardSetP(CardOf(nb))); } } } #ifndef _DEBUG #undef _ASSERTE #define _ASSERTE(expr) ((void)0) #endif // _DEBUG #endif // VERIFY_HEAP #ifdef _DEBUG void DumpSyncBlockCache() { STATIC_CONTRACT_NOTHROW; SyncBlockCache *pCache = SyncBlockCache::GetSyncBlockCache(); LogSpewAlways("Dumping SyncBlockCache size %d\n", pCache->m_FreeSyncTableIndex); static int dumpSBStyle = -1; if (dumpSBStyle == -1) dumpSBStyle = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SBDumpStyle); if (dumpSBStyle == 0) return; BOOL isString = FALSE; DWORD objectCount = 0; DWORD slotCount = 0; for (DWORD nb = 1; nb < pCache->m_FreeSyncTableIndex; nb++) { isString = FALSE; char buffer[1024], buffer2[1024]; LPCUTF8 descrip = "null"; SyncTableEntry *pEntry = &SyncTableEntry::GetSyncTableEntry()[nb]; Object *oref = (Object *) pEntry->m_Object; if (((size_t) oref & 1) != 0) { descrip = "free"; oref = 0; } else { ++slotCount; if (oref) { ++objectCount; struct Param { LPCUTF8 descrip; Object *oref; char *buffer2; UINT cch2; BOOL isString; } param; param.descrip = descrip; param.oref = oref; param.buffer2 = buffer2; param.cch2 = COUNTOF(buffer2); param.isString = isString; PAL_TRY(Param *, pParam, &param) { pParam->descrip = pParam->oref->GetMethodTable()->GetDebugClassName(); if (strlen(pParam->descrip) == 0) pParam->descrip = "<INVALID>"; else if (pParam->oref->GetMethodTable() == g_pStringClass) { sprintf_s(pParam->buffer2, pParam->cch2, "%s (%S)", pParam->descrip, ObjectToSTRINGREF((StringObject*)pParam->oref)->GetBuffer()); pParam->descrip = pParam->buffer2; pParam->isString = TRUE; } } PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { param.descrip = "<INVALID>"; } PAL_ENDTRY descrip = param.descrip; isString = param.isString; } sprintf_s(buffer, COUNTOF(buffer), "%s", descrip); descrip = buffer; } if (dumpSBStyle < 2) LogSpewAlways("[%4.4d]: %8.8x %s\n", nb, oref, descrip); else if (dumpSBStyle == 2 && ! isString) LogSpewAlways("[%4.4d]: %s\n", nb, descrip); } LogSpewAlways("Done dumping SyncBlockCache used slots: %d, objects: %d\n", slotCount, objectCount); } #endif // *************************************************************************** // // ObjHeader class implementation // // *************************************************************************** #if defined(ENABLE_CONTRACTS_IMPL) // The LOCK_TAKEN/RELEASED macros need a "pointer" to the lock object to do // comparisons between takes & releases (and to provide debugging info to the // developer). Ask the syncblock for its lock contract pointer, if the // syncblock exists. Otherwise, use the MethodTable* from the Object. That's not great, // as it's not unique, so we might miss unbalanced lock takes/releases from // different objects of the same type. However, our hands are tied, and we can't // do much better. void * ObjHeader::GetPtrForLockContract() { if (GetHeaderSyncBlockIndex() == 0) { return (void *) GetBaseObject()->GetMethodTable(); } return PassiveGetSyncBlock()->GetPtrForLockContract(); } #endif // defined(ENABLE_CONTRACTS_IMPL) // this enters the monitor of an object void ObjHeader::EnterObjMonitor() { WRAPPER_NO_CONTRACT; GetSyncBlock()->EnterMonitor(); } // Non-blocking version of above BOOL ObjHeader::TryEnterObjMonitor(INT32 timeOut) { WRAPPER_NO_CONTRACT; return GetSyncBlock()->TryEnterMonitor(timeOut); } AwareLock::EnterHelperResult ObjHeader::EnterObjMonitorHelperSpin(Thread* pCurThread) { CONTRACTL{ NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; // Note: EnterObjMonitorHelper must be called before this function (see below) if (g_SystemInfo.dwNumberOfProcessors == 1) { return AwareLock::EnterHelperResult_Contention; } YieldProcessorNormalizationInfo normalizationInfo; const DWORD spinCount = g_SpinConstants.dwMonitorSpinCount; for (DWORD spinIteration = 0; spinIteration < spinCount; ++spinIteration) { AwareLock::SpinWait(normalizationInfo, spinIteration); LONG oldValue = m_SyncBlockValue.LoadWithoutBarrier(); // Since spinning has begun, chances are good that the monitor has already switched to AwareLock mode, so check for that // case first if (oldValue & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) { // If we have a hash code already, we need to create a sync block if (oldValue & BIT_SBLK_IS_HASHCODE) { return AwareLock::EnterHelperResult_UseSlowPath; } SyncBlock *syncBlock = g_pSyncTable[oldValue & MASK_SYNCBLOCKINDEX].m_SyncBlock; _ASSERTE(syncBlock != NULL); AwareLock *awareLock = &syncBlock->m_Monitor; AwareLock::EnterHelperResult result = awareLock->TryEnterBeforeSpinLoopHelper(pCurThread); if (result != AwareLock::EnterHelperResult_Contention) { return result; } ++spinIteration; if (spinIteration < spinCount) { while (true) { AwareLock::SpinWait(normalizationInfo, spinIteration); ++spinIteration; if (spinIteration >= spinCount) { // The last lock attempt for this spin will be done after the loop break; } result = awareLock->TryEnterInsideSpinLoopHelper(pCurThread); if (result == AwareLock::EnterHelperResult_Entered) { return AwareLock::EnterHelperResult_Entered; } if (result == AwareLock::EnterHelperResult_UseSlowPath) { break; } } } if (awareLock->TryEnterAfterSpinLoopHelper(pCurThread)) { return AwareLock::EnterHelperResult_Entered; } break; } DWORD tid = pCurThread->GetThreadId(); if ((oldValue & (BIT_SBLK_SPIN_LOCK + SBLK_MASK_LOCK_THREADID + SBLK_MASK_LOCK_RECLEVEL)) == 0) { if (tid > SBLK_MASK_LOCK_THREADID) { return AwareLock::EnterHelperResult_UseSlowPath; } LONG newValue = oldValue | tid; if (InterlockedCompareExchangeAcquire((LONG*)&m_SyncBlockValue, newValue, oldValue) == oldValue) { return AwareLock::EnterHelperResult_Entered; } continue; } // EnterObjMonitorHelper handles the thin lock recursion case. If it's not that case, it won't become that case. If // EnterObjMonitorHelper failed to increment the recursion level, it will go down the slow path and won't come here. So, // no need to check the recursion case here. _ASSERTE( // The header is transitioning - treat this as if the lock was taken oldValue & BIT_SBLK_SPIN_LOCK || // Here we know we have the "thin lock" layout, but the lock is not free. // It can't be the recursion case though, because the call to EnterObjMonitorHelper prior to this would have taken // the slow path in the recursive case. tid != (DWORD)(oldValue & SBLK_MASK_LOCK_THREADID)); } return AwareLock::EnterHelperResult_Contention; } BOOL ObjHeader::LeaveObjMonitor() { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; //this function switch to preemp mode so we need to protect the object in some path OBJECTREF thisObj = ObjectToOBJECTREF (GetBaseObject ()); DWORD dwSwitchCount = 0; for (;;) { AwareLock::LeaveHelperAction action = thisObj->GetHeader ()->LeaveObjMonitorHelper(GetThread()); switch(action) { case AwareLock::LeaveHelperAction_None: // We are done return TRUE; case AwareLock::LeaveHelperAction_Signal: { // Signal the event SyncBlock *psb = thisObj->GetHeader ()->PassiveGetSyncBlock(); if (psb != NULL) psb->QuickGetMonitor()->Signal(); } return TRUE; case AwareLock::LeaveHelperAction_Yield: YieldProcessorNormalized(); continue; case AwareLock::LeaveHelperAction_Contention: // Some thread is updating the syncblock value. { //protect the object before switching mode GCPROTECT_BEGIN (thisObj); GCX_PREEMP(); __SwitchToThread(0, ++dwSwitchCount); GCPROTECT_END (); } continue; default: // Must be an error otherwise - ignore it _ASSERTE(action == AwareLock::LeaveHelperAction_Error); return FALSE; } } } // The only difference between LeaveObjMonitor and LeaveObjMonitorAtException is switch // to preemptive mode around __SwitchToThread BOOL ObjHeader::LeaveObjMonitorAtException() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; DWORD dwSwitchCount = 0; for (;;) { AwareLock::LeaveHelperAction action = LeaveObjMonitorHelper(GetThread()); switch(action) { case AwareLock::LeaveHelperAction_None: // We are done return TRUE; case AwareLock::LeaveHelperAction_Signal: { // Signal the event SyncBlock *psb = PassiveGetSyncBlock(); if (psb != NULL) psb->QuickGetMonitor()->Signal(); } return TRUE; case AwareLock::LeaveHelperAction_Yield: YieldProcessorNormalized(); continue; case AwareLock::LeaveHelperAction_Contention: // Some thread is updating the syncblock value. // // We never toggle GC mode while holding the spinlock (BeginNoTriggerGC/EndNoTriggerGC // in EnterSpinLock/ReleaseSpinLock ensures it). Thus we do not need to switch to preemptive // while waiting on the spinlock. // { __SwitchToThread(0, ++dwSwitchCount); } continue; default: // Must be an error otherwise - ignore it _ASSERTE(action == AwareLock::LeaveHelperAction_Error); return FALSE; } } } #endif //!DACCESS_COMPILE // Returns TRUE if the lock is owned and FALSE otherwise // threadId is set to the ID (Thread::GetThreadId()) of the thread which owns the lock // acquisitionCount is set to the number of times the lock needs to be released before // it is unowned BOOL ObjHeader::GetThreadOwningMonitorLock(DWORD *pThreadId, DWORD *pAcquisitionCount) { CONTRACTL { NOTHROW; GC_NOTRIGGER; #ifndef DACCESS_COMPILE if (!IsGCSpecialThread ()) {MODE_COOPERATIVE;} else {MODE_ANY;} #endif } CONTRACTL_END; SUPPORTS_DAC; DWORD bits = GetBits(); if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) { if (bits & BIT_SBLK_IS_HASHCODE) { // // This thread does not own the lock. // *pThreadId = 0; *pAcquisitionCount = 0; return FALSE; } else { // // We have a syncblk // DWORD index = bits & MASK_SYNCBLOCKINDEX; SyncBlock* psb = g_pSyncTable[(int)index].m_SyncBlock; _ASSERTE(psb->GetMonitor() != NULL); Thread* pThread = psb->GetMonitor()->GetHoldingThread(); if(pThread == NULL) { *pThreadId = 0; *pAcquisitionCount = 0; return FALSE; } else { *pThreadId = pThread->GetThreadId(); *pAcquisitionCount = psb->GetMonitor()->GetRecursionLevel(); return TRUE; } } } else { // // We have a thinlock // DWORD lockThreadId, recursionLevel; lockThreadId = bits & SBLK_MASK_LOCK_THREADID; recursionLevel = (bits & SBLK_MASK_LOCK_RECLEVEL) >> SBLK_RECLEVEL_SHIFT; //if thread ID is 0, recursionLevel got to be zero //but thread ID doesn't have to be valid because the lock could be orphanend _ASSERTE (lockThreadId != 0 || recursionLevel == 0 ); *pThreadId = lockThreadId; if(lockThreadId != 0) { // in the header, the recursionLevel of 0 means the lock is owned once // (this differs from m_Recursion in the AwareLock) *pAcquisitionCount = recursionLevel + 1; return TRUE; } else { *pAcquisitionCount = 0; return FALSE; } } } #ifndef DACCESS_COMPILE #ifdef MP_LOCKS DEBUG_NOINLINE void ObjHeader::EnterSpinLock() { // NOTE: This function cannot have a dynamic contract. If it does, the contract's // destructor will reset the CLR debug state to what it was before entering the // function, which will undo the BeginNoTriggerGC() call below. SCAN_SCOPE_BEGIN; STATIC_CONTRACT_GC_NOTRIGGER; #ifdef _DEBUG int i = 0; #endif DWORD dwSwitchCount = 0; while (TRUE) { #ifdef _DEBUG #ifdef HOST_64BIT // Give 64bit more time because there isn't a remoting fast path now, and we've hit this assert // needlessly in CLRSTRESS. if (i++ > 30000) #else if (i++ > 10000) #endif // HOST_64BIT _ASSERTE(!"ObjHeader::EnterLock timed out"); #endif // get the value so that it doesn't get changed under us. LONG curValue = m_SyncBlockValue.LoadWithoutBarrier(); // check if lock taken if (! (curValue & BIT_SBLK_SPIN_LOCK)) { // try to take the lock LONG newValue = curValue | BIT_SBLK_SPIN_LOCK; LONG result = FastInterlockCompareExchange((LONG*)&m_SyncBlockValue, newValue, curValue); if (result == curValue) break; } if (g_SystemInfo.dwNumberOfProcessors > 1) { for (int spinCount = 0; spinCount < BIT_SBLK_SPIN_COUNT; spinCount++) { if (! (m_SyncBlockValue & BIT_SBLK_SPIN_LOCK)) break; YieldProcessorNormalized(); // indicate to the processor that we are spinning } if (m_SyncBlockValue & BIT_SBLK_SPIN_LOCK) __SwitchToThread(0, ++dwSwitchCount); } else __SwitchToThread(0, ++dwSwitchCount); } INCONTRACT(Thread* pThread = GetThread()); INCONTRACT(if (pThread != NULL) pThread->BeginNoTriggerGC(__FILE__, __LINE__)); } #else DEBUG_NOINLINE void ObjHeader::EnterSpinLock() { SCAN_SCOPE_BEGIN; STATIC_CONTRACT_GC_NOTRIGGER; #ifdef _DEBUG int i = 0; #endif DWORD dwSwitchCount = 0; while (TRUE) { #ifdef _DEBUG if (i++ > 10000) _ASSERTE(!"ObjHeader::EnterLock timed out"); #endif // get the value so that it doesn't get changed under us. LONG curValue = m_SyncBlockValue.LoadWithoutBarrier(); // check if lock taken if (! (curValue & BIT_SBLK_SPIN_LOCK)) { // try to take the lock LONG newValue = curValue | BIT_SBLK_SPIN_LOCK; LONG result = FastInterlockCompareExchange((LONG*)&m_SyncBlockValue, newValue, curValue); if (result == curValue) break; } __SwitchToThread(0, ++dwSwitchCount); } INCONTRACT(Thread* pThread = GetThread()); INCONTRACT(if (pThread != NULL) pThread->BeginNoTriggerGC(__FILE__, __LINE__)); } #endif //MP_LOCKS DEBUG_NOINLINE void ObjHeader::ReleaseSpinLock() { SCAN_SCOPE_END; LIMITED_METHOD_CONTRACT; INCONTRACT(Thread* pThread = GetThread()); INCONTRACT(if (pThread != NULL) pThread->EndNoTriggerGC()); FastInterlockAnd(&m_SyncBlockValue, ~BIT_SBLK_SPIN_LOCK); } #endif //!DACCESS_COMPILE #ifndef DACCESS_COMPILE DWORD ObjHeader::GetSyncBlockIndex() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; DWORD indx; if ((indx = GetHeaderSyncBlockIndex()) == 0) { BOOL fMustCreateSyncBlock = FALSE; { //Need to get it from the cache SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache()); //Try one more time if (GetHeaderSyncBlockIndex() == 0) { ENTER_SPIN_LOCK(this); // Now the header will be stable - check whether hashcode, appdomain index or lock information is stored in it. DWORD bits = GetBits(); if (((bits & (BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE)) == (BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE)) || ((bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) == 0)) { // Need a sync block to store this info fMustCreateSyncBlock = TRUE; } else { SetIndex(BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | SyncBlockCache::GetSyncBlockCache()->NewSyncBlockSlot(GetBaseObject())); } LEAVE_SPIN_LOCK(this); } // SyncBlockCache::LockHolder goes out of scope here } if (fMustCreateSyncBlock) GetSyncBlock(); if ((indx = GetHeaderSyncBlockIndex()) == 0) COMPlusThrowOM(); } return indx; } #if defined (VERIFY_HEAP) BOOL ObjHeader::Validate (BOOL bVerifySyncBlkIndex) { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_COOPERATIVE; DWORD bits = GetBits (); Object * obj = GetBaseObject (); BOOL bVerifyMore = g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_SYNCBLK; //the highest 2 bits have reloaded meaning // BIT_UNUSED 0x80000000 // BIT_SBLK_FINALIZER_RUN 0x40000000 if (bits & BIT_SBLK_FINALIZER_RUN) { ASSERT_AND_CHECK (obj->GetGCSafeMethodTable ()->HasFinalizer ()); } //BIT_SBLK_GC_RESERVE (0x20000000) is only set during GC. But for frozen object, we don't clean the bit if (bits & BIT_SBLK_GC_RESERVE) { if (!GCHeapUtilities::IsGCInProgress () && !GCHeapUtilities::GetGCHeap()->IsConcurrentGCInProgress ()) { #ifdef FEATURE_BASICFREEZE ASSERT_AND_CHECK (GCHeapUtilities::GetGCHeap()->IsInFrozenSegment(obj)); #else //FEATURE_BASICFREEZE _ASSERTE(!"Reserve bit not cleared"); return FALSE; #endif //FEATURE_BASICFREEZE } } //Don't know how to verify BIT_SBLK_SPIN_LOCK (0x10000000) //BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX (0x08000000) if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) { //if BIT_SBLK_IS_HASHCODE (0x04000000) is not set, //rest of the DWORD is SyncBlk Index if (!(bits & BIT_SBLK_IS_HASHCODE)) { if (bVerifySyncBlkIndex && GCHeapUtilities::GetGCHeap()->RuntimeStructuresValid ()) { DWORD sbIndex = bits & MASK_SYNCBLOCKINDEX; ASSERT_AND_CHECK(SyncTableEntry::GetSyncTableEntry()[sbIndex].m_Object == obj); } } else { // rest of the DWORD is a hash code and we don't have much to validate it } } else { //if BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX is clear, rest of DWORD is thin lock thread ID, //thin lock recursion level and appdomain index DWORD lockThreadId = bits & SBLK_MASK_LOCK_THREADID; DWORD recursionLevel = (bits & SBLK_MASK_LOCK_RECLEVEL) >> SBLK_RECLEVEL_SHIFT; //if thread ID is 0, recursionLeve got to be zero //but thread ID doesn't have to be valid because the lock could be orphanend ASSERT_AND_CHECK (lockThreadId != 0 || recursionLevel == 0 ); } return TRUE; } #endif //VERIFY_HEAP // This holder takes care of the SyncBlock memory cleanup if an OOM occurs inside a call to NewSyncBlockSlot. // // Warning: Assumes you already own the cache lock. // Assumes nothing allocated inside the SyncBlock (only releases the memory, does not destruct.) // // This holder really just meets GetSyncBlock()'s special needs. It's not a general purpose holder. // Do not inline this call. (fyuan) // SyncBlockMemoryHolder is normally a check for empty pointer and return. Inlining VoidDeleteSyncBlockMemory adds expensive exception handling. void VoidDeleteSyncBlockMemory(SyncBlock* psb) { LIMITED_METHOD_CONTRACT; SyncBlockCache::GetSyncBlockCache()->DeleteSyncBlockMemory(psb); } typedef Wrapper<SyncBlock*, DoNothing<SyncBlock*>, VoidDeleteSyncBlockMemory, NULL> SyncBlockMemoryHolder; // get the sync block for an existing object SyncBlock *ObjHeader::GetSyncBlock() { CONTRACT(SyncBlock *) { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); POSTCONDITION(CheckPointer(RETVAL)); } CONTRACT_END; PTR_SyncBlock syncBlock = GetBaseObject()->PassiveGetSyncBlock(); DWORD indx = 0; BOOL indexHeld = FALSE; if (syncBlock) { #ifdef _DEBUG // Has our backpointer been correctly updated through every GC? PTR_SyncTableEntry pEntries(SyncTableEntry::GetSyncTableEntry()); _ASSERTE(pEntries[GetHeaderSyncBlockIndex()].m_Object == GetBaseObject()); #endif // _DEBUG RETURN syncBlock; } //Need to get it from the cache { SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache()); //Try one more time syncBlock = GetBaseObject()->PassiveGetSyncBlock(); if (syncBlock) RETURN syncBlock; SyncBlockMemoryHolder syncBlockMemoryHolder(SyncBlockCache::GetSyncBlockCache()->GetNextFreeSyncBlock()); syncBlock = syncBlockMemoryHolder; if ((indx = GetHeaderSyncBlockIndex()) == 0) { indx = SyncBlockCache::GetSyncBlockCache()->NewSyncBlockSlot(GetBaseObject()); } else { //We already have an index, we need to hold the syncblock indexHeld = TRUE; } { //! NewSyncBlockSlot has side-effects that we don't have backout for - thus, that must be the last //! failable operation called. CANNOTTHROWCOMPLUSEXCEPTION(); FAULT_FORBID(); syncBlockMemoryHolder.SuppressRelease(); new (syncBlock) SyncBlock(indx); { // after this point, nobody can update the index in the header ENTER_SPIN_LOCK(this); { // If the thin lock in the header is in use, transfer the information to the syncblock DWORD bits = GetBits(); if ((bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) == 0) { DWORD lockThreadId = bits & SBLK_MASK_LOCK_THREADID; DWORD recursionLevel = (bits & SBLK_MASK_LOCK_RECLEVEL) >> SBLK_RECLEVEL_SHIFT; if (lockThreadId != 0 || recursionLevel != 0) { // recursionLevel can't be non-zero if thread id is 0 _ASSERTE(lockThreadId != 0); Thread *pThread = g_pThinLockThreadIdDispenser->IdToThreadWithValidation(lockThreadId); if (pThread == NULL) { // The lock is orphaned. pThread = (Thread*) -1; } syncBlock->InitState(recursionLevel + 1, pThread); } } else if ((bits & BIT_SBLK_IS_HASHCODE) != 0) { DWORD hashCode = bits & MASK_HASHCODE; syncBlock->SetHashCode(hashCode); } } SyncTableEntry::GetSyncTableEntry() [indx].m_SyncBlock = syncBlock; // in order to avoid a race where some thread tries to get the AD index and we've already zapped it, // make sure the syncblock etc is all setup with the AD index prior to replacing the index // in the header if (GetHeaderSyncBlockIndex() == 0) { // We have transferred the AppDomain into the syncblock above. SetIndex(BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | indx); } //If we had already an index, hold the syncblock //for the lifetime of the object. if (indexHeld) syncBlock->SetPrecious(); LEAVE_SPIN_LOCK(this); } // SyncBlockCache::LockHolder goes out of scope here } } RETURN syncBlock; } BOOL ObjHeader::Wait(INT32 timeOut, BOOL exitContext) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; // The following code may cause GC, so we must fetch the sync block from // the object now in case it moves. SyncBlock *pSB = GetBaseObject()->GetSyncBlock(); // GetSyncBlock throws on failure _ASSERTE(pSB != NULL); // make sure we own the crst if (!pSB->DoesCurrentThreadOwnMonitor()) COMPlusThrow(kSynchronizationLockException); return pSB->Wait(timeOut,exitContext); } void ObjHeader::Pulse() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; // The following code may cause GC, so we must fetch the sync block from // the object now in case it moves. SyncBlock *pSB = GetBaseObject()->GetSyncBlock(); // GetSyncBlock throws on failure _ASSERTE(pSB != NULL); // make sure we own the crst if (!pSB->DoesCurrentThreadOwnMonitor()) COMPlusThrow(kSynchronizationLockException); pSB->Pulse(); } void ObjHeader::PulseAll() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; // The following code may cause GC, so we must fetch the sync block from // the object now in case it moves. SyncBlock *pSB = GetBaseObject()->GetSyncBlock(); // GetSyncBlock throws on failure _ASSERTE(pSB != NULL); // make sure we own the crst if (!pSB->DoesCurrentThreadOwnMonitor()) COMPlusThrow(kSynchronizationLockException); pSB->PulseAll(); } // *************************************************************************** // // AwareLock class implementation (GC-aware locking) // // *************************************************************************** void AwareLock::AllocLockSemEvent() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; // Before we switch from cooperative, ensure that this syncblock won't disappear // under us. For something as expensive as an event, do it permanently rather // than transiently. SetPrecious(); GCX_PREEMP(); // No need to take a lock - CLREvent::CreateMonitorEvent is thread safe m_SemEvent.CreateMonitorEvent((SIZE_T)this); } void AwareLock::Enter() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; Thread *pCurThread = GetThread(); LockState state = m_lockState.VolatileLoadWithoutBarrier(); if (!state.IsLocked() || m_HoldingThread != pCurThread) { if (m_lockState.InterlockedTryLock_Or_RegisterWaiter(this, state)) { // We get here if we successfully acquired the mutex. m_HoldingThread = pCurThread; m_Recursion = 1; #if defined(_DEBUG) && defined(TRACK_SYNC) // The best place to grab this is from the ECall frame Frame *pFrame = pCurThread->GetFrame(); int caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1); pCurThread->m_pTrackSync->EnterSync(caller, this); #endif return; } // Lock was not acquired and the waiter was registered // Didn't manage to get the mutex, must wait. // The precondition for EnterEpilog is that the count of waiters be bumped // to account for this thread, which was done above. EnterEpilog(pCurThread); return; } // Got the mutex via recursive locking on the same thread. _ASSERTE(m_Recursion >= 1); m_Recursion++; #if defined(_DEBUG) && defined(TRACK_SYNC) // The best place to grab this is from the ECall frame Frame *pFrame = pCurThread->GetFrame(); int caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1); pCurThread->m_pTrackSync->EnterSync(caller, this); #endif } BOOL AwareLock::TryEnter(INT32 timeOut) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; if (timeOut == 0) {MODE_ANY;} else {MODE_COOPERATIVE;} INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; Thread *pCurThread = GetThread(); if (pCurThread->IsAbortRequested()) { pCurThread->HandleThreadAbort(); } LockState state = m_lockState.VolatileLoadWithoutBarrier(); if (!state.IsLocked() || m_HoldingThread != pCurThread) { if (timeOut == 0 ? m_lockState.InterlockedTryLock(state) : m_lockState.InterlockedTryLock_Or_RegisterWaiter(this, state)) { // We get here if we successfully acquired the mutex. m_HoldingThread = pCurThread; m_Recursion = 1; #if defined(_DEBUG) && defined(TRACK_SYNC) // The best place to grab this is from the ECall frame Frame *pFrame = pCurThread->GetFrame(); int caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1); pCurThread->m_pTrackSync->EnterSync(caller, this); #endif return true; } // Lock was not acquired and the waiter was registered if the timeout is nonzero // Didn't manage to get the mutex, return failure if no timeout, else wait // for at most timeout milliseconds for the mutex. if (timeOut == 0) { return false; } // The precondition for EnterEpilog is that the count of waiters be bumped // to account for this thread, which was done above return EnterEpilog(pCurThread, timeOut); } // Got the mutex via recursive locking on the same thread. _ASSERTE(m_Recursion >= 1); m_Recursion++; #if defined(_DEBUG) && defined(TRACK_SYNC) // The best place to grab this is from the ECall frame Frame *pFrame = pCurThread->GetFrame(); int caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1); pCurThread->m_pTrackSync->EnterSync(caller, this); #endif return true; } BOOL AwareLock::EnterEpilog(Thread* pCurThread, INT32 timeOut) { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_GC_TRIGGERS; // While we are in this frame the thread is considered blocked on the // critical section of the monitor lock according to the debugger DebugBlockingItem blockingMonitorInfo; blockingMonitorInfo.dwTimeout = timeOut; blockingMonitorInfo.pMonitor = this; blockingMonitorInfo.pAppDomain = SystemDomain::GetCurrentDomain(); blockingMonitorInfo.type = DebugBlock_MonitorCriticalSection; DebugBlockingItemHolder holder(pCurThread, &blockingMonitorInfo); // We need a separate helper because it uses SEH and the holder has a // destructor return EnterEpilogHelper(pCurThread, timeOut); } #ifdef _DEBUG #define _LOGCONTENTION #endif // _DEBUG #ifdef _LOGCONTENTION inline void LogContention() { WRAPPER_NO_CONTRACT; #ifdef LOGGING if (LoggingOn(LF_SYNC, LL_INFO100)) { LogSpewAlways("Contention: Stack Trace Begin\n"); void LogStackTrace(); LogStackTrace(); LogSpewAlways("Contention: Stack Trace End\n"); } #endif } #else #define LogContention() #endif double ComputeElapsedTimeInNanosecond(LARGE_INTEGER startTicks, LARGE_INTEGER endTicks) { static LARGE_INTEGER freq; if (freq.QuadPart == 0) QueryPerformanceFrequency(&freq); const double NsPerSecond = 1000 * 1000 * 1000; LONGLONG elapsedTicks = endTicks.QuadPart - startTicks.QuadPart; return (elapsedTicks * NsPerSecond) / freq.QuadPart; } BOOL AwareLock::EnterEpilogHelper(Thread* pCurThread, INT32 timeOut) { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_MODE_COOPERATIVE; STATIC_CONTRACT_GC_TRIGGERS; // IMPORTANT!!! // The caller has already registered a waiter. This function needs to unregister the waiter on all paths (exception paths // included). On runtimes where thread-abort is supported, a thread-abort also needs to unregister the waiter. There may be // a possibility for preemptive GC toggles below to handle a thread-abort, that should be taken into consideration when // porting this code back to .NET Framework. // Require all callers to be in cooperative mode. If they have switched to preemptive // mode temporarily before calling here, then they are responsible for protecting // the object associated with this lock. _ASSERTE(pCurThread->PreemptiveGCDisabled()); BOOLEAN IsContentionKeywordEnabled = ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, TRACE_LEVEL_INFORMATION, CLR_CONTENTION_KEYWORD); LARGE_INTEGER startTicks = { {0} }; if (IsContentionKeywordEnabled) { QueryPerformanceCounter(&startTicks); // Fire a contention start event for a managed contention FireEtwContentionStart_V1(ETW::ContentionLog::ContentionStructs::ManagedContention, GetClrInstanceId()); } LogContention(); Thread::IncrementMonitorLockContentionCount(pCurThread); OBJECTREF obj = GetOwningObject(); // We cannot allow the AwareLock to be cleaned up underneath us by the GC. IncrementTransientPrecious(); DWORD ret; GCPROTECT_BEGIN(obj); { if (!m_SemEvent.IsMonitorEventAllocated()) { AllocLockSemEvent(); } _ASSERTE(m_SemEvent.IsMonitorEventAllocated()); pCurThread->EnablePreemptiveGC(); for (;;) { // Measure the time we wait so that, in the case where we wake up // and fail to acquire the mutex, we can adjust remaining timeout // accordingly. ULONGLONG start = CLRGetTickCount64(); // It is likely the case that An APC threw an exception, for instance Thread.Interrupt(). The wait subsystem // guarantees that if a signal to the event being waited upon is observed by the woken thread, that thread's // wait will return WAIT_OBJECT_0. So in any race between m_SemEvent being signaled and the wait throwing an // exception, a thread that is woken by an exception would not observe the signal, and the signal would wake // another thread as necessary. // We must decrement the waiter count in the case an exception happened. This holder takes care of that class UnregisterWaiterHolder { LockState* m_pLockState; public: UnregisterWaiterHolder(LockState* pLockState) : m_pLockState(pLockState) { } ~UnregisterWaiterHolder() { if (m_pLockState != NULL) { m_pLockState->InterlockedUnregisterWaiter(); } } void SuppressRelease() { m_pLockState = NULL; } } unregisterWaiterHolder(&m_lockState); ret = m_SemEvent.Wait(timeOut, TRUE); _ASSERTE((ret == WAIT_OBJECT_0) || (ret == WAIT_TIMEOUT)); if (ret != WAIT_OBJECT_0) { // We timed out // (the holder unregisters the waiter here) break; } unregisterWaiterHolder.SuppressRelease(); // Spin a bit while trying to acquire the lock. This has a few benefits: // - Spinning helps to reduce waiter starvation. Since other non-waiter threads can take the lock while there are // waiters (see LockState::InterlockedTryLock()), once a waiter wakes it will be able to better compete // with other spinners for the lock. // - If there is another thread that is repeatedly acquiring and releasing the lock, spinning before waiting again // helps to prevent a waiter from repeatedly context-switching in and out // - Further in the same situation above, waking up and waiting shortly thereafter deprioritizes this waiter because // events release waiters in FIFO order. Spinning a bit helps a waiter to retain its priority at least for one // spin duration before it gets deprioritized behind all other waiters. if (g_SystemInfo.dwNumberOfProcessors > 1) { bool acquiredLock = false; YieldProcessorNormalizationInfo normalizationInfo; const DWORD spinCount = g_SpinConstants.dwMonitorSpinCount; for (DWORD spinIteration = 0; spinIteration < spinCount; ++spinIteration) { if (m_lockState.InterlockedTry_LockAndUnregisterWaiterAndObserveWakeSignal(this)) { acquiredLock = true; break; } SpinWait(normalizationInfo, spinIteration); } if (acquiredLock) { break; } } if (m_lockState.InterlockedObserveWakeSignal_Try_LockAndUnregisterWaiter(this)) { break; } // When calculating duration we consider a couple of special cases. // If the end tick is the same as the start tick we make the // duration a millisecond, to ensure we make forward progress if // there's a lot of contention on the mutex. Secondly, we have to // cope with the case where the tick counter wrapped while we where // waiting (we can cope with at most one wrap, so don't expect three // month timeouts to be very accurate). Luckily for us, the latter // case is taken care of by 32-bit modulo arithmetic automatically. if (timeOut != (INT32)INFINITE) { ULONGLONG end = CLRGetTickCount64(); ULONGLONG duration; if (end == start) { duration = 1; } else { duration = end - start; } duration = min(duration, (DWORD)timeOut); timeOut -= (INT32)duration; } } pCurThread->DisablePreemptiveGC(); } GCPROTECT_END(); DecrementTransientPrecious(); if (IsContentionKeywordEnabled) { LARGE_INTEGER endTicks; QueryPerformanceCounter(&endTicks); double elapsedTimeInNanosecond = ComputeElapsedTimeInNanosecond(startTicks, endTicks); // Fire a contention end event for a managed contention FireEtwContentionStop_V1(ETW::ContentionLog::ContentionStructs::ManagedContention, GetClrInstanceId(), elapsedTimeInNanosecond); } if (ret == WAIT_TIMEOUT) { return false; } m_HoldingThread = pCurThread; m_Recursion = 1; #if defined(_DEBUG) && defined(TRACK_SYNC) // The best place to grab this is from the ECall frame Frame *pFrame = pCurThread->GetFrame(); int caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1); pCurThread->m_pTrackSync->EnterSync(caller, this); #endif return true; } BOOL AwareLock::Leave() { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; Thread* pThread = GetThread(); AwareLock::LeaveHelperAction action = LeaveHelper(pThread); switch(action) { case AwareLock::LeaveHelperAction_None: // We are done return TRUE; case AwareLock::LeaveHelperAction_Signal: // Signal the event Signal(); return TRUE; default: // Must be an error otherwise _ASSERTE(action == AwareLock::LeaveHelperAction_Error); return FALSE; } } LONG AwareLock::LeaveCompletely() { WRAPPER_NO_CONTRACT; LONG count = 0; while (Leave()) { count++; } _ASSERTE(count > 0); // otherwise we were never in the lock return count; } BOOL AwareLock::OwnedByCurrentThread() { WRAPPER_NO_CONTRACT; return (GetThread() == m_HoldingThread); } // *************************************************************************** // // SyncBlock class implementation // // *************************************************************************** // We maintain two queues for SyncBlock::Wait. // 1. Inside SyncBlock we queue all threads that are waiting on the SyncBlock. // When we pulse, we pick the thread from this queue using FIFO. // 2. We queue all SyncBlocks that a thread is waiting for in Thread::m_WaitEventLink. // When we pulse a thread, we find the event from this queue to set, and we also // or in a 1 bit in the syncblock value saved in the queue, so that we can return // immediately from SyncBlock::Wait if the syncblock has been pulsed. BOOL SyncBlock::Wait(INT32 timeOut, BOOL exitContext) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; Thread *pCurThread = GetThread(); BOOL isTimedOut = FALSE; BOOL isEnqueued = FALSE; WaitEventLink waitEventLink; WaitEventLink *pWaitEventLink; // As soon as we flip the switch, we are in a race with the GC, which could clean // up the SyncBlock underneath us -- unless we report the object. _ASSERTE(pCurThread->PreemptiveGCDisabled()); // Does this thread already wait for this SyncBlock? WaitEventLink *walk = pCurThread->WaitEventLinkForSyncBlock(this); if (walk->m_Next) { if (walk->m_Next->m_WaitSB == this) { // Wait on the same lock again. walk->m_Next->m_RefCount ++; pWaitEventLink = walk->m_Next; } else if ((SyncBlock*)(((DWORD_PTR)walk->m_Next->m_WaitSB) & ~1)== this) { // This thread has been pulsed. No need to wait. return TRUE; } } else { // First time this thread is going to wait for this SyncBlock. CLREvent* hEvent; if (pCurThread->m_WaitEventLink.m_Next == NULL) { hEvent = &(pCurThread->m_EventWait); } else { hEvent = GetEventFromEventStore(); } waitEventLink.m_WaitSB = this; waitEventLink.m_EventWait = hEvent; waitEventLink.m_Thread = pCurThread; waitEventLink.m_Next = NULL; waitEventLink.m_LinkSB.m_pNext = NULL; waitEventLink.m_RefCount = 1; pWaitEventLink = &waitEventLink; walk->m_Next = pWaitEventLink; // Before we enqueue it (and, thus, before it can be dequeued), reset the event // that will awaken us. hEvent->Reset(); // This thread is now waiting on this sync block ThreadQueue::EnqueueThread(pWaitEventLink, this); isEnqueued = TRUE; } _ASSERTE ((SyncBlock*)((DWORD_PTR)walk->m_Next->m_WaitSB & ~1)== this); PendingSync syncState(walk); OBJECTREF obj = m_Monitor.GetOwningObject(); m_Monitor.IncrementTransientPrecious(); // While we are in this frame the thread is considered blocked on the // event of the monitor lock according to the debugger DebugBlockingItem blockingMonitorInfo; blockingMonitorInfo.dwTimeout = timeOut; blockingMonitorInfo.pMonitor = &m_Monitor; blockingMonitorInfo.pAppDomain = SystemDomain::GetCurrentDomain(); blockingMonitorInfo.type = DebugBlock_MonitorEvent; DebugBlockingItemHolder holder(pCurThread, &blockingMonitorInfo); GCPROTECT_BEGIN(obj); { GCX_PREEMP(); // remember how many times we synchronized syncState.m_EnterCount = LeaveMonitorCompletely(); _ASSERTE(syncState.m_EnterCount > 0); isTimedOut = pCurThread->Block(timeOut, &syncState); } GCPROTECT_END(); m_Monitor.DecrementTransientPrecious(); return !isTimedOut; } void SyncBlock::Pulse() { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; WaitEventLink *pWaitEventLink; if ((pWaitEventLink = ThreadQueue::DequeueThread(this)) != NULL) pWaitEventLink->m_EventWait->Set(); } void SyncBlock::PulseAll() { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; WaitEventLink *pWaitEventLink; while ((pWaitEventLink = ThreadQueue::DequeueThread(this)) != NULL) pWaitEventLink->m_EventWait->Set(); } bool SyncBlock::SetInteropInfo(InteropSyncBlockInfo* pInteropInfo) { WRAPPER_NO_CONTRACT; SetPrecious(); // We could be agile, but not have noticed yet. We can't assert here // that we live in any given domain, nor is this an appropriate place // to re-parent the syncblock. /* _ASSERTE (m_dwAppDomainIndex.m_dwIndex == 0 || m_dwAppDomainIndex == SystemDomain::System()->DefaultDomain()->GetIndex() || m_dwAppDomainIndex == GetAppDomain()->GetIndex()); m_dwAppDomainIndex = GetAppDomain()->GetIndex(); */ return (FastInterlockCompareExchangePointer(&m_pInteropInfo, pInteropInfo, NULL) == NULL); } #ifdef EnC_SUPPORTED // Store information about fields added to this object by EnC // This must be called from a thread in the AppDomain of this object instance void SyncBlock::SetEnCInfo(EnCSyncBlockInfo *pEnCInfo) { WRAPPER_NO_CONTRACT; // We can't recreate the field contents, so this SyncBlock can never go away SetPrecious(); // Store the field info (should only ever happen once) _ASSERTE( m_pEnCInfo == NULL ); m_pEnCInfo = pEnCInfo; } #endif // EnC_SUPPORTED #endif // !DACCESS_COMPILE #if defined(HOST_64BIT) && defined(_DEBUG) void ObjHeader::IllegalAlignPad() { WRAPPER_NO_CONTRACT; #ifdef LOGGING void** object = ((void**) this) + 1; LogSpewAlways("\n\n******** Illegal ObjHeader m_alignpad not 0, object" FMT_ADDR "\n\n", DBG_ADDR(object)); #endif _ASSERTE(m_alignpad == 0); } #endif // HOST_64BIT && _DEBUG
30.277684
176
0.593663
swaroop-sridhar
29b74e7c0d5bb67ae412ee47c96971497019c737
16,706
cpp
C++
Source/SVWidgetsLib/FilterParameterWidgets/CalculatorWidget.cpp
jmarquisbq/SIMPL
375653013742cfe9aed603fc9a6bab6d9c96be31
[ "NRL" ]
null
null
null
Source/SVWidgetsLib/FilterParameterWidgets/CalculatorWidget.cpp
jmarquisbq/SIMPL
375653013742cfe9aed603fc9a6bab6d9c96be31
[ "NRL" ]
null
null
null
Source/SVWidgetsLib/FilterParameterWidgets/CalculatorWidget.cpp
jmarquisbq/SIMPL
375653013742cfe9aed603fc9a6bab6d9c96be31
[ "NRL" ]
null
null
null
/* ============================================================================ * Copyright (c) 2009-2015 BlueQuartz Software, LLC * * 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 BlueQuartz Software, the US Air Force, 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. * * The code contained herein was partially funded by the followig contracts: * United States Air Force Prime Contract FA8650-07-D-5800 * United States Air Force Prime Contract FA8650-10-D-5210 * United States Prime Contract Navy N00173-07-C-2068 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "CalculatorWidget.h" #include <QtCore/QDebug> #include <QtWidgets/QMenu> #include "SIMPLib/DataContainers/DataContainerArray.h" #include "SIMPLib/Utilities/FilterCompatibility.hpp" #include "SVWidgetsLib/Core/SVWidgetsLibConstants.h" #include "SVWidgetsLib/Widgets/SVStyle.h" #include "FilterParameterWidgetsDialogs.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- CalculatorWidget::CalculatorWidget(FilterParameter* parameter, AbstractFilter* filter, QWidget* parent) : FilterParameterWidget(parameter, filter, parent) , m_ScalarsMenu(nullptr) , m_VectorsMenu(nullptr) , m_SelectedText("") , m_SelectionStart(-1) { m_Filter = SIMPL_FILTER_COMPATIBILITY_CHECK(filter, parameter, CalculatorWidget, ArrayCalculator); m_FilterParameter = SIMPL_FILTER_PARAMETER_COMPATIBILITY_CHECK(filter, parameter, CalculatorWidget, CalculatorFilterParameter); setupUi(this); setupGui(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- CalculatorWidget::~CalculatorWidget() = default; // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::setupGui() { blockSignals(true); if(getFilterParameter() != nullptr) { QString str = m_FilterParameter->getGetterCallback()(); equation->setText(str); } blockSignals(false); // Catch when the filter is about to execute the preflight connect(getFilter(), &AbstractFilter::preflightAboutToExecute, this, &CalculatorWidget::beforePreflight); // Catch when the filter is finished running the preflight connect(getFilter(), &AbstractFilter::preflightExecuted, this, &CalculatorWidget::afterPreflight); // Catch when the filter wants its values updated connect(getFilter(), &AbstractFilter::updateFilterParameters, this, &CalculatorWidget::filterNeedsInputParameters); // If the DataArrayPath is updated in the filter, update the widget connect(getFilter(), SIGNAL(dataArrayPathUpdated(QString, DataArrayPath::RenameType)), this, SLOT(updateDataArrayPath(QString, DataArrayPath::RenameType))); connect(equation, SIGNAL(textChanged(const QString&)), this, SLOT(widgetChanged(const QString&))); connect(equation, SIGNAL(selectionChanged()), this, SLOT(updateSelection())); // Unary Operator Buttons connect(absBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(sinBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(cosBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(tanBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(sqrtBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(asinBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(acosBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(atanBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(ceilBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(floorBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(log10Btn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); connect(lnBtn, SIGNAL(clicked()), this, SLOT(printUnaryButtonName())); // Other Buttons connect(leftBraceBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(rightBraceBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(commaBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(addBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(subtractBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(multiplyBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(divideBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(oneBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(twoBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(threeBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(fourBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(fiveBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(sixBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(sevenBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(eightBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(nineBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(zeroBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); connect(decimalBtn, SIGNAL(clicked()), this, SLOT(printButtonName())); applyChangesBtn->setVisible(false); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::printUnaryButtonName() { QPushButton* button = static_cast<QPushButton*>(sender()); if(nullptr != button) { printStringToEquation(button->text() + "("); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::printButtonName() { QPushButton* button = static_cast<QPushButton*>(sender()); if(nullptr != button) { printStringToEquation(button->text()); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::printActionName() { QAction* action = static_cast<QAction*>(sender()); if(nullptr != action) { printStringToEquation(action->text()); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::printStringToEquation(QString str) { QString equationText = equation->text(); if(!m_SelectedText.isEmpty() && m_SelectionStart >= 0) { equationText.replace(m_SelectionStart, m_SelectedText.size(), str); equation->setFocus(); equation->setText(equationText); equation->setCursorPosition(m_SelectionStart + str.size()); m_SelectedText.clear(); m_SelectionStart = -1; } else { int pos = equation->cursorPosition(); equationText.insert(pos, str); equation->setText(equationText); equation->setCursorPosition(pos + str.size()); equation->setFocus(); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_clearBtn_clicked() { equation->clear(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_backspaceBtn_clicked() { QString equationText = equation->text(); equationText.chop(1); equation->setText(equationText); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_radiansBtn_toggled(bool checked) { m_DidCausePreflight = true; Q_EMIT parametersChanged(); m_DidCausePreflight = false; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_piBtn_clicked() { printStringToEquation("3.1415927"); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_logBtn_clicked() { printStringToEquation("log("); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_expBtn_clicked() { printStringToEquation("exp("); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_powBtn_clicked() { printStringToEquation("^"); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_rootBtn_clicked() { printStringToEquation("root("); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_scalarsBtn_clicked() { if(nullptr != m_VectorsMenu) { delete m_ScalarsMenu; m_ScalarsMenu = nullptr; } // Create Scalars Menu m_ScalarsMenu = new QMenu(this); AttributeMatrix::Pointer am = m_Filter->getDataContainerArray()->getAttributeMatrix(m_Filter->getSelectedAttributeMatrix()); if(nullptr == am) { return; } QStringList nameList = am->getAttributeArrayNames(); for(int i = 0; i < nameList.size(); i++) { if(am->getAttributeArray(nameList[i])->getComponentDimensions()[0] == 1) { QAction* action = new QAction(nameList[i], m_ScalarsMenu); connect(action, SIGNAL(triggered()), this, SLOT(printActionName())); m_ScalarsMenu->addAction(action); } } scalarsBtn->setMenu(m_ScalarsMenu); scalarsBtn->showMenu(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_vectorsBtn_clicked() { if(nullptr != m_VectorsMenu) { delete m_VectorsMenu; m_VectorsMenu = nullptr; } // Create Vectors Menu m_VectorsMenu = new QMenu(this); AttributeMatrix::Pointer am = m_Filter->getDataContainerArray()->getAttributeMatrix(m_Filter->getSelectedAttributeMatrix()); if(nullptr == am) { return; } QStringList nameList = am->getAttributeArrayNames(); for(int i = 0; i < nameList.size(); i++) { if(am->getAttributeArray(nameList[i])->getComponentDimensions()[0] > 1) { QAction* action = new QAction(nameList[i], m_VectorsMenu); connect(action, SIGNAL(triggered()), this, SLOT(printActionName())); m_VectorsMenu->addAction(action); } } vectorsBtn->setMenu(m_VectorsMenu); vectorsBtn->showMenu(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_equation_returnPressed() { // qDebug() << "DataArrayCreationWidget::on_value_returnPressed() " << this; m_DidCausePreflight = true; on_applyChangesBtn_clicked(); m_DidCausePreflight = false; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::updateSelection() { if(equation->hasFocus()) { m_SelectedText = equation->selectedText(); m_SelectionStart = equation->selectionStart(); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::hideButton() { equation->setToolTip(""); applyChangesBtn->setVisible(false); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::widgetChanged(const QString& text) { SVStyle::Instance()->SetErrorColor("QLineEdit", equation); equation->setToolTip("Press the 'Return' key to apply your changes"); if(!applyChangesBtn->isVisible()) { applyChangesBtn->setVisible(true); fadeInWidget(applyChangesBtn); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::beforePreflight() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::afterPreflight() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::filterNeedsInputParameters(AbstractFilter* filter) { CalculatorFilterParameter::SetterCallbackType setter = m_FilterParameter->getSetterCallback(); if(setter) { setter(equation->text()); } else { getFilter()->notifyMissingProperty(getFilterParameter()); } ArrayCalculator* calculatorFilter = dynamic_cast<ArrayCalculator*>(filter); Q_ASSERT_X(calculatorFilter != nullptr, "NULL Pointer", "CalculatorWidget can ONLY be used with an ArrayCalculator filter"); if(radiansBtn->isChecked()) { calculatorFilter->setUnits(ArrayCalculator::Radians); } else { calculatorFilter->setUnits(ArrayCalculator::Degrees); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::on_applyChangesBtn_clicked() { equation->setStyleSheet(QString("")); Q_EMIT parametersChanged(); QPointer<QtSFaderWidget> faderWidget = new QtSFaderWidget(applyChangesBtn); setFaderWidget(faderWidget); if(getFaderWidget() != nullptr) { faderWidget->close(); } faderWidget = new QtSFaderWidget(applyChangesBtn); faderWidget->setFadeOut(); connect(faderWidget, SIGNAL(animationComplete()), this, SLOT(hideButton())); faderWidget->start(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CalculatorWidget::updateDataArrayPath(QString propertyName, const DataArrayPath::RenameType& renamePath) { DataArrayPath oldPath; DataArrayPath newPath; std::tie(oldPath, newPath) = renamePath; if(propertyName == getFilterParameter()->getPropertyName()) { QString inputStr = equation->text(); inputStr.replace(oldPath.getDataArrayName(), newPath.getDataArrayName()); equation->setText(inputStr); } }
35.773019
158
0.542141
jmarquisbq
29b9130993ce84a96532667cbd236085c4577c5d
5,602
cpp
C++
src/wiztk/system/threading/thread.cpp
wiztk/framework
179baf8a24406b19d3f4ea28e8405358b21f8446
[ "Apache-2.0" ]
37
2017-11-22T14:15:33.000Z
2021-11-25T20:39:39.000Z
src/wiztk/system/threading/thread.cpp
wiztk/framework
179baf8a24406b19d3f4ea28e8405358b21f8446
[ "Apache-2.0" ]
3
2018-03-01T12:44:22.000Z
2021-01-04T23:14:41.000Z
src/wiztk/system/threading/thread.cpp
wiztk/framework
179baf8a24406b19d3f4ea28e8405358b21f8446
[ "Apache-2.0" ]
10
2017-11-25T19:09:11.000Z
2020-12-02T02:05:47.000Z
/* * Copyright 2017 - 2018 The WizTK Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 "thread/private.hpp" #include <stdexcept> namespace wiztk { namespace system { namespace threading { Thread::ID Thread::ID::GetCurrent() { ID id; id.native_ = pthread_self(); return id; } // ----- /** * @brief A helper class to set/get low-level thread attributes. */ class WIZTK_NO_EXPORT Thread::Attribute { friend class Thread; public: WIZTK_DECLARE_NONCOPYABLE_AND_NONMOVALE(Attribute); enum DetachStateType { kCreateDetached = PTHREAD_CREATE_DETACHED, kCreateJoinable = PTHREAD_CREATE_JOINABLE }; enum ScopeType { kSystem = PTHREAD_SCOPE_SYSTEM, kProcess = PTHREAD_SCOPE_PROCESS }; enum SchedulerType { kInheritSched = PTHREAD_INHERIT_SCHED, kExplicitSched = PTHREAD_EXPLICIT_SCHED }; Attribute(); ~Attribute(); void SetDetachState(DetachStateType state_type); DetachStateType GetDetachState() const; void SetScope(ScopeType scope_type); ScopeType GetScope() const; void SetStackSize(size_t stack_size); size_t GetStackSize() const; const pthread_attr_t *data() const { return &native_; } private: pthread_attr_t native_; }; // ------- const Thread::DelegateDeleter Thread::kDefaultDelegateDeleter = [](Delegate *obj) { delete obj; }; const Thread::DelegateDeleter Thread::kLeakyDelegateDeleter = [](Delegate *obj) { // WARNING: do nothing! }; Thread::Thread() { p_ = std::make_unique<Private>(); } Thread::Thread(Delegate *delegate, const DelegateDeleter &deleter) { p_ = std::make_unique<Private>(delegate, deleter); } Thread::Thread(const Options &options) { p_ = std::make_unique<Private>(options); } Thread::Thread(Thread &&other) noexcept { p_ = std::move(other.p_); } Thread::~Thread() { Stop(); } Thread &Thread::operator=(Thread &&other) noexcept { p_ = std::move(other.p_); return *this; } void Thread::Start() { typedef void *(*fn)(void *); int ret = 0; Attribute attr; p_->options.joinable ? attr.SetDetachState(Attribute::kCreateJoinable) : attr.SetDetachState(Attribute::kCreateDetached); if (p_->options.stack_size > 0) attr.SetStackSize(p_->options.stack_size); ret = pthread_create(&p_->id.native_, attr.data(), reinterpret_cast<fn>(Thread::Private::StartRoutine), this); if (ret != 0) throw std::runtime_error("Error! Fail to start a thread!"); } void Thread::Start(const Options &options) { // TODO: implement this method } void Thread::Stop() { if (p_->state == kRunning) pthread_cancel(p_->id.native_); } void Thread::Join() { if (0 != pthread_join(p_->id.native_, nullptr)) throw std::runtime_error("Error! Fail to join a thread!"); p_->id.native_ = pthread_self(); } void Thread::Detach() { if (0 != pthread_detach(p_->id.native_)) throw std::runtime_error("Error! Fail to detach a thread!"); } const Thread::ID &Thread::GetID() const { return p_->id; } Thread *Thread::GetCurrent() { return Specific::kPerThreadStorage.Get()->thread; } void Thread::Run() { // Override in subclass } // ---- void Thread::Delegate::Run() { // Override in subclass } // ---- bool operator==(const Thread::ID &id1, const Thread::ID &id2) { return 0 != pthread_equal(id1.native_, id2.native_); } bool operator!=(const Thread::ID &id1, const Thread::ID &id2) { return 0 == pthread_equal(id1.native_, id2.native_); } // ----- Thread::Attribute::Attribute() { if (0 != pthread_attr_init(&native_)) throw std::runtime_error("Error! Cannot initialize thread attribute!"); } Thread::Attribute::~Attribute() { pthread_attr_destroy(&native_); } void Thread::Attribute::SetDetachState(DetachStateType state_type) { if (0 != pthread_attr_setdetachstate(&native_, state_type)) throw std::runtime_error("Error! Cannot set detach state!"); } Thread::Attribute::DetachStateType Thread::Attribute::GetDetachState() const { int val = 0; if (0 != pthread_attr_getdetachstate(&native_, &val)) throw std::runtime_error("Error! Cannot get detach state!"); return static_cast<DetachStateType>(val); } void Thread::Attribute::SetScope(ScopeType scope_type) { if (0 != pthread_attr_setscope(&native_, scope_type)) throw std::runtime_error("Error! Cannot set scope!"); } Thread::Attribute::ScopeType Thread::Attribute::GetScope() const { int val = 0; if (0 != pthread_attr_getscope(&native_, &val)) throw std::runtime_error("Error! Cannot get scope!"); return static_cast<ScopeType>(val); } void Thread::Attribute::SetStackSize(size_t stack_size) { if (0 != pthread_attr_setstacksize(&native_, stack_size)) throw std::runtime_error("Error! Cannot set stack size!"); } size_t Thread::Attribute::GetStackSize() const { size_t stack_size = 0; if (0 != pthread_attr_getstacksize(&native_, &stack_size)) throw std::runtime_error("Error! Cannot get stack size!"); return stack_size; } } // namespace threading } // namespace system } // namespace wiztk
23.244813
83
0.691539
wiztk
29ba9c18432148acb41da7fde93b13235e944a1e
3,084
hpp
C++
src/boost/serialization/strong_typedef.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
src/boost/serialization/strong_typedef.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
1
2021-08-30T18:02:49.000Z
2021-08-30T18:02:49.000Z
src/boost/serialization/strong_typedef.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
#ifndef BOOST_SERIALIZATION_STRONG_TYPEDEF_HPP #define BOOST_SERIALIZATION_STRONG_TYPEDEF_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // strong_typedef.hpp: // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // (C) Copyright 2016 Ashish Sadanandan // 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) // See http://www.boost.org/libs/serialization for updates, documentation, and revision history. // macro used to implement a strong typedef. strong typedef // guarentees that two types are distinguised even though the // share the same underlying implementation. typedef does not create // a new type. BOOST_STRONG_TYPEDEF(T, D) creates a new type named D // that operates as a type T. #include "boost/config.hpp" #include "boost/operators.hpp" #include "boost/type_traits/has_nothrow_assign.hpp" #include "boost/type_traits/has_nothrow_constructor.hpp" #include "boost/type_traits/has_nothrow_copy.hpp" #define BOOST_STRONG_TYPEDEF(T, D) \ struct D \ : boost::totally_ordered1< D \ , boost::totally_ordered2< D, T \ > > \ { \ T t; \ explicit D(const T& t_) BOOST_NOEXCEPT_IF(boost::has_nothrow_copy_constructor<T>::value) : t(t_) {} \ D() BOOST_NOEXCEPT_IF(boost::has_nothrow_default_constructor<T>::value) : t() {} \ D(const D & t_) BOOST_NOEXCEPT_IF(boost::has_nothrow_copy_constructor<T>::value) : t(t_.t) {} \ D& operator=(const D& rhs) BOOST_NOEXCEPT_IF(boost::has_nothrow_assign<T>::value) {t = rhs.t; return *this;} \ D& operator=(const T& rhs) BOOST_NOEXCEPT_IF(boost::has_nothrow_assign<T>::value) {t = rhs; return *this;} \ operator const T&() const {return t;} \ operator T&() {return t;} \ bool operator==(const D& rhs) const {return t == rhs.t;} \ bool operator<(const D& rhs) const {return t < rhs.t;} \ }; #endif // BOOST_SERIALIZATION_STRONG_TYPEDEF_HPP
60.470588
114
0.479572
107-systems
29c54fa07903f19a551759612a50d6181a24f780
25,392
cpp
C++
src/CommonProperties.cpp
TimoKunze/ButtonControls
a0b9860a30a86e613a633635b16e3db117133c50
[ "MIT" ]
2
2019-12-12T08:12:21.000Z
2021-03-30T05:00:53.000Z
src/CommonProperties.cpp
TimoKunze/ButtonControls
a0b9860a30a86e613a633635b16e3db117133c50
[ "MIT" ]
null
null
null
src/CommonProperties.cpp
TimoKunze/ButtonControls
a0b9860a30a86e613a633635b16e3db117133c50
[ "MIT" ]
1
2021-12-09T18:23:25.000Z
2021-12-09T18:23:25.000Z
// CommonProperties.cpp: The controls' "Common" property page #include "stdafx.h" #include "CommonProperties.h" CommonProperties::CommonProperties() { m_dwTitleID = IDS_TITLECOMMONPROPERTIES; m_dwDocStringID = IDS_DOCSTRINGCOMMONPROPERTIES; } ////////////////////////////////////////////////////////////////////// // implementation of IPropertyPage STDMETHODIMP CommonProperties::Apply(void) { ApplySettings(); return S_OK; } STDMETHODIMP CommonProperties::Activate(HWND hWndParent, LPCRECT pRect, BOOL modal) { IPropertyPage2Impl<CommonProperties>::Activate(hWndParent, pRect, modal); // attach to the controls controls.disabledEventsList.SubclassWindow(GetDlgItem(IDC_DISABLEDEVENTSBOX)); HIMAGELIST hStateImageList = SetupStateImageList(controls.disabledEventsList.GetImageList(LVSIL_STATE)); controls.disabledEventsList.SetImageList(hStateImageList, LVSIL_STATE); controls.disabledEventsList.SetExtendedListViewStyle(LVS_EX_DOUBLEBUFFER | LVS_EX_INFOTIP, LVS_EX_DOUBLEBUFFER | LVS_EX_INFOTIP | LVS_EX_FULLROWSELECT); controls.disabledEventsList.AddColumn(TEXT(""), 0); controls.disabledEventsList.GetToolTips().SetTitle(TTI_INFO, TEXT("Affected events")); controls.useImprovedImgLstSupportCheck.Attach(GetDlgItem(IDC_USEIMPROVEDIMGLSTSUPPORTCHECK)); controls.iconIndexesCombo.Attach(GetDlgItem(IDC_ICONINDEXESCOMBO)); controls.iconIndexEdit.Attach(GetDlgItem(IDC_ICONINDEXEDIT)); controls.iconIndexEdit.SetLimitText(4); controls.setIconIndexButton.Attach(GetDlgItem(IDC_SETICONINDEXBUTTON)); // setup the toolbar CRect toolbarRect; GetClientRect(&toolbarRect); toolbarRect.OffsetRect(0, 2); toolbarRect.left += toolbarRect.right - 46; toolbarRect.bottom = toolbarRect.top + 22; controls.toolbar.Create(*this, toolbarRect, NULL, WS_CHILDWINDOW | WS_VISIBLE | TBSTYLE_TRANSPARENT | TBSTYLE_FLAT | TBSTYLE_TOOLTIPS | CCS_NODIVIDER | CCS_NOPARENTALIGN | CCS_NORESIZE, 0); controls.toolbar.SetButtonStructSize(); controls.imagelistEnabled.CreateFromImage(IDB_TOOLBARENABLED, 16, 0, RGB(255, 0, 255), IMAGE_BITMAP, LR_CREATEDIBSECTION); controls.toolbar.SetImageList(controls.imagelistEnabled); controls.imagelistDisabled.CreateFromImage(IDB_TOOLBARDISABLED, 16, 0, RGB(255, 0, 255), IMAGE_BITMAP, LR_CREATEDIBSECTION); controls.toolbar.SetDisabledImageList(controls.imagelistDisabled); // insert the buttons TBBUTTON buttons[2]; ZeroMemory(buttons, sizeof(buttons)); buttons[0].iBitmap = 0; buttons[0].idCommand = ID_LOADSETTINGS; buttons[0].fsState = TBSTATE_ENABLED; buttons[0].fsStyle = BTNS_BUTTON; buttons[1].iBitmap = 1; buttons[1].idCommand = ID_SAVESETTINGS; buttons[1].fsStyle = BTNS_BUTTON; buttons[1].fsState = TBSTATE_ENABLED; controls.toolbar.AddButtons(2, buttons); LoadSettings(); return S_OK; } STDMETHODIMP CommonProperties::SetObjects(ULONG objects, IUnknown** ppControls) { if(m_bDirty) { Apply(); } IPropertyPage2Impl<CommonProperties>::SetObjects(objects, ppControls); LoadSettings(); return S_OK; } // implementation of IPropertyPage ////////////////////////////////////////////////////////////////////// LRESULT CommonProperties::OnListViewGetInfoTipNotification(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/) { if(pNotificationDetails->hwndFrom != controls.disabledEventsList) { return 0; } LPNMLVGETINFOTIP pDetails = reinterpret_cast<LPNMLVGETINFOTIP>(pNotificationDetails); LPTSTR pBuffer = new TCHAR[pDetails->cchTextMax + 1]; switch(pDetails->iItem) { case 0: ATLVERIFY(SUCCEEDED(StringCchCopy(pBuffer, pDetails->cchTextMax + 1, TEXT("MouseDown, MouseUp, MouseEnter, MouseHover, MouseLeave, MouseMove")))); break; case 1: ATLVERIFY(SUCCEEDED(StringCchCopy(pBuffer, pDetails->cchTextMax + 1, TEXT("Click, DblClick, MClick, MDblClick, RClick, RDblClick, XClick, XDblClick")))); break; case 2: ATLVERIFY(SUCCEEDED(StringCchCopy(pBuffer, pDetails->cchTextMax + 1, TEXT("KeyDown, KeyUp, KeyPress")))); break; case 3: ATLVERIFY(SUCCEEDED(StringCchCopy(pBuffer, pDetails->cchTextMax + 1, TEXT("CustomDraw")))); break; case 4: ATLVERIFY(SUCCEEDED(StringCchCopy(pBuffer, pDetails->cchTextMax + 1, TEXT("CustomDropDownAreaSize")))); break; } ATLVERIFY(SUCCEEDED(StringCchCopy(pDetails->pszText, pDetails->cchTextMax, pBuffer))); delete[] pBuffer; return 0; } LRESULT CommonProperties::OnListViewItemChangedNotification(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/) { LPNMLISTVIEW pDetails = reinterpret_cast<LPNMLISTVIEW>(pNotificationDetails); if(pDetails->uChanged & LVIF_STATE) { if((pDetails->uNewState & LVIS_STATEIMAGEMASK) != (pDetails->uOldState & LVIS_STATEIMAGEMASK)) { if((pDetails->uNewState & LVIS_STATEIMAGEMASK) >> 12 == 3) { if(pNotificationDetails->hwndFrom != properties.hWndCheckMarksAreSetFor) { LVITEM item = {0}; item.state = INDEXTOSTATEIMAGEMASK(1); item.stateMask = LVIS_STATEIMAGEMASK; ::SendMessage(pNotificationDetails->hwndFrom, LVM_SETITEMSTATE, pDetails->iItem, reinterpret_cast<LPARAM>(&item)); } } SetDirty(TRUE); } } return 0; } LRESULT CommonProperties::OnToolTipGetDispInfoNotificationA(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/) { LPNMTTDISPINFOA pDetails = reinterpret_cast<LPNMTTDISPINFOA>(pNotificationDetails); pDetails->hinst = ModuleHelper::GetResourceInstance(); switch(pDetails->hdr.idFrom) { case ID_LOADSETTINGS: pDetails->lpszText = MAKEINTRESOURCEA(IDS_LOADSETTINGS); break; case ID_SAVESETTINGS: pDetails->lpszText = MAKEINTRESOURCEA(IDS_SAVESETTINGS); break; } return 0; } LRESULT CommonProperties::OnToolTipGetDispInfoNotificationW(int /*controlID*/, LPNMHDR pNotificationDetails, BOOL& /*wasHandled*/) { LPNMTTDISPINFOW pDetails = reinterpret_cast<LPNMTTDISPINFOW>(pNotificationDetails); pDetails->hinst = ModuleHelper::GetResourceInstance(); switch(pDetails->hdr.idFrom) { case ID_LOADSETTINGS: pDetails->lpszText = MAKEINTRESOURCEW(IDS_LOADSETTINGS); break; case ID_SAVESETTINGS: pDetails->lpszText = MAKEINTRESOURCEW(IDS_SAVESETTINGS); break; } return 0; } LRESULT CommonProperties::OnUseImprovedImageListSupport(WORD /*notifyCode*/, WORD /*controlID*/, HWND /*hWnd*/, BOOL& /*wasHandled*/) { if(properties.hWndCheckMarksAreSetFor != controls.useImprovedImgLstSupportCheck) { if(controls.useImprovedImgLstSupportCheck.GetCheck() == BST_INDETERMINATE) { controls.useImprovedImgLstSupportCheck.SetCheck(BST_UNCHECKED); } } BOOL checked = (controls.useImprovedImgLstSupportCheck.GetCheck() != BST_UNCHECKED); controls.iconIndexesCombo.EnableWindow(checked); controls.iconIndexEdit.EnableWindow(checked); controls.setIconIndexButton.EnableWindow(FALSE); SetDirty(TRUE); return 0; } LRESULT CommonProperties::OnSetIconIndex(WORD /*notifyCode*/, WORD /*controlID*/, HWND /*hWnd*/, BOOL& /*wasHandled*/) { TCHAR pBuffer[5]; controls.iconIndexEdit.GetWindowText(pBuffer, 5); LONG iconIndex; ConvertStringToInteger(pBuffer, iconIndex); LONG itemIndex = controls.iconIndexesCombo.GetCurSel(); if(itemIndex == 0) { for(int i = 0; i < 6; i++) { properties.iconIndexes[i] = iconIndex; } } else { properties.iconIndexes[itemIndex - 1] = iconIndex; } controls.setIconIndexButton.EnableWindow(FALSE); SetDirty(TRUE); return 0; } LRESULT CommonProperties::OnLoadSettingsFromFile(WORD /*notifyCode*/, WORD /*controlID*/, HWND /*hWnd*/, BOOL& /*wasHandled*/) { ATLASSERT(m_nObjects == 1); IUnknown* pControl = NULL; if(m_ppUnk[0]->QueryInterface(IID_ICheckBox, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { CFileDialog dlg(TRUE, NULL, NULL, OFN_ENABLESIZING | OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST, TEXT("All files\0*.*\0\0"), *this); if(dlg.DoModal() == IDOK) { CComBSTR file = dlg.m_szFileName; VARIANT_BOOL b = VARIANT_FALSE; reinterpret_cast<ICheckBox*>(pControl)->LoadSettingsFromFile(file, &b); if(b == VARIANT_FALSE) { MessageBox(TEXT("The specified file could not be loaded."), TEXT("Error!"), MB_ICONERROR | MB_OK); } } pControl->Release(); } else if(m_ppUnk[0]->QueryInterface(IID_ICommandButton, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { CFileDialog dlg(TRUE, NULL, NULL, OFN_ENABLESIZING | OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST, TEXT("All files\0*.*\0\0"), *this); if(dlg.DoModal() == IDOK) { CComBSTR file = dlg.m_szFileName; VARIANT_BOOL b = VARIANT_FALSE; reinterpret_cast<ICommandButton*>(pControl)->LoadSettingsFromFile(file, &b); if(b == VARIANT_FALSE) { MessageBox(TEXT("The specified file could not be loaded."), TEXT("Error!"), MB_ICONERROR | MB_OK); } } pControl->Release(); } else if(m_ppUnk[0]->QueryInterface(IID_IFrame, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { CFileDialog dlg(TRUE, NULL, NULL, OFN_ENABLESIZING | OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST, TEXT("All files\0*.*\0\0"), *this); if(dlg.DoModal() == IDOK) { CComBSTR file = dlg.m_szFileName; VARIANT_BOOL b = VARIANT_FALSE; reinterpret_cast<IFrame*>(pControl)->LoadSettingsFromFile(file, &b); if(b == VARIANT_FALSE) { MessageBox(TEXT("The specified file could not be loaded."), TEXT("Error!"), MB_ICONERROR | MB_OK); } } pControl->Release(); } else if(m_ppUnk[0]->QueryInterface(IID_IOptionButton, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { CFileDialog dlg(TRUE, NULL, NULL, OFN_ENABLESIZING | OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST, TEXT("All files\0*.*\0\0"), *this); if(dlg.DoModal() == IDOK) { CComBSTR file = dlg.m_szFileName; VARIANT_BOOL b = VARIANT_FALSE; reinterpret_cast<IOptionButton*>(pControl)->LoadSettingsFromFile(file, &b); if(b == VARIANT_FALSE) { MessageBox(TEXT("The specified file could not be loaded."), TEXT("Error!"), MB_ICONERROR | MB_OK); } } pControl->Release(); } return 0; } LRESULT CommonProperties::OnSaveSettingsToFile(WORD /*notifyCode*/, WORD /*controlID*/, HWND /*hWnd*/, BOOL& /*wasHandled*/) { ATLASSERT(m_nObjects == 1); IUnknown* pControl = NULL; if(m_ppUnk[0]->QueryInterface(IID_ICheckBox, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { CFileDialog dlg(FALSE, NULL, TEXT("CheckBox Settings.dat"), OFN_ENABLESIZING | OFN_EXPLORER | OFN_CREATEPROMPT | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT, TEXT("All files\0*.*\0\0"), *this); if(dlg.DoModal() == IDOK) { CComBSTR file = dlg.m_szFileName; VARIANT_BOOL b = VARIANT_FALSE; reinterpret_cast<ICheckBox*>(pControl)->SaveSettingsToFile(file, &b); if(b == VARIANT_FALSE) { MessageBox(TEXT("The specified file could not be written."), TEXT("Error!"), MB_ICONERROR | MB_OK); } } pControl->Release(); } else if(m_ppUnk[0]->QueryInterface(IID_ICommandButton, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { CFileDialog dlg(FALSE, NULL, TEXT("CommandButton Settings.dat"), OFN_ENABLESIZING | OFN_EXPLORER | OFN_CREATEPROMPT | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT, TEXT("All files\0*.*\0\0"), *this); if(dlg.DoModal() == IDOK) { CComBSTR file = dlg.m_szFileName; VARIANT_BOOL b = VARIANT_FALSE; reinterpret_cast<ICommandButton*>(pControl)->SaveSettingsToFile(file, &b); if(b == VARIANT_FALSE) { MessageBox(TEXT("The specified file could not be written."), TEXT("Error!"), MB_ICONERROR | MB_OK); } } pControl->Release(); } else if(m_ppUnk[0]->QueryInterface(IID_IFrame, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { CFileDialog dlg(FALSE, NULL, TEXT("Frame Settings.dat"), OFN_ENABLESIZING | OFN_EXPLORER | OFN_CREATEPROMPT | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT, TEXT("All files\0*.*\0\0"), *this); if(dlg.DoModal() == IDOK) { CComBSTR file = dlg.m_szFileName; VARIANT_BOOL b = VARIANT_FALSE; reinterpret_cast<IFrame*>(pControl)->SaveSettingsToFile(file, &b); if(b == VARIANT_FALSE) { MessageBox(TEXT("The specified file could not be written."), TEXT("Error!"), MB_ICONERROR | MB_OK); } } pControl->Release(); } else if(m_ppUnk[0]->QueryInterface(IID_IOptionButton, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { CFileDialog dlg(FALSE, NULL, TEXT("OptionButton Settings.dat"), OFN_ENABLESIZING | OFN_EXPLORER | OFN_CREATEPROMPT | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT, TEXT("All files\0*.*\0\0"), *this); if(dlg.DoModal() == IDOK) { CComBSTR file = dlg.m_szFileName; VARIANT_BOOL b = VARIANT_FALSE; reinterpret_cast<IOptionButton*>(pControl)->SaveSettingsToFile(file, &b); if(b == VARIANT_FALSE) { MessageBox(TEXT("The specified file could not be written."), TEXT("Error!"), MB_ICONERROR | MB_OK); } } pControl->Release(); } return 0; } LRESULT CommonProperties::OnIconIndexSelChange(WORD /*notifyCode*/, WORD /*controlID*/, HWND /*hWnd*/, BOOL& /*wasHandled*/) { LONG itemIndex = controls.iconIndexesCombo.GetCurSel(); if(itemIndex == 0) { controls.iconIndexEdit.SetWindowText(_T("")); } else { CAtlString s; s.Format(_T("%i"), properties.iconIndexes[itemIndex - 1]); controls.iconIndexEdit.SetWindowText(s); } controls.setIconIndexButton.EnableWindow(FALSE); return 0; } LRESULT CommonProperties::OnIconIndexChange(WORD /*notifyCode*/, WORD /*controlID*/, HWND /*hWnd*/, BOOL& /*wasHandled*/) { controls.setIconIndexButton.EnableWindow(controls.iconIndexEdit.GetWindowTextLength() > 0); return 0; } void CommonProperties::ApplySettings(void) { for(UINT object = 0; object < m_nObjects; ++object) { LPUNKNOWN pControl = NULL; if(m_ppUnk[object]->QueryInterface(IID_ICheckBox, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { DisabledEventsConstants disabledEvents = static_cast<DisabledEventsConstants>(0); reinterpret_cast<ICheckBox*>(pControl)->get_DisabledEvents(&disabledEvents); LONG l = static_cast<LONG>(disabledEvents); SetBit(controls.disabledEventsList.GetItemState(0, LVIS_STATEIMAGEMASK), l, deMouseEvents); SetBit(controls.disabledEventsList.GetItemState(1, LVIS_STATEIMAGEMASK), l, deClickEvents); SetBit(controls.disabledEventsList.GetItemState(2, LVIS_STATEIMAGEMASK), l, deKeyboardEvents); SetBit(controls.disabledEventsList.GetItemState(3, LVIS_STATEIMAGEMASK), l, deCustomDraw); reinterpret_cast<ICheckBox*>(pControl)->put_DisabledEvents(static_cast<DisabledEventsConstants>(l)); int checkState = controls.useImprovedImgLstSupportCheck.GetCheck(); if(checkState != BST_INDETERMINATE) { reinterpret_cast<ICheckBox*>(pControl)->put_UseImprovedImageListSupport(BOOL2VARIANTBOOL(checkState & BST_CHECKED)); } for(LONG i = 0; i < 6; i++) { reinterpret_cast<ICheckBox*>(pControl)->put_IconIndex(i, properties.iconIndexes[i]); } pControl->Release(); } else if(m_ppUnk[object]->QueryInterface(IID_ICommandButton, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { DisabledEventsConstants disabledEvents = static_cast<DisabledEventsConstants>(0); reinterpret_cast<ICommandButton*>(pControl)->get_DisabledEvents(&disabledEvents); LONG l = static_cast<LONG>(disabledEvents); SetBit(controls.disabledEventsList.GetItemState(0, LVIS_STATEIMAGEMASK), l, deMouseEvents); SetBit(controls.disabledEventsList.GetItemState(1, LVIS_STATEIMAGEMASK), l, deClickEvents); SetBit(controls.disabledEventsList.GetItemState(2, LVIS_STATEIMAGEMASK), l, deKeyboardEvents); SetBit(controls.disabledEventsList.GetItemState(3, LVIS_STATEIMAGEMASK), l, deCustomDraw); SetBit(controls.disabledEventsList.GetItemState(4, LVIS_STATEIMAGEMASK), l, deCustomDropDownAreaSize); reinterpret_cast<ICommandButton*>(pControl)->put_DisabledEvents(static_cast<DisabledEventsConstants>(l)); int checkState = controls.useImprovedImgLstSupportCheck.GetCheck(); if(checkState != BST_INDETERMINATE) { reinterpret_cast<ICommandButton*>(pControl)->put_UseImprovedImageListSupport(BOOL2VARIANTBOOL(checkState & BST_CHECKED)); } for(LONG i = 0; i < 6; i++) { reinterpret_cast<ICommandButton*>(pControl)->put_IconIndex(i, properties.iconIndexes[i]); } pControl->Release(); } else if(m_ppUnk[object]->QueryInterface(IID_IFrame, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { DisabledEventsConstants disabledEvents = static_cast<DisabledEventsConstants>(0); reinterpret_cast<IFrame*>(pControl)->get_DisabledEvents(&disabledEvents); LONG l = static_cast<LONG>(disabledEvents); SetBit(controls.disabledEventsList.GetItemState(0, LVIS_STATEIMAGEMASK), l, deMouseEvents); SetBit(controls.disabledEventsList.GetItemState(1, LVIS_STATEIMAGEMASK), l, deClickEvents); reinterpret_cast<IFrame*>(pControl)->put_DisabledEvents(static_cast<DisabledEventsConstants>(l)); int checkState = controls.useImprovedImgLstSupportCheck.GetCheck(); if(checkState != BST_INDETERMINATE) { reinterpret_cast<IFrame*>(pControl)->put_UseImprovedImageListSupport(BOOL2VARIANTBOOL(checkState & BST_CHECKED)); } for(LONG i = 0; i < 6; i++) { reinterpret_cast<IFrame*>(pControl)->put_IconIndex(i, properties.iconIndexes[i]); } pControl->Release(); } else if(m_ppUnk[object]->QueryInterface(IID_IOptionButton, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { DisabledEventsConstants disabledEvents = static_cast<DisabledEventsConstants>(0); reinterpret_cast<IOptionButton*>(pControl)->get_DisabledEvents(&disabledEvents); LONG l = static_cast<LONG>(disabledEvents); SetBit(controls.disabledEventsList.GetItemState(0, LVIS_STATEIMAGEMASK), l, deMouseEvents); SetBit(controls.disabledEventsList.GetItemState(1, LVIS_STATEIMAGEMASK), l, deClickEvents); SetBit(controls.disabledEventsList.GetItemState(2, LVIS_STATEIMAGEMASK), l, deKeyboardEvents); SetBit(controls.disabledEventsList.GetItemState(3, LVIS_STATEIMAGEMASK), l, deCustomDraw); reinterpret_cast<IOptionButton*>(pControl)->put_DisabledEvents(static_cast<DisabledEventsConstants>(l)); int checkState = controls.useImprovedImgLstSupportCheck.GetCheck(); if(checkState != BST_INDETERMINATE) { reinterpret_cast<IOptionButton*>(pControl)->put_UseImprovedImageListSupport(BOOL2VARIANTBOOL(checkState & BST_CHECKED)); } for(LONG i = 0; i < 6; i++) { reinterpret_cast<IOptionButton*>(pControl)->put_IconIndex(i, properties.iconIndexes[i]); } pControl->Release(); } } SetDirty(FALSE); } void CommonProperties::LoadSettings(void) { if(!controls.toolbar.IsWindow()) { // this will happen in Visual Studio's dialog editor if settings are loaded from a file return; } controls.toolbar.EnableButton(ID_LOADSETTINGS, (m_nObjects == 1)); controls.toolbar.EnableButton(ID_SAVESETTINGS, (m_nObjects == 1)); // get the settings int numberOfCheckBoxes = 0; int numberOfCommandButtons = 0; int numberOfFrames = 0; int numberOfOptionButtons = 0; DisabledEventsConstants* pDisabledEvents = static_cast<DisabledEventsConstants*>(HeapAlloc(GetProcessHeap(), 0, m_nObjects * sizeof(DisabledEventsConstants))); if(pDisabledEvents) { ZeroMemory(pDisabledEvents, m_nObjects * sizeof(DisabledEventsConstants)); VARIANT_BOOL* pUseImprovedImageListSupport = static_cast<VARIANT_BOOL*>(HeapAlloc(GetProcessHeap(), 0, m_nObjects * sizeof(VARIANT_BOOL))); if(pUseImprovedImageListSupport) { ZeroMemory(pUseImprovedImageListSupport, m_nObjects * sizeof(VARIANT_BOOL)); ZeroMemory(properties.iconIndexes, 6 * sizeof(LONG)); for(UINT object = 0; object < m_nObjects; ++object) { LPUNKNOWN pControl = NULL; if(m_ppUnk[object]->QueryInterface(IID_ICheckBox, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { ++numberOfCheckBoxes; reinterpret_cast<ICheckBox*>(pControl)->get_DisabledEvents(&pDisabledEvents[object]); if(object == 0) { for(LONG i = 0; i < 6; i++) { reinterpret_cast<ICheckBox*>(pControl)->get_IconIndex(i, &properties.iconIndexes[i]); } } reinterpret_cast<ICheckBox*>(pControl)->get_UseImprovedImageListSupport(&pUseImprovedImageListSupport[object]); pControl->Release(); } else if(m_ppUnk[object]->QueryInterface(IID_ICommandButton, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { ++numberOfCommandButtons; reinterpret_cast<ICommandButton*>(pControl)->get_DisabledEvents(&pDisabledEvents[object]); if(object == 0) { for(LONG i = 0; i < 6; i++) { reinterpret_cast<ICommandButton*>(pControl)->get_IconIndex(i, &properties.iconIndexes[i]); } } reinterpret_cast<ICommandButton*>(pControl)->get_UseImprovedImageListSupport(&pUseImprovedImageListSupport[object]); pControl->Release(); } else if(m_ppUnk[object]->QueryInterface(IID_IFrame, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { ++numberOfFrames; reinterpret_cast<IFrame*>(pControl)->get_DisabledEvents(&pDisabledEvents[object]); if(object == 0) { for(LONG i = 0; i < 6; i++) { reinterpret_cast<IFrame*>(pControl)->get_IconIndex(i, &properties.iconIndexes[i]); } } reinterpret_cast<IFrame*>(pControl)->get_UseImprovedImageListSupport(&pUseImprovedImageListSupport[object]); pControl->Release(); } else if(m_ppUnk[object]->QueryInterface(IID_IOptionButton, reinterpret_cast<LPVOID*>(&pControl)) == S_OK) { ++numberOfOptionButtons; reinterpret_cast<IOptionButton*>(pControl)->get_DisabledEvents(&pDisabledEvents[object]); if(object == 0) { for(LONG i = 0; i < 6; i++) { reinterpret_cast<IOptionButton*>(pControl)->get_IconIndex(i, &properties.iconIndexes[i]); } } reinterpret_cast<IOptionButton*>(pControl)->get_UseImprovedImageListSupport(&pUseImprovedImageListSupport[object]); pControl->Release(); } } // fill the controls LONG* pl = reinterpret_cast<LONG*>(pDisabledEvents); properties.hWndCheckMarksAreSetFor = controls.disabledEventsList; controls.disabledEventsList.DeleteAllItems(); controls.disabledEventsList.AddItem(0, 0, TEXT("Mouse events")); controls.disabledEventsList.SetItemState(0, CalculateStateImageMask(m_nObjects, pl, deMouseEvents), LVIS_STATEIMAGEMASK); controls.disabledEventsList.AddItem(1, 0, TEXT("Click events")); controls.disabledEventsList.SetItemState(1, CalculateStateImageMask(m_nObjects, pl, deClickEvents), LVIS_STATEIMAGEMASK); if((numberOfCheckBoxes > 0) || (numberOfCommandButtons > 0) || (numberOfOptionButtons > 0)) { controls.disabledEventsList.AddItem(2, 0, TEXT("Keyboard events")); controls.disabledEventsList.SetItemState(2, CalculateStateImageMask(m_nObjects, pl, deKeyboardEvents), LVIS_STATEIMAGEMASK); controls.disabledEventsList.AddItem(3, 0, TEXT("CustomDraw event")); controls.disabledEventsList.SetItemState(3, CalculateStateImageMask(m_nObjects, pl, deCustomDraw), LVIS_STATEIMAGEMASK); if(numberOfCommandButtons > 0) { controls.disabledEventsList.AddItem(4, 0, TEXT("CustomDropDownAreaSize event")); controls.disabledEventsList.SetItemState(4, CalculateStateImageMask(m_nObjects, pl, deCustomDropDownAreaSize), LVIS_STATEIMAGEMASK); } } controls.disabledEventsList.SetColumnWidth(0, LVSCW_AUTOSIZE); properties.hWndCheckMarksAreSetFor = controls.useImprovedImgLstSupportCheck; int checkState = BST_UNCHECKED; for(UINT object = 0; object < m_nObjects; ++object) { if(pUseImprovedImageListSupport[object] != VARIANT_FALSE) { if(checkState == BST_UNCHECKED) { checkState = (object == 0 ? BST_CHECKED : BST_INDETERMINATE); } } else { if(checkState == BST_CHECKED) { checkState = (object == 0 ? BST_UNCHECKED : BST_INDETERMINATE); } } } controls.useImprovedImgLstSupportCheck.SetCheck(checkState); BOOL dummy; OnUseImprovedImageListSupport(BN_CLICKED, IDC_USEIMPROVEDIMGLSTSUPPORTCHECK, controls.useImprovedImgLstSupportCheck, dummy); properties.hWndCheckMarksAreSetFor = NULL; controls.iconIndexesCombo.ResetContent(); controls.iconIndexesCombo.AddString(_T("(All States)")); controls.iconIndexesCombo.AddString(_T("Normal State")); controls.iconIndexesCombo.AddString(_T("Hovered (\"Hot\") State")); controls.iconIndexesCombo.AddString(_T("Pressed State")); controls.iconIndexesCombo.AddString(_T("Disabled State")); controls.iconIndexesCombo.AddString(_T("Default Button")); controls.iconIndexesCombo.AddString(_T("Stylus Hot State (Tablet PC)")); controls.iconIndexesCombo.SetCurSel(0); controls.iconIndexEdit.SetWindowText(_T("")); controls.iconIndexEdit.SetModify(FALSE); HeapFree(GetProcessHeap(), 0, pUseImprovedImageListSupport); } HeapFree(GetProcessHeap(), 0, pDisabledEvents); } SetDirty(FALSE); } int CommonProperties::CalculateStateImageMask(UINT arraysize, LONG* pArray, LONG bitsToCheckFor) { int stateImageIndex = 1; for(UINT object = 0; object < arraysize; ++object) { if(pArray[object] & bitsToCheckFor) { if(stateImageIndex == 1) { stateImageIndex = (object == 0 ? 2 : 3); } } else { if(stateImageIndex == 2) { stateImageIndex = (object == 0 ? 1 : 3); } } } return INDEXTOSTATEIMAGEMASK(stateImageIndex); } void CommonProperties::SetBit(int stateImageMask, LONG& value, LONG bitToSet) { stateImageMask >>= 12; switch(stateImageMask) { case 1: value &= ~bitToSet; break; case 2: value |= bitToSet; break; } }
43.628866
231
0.745432
TimoKunze
29c6e3aba66fab1049dfff02a5e850768e564549
4,924
cpp
C++
Spark/effects/BloomPass.cpp
MickAlmighty/SparkRenderer
0e30e342c7cf4003da54e9ce191fead647a868eb
[ "MIT" ]
1
2022-02-15T19:50:01.000Z
2022-02-15T19:50:01.000Z
Spark/effects/BloomPass.cpp
MickAlmighty/SparkRenderer
0e30e342c7cf4003da54e9ce191fead647a868eb
[ "MIT" ]
null
null
null
Spark/effects/BloomPass.cpp
MickAlmighty/SparkRenderer
0e30e342c7cf4003da54e9ce191fead647a868eb
[ "MIT" ]
null
null
null
#include "BloomPass.hpp" #include "CommonUtils.h" #include "Shader.h" #include "Spark.h" namespace spark::effects { BloomPass::BloomPass(unsigned int width, unsigned int height) : w(width), h(height) { bloomDownScaleShaderMip0ToMip1 = Spark::get().getResourceLibrary().getResourceByName<resources::Shader>("bloomDownScaleMip0ToMip1.glsl"); bloomDownScaleShader = Spark::get().getResourceLibrary().getResourceByName<resources::Shader>("bloomDownScale.glsl"); bloomUpsamplerShader = Spark::get().getResourceLibrary().getResourceByName<resources::Shader>("bloomUpsampler.glsl"); createFrameBuffersAndTextures(); } BloomPass::~BloomPass() { GLuint textures[5] = {textureMip1, textureMip2, textureMip3, textureMip4, textureMip5}; glDeleteTextures(5, textures); GLuint framebuffers[6] = {fboMip1, fboMip2, fboMip3, fboMip4, fboMip5, fboMip0}; glDeleteFramebuffers(6, framebuffers); } GLuint BloomPass::process(GLuint lightingTexture, GLuint brightPassTexture) { PUSH_DEBUG_GROUP(BLOOM) downsampleFromMip0ToMip1(brightPassTexture); PUSH_DEBUG_GROUP(DOWNSAMPLE_FROM_MIP_1_TO_MIP_5) downsampleTexture(fboMip2, textureMip1, w / 4, h / 4); downsampleTexture(fboMip3, textureMip2, w / 8, h / 8); downsampleTexture(fboMip4, textureMip3, w / 16, h / 16); downsampleTexture(fboMip5, textureMip4, w / 32, h / 32); POP_DEBUG_GROUP(); PUSH_DEBUG_GROUP(UPSAMPLE) glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_ADD); glEnable(GL_BLEND); upsampleTexture(fboMip4, textureMip5, w / 16, h / 16, radiusMip4); upsampleTexture(fboMip3, textureMip4, w / 8, h / 8, radiusMip3); upsampleTexture(fboMip2, textureMip3, w / 4, h / 4, radiusMip2); upsampleTexture(fboMip1, textureMip2, w / 2, h / 2, radiusMip1); utils::bindTexture2D(fboMip0, lightingTexture); upsampleTexture(fboMip0, textureMip1, w, h, radiusMip0, intensity); glDisable(GL_BLEND); glViewport(0, 0, w, h); POP_DEBUG_GROUP(); POP_DEBUG_GROUP(); return lightingTexture; } void BloomPass::resize(unsigned int width, unsigned int height) { w = width; h = height; createFrameBuffersAndTextures(); } void BloomPass::downsampleFromMip0ToMip1(GLuint brightPassTexture) { PUSH_DEBUG_GROUP(DOWNSAMPLE_MIP_0_TO_MIP_1) glViewport(0, 0, w / 2, h / 2); glBindFramebuffer(GL_FRAMEBUFFER, fboMip1); bloomDownScaleShaderMip0ToMip1->use(); bloomDownScaleShaderMip0ToMip1->setVec2("outputTextureSizeInversion", glm::vec2(1.0f / (w / 2.0f), 1.0f / (w / 2.0f))); bloomDownScaleShaderMip0ToMip1->setFloat("threshold", threshold); bloomDownScaleShaderMip0ToMip1->setFloat("thresholdSize", thresholdSize); glBindTextureUnit(0, brightPassTexture); screenQuad.draw(); POP_DEBUG_GROUP() } void BloomPass::downsampleTexture(GLuint framebuffer, GLuint texture, GLuint viewportWidth, GLuint viewportHeight) { glViewport(0, 0, viewportWidth, viewportHeight); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); bloomDownScaleShader->use(); const auto lowerMipTextureSize = glm::vec2(1.0f / (viewportWidth / 2.0f), 1.0f / (viewportWidth / 2.0f)); bloomDownScaleShader->setVec2("outputTextureSizeInversion", lowerMipTextureSize); glBindTextureUnit(0, texture); screenQuad.draw(); } void BloomPass::upsampleTexture(GLuint framebuffer, GLuint texture, GLuint viewportWidth, GLuint viewportHeight, float radius, float bloomIntensity) { glViewport(0, 0, viewportWidth, viewportHeight); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); bloomUpsamplerShader->use(); bloomUpsamplerShader->setFloat("intensity", bloomIntensity); bloomUpsamplerShader->setFloat("radius", radius); bloomUpsamplerShader->setVec2("outputTextureSizeInversion", glm::vec2(1.0f / viewportWidth, 1.0f / viewportWidth)); glBindTextureUnit(0, texture); screenQuad.draw(); }; void BloomPass::createFrameBuffersAndTextures() { utils::recreateTexture2D(textureMip1, w / 2, h / 2, GL_R11F_G11F_B10F, GL_RGB, GL_FLOAT, GL_CLAMP_TO_EDGE, GL_LINEAR); utils::recreateTexture2D(textureMip2, w / 4, h / 4, GL_R11F_G11F_B10F, GL_RGB, GL_FLOAT, GL_CLAMP_TO_EDGE, GL_LINEAR); utils::recreateTexture2D(textureMip3, w / 8, h / 8, GL_R11F_G11F_B10F, GL_RGB, GL_FLOAT, GL_CLAMP_TO_EDGE, GL_LINEAR); utils::recreateTexture2D(textureMip4, w / 16, h / 16, GL_R11F_G11F_B10F, GL_RGB, GL_FLOAT, GL_CLAMP_TO_EDGE, GL_LINEAR); utils::recreateTexture2D(textureMip5, w / 32, h / 32, GL_R11F_G11F_B10F, GL_RGB, GL_FLOAT, GL_CLAMP_TO_EDGE, GL_LINEAR); utils::recreateFramebuffer(fboMip1, {textureMip1}); utils::recreateFramebuffer(fboMip2, {textureMip2}); utils::recreateFramebuffer(fboMip3, {textureMip3}); utils::recreateFramebuffer(fboMip4, {textureMip4}); utils::recreateFramebuffer(fboMip5, {textureMip5}); utils::recreateFramebuffer(fboMip0, {}); } } // namespace spark::effects
40.694215
148
0.743501
MickAlmighty
29c6e6c2a85399516d56ce80b65d1d71edabdea6
623
cpp
C++
InterviewBit/DP/lls.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
6
2019-10-06T17:39:42.000Z
2022-03-03T10:57:52.000Z
InterviewBit/DP/lls.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
null
null
null
InterviewBit/DP/lls.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
2
2019-10-06T11:09:01.000Z
2019-10-06T17:40:46.000Z
int Solution::longestSubsequenceLength(const vector<int> &A) { if(A.size()==0) return 0; vector<int> incr(A.size(),1); vector<int> decr(A.size(),1); for(int i=0;i<incr.size();i++){ for(int j=0;j<i;j++){ if(A[i]>A[j]) incr[i]=max(incr[i],incr[j]+1); } } for(int i=A.size()-2;i>=0;i--){ for(int j=A.size()-1;j>i;j--){ if(A[i]>A[j]) decr[i] = max(decr[j]+1,decr[i]); } } int ans = INT_MIN; for(int i=0;i<A.size();i++){ ans = max(ans,incr[i]+decr[i]-1); } return ans; }
24.92
62
0.434992
Cobnagi
29cb16ddc22d8dc7c457fb0f0b10ae20d384446c
8,163
hpp
C++
external/range-v3/include/range/v3/view/cycle.hpp
VladPodilnyk/kmeans-cpp
bb8843698a034752fe612fa872403a76a34ab82e
[ "MIT" ]
null
null
null
external/range-v3/include/range/v3/view/cycle.hpp
VladPodilnyk/kmeans-cpp
bb8843698a034752fe612fa872403a76a34ab82e
[ "MIT" ]
null
null
null
external/range-v3/include/range/v3/view/cycle.hpp
VladPodilnyk/kmeans-cpp
bb8843698a034752fe612fa872403a76a34ab82e
[ "MIT" ]
null
null
null
/// \file cycle.hpp // Range v3 library // // Copyright Eric Niebler 2013-present // Copyright Gonzalo Brito Gadeschi 2015 // Copyright Casey Carter 2015 // // 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) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_VIEW_CYCLE_HPP #define RANGES_V3_VIEW_CYCLE_HPP #include <utility> #include <type_traits> #include <meta/meta.hpp> #include <range/v3/detail/satisfy_boost_range.hpp> #include <range/v3/range_fwd.hpp> #include <range/v3/size.hpp> #include <range/v3/begin_end.hpp> #include <range/v3/empty.hpp> #include <range/v3/range_traits.hpp> #include <range/v3/range_concepts.hpp> #include <range/v3/view_facade.hpp> #include <range/v3/view/all.hpp> #include <range/v3/view/view.hpp> #include <range/v3/utility/box.hpp> #include <range/v3/utility/get.hpp> #include <range/v3/utility/iterator.hpp> #include <range/v3/utility/optional.hpp> #include <range/v3/utility/static_const.hpp> namespace ranges { inline namespace v3 { /// \addtogroup group-views ///@{ template<typename Rng, bool /* = (bool) is_infinite<Rng>() */> struct RANGES_EMPTY_BASES cycled_view : view_facade<cycled_view<Rng>, infinite> , private detail::non_propagating_cache< iterator_t<Rng>, cycled_view<Rng>, !BoundedRange<Rng>()> { private: CONCEPT_ASSERT(ForwardRange<Rng>() && !is_infinite<Rng>::value); friend range_access; Rng rng_; using cache_t = detail::non_propagating_cache< iterator_t<Rng>, cycled_view<Rng>, !BoundedRange<Rng>()>; template<bool IsConst> struct cursor { private: friend struct cursor<!IsConst>; template<typename T> using constify_if = meta::const_if_c<IsConst, T>; using cycled_view_t = constify_if<cycled_view>; using CRng = constify_if<Rng>; using iterator = iterator_t<CRng>; cycled_view_t *rng_{}; iterator it_{}; std::intmax_t n_ = 0; iterator get_end_(std::true_type, bool = false) const { return ranges::end(rng_->rng_); } template<bool CanBeEmpty = false> iterator get_end_(std::false_type, meta::bool_<CanBeEmpty> = {}) const { auto &end_ = static_cast<cache_t &>(*rng_); RANGES_EXPECT(CanBeEmpty || end_); if(CanBeEmpty && !end_) end_ = ranges::next(it_, ranges::end(rng_->rng_)); return *end_; } void set_end_(std::true_type) const {} void set_end_(std::false_type) const { auto &end_ = static_cast<cache_t &>(*rng_); if(!end_) end_ = it_; } public: cursor() = default; cursor(cycled_view_t &rng) : rng_(&rng), it_(ranges::begin(rng.rng_)) {} template<bool Other, CONCEPT_REQUIRES_(IsConst && !Other)> cursor(cursor<Other> that) : rng_(that.rng_) , it_(std::move(that.it_)) {} constexpr bool equal(default_sentinel) const { return false; } auto read() const RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT ( *it_ ) bool equal(cursor const &pos) const { RANGES_EXPECT(rng_ == pos.rng_); return n_ == pos.n_ && it_ == pos.it_; } void next() { auto const end = ranges::end(rng_->rng_); RANGES_EXPECT(it_ != end); if(++it_ == end) { ++n_; this->set_end_(BoundedRange<CRng>()); it_ = ranges::begin(rng_->rng_); } } CONCEPT_REQUIRES(BidirectionalRange<CRng>()) void prev() { if(it_ == ranges::begin(rng_->rng_)) { RANGES_EXPECT(n_ > 0); // decrementing the begin iterator?! --n_; it_ = this->get_end_(BoundedRange<CRng>()); } --it_; } CONCEPT_REQUIRES(RandomAccessRange<CRng>()) void advance(std::intmax_t n) { auto const begin = ranges::begin(rng_->rng_); auto const end = this->get_end_(BoundedRange<CRng>(), meta::bool_<true>()); auto const dist = end - begin; auto const d = it_ - begin; auto const off = (d + n) % dist; n_ += (d + n) / dist; RANGES_EXPECT(n_ >= 0); using D = range_difference_type_t<Rng>; it_ = begin + static_cast<D>(off < 0 ? off + dist : off); } CONCEPT_REQUIRES(SizedSentinel<iterator, iterator>()) std::intmax_t distance_to(cursor const &that) const { RANGES_EXPECT(that.rng_ == rng_); auto const begin = ranges::begin(rng_->rng_); auto const end = this->get_end_(BoundedRange<Rng>(), meta::bool_<true>()); auto const dist = end - begin; return (that.n_ - n_) * dist + (that.it_ - it_); } }; CONCEPT_REQUIRES(!simple_view<Rng>() || !BoundedRange<Rng const>()) cursor<false> begin_cursor() { return {*this}; } CONCEPT_REQUIRES(BoundedRange<Rng const>()) cursor<true> begin_cursor() const { return {*this}; } public: cycled_view() = default; /// \pre <tt>!empty(rng)</tt> explicit cycled_view(Rng rng) : rng_(std::move(rng)) { RANGES_EXPECT(!ranges::empty(rng_)); } }; template<typename Rng> struct cycled_view<Rng, true> : identity_adaptor<Rng> { CONCEPT_ASSERT(is_infinite<Rng>()); using identity_adaptor<Rng>::identity_adaptor; }; namespace view { /// Returns an infinite range that endlessly repeats the source /// range. struct cycle_fn { /// \pre <tt>!empty(rng)</tt> template<typename Rng, CONCEPT_REQUIRES_(ForwardRange<Rng>())> cycled_view<all_t<Rng>> operator()(Rng &&rng) const { return cycled_view<all_t<Rng>>{all(static_cast<Rng &&>(rng))}; } #ifndef RANGES_DOXYGEN_INVOKED template<typename Rng, CONCEPT_REQUIRES_(!ForwardRange<Rng>())> void operator()(Rng &&) const { CONCEPT_ASSERT_MSG(ForwardRange<Rng>(), "The object on which view::cycle operates must model " "the ForwardRange concept."); } #endif }; /// \relates cycle_fn /// \ingroup group-views RANGES_INLINE_VARIABLE(view<cycle_fn>, cycle) } // namespace view /// @} } // namespace v3 } // namespace ranges RANGES_SATISFY_BOOST_RANGE(::ranges::v3::cycled_view) #endif
35.646288
95
0.487688
VladPodilnyk
29cc65444999159d8ed28c864083b15576185b07
5,855
cpp
C++
Linked List/Pointer Based Concepts/Remove Duplicates From A Sorted Singly LL.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
8
2021-02-13T17:07:27.000Z
2021-08-20T08:20:40.000Z
Linked List/Pointer Based Concepts/Remove Duplicates From A Sorted Singly LL.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
null
null
null
Linked List/Pointer Based Concepts/Remove Duplicates From A Sorted Singly LL.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
5
2021-02-17T18:12:20.000Z
2021-10-10T17:49:34.000Z
// Problem: https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list/ /****************************************************************************************************/ // Method 1 #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int INF = 0x3f3f3f3f; const int mod = 1e9+7; // Making a node class containing the value and a pointer // to next available node class ListNode { public: int val; ListNode *next; }; class LinkedList { public: // head and tail pointers ListNode *head, *tail; // default constructor. Initializing head and tail pointers LinkedList() { head = NULL; tail = NULL; } // inserting elements (at the end of the list) void insert(int data) { // make a new node ListNode *new_node = new ListNode; new_node->val = data; new_node->next = NULL; // If list is empty, make the new node, the head // initialise tail also as new node if(head == NULL) { head = new_node; tail = new_node; } else { tail->next = new_node; tail = tail->next; } } void display() { ListNode *tmp = head; while(tmp != NULL) { cout << tmp->val; tmp = tmp->next; if(tmp != NULL) cout << "->"; } cout << "\n"; } }; ListNode* remove_duplicates(ListNode *head) { if(head == NULL or head->next == NULL) { return head; } ListNode *prv = head, *cur = head->next; while(cur != NULL) { if(prv->val != cur->val) { prv->next = cur; prv = cur; } else prv->next = NULL; cur = cur->next; } return head; } void solve() { int n; cin >> n; LinkedList l; for(int i = 0; i < n; i++) { int x; cin >> x; l.insert(x); } l.display(); l.head = remove_duplicates(l.head); l.display(); } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; // int test = 1; // cin >> t; while(t--) { // cout << "Case #" << test++ << ": "; solve(); } return 0; } /******************************************************************************************************/ // Method 2 // Ref: https://www.youtube.com/watch?v=GkKTBh12CzA&list=PL7JyMDSI2BfbQZQIFfD7Hep2e6kzUZd7L&index=2 #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int INF = 0x3f3f3f3f; const int mod = 1e9+7; // Making a node class containing the value and a pointer // to next available node class ListNode { public: int val; ListNode *next; }; class LinkedList { public: // head and tail pointers ListNode *head, *tail; // default constructor. Initializing head and tail pointers LinkedList() { head = NULL; tail = NULL; } // inserting elements (at the end of the list) void insert(int data) { // make a new node ListNode *new_node = new ListNode; new_node->val = data; new_node->next = NULL; // If list is empty, make the new node, the head // initialise tail also as new node if(head == NULL) { head = new_node; tail = new_node; } else { tail->next = new_node; tail = tail->next; } } void display() { ListNode *tmp = head; while(tmp != NULL) { cout << tmp->val; tmp = tmp->next; if(tmp != NULL) cout << "->"; } cout << "\n"; } }; ListNode* remove_duplicates(ListNode *head) { if(head == NULL or head->next == NULL) { return head; } ListNode *tmp = head; while(tmp->next != NULL) { if(tmp->val == tmp->next->val) tmp->next = tmp->next->next; else tmp = tmp->next; } return head; } void solve() { int n; cin >> n; LinkedList l; for(int i = 0; i < n; i++) { int x; cin >> x; l.insert(x); } l.display(); l.head = remove_duplicates(l.head); l.display(); } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; // int test = 1; // cin >> t; while(t--) { // cout << "Case #" << test++ << ": "; solve(); } return 0; }
21.061151
104
0.580359
Edith-3000
29ce2f149b1a02816d24937485ccfdce7ff9fc8a
753
cpp
C++
src/simpledbus/common/Introspectable.cpp
jeremyephron/SimpleDBus
d352886b260beb1775348cc88b146e9362809b3e
[ "MIT" ]
5
2020-07-16T02:53:50.000Z
2021-09-08T22:25:15.000Z
src/simpledbus/common/Introspectable.cpp
jeremyephron/SimpleDBus
d352886b260beb1775348cc88b146e9362809b3e
[ "MIT" ]
5
2021-01-03T18:07:47.000Z
2021-02-04T06:37:42.000Z
src/simpledbus/common/Introspectable.cpp
kdewald/SimpleDBus
e8b25b93dce66d172e87ec3c088ed9f1f168bcba
[ "MIT" ]
3
2021-02-03T15:59:19.000Z
2021-08-31T01:52:05.000Z
#include "Introspectable.h" #include "../base/Message.h" #include "../base/Logger.h" #include <iostream> using namespace SimpleDBus; Introspectable::Introspectable(Connection* conn, std::string service, std::string path) : _conn(conn), _service(service), _path(path), _interface("org.freedesktop.DBus.Introspectable") {} Introspectable::~Introspectable() {} // Names are made matching the ones from the DBus specification Holder Introspectable::Introspect() { LOG_F(DEBUG, "%s -> Introspect()", _path.c_str()); Message query_msg = Message::create_method_call(_service, _path, _interface, "Introspect"); Message reply_msg = _conn->send_with_reply_and_block(query_msg); Holder result = reply_msg.extract(); return result; }
31.375
103
0.734396
jeremyephron
29cf0db7ca46e009c9c56dbd8d042faab324c3d2
19,447
cpp
C++
mlir/lib/Conversion/VectorToGPU/VectorToGPU.cpp
guitard0g/llvm-project
283e39c7a0d1bf97a67b77638e9194bd1eb9dae6
[ "Apache-2.0" ]
2
2021-11-20T04:04:47.000Z
2022-01-06T07:44:23.000Z
mlir/lib/Conversion/VectorToGPU/VectorToGPU.cpp
Sayyidalijufri/llvm-project
bf95957c99c77987404dea791d6087b222135fce
[ "Apache-2.0" ]
null
null
null
mlir/lib/Conversion/VectorToGPU/VectorToGPU.cpp
Sayyidalijufri/llvm-project
bf95957c99c77987404dea791d6087b222135fce
[ "Apache-2.0" ]
null
null
null
//===- VectorToGPU.cpp - Convert vector to GPU dialect ----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements lowering of vector operations to GPU dialect ops. // //===----------------------------------------------------------------------===// #include <type_traits> #include "mlir/Conversion/VectorToGPU/VectorToGPU.h" #include "../PassDetail.h" #include "mlir/Analysis/SliceAnalysis.h" #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" #include "mlir/Dialect/GPU/GPUDialect.h" #include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/Dialect/SCF/SCF.h" #include "mlir/Dialect/Utils/StructuredOpsUtils.h" #include "mlir/Dialect/Vector/VectorOps.h" #include "mlir/Dialect/Vector/VectorUtils.h" #include "mlir/IR/Builders.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "mlir/Transforms/Passes.h" using namespace mlir; // Return true if the contract op can be convert to MMA matmul. static bool contractSupportsMMAMatrixType(vector::ContractionOp contract) { if (llvm::size(contract.masks()) != 0) return false; using MapList = ArrayRef<ArrayRef<AffineExpr>>; auto infer = [](MapList m) { return AffineMap::inferFromExprList(m); }; AffineExpr m, n, k; bindDims(contract.getContext(), m, n, k); auto iteratorTypes = contract.iterator_types().getValue(); if (!(isParallelIterator(iteratorTypes[0]) && isParallelIterator(iteratorTypes[1]) && isReductionIterator(iteratorTypes[2]))) return false; // The contract needs to represent a matmul to be able to convert to // MMAMatrix matmul. if (contract.getIndexingMaps() != infer({{m, k}, {k, n}, {m, n}})) return false; // Check that the size matches what is natively supported. VectorType lhsType = contract.lhs().getType().cast<VectorType>(); VectorType rhsType = contract.rhs().getType().cast<VectorType>(); VectorType accType = contract.acc().getType().cast<VectorType>(); std::tuple<int, int, int> dim(lhsType.getDimSize(0), rhsType.getDimSize(1), lhsType.getDimSize(1)); if (lhsType.getElementType().isInteger(8) && rhsType.getElementType().isInteger(8) && accType.getElementType().isInteger(32) && (dim == std::make_tuple(8, 8, 32) || dim == std::make_tuple(16, 16, 32) || dim == std::make_tuple(16, 8, 32))) return true; if (lhsType.getElementType().isF16() && rhsType.getElementType().isF16() && (accType.getElementType().isF16() || accType.getElementType().isF32()) && (dim == std::make_tuple(8, 8, 16) || dim == std::make_tuple(16, 16, 16) || dim == std::make_tuple(16, 8, 16))) return true; return false; } // Return the stide for the dimension 0 of |type| if it is a memref and has a // constant stride. static llvm::Optional<int64_t> getMemrefConstantHorizontalStride(ShapedType type) { auto memrefType = type.dyn_cast<MemRefType>(); if (!memrefType) return false; int64_t offset = 0; SmallVector<int64_t, 2> strides; if (failed(getStridesAndOffset(memrefType, strides, offset))) return llvm::None; if (strides[0] == ShapedType::kDynamicStrideOrOffset) return llvm::None; return strides[0]; } // Return true if the transfer op can be converted to a MMA matrix load. static bool transferReadSupportsMMAMatrixType(vector::TransferReadOp readOp) { if (readOp.mask() || readOp.hasOutOfBoundsDim() || readOp.getVectorType().getRank() != 2) return false; if (!getMemrefConstantHorizontalStride(readOp.getShapedType())) return false; // TODO: Support transpose once it is added to GPU dialect ops. if (!readOp.permutation_map().isMinorIdentity()) return false; return true; } // Return true if the transfer op can be converted to a MMA matrix store. static bool transferWriteSupportsMMAMatrixType(vector::TransferWriteOp writeOp) { if (writeOp.mask() || writeOp.hasOutOfBoundsDim() || writeOp.getVectorType().getRank() != 2) return false; if (!getMemrefConstantHorizontalStride(writeOp.getShapedType())) return false; // TODO: Support transpose once it is added to GPU dialect ops. if (!writeOp.permutation_map().isMinorIdentity()) return false; return true; } /// Return true if the constant is a splat to a 2D vector so that it can be /// converted to a MMA constant matrix op. static bool constantSupportsMMAMatrixType(arith::ConstantOp constantOp) { auto vecType = constantOp.getType().dyn_cast<VectorType>(); if (!vecType || vecType.getRank() != 2) return false; return constantOp.value().isa<SplatElementsAttr>(); } /// Return true if this is a broadcast from scalar to a 2D vector. static bool broadcastSupportsMMAMatrixType(vector::BroadcastOp broadcastOp) { return broadcastOp.getVectorType().getRank() == 2 && broadcastOp.source().getType().isa<FloatType>(); } static bool supportsMMaMatrixType(Operation *op) { if (isa<scf::ForOp, scf::YieldOp>(op)) return true; if (auto transferRead = dyn_cast<vector::TransferReadOp>(op)) return transferReadSupportsMMAMatrixType(transferRead); if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(op)) return transferWriteSupportsMMAMatrixType(transferWrite); if (auto contract = dyn_cast<vector::ContractionOp>(op)) return contractSupportsMMAMatrixType(contract); if (auto constant = dyn_cast<arith::ConstantOp>(op)) return constantSupportsMMAMatrixType(constant); if (auto broadcast = dyn_cast<vector::BroadcastOp>(op)) return broadcastSupportsMMAMatrixType(broadcast); return false; } // Analyze slice of operations based on convert op to figure out if the whole // slice can be converted to MMA operations. static SetVector<Operation *> getOpToConvert(mlir::Operation *op) { auto hasVectorDest = [](Operation *op) { return llvm::any_of(op->getResultTypes(), [](Type t) { return t.isa<VectorType>(); }); }; auto hasVectorSrc = [](Operation *op) { return llvm::any_of(op->getOperandTypes(), [](Type t) { return t.isa<VectorType>(); }); }; SetVector<Operation *> opToConvert; op->walk([&](vector::ContractionOp contract) { if (opToConvert.contains(contract.getOperation())) return; SetVector<Operation *> dependentOps = getSlice(contract, hasVectorDest, hasVectorSrc); // If any instruction cannot use MMA matrix type drop the whole // chaine. MMA matrix are stored in an opaque type so they cannot be used // by all operations. if (llvm::any_of(dependentOps, [](Operation *op) { return !supportsMMaMatrixType(op); })) return; opToConvert.insert(dependentOps.begin(), dependentOps.end()); }); return opToConvert; } namespace { // Transform contract into (m, k)x(k, n)x(m, n) form so that it can be converted // to MMA matmul. struct PrepareContractToGPUMMA : public OpRewritePattern<vector::ContractionOp> { using OpRewritePattern<vector::ContractionOp>::OpRewritePattern; LogicalResult matchAndRewrite(vector::ContractionOp op, PatternRewriter &rewriter) const override { Location loc = op.getLoc(); Value lhs = op.lhs(), rhs = op.rhs(), res = op.acc(); // Set up the parallel/reduction structure in right form. using MapList = ArrayRef<ArrayRef<AffineExpr>>; auto infer = [](MapList m) { return AffineMap::inferFromExprList(m); }; AffineExpr m, n, k; bindDims(rewriter.getContext(), m, n, k); static constexpr std::array<int64_t, 2> perm = {1, 0}; auto iteratorTypes = op.iterator_types().getValue(); SmallVector<AffineMap, 4> maps = op.getIndexingMaps(); if (!(isParallelIterator(iteratorTypes[0]) && isParallelIterator(iteratorTypes[1]) && isReductionIterator(iteratorTypes[2]))) return failure(); // // Two outer parallel, one inner reduction (matmat flavor). // if (maps == infer({{m, k}, {k, n}, {m, n}})) { // This is the classical row-major matmul, nothing to do. return failure(); } if (maps == infer({{m, k}, {n, k}, {m, n}})) { rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm); } else if (maps == infer({{k, m}, {k, n}, {m, n}})) { lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm); } else if (maps == infer({{k, m}, {n, k}, {m, n}})) { rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm); lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm); } else if (maps == infer({{m, k}, {k, n}, {n, m}})) { std::swap(rhs, lhs); rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm); lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm); } else if (maps == infer({{m, k}, {n, k}, {n, m}})) { std::swap(rhs, lhs); rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm); } else if (maps == infer({{k, m}, {k, n}, {n, m}})) { std::swap(lhs, rhs); lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm); } else if (maps == infer({{k, m}, {n, k}, {n, m}})) { std::swap(lhs, rhs); } else { return failure(); } rewriter.replaceOpWithNewOp<vector::ContractionOp>( op, lhs, rhs, res, rewriter.getAffineMapArrayAttr(infer({{m, k}, {k, n}, {m, n}})), op.iterator_types()); return success(); } }; // Merge transpose op into the transfer read op. Transpose are not supported on // MMA types but MMA load can transpose the matrix when loading. struct CombineTransferReadOpTranspose final : public OpRewritePattern<vector::TransposeOp> { using OpRewritePattern<vector::TransposeOp>::OpRewritePattern; LogicalResult matchAndRewrite(vector::TransposeOp op, PatternRewriter &rewriter) const override { auto transferReadOp = op.vector().getDefiningOp<vector::TransferReadOp>(); if (!transferReadOp) return failure(); if (transferReadOp.mask() || transferReadOp.hasOutOfBoundsDim()) return failure(); SmallVector<int64_t, 2> perm; op.getTransp(perm); SmallVector<unsigned, 2> permU; for (int64_t o : perm) permU.push_back(unsigned(o)); AffineMap permutationMap = AffineMap::getPermutationMap(permU, op.getContext()); AffineMap newMap = permutationMap.compose(transferReadOp.permutation_map()); rewriter.replaceOpWithNewOp<vector::TransferReadOp>( op, op.getType(), transferReadOp.source(), transferReadOp.indices(), newMap, transferReadOp.padding(), transferReadOp.mask(), transferReadOp.in_boundsAttr()); return success(); } }; } // namespace // MMA types have different layout based on how they are used in matmul ops. // Figure the right layout to use by looking at op uses. // TODO: Change the GPU dialect to abstract the layout at the this level and // only care about it during lowering to NVVM. template <typename OpTy> static const char *inferFragType(OpTy op) { for (Operation *users : op->getUsers()) { auto contract = dyn_cast<vector::ContractionOp>(users); if (!contract) continue; if (contract.lhs() == op.getResult()) return "AOp"; if (contract.rhs() == op.getResult()) return "BOp"; } return "COp"; } static void convertTransferReadOp(vector::TransferReadOp op, llvm::DenseMap<Value, Value> &valueMapping) { assert(transferReadSupportsMMAMatrixType(op)); Optional<int64_t> stride = getMemrefConstantHorizontalStride(op.getShapedType()); assert(stride); const char *fragType = inferFragType(op); gpu::MMAMatrixType type = gpu::MMAMatrixType::get(op.getVectorType().getShape(), op.getVectorType().getElementType(), fragType); OpBuilder b(op); Value load = b.create<gpu::SubgroupMmaLoadMatrixOp>( op.getLoc(), type, op.source(), op.indices(), b.getIndexAttr(*stride)); valueMapping[op.getResult()] = load; } static void convertTransferWriteOp(vector::TransferWriteOp op, llvm::DenseMap<Value, Value> &valueMapping) { assert(transferWriteSupportsMMAMatrixType(op)); Optional<int64_t> stride = getMemrefConstantHorizontalStride(op.getShapedType()); assert(stride); OpBuilder b(op); Value matrix = valueMapping.find(op.vector())->second; b.create<gpu::SubgroupMmaStoreMatrixOp>( op.getLoc(), matrix, op.source(), op.indices(), b.getIndexAttr(*stride)); op.erase(); } static void convertContractOp(vector::ContractionOp op, llvm::DenseMap<Value, Value> &valueMapping) { OpBuilder b(op); Value opA = valueMapping.find(op.lhs())->second; Value opB = valueMapping.find(op.rhs())->second; Value opC = valueMapping.find(op.acc())->second; Value matmul = b.create<gpu::SubgroupMmaComputeOp>(op.getLoc(), opC.getType(), opA, opB, opC); valueMapping[op.getResult()] = matmul; } /// Convert a 2D splat ConstantOp to a SubgroupMmaConstantMatrix op. static void convertConstantOp(arith::ConstantOp op, llvm::DenseMap<Value, Value> &valueMapping) { assert(constantSupportsMMAMatrixType(op)); OpBuilder b(op); Attribute splat = op.value().cast<SplatElementsAttr>().getSplatValue(); auto scalarConstant = b.create<arith::ConstantOp>(op.getLoc(), splat.getType(), splat); const char *fragType = inferFragType(op); auto vecType = op.getType().cast<VectorType>(); gpu::MMAMatrixType type = gpu::MMAMatrixType::get( vecType.getShape(), vecType.getElementType(), llvm::StringRef(fragType)); auto matrix = b.create<gpu::SubgroupMmaConstantMatrixOp>(op.getLoc(), type, scalarConstant); valueMapping[op.getResult()] = matrix; } /// Convert a vector.broadcast from scalar to a SubgroupMmaConstantMatrix op. static void convertBroadcastOp(vector::BroadcastOp op, llvm::DenseMap<Value, Value> &valueMapping) { assert(broadcastSupportsMMAMatrixType(op)); OpBuilder b(op); const char *fragType = inferFragType(op); auto vecType = op.getVectorType(); gpu::MMAMatrixType type = gpu::MMAMatrixType::get( vecType.getShape(), vecType.getElementType(), llvm::StringRef(fragType)); auto matrix = b.create<gpu::SubgroupMmaConstantMatrixOp>(op.getLoc(), type, op.source()); valueMapping[op.getResult()] = matrix; } // Replace ForOp with a new ForOp with extra operands. The YieldOp is not // updated and needs to be updated separatly for the loop to be correct. static scf::ForOp replaceForOpWithNewSignature(OpBuilder &b, scf::ForOp loop, ValueRange newIterOperands) { // Create a new loop before the existing one, with the extra operands. OpBuilder::InsertionGuard g(b); b.setInsertionPoint(loop); auto operands = llvm::to_vector<4>(loop.getIterOperands()); operands.append(newIterOperands.begin(), newIterOperands.end()); scf::ForOp newLoop = b.create<scf::ForOp>(loop.getLoc(), loop.lowerBound(), loop.upperBound(), loop.step(), operands); newLoop.getBody()->erase(); newLoop.getLoopBody().getBlocks().splice( newLoop.getLoopBody().getBlocks().begin(), loop.getLoopBody().getBlocks()); for (auto operand : newIterOperands) newLoop.getBody()->addArgument(operand.getType()); for (auto it : llvm::zip(loop.getResults(), newLoop.getResults().take_front( loop.getNumResults()))) std::get<0>(it).replaceAllUsesWith(std::get<1>(it)); loop.erase(); return newLoop; } static void convertForOp(scf::ForOp op, llvm::DenseMap<Value, Value> &valueMapping) { SmallVector<Value> newOperands; SmallVector<std::pair<size_t, size_t>> argMapping; for (auto operand : llvm::enumerate(op.getIterOperands())) { auto it = valueMapping.find(operand.value()); if (it == valueMapping.end()) continue; argMapping.push_back(std::make_pair( operand.index(), op.getNumIterOperands() + newOperands.size())); newOperands.push_back(it->second); } OpBuilder b(op); scf::ForOp newForOp = replaceForOpWithNewSignature(b, op, newOperands); Block &loopBody = *newForOp.getBody(); for (auto mapping : argMapping) { valueMapping[newForOp.getResult(mapping.first)] = newForOp.getResult(mapping.second); valueMapping[loopBody.getArgument(mapping.first + newForOp.getNumInductionVars())] = loopBody.getArgument(mapping.second + newForOp.getNumInductionVars()); } } static void convertYieldOp(scf::YieldOp op, llvm::DenseMap<Value, Value> &valueMapping) { OpBuilder b(op); auto loop = cast<scf::ForOp>(op->getParentOp()); auto yieldOperands = llvm::to_vector<4>(op.getOperands()); for (auto operand : llvm::enumerate(op.getOperands())) { auto it = valueMapping.find(operand.value()); if (it == valueMapping.end()) continue; // Replace the yield of old value with the for op argument to make it easier // to remove the dead code. yieldOperands[operand.index()] = loop.getIterOperands()[operand.index()]; yieldOperands.push_back(it->second); } b.create<scf::YieldOp>(op.getLoc(), yieldOperands); op.erase(); } namespace mlir { void populatePrepareVectorToMMAPatterns(RewritePatternSet &patterns) { patterns.add<PrepareContractToGPUMMA, CombineTransferReadOpTranspose>( patterns.getContext()); } void convertVectorToMMAOps(FuncOp funcOp) { SetVector<Operation *> ops = getOpToConvert(funcOp); llvm::DenseMap<Value, Value> valueMapping; for (Operation *op : ops) { if (auto transferRead = dyn_cast<vector::TransferReadOp>(op)) { convertTransferReadOp(transferRead, valueMapping); } else if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(op)) { convertTransferWriteOp(transferWrite, valueMapping); } else if (auto contractOp = dyn_cast<vector::ContractionOp>(op)) { convertContractOp(contractOp, valueMapping); } else if (auto constantOp = dyn_cast<arith::ConstantOp>(op)) { convertConstantOp(constantOp, valueMapping); } else if (auto broadcastOp = dyn_cast<vector::BroadcastOp>(op)) { convertBroadcastOp(broadcastOp, valueMapping); } else if (auto forOp = dyn_cast<scf::ForOp>(op)) { convertForOp(forOp, valueMapping); } else if (auto yiledOp = dyn_cast<scf::YieldOp>(op)) { convertYieldOp(yiledOp, valueMapping); } } } } // namespace mlir namespace { struct ConvertVectorToGPUPass : public ConvertVectorToGPUBase<ConvertVectorToGPUPass> { void runOnFunction() override { RewritePatternSet patterns(getFunction().getContext()); populatePrepareVectorToMMAPatterns(patterns); (void)applyPatternsAndFoldGreedily(getFunction(), std::move(patterns)); convertVectorToMMAOps(getFunction()); } }; } // namespace std::unique_ptr<Pass> mlir::createConvertVectorToGPUPass() { return std::make_unique<ConvertVectorToGPUPass>(); }
41.027426
80
0.668946
guitard0g
29cfb9c987ccdaabb6fb639977d7394a921a5855
379
cpp
C++
src/main.cpp
ananace/LD43
5b52767d09b9fceb60200ef000e83e2a308adb81
[ "MIT" ]
null
null
null
src/main.cpp
ananace/LD43
5b52767d09b9fceb60200ef000e83e2a308adb81
[ "MIT" ]
null
null
null
src/main.cpp
ananace/LD43
5b52767d09b9fceb60200ef000e83e2a308adb81
[ "MIT" ]
null
null
null
#include "Application.hpp" #include <iostream> #include <stdexcept> int main(int argc, char** argv) { Application app; app.init(argc, argv); try { app.run(); } catch (const std::runtime_error& ex) { std::cerr << "Exception occured during execution;" << std::endl << ex.what() << std::endl; throw ex; } return 0; }
15.791667
98
0.559367
ananace
29d0fd29cf8330546439fea5aa6e383314fcc37f
3,185
cpp
C++
apps/tmp_test/main_3.cpp
LucaCiucci/gnuplotpp
2ba852602070b8854259cef5463722a4c8eb5cfa
[ "MIT" ]
null
null
null
apps/tmp_test/main_3.cpp
LucaCiucci/gnuplotpp
2ba852602070b8854259cef5463722a4c8eb5cfa
[ "MIT" ]
5
2021-10-11T08:19:18.000Z
2021-11-01T00:25:17.000Z
apps/tmp_test/main_3.cpp
LucaCiucci/gnuplotpp
2ba852602070b8854259cef5463722a4c8eb5cfa
[ "MIT" ]
null
null
null
/* LC_NOTICE_BEGIN LC_NOTICE_END */ #include <iostream> #include <stdexcept> int safe_main_3(int argc, char** argv); int main(int argc, char** argv) { try { return safe_main_3(argc, argv); } catch (const std::exception& e) { std::cerr << "Uncaught Exception thrown from safe_main(): " << e.what() << std::endl; } catch (...) { std::cerr << "Uncaught Unknown Exception thrown from safe_main()" << std::endl; } return EXIT_FAILURE; } #include <streambuf> #include <vector> #include <sstream> #include <cstring> // https://blog.csdn.net/tangyin025/article/details/50487544 class MyStream : public std::streambuf { public: void aaa() { } MyStream() { m_buff.resize(20); this->setp(m_buff.data(), m_buff.data() + m_buff.capacity()); //m_buff.clear(); } std::vector<char> m_buff; std::stringstream ss; protected: std::streamsize xsputn(const char* ptr, std::streamsize count) override { //std::cout << "xsputn: \"" << std::string(ptr, ptr + count) << "\"" << std::endl; return std::streambuf::xsputn(ptr, count); int free = this->epptr() - pptr(); std::memcpy(pptr(), ptr, count); this->pbump(count); return count; } int_type overflow(int_type ch) { std::cout << "Overflow! m_buffer = \"" << std::string(m_buff.begin(), m_buff.end()) << "\"" << std::endl; //m_buff.clear(); this->setp(m_buff.data(), m_buff.data() + m_buff.capacity()); if (ch != std::char_traits<char>::eof()) { char c = ch; this->xsputn(&c, 1); return std::char_traits<char>::not_eof(ch); } // giusto ?!?!? not_eof? //return std::char_traits<char>::eof() + 1; return std::char_traits<char>::not_eof(ch); } int sync(void) override { std::cout << "sync" << std::endl; this->overflow(std::char_traits<char>::eof()); return 0; } }; //std::stringstream #include <gnuplotpp/gnuplotpp.hpp> #include <random> int safe_main_3(int argc, char** argv) { std::cout << "Hello There!" << std::endl; using namespace lc; std::default_random_engine e; std::normal_distribution n; auto randVec = [&](size_t N, double mean = 0.0, double sigma = 1.0) -> std::vector<double> { std::vector<double> v; v.reserve(N); for (size_t i = 0; i < N; i++) v.push_back(n(e) * sigma + mean); return v; }; { Gnuplotpp gp; //gp.setTerminal(Gnuplotpp::Terminal::Qt); gp.addRdbuf(std::cout.rdbuf()); gp.writeCommandsOnFile("a.p"); std::optional<int> v; v.value(); gp << "plot sin(x)" << std::endl; auto p = gp.plot(randVec(100)); auto p2 = Gnuplotpp::Plot2d(randVec(100)); auto p3 = Gnuplotpp::plot(randVec(100)); p2.options.marker.value().pointType = Gnuplotpp::PointType::TriangleDot; gp.draw( { p, p2, p3 } ); } return 0; MyStream streamBuf; std::ostream ostr(&streamBuf); lc::PipeStreamBuf pipe("gnuplot --persist"); std::ostream gp(&pipe); gp << "plot sin(x)" << std::endl; gp << std::endl; gp << std::endl; gp << std::endl; gp << std::endl; gp << std::endl; gp << std::endl; gp << std::endl; return 0; ostr << "Hello There!" << std::endl; ostr << "Hello There2!" << std::endl; ostr << "Hello There3!" << std::endl; ostr << std::endl; ostr.flush(); return 0; }
19.90625
107
0.620094
LucaCiucci
29d1794d58d893c444fd9850da89409a63537b61
5,310
hpp
C++
include/Firebase/Firestore/Converters/Int16Converter.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/Firebase/Firestore/Converters/Int16Converter.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/Firebase/Firestore/Converters/Int16Converter.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: Firebase.Firestore.Converters.IntegerConverterBase #include "Firebase/Firestore/Converters/IntegerConverterBase.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: Firebase::Firestore namespace Firebase::Firestore { // Forward declaring type: FieldValueProxy class FieldValueProxy; // Forward declaring type: SerializationContext class SerializationContext; // Forward declaring type: DeserializationContext class DeserializationContext; } // Completed forward declares // Type namespace: Firebase.Firestore.Converters namespace Firebase::Firestore::Converters { // Forward declaring type: Int16Converter class Int16Converter; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::Firebase::Firestore::Converters::Int16Converter); DEFINE_IL2CPP_ARG_TYPE(::Firebase::Firestore::Converters::Int16Converter*, "Firebase.Firestore.Converters", "Int16Converter"); // Type namespace: Firebase.Firestore.Converters namespace Firebase::Firestore::Converters { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: Firebase.Firestore.Converters.Int16Converter // [TokenAttribute] Offset: FFFFFFFF class Int16Converter : public ::Firebase::Firestore::Converters::IntegerConverterBase { public: // System.Void .ctor() // Offset: 0xD506DC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static Int16Converter* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::Firebase::Firestore::Converters::Int16Converter::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<Int16Converter*, creationType>())); } // public override Firebase.Firestore.FieldValueProxy Serialize(Firebase.Firestore.SerializationContext context, System.Object value) // Offset: 0xD62190 // Implemented from: Firebase.Firestore.Converters.ConverterBase // Base method: Firebase.Firestore.FieldValueProxy ConverterBase::Serialize(Firebase.Firestore.SerializationContext context, System.Object value) ::Firebase::Firestore::FieldValueProxy* Serialize(::Firebase::Firestore::SerializationContext* context, ::Il2CppObject* value); // protected override System.Object DeserializeInteger(Firebase.Firestore.DeserializationContext context, System.Int64 value) // Offset: 0xD62204 // Implemented from: Firebase.Firestore.Converters.ConverterBase // Base method: System.Object ConverterBase::DeserializeInteger(Firebase.Firestore.DeserializationContext context, System.Int64 value) ::Il2CppObject* DeserializeInteger(::Firebase::Firestore::DeserializationContext* context, int64_t value); }; // Firebase.Firestore.Converters.Int16Converter #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Firebase::Firestore::Converters::Int16Converter::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: Firebase::Firestore::Converters::Int16Converter::Serialize // Il2CppName: Serialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::FieldValueProxy* (Firebase::Firestore::Converters::Int16Converter::*)(::Firebase::Firestore::SerializationContext*, ::Il2CppObject*)>(&Firebase::Firestore::Converters::Int16Converter::Serialize)> { static const MethodInfo* get() { static auto* context = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "SerializationContext")->byval_arg; static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::Converters::Int16Converter*), "Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{context, value}); } }; // Writing MetadataGetter for method: Firebase::Firestore::Converters::Int16Converter::DeserializeInteger // Il2CppName: DeserializeInteger template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (Firebase::Firestore::Converters::Int16Converter::*)(::Firebase::Firestore::DeserializationContext*, int64_t)>(&Firebase::Firestore::Converters::Int16Converter::DeserializeInteger)> { static const MethodInfo* get() { static auto* context = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DeserializationContext")->byval_arg; static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::Converters::Int16Converter*), "DeserializeInteger", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{context, value}); } };
61.034483
289
0.769303
v0idp
29d2f4350d4bf0d7789810dd25c7a3724f78cc6c
474
cpp
C++
plugins/mongo_db/mongo_db_types.cpp
VIZ-World/viz-core
634825fcfff9e392a26789f8e23c4cfab2952b71
[ "MIT" ]
7
2018-03-21T12:56:32.000Z
2018-04-02T16:06:24.000Z
plugins/mongo_db/mongo_db_types.cpp
VIZ-World/viz-core
634825fcfff9e392a26789f8e23c4cfab2952b71
[ "MIT" ]
18
2018-03-21T13:29:46.000Z
2018-05-18T10:56:43.000Z
plugins/mongo_db/mongo_db_types.cpp
VIZ-World/VIZ.Core
634825fcfff9e392a26789f8e23c4cfab2952b71
[ "MIT" ]
9
2019-02-27T05:19:41.000Z
2021-07-04T22:48:33.000Z
#include <graphene/plugins/mongo_db/mongo_db_types.hpp> namespace graphene { namespace plugins { namespace mongo_db { void bmi_insert_or_replace(db_map& bmi, named_document doc) { auto it = bmi.get<hashed_idx>().find(std::make_tuple( doc.collection_name, doc.key, doc.keyval, doc.is_removal)); if (it != bmi.get<hashed_idx>().end()) bmi.get<hashed_idx>().erase(it); bmi.push_back(std::move(doc)); } } } }
27.882353
65
0.635021
VIZ-World
29d40db7b54eee64bdcfc5f4e873d780b27295a1
10,686
cpp
C++
src/dialogs/CloneDialog.cpp
DeadMozay/gitahead
6c27dda42d99f794089913bc06977042a040bbf7
[ "MIT" ]
2
2021-05-22T17:22:25.000Z
2022-03-27T08:43:35.000Z
src/dialogs/CloneDialog.cpp
DeadMozay/gitahead
6c27dda42d99f794089913bc06977042a040bbf7
[ "MIT" ]
1
2019-02-12T14:11:58.000Z
2019-02-12T14:11:58.000Z
src/dialogs/CloneDialog.cpp
DeadMozay/gitahead
6c27dda42d99f794089913bc06977042a040bbf7
[ "MIT" ]
1
2019-09-11T15:45:19.000Z
2019-09-11T15:45:19.000Z
// // Copyright (c) 2016, Scientific Toolworks, Inc. // // This software is licensed under the MIT License. The LICENSE.md file // describes the conditions under which this software may be distributed. // // Author: Jason Haslam // #include "CloneDialog.h" #include "git/Remote.h" #include "git/Repository.h" #include "git/Result.h" #include "log/LogEntry.h" #include "log/LogView.h" #include "ui/ExpandButton.h" #include "ui/RemoteCallbacks.h" #include <QApplication> #include <QCheckBox> #include <QComboBox> #include <QDialogButtonBox> #include <QFileDialog> #include <QFormLayout> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QUrl> #include <QtConcurrent> namespace { const QString kPathKey = "repo/path"; class RemotePage : public QWizardPage { Q_OBJECT public: RemotePage(Repository *repo, QWidget *parent = nullptr) : QWizardPage(parent) { setTitle(tr("Remote Repository URL")); setSubTitle(repo ? tr("Choose protocol to authenticate with the remote.") : tr("Enter the URL of the remote repository.")); if (repo) { mProtocol = new QComboBox(this); mProtocol->addItem("HTTPS", Repository::Https); mProtocol->addItem("SSH", Repository::Ssh); // Reset URL when the protocol changes. using Signal = void (QComboBox::*)(int); auto signal = static_cast<Signal>(&QComboBox::activated); connect(mProtocol, signal, [this, repo] { int protocol = mProtocol->currentData().toInt(); mUrl->setText(repo->url(static_cast<Repository::Protocol>(protocol))); }); } mUrl = new QLineEdit(this); mUrl->setMinimumWidth(mUrl->sizeHint().width() * 2); connect(mUrl, &QLineEdit::textChanged, this, &RemotePage::completeChanged); if (repo) { mUrl->setReadOnly(true); mUrl->setText(repo->url(Repository::Https)); } QLabel *label = nullptr; if (!repo) { label = new QLabel( tr("Examples of valid URLs include:<table cellspacing='8'>" "<tr><td align='right'><b>HTTPS</b></td>" "<td>https://hostname/path/to/repo.git</td></tr>" "<tr><td align='right'><b>SSH</b></td>" "<td>git@hostname:path/to/repo.git</td></tr>" "<tr><td align='right'><b>Git</b></td>" "<td>git://hostname/path/to/repo.git</td></tr>" "<tr><td align='right'><b>Local</b></td>" "<td>/path/to/repo, C:\\path\\to\\repo</td></tr></table>"), this); } QFormLayout *form = new QFormLayout(this); if (mProtocol) form->addRow(tr("Protocol:"), mProtocol); form->addRow(tr("URL:"), mUrl); if (label) form->addRow(label); // Register field. registerField("url", mUrl); } bool isComplete() const override { return !mUrl->text().isEmpty(); } private: QLineEdit *mUrl; QComboBox *mProtocol = nullptr; }; class LocationPage : public QWizardPage { Q_OBJECT public: LocationPage(bool init, QWidget *parent = nullptr) : QWizardPage(parent), mInit(init) { setTitle(tr("Repository Location")); setSubTitle( tr("Choose the name and location of the new repository. A new " "directory will be created if it doesn't already exist.")); setButtonText(init ? QWizard::FinishButton : QWizard::NextButton, init ? tr("Initialize") : tr("Clone")); mName = new QLineEdit(this); mName->setMinimumWidth(mName->sizeHint().width() * 2); connect(mName, &QLineEdit::textChanged, this, &LocationPage::updateLabel); QFrame *path = new QFrame(this); mPath = new QLineEdit(path); mPath->setMinimumWidth(mPath->sizeHint().width() * 2); connect(mPath, &QLineEdit::textChanged, this, &LocationPage::updateLabel); QPushButton *browse = new QPushButton(tr("..."), path); connect(browse, &QPushButton::clicked, [this]() { QString title = tr("Choose Directory"); QFileDialog *dialog = new QFileDialog(this, title, mPath->text(), QString()); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setFileMode(QFileDialog::Directory); dialog->setOption(QFileDialog::ShowDirsOnly); connect(dialog, &QFileDialog::fileSelected, [this](const QString &file) { mPath->setText(file); }); dialog->open(); }); QHBoxLayout *pathLayout = new QHBoxLayout(path); pathLayout->setContentsMargins(0,0,0,0); pathLayout->addWidget(mPath); pathLayout->addWidget(browse); ExpandButton *expand = new ExpandButton(this); QWidget *advanced = new QWidget(this); advanced->setVisible(false); QFormLayout *form = new QFormLayout; form->setFormAlignment(Qt::AlignLeft); form->addRow(tr("Name:"), mName); form->addRow(tr("Directory:"), path); form->addRow(tr("Advanced:"), expand); QCheckBox *bare = new QCheckBox(tr("Create a bare repository")); QFormLayout *advancedForm = new QFormLayout(advanced); advancedForm->setContentsMargins(-1,0,0,0); advancedForm->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); advancedForm->addRow(bare); connect(expand, &ExpandButton::toggled, [this, advanced](bool checked) { advanced->setVisible(checked); QApplication::processEvents(QEventLoop::ExcludeUserInputEvents); resize(sizeHint()); }); mLabel = new QLabel(this); QVBoxLayout *layout = new QVBoxLayout(this); layout->addLayout(form); layout->addWidget(advanced); layout->addWidget(mLabel); // Register fields. registerField("name", mName); registerField("path", mPath); registerField("bare", bare); } bool isComplete() const override { QString path = mPath->text(); return (!mName->text().isEmpty() && !path.isEmpty() && QDir(path).exists()); } int nextId() const override { return mInit ? -1 : QWizardPage::nextId(); } void initializePage() override { QUrl url(field("url").toString()); QString name = QFileInfo(url.path()).fileName(); mName->setText(name.endsWith(".git") ? name.chopped(4) : name); mPath->setText(QSettings().value(kPathKey, QDir::homePath()).toString()); } private: void updateLabel() { QString fmt = tr("The new repository will be created at:" "<p style='text-indent: 12px'><b>%1</b></p>"); QString name = mName->text(); QString path = mPath->text(); mLabel->setText(fmt.arg(QDir(path).filePath(name))); mLabel->setVisible(!path.isEmpty() && !name.isEmpty()); emit completeChanged(); } bool mInit; QLineEdit *mName; QLineEdit *mPath; QLabel *mLabel; }; class ClonePage : public QWizardPage { Q_OBJECT public: ClonePage(QWidget *parent = nullptr) : QWizardPage(parent) { setTitle(tr("Clone Progress")); setSubTitle(tr("The new repository will open after the clone finishes.")); mLogRoot = new LogEntry(this); mLogView = new LogView(mLogRoot, this); connect(mLogView, &LogView::operationCanceled, this, &ClonePage::cancel); QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(mLogView); } bool isComplete() const override { return (!mWatcher || mWatcher->isFinished()); } void initializePage() override { QString url = field("url").toString().trimmed(); QString name = field("name").toString().trimmed(); QString path = QDir(field("path").toString().trimmed()).filePath(name); bool bare = field("bare").toBool(); LogEntry *entry = mLogRoot->addEntry(url, tr("Clone")); mWatcher = new QFutureWatcher<git::Result>(this); connect(mWatcher, &QFutureWatcher<git::Result>::finished, mWatcher, [this, path, entry] { entry->setBusy(false); git::Result result = mWatcher->result(); if (mCallbacks->isCanceled()) { error(entry, tr("clone"), path, tr("Clone canceled.")); } else if (!result) { error(entry, tr("clone"), path, result.errorString()); } else { mCallbacks->storeDeferredCredentials(); emit completeChanged(); } mWatcher->deleteLater(); mWatcher = nullptr; mCallbacks = nullptr; }); mCallbacks = new RemoteCallbacks( RemoteCallbacks::Receive, entry, url, "origin", mWatcher); entry->setBusy(true); mWatcher->setFuture( QtConcurrent::run(&git::Remote::clone, mCallbacks, url, path, bare)); } void cleanupPage() override { cancel(); } private: void cancel() { // Signal the asynchronous transfer to cancel itself. // Wait for it to finish before leaving this page. if (mWatcher && mWatcher->isRunning()) { mCallbacks->setCanceled(true); mWatcher->waitForFinished(); } } void error( LogEntry *entry, const QString &action, const QString &name, const QString &defaultError) { QString text = tr("Failed to %1 into '%2' - %3"); QString detail = git::Repository::lastError(defaultError); entry->addEntry(LogEntry::Error, text.arg(action, name, detail)); } LogEntry *mLogRoot; LogView *mLogView; RemoteCallbacks *mCallbacks = nullptr; QFutureWatcher<git::Result> *mWatcher = nullptr; }; } // anon. namespace CloneDialog::CloneDialog(Kind kind, QWidget *parent, Repository *repo) : QWizard(parent) { bool init = (kind == Init); setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(init ? tr("Initialize Repository") : tr("Clone Repository")); setOptions(QWizard::NoBackButtonOnStartPage | QWizard::CancelButtonOnLeft); setWizardStyle(QWizard::ModernStyle); addPage(new RemotePage(repo, this)); int location = addPage(new LocationPage(init, this)); int clone = addPage(new ClonePage(this)); connect(page(clone), &ClonePage::completeChanged, [this, clone] { if (page(clone)->isComplete()) accept(); }); if (init) setStartId(location); } void CloneDialog::accept() { QString path = this->path(); bool bare = field("bare").toBool(); if (git::Repository::open(path).isValid() || git::Repository::init(path, bare).isValid()) { QSettings().setValue(kPathKey, field("path")); QDialog::accept(); } // FIXME: Report error. } QString CloneDialog::path() const { return QDir(field("path").toString()).filePath(field("name").toString()); } QString CloneDialog::message() const { QString url = field("url").toString(); return url.isEmpty() ? tr("Initialized empty repository into '%1'").arg(path()) : tr("Cloned repository from '%1' into '%2'").arg(url, path()); } QString CloneDialog::messageTitle() const { QString url = field("url").toString(); return url.isEmpty() ? tr("Initialize") : tr("Clone"); } #include "CloneDialog.moc"
28.269841
83
0.647483
DeadMozay
29d42fa77c5f856524ddf94b405f4c92eb36935c
3,749
hpp
C++
SDK/ARKSurvivalEvolved_DinoAttackStateMinionsDragon_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_DinoAttackStateMinionsDragon_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_DinoAttackStateMinionsDragon_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoAttackStateMinionsDragon_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass DinoAttackStateMinionsDragon.DinoAttackStateMinionsDragon_C // 0x005C (0x00B4 - 0x0058) class UDinoAttackStateMinionsDragon_C : public UPrimalAIState { public: TArray<class APrimalDinoCharacter*> SpawnedMinions; // 0x0058(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance) int NumOfMinionsToSpawn; // 0x0068(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x006C(0x0004) MISSED OFFSET TArray<class AActor*> TargetAreasArray; // 0x0070(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance) TArray<class UClass*> MinionCharacterTypeClasses; // 0x0080(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) TArray<float> MinionCharacterTypeClassesWeights; // 0x0090(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) bool PreventMinionTaming; // 0x00A0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool PreventMinionSaving; // 0x00A1(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x2]; // 0x00A2(0x0002) MISSED OFFSET float StasisOverrideRadius; // 0x00A4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) int OverrideMinionBaseLevel; // 0x00A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) struct FName MinionsSpawnAreaTag; // 0x00AC(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass DinoAttackStateMinionsDragon.DinoAttackStateMinionsDragon_C"); return ptr; } void RemoveDeadCharactersInContainer(TArray<class APrimalDinoCharacter*>* Container_In, TArray<class APrimalDinoCharacter*>* ReturnArray); void EndAnimationStateEvent(struct FName* CustomEventName, TEnumAsByte<ENetRole>* Role); void TickAnimationStateEvent(float* DeltaTime, struct FName* CustomEventName, TEnumAsByte<ENetRole>* Role); void StartAnimationStateEvent(struct FName* CustomEventName, TEnumAsByte<ENetRole>* Role); bool OnCanUseStateEvent(); void OnEndEvent(); void OnTickEvent(float* DeltaSeconds); void OnBeginEvent(class UPrimalAIState** InParentState); void ExecuteUbergraph_DinoAttackStateMinionsDragon(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
63.542373
215
0.595092
2bite
29de80e540f56b6943ee7f75320d9fd4e058e478
2,700
cc
C++
table/sst_file_reader.cc
shampoo365/terarkdb
a05a42789b310e1a79f6b5bb2f98f78993f9fbb2
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-12-24T12:43:24.000Z
2020-12-24T12:43:24.000Z
table/sst_file_reader.cc
shampoo365/terarkdb
a05a42789b310e1a79f6b5bb2f98f78993f9fbb2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
table/sst_file_reader.cc
shampoo365/terarkdb
a05a42789b310e1a79f6b5bb2f98f78993f9fbb2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). #ifndef ROCKSDB_LITE #include "rocksdb/sst_file_reader.h" #include "db/db_iter.h" #include "options/cf_options.h" #include "table/get_context.h" #include "table/table_builder.h" #include "table/table_reader.h" #include "util/file_reader_writer.h" namespace rocksdb { struct SstFileReader::Rep { Options options; EnvOptions soptions; ImmutableCFOptions ioptions; MutableCFOptions moptions; std::unique_ptr<TableReader> table_reader; Rep(const Options& opts) : options(opts), soptions(options), ioptions(options), moptions(ColumnFamilyOptions(options)) {} }; SstFileReader::SstFileReader(const Options& options) : rep_(new Rep(options)) {} SstFileReader::~SstFileReader() {} Status SstFileReader::Open(const std::string& file_path) { auto r = rep_.get(); Status s; uint64_t file_size = 0; std::unique_ptr<RandomAccessFile> file; std::unique_ptr<RandomAccessFileReader> file_reader; s = r->options.env->GetFileSize(file_path, &file_size); if (s.ok()) { s = r->options.env->NewRandomAccessFile(file_path, &file, r->soptions); } if (s.ok()) { file_reader.reset(new RandomAccessFileReader(std::move(file), file_path)); } if (s.ok()) { s = r->options.table_factory->NewTableReader( TableReaderOptions(r->ioptions, r->moptions.prefix_extractor.get(), r->soptions, r->ioptions.internal_comparator), std::move(file_reader), file_size, &r->table_reader); } return s; } Iterator* SstFileReader::NewIterator(const ReadOptions& options) { auto r = rep_.get(); auto sequence = options.snapshot != nullptr ? options.snapshot->GetSequenceNumber() : kMaxSequenceNumber; auto internal_iter = r->table_reader->NewIterator(options, r->moptions.prefix_extractor.get()); return NewDBIterator(r->options.env, options, r->ioptions, r->moptions, r->ioptions.user_comparator, internal_iter, nullptr, sequence, nullptr, r->moptions.max_sequential_skip_in_iterations, nullptr /* read_callback */); } std::shared_ptr<const TableProperties> SstFileReader::GetTableProperties() const { return rep_->table_reader->GetTableProperties(); } Status SstFileReader::VerifyChecksum() { return rep_->table_reader->VerifyChecksum(); } } // namespace rocksdb #endif // !ROCKSDB_LITE
31.395349
80
0.683704
shampoo365
29dfe07c148de811c2c034f451b25d8bb3f98c37
1,356
cpp
C++
sort/quick_sort_optimized.cpp
xiangp126/my-algo
300e825b9e5048e7949ee5d9e16e4cc89939a34c
[ "MIT" ]
3
2018-03-16T02:06:04.000Z
2018-05-09T13:57:24.000Z
sort/quick_sort_optimized.cpp
xiangp126/my-algo
300e825b9e5048e7949ee5d9e16e4cc89939a34c
[ "MIT" ]
5
2018-06-11T11:44:41.000Z
2018-06-14T01:48:10.000Z
sort/quick_sort_optimized.cpp
xiangp126/my-algo
300e825b9e5048e7949ee5d9e16e4cc89939a34c
[ "MIT" ]
1
2018-06-08T05:45:43.000Z
2018-06-08T05:45:43.000Z
#include <utility> #include "common.h" #include "sort.h" using std::pair; using std::make_pair; static void qSort(vector<int> &, int, int); static pair<int, int> partition(vector<int> &, int, int); void quickSortOptimized(vector<int> &nums) { int N = nums.size(); qSort(nums, 0, N - 1); } void qSort(vector<int> &nums, int left, int right) { if (left < right) { pair<int, int> pivotIndex = partition(nums, left, right); qSort(nums, left, pivotIndex.first - 1); qSort(nums, pivotIndex.second + 1, right); } } pair<int, int> partition(vector<int> &nums, int left, int right) { // qSort ensure left < right @here int sentinel = nums[right]; int i = left, k = i; int rend = right; while (k < right) { if (nums[k] < sentinel) { swap(nums[i++], nums[k++]); } else { if (nums[k] == sentinel) { // bug point: nums[k], not k++ swap(nums[k], nums[--right]); } else { ++k; } } } // move 'equal' iterms to 'middle' int equalCnt = rend - right + 1; int grCnt = right - left; int cnt = std::min(equalCnt, grCnt); for (int index = 0; index < cnt; ++index) { swap(nums[i + index], nums[rend - index]); } return make_pair( i, i + equalCnt - 1); }
27.12
66
0.533923
xiangp126
29e2304ea458311ab025302cdc8ac34e0925d00f
6,029
hpp
C++
bftengine/src/preprocessor/RequestProcessingState.hpp
yontyon/concord-bft
ea58d4bbaed646471c2d4f21e1dd06a9a4c19611
[ "Apache-2.0" ]
1
2021-08-15T06:43:47.000Z
2021-08-15T06:43:47.000Z
bftengine/src/preprocessor/RequestProcessingState.hpp
yontyon/concord-bft
ea58d4bbaed646471c2d4f21e1dd06a9a4c19611
[ "Apache-2.0" ]
2
2018-10-22T06:53:43.000Z
2018-10-23T15:12:31.000Z
bftengine/src/preprocessor/RequestProcessingState.hpp
yontyon/concord-bft
ea58d4bbaed646471c2d4f21e1dd06a9a4c19611
[ "Apache-2.0" ]
1
2022-02-21T12:49:18.000Z
2022-02-21T12:49:18.000Z
// Concord // // Copyright (c) 2020-2021 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the "License"). You may not use this product except in // compliance with the Apache 2.0 License. // // This product may include a number of subcomponents with separate copyright notices and license terms. Your use of // these subcomponents is subject to the terms and conditions of the sub-component's license, as noted in the LICENSE // file. #pragma once #include "messages/ClientPreProcessRequestMsg.hpp" #include "messages/PreProcessRequestMsg.hpp" #include "messages/PreProcessReplyMsg.hpp" #include "messages/PreProcessResultMsg.hpp" #include "PreProcessorRecorder.hpp" #include <vector> #include <map> #include <list> namespace preprocessor { // This class collects and stores data relevant to the processing of one specific client request by all replicas. typedef enum { NONE, CONTINUE, COMPLETE, CANCEL, EXPIRED, CANCELLED_BY_PRIMARY, RETRY_PRIMARY } PreProcessingResult; using ReplicaIdsList = std::vector<ReplicaId>; class RequestProcessingState { public: RequestProcessingState(ReplicaId myReplicaId, uint16_t numOfReplicas, const std::string& batchCid, uint16_t clientId, uint16_t reqOffsetInBatch, const std::string& cid, ReqId reqSeqNum, ClientPreProcessReqMsgUniquePtr clientReqMsg, PreProcessRequestMsgSharedPtr preProcessRequestMsg, const char* signature = nullptr, const uint32_t signatureLen = 0); ~RequestProcessingState() = default; // None of RequestProcessingState functions is thread-safe. They are guarded by RequestState::mutex from PreProcessor. void handlePrimaryPreProcessed(const char* preProcessResult, uint32_t preProcessResultLen); void handlePreProcessReplyMsg(const PreProcessReplyMsgSharedPtr& preProcessReplyMsg); std::unique_ptr<MessageBase> buildClientRequestMsg(bool emptyReq = false); void setPreProcessRequest(PreProcessRequestMsgSharedPtr preProcessReqMsg); const PreProcessRequestMsgSharedPtr& getPreProcessRequest() const { return preProcessRequestMsg_; } const auto getClientId() const { return clientId_; } const auto getReqOffsetInBatch() const { return reqOffsetInBatch_; } const SeqNum getReqSeqNum() const { return reqSeqNum_; } PreProcessingResult definePreProcessingConsensusResult(); const char* getPrimaryPreProcessedResult() const { return primaryPreProcessResult_; } uint32_t getPrimaryPreProcessedResultLen() const { return primaryPreProcessResultLen_; } bool isReqTimedOut() const; const uint64_t reqRetryId() const { return reqRetryId_; } uint64_t getReqTimeoutMilli() const { return clientPreProcessReqMsg_ ? clientPreProcessReqMsg_->requestTimeoutMilli() : 0; } const char* getReqSignature() const { if (!clientRequestSignature_.empty()) { return clientRequestSignature_.data(); } return nullptr; } uint32_t getReqSignatureLength() const { return clientRequestSignature_.size(); } const std::string getReqCid() const { return clientPreProcessReqMsg_ ? clientPreProcessReqMsg_->getCid() : ""; } const std::string& getBatchCid() const { return batchCid_; } void detectNonDeterministicPreProcessing(const uint8_t* newHash, NodeIdType newSenderId, uint64_t reqRetryId) const; void releaseResources(); ReplicaIdsList getRejectedReplicasList() { return rejectedReplicaIds_; } void resetRejectedReplicasList() { rejectedReplicaIds_.clear(); } void setPreprocessingRightNow(bool set) { preprocessingRightNow_ = set; } const std::list<PreProcessResultSignature>& getPreProcessResultSignatures(); static void init(uint16_t numOfRequiredReplies, preprocessor::PreProcessorRecorder* histograms); private: static concord::util::SHA3_256::Digest convertToArray( const uint8_t resultsHash[concord::util::SHA3_256::SIZE_IN_BYTES]); static uint64_t getMonotonicTimeMilli(); static logging::Logger& logger() { static logging::Logger logger_ = logging::getLogger("concord.preprocessor"); return logger_; } auto calculateMaxNbrOfEqualHashes(uint16_t& maxNumOfEqualHashes) const; void detectNonDeterministicPreProcessing(const concord::util::SHA3_256::Digest& newHash, NodeIdType newSenderId, uint64_t reqRetryId) const; private: static uint16_t numOfRequiredEqualReplies_; static preprocessor::PreProcessorRecorder* preProcessorHistograms_; // The use of the class data members is thread-safe. The PreProcessor class uses a per-instance mutex lock for // the RequestProcessingState objects. const ReplicaId myReplicaId_; const uint16_t numOfReplicas_; const std::string batchCid_; const uint16_t clientId_; const uint16_t reqOffsetInBatch_; const std::string cid_; const ReqId reqSeqNum_; const uint64_t entryTime_; const std::string clientRequestSignature_; ClientPreProcessReqMsgUniquePtr clientPreProcessReqMsg_; PreProcessRequestMsgSharedPtr preProcessRequestMsg_; uint16_t numOfReceivedReplies_ = 0; ReplicaIdsList rejectedReplicaIds_; const char* primaryPreProcessResult_ = nullptr; // This memory is statically pre-allocated per client in PreProcessor uint32_t primaryPreProcessResultLen_ = 0; concord::util::SHA3_256::Digest primaryPreProcessResultHash_ = {}; // Maps result hash to a list of replica signatures sent for this hash. Implcitly this also gives the number of // replicas returning a specific hash. std::map<concord::util::SHA3_256::Digest, std::list<PreProcessResultSignature>> preProcessingResultHashes_; bool retrying_ = false; bool preprocessingRightNow_ = false; uint64_t reqRetryId_ = 0; }; using RequestProcessingStateUniquePtr = std::unique_ptr<RequestProcessingState>; } // namespace preprocessor
47.101563
120
0.752529
yontyon
29e7905e33b68ab5c762481a7a388178fd6ab29e
5,452
hpp
C++
src/TerrainTile.hpp
a4chet/cesium-terrain-builder
ef70212c05d301fa7ad0a497a06765eaec663572
[ "Apache-2.0" ]
null
null
null
src/TerrainTile.hpp
a4chet/cesium-terrain-builder
ef70212c05d301fa7ad0a497a06765eaec663572
[ "Apache-2.0" ]
null
null
null
src/TerrainTile.hpp
a4chet/cesium-terrain-builder
ef70212c05d301fa7ad0a497a06765eaec663572
[ "Apache-2.0" ]
null
null
null
#ifndef TERRAINTILE_HPP #define TERRAINTILE_HPP /******************************************************************************* * Copyright 2014 GeoData <geodata@soton.ac.uk> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. *******************************************************************************/ /** * @file TerrainTile.hpp * @brief This declares the `Terrain` and `TerrainTile` classes */ #include <vector> #include "gdal_priv.h" #include "config.hpp" #include "Tile.hpp" #include "TileCoordinate.hpp" #include "CTBOutputStream.hpp" namespace ctb { class Terrain; class TerrainTile; } /** * @brief Model the terrain heightmap specification * * This aims to implement the Cesium [heightmap-1.0 terrain * format](http://cesiumjs.org/data-and-assets/terrain/formats/heightmap-1.0.html). */ class CTB_DLL ctb::Terrain { public: /// Create an empty terrain object Terrain(); /// Instantiate using terrain data on the file system Terrain(const char *fileName); /// Read terrain data from a file handle Terrain(FILE *fp); /// Read terrain data from the filesystem void readFile(const char *fileName); /// Write terrain data to a file handle void writeFile(FILE *fp) const; /// Write terrain data to the filesystem void writeFile(const char *fileName) const; /// Write terrain data to an output stream void writeFile(CTBOutputStream &ostream) const; /// Get the water mask as a boolean mask std::vector<bool> mask(); /// Does the terrain tile have child tiles? bool hasChildren() const; /// Does the terrain tile have a south west child tile? bool hasChildSW() const; /// Does the terrain tile have a south east child tile? bool hasChildSE() const; /// Does the terrain tile have a north west child tile? bool hasChildNW() const; /// Does the terrain tile have a north east child tile? bool hasChildNE() const; /// Specify that there is a south west child tile void setChildSW(bool on = true); /// Specify that there is a south east child tile void setChildSE(bool on = true); /// Specify that there is a north west child tile void setChildNW(bool on = true); /// Specify that there is a north east child tile void setChildNE(bool on = true); /// Specify that all child tiles are present void setAllChildren(bool on = true); /// Specify that this tile is all water void setIsWater(); /// Is this tile all water? bool isWater() const; /// Specify that this tile is all land void setIsLand(); /// Is this tile all land? bool isLand() const; /// Does this tile have a water mask? bool hasWaterMask() const; /// Get the height data as a const vector const std::vector<i_terrain_height> & getHeights() const; /// Get the height data as a vector std::vector<i_terrain_height> & getHeights(); void setIsValid(bool isValid = true); bool isValidTile() const; protected: /// The terrain height data std::vector<i_terrain_height> mHeights; // replace with `std::array` in C++11 /// The number of height cells within a terrain tile static const unsigned short int TILE_CELL_SIZE = TILE_SIZE * TILE_SIZE; /// The number of water mask cells within a terrain tile static const unsigned int MASK_CELL_SIZE = MASK_SIZE * MASK_SIZE; /** * @brief The maximum byte size of an uncompressed terrain tile * * This is calculated as (heights + child flags + water mask). */ static const unsigned int MAX_TERRAIN_SIZE = (TILE_CELL_SIZE * 2) + 1 + MASK_CELL_SIZE; private: char mChildren; ///< The child flags char mMask[MASK_CELL_SIZE]; ///< The water mask size_t mMaskLength; ///< What size is the water mask? bool isValid = true; /** * @brief Bit flags defining child tile existence * * There is a good discussion on bitflags * [here](http://www.dylanleigh.net/notes/c-cpp-tricks.html#Using_"Bitflags"). */ enum Children { TERRAIN_CHILD_SW = 1, // 2^0, bit 0 TERRAIN_CHILD_SE = 2, // 2^1, bit 1 TERRAIN_CHILD_NW = 4, // 2^2, bit 2 TERRAIN_CHILD_NE = 8 // 2^3, bit 3 }; }; /** * @brief `Terrain` data associated with a `Tile` * * Associating terrain data with a tile coordinate allows the tile to be * converted to a geo-referenced raster (see `TerrainTile::heightsToRaster`). */ class CTB_DLL ctb::TerrainTile : public Terrain, public Tile { friend class TerrainTiler; public: /// Create a terrain tile from a tile coordinate TerrainTile(const TileCoordinate &coord); /// Create a terrain tile from a file TerrainTile(const char *fileName, const TileCoordinate &coord); /// Create a terrain tile from terrain data TerrainTile(const Terrain &terrain, const TileCoordinate &coord); /// Get the height data as an in memory GDAL raster GDALDatasetH heightsToRaster() const; }; #endif /* TERRAINTILE_HPP */
25.476636
89
0.672047
a4chet
29ea8328d3fdb6bf9d5c90c58d42557d555383c9
2,022
cpp
C++
examples/framebuffer.cpp
ataryq/smk
66dae81cc39e1abeb8d8acbcef7521bd4c954cc0
[ "MIT" ]
69
2019-08-08T22:17:59.000Z
2022-03-30T19:11:16.000Z
examples/framebuffer.cpp
ataryq/smk
66dae81cc39e1abeb8d8acbcef7521bd4c954cc0
[ "MIT" ]
7
2020-02-11T02:58:20.000Z
2021-06-06T18:16:37.000Z
examples/framebuffer.cpp
ataryq/smk
66dae81cc39e1abeb8d8acbcef7521bd4c954cc0
[ "MIT" ]
11
2020-08-09T14:49:59.000Z
2022-03-12T16:55:49.000Z
#include <smk/BlendMode.hpp> #include <smk/Color.hpp> #include <smk/Framebuffer.hpp> #include <smk/Input.hpp> #include <smk/Shape.hpp> #include <smk/Sprite.hpp> #include <smk/Window.hpp> int main() { int dim = 512; int center = dim / 2; auto window = smk::Window(dim, dim, "Framebufer example"); // Two framebuffer. Reading one and writing in the other. Swapping both for // every iterations. auto framebuffer_1 = smk::Framebuffer(dim, dim); auto framebuffer_2 = smk::Framebuffer(dim, dim); // Draw a circle under user's mouse. auto circle = smk::Shape::Circle(dim * 0.15); window.ExecuteMainLoop([&] { window.PoolEvents(); // Use framebuffer_1 to draw into framebuffer_2 and the window ------------- auto sprite = smk::Sprite(framebuffer_1); sprite.SetBlendMode(smk::BlendMode::Add); // ----Draw to the window -------------------------------------------------- window.Clear(smk::Color::Black); sprite.SetCenter(center, center); sprite.SetPosition(center, center); window.Draw(sprite); window.Display(); // ----Draw into framebuffer2 ---------------------------------------------- framebuffer_2.Clear(smk::Color::Black); sprite.SetScale(0.5, 0.5); sprite.SetColor({0.6f, 0.7f, 1.f, 1.f}); // Top triangle sprite.SetPosition(center, dim * 0.25); framebuffer_2.Draw(sprite); // Bottom left triangle. sprite.SetPosition(dim * 0.25, dim * 0.75); framebuffer_2.Draw(sprite); // Bottom right triangle. sprite.SetPosition(dim * 0.75, dim * 0.75); framebuffer_2.Draw(sprite); // Circle under user's mouse. circle.SetPosition(window.input().cursor()); framebuffer_2.Draw(circle); // ------------------------------------------------------------------------- std::swap(framebuffer_1, framebuffer_2); }); return EXIT_SUCCESS; } // Copyright 2019 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file.
30.179104
80
0.610287
ataryq
29eeef0f7247a508932517db9248b5f6ba6b80fb
42,122
cpp
C++
3_solver_heuristicas/ExecutadorDeMetaheuristicas.cpp
joaoweissmann/synthetic_instance_generator
4eed082d97c81a13b9c7b4d4ec83b209cd2fe134
[ "Apache-2.0" ]
null
null
null
3_solver_heuristicas/ExecutadorDeMetaheuristicas.cpp
joaoweissmann/synthetic_instance_generator
4eed082d97c81a13b9c7b4d4ec83b209cd2fe134
[ "Apache-2.0" ]
null
null
null
3_solver_heuristicas/ExecutadorDeMetaheuristicas.cpp
joaoweissmann/synthetic_instance_generator
4eed082d97c81a13b9c7b4d4ec83b209cd2fe134
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 João Ricardo Weissmann Santos // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 <bits/stdc++.h> #include "ExecutadorDeMetaheuristicas.h" ExecutadorDeMetaheuristicas::ExecutadorDeMetaheuristicas() { this->_estrutura = 1; this->_modoRealoc = 1; this->_criterio = 1; this->_alpha = 0.9; this->_modoBusca = 14; this->_modoPerturba = 13; this->_nivelPerturba = 20; } ExecutadorDeMetaheuristicas::ExecutadorDeMetaheuristicas(int estrutura, int modoRealoc, int criterio, double alpha, int modoBusca, int modoPerturba, int nivelPerturba) { this->_estrutura = estrutura; this->_modoRealoc = modoRealoc; this->_criterio = criterio; this->_alpha = alpha; this->_modoBusca = modoBusca; this->_modoPerturba = modoPerturba; this->_nivelPerturba = nivelPerturba; } void ExecutadorDeMetaheuristicas::setAlpha(double alpha) { this->_alpha = alpha; } void ExecutadorDeMetaheuristicas::setNivelPerturba(int nivelPerturba) { this->_nivelPerturba = nivelPerturba; } std::tuple<long long, std::map<Sonda, std::vector<Alocacao>>, double, double, int> ExecutadorDeMetaheuristicas::multStartHeuristic(DadosDeEntrada dataset, int nIter, int modoDebug) { auto start = std::chrono::high_resolution_clock::now(); ConstrutorHeuristico construtor{this->_alpha, this->_criterio, this->_estrutura, this->_modoRealoc}; // inicializa bests e constrói solução inicial long long bestTempo; std::map<Sonda, std::vector<Alocacao>> bestAlocsMap; double bestFitness; double bestGastos; int bestTotalFree; std::tie(bestTempo, bestAlocsMap, bestFitness, bestGastos, bestTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); // inicializa vetor de alphas std::vector<double> alphas; alphas.push_back(0.99); alphas.push_back(0.9); alphas.push_back(0.8); alphas.push_back(0.7); alphas.push_back(0.6); alphas.push_back(0.5); // inicializa valores intermediários long long newTempo; std::map<Sonda, std::vector<Alocacao>> newAlocsMap; double newFitness; double newGastos; int newTotalFree; int count = 0; while (count < nIter) { count++; // escolhe critério int criterio = (rand() % 4) + 1; construtor.setCriterio(criterio); // escolhe alpha int alphaIdx = rand() % alphas.size(); double alpha = *std::next(alphas.begin(), alphaIdx); construtor.setAlpha(alpha); // constroi nova solução std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; } } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); long long tempoTotal = duration.count(); return std::make_tuple(tempoTotal, bestAlocsMap, bestFitness, bestGastos, bestTotalFree); } std::tuple<long long, std::map<Sonda, std::vector<Alocacao>>, double, double, int> ExecutadorDeMetaheuristicas::GRASP(DadosDeEntrada dataset, int nIter, int modoDebug, std::set<int> vizinhancasinit, std::set<int> vizinhancasFinal, int nivelIntensifica, int maxIterFO) { int modoDebugAltoNivel = 0; if (modoDebugAltoNivel){ std::cout << std::endl; std::cout << "Rodando GRASP"; std::cout << std::endl;} auto start = std::chrono::high_resolution_clock::now(); ConstrutorHeuristico construtor{this->_alpha, this->_criterio, this->_estrutura, this->_modoRealoc}; MovimentadorEmVizinhancas movimentador{}; // inicializa bests e constroi solução inicial long long bestTempo; std::map<Sonda, std::vector<Alocacao>> bestAlocsMap; double bestFitness; double bestGastos; int bestTotalFree; if (modoDebugAltoNivel){ std::cout << std::endl; std::cout << "Construindo solução inicial"; std::cout << std::endl;} std::tie(bestTempo, bestAlocsMap, bestFitness, bestGastos, bestTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); // inicializa vetor de alphas std::vector<double> alphas; alphas.push_back(0.99); alphas.push_back(0.9); alphas.push_back(0.8); alphas.push_back(0.7); alphas.push_back(0.6); alphas.push_back(0.5); // inicializa valores intermediários long long newTempo; std::map<Sonda, std::vector<Alocacao>> newAlocsMap; double newFitness; double newGastos; int newTotalFree; // inicializa conjunto de ótimos locais std::set<int> otimosLocaisFitness; std::vector<std::pair<int, std::map<Sonda, std::vector<Alocacao>>>> otimosLocaisAlocs; int count = 0; while (count < nIter) { count++; if (modoDebugAltoNivel){ std::cout << std::endl; std::cout << "Rodando iteração: " << count; std::cout << std::endl;} // escolhe critério int criterio = (rand() % 4) + 1; construtor.setCriterio(criterio); // escolhe alpha int alphaIdx = rand() % alphas.size(); double alpha = *std::next(alphas.begin(), alphaIdx); construtor.setAlpha(alpha); // constroi nova solução std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); // realiza busca local std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = movimentador.buscaLocal(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasinit, maxIterFO); if (modoDebugAltoNivel){ std::cout << std::endl; std::cout << "Novos valores após iteração: " << count << std::endl; std::cout << "best fitness: " << bestFitness << std::endl; std::cout << "new fitness: " << newFitness << std::endl; std::cout << std::endl;} // guarda ótimo local, se novo if (otimosLocaisFitness.find((int)newFitness) == otimosLocaisFitness.end()) { if (modoDebugAltoNivel){ std::cout << std::endl << "Guardando ótimo local" << std::endl;} otimosLocaisFitness.insert((int)newFitness); otimosLocaisAlocs.push_back(std::make_pair((int)newFitness, newAlocsMap)); } // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { if (modoDebugAltoNivel){ std::cout << std::endl << "Substituindo best" << std::endl;} bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; } } if (modoDebugAltoNivel){ std::cout << std::endl << "GRASP finalizado sem intensificações finais" << std::endl;} // faz busca final para os melhores ótimos locais struct sort_pred { bool operator()(const std::pair<int, std::map<Sonda, std::vector<Alocacao>>> &left, const std::pair<int, std::map<Sonda, std::vector<Alocacao>>> &right) { return left.first < right.first; } }; std::sort(otimosLocaisAlocs.begin(), otimosLocaisAlocs.end(), sort_pred()); int countOtimosLocais = 0; for (std::vector<std::pair<int, std::map<Sonda, std::vector<Alocacao>>>>::iterator it=otimosLocaisAlocs.begin(); it!=otimosLocaisAlocs.end(); ++it) { countOtimosLocais++; if (countOtimosLocais > nivelIntensifica) { break; } newAlocsMap = it->second; // realiza busca intensificada std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = movimentador.buscaLocal(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasFinal, maxIterFO); // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; } } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); long long tempoTotal = duration.count(); if (modoDebugAltoNivel){ std::cout << std::endl << "GRASP finalizado com intensificações finais" << std::endl;} return std::make_tuple(tempoTotal, bestAlocsMap, bestFitness, bestGastos, bestTotalFree); } std::tuple<long long, std::map<Sonda, std::vector<Alocacao>>, double, double, int> ExecutadorDeMetaheuristicas::GRASPadaptativo(DadosDeEntrada dataset, int nIter, int modoDebug, std::set<int> vizinhancasinit, std::set<int> vizinhancasFinal, int nivelIntensifica, int nIterMelhora, double taxaAlpha, int nIterAlpha, int maxIterFO) { int modoDebugAltoNivel = 0; if (modoDebugAltoNivel){ std::cout << std::endl << "Rodando GRASP adaptativo" << std::endl;} auto start = std::chrono::high_resolution_clock::now(); ConstrutorHeuristico construtor{this->_alpha, this->_criterio, this->_estrutura, this->_modoRealoc}; MovimentadorEmVizinhancas movimentador{}; // inicializa bests e constroi solução inicial long long bestTempo; std::map<Sonda, std::vector<Alocacao>> bestAlocsMap; double bestFitness; double bestGastos; int bestTotalFree; if (modoDebugAltoNivel){ std::cout << std::endl << "Construindo solução inicial" << std::endl;} std::tie(bestTempo, bestAlocsMap, bestFitness, bestGastos, bestTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); // inicializa valores intermediários long long newTempo; std::map<Sonda, std::vector<Alocacao>> newAlocsMap; double newFitness; double newGastos; int newTotalFree; // inicializa conjunto de critérios std::set<int> criterios; criterios.insert(1); criterios.insert(2); criterios.insert(3); criterios.insert(4); criterios.erase(this->_criterio); // inicializa conjunto de ótimos locais std::set<int> otimosLocaisFitness; std::vector<std::pair<int, std::map<Sonda, std::vector<Alocacao>>>> otimosLocaisAlocs; // guarda alpha inicial double alphaInit = construtor.getAlpha(); int count = 0; int countSemMelhora = 0; int countMudouAlpha = 0; while (count < nIter) { count++; if (modoDebugAltoNivel){ std::cout << std::endl << "Rodando iteração: " << count << std::endl;} // constroi nova solução std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); // realiza busca local std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = movimentador.buscaLocal(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasinit, maxIterFO); if (modoDebugAltoNivel){ std::cout << std::endl; std::cout << "Novos valores após iteração: " << count << std::endl; std::cout << "best fitness: " << bestFitness << std::endl; std::cout << "new fitness: " << newFitness << std::endl; std::cout << "Contagem sem melhorar FO: " << countSemMelhora << std::endl; std::cout << "Contagem mudou alpha: " << countMudouAlpha << std::endl; std::cout << std::endl;} // guarda ótimo local, se novo if (otimosLocaisFitness.find((int)newFitness) == otimosLocaisFitness.end()) { if (modoDebugAltoNivel){ std::cout << std::endl << "Guardando ótimo local" << std::endl;} otimosLocaisFitness.insert((int)newFitness); otimosLocaisAlocs.push_back(std::make_pair((int)newFitness, newAlocsMap)); } // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { if (modoDebugAltoNivel){ std::cout << std::endl << "Atualizando best" << std::endl;} bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; countSemMelhora = 0; countMudouAlpha = 0; construtor.setAlpha(alphaInit); } else { countSemMelhora++; if (countSemMelhora > nIterMelhora) { if (modoDebugAltoNivel){ std::cout << std::endl << "Alterando alpha para maior exploração" << std::endl;} double newAlpha = taxaAlpha * construtor.getAlpha(); construtor.setAlpha(newAlpha); countSemMelhora = 0; countMudouAlpha++; } if (countMudouAlpha > nIterAlpha) { if (modoDebugAltoNivel){ std::cout << std::endl << "Alterando critério guloso para maior exploração" << std::endl;} if (criterios.empty()) { criterios.insert(1); criterios.insert(2); criterios.insert(3); criterios.insert(4); int newCriterio = *criterios.begin(); criterios.erase(newCriterio); construtor.setCriterio(newCriterio); construtor.setAlpha(alphaInit); countSemMelhora = 0; countMudouAlpha = 0; } else { int newCriterio = *criterios.begin(); criterios.erase(newCriterio); construtor.setCriterio(newCriterio); construtor.setAlpha(alphaInit); countSemMelhora = 0; countMudouAlpha = 0; } } } } if (modoDebugAltoNivel){ std::cout << std::endl << "GRASP adaptativo finalizado sem intensificações finais" << std::endl;} // faz busca final para os melhores ótimos locais struct sort_pred { bool operator()(const std::pair<int, std::map<Sonda, std::vector<Alocacao>>> &left, const std::pair<int, std::map<Sonda, std::vector<Alocacao>>> &right) { return left.first < right.first; } }; std::sort(otimosLocaisAlocs.begin(), otimosLocaisAlocs.end(), sort_pred()); int countOtimosLocais = 0; for (std::vector<std::pair<int, std::map<Sonda, std::vector<Alocacao>>>>::iterator it=otimosLocaisAlocs.begin(); it!=otimosLocaisAlocs.end(); ++it) { countOtimosLocais++; if (countOtimosLocais > nivelIntensifica) { break; } newAlocsMap = it->second; // realiza busca intensificada std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = movimentador.buscaLocal(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasFinal, maxIterFO); // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; } } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); long long tempoTotal = duration.count(); if (modoDebugAltoNivel){ std::cout << std::endl << "GRASP adaptativo finalizado com intensificações finais" << std::endl;} return std::make_tuple(tempoTotal, bestAlocsMap, bestFitness, bestGastos, bestTotalFree); } std::tuple<long long, std::map<Sonda, std::vector<Alocacao>>, double, double, int> ExecutadorDeMetaheuristicas::ILS(DadosDeEntrada dataset, int nIter, int modoDebug, std::set<int> vizinhancasinit, std::set<int> vizinhancasFinal, double aceitacaoLimite, int nivelIntensifica, int maxIterFO) { int modoDebugAltoNivel = 0; if (modoDebugAltoNivel){ std::cout << std::endl << "Rodando ILS" << std::endl;} auto start = std::chrono::high_resolution_clock::now(); ConstrutorHeuristico construtor{this->_alpha, this->_criterio, this->_estrutura, this->_modoRealoc}; MovimentadorEmVizinhancas movimentador{}; // inicializa bests e constroi solução inicial long long bestTempo; std::map<Sonda, std::vector<Alocacao>> bestAlocsMap; double bestFitness; double bestGastos; int bestTotalFree; if (modoDebugAltoNivel){ std::cout << std::endl << "Construindo solução inicial" << std::endl;} std::tie(bestTempo, bestAlocsMap, bestFitness, bestGastos, bestTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); if (modoDebugAltoNivel){ std::cout << std::endl << "Fazendo busca local inicial" << std::endl;} // realiza busca local std::tie(bestTempo, bestAlocsMap, bestFitness, bestGastos, bestTotalFree) = movimentador.buscaLocal(bestAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasinit, maxIterFO); // inicializa valores intermediários long long newTempo; std::map<Sonda, std::vector<Alocacao>> newAlocsMap = bestAlocsMap; double newFitness = bestFitness; double newGastos; int newTotalFree; long long partTempo; std::map<Sonda, std::vector<Alocacao>> partAlocsMap; double partFitness; double partGastos; int partTotalFree; // inicializa conjunto de ótimos locais std::set<int> otimosLocaisFitness; std::vector<std::pair<int, std::map<Sonda, std::vector<Alocacao>>>> otimosLocaisAlocs; int count = 0; while (count < nIter) { count++; if (modoDebugAltoNivel){ std::cout << std::endl << "Rodando iteração: " << count << std::endl;} // perturba solução partAlocsMap = movimentador.perturbaSolucao(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, this->_nivelPerturba, this->_modoPerturba, modoDebug, vizinhancasinit); // realiza busca local std::tie(partTempo, partAlocsMap, partFitness, partGastos, partTotalFree) = movimentador.buscaLocal(partAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasinit, maxIterFO); if (modoDebugAltoNivel){ std::cout << std::endl; std::cout << "Novos valores após iteração: " << count << std::endl; std::cout << "best fitness: " << bestFitness << std::endl; std::cout << "new fitness: " << newFitness << std::endl; std::cout << "part fitness: " << partFitness << std::endl; std::cout << std::endl;} // guarda ótimo local, se novo if (otimosLocaisFitness.find((int)newFitness) == otimosLocaisFitness.end()) { if (modoDebugAltoNivel){ std::cout << std::endl << "Guardando ótimo local" << std::endl;} otimosLocaisFitness.insert((int)newFitness); otimosLocaisAlocs.push_back(std::make_pair((int)newFitness, newAlocsMap)); } // decide se aceita a nova solução if ((int)partFitness >= (int)(aceitacaoLimite * newFitness)) { if (modoDebugAltoNivel){ std::cout << std::endl << "Aceita solução nova" << std::endl;} newAlocsMap = partAlocsMap; newFitness = partFitness; newGastos = partGastos; newTempo = partTempo; newTotalFree = partTotalFree; } // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { if (modoDebugAltoNivel){ std::cout << std::endl << "Atualiza best" << std::endl;} bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; } } if (modoDebugAltoNivel){ std::cout << std::endl << "ILS finalizado sem intensificações finais" << std::endl;} // faz busca final para os melhores ótimos locais struct sort_pred { bool operator()(const std::pair<int, std::map<Sonda, std::vector<Alocacao>>> &left, const std::pair<int, std::map<Sonda, std::vector<Alocacao>>> &right) { return left.first < right.first; } }; std::sort(otimosLocaisAlocs.begin(), otimosLocaisAlocs.end(), sort_pred()); int countOtimosLocais = 0; for (std::vector<std::pair<int, std::map<Sonda, std::vector<Alocacao>>>>::iterator it=otimosLocaisAlocs.begin(); it!=otimosLocaisAlocs.end(); ++it) { countOtimosLocais++; if (countOtimosLocais > nivelIntensifica) { break; } newAlocsMap = it->second; // realiza busca intensificada std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = movimentador.buscaLocal(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasFinal, maxIterFO); // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; } } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); long long tempoTotal = duration.count(); if (modoDebugAltoNivel){ std::cout << std::endl << "ILS finalizado com intensificações finais" << std::endl;} return std::make_tuple(tempoTotal, bestAlocsMap, bestFitness, bestGastos, bestTotalFree); } std::tuple<long long, std::map<Sonda, std::vector<Alocacao>>, double, double, int> ExecutadorDeMetaheuristicas::ILSadaptativo(DadosDeEntrada dataset, int nIter, int modoDebug, std::set<int> vizinhancasinit, std::set<int> vizinhancasFinal, double aceitacaoLimite, int nivelIntensifica, int nIterMelhora, int taxaPerturba, double taxaAceitacao, int nIterRestart, double alphaRestart, int maxIterFO) { int modoDebugAltoNivel = 0; if (modoDebugAltoNivel){ std::cout << std::endl << "Rodando ILS adaptativo" << std::endl;} auto start = std::chrono::high_resolution_clock::now(); ConstrutorHeuristico construtor{this->_alpha, this->_criterio, this->_estrutura, this->_modoRealoc}; MovimentadorEmVizinhancas movimentador{}; // inicializa bests e constroi solução inicial long long bestTempo; std::map<Sonda, std::vector<Alocacao>> bestAlocsMap; double bestFitness; double bestGastos; int bestTotalFree; if (modoDebugAltoNivel){ std::cout << std::endl << "Construindo solução inicial" << std::endl;} std::tie(bestTempo, bestAlocsMap, bestFitness, bestGastos, bestTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); if (modoDebugAltoNivel){ std::cout << std::endl << "Rodando busca local inicial" << std::endl;} // realiza busca local std::tie(bestTempo, bestAlocsMap, bestFitness, bestGastos, bestTotalFree) = movimentador.buscaLocal(bestAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasinit, maxIterFO); // inicializa valores intermediários long long newTempo; std::map<Sonda, std::vector<Alocacao>> newAlocsMap = bestAlocsMap; double newFitness = bestFitness; double newGastos; int newTotalFree; long long partTempo; std::map<Sonda, std::vector<Alocacao>> partAlocsMap; double partFitness; double partGastos; int partTotalFree; // guarda parâmetros iniciais do ILS double limiteAceitacaoInit = aceitacaoLimite; int nivelPerturbaInit = this->_nivelPerturba; // inicializa conjunto de ótimos locais std::set<int> otimosLocaisFitness; std::vector<std::pair<int, std::map<Sonda, std::vector<Alocacao>>>> otimosLocaisAlocs; int count = 0; int countSemMelhora = 0; int countRestart = 0; while (count < nIter) { count++; if (modoDebugAltoNivel){ std::cout << std::endl << "Rodando iteração: " << count << std::endl;} // perturba solução partAlocsMap = movimentador.perturbaSolucao(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, this->_nivelPerturba, this->_modoPerturba, modoDebug, vizinhancasinit); // realiza busca local std::tie(partTempo, partAlocsMap, partFitness, partGastos, partTotalFree) = movimentador.buscaLocal(partAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasinit, maxIterFO); if (modoDebugAltoNivel){ std::cout << std::endl; std::cout << "Novos valores após iteração: " << count << std::endl; std::cout << "best fitness: " << bestFitness << std::endl; std::cout << "new fitness: " << newFitness << std::endl; std::cout << "part fitness: " << partFitness << std::endl; std::cout << "count sem melhorar FO: " << countSemMelhora << std::endl; std::cout << "count para restart: " << countRestart << std::endl; std::cout << std::endl;} // guarda ótimo local, se novo if (otimosLocaisFitness.find((int)partFitness) == otimosLocaisFitness.end()) { if (modoDebugAltoNivel){ std::cout << std::endl << "Guardando ótimo local" << std::endl;} otimosLocaisFitness.insert((int)partFitness); otimosLocaisAlocs.push_back(std::make_pair((int)partFitness, partAlocsMap)); } // decide se aceita a nova solução if ((int)partFitness >= (int)(aceitacaoLimite * newFitness)) { if (modoDebugAltoNivel){ std::cout << std::endl << "Aceita nova solução" << std::endl;} newAlocsMap = partAlocsMap; newFitness = partFitness; newGastos = partGastos; newTempo = partTempo; newTotalFree = partTotalFree; } // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { if (modoDebugAltoNivel){ std::cout << std::endl << "Atualiza best" << std::endl;} bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; countSemMelhora = 0; countRestart = 0; aceitacaoLimite = limiteAceitacaoInit; this->_nivelPerturba = nivelPerturbaInit; } else { countSemMelhora++; if (countSemMelhora > nIterMelhora) { if (modoDebugAltoNivel){ std::cout << std::endl << "Alterando taxaAceitacao e nivelPerturba para mais exploração" << std::endl;} this->_nivelPerturba = this->_nivelPerturba + taxaPerturba; aceitacaoLimite = aceitacaoLimite * taxaAceitacao; countSemMelhora = 0; countRestart++; } if (countRestart > nIterRestart) { if (modoDebugAltoNivel){ std::cout << std::endl << "Realizando restart" << std::endl;} // restart construtor.setAlpha(alphaRestart); // constroi solução std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = construtor.ConstruirSolucao(dataset, modoDebug); // realiza busca local std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = movimentador.buscaLocal(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasinit, maxIterFO); } } } if (modoDebugAltoNivel){ std::cout << std::endl << "ILS adaptativo finalizado sem intensificações finais" << std::endl;} // faz busca final para os melhores ótimos locais struct sort_pred { bool operator()(const std::pair<int, std::map<Sonda, std::vector<Alocacao>>> &left, const std::pair<int, std::map<Sonda, std::vector<Alocacao>>> &right) { return left.first < right.first; } }; std::sort(otimosLocaisAlocs.begin(), otimosLocaisAlocs.end(), sort_pred()); int countOtimosLocais = 0; for (std::vector<std::pair<int, std::map<Sonda, std::vector<Alocacao>>>>::iterator it=otimosLocaisAlocs.begin(); it!=otimosLocaisAlocs.end(); ++it) { countOtimosLocais++; if (countOtimosLocais > nivelIntensifica) { break; } newAlocsMap = it->second; // realiza busca intensificada std::tie(newTempo, newAlocsMap, newFitness, newGastos, newTotalFree) = movimentador.buscaLocal(newAlocsMap, dataset, this->_estrutura, this->_modoRealoc, dataset.getDelta(), this->_modoBusca, modoDebug, vizinhancasFinal, maxIterFO); // se for melhor que best, substitui if ((int)newFitness > (int)bestFitness) { bestAlocsMap = newAlocsMap; bestFitness = newFitness; bestGastos = newGastos; bestTempo = newTempo; bestTotalFree = newTotalFree; } } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start); long long tempoTotal = duration.count(); if (modoDebugAltoNivel){ std::cout << std::endl << "ILS adaptativo finalizado com intensificações finais" << std::endl;} return std::make_tuple(tempoTotal, bestAlocsMap, bestFitness, bestGastos, bestTotalFree); } void ExecutadorDeMetaheuristicas::rodarVariosArquivos(const char * caminho, int nIter, int modoDebug, std::set<int> vizinhancasinit, std::set<int> vizinhancasFinal, double aceitacaoLimite, int nivelIntensifica, int nIterMelhora, double taxaAlpha, int nIterAlpha, int taxaPerturba, double taxaAceitacao, int nIterRestart, double alphaRestart, int maxIterFO) { DIR *dir; struct dirent *diread; std::vector<std::string> arquivos; // armazenando nomes dos arquivos if ( (dir = opendir(caminho)) != nullptr ) { while ( (diread = readdir(dir)) != nullptr ) { arquivos.push_back(diread->d_name); } closedir (dir); } else { perror ("opendir"); } std::ofstream outfile; outfile.open("resultados_automaticos_MH.txt"); outfile << "Arquivo" << " " << "Algoritmo" << " " << "estrutura" << " " << "modoRealoc" << " " << "criterio" << " " << "alpha" << " " << "modoBusca" << " " << "modoPerturba" << " " << "nivelPerturba" << " " << "nIter" << " " << "aceitacaoLimite" << " " << "nivelIntensifica" << " " << "nIterMelhora" << " " << "taxaAlpha" << " " << "nIterAlpha" << " " << "taxaPerturba" << " " << "taxaAceitacao" << " " << "nIterRestart" << " " << "alphaRestart" << " " << "maxIterFO" << " " << "tempo" << " " << "fitness" << " " << "gastos" << " " << std::endl; std::string s1 = "instancia"; for (std::vector<std::string>::iterator it=arquivos.begin(); it!=arquivos.end(); ++it) { std::string arquivo = *it; if (arquivo.find(s1) != std::string::npos) { std::string s2 = "/home/joaoweissmann/Documents/repos/synthetic_instance_generator/synthetic_instance_generator/1_gerador_instancias_sinteticas/instancias/"; s2.append(*it); std::cout << "Rodando heurísticas para arquivo: " << s2 << std::endl; LeitorDeDados leitor; DadosDeEntrada dataset = leitor.lerDadosDeEntrada(s2); long long nIterAlvo = 10000 / 5; nIter = ( nIterAlvo ) / ( (int)dataset.getProjetos().size() ); // inicializa variaveis a serem retornadas long long tempo; std::map<Sonda, std::vector<Alocacao>> alocsMap; double fitness; double gastos; int totalFree; // mult-start heuristic std::cout << "Rodando Mult-Start Heuristic" << std::endl; std::tie(tempo, alocsMap, fitness, gastos, totalFree) = this->multStartHeuristic(dataset, nIter, modoDebug); outfile << s2 << " " << "Mult-Start" << " " << this->_estrutura << " " << this->_modoRealoc << " " << this->_criterio << " " << this->_alpha << " " << this->_modoBusca << " " << this->_modoPerturba << " " << this->_nivelPerturba << " " << nIter << " " << aceitacaoLimite << " " << nivelIntensifica << " " << nIterMelhora << " " << taxaAlpha << " " << nIterAlpha << " " << taxaPerturba << " " << taxaAceitacao << " " << nIterRestart << " " << alphaRestart << " " << maxIterFO << " " << tempo << " " << fitness << " " << gastos << " " << std::endl; // GRASP std::cout << "Rodando GRASP" << std::endl; std::tie(tempo, alocsMap, fitness, gastos, totalFree) = this->GRASP(dataset, nIter, modoDebug, vizinhancasinit, vizinhancasFinal, nivelIntensifica, maxIterFO); outfile << s2 << " " << "GRASP" << " " << this->_estrutura << " " << this->_modoRealoc << " " << this->_criterio << " " << this->_alpha << " " << this->_modoBusca << " " << this->_modoPerturba << " " << this->_nivelPerturba << " " << nIter << " " << aceitacaoLimite << " " << nivelIntensifica << " " << nIterMelhora << " " << taxaAlpha << " " << nIterAlpha << " " << taxaPerturba << " " << taxaAceitacao << " " << nIterRestart << " " << alphaRestart << " " << maxIterFO << " " << tempo << " " << fitness << " " << gastos << " " << std::endl; // GRASP adaptativo std::cout << "Rodando GRASP adaptativo" << std::endl; std::tie(tempo, alocsMap, fitness, gastos, totalFree) = this->GRASPadaptativo(dataset, nIter, modoDebug, vizinhancasinit, vizinhancasFinal, nivelIntensifica, nIterMelhora, taxaAlpha, nIterAlpha, maxIterFO); outfile << s2 << " " << "GRASP_ada" << " " << this->_estrutura << " " << this->_modoRealoc << " " << this->_criterio << " " << this->_alpha << " " << this->_modoBusca << " " << this->_modoPerturba << " " << this->_nivelPerturba << " " << nIter << " " << aceitacaoLimite << " " << nivelIntensifica << " " << nIterMelhora << " " << taxaAlpha << " " << nIterAlpha << " " << taxaPerturba << " " << taxaAceitacao << " " << nIterRestart << " " << alphaRestart << " " << maxIterFO << " " << tempo << " " << fitness << " " << gastos << " " << std::endl; // ILS std::cout << "Rodando ILS" << std::endl; std::tie(tempo, alocsMap, fitness, gastos, totalFree) = this->ILS(dataset, nIter, modoDebug, vizinhancasinit, vizinhancasFinal, aceitacaoLimite, nivelIntensifica, maxIterFO); outfile << s2 << " " << "ILS" << " " << this->_estrutura << " " << this->_modoRealoc << " " << this->_criterio << " " << this->_alpha << " " << this->_modoBusca << " " << this->_modoPerturba << " " << this->_nivelPerturba << " " << nIter << " " << aceitacaoLimite << " " << nivelIntensifica << " " << nIterMelhora << " " << taxaAlpha << " " << nIterAlpha << " " << taxaPerturba << " " << taxaAceitacao << " " << nIterRestart << " " << alphaRestart << " " << maxIterFO << " " << tempo << " " << fitness << " " << gastos << " " << std::endl; // ILS adaptativo std::cout << "Rodando ILS adaptativo" << std::endl; std::tie(tempo, alocsMap, fitness, gastos, totalFree) = this->ILSadaptativo(dataset, nIter, modoDebug, vizinhancasinit, vizinhancasFinal, aceitacaoLimite, nivelIntensifica, nIterMelhora, taxaPerturba, taxaAceitacao, nIterRestart, alphaRestart, maxIterFO); outfile << s2 << " " << "ILS_ada" << " " << this->_estrutura << " " << this->_modoRealoc << " " << this->_criterio << " " << this->_alpha << " " << this->_modoBusca << " " << this->_modoPerturba << " " << this->_nivelPerturba << " " << nIter << " " << aceitacaoLimite << " " << nivelIntensifica << " " << nIterMelhora << " " << taxaAlpha << " " << nIterAlpha << " " << taxaPerturba << " " << taxaAceitacao << " " << nIterRestart << " " << alphaRestart << " " << maxIterFO << " " << tempo << " " << fitness << " " << gastos << " " << std::endl; } } outfile.close(); }
40.895146
267
0.5542
joaoweissmann
29ef5be757609a091ef9810a2fcbc56647a40d82
12,336
cpp
C++
src/ViewTask.cpp
8-bit-fox/taskwarrior
ccb222a31be049fe6e3ef28fe660a1eaca351a95
[ "MIT" ]
null
null
null
src/ViewTask.cpp
8-bit-fox/taskwarrior
ccb222a31be049fe6e3ef28fe660a1eaca351a95
[ "MIT" ]
null
null
null
src/ViewTask.cpp
8-bit-fox/taskwarrior
ccb222a31be049fe6e3ef28fe660a1eaca351a95
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2020, Paul Beckingham, Federico Hernandez. // // 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. // // https://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <ViewTask.h> #include <numeric> #include <Context.h> #include <format.h> #include <util.h> #include <utf8.h> #include <main.h> //////////////////////////////////////////////////////////////////////////////// ViewTask::ViewTask () : _width (0) , _left_margin (0) , _header (0) , _sort_header (0) , _odd (0) , _even (0) , _intra_padding (1) , _intra_odd (0) , _intra_even (0) , _extra_padding (0) , _extra_odd (0) , _extra_even (0) , _truncate_lines (0) , _truncate_rows (0) , _lines (0) , _rows (0) { } //////////////////////////////////////////////////////////////////////////////// ViewTask::~ViewTask () { for (auto& col : _columns) delete col; _columns.clear (); } //////////////////////////////////////////////////////////////////////////////// // |<---------- terminal width ---------->| // // +-------+ +-------+ +-------+ // |header | |header | |header | // +--+--+-------+--+-------+--+-------+--+ // |ma|ex|cell |in|cell |in|cell |ex| // +--+--+-------+--+-------+--+-------+--+ // |ma|ex|cell |in|cell |in|cell |ex| // +--+--+-------+--+-------+--+-------+--+ // // margin - indentation for the whole table // extrapadding - left and right padding for the whole table // intrapadding - padding between columns // // // Layout Algorithm: // - Height is irrelevant // - Determine the usable horizontal space for N columns: // // usable = width - ma - (ex * 2) - (in * (N - 1)) // // - Look at every column, for every task, and determine the minimum and // maximum widths. The minimum is the length of the largest indivisible // word, and the maximum is the full length of the value. // - If there is sufficient terminal width to display every task using the // maximum width, then do so. // - If there is insufficient terminal width to display every task using the // minimum width, then there is no layout solution. Error. // - Otherwise there is a need for column wrapping. Calculate the overage, // which is the difference between the sum of the minimum widths and the // usable width. // - Start by using all the minimum column widths, and distribute the overage // among all columns, one character at a time, while the column width is // less than the maximum width, and while there is overage remaining. // // Note: a possible enhancement is to proportionally distribute the overage // according to average data length. // // Note: an enhancement to the 'no solution' problem is to simply force-break // the larger fields. If the widest field is W0, and the second widest // field is W1, then a solution may be achievable by reducing W0 --> W1. // std::string ViewTask::render (std::vector <Task>& data, std::vector <int>& sequence) { Timer timer; bool const obfuscate = Context::getContext ().config.getBoolean ("obfuscate"); bool const print_empty_columns = Context::getContext ().config.getBoolean ("print.empty.columns"); std::vector <Column*> nonempty_columns; std::vector <bool> nonempty_sort; // Determine minimal, ideal column widths. std::vector <int> minimal; std::vector <int> ideal; for (unsigned int i = 0; i < _columns.size (); ++i) { // Headers factor in to width calculations. unsigned int global_min = 0; unsigned int global_ideal = global_min; for (unsigned int s = 0; s < sequence.size (); ++s) { if ((int)s >= _truncate_lines && _truncate_lines != 0) break; if ((int)s >= _truncate_rows && _truncate_rows != 0) break; // Determine minimum and ideal width for this column. unsigned int min = 0; unsigned int ideal = 0; _columns[i]->measure (data[sequence[s]], min, ideal); if (min > global_min) global_min = min; if (ideal > global_ideal) global_ideal = ideal; // If a fixed-width column was just measured, there is no point repeating // the measurement for all tasks. if (_columns[i]->is_fixed_width ()) break; } if (print_empty_columns || global_min != 0) { unsigned int label_length = utf8_width (_columns[i]->label ()); if (label_length > global_min) global_min = label_length; if (label_length > global_ideal) global_ideal = label_length; minimal.push_back (global_min); ideal.push_back (global_ideal); } if (! print_empty_columns) { if (global_min != 0) // Column is nonempty { nonempty_columns.push_back (_columns[i]); nonempty_sort.push_back (_sort[i]); } else // Column is empty, drop it { // Note: This is safe to do because we set _columns = nonempty_columns // after iteration over _columns is finished. delete _columns[i]; } } } if (! print_empty_columns) { _columns = nonempty_columns; _sort = nonempty_sort; } int all_extra = _left_margin + (2 * _extra_padding) + ((_columns.size () - 1) * _intra_padding); // Sum the widths. int sum_minimal = std::accumulate (minimal.begin (), minimal.end (), 0); int sum_ideal = std::accumulate (ideal.begin (), ideal.end (), 0); // Calculate final column widths. int overage = _width - sum_minimal - all_extra; Context::getContext ().debug (format ("ViewTask::render min={1} ideal={2} overage={3} width={4}", sum_minimal + all_extra, sum_ideal + all_extra, overage, _width)); std::vector <int> widths; // Ideal case. Everything fits. if (_width == 0 || sum_ideal + all_extra <= _width) { widths = ideal; } // Not enough for minimum. else if (overage < 0) { Context::getContext ().error (format ("The report has a minimum width of {1} and does not fit in the available width of {2}.", sum_minimal + all_extra, _width)); widths = minimal; } // Perfect minimal width. else if (overage == 0) { widths = minimal; } // Extra space to share. else if (overage > 0) { widths = minimal; // Spread 'overage' among columns where width[i] < ideal[i] bool needed = true; while (overage && needed) { needed = false; for (unsigned int i = 0; i < _columns.size () && overage; ++i) { if (widths[i] < ideal[i]) { ++widths[i]; --overage; needed = true; } } } } // Compose column headers. unsigned int max_lines = 0; std::vector <std::vector <std::string>> headers; for (unsigned int c = 0; c < _columns.size (); ++c) { headers.push_back (std::vector <std::string> ()); _columns[c]->renderHeader (headers[c], widths[c], _sort[c] ? _sort_header : _header); if (headers[c].size () > max_lines) max_lines = headers[c].size (); } // Render column headers. std::string left_margin = std::string (_left_margin, ' '); std::string extra = std::string (_extra_padding, ' '); std::string intra = std::string (_intra_padding, ' '); std::string extra_odd = Context::getContext ().color () ? _extra_odd.colorize (extra) : extra; std::string extra_even = Context::getContext ().color () ? _extra_even.colorize (extra) : extra; std::string intra_odd = Context::getContext ().color () ? _intra_odd.colorize (intra) : intra; std::string intra_even = Context::getContext ().color () ? _intra_even.colorize (intra) : intra; std::string out; _lines = 0; for (unsigned int i = 0; i < max_lines; ++i) { out += left_margin + extra; for (unsigned int c = 0; c < _columns.size (); ++c) { if (c) out += intra; if (headers[c].size () < max_lines - i) out += _header.colorize (std::string (widths[c], ' ')); else out += headers[c][i]; } out += extra; // Trim right. out.erase (out.find_last_not_of (" ") + 1); out += "\n"; // Stop if the line limit is exceeded. if (++_lines >= _truncate_lines && _truncate_lines != 0) { Context::getContext ().time_render_us += timer.total_us (); return out; } } // Compose, render columns, in sequence. _rows = 0; std::vector <std::vector <std::string>> cells; for (unsigned int s = 0; s < sequence.size (); ++s) { max_lines = 0; // Apply color rules to task. Color rule_color; autoColorize (data[sequence[s]], rule_color); // Alternate rows based on |s % 2| bool odd = (s % 2) ? true : false; Color row_color; if (Context::getContext ().color ()) { row_color = odd ? _odd : _even; row_color.blend (rule_color); } for (unsigned int c = 0; c < _columns.size (); ++c) { cells.push_back (std::vector <std::string> ()); _columns[c]->render (cells[c], data[sequence[s]], widths[c], row_color); if (cells[c].size () > max_lines) max_lines = cells[c].size (); if (obfuscate) if (_columns[c]->type () == "string") for (unsigned int line = 0; line < cells[c].size (); ++line) cells[c][line] = obfuscateText (cells[c][line]); } // Listing breaks are simply blank lines inserted when a column value // changes. if (s > 0 && _breaks.size () > 0) { for (auto& b : _breaks) { if (data[sequence[s - 1]].get (b) != data[sequence[s]].get (b)) { out += "\n"; ++_lines; // Only want one \n, regardless of how many values change. break; } } } for (unsigned int i = 0; i < max_lines; ++i) { out += left_margin + (odd ? extra_odd : extra_even); for (unsigned int c = 0; c < _columns.size (); ++c) { if (c) { if (row_color.nontrivial ()) row_color._colorize (out, intra); else out += (odd ? intra_odd : intra_even); } if (i < cells[c].size ()) out += cells[c][i]; else row_color._colorize (out, std::string (widths[c], ' ')); } out += (odd ? extra_odd : extra_even); // Trim right. out.erase (out.find_last_not_of (" ") + 1); out += "\n"; // Stop if the line limit is exceeded. if (++_lines >= _truncate_lines && _truncate_lines != 0) { Context::getContext ().time_render_us += timer.total_us (); return out; } } cells.clear (); // Stop if the row limit is exceeded. if (++_rows >= _truncate_rows && _truncate_rows != 0) { Context::getContext ().time_render_us += timer.total_us (); return out; } } Context::getContext ().time_render_us += timer.total_us (); return out; } ////////////////////////////////////////////////////////////////////////////////
31.309645
165
0.568742
8-bit-fox
29f0c1430e78d71094dac153a029d154f4636694
2,346
cpp
C++
Codeforces/1~999/528/D.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
6
2018-12-30T06:16:54.000Z
2022-03-23T08:03:33.000Z
Codeforces/1~999/528/D.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
Codeforces/1~999/528/D.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdio> #include <cstring> #include <vector> typedef unsigned long long L; const int N = 1e6 + 61, P = 998244353, G = 114514; int pw(int x, int y) { int r = 1; for (; y; y >>= 1, x = (L)x * x % P) if (y & 1) r = (L)r * x % P; return r; } struct poly { std::vector<int> v; poly() {} poly(int n) : v(n) {} poly(const poly& rhs) : v(rhs.v) {} static int len(int n) { return 1 << (32 - __builtin_clz(n)); } inline size_t size() { return v.size(); } inline bool empty() { return v.empty(); } inline void resize(int n) { v.resize(n); } inline void clear() { v.clear(); } inline int& operator[](int i) { return v[i]; } void dft(int n) { static L tmp[N]; resize(n); if (n <= 1) return; for (int i = 0, ri = 0; i < n; i++) { tmp[i] = v[ri]; for (int k = n >> 1; (ri ^= k) < k;) k >>= 1; } for (int i = 1; i < n; i *= 2) { int wn = pw(G, (P - 1) / (i * 2)); for (int j = 0; j < n; j += i * 2) { L *a = tmp + j, *b = tmp + j + i; for (int k = 0, w = 1; k < i; k++, w = (L)w * wn % P) { int y = b[k] * w % P; b[k] = a[k] + P - y, a[k] += y; } } } for (int i = 0; i < n; i++) v[i] = tmp[i] % P; } void idft(int n) { dft(n); if (n <= 1) return; std::reverse(v.begin() + 1, v.end()); int tmp = P - (P - 1) / n; for (int& i : v) i = (L)i * tmp % P; } void mul(poly rhs) { int n = len(size() + rhs.size() - 1); dft(n), rhs.dft(n); for (int i = 0; i < n; i++) v[i] = (L)v[i] * rhs[i] % P; idft(n); } } a[4], b[4]; int last[5], mp[128], ans; char s[N], t[N]; int n, m, k; int main() { 'A'[mp] = 0, 'T'[mp] = 1, 'G'[mp] = 2, 'C'[mp] = 3; scanf("%d%d%d%s%s", &n, &m, &k, s, t); for (int i = 0; i < 4; i++) a[i].resize(n), b[i].resize(m); for (int i = 0; i < m; i++) b[t[i][mp]][m - i - 1] = 1; for (int i = 0; i < n; i++) s[i] = s[i][mp]; 0 [last] = 1 [last] = 2 [last] = 3 [last] = -1e9; for (int i = 0; i < n; i++) { s[i][last] = i; for (int j = 0; j < 4; j++) a[j][i] |= j[last] >= i - k; } 0 [last] = 1 [last] = 2 [last] = 3 [last] = 1e9; for (int i = n - 1; i >= 0; i--) { s[i][last] = i; for (int j = 0; j < 4; j++) a[j][i] |= j[last] <= i + k; } for (int i = 0; i < 4; i++) a[i].mul(b[i]); for (int i = m - 1; i < m + n - 1; i++) ans += (a[0][i] + a[1][i] + a[2][i] + a[3][i]) == m; printf("%d", ans); }
25.78022
63
0.43734
tiger0132
29f1b7b31532c9400dcf87453248b878c332fc12
1,873
cpp
C++
ShowDatabaseView.cpp
zswdjh/A_Functional_Database_Application
79583984aac3b8dfd007633ac0a1f39f7e2cb573
[ "MIT" ]
null
null
null
ShowDatabaseView.cpp
zswdjh/A_Functional_Database_Application
79583984aac3b8dfd007633ac0a1f39f7e2cb573
[ "MIT" ]
null
null
null
ShowDatabaseView.cpp
zswdjh/A_Functional_Database_Application
79583984aac3b8dfd007633ac0a1f39f7e2cb573
[ "MIT" ]
null
null
null
// // ShowDatabaseView.cpp // database // // Created by Vladi Iotov on 5/14/18. // Copyright © 2018 vladi. All rights reserved. // #include "ShowDatabaseView.hpp" namespace SF { //basic callback function...can be made more thorough easily... void ShowDatabaseView::printFileName(std::string& aFileName, std::ostream& aStream){ aStream << "\t" << aFileName << "\n"; } StatusResult ShowDatabaseView::traverseDirectoryByExtension(std::string& aExt, std::ostream& aStream){ DIR *dp; struct dirent *dirp; StatusResult result{false, gFilePathDNE}; if((dp = opendir(thePath.c_str())) == NULL) { return result; } size_t extLen = aExt.length(); while ((dirp = readdir(dp)) != NULL) { std::string currFile = std::string(dirp->d_name); //only print out filenames with valid extension //at a minimum filename is as long as extension if(currFile.length() > extLen){ //check if current file's extension matches requested std::string fileExt = currFile.substr(currFile.length()-extLen); if(fileExt == aExt){ currFile = currFile.substr(0, currFile.length()-extLen); //get rid of extension when printing printFileName(currFile, aStream); result = StatusResult{true}; } } } closedir(dp); return result; } StatusResult ShowDatabaseView::show(std::string& anExtension, std::ostream& aStream){ if(!traverseDirectoryByExtension(anExtension, aStream) ){ aStream << "\tThere are no available databases!\n"; } return StatusResult{true}; } }
30.209677
113
0.557928
zswdjh
29f550705b420d632e531ca65b32d5a2e07d034b
11,955
cc
C++
src/openvslam/match/stereo.cc
Patrixe/openvslam
8ec940dc4498e25bebd541939b8c25801f789f6f
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
1
2021-03-11T10:12:31.000Z
2021-03-11T10:12:31.000Z
src/openvslam/match/stereo.cc
Patrixe/openvslam
8ec940dc4498e25bebd541939b8c25801f789f6f
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
src/openvslam/match/stereo.cc
Patrixe/openvslam
8ec940dc4498e25bebd541939b8c25801f789f6f
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
1
2021-03-10T09:05:47.000Z
2021-03-10T09:05:47.000Z
#include "openvslam/match/stereo.h" #include "openvslam/data/keypoint.h" namespace openvslam { namespace match { stereo::stereo(const std::vector<cv::Mat>& left_image_pyramid, const std::vector<cv::Mat>& right_image_pyramid, data::keypoint_container &keypts_left, data::keypoint_container &keypts_right, const std::vector<float>& scale_factors, const std::vector<float>& inv_scale_factors, const float focal_x_baseline, const float true_baseline) : left_image_pyramid_(left_image_pyramid), right_image_pyramid_(right_image_pyramid), num_keypts_(keypts_left.size()), keypts_left_(keypts_left), keypts_right_(keypts_right), scale_factors_(scale_factors), inv_scale_factors_(inv_scale_factors), focal_x_baseline_(focal_x_baseline), true_baseline_(true_baseline), min_disp_(0.0f), max_disp_(focal_x_baseline_ / true_baseline_) {} void stereo::compute() const { // 画像の行ごとに,ORBで抽出した右画像の特徴点indexを格納しておく const auto indices_right_in_row = get_right_keypoint_indices_in_each_row(2.0); // 左画像の各特徴点についてサブピクセルで視差と深度を求める std::map<int, std::pair<int, data::keypoint&>> correlation_and_idx_left; #ifdef USE_OPENMP #pragma omp parallel for #endif int i = 0; int dismissed = 0; int dispsort = 0; int nonvalid = 0; for (auto &keypoint_left : keypts_left_) { auto &keypoint = keypoint_left.second; const auto scale_level_left = keypoint.get_cv_keypoint().octave; const float y_left = keypoint.get_cv_keypoint().pt.y; const float x_left = keypoint.get_cv_keypoint().pt.x; // 左画像の特徴点と同じ高さにある右画像の特徴点のindexを取得 -> マッチング候補 const auto& candidate_indices_right = indices_right_in_row.at(y_left); if (candidate_indices_right.empty()) { continue; } // 右画像のxの許容範囲を計算する const float min_x_right = x_left - max_disp_; const float max_x_right = x_left - min_disp_; if (max_x_right < 0) { continue; } // 左画像のidx_leftと特徴ベクトルが一番近いbest_idx_rightを探す unsigned int best_idx_right = 0; unsigned int best_hamm_dist = hamm_dist_thr_; find_closest_keypoints_in_stereo(keypoint.get_orb_descriptor_as_cv_mat(), scale_level_left, candidate_indices_right, min_x_right, max_x_right, best_idx_right, best_hamm_dist); // ハミング距離が閾値を満たさなければ破棄 if (hamm_dist_thr_ <= best_hamm_dist) { dismissed++; continue; } const auto& keypt_right = keypts_right_.at(best_idx_right); // パッチの相関を求めて,サブピクセルオーダーの視差を求める float best_x_right = -1.0f; float best_disp = -1.0f; float best_correlation = UINT_MAX; const auto is_valid = compute_subpixel_disparity(keypoint.get_cv_keypoint(), keypt_right.get_cv_keypoint(), best_x_right, best_disp, best_correlation); // 見つからなければ破棄 if (!is_valid) { nonvalid++; continue; } // 視差が有効範囲外であれば破棄 if (best_disp < min_disp_ || max_disp_ <= best_disp) { dispsort++; continue; } // 視差が範囲内であれば情報を保存する if (best_disp <= 0.0f) { // 視差が0の場合は微小量を設定しておく best_disp = 0.01f; best_x_right = x_left - best_disp; } // 計算結果をセット // depths, stereo_x_right についてはループごとに別のメモリ領域にアクセスするのでcritical指定は必要ない keypoint.set_depth(focal_x_baseline_ / best_disp); keypoint.set_stereo_x_offset(best_x_right); // こっちはcritical指定が必要 #ifdef USE_OPENMP #pragma omp critical #endif { correlation_and_idx_left.insert(std::make_pair(keypoint.get_id(), std::make_pair(best_correlation, std::reference_wrapper<data::keypoint>(keypoint)))); } } // 相関の中央値を求める // std::sort(correlation_and_idx_left.begin(), correlation_and_idx_left.end(), // [] (const std::pair<int, std::pair<int, data::keypoint&>> &left, // const std::pair<int, std::pair<int, data::keypoint&>> &right) { // return left.second.first < right.second.first; // } // ); std::vector<std::pair<int, std::reference_wrapper<data::keypoint>>> correlations; for (const auto &correlation_pairs : correlation_and_idx_left) { correlations.emplace_back(correlation_pairs.second); } std::sort(correlations.begin(), correlations.end(), [] (const std::pair<int, data::keypoint&> &left, const std::pair<int, data::keypoint&> &right) { return left.first < right.first; } ); const auto median_i = correlations.size() / 2; const float median_correlation = correlation_and_idx_left.empty() ? 0.0f : correlations.at(median_i).first; // const auto median_i = correlation_and_idx_left.size() / 2; // const float median_correlation = correlation_and_idx_left.empty() // ? 0.0f // : correlation_and_idx_left.at(median_i).first; // 相関の中央値x2より相関が弱いものは破棄する const float correlation_thr = 2.0 * median_correlation; // 相関の中央値x2を閾値としているので,iはmedian_iから始めればよい int j = 0; for (unsigned int correlation_index = median_i; correlation_index < correlations.size(); correlation_index++) { auto correlation_pair = correlations.at(correlation_index); const auto correlation = correlation_pair.first; auto keypoint = correlation_pair.second; if (correlation_thr < correlation) { // TODO maybe we need to delete the points here, as they could not be matched keypoint.get().set_depth(-1); keypoint.get().set_stereo_x_offset(-1); } else { j++; } } j = -1; } std::vector<std::vector<unsigned int>> stereo::get_right_keypoint_indices_in_each_row(const float margin) const { // 画像の行ごとに,ORBで抽出した右画像の特徴点indexを格納しておく const unsigned int num_img_rows = left_image_pyramid_.at(0).rows; std::vector<std::vector<unsigned int>> indices_right_in_row(num_img_rows, std::vector<unsigned int>()); for (unsigned int row = 0; row < num_img_rows; ++row) { indices_right_in_row.at(row).reserve(100); } for (const auto& keypoint_right : keypts_right_) { // 右画像の特徴点のy座標を取得 const auto& keypt_right = keypoint_right.second; const float y_right = keypt_right.get_cv_keypoint().pt.y; // スケールに応じて座標の不定性を設定 const float r = margin * scale_factors_.at(keypt_right.get_cv_keypoint().octave); // 上端と下端を計算 const int max_r = cvCeil(y_right + r); const int min_r = cvFloor(y_right - r); // 上端と下端の間の行番号すべてについて,特徴点indexを保存しておく for (int row_right = min_r; row_right <= max_r; ++row_right) { indices_right_in_row.at(row_right).push_back(keypoint_right.first); } } return indices_right_in_row; } void stereo::find_closest_keypoints_in_stereo(const cv::Mat& desc_left, const int scale_level_left, const std::vector<unsigned int>& candidate_indices_right, const float min_x_right, const float max_x_right, unsigned int& best_idx_right, unsigned int& best_hamm_dist) const { best_idx_right = 0; best_hamm_dist = hamm_dist_thr_; // 左画像の特徴点と右画像の各特徴点のハミング距離を計算する // 左画像の特徴点に対して,一番近い右画像の特徴点indexを取得する -> best_idx_right for (const auto idx_right : candidate_indices_right) { const auto& keypt_right = keypts_right_.at(idx_right); // ORBスケールが大きく異なる場合は破棄 if (keypt_right.get_cv_keypoint().octave < scale_level_left - 1 || keypt_right.get_cv_keypoint().octave > scale_level_left + 1) { continue; } // 視差をチェックして許容範囲外だったら破棄 const float x_right = keypt_right.get_cv_keypoint().pt.x; if (x_right < min_x_right || max_x_right < x_right) { continue; } // ハミング距離を計算 const auto& desc_right = keypt_right.get_orb_descriptor_as_cv_mat(); const unsigned int hamm_dist = match::compute_descriptor_distance_32(desc_left, desc_right); if (hamm_dist < best_hamm_dist) { best_idx_right = idx_right; best_hamm_dist = hamm_dist; } } } bool stereo::compute_subpixel_disparity(const cv::KeyPoint& keypt_left, const cv::KeyPoint& keypt_right, float& best_x_right, float& best_disp, float& best_correlation) const { // 最もハミング距離が近い右画像の特徴点 const float x_right = keypt_right.pt.x; // スケールした画像でパッチの相関を計算するので,座標をスケール倍に変換する const float inv_scale_factor = inv_scale_factors_.at(keypt_left.octave); const int scaled_x_left = cvRound(keypt_left.pt.x * inv_scale_factor); const int scaled_y_left = cvRound(keypt_left.pt.y * inv_scale_factor); const int scaled_x_right = cvRound(x_right * inv_scale_factor); // パッチの移動範囲を計算し,範囲外であれば破棄 constexpr int win_size = 5; constexpr int slide_width = 5; const int ini_x = scaled_x_right - slide_width - win_size; const int end_x = scaled_x_right + slide_width + win_size; if (ini_x < 0 || right_image_pyramid_.at(keypt_left.octave).cols <= end_x) { return false; } // 特徴点周辺画素の相関を計算して,放物線フィッティングによりサブピクセルオーダーの視差を求める best_correlation = UINT_MAX; int best_offset = 0; std::vector<float> correlations(2 * slide_width + 1, -1); // 左画像のパッチを抽出する auto patch_left = left_image_pyramid_.at(keypt_left.octave) .rowRange(scaled_y_left - win_size, scaled_y_left + win_size + 1) .colRange(scaled_x_left - win_size, scaled_x_left + win_size + 1); patch_left.convertTo(patch_left, CV_32F); patch_left -= patch_left.at<float>(win_size, win_size) * cv::Mat::ones(patch_left.rows, patch_left.cols, CV_32F); for (int offset = -slide_width; offset <= +slide_width; ++offset) { // 右画像のパッチを抽出する auto patch_right = right_image_pyramid_.at(keypt_left.octave) .rowRange(scaled_y_left - win_size, scaled_y_left + win_size + 1) .colRange(scaled_x_right + offset - win_size, scaled_x_right + offset + win_size + 1); patch_right.convertTo(patch_right, CV_32F); patch_right -= patch_right.at<float>(win_size, win_size) * cv::Mat::ones(patch_right.rows, patch_right.cols, CV_32F); // L1相関を求める const float correlation = cv::norm(patch_left, patch_right, cv::NORM_L1); if (correlation < best_correlation) { best_correlation = correlation; best_offset = offset; } correlations.at(slide_width + offset) = correlation; } if (best_offset == -slide_width || best_offset == slide_width) { return false; } // 一番相関が強い点を中心に,3点の相関値を取り出して放物線をフィッティングする const float correlation_1 = correlations.at(slide_width + best_offset - 1); const float correlation_2 = correlations.at(slide_width + best_offset); const float correlation_3 = correlations.at(slide_width + best_offset + 1); // best_offsetからの平行移動量を計算する // x_delta : (-1, correlation_1),(0, correlation_2),(+1, correlation_1)の3点を通る放物線の頂点座標 const float x_delta = (correlation_1 - correlation_3) / (2.0 * (correlation_1 + correlation_3) - 4.0 * correlation_2); if (x_delta < -1.0 || 1.0 < x_delta) { return false; } // 元の画像での視差を計算する best_x_right = scale_factors_.at(keypt_left.octave) * (scaled_x_right + best_offset + x_delta); best_disp = keypt_left.pt.x - best_x_right; return true; } } // namespace match } // namespace openvslam
42.09507
163
0.643831
Patrixe
29f9aaa74cfa827916c07a07ab261333311fc897
4,130
cpp
C++
src/cpp/transport/serial/SerialAgentLinux.cpp
vibnwis/Micro-XRCE-DDS-Agent
57ff677855b75d79657b7c20110241e6c1eec351
[ "Apache-2.0" ]
null
null
null
src/cpp/transport/serial/SerialAgentLinux.cpp
vibnwis/Micro-XRCE-DDS-Agent
57ff677855b75d79657b7c20110241e6c1eec351
[ "Apache-2.0" ]
null
null
null
src/cpp/transport/serial/SerialAgentLinux.cpp
vibnwis/Micro-XRCE-DDS-Agent
57ff677855b75d79657b7c20110241e6c1eec351
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 <uxr/agent/transport/serial/SerialAgentLinux.hpp> #include <uxr/agent/utils/Conversion.hpp> #include <uxr/agent/logger/Logger.hpp> #include <unistd.h> namespace eprosima { namespace uxr { SerialAgent::SerialAgent( uint8_t addr, Middleware::Kind middleware_kind) : Server<SerialEndPoint>{middleware_kind} , addr_{addr} , poll_fd_{} , buffer_{0} , serial_io_( addr, std::bind(&SerialAgent::write_data, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), std::bind(&SerialAgent::read_data, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)) {} size_t SerialAgent::write_data( uint8_t* buf, size_t len, TransportRc& transport_rc) { size_t rv = 0; ssize_t bytes_written = ::write(poll_fd_.fd, buf, len); if ((0 < bytes_written) && size_t(bytes_written) == len) { rv = size_t(bytes_written); } else { transport_rc = TransportRc::server_error; } return rv; } size_t SerialAgent::read_data( uint8_t* buf, size_t len, int timeout, TransportRc& transport_rc) { size_t rv = 0; int poll_rv = poll(&poll_fd_, 1, timeout); if (0 < poll_rv) { ssize_t bytes_read = read(poll_fd_.fd, buf, len); if (0 < bytes_read) { rv = size_t(bytes_read); } else { transport_rc = TransportRc::server_error; } } else { transport_rc = (poll_rv == 0) ? TransportRc::timeout_error : TransportRc::server_error; } return rv; } bool SerialAgent::recv_message( InputPacket<SerialEndPoint>& input_packet, int timeout, TransportRc& transport_rc) { bool rv = false; uint8_t remote_addr; size_t bytes_read = serial_io_.read_msg(buffer_,sizeof (buffer_), remote_addr, timeout, transport_rc); if (0 < bytes_read) { input_packet.message.reset(new InputMessage(buffer_, static_cast<size_t>(bytes_read))); input_packet.source = SerialEndPoint(remote_addr); rv = true; uint32_t raw_client_key; if (Server<SerialEndPoint>::get_client_key(input_packet.source, raw_client_key)) { UXR_AGENT_LOG_MESSAGE( UXR_DECORATE_YELLOW("[==>> SER <<==]"), raw_client_key, input_packet.message->get_buf(), input_packet.message->get_len()); } } return rv; } bool SerialAgent::send_message( OutputPacket<SerialEndPoint> output_packet, TransportRc& transport_rc) { bool rv = false; size_t bytes_written = serial_io_.write_msg( output_packet.message->get_buf(), output_packet.message->get_len(), output_packet.destination.get_addr(), transport_rc); if ((0 < bytes_written) && (bytes_written == output_packet.message->get_len())) { rv = true; uint32_t raw_client_key; if (Server<SerialEndPoint>::get_client_key(output_packet.destination, raw_client_key)) { UXR_AGENT_LOG_MESSAGE( UXR_DECORATE_YELLOW("[** <<SER>> **]"), raw_client_key, output_packet.message->get_buf(), output_packet.message->get_len()); } } return rv; } } // namespace uxr } // namespace eprosima
29.71223
143
0.623971
vibnwis
29f9d8e0cdf442696acf8a8a2c0a153c1487624d
434
cpp
C++
P1226.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P1226.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P1226.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> #include <string.h> using namespace std; int main(){ long int b,b1,p,p1,k,s=1; scanf("%ld%ld%ld",&b,&p,&k); b1=b; p1=p; b=b%k; if(p==0){ s=1%k; printf("%ld^%ld mod %ld=%ld",b1,p1,k,s); return 0; } while(p>0){ if(p%2==1)s=(s*b)%k; p=p/2; b=(b*b)%k; } printf("%ld^%ld mod %ld=%ld",b1,p1,k,s); return 0; }
17.36
48
0.449309
AndrewWayne
29fa0ff9970a98bcb95ec0d3a35485da1cca229c
9,730
cc
C++
test/test_marshalling.cc
planthaber/typelib
75b22b66c04d66f918461c47bd866f5f7f985a90
[ "CECILL-B" ]
null
null
null
test/test_marshalling.cc
planthaber/typelib
75b22b66c04d66f918461c47bd866f5f7f985a90
[ "CECILL-B" ]
null
null
null
test/test_marshalling.cc
planthaber/typelib
75b22b66c04d66f918461c47bd866f5f7f985a90
[ "CECILL-B" ]
null
null
null
#include <boost/test/auto_unit_test.hpp> #include <test/testsuite.hh> #include <typelib/utilmm/configset.hh> #include <typelib/pluginmanager.hh> #include <typelib/importer.hh> #include <typelib/typemodel.hh> #include <typelib/registry.hh> #include <typelib/value.hh> #include <typelib/value_ops.hh> #include <test/test_cimport.1> #include <string.h> using namespace Typelib; using namespace std; BOOST_AUTO_TEST_CASE( test_marshalling_simple ) { // Get the test file into repository Registry registry; PluginManager::self manager; auto_ptr<Importer> importer(manager->importer("tlb")); utilmm::config_set config; BOOST_REQUIRE_NO_THROW( importer->load(TEST_DATA_PATH("test_cimport.tlb"), config, registry) ); /* Check a simple structure which translates into MEMCPY */ { Type const& type = *registry.get("/A"); A a; memset(&a, 1, sizeof(A)); a.a = 10000; a.b = 1000; a.c = 100; a.d = 10; vector<uint8_t> buffer = dump(Value(&a, type)); size_t expected_dump_size = offsetof(A, d) + sizeof(a.d); BOOST_REQUIRE_EQUAL( buffer.size(), expected_dump_size); BOOST_REQUIRE( !memcmp(&buffer[0], &a, expected_dump_size) ); A reloaded; load(Value(&reloaded, type), buffer); BOOST_REQUIRE( !memcmp(&reloaded, &a, expected_dump_size) ); // Try (in order) // - smaller type // - bigger type // - bigger buffer // - smaller buffer BOOST_REQUIRE_THROW(load(Value(&reloaded, *registry.build("/int[200]")), buffer), std::runtime_error); BOOST_REQUIRE_THROW(load(Value(&reloaded, *registry.get("/int")), buffer), std::runtime_error); buffer.resize(buffer.size() + 2); BOOST_REQUIRE_THROW(load(Value(&reloaded, type), buffer), std::runtime_error); buffer.resize(buffer.size() - 4); BOOST_REQUIRE_THROW(load(Value(&reloaded, type), buffer), std::runtime_error); } /* Now, insert SKIPS into it */ { A a; size_t align1 = offsetof(A, b) - sizeof(a.a); size_t align2 = offsetof(A, c) - sizeof(a.b) - offsetof(A, b); size_t align3 = offsetof(A, d) - sizeof(a.c) - offsetof(A, c); size_t align4 = sizeof(A) - sizeof(a.d) - offsetof(A, d); size_t raw_ops[] = { MemLayout::FLAG_MEMCPY, sizeof(long long), MemLayout::FLAG_SKIP, align1, MemLayout::FLAG_MEMCPY, sizeof(int), MemLayout::FLAG_SKIP, align2, MemLayout::FLAG_MEMCPY, sizeof(char), MemLayout::FLAG_SKIP, align3, MemLayout::FLAG_MEMCPY, sizeof(short) }; MemoryLayout ops; ops.insert(ops.end(), raw_ops, raw_ops + 14); Type const& type = *registry.get("/A"); memset(&a, 1, sizeof(A)); a.a = 10000; a.b = 1000; a.c = 100; a.d = 10; vector<uint8_t> buffer; dump(Value(&a, type), buffer, ops); BOOST_REQUIRE_EQUAL( sizeof(A) - align1 - align2 - align3 - align4, buffer.size()); BOOST_REQUIRE_EQUAL( *reinterpret_cast<long long*>(&buffer[0]), a.a ); A reloaded; memset(&reloaded, 2, sizeof(A)); load(Value(&reloaded, type), buffer, ops); BOOST_REQUIRE(memcmp(&a, &reloaded, sizeof(A)) < 0); BOOST_REQUIRE_EQUAL(a.a, reloaded.a); BOOST_REQUIRE_EQUAL(a.b, reloaded.b); BOOST_REQUIRE_EQUAL(a.c, reloaded.c); BOOST_REQUIRE_EQUAL(a.d, reloaded.d); } // And now check the array semantics { B b; for (unsigned int i = 0; i < sizeof(b); ++i) reinterpret_cast<uint8_t*>(&b)[i] = rand(); size_t raw_ops[] = { MemLayout::FLAG_MEMCPY, offsetof(B, c), MemLayout::FLAG_ARRAY, 100, MemLayout::FLAG_MEMCPY, sizeof(b.c[0]), MemLayout::FLAG_END, MemLayout::FLAG_MEMCPY, sizeof(B) - offsetof(B, d) }; MemoryLayout ops; ops.insert(ops.end(), raw_ops, raw_ops + 9); Type const& type = *registry.get("/B"); vector<uint8_t> buffer; dump(Value(&b, type), buffer, ops); BOOST_REQUIRE_EQUAL( sizeof(B), buffer.size()); BOOST_REQUIRE(!memcmp(&buffer[0], &b, sizeof(B))); B reloaded; load(Value(&reloaded, type), buffer, ops); BOOST_REQUIRE(!memcmp(&b, &reloaded, sizeof(B))); } } template<typename T> size_t CHECK_SIMPLE_VALUE(vector<uint8_t> const& buffer, size_t offset, T value) { BOOST_REQUIRE_EQUAL(value, *reinterpret_cast<T const*>(&buffer[offset])); return offset + sizeof(T); } template<typename T> size_t CHECK_VECTOR_VALUE(vector<uint8_t> const& buffer, size_t offset, vector<T> const& value) { // First, check for the size offset = CHECK_SIMPLE_VALUE(buffer, offset, static_cast<uint64_t>(value.size())); // Then for the elements for (size_t i = 0; i < value.size(); ++i) offset = CHECK_SIMPLE_VALUE(buffer, offset, value[i]); return offset; } BOOST_AUTO_TEST_CASE(test_marshalapply_containers) { // Get the test file into repository Registry registry; PluginManager::self manager; auto_ptr<Importer> importer(manager->importer("tlb")); utilmm::config_set config; BOOST_REQUIRE_NO_THROW( importer->load(TEST_DATA_PATH("test_cimport.tlb"), config, registry) ); StdCollections offset_discovery; uint8_t* base_ptr = reinterpret_cast<uint8_t*>(&offset_discovery); size_t off_dbl_vector = reinterpret_cast<uint8_t*>(&offset_discovery.dbl_vector) - base_ptr; size_t off_v8 = reinterpret_cast<uint8_t*>(&offset_discovery.v8) - base_ptr; size_t off_v_of_v = reinterpret_cast<uint8_t*>(&offset_discovery.v_of_v) - base_ptr; { StdCollections data; data.iv = 10; data.dbl_vector.resize(5); for (int i = 0; i < 5; ++i) data.dbl_vector[i] = 0.01 * i; data.v8 = -106; data.v_of_v.resize(5); for (int i = 0; i < 5; ++i) { data.v_of_v[i].resize(3); for (int j = 0; j < 3; ++j) data.v_of_v[i][j] = i * 10 + j; } data.v16 = 5235; data.v64 = 5230971546LL; Type const& type = *registry.get("/StdCollections"); vector<uint8_t> buffer = dump(Value(&data, type)); size_t size_without_trailing_padding = reinterpret_cast<uint8_t const*>(&data.padding) + sizeof(data.padding) - reinterpret_cast<uint8_t const*>(&data) - sizeof(std::vector<double>) - sizeof (std::vector< std::vector<double> >) + sizeof(double) * 20 // elements + 7 * sizeof(uint64_t); BOOST_REQUIRE_EQUAL( buffer.size(), size_without_trailing_padding ); CHECK_SIMPLE_VALUE(buffer, 0, data.iv); size_t pos = CHECK_VECTOR_VALUE(buffer, off_dbl_vector, data.dbl_vector); CHECK_SIMPLE_VALUE(buffer, pos, data.v8); pos = CHECK_SIMPLE_VALUE(buffer, pos + off_v_of_v - off_v8, static_cast<uint64_t>(data.v_of_v.size())); for (int i = 0; i < 5; ++i) pos = CHECK_VECTOR_VALUE(buffer, pos, data.v_of_v[i]); StdCollections reloaded; load(Value(&reloaded, type), buffer); BOOST_REQUIRE( data.iv == reloaded.iv ); BOOST_REQUIRE( data.dbl_vector == reloaded.dbl_vector ); BOOST_REQUIRE( data.v8 == reloaded.v8 ); BOOST_REQUIRE( data.v16 == reloaded.v16 ); BOOST_REQUIRE( data.v64 == reloaded.v64 ); BOOST_REQUIRE( data.padding == reloaded.padding ); // Now, add the trailing bytes back. The load method should be OK with // it size_t size_with_trailing_padding = sizeof(StdCollections) - sizeof(std::vector<double>) - sizeof (std::vector< std::vector<double> >) + sizeof(double) * 20 // elements + 7 * sizeof(uint64_t); // element counts buffer.insert(buffer.end(), size_with_trailing_padding - size_without_trailing_padding, 0); { StdCollections reloaded; load(Value(&reloaded, type), buffer); BOOST_REQUIRE( data.iv == reloaded.iv ); BOOST_REQUIRE( data.dbl_vector == reloaded.dbl_vector ); BOOST_REQUIRE( data.v8 == reloaded.v8 ); BOOST_REQUIRE( data.v16 == reloaded.v16 ); BOOST_REQUIRE( data.v64 == reloaded.v64 ); BOOST_REQUIRE( data.padding == reloaded.padding ); } } { StdCollections data; data.iv = 0; data.v8 = 1; data.v_of_v.resize(5); data.v16 = 2; data.v64 = 3; Type const& type = *registry.get("/StdCollections"); vector<uint8_t> buffer = dump(Value(&data, type)); size_t size_without_trailing_padding = reinterpret_cast<uint8_t const*>(&data.padding) + sizeof(data.padding) - reinterpret_cast<uint8_t const*>(&data); BOOST_REQUIRE_EQUAL( buffer.size(), size_without_trailing_padding - sizeof(std::vector<double>) - sizeof (std::vector< std::vector<double> >) + 7 * sizeof(uint64_t)); // element counts CHECK_SIMPLE_VALUE(buffer, 0, data.iv); size_t pos = CHECK_VECTOR_VALUE(buffer, off_dbl_vector, data.dbl_vector); CHECK_SIMPLE_VALUE(buffer, pos, data.v8); pos = CHECK_SIMPLE_VALUE(buffer, pos + off_v_of_v - off_v8, static_cast<uint64_t>(data.v_of_v.size())); for (int i = 0; i < 5; ++i) pos = CHECK_VECTOR_VALUE(buffer, pos, data.v_of_v[i]); } }
38.156863
125
0.601747
planthaber
29fb45ae3bec81fbbd45de192347835aa2590423
2,429
cpp
C++
fileaccessor.cpp
negasora/binaryninja-api
d26bfd9298d8696be1f52f2b2a4de3403c3871b5
[ "MIT" ]
null
null
null
fileaccessor.cpp
negasora/binaryninja-api
d26bfd9298d8696be1f52f2b2a4de3403c3871b5
[ "MIT" ]
null
null
null
fileaccessor.cpp
negasora/binaryninja-api
d26bfd9298d8696be1f52f2b2a4de3403c3871b5
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2017 Vector 35 LLC // // 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. #include "binaryninjaapi.h" using namespace BinaryNinja; using namespace std; uint64_t FileAccessor::GetLengthCallback(void* ctxt) { FileAccessor* file = (FileAccessor*)ctxt; return file->GetLength(); } size_t FileAccessor::ReadCallback(void* ctxt, void* dest, uint64_t offset, size_t len) { FileAccessor* file = (FileAccessor*)ctxt; return file->Read(dest, offset, len); } size_t FileAccessor::WriteCallback(void* ctxt, uint64_t offset, const void* src, size_t len) { FileAccessor* file = (FileAccessor*)ctxt; return file->Write(offset, src, len); } FileAccessor::FileAccessor() { m_callbacks.context = this; m_callbacks.getLength = GetLengthCallback; m_callbacks.read = ReadCallback; m_callbacks.write = WriteCallback; } FileAccessor::FileAccessor(BNFileAccessor* accessor): m_callbacks(*accessor) { } CoreFileAccessor::CoreFileAccessor(BNFileAccessor* accessor): FileAccessor(accessor) { } uint64_t CoreFileAccessor::GetLength() const { return m_callbacks.getLength(m_callbacks.context); } size_t CoreFileAccessor::Read(void* dest, uint64_t offset, size_t len) { return m_callbacks.read(m_callbacks.context, dest, offset, len); } size_t CoreFileAccessor::Write(uint64_t offset, const void* src, size_t len) { return m_callbacks.write(m_callbacks.context, offset, src, len); }
28.916667
92
0.765336
negasora
4b008be4fd16bfa8d9db0eef557cbf38c9023e00
481
hpp
C++
zxengine-core/include/scene/coms_vector.hpp
joeccane/ZxEngine
2df880ab7681022d58cd7d955dcffad65d53dab2
[ "MIT" ]
null
null
null
zxengine-core/include/scene/coms_vector.hpp
joeccane/ZxEngine
2df880ab7681022d58cd7d955dcffad65d53dab2
[ "MIT" ]
3
2020-08-08T18:15:20.000Z
2020-08-21T01:11:59.000Z
zxengine-core/include/scene/coms_vector.hpp
joeccane/zxengine
2df880ab7681022d58cd7d955dcffad65d53dab2
[ "MIT" ]
null
null
null
#pragma once #include "core.hpp" #include <memory_resource> namespace zx { using coms_list_memory_resource = std::pmr::synchronized_pool_resource; template<component_type T> using coms_vector = zx::vector<T>; struct coms_vector_resource { inline static coms_list_memory_resource resource = coms_list_memory_resource(std::pmr::pool_options{ 10, 256 }); template<component_type T> inline static coms_vector<T> create() { return coms_vector<T>(&resource); } }; }
22.904762
114
0.758836
joeccane
4b020cae6478e18f355339c56d4de5aeda83ff05
14,296
cpp
C++
src/nsc/Patch.cpp
suzukiplan/nsdlib
ae1d840adadbad3b55c205d661e4d80586eb73df
[ "Unlicense" ]
null
null
null
src/nsc/Patch.cpp
suzukiplan/nsdlib
ae1d840adadbad3b55c205d661e4d80586eb73df
[ "Unlicense" ]
null
null
null
src/nsc/Patch.cpp
suzukiplan/nsdlib
ae1d840adadbad3b55c205d661e4d80586eb73df
[ "Unlicense" ]
null
null
null
/******************************************************************************* NES Sound Driver & Library (NSD.lib) MML Compiler Copyright (c) 2012 A.Watanabe (S.W.), All rights reserved. For conditions of distribution and use, see copyright notice in "nsc.cpp". *******************************************************************************/ #include "StdAfx.h" #include "Patch.h" /****************************************************************/ /* グローバル変数(クラスだけど・・・) */ /****************************************************************/ extern OPSW* cOptionSW; //オプション情報へのポインタ変数 //============================================================== // コンストラクタ //-------------------------------------------------------------- // ●引数 // MMLfile* MML MMLファイルのオブジェクト // int _id パッチ番号 // ●返値 // 無し //============================================================== Patch::Patch(MMLfile* MML, int _id): m_id(_id) { //---------------------- //Local変数 // 定数定義 enum Command_ID_mml { Patch_MacroSet, Patch_Macro, Patch_C, Patch_Cis, Patch_D, Patch_Dis, Patch_E, Patch_F, Patch_Fis, Patch_G, Patch_Gis, Patch_A, Patch_Ais, Patch_B, Patch_Note, Patch_Off_Evoi, Patch_Off_Evol, Patch_Off_Em, Patch_Off_En, Patch_Evoi, Patch_Evol, Patch_Em, Patch_En, Patch_Gate_q, Patch_Gate_u, Patch_Voice, Patch_KeyShift, Patch_n163set, Patch_Sweep, Patch_Sub }; // これらは、MML構文で使えるコマンド。 const static Command_Info Command[] = { { "$$", Patch_MacroSet }, { "$", Patch_Macro }, { "c#", Patch_Cis }, { "d#", Patch_Dis }, { "f#", Patch_Fis }, { "g#", Patch_Gis }, { "a#", Patch_Ais }, { "c+", Patch_Cis }, { "d+", Patch_Dis }, { "f+", Patch_Fis }, { "g+", Patch_Gis }, { "a+", Patch_Ais }, { "d-", Patch_Cis }, { "e-", Patch_Dis }, { "g-", Patch_Fis }, { "a-", Patch_Gis }, { "b-", Patch_Ais }, { "c", Patch_C }, { "d", Patch_D }, { "e", Patch_E }, { "f", Patch_F }, { "g", Patch_G }, { "a", Patch_A }, { "b", Patch_B }, { "ど#", Patch_Cis }, { "れ#", Patch_Dis }, { "ふぁ#", Patch_Fis }, { "ふ#", Patch_Fis }, { "そ#", Patch_Gis }, { "ら#", Patch_Ais }, { "れ-", Patch_Cis }, { "み-", Patch_Dis }, { "そ-", Patch_Fis }, { "ら-", Patch_Gis }, { "し-", Patch_Ais }, { "ど", Patch_C }, { "れ", Patch_D }, { "み", Patch_E }, { "ふぁ", Patch_F }, { "ふ", Patch_F }, { "そ", Patch_G }, { "ら", Patch_A }, { "し", Patch_B }, { "ド#", Patch_Cis }, { "レ#", Patch_Dis }, { "ファ#", Patch_Fis }, { "フ#", Patch_Fis }, { "ソ#", Patch_Gis }, { "ラ#", Patch_Ais }, { "レ-", Patch_Cis }, { "ミ-", Patch_Dis }, { "ソ-", Patch_Fis }, { "ラ-", Patch_Gis }, { "シ-", Patch_Ais }, { "ド", Patch_C }, { "レ", Patch_D }, { "ミ", Patch_E }, { "ファ", Patch_F }, { "フ", Patch_F }, { "ソ", Patch_G }, { "ラ", Patch_A }, { "シ", Patch_B }, { "n", Patch_Note }, { "E@*", Patch_Off_Evoi }, { "Ev*", Patch_Off_Evol }, { "Em*", Patch_Off_Em }, { "En*", Patch_Off_En }, { "E@", Patch_Evoi }, { "Ev", Patch_Evol }, { "Em", Patch_Em }, { "En", Patch_En }, { "q", Patch_Gate_q }, { "u", Patch_Gate_u }, { "s", Patch_Sweep }, { "@NS", Patch_n163set }, { "@", Patch_Voice }, { "_", Patch_KeyShift }, { "S", Patch_Sub } }; int i; unsigned char cData; //------------------------------ //クラスの初期設定 setN(MML, 0); //ノート番号 0 の情報は必ず作成する。 //------------------------------ //コンパイル // { の検索 while(MML->cRead() != '{'){ if(MML->eof()){ MML->Err(_T("ブロックの開始を示す{が見つかりません。")); } } // } が来るまで、記述ブロック内をコンパイルする。 while((cData = MML->GetChar()) != '}'){ // } が来る前に、[EOF]が来たらエラー if( MML->eof() ){ MML->Err(_T("ブロックの終端を示す`}'がありません。")); } //1つ戻る MML->Back(); //各コマンド毎の処理 switch(MML->GetCommandID(Command, sizeof(Command)/sizeof(Command_Info))){ case(Patch_Macro): MML->CallMacro(); break; case(Patch_MacroSet): MML->SetMacro(1); break; case(Patch_C): setKey(MML, 0); break; case(Patch_Cis): setKey(MML, 1); break; case(Patch_D): setKey(MML, 2); break; case(Patch_Dis): setKey(MML, 3); break; case(Patch_E): setKey(MML, 4); break; case(Patch_F): setKey(MML, 5); break; case(Patch_Fis): setKey(MML, 6); break; case(Patch_G): setKey(MML, 7); break; case(Patch_Gis): setKey(MML, 8); break; case(Patch_A): setKey(MML, 9); break; case(Patch_Ais): setKey(MML, 10); break; case(Patch_B): setKey(MML, 11); break; case(Patch_Note): setN(MML, MML->GetInt()); break; case(Patch_Voice): if(m_now_Patch->fEvoi == true){ MML->Err(_T("音色エンベロープと同時に定義することはできません。")); } if(m_now_Patch->fVoi == true){ MML->Err(_T("音色の2重定義です。")); } i = MML->GetInt(); if( (i<0) || (i>255) ){ MML->Err(_T("音色は0〜255の範囲で指定してください。")); } m_now_Patch->iVoi = i; m_now_Patch->fVoi = true; m_now_Patch->sw_Evoi = false; break; case(Patch_Off_Evoi): MML->Err(_T("音色エンベロープは、@コマンドで無効にできます。")); break; case(Patch_Off_Evol): if(m_now_Patch->fEvol == true){ MML->Err(_T("音量エンベロープの2重定義です。")); } m_now_Patch->fEvol = true; m_now_Patch->sw_Evol = false; break; case(Patch_Off_Em): if(m_now_Patch->fEm == true){ MML->Err(_T("音程エンベロープの2重定義です。")); } m_now_Patch->fEm = true; m_now_Patch->sw_Em = false; break; case(Patch_Off_En): if(m_now_Patch->fEn == true){ MML->Err(_T("ノートエンベロープの2重定義です。")); } m_now_Patch->fEn = true; m_now_Patch->sw_En = false; break; case(Patch_Evoi): if(m_now_Patch->fEvoi == true){ MML->Err(_T("音色エンベロープの2重定義です。")); } if(m_now_Patch->fVoi == true){ MML->Err(_T("音色と同時に定義することはできません。")); } m_now_Patch->iEvoi = MML->GetInt(); m_now_Patch->fEvoi = true; m_now_Patch->sw_Evoi = true; break; case(Patch_Evol): if(m_now_Patch->fEvol == true){ MML->Err(_T("音量エンベロープの2重定義です。")); } m_now_Patch->iEvol = MML->GetInt(); m_now_Patch->fEvol = true; m_now_Patch->sw_Evol = true; break; case(Patch_Em): if(m_now_Patch->fEm == true){ MML->Err(_T("音程エンベロープの2重定義です。")); } m_now_Patch->iEm = MML->GetInt(); m_now_Patch->fEm = true; m_now_Patch->sw_Em = true; break; case(Patch_En): if(m_now_Patch->fEn == true){ MML->Err(_T("ノートエンベロープの2重定義です。")); } m_now_Patch->iEn = MML->GetInt(); m_now_Patch->fEn = true; m_now_Patch->sw_En = true; break; case(Patch_Gate_q): if(m_now_Patch->fGate_q == true){ MML->Err(_T("qコマンドの2重定義です。")); } m_now_Patch->iGate_q = MML->GetInt(); m_now_Patch->fGate_q = true; break; case(Patch_Gate_u): if(m_now_Patch->fGate_u == true){ MML->Err(_T("uコマンドの2重定義です。")); } cData = MML->GetChar(); if(cData == '0'){ i = 0; } else { MML->Back(); i = MML->GetLength(-1); } m_now_Patch->iGate_u = i; m_now_Patch->fGate_u = true; break; case(Patch_KeyShift): if(m_now_Patch->fKey == true){ MML->Err(_T("移調の2重定義です。")); } m_now_Patch->iKey = MML->GetInt(); m_now_Patch->fKey = true; break; case(Patch_Sweep): if(m_now_Patch->fSweep == true){ MML->Err(_T("sコマンドの2重定義です。")); } else { int iSpeed; int iDepth; char c; iSpeed = MML->GetInt(); cData = MML->GetChar(); if(cData != ','){ if( (iSpeed < 0) || (iSpeed > 255) ){ MML->Err(_T("sコマンドは0〜255の範囲で指定してください。")); } MML->Back(); c = (unsigned char)iSpeed; } else { if( (iSpeed < 0) || (iSpeed > 15) ){ MML->Err(_T("sコマンドの第1パラメータは0〜15の範囲で指定してください。")); } iDepth = MML->GetInt(); if( (iDepth < 0) || (iDepth > 15) ){ MML->Err(_T("sコマンドの第2パラメータは0〜15の範囲で指定してください。")); } c = (unsigned char)(((iSpeed & 0x0F) << 4) | (iDepth & 0x0F)); } m_now_Patch->iSweep = c; m_now_Patch->fSweep = true; } break; case(Patch_n163set): if(m_now_Patch->fVoi == true){ MML->Err(_T("@コマンドが既に指定されています。")); } if(m_now_Patch->fEvoi == true){ MML->Err(_T("E@コマンドが既に指定されています。")); } i = MML->GetInt(); if((i<0) || (i>252)){ MML->Err(_T("n16xの波形開始点は0〜252の範囲で指定してください。")); } if((i % 4) != 0){ MML->Err(_T("n16xの波形開始点は4の倍数で指定してください。")); } m_now_Patch->iVoi = i/4; m_now_Patch->fVoi = true; m_now_Patch->sw_Evoi = false; cData = MML->GetChar(); if(cData == ','){ if(m_now_Patch->fSweep == true){ MML->Err(_T("sコマンドが既に指定されています。")); } i = MML->GetInt(); if((i<4) || (i>256)){ MML->Err(_T("n16xのサンプル長は4〜256の範囲で指定してください。")); } if((i % 4) != 0){ MML->Err(_T("n16xのサンプル長は4の倍数で指定してください。")); } m_now_Patch->iSweep = (unsigned char)(64 - (i/4)); m_now_Patch->fSweep = true; } else { MML->Back(); } break; case(Patch_Sub): if(m_now_Patch->fSub == true){ MML->Err(_T("サブルーチンの2重定義です。")); } m_now_Patch->iSub = MML->GetInt(); m_now_Patch->fSub = true; cData = MML->GetChar(); if(cData == ','){ //最適化無効フラグ i = MML->GetInt(); switch(i){ case(0): m_now_Patch->fSub_opt=false; break; case(1): m_now_Patch->fSub_opt=true; break; default: MML->Err(_T("サブルーチンの最適化フラグは0〜1の範囲で指定してください。")); break; } } else { MML->Back(); } break; //unknown command default: MML->Err(_T("unknown command")); break; } } //Local Macroの解放 MML->DeleteMacro(1); //Debug message (うざい程出力するので注意。) if(cOptionSW->cDebug & 0x01){ DebugMsg(); } } //============================================================== // デストラクタ //-------------------------------------------------------------- // ●引数 // 無し // ●返値 // 無し //============================================================== Patch::~Patch(void) { //---------------------- //Local変数 map<unsigned int, patch_scrap*>::iterator itPatch; //---------------------- //Delete Class if(!m_Patch.empty()){ itPatch = m_Patch.begin(); while(itPatch != m_Patch.end()){ delete itPatch->second; itPatch++; } m_Patch.clear(); } } //============================================================== // デバッグ用 //-------------------------------------------------------------- // ●引数 // 無し // ●返値 // 無し //============================================================== void Patch::DebugMsg(void) { //---------------------- //Local変数 map<unsigned int, patch_scrap*>::iterator itPatch; //---------------------- //Delete Class cout << "==== [ Patch(" << m_id << ") ] ====" << endl; if(!m_Patch.empty()){ itPatch = m_Patch.begin(); while(itPatch != m_Patch.end()){ m_now_Patch = itPatch->second; cout << " n" << itPatch->first; if(get_fGate_q()){ cout << " q" << get_iGate_q(); }; if(get_fGate_u()){ cout << " u" << get_iGate_u(); }; if(get_fSub()){ cout << " S" << get_iSub() << "," << get_fSub_opt(); }; if(get_fKey()){ cout << " _" << get_iKey(); }; if(get_fSweep()){cout << " s" << (int)get_iSweep(); }; if(get_fVoi()){ cout << " @" << get_iVoi(); }; if(get_fEvoi()){cout << " E@" << get_iEvoi(); }; if(get_fEvol()){ if(get_sw_Evol()){ cout << " Ev*"; } else { cout << " Ev" << get_iEvol(); } }; if(get_fEm()){ if(get_sw_Em()){ cout << " Em*"; } else { cout << " Em" << get_iEm(); } }; if(get_fEn()){ if(get_sw_En()){ cout << " En*"; } else { cout << " En" << get_iEn(); } }; cout << endl; itPatch++; } } } //============================================================== // 設定 //-------------------------------------------------------------- // ●引数 // MMLfile* MML MMLファイルのオブジェクト // int key キー番号(0:C / 1:Cis / ...) // ●返値 // 無し //============================================================== void Patch::setKey(MMLfile* MML, int key) { setN(MML, ((MML->GetInt()-1) * 12) + key); } //============================================================== // 設定 //-------------------------------------------------------------- // ●引数 // MMLfile* MML MMLファイルのオブジェクト // int note ノート番号 // ●返値 // 無し //============================================================== void Patch::setN(MMLfile* MML, int note) { if((note<0) || (note>255)){ MML->Err(_T("音階の範囲を超えています。")); } //パッチの設定 m_kn = note; if(m_Patch.count(m_kn) != 0){ //既存パッチのロード m_now_Patch = m_Patch[m_kn]; } else { //パッチの新規作成 m_now_Patch = new patch_scrap; m_Patch[m_kn] = m_now_Patch; m_now_Patch->fVoi = false; m_now_Patch->fEvoi = false; m_now_Patch->fEvol = false; m_now_Patch->fEm = false; m_now_Patch->fEn = false; m_now_Patch->fKey = false; m_now_Patch->fSweep = false; m_now_Patch->fSub = false; m_now_Patch->fSub_opt= false; m_now_Patch->fGate_q = false; m_now_Patch->fGate_u = false; m_now_Patch->sw_Evoi= false; m_now_Patch->sw_Evol= false; m_now_Patch->sw_Em = false; m_now_Patch->sw_En = false; } } //============================================================== // //-------------------------------------------------------------- // ●引数 // int note ノート番号 // ●返値 // //============================================================== void Patch::setNote(int i) { bool f_set = false; m_kn = i; while(m_kn > 0){ if(m_Patch.count(m_kn) != 0){ f_set = true; break; } else { m_kn--; } } m_now_Patch = m_Patch[m_kn]; }
21.53012
81
0.452084
suzukiplan
4b0238ed4664c068e9acc6eee999e9c2d4cc3d12
48
hpp
C++
src/boost_type_traits_remove_pointer.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_type_traits_remove_pointer.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_type_traits_remove_pointer.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/type_traits/remove_pointer.hpp>
24
47
0.833333
miathedev
4b039e26368685770670a55357fb641e032cb230
1,488
cpp
C++
src/Evolution/Systems/NewtonianEuler/Characteristics.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
src/Evolution/Systems/NewtonianEuler/Characteristics.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
src/Evolution/Systems/NewtonianEuler/Characteristics.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Evolution/Systems/NewtonianEuler/Characteristics.hpp" #include "DataStructures/DataVector.hpp" #include "DataStructures/Tensor/EagerMath/DotProduct.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "Utilities/GenerateInstantiations.hpp" #include "Utilities/MakeArray.hpp" // IWYU pragma: no_forward_declare Tensor /// \cond namespace NewtonianEuler { template <size_t Dim> std::array<DataVector, Dim + 2> characteristic_speeds( const tnsr::I<DataVector, Dim>& velocity, const Scalar<DataVector>& sound_speed_squared, const tnsr::i<DataVector, Dim>& normal) noexcept { const DataVector sound_speed = sqrt(get(sound_speed_squared)); auto characteristic_speeds = make_array<Dim + 2>(DataVector(get(dot_product(velocity, normal)))); characteristic_speeds[0] -= sound_speed; characteristic_speeds[Dim + 1] += sound_speed; return characteristic_speeds; } } // namespace NewtonianEuler #define DIM(data) BOOST_PP_TUPLE_ELEM(0, data) #define INSTANTIATE(_, data) \ template std::array<DataVector, DIM(data) + 2> \ NewtonianEuler::characteristic_speeds( \ const tnsr::I<DataVector, DIM(data)>& velocity, \ const Scalar<DataVector>& sound_speed_squared, \ const tnsr::i<DataVector, DIM(data)>& normal) noexcept; GENERATE_INSTANTIATIONS(INSTANTIATE, (1, 2, 3)) #undef DIM #undef INSTANTIATE /// \endcond
31
74
0.728495
marissawalker
4b03d259476887e50fcbfdadfd166a66e6991bf1
389
cpp
C++
ieee_sep/SubscriptionBase.cpp
Tylores/ieee_sep
1928bed8076f4bfe702d34e436c6a85f197b0832
[ "BSD-2-Clause" ]
null
null
null
ieee_sep/SubscriptionBase.cpp
Tylores/ieee_sep
1928bed8076f4bfe702d34e436c6a85f197b0832
[ "BSD-2-Clause" ]
null
null
null
ieee_sep/SubscriptionBase.cpp
Tylores/ieee_sep
1928bed8076f4bfe702d34e436c6a85f197b0832
[ "BSD-2-Clause" ]
null
null
null
/////////////////////////////////////////////////////////// // SubscriptionBase.cpp // Implementation of the Class SubscriptionBase // Created on: 13-Apr-2020 2:51:43 PM // Original author: svanausdall /////////////////////////////////////////////////////////// #include "SubscriptionBase.h" SubscriptionBase::SubscriptionBase(){ } SubscriptionBase::~SubscriptionBase(){ }
20.473684
59
0.506427
Tylores
4b0893fec3b111d8471368806bc672a62439a849
1,507
cpp
C++
codes/CF/1520/hackE.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
2
2021-03-07T03:34:02.000Z
2021-03-09T01:22:21.000Z
codes/CF/1520/hackE.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T15:01:23.000Z
2021-03-27T15:55:34.000Z
codes/CF/1520/hackE.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T05:02:33.000Z
2021-03-27T05:02:33.000Z
//here take a cat #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <string> #include <utility> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <random> #include <chrono> #include <queue> #include <set> #define ll long long #define lb long double #define moorz multiset #define apple multimap #define pii pair<int, int> #define pb push_back #define mp make_pair #define ins insert #define cont continue #define pow2(n) (1 << (n)) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define add(a, b) (((a)%mod + (b)%mod)%mod) #define mul(a, b) (((a)%mod * (b)%mod)%mod) #define init(arr, val) memset(arr, val, sizeof(arr)) #define bckt(arr, val, sz) memset(arr, val, sizeof(arr[0]) * (sz)) #define uid(a, b) uniform_int_distribution<int>(a, b)(rng) #define tern(a, b, c) ((a) ? (b) : (c)) #define feq(a, b) (fabs(a - b) < eps) #define pbenq priority_queue #define moo printf #define oom scanf #define mool puts("") #define loom getline #define orz assert //what if using geniousities in my macros //will boost my chances at ac? //might as well try it out const lb eps = 1e-9; const ll mod = 1e9 + 7; const int MX = 2e5 +10, int_max = 0x3f3f3f3f; using namespace std; int main(){ cin.tie(0) -> sync_with_stdio(0); mt19937_64 rng(0); int n = 2e3; moo("%d %d 1000000000\n", n, n); for(int i = 0; i<n; i++){ for(int j = 0; j<n-1; j++){ moo("%d ", rng()%(ll)(1e9)); } moo("1\n"); } return 0; }
22.161765
66
0.637691
chessbot108
4b09f9ca6644870541cb0b44c03ee36ccec68e0d
1,297
cpp
C++
typical_dp/g.cpp
KoukiNAGATA/c-
ae51bacb9facb936a151dd777beb6688383a2dcd
[ "MIT" ]
null
null
null
typical_dp/g.cpp
KoukiNAGATA/c-
ae51bacb9facb936a151dd777beb6688383a2dcd
[ "MIT" ]
3
2021-03-31T01:39:25.000Z
2021-05-04T10:02:35.000Z
typical_dp/g.cpp
KoukiNAGATA/c-
ae51bacb9facb936a151dd777beb6688383a2dcd
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define REP(i, n) for (int i = 0; i < n; i++) #define REPR(i, n) for (int i = n - 1; i >= 0; i--) #define FOR(i, m, n) for (int i = m; i <= n; i++) #define FORR(i, m, n) for (int i = m; i >= n; i--) #define SORT(v, n) sort(v, v + n) #define MAX 100000 #define inf 1000000007 using namespace std; using ll = long long; using vll = vector<ll>; using vvll = vector<vector<ll>>; using P = pair<ll, ll>; using Graph = vector<vector<int>>; template <class T> void chmin(T &a, T b) { if (a > b) a = b; } template <class T> void chmax(T &a, T b) { if (a < b) a = b; } // 入力 int n, m; Graph g; // グラフ // メモ化再帰 int dp[100100]; int rec(int v) { if (dp[v] != -1) return dp[v]; // 既に更新済み int res = 0; // 生えてる頂点について再帰 for (auto nv : g[v]) { chmax(res, rec(nv) + 1); } return dp[v] = res; // メモしながらリターン } int main() { // cin高速化 cin.tie(0); ios::sync_with_stdio(false); cin >> n >> m; g.resize(n); int ans = 0; REP(i, m) { int x, y; cin >> x >> y; --x, --y; // 0-indexed にする g[x].push_back(y); } // 初期化 REP(i, n) dp[i] = -1; // 全ノードを一通り更新しながら答えを求める; REP(i, n) chmax(ans, rec(i)); cout << ans << "\n"; return 0; }
17.293333
51
0.48882
KoukiNAGATA
4b0ac826a362ab101f56aac402e50d26c0d684e8
2,143
cpp
C++
codechef_DSA/fencing.cpp
archit-1997/codechef
713051daa25b436fa63a0a7ac7fd769ac8a091ef
[ "MIT" ]
1
2021-01-27T16:37:34.000Z
2021-01-27T16:37:34.000Z
codechef_DSA/fencing.cpp
archit-1997/codechef
713051daa25b436fa63a0a7ac7fd769ac8a091ef
[ "MIT" ]
null
null
null
codechef_DSA/fencing.cpp
archit-1997/codechef
713051daa25b436fa63a0a7ac7fd769ac8a091ef
[ "MIT" ]
null
null
null
// Archit Singh // architsingh456@gmail.com // GitHub : archit-1997 #include <bits/stdc++.h> using namespace std; #define ll long long int #define ld long double #define line cout << "-------------" << endl; #define F first #define S second #define P pair<ll, ll> #define PP pair<pair<ll, ll>, ll> #define V vector<ll> #define VP vector<pair<ll, ll>> #define VS vector<string> #define VV vector<vector<ll>> #define VVP vector<vector<pair<ll, ll>>> #define pb push_back #define pf push_front #define PQ priority_queue<ll> #define PQ_G priority_queue<ll, vector<ll>, greater<ll>> #define line cout << "-------------" << endl; #define mod 1000000007 #define inf 1e18 #define setbits(x) __builtin_popcount(x) #define zerobits(x) __builtin_ctzll(x) #define ps(x, y) fixed << setprecision(y) << x #define w(x) \ ll x; \ cin >> x; \ while (x--) #define FOR(i, a, b) for (ll i = a; i < b; i++) #define ma(arr, n, type) type *arr = new type[n] void init() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); } int main() { init(); w(x) { ll n, m, k; cin >> n >> m >> k; set<P> s; map<ll, ll> hash_x, hash_y; FOR(i, 0, k) { ll a, b; cin >> a >> b; hash_x[a] = 1, hash_y[b] = 1; s.insert({a, b}); } ll ans = k * 4; for (auto it = s.begin(); it != s.end(); it++) { P p = *it; ll a = p.F, b = p.S; ll sub = 0; // x y+1 if (s.find({a, b + 1}) != s.end()) sub++; // x y-1 if (s.find({a, b - 1}) != s.end()) sub++; // x+1 y if (s.find({a + 1, b}) != s.end()) sub++; // x-1 y if (s.find({a - 1, b}) != s.end()) sub++; ans -= sub; } cout << ans << endl; } return 0; }
23.293478
81
0.451237
archit-1997
4b0ca02159d3e50667033e6b4ab4d78756c1339c
8,188
cpp
C++
library/text/test/src/test_tetengo.text.grapheme_splitting.grapheme_segment.cpp
tetengo/tetengo
66e0d03635583c25be4320171f3cc1e7f40a56e6
[ "MIT" ]
null
null
null
library/text/test/src/test_tetengo.text.grapheme_splitting.grapheme_segment.cpp
tetengo/tetengo
66e0d03635583c25be4320171f3cc1e7f40a56e6
[ "MIT" ]
41
2021-06-25T14:20:29.000Z
2022-01-16T02:50:50.000Z
library/text/test/src/test_tetengo.text.grapheme_splitting.grapheme_segment.cpp
tetengo/tetengo
66e0d03635583c25be4320171f3cc1e7f40a56e6
[ "MIT" ]
null
null
null
/*! \file \brief A grapheme segment. Copyright (C) 2019-2022 kaoru https://www.tetengo.org/ */ #include <algorithm> #include <cstddef> #include <iterator> #include <utility> #include <vector> #include <boost/preprocessor.hpp> #include <boost/test/unit_test.hpp> #include <tetengo/text/grapheme_splitting/grapheme_segment.hpp> namespace { using bp = tetengo::text::grapheme_splitting::grapheme_segment::break_property_type; constexpr bp graphemes[] = { bp::cr, bp::lf, bp::control, bp::extend, bp::zwj, bp::regional, bp::prepend, bp::spacing_mark, bp::l, bp::v, bp::t, bp::lv, bp::lvt, bp::other }; bool contains(const std::vector<std::pair<bp, bp>>& connectings, const bp from, const bp to) { return std::find(std::begin(connectings), std::end(connectings), std::make_pair(from, to)) != std::end(connectings); } } BOOST_AUTO_TEST_SUITE(test_tetengo) BOOST_AUTO_TEST_SUITE(text) BOOST_AUTO_TEST_SUITE(grapheme_splitting) BOOST_AUTO_TEST_SUITE(grapheme_segment) BOOST_AUTO_TEST_CASE(instance) { BOOST_TEST_PASSPOINT(); [[maybe_unused]] const auto& segment_maker = tetengo::text::grapheme_splitting::grapheme_segment::instance(); } BOOST_AUTO_TEST_CASE(segment_offsets) { BOOST_TEST_PASSPOINT(); const auto& segment_maker = tetengo::text::grapheme_splitting::grapheme_segment::instance(); { const auto offsets = segment_maker.segment_offsets({}); BOOST_TEST(std::empty(offsets)); } { std::vector<std::pair<bp, bp>> connectings; for (auto i = std::begin(graphemes); i != std::end(graphemes); ++i) { { const auto offsets = segment_maker.segment_offsets({ *i }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 1 })); } for (auto j = std::begin(graphemes); j != std::end(graphemes); ++j) { const auto offsets = segment_maker.segment_offsets({ *i, *j }); BOOST_CHECK(std::size(offsets) == 2U || std::size(offsets) == 3U); if (std::size(offsets) == 2) { BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 2 })); connectings.emplace_back(*i, *j); } else { BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 1, 2 })); } } } BOOST_TEST(std::size(connectings) == 54U); BOOST_TEST(contains(connectings, bp::cr, bp::lf)); BOOST_TEST(contains(connectings, bp::extend, bp::extend)); BOOST_TEST(contains(connectings, bp::extend, bp::zwj)); BOOST_TEST(contains(connectings, bp::extend, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::zwj, bp::extend)); BOOST_TEST(contains(connectings, bp::zwj, bp::zwj)); BOOST_TEST(contains(connectings, bp::zwj, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::zwj, bp::other)); BOOST_TEST(contains(connectings, bp::regional, bp::extend)); BOOST_TEST(contains(connectings, bp::regional, bp::zwj)); BOOST_TEST(contains(connectings, bp::regional, bp::regional)); BOOST_TEST(contains(connectings, bp::regional, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::prepend, bp::extend)); BOOST_TEST(contains(connectings, bp::prepend, bp::zwj)); BOOST_TEST(contains(connectings, bp::prepend, bp::regional)); BOOST_TEST(contains(connectings, bp::prepend, bp::prepend)); BOOST_TEST(contains(connectings, bp::prepend, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::prepend, bp::l)); BOOST_TEST(contains(connectings, bp::prepend, bp::v)); BOOST_TEST(contains(connectings, bp::prepend, bp::t)); BOOST_TEST(contains(connectings, bp::prepend, bp::lv)); BOOST_TEST(contains(connectings, bp::prepend, bp::lvt)); BOOST_TEST(contains(connectings, bp::prepend, bp::other)); BOOST_TEST(contains(connectings, bp::spacing_mark, bp::extend)); BOOST_TEST(contains(connectings, bp::spacing_mark, bp::zwj)); BOOST_TEST(contains(connectings, bp::spacing_mark, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::l, bp::extend)); BOOST_TEST(contains(connectings, bp::l, bp::zwj)); BOOST_TEST(contains(connectings, bp::l, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::l, bp::l)); BOOST_TEST(contains(connectings, bp::l, bp::v)); BOOST_TEST(contains(connectings, bp::l, bp::lv)); BOOST_TEST(contains(connectings, bp::l, bp::lvt)); BOOST_TEST(contains(connectings, bp::v, bp::extend)); BOOST_TEST(contains(connectings, bp::v, bp::zwj)); BOOST_TEST(contains(connectings, bp::v, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::v, bp::v)); BOOST_TEST(contains(connectings, bp::v, bp::t)); BOOST_TEST(contains(connectings, bp::t, bp::extend)); BOOST_TEST(contains(connectings, bp::t, bp::zwj)); BOOST_TEST(contains(connectings, bp::t, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::t, bp::t)); BOOST_TEST(contains(connectings, bp::lv, bp::extend)); BOOST_TEST(contains(connectings, bp::lv, bp::zwj)); BOOST_TEST(contains(connectings, bp::lv, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::lv, bp::v)); BOOST_TEST(contains(connectings, bp::lv, bp::t)); BOOST_TEST(contains(connectings, bp::lvt, bp::extend)); BOOST_TEST(contains(connectings, bp::lvt, bp::zwj)); BOOST_TEST(contains(connectings, bp::lvt, bp::spacing_mark)); BOOST_TEST(contains(connectings, bp::lvt, bp::t)); BOOST_TEST(contains(connectings, bp::other, bp::extend)); BOOST_TEST(contains(connectings, bp::other, bp::zwj)); BOOST_TEST(contains(connectings, bp::other, bp::spacing_mark)); } { const auto offsets = segment_maker.segment_offsets({ bp::regional }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 1 })); } { const auto offsets = segment_maker.segment_offsets({ bp::regional, bp::regional }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 2 })); } { const auto offsets = segment_maker.segment_offsets({ bp::regional, bp::regional, bp::regional }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 2, 3 })); } { const auto offsets = segment_maker.segment_offsets({ bp::regional, bp::regional, bp::regional, bp::regional }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 2, 4 })); } { const auto offsets = segment_maker.segment_offsets({ bp::regional, bp::regional, bp::regional, bp::regional, bp::regional }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 2, 4, 5 })); } { const auto offsets = segment_maker.segment_offsets({ bp::regional, bp::regional, bp::extend, bp::regional, bp::regional }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 3, 5 })); } { const auto offsets = segment_maker.segment_offsets({ bp::regional, bp::regional, bp::prepend, bp::regional, bp::regional }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 2, 5 })); } { const auto offsets = segment_maker.segment_offsets({ bp::other, // U+1F469 bp::zwj, // U+200D bp::other, // U+2764 bp::extend, // U+FE0F bp::zwj, // U+200D bp::other, // U+1F48B bp::zwj, // U+200D bp::other // U+1F468 }); BOOST_TEST((offsets == std::vector<std::size_t>{ 0, 8 })); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
42.86911
120
0.596971
tetengo
4b10cf02b0be6a803eb200ba5d6a6b4428523b14
5,180
cpp
C++
ReactAndroid/third-party-ndk/boost/boost_1_66_0/libs/mp11/test/construct_from_tuple.cpp
yinhangfeng/react-native
35e88f14195aa7a75ace8881956a0eb4bdadea62
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
ReactAndroid/third-party-ndk/boost/boost_1_66_0/libs/mp11/test/construct_from_tuple.cpp
yinhangfeng/react-native
35e88f14195aa7a75ace8881956a0eb4bdadea62
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
ReactAndroid/third-party-ndk/boost/boost_1_66_0/libs/mp11/test/construct_from_tuple.cpp
yinhangfeng/react-native
35e88f14195aa7a75ace8881956a0eb4bdadea62
[ "CC-BY-4.0", "BSD-3-Clause" ]
1
2019-03-08T11:06:22.000Z
2019-03-08T11:06:22.000Z
// Copyright 2015, 2017 Peter Dimov. // // Distributed under 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 #include <boost/mp11/tuple.hpp> #include <boost/core/lightweight_test.hpp> #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <tuple> #include <memory> #include <utility> #include <array> struct T1 { int x, y, z; T1( int x = 0, int y = 0, int z = 0 ): x(x), y(y), z(z) {} }; struct T2 { std::unique_ptr<int> x, y, z; T2( std::unique_ptr<int> x, std::unique_ptr<int> y, std::unique_ptr<int> z ): x(std::move(x)), y(std::move(y)), z(std::move(z)) {} #if BOOST_WORKAROUND( BOOST_MSVC, <= 1800 ) T2( T2&& r ): x( std::move(r.x) ), y( std::move(r.y) ), z( std::move(r.z) ) {} #endif }; int main() { using boost::mp11::construct_from_tuple; { std::tuple<int, short, char> tp{ 1, 2, 3 }; { T1 t1 = construct_from_tuple<T1>( tp ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 3 ); } { T1 t1 = construct_from_tuple<T1>( std::move(tp) ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 3 ); } } { std::tuple<int, short, char> const tp{ 1, 2, 3 }; { T1 t1 = construct_from_tuple<T1>( tp ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 3 ); } { T1 t1 = construct_from_tuple<T1>( std::move(tp) ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 3 ); } } #if defined( __clang_major__ ) && __clang_major__ == 3 && __clang_minor__ < 8 #else { std::tuple<std::unique_ptr<int>, std::unique_ptr<int>, std::unique_ptr<int>> tp{ std::unique_ptr<int>(new int(1)), std::unique_ptr<int>(new int(2)), std::unique_ptr<int>(new int(3)) }; T2 t2 = construct_from_tuple<T2>( std::move(tp) ); BOOST_TEST_EQ( *t2.x, 1 ); BOOST_TEST_EQ( *t2.y, 2 ); BOOST_TEST_EQ( *t2.z, 3 ); } #endif { std::pair<int, short> tp{ 1, 2 }; { T1 t1 = construct_from_tuple<T1>( tp ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 0 ); } { T1 t1 = construct_from_tuple<T1>( std::move(tp) ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 0 ); } } { std::pair<int, short> const tp{ 1, 2 }; { T1 t1 = construct_from_tuple<T1>( tp ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 0 ); } { T1 t1 = construct_from_tuple<T1>( std::move(tp) ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 0 ); } } { std::array<int, 3> tp{{ 1, 2, 3 }}; { T1 t1 = construct_from_tuple<T1>( tp ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 3 ); } { T1 t1 = construct_from_tuple<T1>( std::move(tp) ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 3 ); } } { std::array<int, 3> const tp{{ 1, 2, 3 }}; { T1 t1 = construct_from_tuple<T1>( tp ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 3 ); } { T1 t1 = construct_from_tuple<T1>( std::move(tp) ); BOOST_TEST_EQ( t1.x, 1 ); BOOST_TEST_EQ( t1.y, 2 ); BOOST_TEST_EQ( t1.z, 3 ); } } { std::tuple<> tp; { T1 t1 = construct_from_tuple<T1>( tp ); BOOST_TEST_EQ( t1.x, 0 ); BOOST_TEST_EQ( t1.y, 0 ); BOOST_TEST_EQ( t1.z, 0 ); } { T1 t1 = construct_from_tuple<T1>( std::move(tp) ); BOOST_TEST_EQ( t1.x, 0 ); BOOST_TEST_EQ( t1.y, 0 ); BOOST_TEST_EQ( t1.z, 0 ); } } { std::array<int, 0> tp; { T1 t1 = construct_from_tuple<T1>( tp ); BOOST_TEST_EQ( t1.x, 0 ); BOOST_TEST_EQ( t1.y, 0 ); BOOST_TEST_EQ( t1.z, 0 ); } { T1 t1 = construct_from_tuple<T1>( std::move(tp) ); BOOST_TEST_EQ( t1.x, 0 ); BOOST_TEST_EQ( t1.y, 0 ); BOOST_TEST_EQ( t1.z, 0 ); } } return boost::report_errors(); }
23.545455
193
0.453089
yinhangfeng
4b12cca2affd15b93f76f3db4203ad337d6331c2
217
cpp
C++
input/Controller.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
input/Controller.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
input/Controller.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#include "Controller.hpp" BEGIN_INANITY_INPUT Controller::Controller(uint64_t controllerId) : controllerId(controllerId) {} uint64_t Controller::GetControllerId() const { return controllerId; } END_INANITY_INPUT
15.5
45
0.81106
quyse
4b152456aed6adcf04af6becee2f0028c6991df7
1,640
hpp
C++
src/common/utils/if.hpp
jarrielcook/openair-cn-cups
e3bd21569576ce240daf4d16ed8c243224b4bafb
[ "Apache-2.0" ]
2
2020-06-29T07:35:43.000Z
2021-08-14T19:49:26.000Z
src/common/utils/if.hpp
jarrielcook/openair-cn-cups
e3bd21569576ce240daf4d16ed8c243224b4bafb
[ "Apache-2.0" ]
13
2020-06-09T22:12:13.000Z
2021-05-29T13:43:31.000Z
src/common/utils/if.hpp
jarrielcook/openair-cn-cups
e3bd21569576ce240daf4d16ed8c243224b4bafb
[ "Apache-2.0" ]
2
2020-06-09T21:03:53.000Z
2021-08-17T03:27:53.000Z
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ /*! \file get_gateway_netlink.h \brief \author Lionel Gauthier \company Eurecom \email: lionel.gauthier@eurecom.fr */ #ifndef FILE_IF_HPP_SEEN #define FILE_IF_HPP_SEEN # include <string> int get_gateway_and_iface(std::string *gw /*OUT*/, std::string *iface /*OUT*/); int get_inet_addr_from_iface(const std::string& if_name, struct in_addr& inet_addr); int get_mtu_from_iface(const std::string& if_name, uint32_t& mtu); int get_inet_addr_infos_from_iface(const std::string& if_name, struct in_addr& inet_addr, struct in_addr& inet_netmask, unsigned int& mtu); #endif /* FILE_IF_HPP_SEEN */
43.157895
139
0.727439
jarrielcook
4b15898d306c2382dbe5badb6584a1f496e2bffc
166
cpp
C++
game_from_scratch/game_from_scratch/main.cpp
Robertk92/GameFromScratch
aa38a443636adbaf771514b1a3a868503feac87e
[ "MIT" ]
null
null
null
game_from_scratch/game_from_scratch/main.cpp
Robertk92/GameFromScratch
aa38a443636adbaf771514b1a3a868503feac87e
[ "MIT" ]
null
null
null
game_from_scratch/game_from_scratch/main.cpp
Robertk92/GameFromScratch
aa38a443636adbaf771514b1a3a868503feac87e
[ "MIT" ]
null
null
null
#pragma comment(lib, "blitwave.lib") #include <blitwave/engine.h> #include <game/core/game.h> int main(int argc, char** argv) { engine()->run<Game>(); return 0; }
18.444444
36
0.668675
Robertk92
4b16aaccc83cbe1c514d584484bb9cb33dc8c3c1
1,443
cpp
C++
Game/main.cpp
gamepopper/Tunnel-Bug
6327a1737421f2c81f8cf3e11fc393d1ef94cbaa
[ "MIT" ]
null
null
null
Game/main.cpp
gamepopper/Tunnel-Bug
6327a1737421f2c81f8cf3e11fc393d1ef94cbaa
[ "MIT" ]
null
null
null
Game/main.cpp
gamepopper/Tunnel-Bug
6327a1737421f2c81f8cf3e11fc393d1ef94cbaa
[ "MIT" ]
null
null
null
#include <VFrame/VGame.h> #include <memory> #include "TitleState.h" #include "VFrame/VGlobal.h" /** Theme: Your Life Is Currency Navigate a ship through a winding RNG path, touching the walls loses health. Health can be regained by collecting orbs. Health can be spent to make the future paths easier. TODO: Generate tilemap out of a spline with infinite amount of nodes. DONE Ship that can only navigate through rotation and thrust. DONE Get the following options implemented between levels: - Increase Path Width - Increase Rotation Speed - Decrease Path Windingness - Decrease Orb Speed - Decrease Move Speed Use physics engine for collision handling? */ int main() { std::unique_ptr<VGame> game = std::make_unique<VGame>(); sf::ContextSettings settings; settings.depthBits = 24; settings.stencilBits = 0; settings.antialiasingLevel = 0; settings.majorVersion = 4; settings.minorVersion = 5; VGlobal::p()->Input->SetAxisInput("X", sf::Keyboard::A, sf::Keyboard::D, VInputHandler::PovX); VGlobal::p()->Input->SetButtonInput("Left", sf::Keyboard::Left, GAMEPAD_BUTTON::BUTTON_LEFT_SHOULDER); VGlobal::p()->Input->SetButtonInput("Right", sf::Keyboard::Right, GAMEPAD_BUTTON::BUTTON_RIGHT_SHOULDER); VGlobal::p()->Input->SetButtonInput("Forward", sf::Keyboard::Space, GAMEPAD_BUTTON::BUTTON_A); return game->Run("Tunnel Bug", new TitleState(), 1280, 720, 60.0f, 7, settings); }
32.066667
107
0.729037
gamepopper
4b1a02fe63568a5bd279158a7c2693eb99cd9232
4,935
cpp
C++
src/model/model.cpp
Gotatang/DadEngine_2.0
1e97e86996571c8ba1efec72b0f0e914d86533d3
[ "MIT" ]
2
2018-03-12T13:59:13.000Z
2018-11-27T20:13:57.000Z
src/model/model.cpp
Gotatang/DadEngine_2.0
1e97e86996571c8ba1efec72b0f0e914d86533d3
[ "MIT" ]
5
2018-12-22T10:43:28.000Z
2019-01-17T22:02:16.000Z
src/model/model.cpp
ladevieq/dadengine
1e97e86996571c8ba1efec72b0f0e914d86533d3
[ "MIT" ]
null
null
null
#include "model.hpp" namespace DadEngine { VertexBuffer::VertexBuffer(std::vector<Vertex> &&_vertices) : vertices(_vertices) { #if defined(OPENGL) glGenVertexArrays(1, &vertexArrayID); glBindVertexArray(vertexArrayID); glGenBuffers(1, &vertexBufferID); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID); glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizei>(vertices.size() * sizeof(Vertex)), vertices.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void *>(offsetof(Vertex, normal))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void *>(offsetof(Vertex, tangent))); glEnableVertexAttribArray(2); glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void *>(offsetof(Vertex, uv0))); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); #elif defined(_VULKAN) #endif } IndexBuffer::IndexBuffer(std::vector<uint32_t> &&_indices) : indices(_indices) { #if defined(OPENGL) glGenBuffers(1, &elementBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizei>(indices.size() * sizeof(uint32_t)), indices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); #elif defined(_VULKAN) #endif } Texture::Texture(uint8_t *_data, int32_t _width, int32_t _height, int32_t _channels, Sampler _sampler, bool _hasAlpha) : sampler(_sampler), data(_data), width(_width), height(_height), channels(_channels), hasAlpha(_hasAlpha) { #if defined(OPENGL) glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, sampler.wrapS); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, sampler.wrapT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, sampler.minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, sampler.magFilter); glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? GL_RGBA : GL_RGB, width, height, 0, hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); #elif defined(_VULKAN) #endif } void Primitive::Render() { #if defined(OPENGL) glBindVertexArray(vertices.vertexArrayID); glUniform4fv(0, 1, reinterpret_cast<float *>(&material.baseColorFactor)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, material.baseColorTexture.textureID); glUniform1i(1, 0); glUniform1f(3, material.metallicFactor); glUniform1f(9, material.roughnessFactor); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, material.metallicRoughnessTexture.textureID); glUniform1i(4, 1); glUniform1f(6, material.normalScale); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, material.normalTexture.textureID); glUniform1i(7, 2); // glUniform1f(8, material.occlusionStrength); // glActiveTexture(GL_TEXTURE3); // glBindTexture(GL_TEXTURE_2D, material.occlusionTexture.textureID); // glUniform1i(9, 3); // glUniform3f(4, material.emissiveFactor.x, material.emissiveFactor.y, // material.emissiveFactor.z); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, // material.emissiveTexture.textureID); glUniform1i(4, 4); if (indices.indices.empty()) { glDrawArrays(drawMode, 0, static_cast<GLsizei>(vertices.vertices.size())); } else { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices.elementBufferID); glDrawElements(drawMode, static_cast<GLsizei>(indices.indices.size()), GL_UNSIGNED_INT, nullptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } glBindVertexArray(0); #elif defined(_VULKAN) #endif } void Mesh::Render() { for (auto &primitive : m_primitives) { if (!primitive.material.hasTransparency) { primitive.Render(); } } for (auto &primitive : m_primitives) { if (primitive.material.hasTransparency) { primitive.Render(); } } } } // namespace DadEngine
32.9
122
0.639716
Gotatang
4b1cfa1f656693d993b4622819397413870d570b
77,199
cpp
C++
td/telegram/files/FileManager.cpp
takpare/-T
6c706f45e7a73c936b9f2f267785092c8a73348f
[ "BSL-1.0" ]
null
null
null
td/telegram/files/FileManager.cpp
takpare/-T
6c706f45e7a73c936b9f2f267785092c8a73348f
[ "BSL-1.0" ]
null
null
null
td/telegram/files/FileManager.cpp
takpare/-T
6c706f45e7a73c936b9f2f267785092c8a73348f
[ "BSL-1.0" ]
null
null
null
// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018 // // Distributed under 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) // #include "td/telegram/files/FileManager.h" #include "td/telegram/telegram_api.h" #include "td/telegram/files/FileLoaderUtils.h" #include "td/telegram/files/FileLocation.h" #include "td/telegram/files/FileUploader.h" #include "td/telegram/Global.h" #include "td/telegram/misc.h" #include "td/telegram/Td.h" #include "td/utils/base64.h" #include "td/utils/format.h" #include "td/utils/HttpUrl.h" #include "td/utils/logging.h" #include "td/utils/misc.h" #include "td/utils/PathView.h" #include "td/utils/port/FileFd.h" #include "td/utils/port/path.h" #include "td/utils/port/Stat.h" #include "td/utils/ScopeGuard.h" #include "td/utils/tl_helpers.h" #include <algorithm> #include <limits> #include <tuple> #include <utility> namespace td { static int VERBOSITY_NAME(update_file) = VERBOSITY_NAME(INFO); FileNode *FileNodePtr::operator->() const { return get(); } FileNode &FileNodePtr::operator*() const { return *get(); } FileNode *FileNodePtr::get() const { auto res = get_unsafe(); CHECK(res); return res; } FileNode *FileNodePtr::get_unsafe() const { CHECK(file_manager_ != nullptr); return file_manager_->get_file_node_raw(file_id_); } FileNodePtr::operator bool() const { return file_manager_ != nullptr && get_unsafe() != nullptr; } void FileNode::set_local_location(const LocalFileLocation &local, int64 ready_size) { if (local_ready_size_ != ready_size) { local_ready_size_ = ready_size; VLOG(update_file) << "File " << main_file_id_ << " has changed local ready size"; on_info_changed(); } if (local_ != local) { VLOG(update_file) << "File " << main_file_id_ << " has changed local location"; local_ = local; on_changed(); } } void FileNode::set_remote_location(const RemoteFileLocation &remote, FileLocationSource source, int64 ready_size) { if (remote_ready_size_ != ready_size) { remote_ready_size_ = ready_size; VLOG(update_file) << "File " << main_file_id_ << " has changed remote ready size"; on_info_changed(); } if (remote_ == remote) { if (remote_.type() == RemoteFileLocation::Type::Full) { if (remote_.full().get_access_hash() == remote.full().get_access_hash()) { return; } } else { return; } } VLOG(update_file) << "File " << main_file_id_ << " has changed remote location"; remote_ = remote; remote_source_ = source; on_changed(); } void FileNode::set_generate_location(const GenerateFileLocation &generate) { if (generate_ != generate) { generate_ = generate; on_pmc_changed(); } } void FileNode::set_size(int64 size) { if (size_ != size) { VLOG(update_file) << "File " << main_file_id_ << " has changed size to " << size; size_ = size; on_changed(); } } void FileNode::set_expected_size(int64 expected_size) { if (expected_size_ != expected_size) { VLOG(update_file) << "File " << main_file_id_ << " has changed expected size to " << expected_size; expected_size_ = expected_size; on_changed(); } } void FileNode::set_name(string name) { if (name_ != name) { name_ = std::move(name); on_pmc_changed(); } } void FileNode::set_url(string url) { if (url_ != url) { VLOG(update_file) << "File " << main_file_id_ << " has changed URL to " << url; url_ = std::move(url); on_changed(); } } void FileNode::set_owner_dialog_id(DialogId owner_id) { if (owner_dialog_id_ != owner_id) { owner_dialog_id_ = owner_id; on_pmc_changed(); } } void FileNode::set_encryption_key(FileEncryptionKey key) { if (encryption_key_ != key) { encryption_key_ = std::move(key); on_pmc_changed(); } } void FileNode::set_download_priority(int8 priority) { if ((download_priority_ == 0) != (priority == 0)) { VLOG(update_file) << "File " << main_file_id_ << " has changed download priority to " << priority; on_info_changed(); } download_priority_ = priority; } void FileNode::set_upload_priority(int8 priority) { if ((upload_priority_ == 0) != (priority == 0)) { VLOG(update_file) << "File " << main_file_id_ << " has changed upload priority to " << priority; on_info_changed(); } upload_priority_ = priority; } void FileNode::set_generate_priority(int8 download_priority, int8 upload_priority) { if ((download_priority_ == 0) != (download_priority == 0) || (upload_priority_ == 0) != (upload_priority == 0)) { VLOG(update_file) << "File " << main_file_id_ << " has changed generate priority to " << download_priority << "/" << upload_priority; on_info_changed(); } generate_priority_ = std::max(download_priority, upload_priority); generate_download_priority_ = download_priority; generate_upload_priority_ = upload_priority; } void FileNode::on_changed() { on_pmc_changed(); on_info_changed(); } void FileNode::on_info_changed() { info_changed_flag_ = true; } void FileNode::on_pmc_changed() { pmc_changed_flag_ = true; } bool FileNode::need_info_flush() const { return info_changed_flag_; } bool FileNode::need_pmc_flush() const { if (!pmc_changed_flag_) { return false; } // already in pmc if (pmc_id_ != 0) { return true; } // We must save encryption key if (!encryption_key_.empty()) { // && remote_.type() != RemoteFileLocation::Type::Empty return true; } bool has_generate_location = generate_.type() == GenerateFileLocation::Type::Full; // Do not save "#file_id#" conversion. if (has_generate_location && begins_with(generate_.full().conversion_, "#file_id#")) { has_generate_location = false; } if (remote_.type() == RemoteFileLocation::Type::Full && (has_generate_location || local_.type() != LocalFileLocation::Type::Empty)) { return true; } if (local_.type() == LocalFileLocation::Type::Full && (has_generate_location || remote_.type() != RemoteFileLocation::Type::Empty)) { return true; } // TODO: Generate location with constant conversion return false; } void FileNode::on_pmc_flushed() { pmc_changed_flag_ = false; } void FileNode::on_info_flushed() { info_changed_flag_ = false; } /*** FileView ***/ bool FileView::has_local_location() const { return node_->local_.type() == LocalFileLocation::Type::Full; } const FullLocalFileLocation &FileView::local_location() const { CHECK(has_local_location()); return node_->local_.full(); } bool FileView::has_remote_location() const { return node_->remote_.type() == RemoteFileLocation::Type::Full; } const FullRemoteFileLocation &FileView::remote_location() const { CHECK(has_remote_location()); return node_->remote_.full(); } bool FileView::has_generate_location() const { return node_->generate_.type() == GenerateFileLocation::Type::Full; } const FullGenerateFileLocation &FileView::generate_location() const { CHECK(has_generate_location()); return node_->generate_.full(); } int64 FileView::size() const { return node_->size_; } int64 FileView::expected_size() const { if (node_->size_ != 0) { return node_->size_; } return node_->expected_size_; } bool FileView::is_downloading() const { return node_->download_priority_ != 0 || node_->generate_download_priority_ != 0; } int64 FileView::local_size() const { switch (node_->local_.type()) { case LocalFileLocation::Type::Full: return node_->size_; case LocalFileLocation::Type::Partial: return node_->local_.partial().part_size_ * node_->local_.partial().ready_part_count_; default: return 0; } } int64 FileView::local_total_size() const { switch (node_->local_.type()) { case LocalFileLocation::Type::Empty: return 0; case LocalFileLocation::Type::Full: return node_->size_; case LocalFileLocation::Type::Partial: return std::max( static_cast<int64>(node_->local_.partial().part_size_) * node_->local_.partial().ready_part_count_, node_->local_ready_size_); default: UNREACHABLE(); return 0; } } bool FileView::is_uploading() const { return node_->upload_priority_ != 0 || node_->generate_upload_priority_ != 0; } int64 FileView::remote_size() const { switch (node_->remote_.type()) { case RemoteFileLocation::Type::Full: return node_->size_; case RemoteFileLocation::Type::Partial: { auto res = std::max(static_cast<int64>(node_->remote_.partial().part_size_) * node_->remote_.partial().ready_part_count_, node_->remote_ready_size_); if (size() != 0 && size() < res) { res = size(); } return res; } default: return 0; } } string FileView::path() const { switch (node_->local_.type()) { case LocalFileLocation::Type::Full: return node_->local_.full().path_; case LocalFileLocation::Type::Partial: return node_->local_.partial().path_; default: return ""; } } bool FileView::has_url() const { return !node_->url_.empty(); } const string &FileView::url() const { return node_->url_; } const string &FileView::name() const { return node_->name_; } DialogId FileView::owner_dialog_id() const { return node_->owner_dialog_id_; } bool FileView::get_by_hash() const { return node_->get_by_hash_; } FileView::FileView(ConstFileNodePtr node) : node_(node) { } bool FileView::empty() const { return !node_; } bool FileView::can_download_from_server() const { if (!has_remote_location()) { return false; } if (remote_location().file_type_ == FileType::Encrypted && encryption_key().empty()) { return false; } if (remote_location().get_dc_id().is_empty()) { return false; } return true; } bool FileView::can_generate() const { return has_generate_location(); } bool FileView::can_delete() const { if (has_local_location()) { return begins_with(local_location().path_, get_files_dir(get_type())); } return node_->local_.type() == LocalFileLocation::Type::Partial; } /*** FileManager ***/ namespace { void prepare_path_for_pmc(FileType file_type, string &path) { path = PathView::relative(path, get_files_base_dir(file_type)).str(); } } // namespace FileManager::FileManager(std::unique_ptr<Context> context) : context_(std::move(context)) { if (G()->parameters().use_file_db) { file_db_ = G()->td_db()->get_file_db_shared(); } parent_ = context_->create_reference(); next_file_id(); next_file_node_id(); std::vector<string> dirs; auto create_dir = [&](CSlice path) { dirs.push_back(path.str()); auto status = mkdir(path, 0750); if (status.is_error()) { auto r_stat = stat(path); if (r_stat.is_ok() && r_stat.ok().is_dir_) { LOG(ERROR) << "mkdir " << tag("path", path) << " failed " << status << ", but directory exists"; } else { LOG(FATAL) << "mkdir " << tag("path", path) << " failed " << status; } } #if TD_ANDROID FileFd::open(dirs.back() + ".nomedia", FileFd::Create | FileFd::Read).ignore(); #endif }; for (int i = 0; i < file_type_size; i++) { auto path = get_files_dir(FileType(i)); create_dir(path); } // Create both temp dirs. create_dir(get_files_temp_dir(FileType::Encrypted)); create_dir(get_files_temp_dir(FileType::Video)); G()->td_db()->with_db_path([this](CSlice path) { this->bad_paths_.insert(path.str()); }); } void FileManager::init_actor() { file_load_manager_ = create_actor_on_scheduler<FileLoadManager>("FileLoadManager", G()->get_slow_net_scheduler_id(), actor_shared(this), context_->create_reference()); file_generate_manager_ = create_actor_on_scheduler<FileGenerateManager>( "FileGenerateManager", G()->get_slow_net_scheduler_id(), context_->create_reference()); } FileManager::~FileManager() { // NB: As FileLoadManager callback is just "this" pointer, this event must be processed immediately. send_closure(std::move(file_load_manager_), &FileLoadManager::close); } string FileManager::fix_file_extension(Slice file_name, Slice file_type, Slice file_extension) { return (file_name.empty() ? file_type : file_name).str() + "." + file_extension.str(); } string FileManager::get_file_name(FileType file_type, Slice path) { PathView path_view(path); auto file_name = path_view.file_name(); auto extension = path_view.extension(); switch (file_type) { case FileType::Thumbnail: if (extension != "jpg" && extension != "jpeg" && extension != "webp") { return fix_file_extension(file_name, "thumbnail", "jpg"); } break; case FileType::ProfilePhoto: case FileType::Photo: if (extension != "jpg" && extension != "jpeg" && extension != "gif" && extension != "png" && extension != "tif" && extension != "bmp") { return fix_file_extension(file_name, "photo", "jpg"); } break; case FileType::VoiceNote: if (extension != "ogg" && extension != "oga" && extension != "mp3" && extension != "mpeg3" && extension != "m4a") { return fix_file_extension(file_name, "voice", "oga"); } break; case FileType::Video: case FileType::VideoNote: if (extension != "mov" && extension != "3gp" && extension != "mpeg4" && extension != "mp4") { return fix_file_extension(file_name, "video", "mp4"); } break; case FileType::Audio: if (extension != "ogg" && extension != "oga" && extension != "mp3" && extension != "mpeg3" && extension != "m4a") { return fix_file_extension(file_name, "audio", "mp3"); } break; case FileType::Document: case FileType::Sticker: case FileType::Animation: case FileType::Encrypted: case FileType::Temp: case FileType::EncryptedThumbnail: case FileType::Wallpaper: break; default: UNREACHABLE(); } return file_name.str(); } Status FileManager::check_local_location(FullLocalFileLocation &location, int64 &size) { constexpr int64 MAX_THUMBNAIL_SIZE = 200 * (1 << 10) /* 200KB */; constexpr int64 MAX_FILE_SIZE = 1500 * (1 << 20) /* 1500MB */; if (location.path_.empty()) { return Status::Error("File must have non-empty path"); } TRY_RESULT(path, realpath(location.path_, true)); if (bad_paths_.count(path) != 0) { return Status::Error("Sending of internal database files is forbidden"); } location.path_ = std::move(path); TRY_RESULT(stat, stat(location.path_)); if (!stat.is_reg_) { return Status::Error("File must be a regular file"); } if (stat.size_ < 0) { // TODO is it possible? return Status::Error("File is too big"); } if (stat.size_ == 0) { return Status::Error("File must be non-empty"); } if (size == 0) { size = stat.size_; } if (location.mtime_nsec_ == 0) { LOG(INFO) << "Set file modification time to " << stat.mtime_nsec_; location.mtime_nsec_ = stat.mtime_nsec_; } else if (location.mtime_nsec_ != stat.mtime_nsec_) { LOG(INFO) << "File was nodified: old mtime = " << location.mtime_nsec_ << ", new mtime = " << stat.mtime_nsec_; return Status::Error("File was modified"); } if ((location.file_type_ == FileType::Thumbnail || location.file_type_ == FileType::EncryptedThumbnail) && size >= MAX_THUMBNAIL_SIZE) { return Status::Error(PSLICE() << "File is too big for thumbnail " << tag("size", format::as_size(size))); } if (size >= MAX_FILE_SIZE) { return Status::Error(PSLICE() << "File is too big " << tag("size", format::as_size(size))); } return Status::OK(); } static Status check_partial_local_location(const PartialLocalFileLocation &location) { TRY_RESULT(stat, stat(location.path_)); if (!stat.is_reg_) { return Status::Error("File must be a regular file"); } // can't check mtime. Hope nobody will mess with this file in our temporary dir. return Status::OK(); } Status FileManager::check_local_location(FileNodePtr node) { Status status; if (node->local_.type() == LocalFileLocation::Type::Full) { status = check_local_location(node->local_.full(), node->size_); } else if (node->local_.type() == LocalFileLocation::Type::Partial) { status = check_partial_local_location(node->local_.partial()); } if (status.is_error()) { node->set_local_location(LocalFileLocation(), 0); try_flush_node(node); } return status; } FileManager::FileIdInfo *FileManager::get_file_id_info(FileId file_id) { CHECK(0 <= file_id.get() && file_id.get() < static_cast<int32>(file_id_info_.size())) << file_id << " " << file_id_info_.size(); return &file_id_info_[file_id.get()]; } FileId FileManager::dup_file_id(FileId file_id) { int32 file_node_id; auto *file_node = get_file_node_raw(file_id, &file_node_id); if (!file_node) { return FileId(); } auto result = create_file_id(file_node_id, file_node); LOG(INFO) << "Dup file " << file_id << " to " << result; return result; } FileId FileManager::create_file_id(int32 file_node_id, FileNode *file_node) { auto file_id = next_file_id(); get_file_id_info(file_id)->node_id_ = file_node_id; file_node->file_ids_.push_back(file_id); return file_id; } void FileManager::try_forget_file_id(FileId file_id) { auto *info = get_file_id_info(file_id); if (info->send_updates_flag_ || info->pin_flag_) { return; } auto file_node = get_file_node(file_id); if (file_node->main_file_id_ == file_id) { return; } LOG(INFO) << "Forget file " << file_id; auto it = std::find(file_node->file_ids_.begin(), file_node->file_ids_.end(), file_id); CHECK(it != file_node->file_ids_.end()); file_node->file_ids_.erase(it); *info = FileIdInfo(); empty_file_ids_.push_back(file_id); } FileId FileManager::register_empty(FileType type) { return register_local(FullLocalFileLocation(type, "", 0), DialogId(), 0, false, true).ok(); } void FileManager::on_file_unlink(const FullLocalFileLocation &location) { auto it = local_location_to_file_id_.find(location); if (it == local_location_to_file_id_.end()) { return; } auto file_id = it->second; auto file_node = get_sync_file_node(file_id); CHECK(file_node); file_node->set_local_location(LocalFileLocation(), 0); try_flush_node_info(file_node); } Result<FileId> FileManager::register_local(FullLocalFileLocation location, DialogId owner_dialog_id, int64 size, bool get_by_hash, bool force) { // TODO: use get_by_hash FileData data; data.local_ = LocalFileLocation(std::move(location)); data.owner_dialog_id_ = owner_dialog_id; data.size_ = size; return register_file(std::move(data), FileLocationSource::None /*won't be used*/, "register_local", force); } FileId FileManager::register_remote(const FullRemoteFileLocation &location, FileLocationSource file_location_source, DialogId owner_dialog_id, int64 size, int64 expected_size, string name) { FileData data; data.remote_ = RemoteFileLocation(location); data.owner_dialog_id_ = owner_dialog_id; data.size_ = size; data.expected_size_ = expected_size; data.name_ = std::move(name); return register_file(std::move(data), file_location_source, "register_remote", false).move_as_ok(); } FileId FileManager::register_url(string url, FileType file_type, FileLocationSource file_location_source, DialogId owner_dialog_id) { auto file_id = register_generate(file_type, file_location_source, url, "#url#", owner_dialog_id, 0).ok(); auto file_node = get_file_node(file_id); CHECK(file_node); file_node->set_url(url); return file_id; } Result<FileId> FileManager::register_generate(FileType file_type, FileLocationSource file_location_source, string original_path, string conversion, DialogId owner_dialog_id, int64 expected_size) { FileData data; data.generate_ = GenerateFileLocation(FullGenerateFileLocation(file_type, original_path, std::move(conversion))); data.owner_dialog_id_ = owner_dialog_id; data.expected_size_ = expected_size; return register_file(std::move(data), file_location_source, "register_generate", false); } Result<FileId> FileManager::register_file(FileData data, FileLocationSource file_location_source, const char *source, bool force) { bool has_remote = data.remote_.type() == RemoteFileLocation::Type::Full; bool has_generate = data.generate_.type() == GenerateFileLocation::Type::Full; if (data.local_.type() == LocalFileLocation::Type::Full && !force) { if (file_location_source == FileLocationSource::FromDb) { PathView path_view(data.local_.full().path_); if (path_view.is_relative()) { data.local_.full().path_ = get_files_base_dir(data.local_.full().file_type_) + data.local_.full().path_; } } auto status = check_local_location(data.local_.full(), data.size_); if (status.is_error()) { LOG(WARNING) << "Invalid local location: " << status << " from " << source; data.local_ = LocalFileLocation(); if (data.remote_.type() == RemoteFileLocation::Type::Partial) { data.remote_ = {}; } if (!has_remote && !has_generate) { return std::move(status); } } } bool has_local = data.local_.type() == LocalFileLocation::Type::Full; bool has_location = has_local || has_remote || has_generate; if (!has_location) { return Status::Error("No location"); } FileId file_id = next_file_id(); LOG(INFO) << "Register file data " << data << " as " << file_id << " from " << source; // create FileNode auto file_node_id = next_file_node_id(); auto &node = file_nodes_[file_node_id]; node = std::make_unique<FileNode>(std::move(data.local_), std::move(data.remote_), std::move(data.generate_), data.size_, data.expected_size_, std::move(data.name_), std::move(data.url_), data.owner_dialog_id_, std::move(data.encryption_key_), file_id, static_cast<int8>(has_remote)); node->remote_source_ = file_location_source; node->pmc_id_ = data.pmc_id_; get_file_id_info(file_id)->node_id_ = file_node_id; node->file_ids_.push_back(file_id); FileView file_view(get_file_node(file_id)); std::vector<FileId> to_merge; auto register_location = [&](const auto &location, auto &mp) { auto &other_id = mp[location]; if (other_id.empty()) { other_id = file_id; get_file_id_info(file_id)->pin_flag_ = true; return true; } else { to_merge.push_back(other_id); return false; } }; bool new_remote = false; if (file_view.has_remote_location()) { new_remote = register_location(file_view.remote_location(), remote_location_to_file_id_); } bool new_local = false; if (file_view.has_local_location()) { new_local = register_location(file_view.local_location(), local_location_to_file_id_); } bool new_generate = false; if (file_view.has_generate_location()) { new_generate = register_location(file_view.generate_location(), generate_location_to_file_id_); } std::sort(to_merge.begin(), to_merge.end()); to_merge.erase(std::unique(to_merge.begin(), to_merge.end()), to_merge.end()); int new_cnt = new_remote + new_local + new_generate; if (data.pmc_id_ == 0 && file_db_ && new_cnt > 0) { node->need_load_from_pmc_ = true; } bool no_sync_merge = to_merge.size() == 1 && new_cnt == 0; for (auto id : to_merge) { // may invalidate node merge(file_id, id, no_sync_merge).ignore(); } try_flush_node(get_file_node(file_id)); auto main_file_id = get_file_node(file_id)->main_file_id_; try_forget_file_id(file_id); return main_file_id; } // 0 -- choose x // 1 -- choose y // 2 -- choose any static int merge_choose(const LocalFileLocation &x, const LocalFileLocation &y) { int32 x_type = static_cast<int32>(x.type()); int32 y_type = static_cast<int32>(y.type()); if (x_type != y_type) { return x_type < y_type; } return 2; } static int merge_choose(const RemoteFileLocation &x, int8 x_source, const RemoteFileLocation &y, int8 y_source) { int32 x_type = static_cast<int32>(x.type()); int32 y_type = static_cast<int32>(y.type()); if (x_type != y_type) { return x_type < y_type; } // If access_hash changed use a newer one if (x.type() == RemoteFileLocation::Type::Full) { if (x.full().get_access_hash() != y.full().get_access_hash()) { return x_source < y_source; } } return 2; } static int merge_choose(const GenerateFileLocation &x, const GenerateFileLocation &y) { int32 x_type = static_cast<int32>(x.type()); int32 y_type = static_cast<int32>(y.type()); if (x_type != y_type) { return x_type < y_type; } return 2; } // -1 -- error static int merge_choose_size(int64 x, int64 y) { if (x == 0) { return 1; } if (y == 0) { return 0; } if (x != y) { return -1; } return 2; } static int merge_choose_expected_size(int64 x, int64 y) { if (x == 0) { return 1; } if (y == 0) { return 0; } return 2; } static int merge_choose_name(Slice x, Slice y) { if (x.empty() != y.empty()) { return x.empty() > y.empty(); } return 2; } static int merge_choose_owner(DialogId x, DialogId y) { if (x.is_valid() != y.is_valid()) { return x.is_valid() < y.is_valid(); } return 2; } static int merge_choose_main_file_id(FileId a, int8 a_priority, FileId b, int8 b_priority) { if (a_priority != b_priority) { return a_priority < b_priority; } return a.get() > b.get(); } static int merge_choose_encryption_key(const FileEncryptionKey &a, const FileEncryptionKey &b) { if (a.empty() != b.empty()) { return a.empty() > b.empty(); } if (a.key_iv_ != b.key_iv_) { return -1; } return 2; } void FileManager::cancel_download(FileNodePtr node) { if (node->download_id_ == 0) { return; } send_closure(file_load_manager_, &FileLoadManager::cancel, node->download_id_); node->download_id_ = 0; node->is_download_started_ = false; node->set_download_priority(0); } void FileManager::cancel_upload(FileNodePtr node) { if (node->upload_id_ == 0) { return; } send_closure(file_load_manager_, &FileLoadManager::cancel, node->upload_id_); node->upload_id_ = 0; node->set_upload_priority(0); } void FileManager::cancel_generate(FileNodePtr node) { if (node->generate_id_ == 0) { return; } send_closure(file_generate_manager_, &FileGenerateManager::cancel, node->generate_id_); node->generate_id_ = 0; node->generate_was_update_ = false; node->set_generate_priority(0, 0); } Result<FileId> FileManager::merge(FileId x_file_id, FileId y_file_id, bool no_sync) { LOG(INFO) << x_file_id << " VS " << y_file_id; if (!x_file_id.is_valid()) { return Status::Error("First file_id is invalid"); } FileNodePtr x_node = no_sync ? get_file_node(x_file_id) : get_sync_file_node(x_file_id); if (!x_node) { return Status::Error(PSLICE() << "Can't merge files. First id is invalid: " << x_file_id << " and " << y_file_id); } if (!y_file_id.is_valid()) { return x_node->main_file_id_; } FileNodePtr y_node = no_sync ? get_file_node(y_file_id) : get_file_node(y_file_id); if (!y_node) { return Status::Error(PSLICE() << "Can't merge files. Second id is invalid: " << x_file_id << " and " << y_file_id); } if (x_file_id == x_node->upload_pause_) { x_node->upload_pause_ = FileId(); } if (x_node.get() == y_node.get()) { return x_node->main_file_id_; } if (y_file_id == y_node->upload_pause_) { y_node->upload_pause_ = FileId(); } if (x_node->remote_.type() == RemoteFileLocation::Type::Full && y_node->remote_.type() == RemoteFileLocation::Type::Full && x_node->remote_.full().get_dc_id() != y_node->remote_.full().get_dc_id()) { LOG(ERROR) << "File remote location was changed from " << y_node->remote_.full() << " to " << x_node->remote_.full(); } FileNodePtr nodes[] = {x_node, y_node, x_node}; FileNodeId node_ids[] = {get_file_id_info(x_file_id)->node_id_, get_file_id_info(y_file_id)->node_id_}; int local_i = merge_choose(x_node->local_, y_node->local_); int remote_i = merge_choose(x_node->remote_, static_cast<int8>(x_node->remote_source_), y_node->remote_, static_cast<int8>(y_node->remote_source_)); int generate_i = merge_choose(x_node->generate_, y_node->generate_); int size_i = merge_choose_size(x_node->size_, y_node->size_); int expected_size_i = merge_choose_expected_size(x_node->expected_size_, y_node->expected_size_); int name_i = merge_choose_name(x_node->name_, y_node->name_); int url_i = merge_choose_name(x_node->url_, y_node->url_); int owner_i = merge_choose_owner(x_node->owner_dialog_id_, y_node->owner_dialog_id_); int encryption_key_i = merge_choose_encryption_key(x_node->encryption_key_, y_node->encryption_key_); int main_file_id_i = merge_choose_main_file_id(x_node->main_file_id_, x_node->main_file_id_priority_, y_node->main_file_id_, y_node->main_file_id_priority_); if (size_i == -1) { return Status::Error(PSLICE() << "Can't merge files. Different size: " << x_node->size_ << " and " << y_node->size_); } if (encryption_key_i == -1) { if (nodes[remote_i]->remote_.type() == RemoteFileLocation::Type::Full && nodes[local_i]->local_.type() != LocalFileLocation::Type::Partial) { //??? LOG(ERROR) << "Different encryption key in files, but go Choose same key as remote location"; encryption_key_i = remote_i; } else { return Status::Error("Can't merge files. Different encryption keys"); } } int node_i = std::make_tuple(y_node->pmc_id_, y_node->file_ids_.size(), main_file_id_i == 1) > std::make_tuple(x_node->pmc_id_, x_node->file_ids_.size(), main_file_id_i == 0); auto other_node_i = 1 - node_i; FileNodePtr node = nodes[node_i]; FileNodePtr other_node = nodes[other_node_i]; auto file_view = FileView(node); LOG(INFO) << "x_node->pmc_id_ = " << x_node->pmc_id_ << ", y_node->pmc_id_ = " << y_node->pmc_id_ << ", x_node_size = " << x_node->file_ids_.size() << ", y_node_size = " << y_node->file_ids_.size() << ", node_i = " << node_i << ", local_i = " << local_i << ", remote_i = " << remote_i << ", generate_i = " << generate_i << ", size_i = " << size_i << ", name_i = " << name_i << ", url_i = " << url_i << ", owner_i = " << owner_i << ", encryption_key_i = " << encryption_key_i << ", main_file_id_i = " << main_file_id_i; if (local_i == other_node_i) { cancel_download(node); node->set_local_location(other_node->local_, other_node->local_ready_size_); node->download_id_ = other_node->download_id_; node->is_download_started_ |= other_node->is_download_started_; node->set_download_priority(other_node->download_priority_); other_node->download_id_ = 0; other_node->is_download_started_ = false; other_node->download_priority_ = 0; //cancel_generate(node); //node->set_generate_location(other_node->generate_); //node->generate_id_ = other_node->generate_id_; //node->set_generate_priority(other_node->generate_download_priority_, other_node->generate_upload_priority_); //other_node->generate_id_ = 0; //other_node->generate_was_update_ = false; //other_node->generate_priority_ = 0; //other_node->generate_download_priority_ = 0; //other_node->generate_upload_priority_ = 0; } else { cancel_download(other_node); //cancel_generate(other_node); } if (remote_i == other_node_i) { cancel_upload(node); node->set_remote_location(other_node->remote_, other_node->remote_source_, other_node->remote_ready_size_); node->upload_id_ = other_node->upload_id_; node->set_upload_priority(other_node->upload_priority_); node->upload_pause_ = other_node->upload_pause_; other_node->upload_id_ = 0; other_node->upload_priority_ = 0; other_node->upload_pause_ = FileId(); } else { cancel_upload(other_node); } if (generate_i == other_node_i) { cancel_generate(node); node->set_generate_location(other_node->generate_); node->generate_id_ = other_node->generate_id_; node->set_generate_priority(other_node->generate_download_priority_, other_node->generate_upload_priority_); other_node->generate_id_ = 0; other_node->generate_priority_ = 0; other_node->generate_download_priority_ = 0; other_node->generate_upload_priority_ = 0; } else { cancel_generate(other_node); } if (size_i == other_node_i) { node->set_size(other_node->size_); } if (expected_size_i == other_node_i) { node->set_expected_size(other_node->expected_size_); } if (name_i == other_node_i) { node->set_name(other_node->name_); } if (url_i == other_node_i) { node->set_url(other_node->url_); } if (owner_i == other_node_i) { node->set_owner_dialog_id(other_node->owner_dialog_id_); } if (encryption_key_i == other_node_i) { node->set_encryption_key(other_node->encryption_key_); nodes[node_i]->set_encryption_key(nodes[encryption_key_i]->encryption_key_); } node->need_load_from_pmc_ |= other_node->need_load_from_pmc_; if (main_file_id_i == other_node_i) { node->main_file_id_ = other_node->main_file_id_; node->main_file_id_priority_ = other_node->main_file_id_priority_; } bool send_updates_flag = false; auto other_pmc_id = other_node->pmc_id_; node->file_ids_.insert(node->file_ids_.end(), other_node->file_ids_.begin(), other_node->file_ids_.end()); for (auto file_id : other_node->file_ids_) { auto file_id_info = get_file_id_info(file_id); CHECK(file_id_info->node_id_ == node_ids[other_node_i]) << node_ids[node_i] << " " << node_ids[other_node_i] << " " << file_id << " " << file_id_info->node_id_; file_id_info->node_id_ = node_ids[node_i]; send_updates_flag |= file_id_info->send_updates_flag_; } other_node = {}; if (send_updates_flag) { // node might not changed, but other_node might changed, so we need to send update anyway VLOG(update_file) << "File " << node->main_file_id_ << " has been merged"; node->on_info_changed(); } // Check is some download/upload queries are ready for (auto file_id : vector<FileId>(node->file_ids_)) { auto *info = get_file_id_info(file_id); if (info->download_priority_ != 0 && file_view.has_local_location()) { info->download_priority_ = 0; if (info->download_callback_) { info->download_callback_->on_download_ok(file_id); info->download_callback_.reset(); } } if (info->upload_priority_ != 0 && file_view.has_remote_location()) { info->upload_priority_ = 0; if (info->upload_callback_) { info->upload_callback_->on_upload_ok(file_id, nullptr); info->upload_callback_.reset(); } } } file_nodes_[node_ids[other_node_i]] = nullptr; run_generate(node); run_download(node); run_upload(node, {}); if (other_pmc_id != 0) { // node might not changed, but we need to merge nodes in pmc anyway node->on_pmc_changed(); } try_flush_node(node, node_i != remote_i, node_i != local_i, node_i != generate_i, other_pmc_id); return node->main_file_id_; } void FileManager::try_flush_node(FileNodePtr node, bool new_remote, bool new_local, bool new_generate, FileDbId other_pmc_id) { if (node->need_pmc_flush()) { if (file_db_) { load_from_pmc(node, true, true, true); flush_to_pmc(node, new_remote, new_local, new_generate); if (other_pmc_id != 0 && node->pmc_id_ != other_pmc_id) { file_db_->set_file_data_ref(other_pmc_id, node->pmc_id_); } } node->on_pmc_flushed(); } try_flush_node_info(node); } void FileManager::try_flush_node_info(FileNodePtr node) { if (node->need_info_flush()) { for (auto file_id : vector<FileId>(node->file_ids_)) { auto *info = get_file_id_info(file_id); if (info->send_updates_flag_) { VLOG(update_file) << "Send UpdateFile about file " << file_id; context_->on_file_updated(file_id); } } node->on_info_flushed(); } } void FileManager::clear_from_pmc(FileNodePtr node) { if (!file_db_) { return; } if (node->pmc_id_ == 0) { return; } LOG(INFO) << "Delete files " << format::as_array(node->file_ids_) << " from pmc"; FileData data; auto file_view = FileView(node); if (file_view.has_local_location()) { data.local_ = node->local_; } if (file_view.has_remote_location()) { data.remote_ = node->remote_; } if (file_view.has_generate_location()) { data.generate_ = node->generate_; } file_db_->clear_file_data(node->pmc_id_, data); } void FileManager::flush_to_pmc(FileNodePtr node, bool new_remote, bool new_local, bool new_generate) { if (!file_db_) { return; } FileView view(node); bool create_flag = false; if (node->pmc_id_ == 0) { create_flag = true; node->pmc_id_ = file_db_->create_pmc_id(); } FileData data; data.pmc_id_ = node->pmc_id_; data.local_ = node->local_; if (data.local_.type() == LocalFileLocation::Type::Full) { prepare_path_for_pmc(data.local_.full().file_type_, data.local_.full().path_); } data.remote_ = node->remote_; data.generate_ = node->generate_; if (data.generate_.type() == GenerateFileLocation::Type::Full && begins_with(data.generate_.full().conversion_, "#file_id#")) { data.generate_ = GenerateFileLocation(); } // TODO: not needed when GenerateLocation has constant convertion if (data.remote_.type() != RemoteFileLocation::Type::Full && data.local_.type() != LocalFileLocation::Type::Full) { data.local_ = LocalFileLocation(); data.remote_ = RemoteFileLocation(); } data.size_ = node->size_; data.expected_size_ = node->expected_size_; data.name_ = node->name_; data.encryption_key_ = node->encryption_key_; data.url_ = node->url_; data.owner_dialog_id_ = node->owner_dialog_id_; file_db_->set_file_data(node->pmc_id_, data, (create_flag || new_remote), (create_flag || new_local), (create_flag || new_generate)); } FileNode *FileManager::get_file_node_raw(FileId file_id, FileNodeId *file_node_id) { if (file_id.get() <= 0 || file_id.get() >= static_cast<int32>(file_id_info_.size())) { return nullptr; } FileNodeId node_id = file_id_info_[file_id.get()].node_id_; if (node_id == 0) { return nullptr; } if (file_node_id != nullptr) { *file_node_id = node_id; } return file_nodes_[node_id].get(); } FileNodePtr FileManager::get_sync_file_node(FileId file_id) { auto file_node = get_file_node(file_id); if (!file_node) { return {}; } load_from_pmc(file_node, true, true, true); return file_node; } void FileManager::load_from_pmc(FileNodePtr node, bool new_remote, bool new_local, bool new_generate) { if (!node->need_load_from_pmc_) { return; } auto file_id = node->main_file_id_; node->need_load_from_pmc_ = false; if (!file_db_) { return; } auto file_view = get_file_view(file_id); FullRemoteFileLocation remote; FullLocalFileLocation local; FullGenerateFileLocation generate; new_remote &= file_view.has_remote_location(); if (new_remote) { remote = file_view.remote_location(); } new_local &= file_view.has_local_location(); if (new_local) { local = get_file_view(file_id).local_location(); prepare_path_for_pmc(local.file_type_, local.path_); } new_generate &= file_view.has_generate_location(); if (new_generate) { generate = file_view.generate_location(); } auto load = [&](auto location) { TRY_RESULT(file_data, file_db_->get_file_data_sync(location)); TRY_RESULT(new_file_id, register_file(std::move(file_data), FileLocationSource::FromDb, "load_from_pmc", false)); TRY_RESULT(main_file_id, merge(file_id, new_file_id)); file_id = main_file_id; return Status::OK(); }; if (new_remote) { load(remote); } if (new_local) { load(local); } if (new_generate) { load(generate); } return; } bool FileManager::set_encryption_key(FileId file_id, FileEncryptionKey key) { auto node = get_sync_file_node(file_id); if (!node) { return false; } auto view = FileView(node); if (view.has_local_location() && view.has_remote_location()) { return false; } if (!node->encryption_key_.empty()) { return false; } node->set_encryption_key(std::move(key)); try_flush_node(node); return true; } bool FileManager::set_content(FileId file_id, BufferSlice bytes) { auto node = get_sync_file_node(file_id); if (!node) { return false; } if (node->local_.type() == LocalFileLocation::Type::Full) { // There was no download so we don't need an update return true; } if (node->download_priority_ == FROM_BYTES_PRIORITY) { return true; } cancel_download(node); auto *file_info = get_file_id_info(file_id); file_info->download_priority_ = FROM_BYTES_PRIORITY; node->set_download_priority(FROM_BYTES_PRIORITY); QueryId id = queries_container_.create(Query{file_id, Query::SetContent}); node->download_id_ = id; node->is_download_started_ = true; send_closure(file_load_manager_, &FileLoadManager::from_bytes, id, node->remote_.full().file_type_, std::move(bytes), node->name_); return true; } void FileManager::get_content(FileId file_id, Promise<BufferSlice> promise) { auto node = get_sync_file_node(file_id); if (!node) { return promise.set_error(Status::Error("Unknown file_id")); } auto status = check_local_location(node); status.ignore(); auto file_view = FileView(node); if (!file_view.has_local_location()) { return promise.set_error(Status::Error("No local location")); } send_closure(file_load_manager_, &FileLoadManager::get_content, node->local_.full(), std::move(promise)); } void FileManager::delete_file(FileId file_id, Promise<Unit> promise, const char *source) { LOG(INFO) << "Trying to delete file " << file_id << " from " << source; auto node = get_sync_file_node(file_id); if (!node) { return promise.set_value(Unit()); } auto file_view = FileView(node); // TODO: review delete condition if (file_view.has_local_location()) { if (begins_with(file_view.local_location().path_, get_files_dir(file_view.get_type()))) { LOG(INFO) << "Unlink file " << file_id << " at " << file_view.local_location().path_; clear_from_pmc(node); unlink(file_view.local_location().path_).ignore(); context_->on_new_file(-file_view.size()); node->set_local_location(LocalFileLocation(), 0); try_flush_node(node); } } else { if (file_view.get_type() == FileType::Encrypted) { clear_from_pmc(node); } if (node->local_.type() == LocalFileLocation::Type::Partial) { LOG(INFO) << "Unlink partial file " << file_id << " at " << node->local_.partial().path_; unlink(node->local_.partial().path_).ignore(); node->set_local_location(LocalFileLocation(), 0); try_flush_node(node); } } promise.set_value(Unit()); } void FileManager::download(FileId file_id, std::shared_ptr<DownloadCallback> callback, int32 new_priority) { auto node = get_sync_file_node(file_id); if (!node) { if (callback) { callback->on_download_error(file_id, Status::Error("File not found")); } return; } if (node->local_.type() == LocalFileLocation::Type::Full) { auto status = check_local_location(node); if (status.is_error()) { LOG(WARNING) << "Need to redownload file " << file_id << ": " << status.error(); } else { if (callback) { callback->on_download_ok(file_id); } return; } } else if (node->local_.type() == LocalFileLocation::Type::Partial) { auto status = check_local_location(node); if (status.is_error()) { LOG(WARNING) << "Need to download file " << file_id << " from beginning: " << status.error(); } } FileView file_view(node); if (!file_view.can_download_from_server() && !file_view.can_generate()) { if (callback) { callback->on_download_error(file_id, Status::Error("Can't download or generate file")); } return; } if (new_priority == -1) { if (node->is_download_started_) { return; } new_priority = 0; } auto *file_info = get_file_id_info(file_id); CHECK(new_priority == 0 || callback); file_info->download_priority_ = narrow_cast<int8>(new_priority); file_info->download_callback_ = std::move(callback); // TODO: send current progress? run_generate(node); run_download(node); try_flush_node(node); } void FileManager::run_download(FileNodePtr node) { if (node->need_load_from_pmc_) { return; } if (node->generate_id_) { return; } auto file_view = FileView(node); if (!file_view.can_download_from_server()) { return; } int8 priority = 0; for (auto id : node->file_ids_) { auto *info = get_file_id_info(id); if (info->download_priority_ > priority) { priority = info->download_priority_; } } auto old_priority = node->download_priority_; node->set_download_priority(priority); if (priority == 0) { if (old_priority != 0) { cancel_download(node); } return; } if (old_priority != 0) { CHECK(node->download_id_ != 0); send_closure(file_load_manager_, &FileLoadManager::update_priority, node->download_id_, priority); return; } CHECK(node->download_id_ == 0); CHECK(!node->file_ids_.empty()); auto file_id = node->file_ids_.back(); QueryId id = queries_container_.create(Query{file_id, Query::Download}); node->download_id_ = id; node->is_download_started_ = false; send_closure(file_load_manager_, &FileLoadManager::download, id, node->remote_.full(), node->local_, node->size_, node->name_, node->encryption_key_, priority); } void FileManager::resume_upload(FileId file_id, std::vector<int> bad_parts, std::shared_ptr<UploadCallback> callback, int32 new_priority, uint64 upload_order) { LOG(INFO) << "Resume upload of file " << file_id << " with priority " << new_priority; auto node = get_sync_file_node(file_id); if (!node) { if (callback) { callback->on_upload_error(file_id, Status::Error("Wrong file id to upload")); } return; } if (node->upload_pause_ == file_id) { node->upload_pause_ = FileId(); } FileView file_view(node); if (file_view.has_remote_location() && file_view.get_type() != FileType::Thumbnail && file_view.get_type() != FileType::EncryptedThumbnail) { if (callback) { callback->on_upload_ok(file_id, nullptr); } return; } if (file_view.has_local_location()) { auto status = check_local_location(node); if (status.is_error()) { LOG(INFO) << "Full local location of file " << file_id << " for upload is invalid: " << status; } } if (!file_view.has_local_location() && !file_view.has_generate_location()) { if (callback) { callback->on_upload_error(file_id, Status::Error("Need full local (or generate) location for upload")); } return; } auto *file_info = get_file_id_info(file_id); CHECK(new_priority == 0 || callback); file_info->upload_order_ = upload_order; file_info->upload_priority_ = narrow_cast<int8>(new_priority); file_info->upload_callback_ = std::move(callback); // TODO: send current progress? run_generate(node); run_upload(node, std::move(bad_parts)); try_flush_node(node); } bool FileManager::delete_partial_remote_location(FileId file_id) { auto node = get_sync_file_node(file_id); if (!node) { LOG(INFO) << "Wrong file id " << file_id; return false; } if (node->upload_pause_ == file_id) { node->upload_pause_ = FileId(); } if (node->remote_.type() == RemoteFileLocation::Type::Full) { LOG(INFO) << "File " << file_id << " is already uploaded"; return true; } node->set_remote_location(RemoteFileLocation(), FileLocationSource::None, 0); auto *file_info = get_file_id_info(file_id); file_info->upload_priority_ = 0; if (node->local_.type() != LocalFileLocation::Type::Full) { LOG(INFO) << "Need full local location to upload file " << file_id; return false; } auto status = check_local_location(node); if (status.is_error()) { LOG(INFO) << "Need full local location to upload file " << file_id << ": " << status; return false; } run_upload(node, std::vector<int>()); try_flush_node(node); return true; } void FileManager::external_file_generate_progress(int64 id, int32 expected_size, int32 local_prefix_size, Promise<> promise) { send_closure(file_generate_manager_, &FileGenerateManager::external_file_generate_progress, id, expected_size, local_prefix_size, std::move(promise)); } void FileManager::external_file_generate_finish(int64 id, Status status, Promise<> promise) { send_closure(file_generate_manager_, &FileGenerateManager::external_file_generate_finish, id, std::move(status), std::move(promise)); } void FileManager::run_generate(FileNodePtr node) { if (node->need_load_from_pmc_) { return; } FileView file_view(node); if (file_view.has_local_location() || file_view.can_download_from_server() || !file_view.can_generate()) { return; } int8 download_priority = 0; int8 upload_priority = 0; FileId file_id; for (auto id : node->file_ids_) { auto *info = get_file_id_info(id); if (info->download_priority_ > download_priority) { download_priority = info->download_priority_; if (download_priority > upload_priority) { file_id = id; } } if (info->upload_priority_ > upload_priority) { upload_priority = info->upload_priority_; if (upload_priority > download_priority) { file_id = id; } } } auto old_priority = node->generate_priority_; node->set_generate_priority(download_priority, upload_priority); if (node->generate_priority_ == 0) { if (old_priority != 0) { LOG(INFO) << "Cancel file " << file_id << " generation"; cancel_generate(node); } return; } if (old_priority != 0) { LOG(INFO) << "TODO: change file " << file_id << " generation priority"; return; } QueryId id = queries_container_.create(Query{file_id, Query::Generate}); node->generate_id_ = id; send_closure(file_generate_manager_, &FileGenerateManager::generate_file, id, node->generate_.full(), node->local_, node->name_, [file_manager = this, id] { class Callback : public FileGenerateCallback { ActorId<FileManager> actor_; uint64 query_id_; public: Callback(ActorId<FileManager> actor, QueryId id) : actor_(std::move(actor)), query_id_(id) { } void on_partial_generate(const PartialLocalFileLocation &partial_local, int32 expected_size) override { send_closure(actor_, &FileManager::on_partial_generate, query_id_, partial_local, expected_size); } void on_ok(const FullLocalFileLocation &local) override { send_closure(actor_, &FileManager::on_generate_ok, query_id_, local); } void on_error(Status error) override { send_closure(actor_, &FileManager::on_error, query_id_, std::move(error)); } }; return std::make_unique<Callback>(file_manager->actor_id(file_manager), id); }()); LOG(INFO) << "File " << file_id << " generate request has sent to FileGenerateManager"; } void FileManager::run_upload(FileNodePtr node, std::vector<int> bad_parts) { if (node->need_load_from_pmc_) { return; } if (node->upload_pause_.is_valid()) { return; } FileView file_view(node); if (!file_view.has_local_location()) { if (node->get_by_hash_ || node->generate_id_ == 0 || !node->generate_was_update_) { return; } } int8 priority = 0; FileId file_id; for (auto id : node->file_ids_) { auto *info = get_file_id_info(id); if (info->upload_priority_ > priority) { priority = info->upload_priority_; file_id = id; } } auto old_priority = node->upload_priority_; node->set_upload_priority(priority); if (priority == 0) { if (old_priority != 0) { LOG(INFO) << "Cancel file " << file_id << " uploading"; cancel_upload(node); } return; } // create encryption key if necessary if (((file_view.has_generate_location() && file_view.generate_location().file_type_ == FileType::Encrypted) || (file_view.has_local_location() && file_view.local_location().file_type_ == FileType::Encrypted)) && file_view.encryption_key().empty()) { CHECK(!node->file_ids_.empty()); bool success = set_encryption_key(node->file_ids_[0], FileEncryptionKey::create()); LOG_IF(FATAL, !success) << "Failed to set encryption key for file " << file_id; } if (old_priority != 0) { LOG(INFO) << "File " << file_id << " is already uploading"; CHECK(node->upload_id_ != 0); send_closure(file_load_manager_, &FileLoadManager::update_priority, node->upload_id_, narrow_cast<int8>(-priority)); return; } CHECK(node->upload_id_ == 0); if (node->remote_.type() != RemoteFileLocation::Type::Partial && node->get_by_hash_) { QueryId id = queries_container_.create(Query{file_id, Query::UploadByHash}); node->upload_id_ = id; send_closure(file_load_manager_, &FileLoadManager::upload_by_hash, id, node->local_.full(), node->size_, narrow_cast<int8>(-priority)); return; } QueryId id = queries_container_.create(Query{file_id, Query::Upload}); node->upload_id_ = id; send_closure(file_load_manager_, &FileLoadManager::upload, id, node->local_, node->remote_, node->size_, node->encryption_key_, narrow_cast<int8>(bad_parts.empty() ? -priority : priority), std::move(bad_parts)); LOG(INFO) << "File " << file_id << " upload request has sent to FileLoadManager"; } void FileManager::upload(FileId file_id, std::shared_ptr<UploadCallback> callback, int32 new_priority, uint64 upload_order) { return resume_upload(file_id, std::vector<int>(), std::move(callback), new_priority, upload_order); } // is't quite stupid, yep // 0x00 <count of zeroes> static string zero_decode(Slice s) { string res; for (size_t n = s.size(), i = 0; i < n; i++) { if (i + 1 < n && s[i] == 0) { res.append(static_cast<unsigned char>(s[i + 1]), 0); i++; continue; } res.push_back(s[i]); } return res; } static string zero_encode(Slice s) { string res; for (size_t n = s.size(), i = 0; i < n; i++) { res.push_back(s[i]); if (s[i] == 0) { unsigned char cnt = 1; while (cnt < 250 && i + cnt < n && s[i + cnt] == 0) { cnt++; } res.push_back(cnt); i += cnt - 1; } } return res; } static bool is_document_type(FileType type) { return type == FileType::Document || type == FileType::Sticker || type == FileType::Audio || type == FileType::Animation; } string FileManager::get_persistent_id(const FullRemoteFileLocation &location) { auto binary = serialize(location); binary = zero_encode(binary); binary.push_back(PERSISTENT_ID_VERSION); return base64url_encode(binary); } Result<string> FileManager::to_persistent_id(FileId file_id) { auto view = get_file_view(file_id); if (view.empty()) { return Status::Error(10, "Unknown file id"); } if (!view.has_remote_location()) { return Status::Error(10, "File has no persistent id"); } return get_persistent_id(view.remote_location()); } Result<FileId> FileManager::from_persistent_id(CSlice persistent_id, FileType file_type) { if (persistent_id.find('.') != string::npos) { string input_url = persistent_id.str(); // TODO do not copy persistent_id TRY_RESULT(http_url, parse_url(input_url)); auto url = http_url.get_url(); if (!clean_input_string(url)) { return Status::Error(400, "URL must be in UTF-8"); } return register_url(std::move(url), file_type, FileLocationSource::FromUser, DialogId()); } auto r_binary = base64url_decode(persistent_id); if (r_binary.is_error()) { return Status::Error(10, "Wrong remote file id specified: " + r_binary.error().message().str()); } auto binary = r_binary.move_as_ok(); if (binary.empty()) { return Status::Error(10, "Remote file id can't be empty"); } if (binary.back() != PERSISTENT_ID_VERSION) { return Status::Error(10, "Wrong remote file id specified: can't unserialize it. Wrong last symbol"); } binary.pop_back(); binary = zero_decode(binary); FullRemoteFileLocation remote_location; auto status = unserialize(remote_location, binary); if (status.is_error()) { return Status::Error(10, "Wrong remote file id specified: can't unserialize it"); } auto &real_file_type = remote_location.file_type_; if (is_document_type(real_file_type) && is_document_type(file_type)) { real_file_type = file_type; } else if (real_file_type != file_type && file_type != FileType::Temp) { return Status::Error(10, "Type of file mismatch"); } FileData data; data.remote_ = RemoteFileLocation(std::move(remote_location)); return register_file(std::move(data), FileLocationSource::FromUser, "from_persistent_id", false).move_as_ok(); } FileView FileManager::get_file_view(FileId file_id) const { auto file_node = get_file_node(file_id); if (!file_node) { return FileView(); } return FileView(file_node); } FileView FileManager::get_sync_file_view(FileId file_id) { auto file_node = get_sync_file_node(file_id); if (!file_node) { return FileView(); } return FileView(file_node); } tl_object_ptr<td_api::file> FileManager::get_file_object(FileId file_id, bool with_main_file_id) { auto file_view = get_sync_file_view(file_id); if (file_view.empty()) { return td_api::make_object<td_api::file>(0, 0, 0, td_api::make_object<td_api::localFile>(), td_api::make_object<td_api::remoteFile>()); } string persistent_file_id; if (file_view.has_remote_location()) { persistent_file_id = get_persistent_id(file_view.remote_location()); } else if (file_view.has_url()) { persistent_file_id = file_view.url(); } int32 size = narrow_cast<int32>(file_view.size()); int32 expected_size = narrow_cast<int32>(file_view.expected_size()); int32 local_size = narrow_cast<int32>(file_view.local_size()); int32 local_total_size = narrow_cast<int32>(file_view.local_total_size()); int32 remote_size = narrow_cast<int32>(file_view.remote_size()); string path = file_view.path(); bool can_be_downloaded = file_view.can_download_from_server() || file_view.can_generate(); bool can_be_deleted = file_view.can_delete(); auto result_file_id = file_id; auto *file_info = get_file_id_info(result_file_id); if (with_main_file_id) { if (!file_info->send_updates_flag_) { result_file_id = file_view.file_id(); } file_info = get_file_id_info(file_view.file_id()); } file_info->send_updates_flag_ = true; VLOG(update_file) << "Send file " << file_id << " as " << result_file_id << " and update send_updates_flag_ for file " << (with_main_file_id ? file_view.file_id() : result_file_id); return td_api::make_object<td_api::file>( result_file_id.get(), size, expected_size, td_api::make_object<td_api::localFile>(std::move(path), can_be_downloaded, can_be_deleted, file_view.is_downloading(), file_view.has_local_location(), local_size, local_total_size), td_api::make_object<td_api::remoteFile>(std::move(persistent_file_id), file_view.is_uploading(), file_view.has_remote_location(), remote_size)); } Result<FileId> FileManager::check_input_file_id(FileType type, Result<FileId> result, bool is_encrypted, bool allow_zero) { TRY_RESULT(file_id, std::move(result)); if (allow_zero && !file_id.is_valid()) { return FileId(); } auto file_node = get_file_node(file_id); if (!file_node) { return Status::Error(6, "File not found"); } auto file_view = FileView(file_node); FileType real_type = file_view.get_type(); if (!is_encrypted) { if (real_type != type && !(real_type == FileType::Temp && file_view.has_url()) && !(is_document_type(real_type) && is_document_type(type))) { // TODO: send encrypted file to unencrypted chat return Status::Error(6, "Type of file mismatch"); } } if (!file_view.has_remote_location()) { // TODO why not return file_id here? We will dup it anyway // But it will not be duped if has_input_media(), so for now we can't return main_file_id return dup_file_id(file_id); } return file_node->main_file_id_; } Result<FileId> FileManager::get_input_thumbnail_file_id(const tl_object_ptr<td_api::InputFile> &thumbnail_input_file, DialogId owner_dialog_id, bool is_encrypted) { if (thumbnail_input_file == nullptr) { return Status::Error(6, "inputThumbnail not specified"); } switch (thumbnail_input_file->get_id()) { case td_api::inputFileLocal::ID: { const string &path = static_cast<const td_api::inputFileLocal *>(thumbnail_input_file.get())->path_; return register_local( FullLocalFileLocation(is_encrypted ? FileType::EncryptedThumbnail : FileType::Thumbnail, path, 0), owner_dialog_id, 0, false); } case td_api::inputFileId::ID: return Status::Error(6, "InputFileId is not supported for thumbnails"); case td_api::inputFileRemote::ID: return Status::Error(6, "InputFileRemote is not supported for thumbnails"); case td_api::inputFileGenerated::ID: { auto *generated_thumbnail = static_cast<const td_api::inputFileGenerated *>(thumbnail_input_file.get()); return register_generate(is_encrypted ? FileType::EncryptedThumbnail : FileType::Thumbnail, FileLocationSource::FromUser, generated_thumbnail->original_path_, generated_thumbnail->conversion_, owner_dialog_id, generated_thumbnail->expected_size_); } default: UNREACHABLE(); return Status::Error(500, "Unreachable"); } } Result<FileId> FileManager::get_input_file_id(FileType type, const tl_object_ptr<td_api::InputFile> &file, DialogId owner_dialog_id, bool allow_zero, bool is_encrypted, bool get_by_hash) { if (is_encrypted) { get_by_hash = false; } if (!file) { if (allow_zero) { return FileId(); } return Status::Error(6, "InputFile not specified"); } auto r_file_id = [&]() -> Result<FileId> { switch (file->get_id()) { case td_api::inputFileLocal::ID: { const string &path = static_cast<const td_api::inputFileLocal *>(file.get())->path_; if (allow_zero && path.empty()) { return FileId(); } return register_local(FullLocalFileLocation(is_encrypted ? FileType::Encrypted : type, path, 0), owner_dialog_id, 0, get_by_hash); } case td_api::inputFileId::ID: { FileId file_id(static_cast<const td_api::inputFileId *>(file.get())->id_); if (!file_id.is_valid()) { return FileId(); } return file_id; } case td_api::inputFileRemote::ID: { const string &file_persistent_id = static_cast<const td_api::inputFileRemote *>(file.get())->id_; if (allow_zero && file_persistent_id.empty()) { return FileId(); } return from_persistent_id(file_persistent_id, type); } case td_api::inputFileGenerated::ID: { auto *generated_file = static_cast<const td_api::inputFileGenerated *>(file.get()); return register_generate(is_encrypted ? FileType::Encrypted : type, FileLocationSource::FromUser, generated_file->original_path_, generated_file->conversion_, owner_dialog_id, generated_file->expected_size_); } default: UNREACHABLE(); return Status::Error(500, "Unreachable"); } }(); return check_input_file_id(type, std::move(r_file_id), is_encrypted, allow_zero); } vector<tl_object_ptr<telegram_api::InputDocument>> FileManager::get_input_documents(const vector<FileId> &file_ids) { vector<tl_object_ptr<telegram_api::InputDocument>> result; result.reserve(file_ids.size()); for (auto file_id : file_ids) { auto file_view = get_file_view(file_id); CHECK(!file_view.empty()); CHECK(file_view.has_remote_location()); CHECK(!file_view.remote_location().is_web()); result.push_back(file_view.remote_location().as_input_document()); } return result; } FileId FileManager::next_file_id() { if (!empty_file_ids_.empty()) { auto res = empty_file_ids_.back(); empty_file_ids_.pop_back(); return res; } FileId res(static_cast<int32>(file_id_info_.size())); // LOG(ERROR) << "NEXT file_id " << res; file_id_info_.push_back({}); return res; } FileManager::FileNodeId FileManager::next_file_node_id() { FileNodeId res = static_cast<FileNodeId>(file_nodes_.size()); file_nodes_.emplace_back(nullptr); return res; } void FileManager::on_start_download(QueryId query_id) { auto query = queries_container_.get(query_id); CHECK(query != nullptr); auto file_id = query->file_id_; auto file_node = get_file_node(file_id); if (!file_node) { return; } if (file_node->download_id_ != query_id) { return; } LOG(DEBUG) << "Start to download part of file " << file_id; file_node->is_download_started_ = true; } void FileManager::on_partial_download(QueryId query_id, const PartialLocalFileLocation &partial_local, int64 ready_size) { auto query = queries_container_.get(query_id); CHECK(query != nullptr); auto file_id = query->file_id_; auto file_node = get_file_node(file_id); if (!file_node) { return; } if (file_node->download_id_ != query_id) { return; } file_node->set_local_location(LocalFileLocation(partial_local), ready_size); try_flush_node(file_node); } void FileManager::on_partial_upload(QueryId query_id, const PartialRemoteFileLocation &partial_remote, int64 ready_size) { auto query = queries_container_.get(query_id); CHECK(query != nullptr); auto file_id = query->file_id_; auto file_node = get_file_node(file_id); if (!file_node) { return; } if (file_node->upload_id_ != query_id) { return; } file_node->set_remote_location(RemoteFileLocation(partial_remote), FileLocationSource::None, ready_size); try_flush_node(file_node); } void FileManager::on_download_ok(QueryId query_id, const FullLocalFileLocation &local, int64 size) { auto file_id = finish_query(query_id).first.file_id_; LOG(INFO) << "ON DOWNLOAD OK file " << file_id << " of size " << size; auto r_new_file_id = register_local(local, DialogId(), size); if (r_new_file_id.is_error()) { LOG(ERROR) << "Can't register local file after download: " << r_new_file_id.error(); } else { context_->on_new_file(get_file_view(r_new_file_id.ok()).size()); LOG_STATUS(merge(r_new_file_id.ok(), file_id)); } } void FileManager::on_upload_ok(QueryId query_id, FileType file_type, const PartialRemoteFileLocation &partial_remote, int64 size) { CHECK(partial_remote.ready_part_count_ == partial_remote.part_count_); auto some_file_id = finish_query(query_id).first.file_id_; LOG(INFO) << "ON UPLOAD OK file " << some_file_id << " of size " << size; auto file_node = get_file_node(some_file_id); if (!file_node) { return; } FileId file_id; uint64 file_id_upload_order{std::numeric_limits<uint64>::max()}; for (auto id : file_node->file_ids_) { auto *info = get_file_id_info(id); if (info->upload_priority_ != 0 && info->upload_order_ < file_id_upload_order) { file_id = id; file_id_upload_order = info->upload_order_; } } if (!file_id.is_valid()) { return; } auto *file_info = get_file_id_info(file_id); file_info->upload_priority_ = 0; file_info->download_priority_ = 0; FileView file_view(file_node); string file_name = get_file_name(file_type, file_view.has_local_location() ? file_view.local_location().path_ : ""); if (file_view.is_encrypted()) { tl_object_ptr<telegram_api::InputEncryptedFile> input_file; if (partial_remote.is_big_) { input_file = make_tl_object<telegram_api::inputEncryptedFileBigUploaded>( partial_remote.file_id_, partial_remote.part_count_, file_view.encryption_key().calc_fingerprint()); } else { input_file = make_tl_object<telegram_api::inputEncryptedFileUploaded>( partial_remote.file_id_, partial_remote.part_count_, "", file_view.encryption_key().calc_fingerprint()); } if (file_info->upload_callback_) { file_info->upload_callback_->on_upload_encrypted_ok(file_id, std::move(input_file)); file_node->upload_pause_ = file_id; file_info->upload_callback_.reset(); } } else { tl_object_ptr<telegram_api::InputFile> input_file; if (partial_remote.is_big_) { input_file = make_tl_object<telegram_api::inputFileBig>(partial_remote.file_id_, partial_remote.part_count_, std::move(file_name)); } else { input_file = make_tl_object<telegram_api::inputFile>(partial_remote.file_id_, partial_remote.part_count_, std::move(file_name), ""); } if (file_info->upload_callback_) { file_info->upload_callback_->on_upload_ok(file_id, std::move(input_file)); file_node->upload_pause_ = file_id; file_info->upload_callback_.reset(); } } } void FileManager::on_upload_full_ok(QueryId query_id, const FullRemoteFileLocation &remote) { LOG(INFO) << "ON UPLOAD OK"; auto file_id = finish_query(query_id).first.file_id_; auto new_file_id = register_remote(remote, FileLocationSource::FromServer, DialogId(), 0, 0, ""); LOG_STATUS(merge(new_file_id, file_id)); } void FileManager::on_partial_generate(QueryId query_id, const PartialLocalFileLocation &partial_local, int32 expected_size) { LOG(INFO) << "on_parital_generate: " << partial_local.path_ << " " << partial_local.ready_part_count_; auto query = queries_container_.get(query_id); CHECK(query != nullptr); auto file_id = query->file_id_; auto file_node = get_file_node(file_id); if (!file_node) { return; } if (file_node->generate_id_ != query_id) { return; } file_node->set_local_location(LocalFileLocation(partial_local), 0); // TODO check for size and local_size, abort generation if needed if (expected_size != 0) { file_node->set_expected_size(expected_size); } if (!file_node->generate_was_update_) { file_node->generate_was_update_ = true; run_upload(file_node, {}); } if (file_node->upload_id_ != 0) { send_closure(file_load_manager_, &FileLoadManager::update_local_file_location, file_node->upload_id_, LocalFileLocation(partial_local)); } try_flush_node(file_node); } void FileManager::on_generate_ok(QueryId query_id, const FullLocalFileLocation &local) { LOG(INFO) << "on_ok_generate: " << local; Query query; bool was_active; std::tie(query, was_active) = finish_query(query_id); auto generate_file_id = query.file_id_; auto file_node = get_file_node(generate_file_id); if (!file_node) { return; } auto old_upload_id = file_node->upload_id_; auto r_new_file_id = register_local(local, DialogId(), 0); Status status; if (r_new_file_id.is_error()) { status = Status::Error(PSLICE() << "Can't register local file after generate: " << r_new_file_id.error()); } else { auto result = merge(r_new_file_id.ok(), generate_file_id); if (result.is_error()) { status = result.move_as_error(); } } file_node = get_file_node(generate_file_id); if (status.is_error()) { return on_error_impl(file_node, query.type_, was_active, std::move(status)); } CHECK(file_node); context_->on_new_file(FileView(file_node).size()); run_upload(file_node, {}); if (was_active) { if (old_upload_id != 0 && old_upload_id == file_node->upload_id_) { send_closure(file_load_manager_, &FileLoadManager::update_local_file_location, file_node->upload_id_, LocalFileLocation(local)); } } } void FileManager::on_error(QueryId query_id, Status status) { Query query; bool was_active; std::tie(query, was_active) = finish_query(query_id); auto node = get_file_node(query.file_id_); if (!node) { LOG(ERROR) << "Can't find file node for " << query.file_id_; return; } if (query.type_ == Query::UploadByHash) { LOG(INFO) << "Upload By Hash failed: " << status << ", restart upload"; node->get_by_hash_ = false; run_upload(node, {}); return; } on_error_impl(node, query.type_, was_active, std::move(status)); } void FileManager::on_error_impl(FileNodePtr node, FileManager::Query::Type type, bool was_active, Status status) { SCOPE_EXIT { try_flush_node(node); }; if (status.code() != 1) { LOG(WARNING) << "Failed to upload/download/generate file: " << status << ". Query type = " << type << ". File type is " << file_type_name[static_cast<int32>(FileView(node).get_type())]; if (status.code() == 0) { // Remove partial locations if (node->local_.type() == LocalFileLocation::Type::Partial && status.message() != "FILE_UPLOAD_RESTART") { LOG(INFO) << "Unlink file " << node->local_.partial().path_; unlink(node->local_.partial().path_).ignore(); node->set_local_location(LocalFileLocation(), 0); } if (node->remote_.type() == RemoteFileLocation::Type::Partial) { node->set_remote_location(RemoteFileLocation(), FileLocationSource::None, 0); } status = Status::Error(400, status.message()); } } if (status.message() == "FILE_UPLOAD_RESTART") { run_upload(node, {}); return; } if (!was_active) { return; } // Stop everything on error cancel_generate(node); cancel_download(node); cancel_upload(node); for (auto file_id : vector<FileId>(node->file_ids_)) { auto *info = get_file_id_info(file_id); if (info->download_priority_ != 0) { info->download_priority_ = 0; if (info->download_callback_) { info->download_callback_->on_download_error(file_id, status.clone()); info->download_callback_.reset(); } } if (info->upload_priority_ != 0) { info->upload_priority_ = 0; if (info->upload_callback_) { info->upload_callback_->on_upload_error(file_id, status.clone()); info->upload_callback_.reset(); } } } } std::pair<FileManager::Query, bool> FileManager::finish_query(QueryId query_id) { SCOPE_EXIT { queries_container_.erase(query_id); }; auto query = queries_container_.get(query_id); CHECK(query != nullptr); auto res = *query; auto node = get_file_node(res.file_id_); if (!node) { return std::make_pair(res, false); } bool was_active = false; if (node->generate_id_ == query_id) { node->generate_id_ = 0; node->generate_was_update_ = false; node->set_generate_priority(0, 0); was_active = true; } if (node->download_id_ == query_id) { node->download_id_ = 0; node->is_download_started_ = false; node->set_download_priority(0); was_active = true; } if (node->upload_id_ == query_id) { node->upload_id_ = 0; node->set_upload_priority(0); was_active = true; } return std::make_pair(res, was_active); } void FileManager::hangup() { file_db_.reset(); file_generate_manager_.reset(); file_load_manager_.reset(); stop(); } void FileManager::tear_down() { parent_.reset(); } } // namespace td
33.726081
120
0.67063
takpare
4b2311d4fe27db8d3017f248e1344b022bf710ad
37,034
cpp
C++
Unity/build/iOS-Simulator/Classes/Native/Bulk_UnityEngine.InputModule_0.cpp
AnnaOpareva/Unity-iOS
dba005999d63e387167a36fe1feafd0b900626a8
[ "MIT" ]
31
2019-01-15T16:32:02.000Z
2021-12-21T21:59:57.000Z
Unity/build/iOS-Simulator/Classes/Native/Bulk_UnityEngine.InputModule_0.cpp
AnnaOpareva/Unity-iOS
dba005999d63e387167a36fe1feafd0b900626a8
[ "MIT" ]
5
2019-05-16T05:36:44.000Z
2022-03-18T10:12:53.000Z
Unity/build/iOS-Simulator/Classes/Native/Bulk_UnityEngine.InputModule_0.cpp
AnnaOpareva/Unity-iOS
dba005999d63e387167a36fe1feafd0b900626a8
[ "MIT" ]
3
2019-05-25T02:30:43.000Z
2021-10-12T10:56:57.000Z
#import <TargetConditionals.h> // Modified by PostBuild.cs #if TARGET_OS_SIMULATOR // Modified by PostBuild.cs #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "il2cpp-class-internals.h" #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.Action`1<System.Int32Enum> struct Action_1_tABA1E3BFA092E3309A0ECC53722E4F9826DCE983; // System.Action`1<UnityEngineInternal.Input.NativeInputUpdateType> struct Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1; // System.Action`2<System.Int32,System.Object> struct Action_2_tCC05A68F0FC31E84E54091438749644062A6C27F; // System.Action`2<System.Int32,System.String> struct Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36; // System.Action`3<System.Int32Enum,System.Int32,System.IntPtr> struct Action_3_tA1F157C5B221E0F24BDD45BD4F6A9C25B81357F9; // System.Action`3<UnityEngineInternal.Input.NativeInputUpdateType,System.Int32,System.IntPtr> struct Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4; // System.AsyncCallback struct AsyncCallback_t3F3DA3BEDAEE81DD1D24125DF8EB30E85EE14DA4; // System.Char[] struct CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2; // System.DelegateData struct DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE; // System.Delegate[] struct DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86; // System.IAsyncResult struct IAsyncResult_t8E194308510B375B42432981AE5E7488C458D598; // System.Reflection.MethodInfo struct MethodInfo_t; // System.String struct String_t; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017; extern RuntimeClass* NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_il2cpp_TypeInfo_var; extern const RuntimeMethod* Action_1_Invoke_m60C027AA0F030AC2B693BEFB8E213066CD9000D0_RuntimeMethod_var; extern const RuntimeMethod* Action_2_Invoke_mC215CA1421B7DF8C0023F107CA72045332A79489_RuntimeMethod_var; extern const RuntimeMethod* Action_3_Invoke_m14ADB6DD0234BFB201A7050855A62A4DA2612D0A_RuntimeMethod_var; extern const uint32_t NativeInputSystem_NotifyBeforeUpdate_m317D534DBDD42915CE638051B87E48B76ED28574_MetadataUsageId; extern const uint32_t NativeInputSystem_NotifyDeviceDiscovered_m48C3818DDCFB1A2C0530B6CE1C78743ABA4614B0_MetadataUsageId; extern const uint32_t NativeInputSystem_NotifyUpdate_m77B02AB50FCFA5649D7203E76163C757EE1DA3CA_MetadataUsageId; #ifndef U3CMODULEU3E_TF8A948C14EE892A95D0E0992A0BE6B176FF2DA1D_H #define U3CMODULEU3E_TF8A948C14EE892A95D0E0992A0BE6B176FF2DA1D_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_tF8A948C14EE892A95D0E0992A0BE6B176FF2DA1D { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_TF8A948C14EE892A95D0E0992A0BE6B176FF2DA1D_H #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H struct Il2CppArrayBounds; #ifndef RUNTIMEARRAY_H #define RUNTIMEARRAY_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEARRAY_H #ifndef STRING_T_H #define STRING_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::m_stringLength int32_t ___m_stringLength_0; // System.Char System.String::m_firstChar Il2CppChar ___m_firstChar_1; public: inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); } inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; } inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; } inline void set_m_stringLength_0(int32_t value) { ___m_stringLength_0 = value; } inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); } inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; } inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; } inline void set_m_firstChar_1(Il2CppChar value) { ___m_firstChar_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_5; public: inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); } inline String_t* get_Empty_5() const { return ___Empty_5; } inline String_t** get_address_of_Empty_5() { return &___Empty_5; } inline void set_Empty_5(String_t* value) { ___Empty_5 = value; Il2CppCodeGenWriteBarrier((&___Empty_5), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRING_T_H #ifndef VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H #define VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com { }; #endif // VALUETYPE_T4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_H #ifndef NATIVEINPUTSYSTEM_T522F6391494159917EE6963E9E61C9EFA9C5795C_H #define NATIVEINPUTSYSTEM_T522F6391494159917EE6963E9E61C9EFA9C5795C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngineInternal.Input.NativeInputSystem struct NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C : public RuntimeObject { public: public: }; struct NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_StaticFields { public: // System.Action`3<UnityEngineInternal.Input.NativeInputUpdateType,System.Int32,System.IntPtr> UnityEngineInternal.Input.NativeInputSystem::onUpdate Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 * ___onUpdate_0; // System.Action`1<UnityEngineInternal.Input.NativeInputUpdateType> UnityEngineInternal.Input.NativeInputSystem::onBeforeUpdate Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 * ___onBeforeUpdate_1; // System.Action`2<System.Int32,System.String> UnityEngineInternal.Input.NativeInputSystem::s_OnDeviceDiscoveredCallback Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 * ___s_OnDeviceDiscoveredCallback_2; public: inline static int32_t get_offset_of_onUpdate_0() { return static_cast<int32_t>(offsetof(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_StaticFields, ___onUpdate_0)); } inline Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 * get_onUpdate_0() const { return ___onUpdate_0; } inline Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 ** get_address_of_onUpdate_0() { return &___onUpdate_0; } inline void set_onUpdate_0(Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 * value) { ___onUpdate_0 = value; Il2CppCodeGenWriteBarrier((&___onUpdate_0), value); } inline static int32_t get_offset_of_onBeforeUpdate_1() { return static_cast<int32_t>(offsetof(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_StaticFields, ___onBeforeUpdate_1)); } inline Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 * get_onBeforeUpdate_1() const { return ___onBeforeUpdate_1; } inline Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 ** get_address_of_onBeforeUpdate_1() { return &___onBeforeUpdate_1; } inline void set_onBeforeUpdate_1(Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 * value) { ___onBeforeUpdate_1 = value; Il2CppCodeGenWriteBarrier((&___onBeforeUpdate_1), value); } inline static int32_t get_offset_of_s_OnDeviceDiscoveredCallback_2() { return static_cast<int32_t>(offsetof(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_StaticFields, ___s_OnDeviceDiscoveredCallback_2)); } inline Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 * get_s_OnDeviceDiscoveredCallback_2() const { return ___s_OnDeviceDiscoveredCallback_2; } inline Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 ** get_address_of_s_OnDeviceDiscoveredCallback_2() { return &___s_OnDeviceDiscoveredCallback_2; } inline void set_s_OnDeviceDiscoveredCallback_2(Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 * value) { ___s_OnDeviceDiscoveredCallback_2 = value; Il2CppCodeGenWriteBarrier((&___s_OnDeviceDiscoveredCallback_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVEINPUTSYSTEM_T522F6391494159917EE6963E9E61C9EFA9C5795C_H #ifndef BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H #define BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Boolean struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C { public: // System.Boolean System.Boolean::m_value bool ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C, ___m_value_0)); } inline bool get_m_value_0() const { return ___m_value_0; } inline bool* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(bool value) { ___m_value_0 = value; } }; struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields { public: // System.String System.Boolean::TrueString String_t* ___TrueString_5; // System.String System.Boolean::FalseString String_t* ___FalseString_6; public: inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___TrueString_5)); } inline String_t* get_TrueString_5() const { return ___TrueString_5; } inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; } inline void set_TrueString_5(String_t* value) { ___TrueString_5 = value; Il2CppCodeGenWriteBarrier((&___TrueString_5), value); } inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___FalseString_6)); } inline String_t* get_FalseString_6() const { return ___FalseString_6; } inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; } inline void set_FalseString_6(String_t* value) { ___FalseString_6 = value; Il2CppCodeGenWriteBarrier((&___FalseString_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEAN_TB53F6830F670160873277339AA58F15CAED4399C_H #ifndef ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H #define ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521 : public ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF { public: public: }; struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_com { }; #endif // ENUM_T2AF27C02B8653AE29442467390005ABC74D8F521_H #ifndef INT32_T585191389E07734F19F3156FF88FB3EF4800D102_H #define INT32_T585191389E07734F19F3156FF88FB3EF4800D102_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 struct Int32_t585191389E07734F19F3156FF88FB3EF4800D102 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t585191389E07734F19F3156FF88FB3EF4800D102, ___m_value_0)); } inline int32_t get_m_value_0() const { return ___m_value_0; } inline int32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int32_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32_T585191389E07734F19F3156FF88FB3EF4800D102_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef VOID_T22962CB4C05B1D89B55A6E1139F0E87A90987017_H #define VOID_T22962CB4C05B1D89B55A6E1139F0E87A90987017_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017 { public: union { struct { }; uint8_t Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017__padding[1]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T22962CB4C05B1D89B55A6E1139F0E87A90987017_H #ifndef DELEGATE_T_H #define DELEGATE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Delegate struct Delegate_t : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::extra_arg intptr_t ___extra_arg_5; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_6; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_7; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_8; // System.DelegateData System.Delegate::data DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * ___data_9; // System.Boolean System.Delegate::method_is_virtual bool ___method_is_virtual_10; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((&___m_target_2), value); } inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t, ___extra_arg_5)); } inline intptr_t get_extra_arg_5() const { return ___extra_arg_5; } inline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; } inline void set_extra_arg_5(intptr_t value) { ___extra_arg_5 = value; } inline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_code_6)); } inline intptr_t get_method_code_6() const { return ___method_code_6; } inline intptr_t* get_address_of_method_code_6() { return &___method_code_6; } inline void set_method_code_6(intptr_t value) { ___method_code_6 = value; } inline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_info_7)); } inline MethodInfo_t * get_method_info_7() const { return ___method_info_7; } inline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; } inline void set_method_info_7(MethodInfo_t * value) { ___method_info_7 = value; Il2CppCodeGenWriteBarrier((&___method_info_7), value); } inline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t, ___original_method_info_8)); } inline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; } inline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; } inline void set_original_method_info_8(MethodInfo_t * value) { ___original_method_info_8 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_8), value); } inline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t, ___data_9)); } inline DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * get_data_9() const { return ___data_9; } inline DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE ** get_address_of_data_9() { return &___data_9; } inline void set_data_9(DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * value) { ___data_9 = value; Il2CppCodeGenWriteBarrier((&___data_9), value); } inline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_is_virtual_10)); } inline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; } inline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; } inline void set_method_is_virtual_10(bool value) { ___method_is_virtual_10 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Delegate struct Delegate_t_marshaled_pinvoke { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * ___data_9; int32_t ___method_is_virtual_10; }; // Native definition for COM marshalling of System.Delegate struct Delegate_t_marshaled_com { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t1BF9F691B56DAE5F8C28C5E084FDE94F15F27BBE * ___data_9; int32_t ___method_is_virtual_10; }; #endif // DELEGATE_T_H #ifndef INT32ENUM_T6312CE4586C17FE2E2E513D2E7655B574F10FDCD_H #define INT32ENUM_T6312CE4586C17FE2E2E513D2E7655B574F10FDCD_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32Enum struct Int32Enum_t6312CE4586C17FE2E2E513D2E7655B574F10FDCD { public: // System.Int32 System.Int32Enum::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(Int32Enum_t6312CE4586C17FE2E2E513D2E7655B574F10FDCD, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32ENUM_T6312CE4586C17FE2E2E513D2E7655B574F10FDCD_H #ifndef NATIVEINPUTUPDATETYPE_T744D5594ED044E47F3BAF84F45326948B8930C71_H #define NATIVEINPUTUPDATETYPE_T744D5594ED044E47F3BAF84F45326948B8930C71_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngineInternal.Input.NativeInputUpdateType struct NativeInputUpdateType_t744D5594ED044E47F3BAF84F45326948B8930C71 { public: // System.Int32 UnityEngineInternal.Input.NativeInputUpdateType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(NativeInputUpdateType_t744D5594ED044E47F3BAF84F45326948B8930C71, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVEINPUTUPDATETYPE_T744D5594ED044E47F3BAF84F45326948B8930C71_H #ifndef MULTICASTDELEGATE_T_H #define MULTICASTDELEGATE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MulticastDelegate struct MulticastDelegate_t : public Delegate_t { public: // System.Delegate[] System.MulticastDelegate::delegates DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86* ___delegates_11; public: inline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___delegates_11)); } inline DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86* get_delegates_11() const { return ___delegates_11; } inline DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86** get_address_of_delegates_11() { return &___delegates_11; } inline void set_delegates_11(DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86* value) { ___delegates_11 = value; Il2CppCodeGenWriteBarrier((&___delegates_11), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_pinvoke : public Delegate_t_marshaled_pinvoke { DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86* ___delegates_11; }; // Native definition for COM marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_com : public Delegate_t_marshaled_com { DelegateU5BU5D_tDFCDEE2A6322F96C0FE49AF47E9ADB8C4B294E86* ___delegates_11; }; #endif // MULTICASTDELEGATE_T_H #ifndef ACTION_1_TA0A72999A108CE29CD4CB14537B8FE41501859C1_H #define ACTION_1_TA0A72999A108CE29CD4CB14537B8FE41501859C1_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`1<UnityEngineInternal.Input.NativeInputUpdateType> struct Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_1_TA0A72999A108CE29CD4CB14537B8FE41501859C1_H #ifndef ACTION_2_T3DE7FA14577DE01568F76D409273F315827CAA36_H #define ACTION_2_T3DE7FA14577DE01568F76D409273F315827CAA36_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`2<System.Int32,System.String> struct Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_2_T3DE7FA14577DE01568F76D409273F315827CAA36_H #ifndef ACTION_3_T218EFA183BDE39E1AC9A0240E98B4BFC33A703D4_H #define ACTION_3_T218EFA183BDE39E1AC9A0240E98B4BFC33A703D4_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`3<UnityEngineInternal.Input.NativeInputUpdateType,System.Int32,System.IntPtr> struct Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_3_T218EFA183BDE39E1AC9A0240E98B4BFC33A703D4_H // System.Void System.Action`1<System.Int32Enum>::Invoke(!0) extern "C" IL2CPP_METHOD_ATTR void Action_1_Invoke_m8672DDC58300CA227FC37981067B766C9879344B_gshared (Action_1_tABA1E3BFA092E3309A0ECC53722E4F9826DCE983 * __this, int32_t p0, const RuntimeMethod* method); // System.Void System.Action`3<System.Int32Enum,System.Int32,System.IntPtr>::Invoke(!0,!1,!2) extern "C" IL2CPP_METHOD_ATTR void Action_3_Invoke_mA42EA0FED3B60DF0F9FC0E7EA4DECB94B577ED27_gshared (Action_3_tA1F157C5B221E0F24BDD45BD4F6A9C25B81357F9 * __this, int32_t p0, int32_t p1, intptr_t p2, const RuntimeMethod* method); // System.Void System.Action`2<System.Int32,System.Object>::Invoke(!0,!1) extern "C" IL2CPP_METHOD_ATTR void Action_2_Invoke_m8C87606D1DEC8A89FB53D1ADF8768A7403DD6202_gshared (Action_2_tCC05A68F0FC31E84E54091438749644062A6C27F * __this, int32_t p0, RuntimeObject * p1, const RuntimeMethod* method); // System.Void UnityEngineInternal.Input.NativeInputSystem::set_hasDeviceDiscoveredCallback(System.Boolean) extern "C" IL2CPP_METHOD_ATTR void NativeInputSystem_set_hasDeviceDiscoveredCallback_mB5319D5A7C245D6F12C294928D4AF3B635FFE362 (bool ___value0, const RuntimeMethod* method); // System.Void System.Action`1<UnityEngineInternal.Input.NativeInputUpdateType>::Invoke(!0) inline void Action_1_Invoke_m60C027AA0F030AC2B693BEFB8E213066CD9000D0 (Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 * __this, int32_t p0, const RuntimeMethod* method) { (( void (*) (Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 *, int32_t, const RuntimeMethod*))Action_1_Invoke_m8672DDC58300CA227FC37981067B766C9879344B_gshared)(__this, p0, method); } // System.Void System.Action`3<UnityEngineInternal.Input.NativeInputUpdateType,System.Int32,System.IntPtr>::Invoke(!0,!1,!2) inline void Action_3_Invoke_m14ADB6DD0234BFB201A7050855A62A4DA2612D0A (Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 * __this, int32_t p0, int32_t p1, intptr_t p2, const RuntimeMethod* method) { (( void (*) (Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 *, int32_t, int32_t, intptr_t, const RuntimeMethod*))Action_3_Invoke_mA42EA0FED3B60DF0F9FC0E7EA4DECB94B577ED27_gshared)(__this, p0, p1, p2, method); } // System.Void System.Action`2<System.Int32,System.String>::Invoke(!0,!1) inline void Action_2_Invoke_mC215CA1421B7DF8C0023F107CA72045332A79489 (Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 * __this, int32_t p0, String_t* p1, const RuntimeMethod* method) { (( void (*) (Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 *, int32_t, String_t*, const RuntimeMethod*))Action_2_Invoke_m8C87606D1DEC8A89FB53D1ADF8768A7403DD6202_gshared)(__this, p0, p1, method); } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngineInternal.Input.NativeInputSystem::.cctor() extern "C" IL2CPP_METHOD_ATTR void NativeInputSystem__cctor_m062AB23A2EB8CDEC8BEB378C4588038BD1614A11 (const RuntimeMethod* method) { { NativeInputSystem_set_hasDeviceDiscoveredCallback_mB5319D5A7C245D6F12C294928D4AF3B635FFE362((bool)0, /*hidden argument*/NULL); return; } } // System.Void UnityEngineInternal.Input.NativeInputSystem::NotifyBeforeUpdate(UnityEngineInternal.Input.NativeInputUpdateType) extern "C" IL2CPP_METHOD_ATTR void NativeInputSystem_NotifyBeforeUpdate_m317D534DBDD42915CE638051B87E48B76ED28574 (int32_t ___updateType0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (NativeInputSystem_NotifyBeforeUpdate_m317D534DBDD42915CE638051B87E48B76ED28574_MetadataUsageId); s_Il2CppMethodInitialized = true; } Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 * V_0 = NULL; { IL2CPP_RUNTIME_CLASS_INIT(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_il2cpp_TypeInfo_var); Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 * L_0 = ((NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_StaticFields*)il2cpp_codegen_static_fields_for(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_il2cpp_TypeInfo_var))->get_onBeforeUpdate_1(); V_0 = L_0; Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 * L_1 = V_0; if (!L_1) { goto IL_0014; } } { Action_1_tA0A72999A108CE29CD4CB14537B8FE41501859C1 * L_2 = V_0; int32_t L_3 = ___updateType0; NullCheck(L_2); Action_1_Invoke_m60C027AA0F030AC2B693BEFB8E213066CD9000D0(L_2, L_3, /*hidden argument*/Action_1_Invoke_m60C027AA0F030AC2B693BEFB8E213066CD9000D0_RuntimeMethod_var); } IL_0014: { return; } } // System.Void UnityEngineInternal.Input.NativeInputSystem::NotifyUpdate(UnityEngineInternal.Input.NativeInputUpdateType,System.Int32,System.IntPtr) extern "C" IL2CPP_METHOD_ATTR void NativeInputSystem_NotifyUpdate_m77B02AB50FCFA5649D7203E76163C757EE1DA3CA (int32_t ___updateType0, int32_t ___eventCount1, intptr_t ___eventData2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (NativeInputSystem_NotifyUpdate_m77B02AB50FCFA5649D7203E76163C757EE1DA3CA_MetadataUsageId); s_Il2CppMethodInitialized = true; } Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 * V_0 = NULL; { IL2CPP_RUNTIME_CLASS_INIT(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_il2cpp_TypeInfo_var); Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 * L_0 = ((NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_StaticFields*)il2cpp_codegen_static_fields_for(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_il2cpp_TypeInfo_var))->get_onUpdate_0(); V_0 = L_0; Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 * L_1 = V_0; if (!L_1) { goto IL_0016; } } { Action_3_t218EFA183BDE39E1AC9A0240E98B4BFC33A703D4 * L_2 = V_0; int32_t L_3 = ___updateType0; int32_t L_4 = ___eventCount1; intptr_t L_5 = ___eventData2; NullCheck(L_2); Action_3_Invoke_m14ADB6DD0234BFB201A7050855A62A4DA2612D0A(L_2, L_3, L_4, (intptr_t)L_5, /*hidden argument*/Action_3_Invoke_m14ADB6DD0234BFB201A7050855A62A4DA2612D0A_RuntimeMethod_var); } IL_0016: { return; } } // System.Void UnityEngineInternal.Input.NativeInputSystem::NotifyDeviceDiscovered(System.Int32,System.String) extern "C" IL2CPP_METHOD_ATTR void NativeInputSystem_NotifyDeviceDiscovered_m48C3818DDCFB1A2C0530B6CE1C78743ABA4614B0 (int32_t ___deviceId0, String_t* ___deviceDescriptor1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (NativeInputSystem_NotifyDeviceDiscovered_m48C3818DDCFB1A2C0530B6CE1C78743ABA4614B0_MetadataUsageId); s_Il2CppMethodInitialized = true; } Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 * V_0 = NULL; { IL2CPP_RUNTIME_CLASS_INIT(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_il2cpp_TypeInfo_var); Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 * L_0 = ((NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_StaticFields*)il2cpp_codegen_static_fields_for(NativeInputSystem_t522F6391494159917EE6963E9E61C9EFA9C5795C_il2cpp_TypeInfo_var))->get_s_OnDeviceDiscoveredCallback_2(); V_0 = L_0; Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 * L_1 = V_0; if (!L_1) { goto IL_0015; } } { Action_2_t3DE7FA14577DE01568F76D409273F315827CAA36 * L_2 = V_0; int32_t L_3 = ___deviceId0; String_t* L_4 = ___deviceDescriptor1; NullCheck(L_2); Action_2_Invoke_mC215CA1421B7DF8C0023F107CA72045332A79489(L_2, L_3, L_4, /*hidden argument*/Action_2_Invoke_mC215CA1421B7DF8C0023F107CA72045332A79489_RuntimeMethod_var); } IL_0015: { return; } } // System.Void UnityEngineInternal.Input.NativeInputSystem::set_hasDeviceDiscoveredCallback(System.Boolean) extern "C" IL2CPP_METHOD_ATTR void NativeInputSystem_set_hasDeviceDiscoveredCallback_mB5319D5A7C245D6F12C294928D4AF3B635FFE362 (bool ___value0, const RuntimeMethod* method) { typedef void (*NativeInputSystem_set_hasDeviceDiscoveredCallback_mB5319D5A7C245D6F12C294928D4AF3B635FFE362_ftn) (bool); static NativeInputSystem_set_hasDeviceDiscoveredCallback_mB5319D5A7C245D6F12C294928D4AF3B635FFE362_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (NativeInputSystem_set_hasDeviceDiscoveredCallback_mB5319D5A7C245D6F12C294928D4AF3B635FFE362_ftn)il2cpp_codegen_resolve_icall ("UnityEngineInternal.Input.NativeInputSystem::set_hasDeviceDiscoveredCallback(System.Boolean)"); _il2cpp_icall_func(___value0); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // Modified by PostBuild.cs
39.106653
290
0.840498
AnnaOpareva
4b237561a0f86dac212646b03b2139993c6df021
8,266
cpp
C++
Source/common/P4Image.cpp
vtslothy/P4Win
7aac7763d984db66d31de06ff7686c309851884c
[ "BSD-2-Clause" ]
10
2018-08-03T12:15:43.000Z
2021-06-03T18:31:04.000Z
Source/common/P4Image.cpp
danieljennings/P4Win
95fb3766159076555eec861098f205691b3cb86c
[ "BSD-2-Clause" ]
10
2018-07-31T21:35:10.000Z
2019-07-08T02:06:32.000Z
Source/common/P4Image.cpp
danieljennings/P4Win
95fb3766159076555eec861098f205691b3cb86c
[ "BSD-2-Clause" ]
3
2019-05-10T20:13:46.000Z
2021-03-03T05:03:40.000Z
#include "stdafx.h" #include "P4Image.h" /////////////////////////////////////////////////////////////////////////// // CP4Image16 - support for 16 color images bool CP4Image16::Load(int nId) { if(!m_bmp.LoadBitmap(nId)) return false; m_bmp.GetBitmap(&m_bm); m_w = m_bm.bmWidth; m_h = m_bm.bmHeight; return true; } bool CP4Image16::Create(CDC &dc, int w, int h) { if(!m_bmp.CreateCompatibleBitmap(&dc, w, h)) return false; m_w = w; m_h = h; return true; } void CP4Image16::StartBlendingSource() { m_imgList = new CImageList(); m_imgList->Create(m_cellWidth, m_h, ILC_COLOR4|ILC_MASK, 1, 1); m_imgList->Add(&m_bmp, m_chromaKey); } void CP4Image16::EndBlendingSource() { delete m_imgList; m_imgList = 0; } void CP4Image16::StartBlendingDest(CDC &dc) { m_dc = new CDC; m_dc->CreateCompatibleDC(&dc); m_oldBmp = m_dc->SelectObject(&m_bmp); } void CP4Image16::EndBlendingDest() { m_dc->SelectObject(m_oldBmp); m_oldBmp = 0; delete m_dc; m_dc = 0; } void CP4Image16::FillImage(COLORREF clr) { CBrush bgbr; bgbr.CreateSolidBrush(clr); m_dc->FillRect(CRect(0, 0, m_w, m_h), &bgbr); } void CP4Image16::BlendImage(int di, CP4Image &src, int si) { // Blending is done using an ImageList rather than just // using TransparentBlt, because TransparentBlt isn't // available on win95 or nt4 CP4Image16 * src4 = dynamic_cast<CP4Image16*>(&src); ASSERT(src4); ASSERT(src4->m_cellWidth == m_cellWidth); src4->m_imgList->Draw(m_dc, si, CPoint(di * m_cellWidth, 0), ILD_TRANSPARENT); } CBitmap * CP4Image16::CreateDDB(CDC &/*dc*/) { return &m_bmp; } /////////////////////////////////////////////////////////////////////////// // CP4ImageDib - support for 32 bit rgba images bool CP4ImageDib::Load(int nId) { // You might think it would work to just call LoadImage // to load a bitmap image. But apparently some versions // of Windows will be confused and load a 32-bit image // incorrectly for some mysterious reason. So we do it // the slightly harder way here: HRSRC hRes = FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(nId), RT_BITMAP); if(hRes == NULL) return false; HGLOBAL hResLoad = LoadResource(AfxGetResourceHandle(), hRes); if(hResLoad == NULL) return false; char * lpResLock = (char*)LockResource(hResLoad); if (lpResLock == NULL) return false; BITMAPINFOHEADER * bmih = (BITMAPINFOHEADER*)lpResLock; if(bmih->biBitCount != 32 || bmih->biPlanes != 1) { return false; } // create a dib using the dib section and copy the bits m_bmi.bmiHeader = *bmih; m_w = m_bmi.bmiHeader.biWidth; m_h = m_bmi.bmiHeader.biHeight; m_bmi.bmiHeader.biSizeImage = m_w * m_h * 4; m_bits = new unsigned char [m_bmi.bmiHeader.biSizeImage]; memcpy(m_bits, lpResLock + bmih->biSize, m_bmi.bmiHeader.biSizeImage); return true; } bool CP4ImageDib::Create(int w, int h) { // set up the DIB m_bmi.bmiHeader.biSize = sizeof(m_bmi.bmiHeader); m_bmi.bmiHeader.biWidth = w; m_bmi.bmiHeader.biHeight = h; m_bmi.bmiHeader.biPlanes = 1; m_bmi.bmiHeader.biBitCount = 32; m_bmi.bmiHeader.biCompression = BI_RGB; m_bmi.bmiHeader.biSizeImage = w * h * 4; m_bmi.bmiHeader.biXPelsPerMeter = 0; m_bmi.bmiHeader.biYPelsPerMeter = 0; m_bmi.bmiHeader.biClrUsed = 0; m_bmi.bmiHeader.biClrImportant = 0; m_w = m_bmi.bmiHeader.biWidth; m_h = m_bmi.bmiHeader.biHeight; m_bits = new unsigned char [m_bmi.bmiHeader.biSizeImage]; return true; } void CP4ImageDib::FillImage(COLORREF clr) { for(int r = 0; r < m_h; r++) { unsigned char *pd = m_bits + r * m_w * 4; for(int c = 0; c < m_w; c++, pd += 4) { pd[0] = GetBValue(clr); pd[1] = GetGValue(clr); pd[2] = GetRValue(clr); pd[3] = 0; } } } void CP4ImageDib::BlendImage(int di, CP4Image &src, int si) { CP4ImageDib * dib = dynamic_cast<CP4ImageDib*>(&src); ASSERT(dib); if(!dib) return; for(int r = 0; r < m_h; r++) { unsigned char *ps = dib->m_bits + r * dib->m_w * 4 + si * m_cellWidth * 4; unsigned char *pd = m_bits + r * m_w * 4 + di * m_cellWidth * 4; for(int c = 0; c < m_cellWidth; c++, ps += 4, pd += 4) { int alpha = ps[3]; if(!alpha) continue; // blend source bitmap with background color using source alpha pd[0] = (unsigned char)(ps[0] + ((255 - alpha) * pd[0] >> 8)); pd[1] = (unsigned char)(ps[1] + ((255 - alpha) * pd[1] >> 8)); pd[2] = (unsigned char)(ps[2] + ((255 - alpha) * pd[2] >> 8)); pd[3] = (unsigned char)(ps[3] + ((255 - alpha) * pd[3] >> 8)); } } } CBitmap * CP4ImageDib::CreateDDB(CDC &dc) { HBITMAP hBitmap = ::CreateDIBitmap(dc.m_hDC, &m_bmi.bmiHeader, CBM_INIT, m_bits, &m_bmi, DIB_RGB_COLORS); m_bmp.Attach(hBitmap); return &m_bmp; } void CP4ImageDib::PreMultiplyAlpha() { for(int r = 0; r < m_h; r++) { unsigned char *ps = m_bits + r * m_w * 4; for(int c = 0; c < m_w; c++, ps += 4) { // pre-multiply alpha into source bitmap int alpha = ps[3]; ps[0] = (unsigned char)((ps[0] * alpha) >> 8); ps[1] = (unsigned char)((ps[1] * alpha) >> 8); ps[2] = (unsigned char)((ps[2] * alpha) >> 8); } } } void CP4ImageDib::BlendBackground(COLORREF bg) { // set up some colors unsigned char bgb = GetBValue(bg); unsigned char bgg = GetGValue(bg); unsigned char bgr = GetRValue(bg); unsigned ubg = GetBValue(bg) | (GetGValue(bg)<<8) | (GetRValue(bg)<<16); for(int r = 0; r < m_h; r++) { unsigned char *ps = m_bits + r * m_w * 4; for(int c = 0; c < m_w; c++, ps += 4) { int alpha = ps[3]; if(!alpha) { // special case for totally transparent parts *((unsigned*)ps) = ubg; continue; } // blend source bitmap with background color using source alpha ps[0] = (unsigned char)((bgb * (255 - alpha) + ps[0] * alpha) >> 8); ps[1] = (unsigned char)((bgg * (255 - alpha) + ps[1] * alpha) >> 8); ps[2] = (unsigned char)((bgr * (255 - alpha) + ps[2] * alpha) >> 8); ps[3] = 255; } } } bool CP4ImageDib::CreateDisabled(CP4ImageDib &src, COLORREF bg) { if(!Create(src.m_w, src.m_h)) return false; // To create the disabled image, convert to a 'grayscale' // using a range from COLOR_3DHILIGHT to COLOR_3DDKSHADOW // This produces a good approximation to what winxp does. COLORREF shadow = ::GetSysColor(COLOR_3DDKSHADOW); COLORREF hilight = ::GetSysColor(COLOR_3DHILIGHT); unsigned char bgb = GetBValue(bg); unsigned char bgg = GetGValue(bg); unsigned char bgr = GetRValue(bg); unsigned char sb = GetBValue(shadow); unsigned char sg = GetGValue(shadow); unsigned char sr = GetRValue(shadow); unsigned char hb = GetBValue(hilight); unsigned char hg = GetGValue(hilight); unsigned char hr = GetRValue(hilight); unsigned ubg = GetBValue(bg) | (GetGValue(bg)<<8) | (GetRValue(bg)<<16); for(int r = 0; r < m_h; r++) { unsigned *ps = (unsigned *)src.m_bits + r * m_w; unsigned *pd = (unsigned *)m_bits + r * m_w; for(int c = 0; c < m_w; c++, ps++, pd++) { if(*ps == ubg) { *pd = ubg; continue; } // get source image components unsigned nb = *ps & 0xff; unsigned ng = (*ps >> 8) & 0xff; unsigned nr = (*ps >> 16) & 0xff; unsigned alpha = (*ps >> 24) & 0xff; // calculate luminance. This is what is used to determine // where in the monochrome range the color maps. double luminance = (0.299 * nr + 0.587 * ng + 0.114 * nb)/255; if(luminance > 1.0) luminance = 1.0; // map from color to monochrome unsigned char b = (unsigned char)(sb + luminance * (hb - sb)); unsigned char g = (unsigned char)(sg + luminance * (hg - sg)); unsigned char r = (unsigned char)(sr + luminance * (hr - sr)); // blend with the background color b = (unsigned char)((bgb * (255 - alpha) + b * alpha) >> 8); g = (unsigned char)((bgg * (255 - alpha) + g * alpha) >> 8); r = (unsigned char)((bgr * (255 - alpha) + r * alpha) >> 8); // and put it away pd[0] = b | (g << 8) | (r << 16) | 0xff000000; } } return true; } void CP4ImageDib::SetTransparentColor(COLORREF t) { unsigned clr = GetBValue(t) | (GetGValue(t)<<8) | (GetRValue(t)<<16); for(int r = 0; r < m_h; r++) { unsigned char *ps = m_bits + r * m_w * 4; for(int c = 0; c < m_w; c++, ps += 4) { int alpha = ps[3]; if(!alpha) { // replace color only for totally transparent pixels *((unsigned*)ps) = clr; } } } }
26.324841
79
0.628115
vtslothy
4b24cdb361e9222ca97228a7ea2d20d5f252319b
1,892
cpp
C++
benchmark/parallel_read.cpp
OpenSSE/insecure-index
14be5afa278543a938edd9dac49c86b99dd5eab7
[ "MIT" ]
1
2021-09-01T02:22:29.000Z
2021-09-01T02:22:29.000Z
benchmark/parallel_read.cpp
OpenSSE/insecure-index
14be5afa278543a938edd9dac49c86b99dd5eab7
[ "MIT" ]
null
null
null
benchmark/parallel_read.cpp
OpenSSE/insecure-index
14be5afa278543a938edd9dac49c86b99dd5eab7
[ "MIT" ]
1
2019-11-15T00:50:18.000Z
2019-11-15T00:50:18.000Z
#include "file_benchmark.hpp" #include "logger.hpp" #include <omp.h> #include <iomanip> #include <iostream> void run_benchmark(const std::string filename, const size_t file_size, const bool direct_access, const size_t read_size, const size_t n_iters, const size_t n_threads) { FileBenchmark fw(filename, file_size, 0xAA, direct_access); std::vector<uint8_t*> buffers(n_threads); std::cerr << "Init buffers\n"; for (auto& ptr : buffers) { int ret = posix_memalign((reinterpret_cast<void**>(&ptr)), 4096, read_size); if (ret != 0) { throw std::runtime_error("Unable to do an aligned allocation"); } } std::cerr << "Start benchmark\n"; std::string message = direct_access ? "parallel direct read" : "parallel cached read"; sse::SearchBenchmark bench(message); { #pragma omp parallel for num_threads(n_threads) schedule(dynamic) for (size_t i = 0; i < n_iters; i++) { int thread_num = omp_get_thread_num(); // auto str = "Thread " + std::to_string(thread_num) + "/" + // std::to_string(omp_get_num_threads()) + "\n"; std::cerr << str; fw.random_aligned_read(buffers[thread_num], read_size); } } bench.stop(n_iters); bench.set_locality(n_threads); for (auto& ptr : buffers) { free(ptr); } } int main(int argc, char const* argv[]) { sse::Benchmark::set_log_to_console(); const std::string filename = "bench_read"; const size_t file_size = 32UL << 30; const size_t n_threads = 128; const size_t n_iters = 100000; const size_t read_size = 4UL << 10; run_benchmark(filename, file_size, true, read_size, n_iters, n_threads); return 0; }
26.277778
80
0.588795
OpenSSE
4b25015fea88c58b1af2f516c91321d895b4cf1b
263
cpp
C++
PATTERN/Pattern_4/Solution.cpp
UndefeatedSunny/C-Interview-Problems
5eb4d3c52cb7ffe4bc97380d13f62e23bc7d1e2f
[ "MIT" ]
4
2020-02-25T19:02:46.000Z
2021-04-17T09:13:51.000Z
PATTERN/Pattern_4/Solution.cpp
UndefeatedSunny/C-Interview-Problems
5eb4d3c52cb7ffe4bc97380d13f62e23bc7d1e2f
[ "MIT" ]
null
null
null
PATTERN/Pattern_4/Solution.cpp
UndefeatedSunny/C-Interview-Problems
5eb4d3c52cb7ffe4bc97380d13f62e23bc7d1e2f
[ "MIT" ]
2
2021-01-08T07:25:35.000Z
2021-04-17T09:14:57.000Z
#include <bits/stdc++.h> using namespace std; int main() { for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { if(i<=j) { cout<<"* "; } } cout<<endl; } return 0; }
13.842105
28
0.323194
UndefeatedSunny
4b273d711d50b47876c08583b21c69ebd5e085d9
2,718
cpp
C++
rh-/rh-/Input.cpp
ShiroixD/Rh-
33db74b21bb9a7255d72b14afd6746f142c1784b
[ "Apache-2.0" ]
null
null
null
rh-/rh-/Input.cpp
ShiroixD/Rh-
33db74b21bb9a7255d72b14afd6746f142c1784b
[ "Apache-2.0" ]
null
null
null
rh-/rh-/Input.cpp
ShiroixD/Rh-
33db74b21bb9a7255d72b14afd6746f142c1784b
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "Input.h" unique_ptr<Keyboard> Input::_keyboard(new Keyboard()); unique_ptr<Mouse> Input::_mouse(new Mouse()); map<availableKeys, actionList> Input::AvailableKeysActionsBinding = {}; Keyboard::State Input::GetKeyboardState() { return _keyboard->GetState(); } Mouse::State Input::GetMouseState() { return _mouse->GetState(); } map<availableKeys, actionList> Input::GetActionKeysBindings() { return AvailableKeysActionsBinding; } std::map<availableKeys, bool> Input::GetPushedKeys() { Mouse::State MouseState = _mouse->GetState(); Keyboard::State KeyboardState = _keyboard->GetState(); std::map<availableKeys, bool> pushedKeys; if (MouseState.leftButton) pushedKeys[lpm] = true; if (KeyboardState.Escape) pushedKeys[esc] = true; if (KeyboardState.Space) pushedKeys[space] = true; if (KeyboardState.LeftControl) pushedKeys[leftControl] = true; if (KeyboardState.A) pushedKeys[a] = true; if (KeyboardState.D) pushedKeys[d] = true; if (KeyboardState.W) pushedKeys[w] = true; if (KeyboardState.S) pushedKeys[s] = true; if (KeyboardState.Up) pushedKeys[upperArrow] = true; if (KeyboardState.Down) pushedKeys[lowerArrow] = true; if (KeyboardState.Left) pushedKeys[leftArrow] = true; if (KeyboardState.Right) pushedKeys[rightArrow] = true; if (KeyboardState.D1) pushedKeys[one] = true; if (KeyboardState.D2) pushedKeys[two] = true; if (KeyboardState.D3) pushedKeys[three] = true; if (KeyboardState.D4) pushedKeys[four] = true; if (KeyboardState.Z) pushedKeys[z] = true; if (KeyboardState.X) pushedKeys[x] = true; if (KeyboardState.C) pushedKeys[c] = true; if (KeyboardState.V) pushedKeys[v] = true; if (KeyboardState.B) pushedKeys[b] = true; return pushedKeys; } SimpleMath::Vector2 Input::GetMousePosition() { Mouse::State MouseState = GetMouseState(); return DirectX::SimpleMath::Vector2(MouseState.x, MouseState.y); } void Input::SetWindowForMouse(HWND window) { _mouse->SetWindow(window); } void Input::SetMouseMode(Mouse::Mode mode) { _mouse->SetMode(mode); } void Input::ResetWheel() { _mouse->ResetScrollWheelValue(); } vector<actionList> Input::GetActions() { vector<actionList> pushedBindedKeys; map<availableKeys, actionList> actionKeyBindings = AvailableKeysActionsBinding; map<availableKeys, bool> pushedKeys = GetPushedKeys(); for (map<availableKeys, bool>::iterator iter = pushedKeys.begin(); iter != pushedKeys.end(); ++iter) { //Key k = iter->first; //Value v = iter->second; if (actionKeyBindings.find(iter->first) != actionKeyBindings.end() && iter->second) { pushedBindedKeys.push_back(actionKeyBindings[iter->first]); } } return pushedBindedKeys; }
19.985294
101
0.720751
ShiroixD
4b2ba4687ccbb2a11ba57d349a4536daf4dcc67f
551
hh
C++
inc/Cuboid.hh
KPO-2020-2021/zad5_3-AdamDomachowski
1d3e1af48e948989937a9cdb206198b7de32f428
[ "Unlicense" ]
null
null
null
inc/Cuboid.hh
KPO-2020-2021/zad5_3-AdamDomachowski
1d3e1af48e948989937a9cdb206198b7de32f428
[ "Unlicense" ]
null
null
null
inc/Cuboid.hh
KPO-2020-2021/zad5_3-AdamDomachowski
1d3e1af48e948989937a9cdb206198b7de32f428
[ "Unlicense" ]
null
null
null
#pragma once #include "Solid.hh" /*! \brief klasa Cuboid jest klasa pochodna i dziedziczy wzystko z klasy Solid */ class Cuboid : public Solid { public: /*! \brief konstruktor parametryczny*/ Cuboid(Vector3D srodek=Vector3D(), double a=50, double b=50, double c=100, std::string nazwa_pliku_prostopadloscianu = "../datas/cuboid.dat"); Cuboid( Cuboid& cub ); Cuboid &operator=(const Cuboid &drugi) { wymiary=drugi.wymiary; wierzcholki=drugi.wierzcholki; srodek_bryly=drugi.srodek_bryly; nazwa_pliku_bryly=drugi.nazwa_pliku_bryly; return *this; } };
29
142
0.76225
KPO-2020-2021
4b2d1ef27952afa05ae2c6debb2a7b259c2c8536
11,810
cpp
C++
src/vizdoom/src/viz_input.cpp
monaj07/Vizdoom
3537793ced50273cdd9e513155ce9ef3bacca67b
[ "MIT" ]
null
null
null
src/vizdoom/src/viz_input.cpp
monaj07/Vizdoom
3537793ced50273cdd9e513155ce9ef3bacca67b
[ "MIT" ]
null
null
null
src/vizdoom/src/viz_input.cpp
monaj07/Vizdoom
3537793ced50273cdd9e513155ce9ef3bacca67b
[ "MIT" ]
null
null
null
/* Copyright (C) 2016 by Wojciech Jaśkowski, Michał Kempka, Grzegorz Runc, Jakub Toczek, Marek Wydmuch 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. */ #include "viz_input.h" #include "viz_main.h" #include "viz_defines.h" #include "viz_message_queue.h" #include "viz_shared_memory.h" #include "d_main.h" #include "g_game.h" #include "d_player.h" #include "c_dispatch.h" #include "r_utility.h" bip::mapped_region *vizInputSMRegion = NULL; VIZInputState *vizInput = NULL; bool vizInputInited = false; int vizLastInputBT[VIZ_BT_COUNT]; unsigned int vizLastInputUpdate[VIZ_BT_COUNT]; EXTERN_CVAR (Bool, viz_debug) EXTERN_CVAR (Bool, viz_allow_input) void VIZ_Command(char * cmd){ AddCommandString(cmd); } bool VIZ_CommmandFilter(const char *cmd){ VIZ_DebugMsg(3, VIZ_FUNC, "allow_input: %d, cmd: %s", *viz_allow_input, cmd); if(!vizInputInited || !*viz_allow_input) return true; bool action = false; int state = 1; if (*cmd == '+'){ action = true; state = 1; } else if(*cmd == '-'){ action = true; state = 0; } const char* beg; if(action) beg = cmd+1; else beg = cmd; if (strcmp(beg, "togglemap") == 0 || strcmp(beg, "toggleconsole") == 0 || strcmp(beg, "showscores") == 0 || strcmp(beg, "menu_main") == 0 || strcmp(beg, "menu_help") == 0 || strcmp(beg, "menu_save") == 0 || strcmp(beg, "menu_load") == 0 || strcmp(beg, "menu_options") == 0 || strcmp(beg, "menu_display") == 0 || strcmp(beg, "quicksave") == 0 || strcmp(beg, "menu_endgame") == 0 || strcmp(beg, "togglemessages") == 0 || strcmp(beg, "quickload") == 0 || strcmp(beg, "menu_quit") == 0 || strcmp(beg, "bumpgamma") == 0 || strcmp(beg, "spynext") == 0 || strcmp(beg, "screenshot") == 0 || strcmp(beg, "pause") == 0 || strcmp(beg, "centerview") == 0){ return false; } for(int i = 0; i<VIZ_BT_CMD_BT_COUNT; ++i){ char * ckeckCmd = VIZ_BTToCommand((VIZButton)i); if (strcmp(beg, ckeckCmd) == 0){ if(!vizInput->BT_AVAILABLE[i]) { vizInput->BT[i] = 0; return false; } else{ vizInput->BT[i] = state; vizLastInputUpdate[i] = VIZ_TIME; } } delete[] ckeckCmd; } return true; } int VIZ_AxisFilter(VIZButton button, int value){ if(value != 0 && button >= VIZ_BT_CMD_BT_COUNT && button < VIZ_BT_COUNT){ if(!vizInput->BT_AVAILABLE[button]) return 0; int axis = button - VIZ_BT_CMD_BT_COUNT; if(vizInput->BT_MAX_VALUE[axis] != 0){ int maxValue; if(button == VIZ_BT_VIEW_ANGLE_AXIS || button == VIZ_BT_VIEW_PITCH_AXIS) maxValue = (int)((float)vizInput->BT_MAX_VALUE[axis]/180 * 32768); else maxValue = vizInput->BT_MAX_VALUE[axis]; if((int)labs(value) > (int)labs(maxValue)) value = value/(int)labs(value) * (int)(labs(maxValue) + 1); } if(button == VIZ_BT_VIEW_ANGLE_AXIS || button == VIZ_BT_VIEW_PITCH_AXIS) vizInput->BT[button] = (int)((float)value/32768 * 180); else vizInput->BT[button] = value; vizLastInputUpdate[button] = VIZ_TIME; } return value; } void VIZ_AddAxisBT(VIZButton button, int value){ if(button == VIZ_BT_VIEW_ANGLE_AXIS || button == VIZ_BT_VIEW_PITCH_AXIS) value = (int)((float)value/180 * 32768); value = VIZ_AxisFilter(button, value); switch(button){ case VIZ_BT_VIEW_PITCH_AXIS : G_AddViewPitch(value); //LocalViewPitch = value; break; case VIZ_BT_VIEW_ANGLE_AXIS : G_AddViewAngle(value); //LocalViewAngle = value; break; case VIZ_BT_FORWARD_BACKWARD_AXIS : LocalForward = value; break; case VIZ_BT_LEFT_RIGHT_AXIS : LocalSide = value; break; case VIZ_BT_UP_DOWN_AXIS : LocalFly = value; break; default: break; } } char* VIZ_BTToCommand(VIZButton button){ switch(button){ case VIZ_BT_ATTACK: return strdup("attack"); case VIZ_BT_USE : return strdup("use"); case VIZ_BT_JUMP : return strdup("jump"); case VIZ_BT_CROUCH : return strdup("crouch"); case VIZ_BT_TURN180 : return strdup("turn180"); case VIZ_BT_ALTATTACK : return strdup("altattack"); case VIZ_BT_RELOAD : return strdup("reload"); case VIZ_BT_ZOOM : return strdup("zoom"); case VIZ_BT_SPEED : return strdup("speed"); case VIZ_BT_STRAFE : return strdup("strafe"); case VIZ_BT_MOVE_RIGHT: return strdup("moveright"); case VIZ_BT_MOVE_LEFT: return strdup("moveleft"); case VIZ_BT_MOVE_BACK : return strdup("back"); case VIZ_BT_MOVE_FORWARD : return strdup("forward"); case VIZ_BT_TURN_RIGHT : return strdup("right"); case VIZ_BT_TURN_LEFT : return strdup("left"); case VIZ_BT_LOOK_UP : return strdup("lookup"); case VIZ_BT_LOOK_DOWN : return strdup("lookdown"); case VIZ_BT_MOVE_UP : return strdup("moveup"); case VIZ_BT_MOVE_DOWN : return strdup("movedown"); case VIZ_BT_LAND : return strdup("land"); case VIZ_BT_SELECT_WEAPON1 : return strdup("slot 1"); case VIZ_BT_SELECT_WEAPON2 : return strdup("slot 2"); case VIZ_BT_SELECT_WEAPON3 : return strdup("slot 3"); case VIZ_BT_SELECT_WEAPON4 : return strdup("slot 4"); case VIZ_BT_SELECT_WEAPON5 : return strdup("slot 5"); case VIZ_BT_SELECT_WEAPON6 : return strdup("slot 6"); case VIZ_BT_SELECT_WEAPON7 : return strdup("slot 7"); case VIZ_BT_SELECT_WEAPON8 : return strdup("slot 8"); case VIZ_BT_SELECT_WEAPON9 : return strdup("slot 9"); case VIZ_BT_SELECT_WEAPON0 : return strdup("slot 0"); case VIZ_BT_SELECT_NEXT_WEAPON : return strdup("weapnext"); case VIZ_BT_SELECT_PREV_WEAPON : return strdup("weapprev"); case VIZ_BT_DROP_SELECTED_WEAPON : return strdup("weapdrop"); case VIZ_BT_ACTIVATE_SELECTED_ITEM : return strdup("invuse"); case VIZ_BT_SELECT_NEXT_ITEM : return strdup("invnext"); case VIZ_BT_SELECT_PREV_ITEM : return strdup("invprev"); case VIZ_BT_DROP_SELECTED_ITEM : return strdup("invdrop"); case VIZ_BT_VIEW_PITCH_AXIS : case VIZ_BT_VIEW_ANGLE_AXIS : case VIZ_BT_FORWARD_BACKWARD_AXIS : case VIZ_BT_LEFT_RIGHT_AXIS : case VIZ_BT_UP_DOWN_AXIS : default : return strdup(""); } } void VIZ_ResetDiscontinuousBT(){ if(vizLastInputUpdate[VIZ_BT_TURN180] < VIZ_TIME) vizInput->BT[VIZ_BT_TURN180] = 0; for(int i = VIZ_BT_LAND; i < VIZ_BT_COUNT; ++i){ if(vizLastInputUpdate[i] < VIZ_TIME) vizInput->BT[i] = 0; } } char* VIZ_AddStateToBTCommmand(char *& cmd, int state){ size_t cmdLen = strlen(cmd); char *stateCmd = new char[cmdLen + 2]; if (state != 0) stateCmd[0] = '+'; else stateCmd[0] = '-'; strncpy(stateCmd + 1, cmd, cmdLen); stateCmd[cmdLen + 1] = '\0'; delete[] cmd; cmd = stateCmd; return stateCmd; } void VIZ_AddBTCommand(VIZButton button, int state){ char* buttonCmd = VIZ_BTToCommand(button); switch(button){ case VIZ_BT_ATTACK : case VIZ_BT_USE : case VIZ_BT_JUMP : case VIZ_BT_CROUCH : case VIZ_BT_ALTATTACK : case VIZ_BT_RELOAD : case VIZ_BT_ZOOM : case VIZ_BT_SPEED : case VIZ_BT_STRAFE : case VIZ_BT_MOVE_RIGHT : case VIZ_BT_MOVE_LEFT : case VIZ_BT_MOVE_BACK : case VIZ_BT_MOVE_FORWARD : case VIZ_BT_TURN_RIGHT : case VIZ_BT_TURN_LEFT : case VIZ_BT_LOOK_UP : case VIZ_BT_LOOK_DOWN : case VIZ_BT_MOVE_UP : case VIZ_BT_MOVE_DOWN: VIZ_AddStateToBTCommmand(buttonCmd, state); VIZ_Command(buttonCmd); break; case VIZ_BT_TURN180 : case VIZ_BT_LAND : case VIZ_BT_SELECT_WEAPON1 : case VIZ_BT_SELECT_WEAPON2 : case VIZ_BT_SELECT_WEAPON3 : case VIZ_BT_SELECT_WEAPON4 : case VIZ_BT_SELECT_WEAPON5 : case VIZ_BT_SELECT_WEAPON6 : case VIZ_BT_SELECT_WEAPON7 : case VIZ_BT_SELECT_WEAPON8 : case VIZ_BT_SELECT_WEAPON9 : case VIZ_BT_SELECT_WEAPON0 : case VIZ_BT_SELECT_NEXT_WEAPON : case VIZ_BT_SELECT_PREV_WEAPON : case VIZ_BT_DROP_SELECTED_WEAPON : case VIZ_BT_ACTIVATE_SELECTED_ITEM : case VIZ_BT_SELECT_NEXT_ITEM : case VIZ_BT_SELECT_PREV_ITEM : case VIZ_BT_DROP_SELECTED_ITEM : if (state) VIZ_Command(buttonCmd); break; case VIZ_BT_VIEW_PITCH_AXIS : case VIZ_BT_VIEW_ANGLE_AXIS : case VIZ_BT_FORWARD_BACKWARD_AXIS : case VIZ_BT_LEFT_RIGHT_AXIS : case VIZ_BT_UP_DOWN_AXIS : if(state != 0) VIZ_AddAxisBT(button, state); break; } delete[] buttonCmd; } void VIZ_InputInit() { try { VIZSMRegion* inputRegion = &vizSMRegion[1]; VIZ_SMCreateRegion(inputRegion, true, VIZ_SMGetRegionOffset(inputRegion), sizeof(VIZInputState)); vizInput = static_cast<VIZInputState *>(inputRegion->address); VIZ_DebugMsg(1, VIZ_FUNC, "inputOffset: %zu, inputSize: %zu", inputRegion->offset, sizeof(VIZInputState)); } catch (bip::interprocess_exception &ex) { VIZ_Error(VIZ_FUNC, "Failed to create input."); } for (int i = 0; i < VIZ_BT_COUNT; ++i) { vizInput->BT[i] = 0; vizInput->BT_AVAILABLE[i] = true; vizLastInputBT[i] = 0; vizLastInputUpdate[i] = 0; } for(int i = 0; i < VIZ_BT_AXIS_BT_COUNT; ++i){ vizInput->BT_MAX_VALUE[i] = 0; } LocalForward = 0; LocalSide = 0; LocalFly = 0; LocalViewAngle = 0; LocalViewPitch = 0; vizInputInited = true; } void VIZ_InputTic(){ if(!*viz_allow_input) { for (unsigned int i = 0; i < VIZ_BT_CMD_BT_COUNT; ++i) { if (vizInput->BT_AVAILABLE[i] && vizInput->BT[i] != vizLastInputBT[i]){ VIZ_AddBTCommand((VIZButton)i, vizInput->BT[i]); } } for (unsigned int i = VIZ_BT_CMD_BT_COUNT; i < VIZ_BT_COUNT; ++i) { if (vizInput->BT_AVAILABLE[i]) { VIZ_AddBTCommand((VIZButton)i, vizInput->BT[i]); } } } else if(vizLastUpdate == VIZ_TIME){ VIZ_ResetDiscontinuousBT(); D_ProcessEvents (); } for (int i = 0; i < VIZ_BT_COUNT; ++i) { vizLastInputBT[i] = vizInput->BT[i]; } } void VIZ_InputClose(){ delete vizInputSMRegion ; }
32.624309
114
0.631414
monaj07
4b2d6f00e6f5ded6c790093f51190e2841dbe750
14,741
cpp
C++
Modules/Core/test/mitkPointSetTest.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
1
2021-11-20T08:19:27.000Z
2021-11-20T08:19:27.000Z
Modules/Core/test/mitkPointSetTest.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
null
null
null
Modules/Core/test/mitkPointSetTest.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
1
2019-01-09T08:20:18.000Z
2019-01-09T08:20:18.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include <mitkInteractionConst.h> #include <mitkNumericTypes.h> #include <mitkPointOperation.h> #include <mitkPointSet.h> #include <fstream> /** * TestSuite for PointSet stuff not only operating on an empty PointSet */ class mitkPointSetTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPointSetTestSuite); MITK_TEST(TestIsNotEmpty); MITK_TEST(TestSetSelectInfo); MITK_TEST(TestGetNumberOfSelected); MITK_TEST(TestSearchSelectedPoint); MITK_TEST(TestGetPointIfExists); MITK_TEST(TestSwapPointPositionUpwards); MITK_TEST(TestSwapPointPositionUpwardsNotPossible); MITK_TEST(TestSwapPointPositionDownwards); MITK_TEST(TestSwapPointPositionDownwardsNotPossible); MITK_TEST(TestCreateHoleInThePointIDs); MITK_TEST(TestInsertPointWithPointSpecification); MITK_TEST(TestRemovePointInterface); MITK_TEST(TestMaxIdAccess); MITK_TEST(TestInsertPointAtEnd); CPPUNIT_TEST_SUITE_END(); private: mitk::PointSet::Pointer pointSet; static const mitk::PointSet::PointIdentifier selectedPointId = 2; public: void setUp() override { // Create PointSet pointSet = mitk::PointSet::New(); // add some points mitk::Point3D point2, point3, point4; point2.Fill(3); point3.Fill(4); point4.Fill(5); pointSet->InsertPoint(2, point2); pointSet->InsertPoint(3, point3); pointSet->InsertPoint(4, point4); mitk::Point3D point1; mitk::FillVector3D(point1, 1.0, 2.0, 3.0); pointSet->InsertPoint(1, point1); mitk::Point3D point0; point0.Fill(1); pointSet->InsertPoint(0, point0); // select point with id 2 pointSet->SetSelectInfo(2, true); } void tearDown() override { pointSet = nullptr; } void TestIsNotEmpty() { // PointSet can not be empty! CPPUNIT_ASSERT_EQUAL_MESSAGE("check if the PointSet is not empty ", true, !pointSet->IsEmptyTimeStep(0)); /* std::cout << "check if the PointSet is not empty "; if (pointSet->IsEmpty(0)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSetSelectInfo() { // check SetSelectInfo pointSet->SetSelectInfo(4, true); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SetSelectInfo", true, pointSet->GetSelectInfo(4)); /* if (!pointSet->GetSelectInfo(2)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } delete doOp; std::cout<<"[PASSED]"<<std::endl; */ } void TestSearchSelectedPoint() { // check SearchSelectedPoint CPPUNIT_ASSERT_EQUAL_MESSAGE( "check SearchSelectedPoint ", true, pointSet->SearchSelectedPoint() == (int)selectedPointId); /* if( pointSet->SearchSelectedPoint() != 4) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestGetNumberOfSelected() { // check GetNumeberOfSelected CPPUNIT_ASSERT_EQUAL_MESSAGE("check GetNumeberOfSelected ", true, pointSet->GetNumberOfSelected() == 1); /* if(pointSet->GetNumberOfSelected() != 1) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestGetPointIfExists() { // check GetPointIfExists mitk::Point3D point4; mitk::Point3D tempPoint; point4.Fill(5); mitk::PointSet::PointType tmpPoint; pointSet->GetPointIfExists(4, &tmpPoint); CPPUNIT_ASSERT_EQUAL_MESSAGE("check GetPointIfExists: ", true, tmpPoint == point4); /* if (tmpPoint != point5) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionUpwards() { // Check SwapPointPosition upwards mitk::Point3D point; mitk::Point3D tempPoint; point = pointSet->GetPoint(1); pointSet->SwapPointPosition(1, true); tempPoint = pointSet->GetPoint(0); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition upwards", true, point == tempPoint); /* if(point != tempPoint) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionUpwardsNotPossible() { // Check SwapPointPosition upwards not possible CPPUNIT_ASSERT_EQUAL_MESSAGE( "check SwapPointPosition upwards not possible", false, pointSet->SwapPointPosition(0, true)); /* if(pointSet->SwapPointPosition(0, true)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionDownwards() { // Check SwapPointPosition downwards mitk::Point3D point; mitk::Point3D tempPoint; point = pointSet->GetPoint(0); pointSet->SwapPointPosition(0, false); tempPoint = pointSet->GetPoint(1); CPPUNIT_ASSERT_EQUAL_MESSAGE("check SwapPointPosition down", true, point == tempPoint); /* if(point != tempPoint) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestSwapPointPositionDownwardsNotPossible() { mitk::PointSet::Pointer pointSet2 = mitk::PointSet::New(); int id = 0; mitk::Point3D point; point.Fill(1); pointSet2->SetPoint(id, point); // Check SwapPointPosition downwards not possible CPPUNIT_ASSERT_EQUAL_MESSAGE( "check SwapPointPosition downwards not possible", false, pointSet2->SwapPointPosition(id, false)); /* if(pointSet->SwapPointPosition(1, false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestCreateHoleInThePointIDs() { // create a hole in the point IDs mitk::Point3D point(0.); mitk::PointSet::PointType p10, p11, p12; p10.Fill(10.0); p11.Fill(11.0); p12.Fill(12.0); pointSet->InsertPoint(10, p10); pointSet->InsertPoint(11, p11); pointSet->InsertPoint(12, p12); CPPUNIT_ASSERT_EQUAL_MESSAGE("add points with id 10, 11, 12: ", true, (pointSet->IndexExists(10) == true) || (pointSet->IndexExists(11) == true) || (pointSet->IndexExists(12) == true)); // check OpREMOVE ExecuteOperation int id = 11; auto doOp = new mitk::PointOperation(mitk::OpREMOVE, point, id); pointSet->ExecuteOperation(doOp); CPPUNIT_ASSERT_EQUAL_MESSAGE("remove point id 11: ", false, pointSet->IndexExists(id)); /* if(pointSet->IndexExists(id)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } delete doOp; std::cout<<"[PASSED]"<<std::endl; */ // mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12); // pointSet->ExecuteOperation(doOp); delete doOp; // check OpMOVEPOINTUP ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, p12, 12); pointSet->ExecuteOperation(doOp); delete doOp; mitk::PointSet::PointType newP10 = pointSet->GetPoint(10); mitk::PointSet::PointType newP12 = pointSet->GetPoint(12); CPPUNIT_ASSERT_EQUAL_MESSAGE( "check PointOperation OpMOVEPOINTUP for point id 12:", true, ((newP10 == p12) && (newP12 == p10))); // check OpMOVEPOINTDOWN ExecuteOperation doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, p10, 10); pointSet->ExecuteOperation(doOp); delete doOp; newP10 = pointSet->GetPoint(10); newP12 = pointSet->GetPoint(12); CPPUNIT_ASSERT_EQUAL_MESSAGE( "check PointOperation OpMOVEPOINTDOWN for point id 10: ", true, ((newP10 == p10) && (newP12 == p12))); } void TestInsertPointWithPointSpecification() { // check InsertPoint with PointSpecification mitk::Point3D point5; mitk::Point3D tempPoint; point5.Fill(7); pointSet->SetPoint(5, point5, mitk::PTEDGE); tempPoint = pointSet->GetPoint(5); CPPUNIT_ASSERT_EQUAL_MESSAGE("check InsertPoint with PointSpecification", true, tempPoint == point5); /* if (tempPoint != point5) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; */ } void TestRemovePointInterface() { mitk::PointSet::Pointer psClone = pointSet->Clone(); mitk::PointSet::Pointer refPsLastRemoved = mitk::PointSet::New(); mitk::Point3D point0, point1, point2, point3, point4; point0.Fill(1); refPsLastRemoved->InsertPoint(0, point0); mitk::FillVector3D(point1, 1.0, 2.0, 3.0); refPsLastRemoved->InsertPoint(1, point1); point2.Fill(3); point3.Fill(4); refPsLastRemoved->InsertPoint(2, point2); refPsLastRemoved->InsertPoint(3, point3); mitk::PointSet::Pointer refPsMiddleRemoved = mitk::PointSet::New(); refPsMiddleRemoved->InsertPoint(0, point0); refPsMiddleRemoved->InsertPoint(1, point1); refPsMiddleRemoved->InsertPoint(3, point3); // remove non-existent point bool removed = pointSet->RemovePointIfExists(5, 0); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove non-existent point", false, removed); MITK_ASSERT_EQUAL(pointSet, psClone, "No changes made"); // remove point from non-existent time-step removed = pointSet->RemovePointIfExists(1, 1); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove non-existent point", false, removed); MITK_ASSERT_EQUAL(pointSet, psClone, "No changes made"); // remove max id from non-existent time-step mitk::PointSet::PointsIterator maxIt = pointSet->RemovePointAtEnd(2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove max id point from non-existent time step", true, maxIt == pointSet->End(2)); MITK_ASSERT_EQUAL(pointSet, psClone, "No changes made"); // remove max id from empty point set mitk::PointSet::Pointer emptyPS = mitk::PointSet::New(); maxIt = emptyPS->RemovePointAtEnd(0); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove max id point from non-existent time step", true, maxIt == emptyPS->End(0)); int size = emptyPS->GetSize(0); unsigned int pointSetSeriesSize = emptyPS->GetPointSetSeriesSize(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Nothing added", true, size == 0 && pointSetSeriesSize == 1); // remove max id point maxIt = pointSet->RemovePointAtEnd(0); CPPUNIT_ASSERT_EQUAL_MESSAGE("Point id 4 removed", false, pointSet->IndexExists(4)); MITK_ASSERT_EQUAL(pointSet, refPsLastRemoved, "No changes made"); mitk::PointSet::PointIdentifier id = maxIt.Index(); mitk::PointSet::PointType refPt; refPt[0] = 4.0; refPt[1] = 4.0; refPt[2] = 4.0; mitk::PointSet::PointType pt = maxIt.Value(); bool equal = mitk::Equal(refPt, pt); CPPUNIT_ASSERT_EQUAL_MESSAGE("Returned iterator pointing at max id", true, id == 3 && equal); // remove middle point removed = pointSet->RemovePointIfExists(2, 0); CPPUNIT_ASSERT_EQUAL_MESSAGE("Remove point id 2", true, removed); MITK_ASSERT_EQUAL(pointSet, refPsMiddleRemoved, "Point removed"); } void TestMaxIdAccess() { typedef mitk::PointSet::PointIdentifier IdType; typedef mitk::PointSet::PointsIterator PointsIteratorType; PointsIteratorType empty; mitk::Point3D new1, new2, new3, new4, refMaxPt; new1.Fill(4); new2.Fill(5); new3.Fill(6); new4.Fill(7); refMaxPt.Fill(5); pointSet->SetPoint(0, new1, 2); pointSet->InsertPoint(1, new2, 2); pointSet->InsertPoint(3, new3, 2); pointSet->InsertPoint(6, new4, 2); PointsIteratorType maxIt = pointSet->GetMaxId(1); empty = pointSet->End(1); CPPUNIT_ASSERT_EQUAL_MESSAGE("Check empty time step max id.", true, maxIt == empty); maxIt = pointSet->GetMaxId(3); empty = pointSet->End(3); CPPUNIT_ASSERT_EQUAL_MESSAGE("Check non-existent time step max id.", true, maxIt == empty); maxIt = pointSet->GetMaxId(0); empty = pointSet->End(0); IdType maxId = maxIt.Index(); mitk::Point3D maxPt = maxIt.Value(); bool equal = mitk::Equal(maxPt, refMaxPt); CPPUNIT_ASSERT_EQUAL_MESSAGE("Check time step 0 max id iterator.", false, maxIt == empty); CPPUNIT_ASSERT_EQUAL_MESSAGE("Check time step 0 max id.", true, maxId == 4); CPPUNIT_ASSERT_EQUAL_MESSAGE("Check time step 0 max id point.", true, equal); maxIt = pointSet->GetMaxId(2); empty = pointSet->End(2); maxId = maxIt.Index(); maxPt = maxIt.Value(); equal = mitk::Equal(maxPt, new4); CPPUNIT_ASSERT_EQUAL_MESSAGE("Check time step 2 max id iterator.", false, maxIt == empty); CPPUNIT_ASSERT_EQUAL_MESSAGE("Check time step 2 max id.", true, maxId == 6); CPPUNIT_ASSERT_EQUAL_MESSAGE("Check time step 2 max id point.", true, equal); } void TestInsertPointAtEnd() { typedef mitk::PointSet::PointType PointType; PointType new1, new2, new3, new4, refMaxPt; new1.Fill(4); new2.Fill(5); new3.Fill(6); new4.Fill(7); pointSet->SetPoint(1, new1, 2); pointSet->InsertPoint(3, new2, 2); pointSet->InsertPoint(4, new3, 2); pointSet->InsertPoint(6, new4, 2); PointType in1, in2, in3, in4; in1.Fill(8); in2.Fill(9); in3.Fill(10); in4.Fill(11); mitk::PointSet::Pointer refPs1 = pointSet->Clone(); refPs1->SetPoint(5, in1, 0); mitk::PointSet::Pointer refPs2 = pointSet->Clone(); refPs2->SetPoint(5, in1, 0); refPs2->SetPoint(0, in2, 1); mitk::PointSet::Pointer refPs3 = pointSet->Clone(); refPs3->SetPoint(5, in1, 0); refPs3->SetPoint(0, in2, 1); refPs3->SetPoint(7, in3, 2); mitk::PointSet::Pointer refPs4 = pointSet->Clone(); refPs4->SetPoint(5, in1, 0); refPs4->SetPoint(0, in2, 1); refPs4->SetPoint(7, in3, 2); refPs4->SetPoint(0, in4, 7); pointSet->InsertPoint(in1, 0); MITK_ASSERT_EQUAL(pointSet, refPs1, "Check point insertion for time step 0."); pointSet->InsertPoint(in2, 1); MITK_ASSERT_EQUAL(pointSet, refPs2, "Check point insertion for time step 1."); pointSet->InsertPoint(in3, 2); MITK_ASSERT_EQUAL(pointSet, refPs3, "Check point insertion for time step 2."); pointSet->InsertPoint(in4, 7); MITK_ASSERT_EQUAL(pointSet, refPs4, "Check point insertion for time step 7."); } }; MITK_TEST_SUITE_REGISTRATION(mitkPointSet)
30.206967
117
0.669018
ZP-Hust
4b2ef541e499933dfe0e88759dbf13a48da70bc8
12,382
cpp
C++
scripting/lua/cocos2dx_support/CCLuaStack.cpp
CocosRobot/cocos2d-x
1a527ea331363cfe108b5e2f0ac04a61f8883527
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
scripting/lua/cocos2dx_support/CCLuaStack.cpp
CocosRobot/cocos2d-x
1a527ea331363cfe108b5e2f0ac04a61f8883527
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
scripting/lua/cocos2dx_support/CCLuaStack.cpp
CocosRobot/cocos2d-x
1a527ea331363cfe108b5e2f0ac04a61f8883527
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
/**************************************************************************** Copyright (c) 2011 cocos2d-x.org http://www.cocos2d-x.org 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. ****************************************************************************/ #include "CCLuaStack.h" extern "C" { #include "lua.h" #include "tolua++.h" #include "lualib.h" #include "lauxlib.h" #include "tolua_fix.h" } #include "LuaCocos2d.h" #include "Cocos2dxLuaLoader.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #include "platform/ios/CCLuaObjcBridge.h" #endif namespace { int lua_print(lua_State * luastate) { int nargs = lua_gettop(luastate); std::string t; for (int i=1; i <= nargs; i++) { if (lua_istable(luastate, i)) t += "table"; else if (lua_isnone(luastate, i)) t += "none"; else if (lua_isnil(luastate, i)) t += "nil"; else if (lua_isboolean(luastate, i)) { if (lua_toboolean(luastate, i) != 0) t += "true"; else t += "false"; } else if (lua_isfunction(luastate, i)) t += "function"; else if (lua_islightuserdata(luastate, i)) t += "lightuserdata"; else if (lua_isthread(luastate, i)) t += "thread"; else { const char * str = lua_tostring(luastate, i); if (str) t += lua_tostring(luastate, i); else t += lua_typename(luastate, lua_type(luastate, i)); } if (i!=nargs) t += "\t"; } CCLOG("[LUA-print] %s", t.c_str()); return 0; } } // namespace { NS_CC_BEGIN CCLuaStack *CCLuaStack::create(void) { CCLuaStack *stack = new CCLuaStack(); stack->init(); stack->autorelease(); return stack; } CCLuaStack *CCLuaStack::attach(lua_State *L) { CCLuaStack *stack = new CCLuaStack(); stack->initWithLuaState(L); stack->autorelease(); return stack; } bool CCLuaStack::init(void) { m_state = lua_open(); luaL_openlibs(m_state); tolua_Cocos2d_open(m_state); toluafix_open(m_state); // Register our version of the global "print" function const luaL_reg global_functions [] = { {"print", lua_print}, {NULL, NULL} }; luaL_register(m_state, "_G", global_functions); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) CCLuaObjcBridge::luaopen_luaoc(m_state); #endif // add cocos2dx loader addLuaLoader(cocos2dx_lua_loader); return true; } bool CCLuaStack::initWithLuaState(lua_State *L) { m_state = L; return true; } void CCLuaStack::addSearchPath(const char* path) { lua_getglobal(m_state, "package"); /* L: package */ lua_getfield(m_state, -1, "path"); /* get package.path, L: package path */ const char* cur_path = lua_tostring(m_state, -1); lua_pushfstring(m_state, "%s;%s/?.lua", cur_path, path); /* L: package path newpath */ lua_setfield(m_state, -3, "path"); /* package.path = newpath, L: package path */ lua_pop(m_state, 2); /* L: - */ } void CCLuaStack::addLuaLoader(lua_CFunction func) { if (!func) return; // stack content after the invoking of the function // get loader table lua_getglobal(m_state, "package"); /* L: package */ lua_getfield(m_state, -1, "loaders"); /* L: package, loaders */ // insert loader into index 2 lua_pushcfunction(m_state, func); /* L: package, loaders, func */ for (int i = lua_objlen(m_state, -2) + 1; i > 2; --i) { lua_rawgeti(m_state, -2, i - 1); /* L: package, loaders, func, function */ // we call lua_rawgeti, so the loader table now is at -3 lua_rawseti(m_state, -3, i); /* L: package, loaders, func */ } lua_rawseti(m_state, -2, 2); /* L: package, loaders */ // set loaders into package lua_setfield(m_state, -2, "loaders"); /* L: package */ lua_pop(m_state, 1); } void CCLuaStack::removeScriptObjectByCCObject(CCObject* pObj) { toluafix_remove_ccobject_by_refid(m_state, pObj->m_nLuaID); } void CCLuaStack::removeScriptHandler(int nHandler) { toluafix_remove_function_by_refid(m_state, nHandler); } int CCLuaStack::executeString(const char *codes) { luaL_loadstring(m_state, codes); return executeFunction(0); } int CCLuaStack::executeScriptFile(const char* filename) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) std::string code("require \""); code.append(filename); code.append("\""); return executeString(code.c_str()); #else std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(filename); ++m_callFromLua; int nRet = luaL_dofile(m_state, fullPath.c_str()); --m_callFromLua; CC_ASSERT(m_callFromLua >= 0); // lua_gc(m_state, LUA_GCCOLLECT, 0); if (nRet != 0) { CCLOG("[LUA ERROR] %s", lua_tostring(m_state, -1)); lua_pop(m_state, 1); return nRet; } return 0; #endif } int CCLuaStack::executeGlobalFunction(const char* functionName) { lua_getglobal(m_state, functionName); /* query function by name, stack: function */ if (!lua_isfunction(m_state, -1)) { CCLOG("[LUA ERROR] name '%s' does not represent a Lua function", functionName); lua_pop(m_state, 1); return 0; } return executeFunction(0); } void CCLuaStack::clean(void) { lua_settop(m_state, 0); } void CCLuaStack::pushInt(int intValue) { lua_pushinteger(m_state, intValue); } void CCLuaStack::pushFloat(float floatValue) { lua_pushnumber(m_state, floatValue); } void CCLuaStack::pushBoolean(bool boolValue) { lua_pushboolean(m_state, boolValue); } void CCLuaStack::pushString(const char* stringValue) { lua_pushstring(m_state, stringValue); } void CCLuaStack::pushString(const char* stringValue, int length) { lua_pushlstring(m_state, stringValue, length); } void CCLuaStack::pushNil(void) { lua_pushnil(m_state); } void CCLuaStack::pushCCObject(CCObject* objectValue, const char* typeName) { toluafix_pushusertype_ccobject(m_state, objectValue->m_uID, &objectValue->m_nLuaID, objectValue, typeName); } void CCLuaStack::pushCCLuaValue(const CCLuaValue& value) { const CCLuaValueType type = value.getType(); if (type == CCLuaValueTypeInt) { return pushInt(value.intValue()); } else if (type == CCLuaValueTypeFloat) { return pushFloat(value.floatValue()); } else if (type == CCLuaValueTypeBoolean) { return pushBoolean(value.booleanValue()); } else if (type == CCLuaValueTypeString) { return pushString(value.stringValue().c_str()); } else if (type == CCLuaValueTypeDict) { pushCCLuaValueDict(value.dictValue()); } else if (type == CCLuaValueTypeArray) { pushCCLuaValueArray(value.arrayValue()); } else if (type == CCLuaValueTypeCCObject) { pushCCObject(value.ccobjectValue(), value.getCCObjectTypename().c_str()); } } void CCLuaStack::pushCCLuaValueDict(const CCLuaValueDict& dict) { lua_newtable(m_state); /* L: table */ for (CCLuaValueDictIterator it = dict.begin(); it != dict.end(); ++it) { lua_pushstring(m_state, it->first.c_str()); /* L: table key */ pushCCLuaValue(it->second); /* L: table key value */ lua_rawset(m_state, -3); /* table.key = value, L: table */ } } void CCLuaStack::pushCCLuaValueArray(const CCLuaValueArray& array) { lua_newtable(m_state); /* L: table */ int index = 1; for (CCLuaValueArrayIterator it = array.begin(); it != array.end(); ++it) { pushCCLuaValue(*it); /* L: table value */ lua_rawseti(m_state, -2, index); /* table[index] = value, L: table */ ++index; } } bool CCLuaStack::pushFunctionByHandler(int nHandler) { toluafix_get_function_by_refid(m_state, nHandler); /* L: ... func */ if (!lua_isfunction(m_state, -1)) { CCLOG("[LUA ERROR] function refid '%d' does not reference a Lua function", nHandler); lua_pop(m_state, 1); return false; } return true; } int CCLuaStack::executeFunction(int numArgs) { int functionIndex = -(numArgs + 1); if (!lua_isfunction(m_state, functionIndex)) { CCLOG("value at stack [%d] is not function", functionIndex); lua_pop(m_state, numArgs + 1); // remove function and arguments return 0; } int traceback = 0; lua_getglobal(m_state, "__G__TRACKBACK__"); /* L: ... func arg1 arg2 ... G */ if (!lua_isfunction(m_state, -1)) { lua_pop(m_state, 1); /* L: ... func arg1 arg2 ... */ } else { lua_insert(m_state, functionIndex - 1); /* L: ... G func arg1 arg2 ... */ traceback = functionIndex - 1; } int error = 0; ++m_callFromLua; error = lua_pcall(m_state, numArgs, 1, traceback); /* L: ... [G] ret */ --m_callFromLua; if (error) { if (traceback == 0) { CCLOG("[LUA ERROR] %s", lua_tostring(m_state, - 1)); /* L: ... error */ lua_pop(m_state, 1); // remove error message from stack } else /* L: ... G error */ { lua_pop(m_state, 2); // remove __G__TRACKBACK__ and error message from stack } return 0; } // get return value int ret = 0; if (lua_isnumber(m_state, -1)) { ret = lua_tointeger(m_state, -1); } else if (lua_isboolean(m_state, -1)) { ret = lua_toboolean(m_state, -1); } // remove return value from stack lua_pop(m_state, 1); /* L: ... [G] */ if (traceback) { lua_pop(m_state, 1); // remove __G__TRACKBACK__ from stack /* L: ... */ } return ret; } int CCLuaStack::executeFunctionByHandler(int nHandler, int numArgs) { int ret = 0; if (pushFunctionByHandler(nHandler)) /* L: ... arg1 arg2 ... func */ { if (numArgs > 0) { lua_insert(m_state, -(numArgs + 1)); /* L: ... func arg1 arg2 ... */ } ret = executeFunction(numArgs); } lua_settop(m_state, 0); return ret; } bool CCLuaStack::handleAssert(const char *msg) { if (m_callFromLua == 0) return false; lua_pushfstring(m_state, "ASSERT FAILED ON LUA EXECUTE: %s", msg ? msg : "unknown"); lua_error(m_state); return true; } NS_CC_END
29.693046
113
0.576159
CocosRobot
4b30fe9ffd813767512f64e63e67fd460bc1b84a
2,540
cpp
C++
cpp/cpp/843. Guess the Word.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
3
2021-08-07T07:01:34.000Z
2021-08-07T07:03:02.000Z
cpp/cpp/843. Guess the Word.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
cpp/cpp/843. Guess the Word.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/guess-the-word/ // This is an interactive problem. // You are given an array of unique strings wordlist where wordlist[i] is 6 letters // long, and one word in this list is chosen as secret. // You may call Master.guess(word) to guess a word. The guessed word should have // type string and must be from the original list with 6 lowercase letters. // This function returns an integer type, representing the number of exact matches // (value and position) of your guess to the secret word. Also, if your guess is // not in the given wordlist, it will return -1 instead. // For each test case, you have exactly 10 guesses to guess the word. At the end of // any number of calls, if you have made 10 or fewer calls to Master.guess and at // least one of these guesses was secret, then you pass the test case. //////////////////////////////////////////////////////////////////////////////// // randomly pick a word, keep the words having the same match /** * // This is the Master's API interface. * // You should not implement it, or speculate about its implementation * class Master { * public: * int guess(string word); * }; */ class Solution { public: void findSecretWord(vector<string>& wordlist, Master& master) { for (int i = 0; i < 10; ++i) { unordered_map<string, int> no_match_counts; for (string word1 : wordlist) for (string word2 : wordlist) if (CountMatch(word1, word2) == 0) ++no_match_counts[word1]; // pick the word with smallest no_match_count int no_match_count = INT_MAX; string cand_word; for (string word : wordlist) if (no_match_counts[word] <= no_match_count) { cand_word = word; no_match_count = no_match_counts[word]; } int match = master.guess(cand_word); if (match == 6) return; vector<string> wordlist2; for (string other_word : wordlist) { if (CountMatch(other_word, cand_word) == match) { wordlist2.push_back(other_word); } } wordlist = wordlist2; } } private: int CountMatch(string& s1, string& s2) { int match = 0, n = s1.size(); for (int i = 0; i < n; ++i) { if (s1[i] == s2[i]) ++match; } return match; } };
35.774648
83
0.565748
longwangjhu
4b39d285d109df7524da0a5fdd9ed8c24016c8fa
1,368
cpp
C++
source/RegistRTTR.cpp
xzrunner/taskgraph
56fd18358ac22a77f9c07ba69923883397057c52
[ "MIT" ]
null
null
null
source/RegistRTTR.cpp
xzrunner/taskgraph
56fd18358ac22a77f9c07ba69923883397057c52
[ "MIT" ]
null
null
null
source/RegistRTTR.cpp
xzrunner/taskgraph
56fd18358ac22a77f9c07ba69923883397057c52
[ "MIT" ]
null
null
null
#define EXE_FILEPATH "taskgraph/task_include_gen.h" #include "taskgraph/task_regist_cfg.h" #undef EXE_FILEPATH #include "taskgraph/Task.h" #include "taskgraph/task/Group.h" #include <rttr/registration> #define REGIST_ENUM_ITEM(type, name, label) \ rttr::value(name, type), \ rttr::metadata(type, label) \ RTTR_REGISTRATION { // base rttr::registration::class_<dag::Node<taskgraph::ParamType>::Port>("taskgraph::Task::Port") .property("var", &dag::Node<taskgraph::ParamType>::Port::var) ; rttr::registration::class_<taskgraph::Task>("taskgraph::Task") .method("GetImports", &taskgraph::Task::GetImports) .method("GetExports", &taskgraph::Task::GetExports) ; #define EXE_FILEPATH "taskgraph/task_rttr_gen.h" #include "taskgraph/task_regist_cfg.h" #undef EXE_FILEPATH rttr::registration::enumeration<taskgraph::task::WriteImage::Type>("task_write_img_type") ( REGIST_ENUM_ITEM(taskgraph::task::WriteImage::Type::PNG, "png", "PNG"), REGIST_ENUM_ITEM(taskgraph::task::WriteImage::Type::HGT, "hgt", "HGT") ); rttr::registration::enumeration<taskgraph::task::Group::Type>("task_group_type") ( REGIST_ENUM_ITEM(taskgraph::task::Group::Type::Parallel, "parallel", "Parallel"), REGIST_ENUM_ITEM(taskgraph::task::Group::Type::Sequence, "sequence", "Sequence") ); } namespace taskgraph { void regist_rttr() { } }
25.811321
90
0.717836
xzrunner
4b3aafef1712aa0258bb8ad09e6eee752240ba59
276
hpp
C++
include/IModule.hpp
ForTheReallys/Waybar
9d4048983db4dd1e7224ce9b34ca4853570cae85
[ "MIT" ]
null
null
null
include/IModule.hpp
ForTheReallys/Waybar
9d4048983db4dd1e7224ce9b34ca4853570cae85
[ "MIT" ]
null
null
null
include/IModule.hpp
ForTheReallys/Waybar
9d4048983db4dd1e7224ce9b34ca4853570cae85
[ "MIT" ]
null
null
null
#pragma once #include <gtkmm.h> namespace waybar { class IModule { public: virtual ~IModule() = default; virtual auto update() -> void = 0; virtual operator Gtk::Widget &() = 0; Glib::Dispatcher dp; // Hmmm Maybe I should create an abstract class ? }; }
17.25
74
0.641304
ForTheReallys
4b3cd904c82989aa55007558ed118a9955e1d778
778
hpp
C++
SFML-UI/include/SFML-UI/Core/Transform.hpp
PoetaKodu/sfml-ui
35be37d1b803555e9b2c030cfa215c4c65b1e9e9
[ "MIT" ]
null
null
null
SFML-UI/include/SFML-UI/Core/Transform.hpp
PoetaKodu/sfml-ui
35be37d1b803555e9b2c030cfa215c4c65b1e9e9
[ "MIT" ]
null
null
null
SFML-UI/include/SFML-UI/Core/Transform.hpp
PoetaKodu/sfml-ui
35be37d1b803555e9b2c030cfa215c4c65b1e9e9
[ "MIT" ]
null
null
null
#pragma once #include SFMLUI_PCH namespace sfui { namespace transform_algorithm { /// <summary> /// Extracts position from specified transform. /// </summary> /// <param name="transform_"></param> /// <returns>Extracted position.</returns> sf::Vector2f extractPosition(sf::Transform const & transform_); /// <summary> /// Extracts scale from specified transform. /// </summary> /// <param name="transform_"></param> /// <param name="xyz_"></param> /// <returns>Extracted scale.</returns> sf::Vector2f extractScale(sf::Transform const & transform_); /// <summary> /// Extracts rotation from specified transform. /// </summary> /// <param name="transform_"></param> /// <returns>Extracted rotation.</returns> float extractRotation(sf::Transform const & transform_); } }
21.027027
63
0.701799
PoetaKodu
4b3d13b451dac68d140598cef01d29933a845424
833
cc
C++
engine/core/bitTables.cc
ClayHanson/B4v21-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
1
2020-08-18T19:45:34.000Z
2020-08-18T19:45:34.000Z
engine/core/bitTables.cc
ClayHanson/B4v21-Launcher-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
null
null
null
engine/core/bitTables.cc
ClayHanson/B4v21-Launcher-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- #include "core/bitTables.h" bool BitTables::mTablesBuilt = false; S8 BitTables::mHighBit[256]; S8 BitTables::mWhichOn[256][8]; S8 BitTables::mNumOn[256]; static BitTables sBuildTheTables; // invoke ctor first-time work BitTables::BitTables() { if(! mTablesBuilt){ // This code only happens once - it relies on the tables being clear. for( U32 byte = 0; byte < 256; byte++ ) for( U32 bit = 0; bit < 8; bit++ ) if( byte & (1 << bit) ) mHighBit[byte] = (mWhichOn[byte][mNumOn[byte]++] = bit) + 1; mTablesBuilt = true; } }
32.038462
79
0.478992
ClayHanson
4b3d36d253fd6fba4101a1d2e9e3941b21d36b02
774
cpp
C++
src/AdventOfCode2021/Day03-BinaryDiagnostic/Day03-BinaryDiagnostic.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2021/Day03-BinaryDiagnostic/Day03-BinaryDiagnostic.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2021/Day03-BinaryDiagnostic/Day03-BinaryDiagnostic.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
#include "Day03-BinaryDiagnostic.h" #include "DiagnosticReportAnalyzer.h" #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS __END_LIBRARIES_DISABLE_WARNINGS namespace AdventOfCode { namespace Year2021 { namespace Day03 { int submarinePowerConsumption(const std::vector<std::string>& diagnosticReportLines) { DiagnosticReportAnalyzer analyzer{diagnosticReportLines}; analyzer.calculatePowerConsumptionParameters(); return analyzer.getSubmarinePowerConsumption(); } int lifeSupportRating(const std::vector<std::string>& diagnosticReportLines) { DiagnosticReportAnalyzer analyzer{diagnosticReportLines}; analyzer.calculateLifeSupportRatingParameters(); return analyzer.getLifeSupportRating(); } } } }
23.454545
84
0.824289
dbartok
4b45519dc02224405a435ad752df0f37d34e21be
8,280
cpp
C++
src/bin/unix/state.cpp
EIRNf/twizzler
794383026ce605789c6cfc62093d79f0b01fe1d5
[ "BSD-3-Clause" ]
23
2021-07-09T22:11:58.000Z
2022-03-24T04:19:44.000Z
src/bin/unix/state.cpp
EIRNf/twizzler
794383026ce605789c6cfc62093d79f0b01fe1d5
[ "BSD-3-Clause" ]
38
2021-07-10T02:50:30.000Z
2022-03-16T01:22:46.000Z
src/bin/unix/state.cpp
EIRNf/twizzler
794383026ce605789c6cfc62093d79f0b01fe1d5
[ "BSD-3-Clause" ]
6
2021-07-03T04:15:06.000Z
2022-03-15T00:33:32.000Z
#include "state.h" #include <twix/twix.h> #include <memory> #include <mutex> #include <unordered_map> #include <twz/sys/obj.h> static std::atomic_int next_taskid(2); template<typename K, typename V> class refmap { private: std::unordered_map<K, std::shared_ptr<V>> map; std::mutex lock; public: std::shared_ptr<V> lookup(K k) { std::lock_guard<std::mutex> _lg(lock); auto it = map.find(k); if(it == map.end()) return nullptr; else return (*it).second; } template<typename... Args> void insert(K k, Args... args) { std::lock_guard<std::mutex> _lg(lock); map.insert(std::make_pair(k, std::make_shared<V>(k, args...))); } void insert_existing(K k, std::shared_ptr<V> v) { std::lock_guard<std::mutex> _lg(lock); map.insert(std::make_pair(k, v)); } void remove(K k) { std::lock_guard<std::mutex> _lg(lock); map.erase(k); } }; static refmap<int, unixprocess> proctable; static refmap<int, unixthread> thrtable; static std::mutex forked_lock; static std::unordered_map<objid_t, std::shared_ptr<unixprocess>> forked_procs; static std::unordered_map<objid_t, std::shared_ptr<unixthread>> forked_thrds; std::shared_ptr<unixprocess> process_lookup(int pid) { return proctable.lookup(pid); } void procs_insert_forked(objid_t id, std::shared_ptr<unixprocess> proc) { std::lock_guard<std::mutex> _lg(forked_lock); forked_procs.insert(std::make_pair(id, proc)); } void thrds_insert_forked(objid_t id, std::shared_ptr<unixthread> thrd) { std::lock_guard<std::mutex> _lg(forked_lock); forked_thrds.insert(std::make_pair(id, thrd)); } std::shared_ptr<unixthread> thrds_lookup_forked(objid_t id) { /* TODO: also need to clean up this map when a parent exits... */ std::lock_guard<std::mutex> _lg(forked_lock); auto it = forked_thrds.find(id); if(it == forked_thrds.end()) { return nullptr; } auto ret = it->second; forked_thrds.erase(it); return ret; } std::shared_ptr<unixprocess> procs_lookup_forked(objid_t id) { /* TODO: also need to clean up this map when a parent exits... */ std::lock_guard<std::mutex> _lg(forked_lock); auto it = forked_procs.find(id); if(it == forked_procs.end()) { return nullptr; } auto ret = it->second; forked_procs.erase(it); return ret; } void unixprocess::exit() { /* already locked */ // fprintf(stderr, "process exited! %d\n", pid); { std::lock_guard<std::mutex> _lg(lock); state = PROC_EXITED; status_changed = true; } /* TODO: kill child threads */ for(auto th : threads) { th->kill(); } for(auto child : children) { /* handle parent process exit */ child->parent = nullptr; } children.clear(); // fprintf(stderr, "TODO: send sigchild\n"); /* handle child process exit for parent */ // if(parent) { // parent->child_died(pid); //} else { proctable.remove(pid); //} /* TODO: clean up */ for(auto pw : waiting_clients) { delete pw; } waiting_clients.clear(); } void unixprocess::kill_all_threads(int except) { std::lock_guard<std::mutex> _lg(lock); for(auto t : threads) { if(except == -1 || (t->tid != except)) { t->kill(); } } } void unixthread::kill() { // fprintf(stderr, "TODO: thread kill\n"); sys_signal(twz_object_guid(&client->thrdobj), -1ul, SIGKILL, 0, 0); /* TODO: actually kill thread */ } bool unixthread::send_signal(int sig, bool allow_pending) { fprintf(stderr, "sending signal %d to %d\n", sig, tid); long r = sys_signal(twz_object_guid(&client->thrdobj), -1ul, sig, 0, 0); if(r) { fprintf(stderr, "WARNING: send_signal %ld\n", r); } resume(); return true; } void unixprocess::send_signal(int sig) { std::lock_guard<std::mutex> _lg(lock); if(threads.size() == 0) return; bool ok = false; for(auto thread : threads) { if(thread->send_signal(sig, false)) { ok = true; break; } } if(!ok) { threads[0]->send_signal(sig, true); } } unixthread::unixthread(std::shared_ptr<unixprocess> parent) { tid = next_taskid.fetch_add(1); parent_process = parent; client = nullptr; } unixprocess::unixprocess(std::shared_ptr<unixprocess> parent) : parent(parent) { std::lock_guard<std::mutex> _lg(parent->lock); pid = next_taskid.fetch_add(1); fds = parent->fds; cwd = parent->cwd; state = PROC_FORKED; gid = parent->gid; uid = parent->uid; } bool unixprocess::wait_for_child(std::shared_ptr<queue_client> client, twix_queue_entry *tqe, int pid) { std::lock_guard<std::mutex> _lg(lock); bool found = false; for(auto child : children) { int status; if(pid == -1 || pid == child->pid) { found = true; if(child->wait(&status)) { tqe->arg0 = status; tqe->ret = child->pid; client->complete(tqe); return true; } } } if(!found) return false; pwaiter *pw = new pwaiter(client, tqe, pid); waiting_clients.push_back(pw); return true; } bool unixprocess::child_status_change(unixprocess *child, int status) { /* TODO: signal SIGCHLD? */ std::lock_guard<std::mutex> _lg(lock); for(size_t i = 0; i < waiting_clients.size(); i++) { pwaiter *pw = waiting_clients[i]; if(pw->pid == child->pid || pw->pid == -1) { pw->tqe.arg0 = status; pw->tqe.ret = child->pid; pw->client->complete(&pw->tqe); waiting_clients.erase(waiting_clients.begin() + i); delete pw; if(child->state == PROC_EXITED) child_died(child->pid); return true; } } return false; } int client_init(std::shared_ptr<queue_client> client) { int r = twz_object_new(&client->queue, NULL, NULL, OBJ_VOLATILE, TWZ_OC_DFL_READ | TWZ_OC_DFL_WRITE | TWZ_OC_TIED_NONE); if(r) return r; r = twz_object_new(&client->buffer, NULL, NULL, OBJ_VOLATILE, TWZ_OC_DFL_READ | TWZ_OC_DFL_WRITE | TWZ_OC_TIED_NONE); if(r) return r; r = queue_init_hdr( &client->queue, 12, sizeof(struct twix_queue_entry), 12, sizeof(struct twix_queue_entry)); if(r) return r; int existing = 0; std::shared_ptr<unixprocess> existing_proc = procs_lookup_forked(twz_object_guid(&client->thrdobj)); if(existing_proc != nullptr) { existing = 1; // debug_printf("queue_client_init existing\n"); client->proc = existing_proc; proctable.insert_existing(existing_proc->pid, existing_proc); thrtable.insert(client->proc->pid, client->proc, client); client->thr = thrtable.lookup(client->proc->pid); client->thr->perproc_id = client->proc->add_thread(client->thr); } else { std::shared_ptr<unixthread> existing_thread = thrds_lookup_forked(twz_object_guid(&client->thrdobj)); if(existing_thread != nullptr) { existing = 2; // debug_printf("queue_client_init existing thread\n"); client->proc = existing_thread->parent_process; client->thr = existing_thread; existing_thread->perproc_id = client->proc->add_thread(existing_thread); existing_thread->client = client; thrtable.insert_existing(existing_thread->tid, existing_thread); } else { int taskid = next_taskid.fetch_add(1); proctable.insert(taskid); client->proc = proctable.lookup(taskid); thrtable.insert(client->proc->pid, client->proc, client); client->thr = thrtable.lookup(client->proc->pid); client->thr->perproc_id = client->proc->add_thread(client->thr); } } if(!existing) { auto [rr, desc] = open_file(nullptr, "/"); if(rr) { return rr; } client->proc->cwd = desc; } if(existing != 2) client->proc->mark_ready(); return 0; } void unixthread::resume() { std::lock_guard<std::mutex> _lg(lock); if(suspended_tqe) { client->complete(suspended_tqe); suspended_tqe = nullptr; } } void unixprocess::change_status(proc_state _state, int status) { std::lock_guard<std::mutex> _lg(lock); proc_state old_state = state; state = _state; exit_status = status; for(auto w : state_waiters) { w.first->complete(w.second); delete w.second; } state_waiters.clear(); if(old_state != PROC_FORKED && parent) { parent->child_status_change(this, status); } } void unixprocess::mark_ready() { change_status(PROC_NORMAL, 0); } void queue_client::exit() { thr->exit(); } queue_client::~queue_client() { // fprintf(stderr, "client destructed! (tid %d)\n", thr->tid); twz_object_delete(&queue, 0); twz_object_delete(&buffer, 0); twz_object_release(&queue); twz_object_release(&buffer); (void)twz_object_unwire(NULL, &thrdobj); twz_object_release(&thrdobj); thrtable.remove(thr->tid); }
22.747253
93
0.683696
EIRNf
4b4be78589b6b017b246e5a9e7e9f9bcb71423ee
71,440
hpp
C++
include/staticlib/pimpl/ext_preprocessor/repetition/detail/edg/for.hpp
staticlibs/staticlib_pimpl
1c6ced163cd4a5d7aa08081b78ac14ac4d6e2bf3
[ "Apache-2.0" ]
null
null
null
include/staticlib/pimpl/ext_preprocessor/repetition/detail/edg/for.hpp
staticlibs/staticlib_pimpl
1c6ced163cd4a5d7aa08081b78ac14ac4d6e2bf3
[ "Apache-2.0" ]
null
null
null
include/staticlib/pimpl/ext_preprocessor/repetition/detail/edg/for.hpp
staticlibs/staticlib_pimpl
1c6ced163cd4a5d7aa08081b78ac14ac4d6e2bf3
[ "Apache-2.0" ]
1
2021-06-13T15:46:29.000Z
2021-06-13T15:46:29.000Z
# /* Copyright (C) 2001 # * Housemarque Oy # * http://www.housemarque.com # * # * Distributed under 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) # */ # # /* Revised by Paul Mensonides (2002) */ # # /* See http://www.boost.org for most recent version. */ # # ifndef STATICLIB_PREPROCESSOR_REPETITION_DETAIL_EDG_FOR_HPP # define STATICLIB_PREPROCESSOR_REPETITION_DETAIL_EDG_FOR_HPP # # include "staticlib/pimpl/ext_preprocessor/control/if.hpp" # include "staticlib/pimpl/ext_preprocessor/tuple/eat.hpp" # # define STATICLIB_PP_FOR_1(s, p, o, m) STATICLIB_PP_FOR_1_I(s, p, o, m) # define STATICLIB_PP_FOR_2(s, p, o, m) STATICLIB_PP_FOR_2_I(s, p, o, m) # define STATICLIB_PP_FOR_3(s, p, o, m) STATICLIB_PP_FOR_3_I(s, p, o, m) # define STATICLIB_PP_FOR_4(s, p, o, m) STATICLIB_PP_FOR_4_I(s, p, o, m) # define STATICLIB_PP_FOR_5(s, p, o, m) STATICLIB_PP_FOR_5_I(s, p, o, m) # define STATICLIB_PP_FOR_6(s, p, o, m) STATICLIB_PP_FOR_6_I(s, p, o, m) # define STATICLIB_PP_FOR_7(s, p, o, m) STATICLIB_PP_FOR_7_I(s, p, o, m) # define STATICLIB_PP_FOR_8(s, p, o, m) STATICLIB_PP_FOR_8_I(s, p, o, m) # define STATICLIB_PP_FOR_9(s, p, o, m) STATICLIB_PP_FOR_9_I(s, p, o, m) # define STATICLIB_PP_FOR_10(s, p, o, m) STATICLIB_PP_FOR_10_I(s, p, o, m) # define STATICLIB_PP_FOR_11(s, p, o, m) STATICLIB_PP_FOR_11_I(s, p, o, m) # define STATICLIB_PP_FOR_12(s, p, o, m) STATICLIB_PP_FOR_12_I(s, p, o, m) # define STATICLIB_PP_FOR_13(s, p, o, m) STATICLIB_PP_FOR_13_I(s, p, o, m) # define STATICLIB_PP_FOR_14(s, p, o, m) STATICLIB_PP_FOR_14_I(s, p, o, m) # define STATICLIB_PP_FOR_15(s, p, o, m) STATICLIB_PP_FOR_15_I(s, p, o, m) # define STATICLIB_PP_FOR_16(s, p, o, m) STATICLIB_PP_FOR_16_I(s, p, o, m) # define STATICLIB_PP_FOR_17(s, p, o, m) STATICLIB_PP_FOR_17_I(s, p, o, m) # define STATICLIB_PP_FOR_18(s, p, o, m) STATICLIB_PP_FOR_18_I(s, p, o, m) # define STATICLIB_PP_FOR_19(s, p, o, m) STATICLIB_PP_FOR_19_I(s, p, o, m) # define STATICLIB_PP_FOR_20(s, p, o, m) STATICLIB_PP_FOR_20_I(s, p, o, m) # define STATICLIB_PP_FOR_21(s, p, o, m) STATICLIB_PP_FOR_21_I(s, p, o, m) # define STATICLIB_PP_FOR_22(s, p, o, m) STATICLIB_PP_FOR_22_I(s, p, o, m) # define STATICLIB_PP_FOR_23(s, p, o, m) STATICLIB_PP_FOR_23_I(s, p, o, m) # define STATICLIB_PP_FOR_24(s, p, o, m) STATICLIB_PP_FOR_24_I(s, p, o, m) # define STATICLIB_PP_FOR_25(s, p, o, m) STATICLIB_PP_FOR_25_I(s, p, o, m) # define STATICLIB_PP_FOR_26(s, p, o, m) STATICLIB_PP_FOR_26_I(s, p, o, m) # define STATICLIB_PP_FOR_27(s, p, o, m) STATICLIB_PP_FOR_27_I(s, p, o, m) # define STATICLIB_PP_FOR_28(s, p, o, m) STATICLIB_PP_FOR_28_I(s, p, o, m) # define STATICLIB_PP_FOR_29(s, p, o, m) STATICLIB_PP_FOR_29_I(s, p, o, m) # define STATICLIB_PP_FOR_30(s, p, o, m) STATICLIB_PP_FOR_30_I(s, p, o, m) # define STATICLIB_PP_FOR_31(s, p, o, m) STATICLIB_PP_FOR_31_I(s, p, o, m) # define STATICLIB_PP_FOR_32(s, p, o, m) STATICLIB_PP_FOR_32_I(s, p, o, m) # define STATICLIB_PP_FOR_33(s, p, o, m) STATICLIB_PP_FOR_33_I(s, p, o, m) # define STATICLIB_PP_FOR_34(s, p, o, m) STATICLIB_PP_FOR_34_I(s, p, o, m) # define STATICLIB_PP_FOR_35(s, p, o, m) STATICLIB_PP_FOR_35_I(s, p, o, m) # define STATICLIB_PP_FOR_36(s, p, o, m) STATICLIB_PP_FOR_36_I(s, p, o, m) # define STATICLIB_PP_FOR_37(s, p, o, m) STATICLIB_PP_FOR_37_I(s, p, o, m) # define STATICLIB_PP_FOR_38(s, p, o, m) STATICLIB_PP_FOR_38_I(s, p, o, m) # define STATICLIB_PP_FOR_39(s, p, o, m) STATICLIB_PP_FOR_39_I(s, p, o, m) # define STATICLIB_PP_FOR_40(s, p, o, m) STATICLIB_PP_FOR_40_I(s, p, o, m) # define STATICLIB_PP_FOR_41(s, p, o, m) STATICLIB_PP_FOR_41_I(s, p, o, m) # define STATICLIB_PP_FOR_42(s, p, o, m) STATICLIB_PP_FOR_42_I(s, p, o, m) # define STATICLIB_PP_FOR_43(s, p, o, m) STATICLIB_PP_FOR_43_I(s, p, o, m) # define STATICLIB_PP_FOR_44(s, p, o, m) STATICLIB_PP_FOR_44_I(s, p, o, m) # define STATICLIB_PP_FOR_45(s, p, o, m) STATICLIB_PP_FOR_45_I(s, p, o, m) # define STATICLIB_PP_FOR_46(s, p, o, m) STATICLIB_PP_FOR_46_I(s, p, o, m) # define STATICLIB_PP_FOR_47(s, p, o, m) STATICLIB_PP_FOR_47_I(s, p, o, m) # define STATICLIB_PP_FOR_48(s, p, o, m) STATICLIB_PP_FOR_48_I(s, p, o, m) # define STATICLIB_PP_FOR_49(s, p, o, m) STATICLIB_PP_FOR_49_I(s, p, o, m) # define STATICLIB_PP_FOR_50(s, p, o, m) STATICLIB_PP_FOR_50_I(s, p, o, m) # define STATICLIB_PP_FOR_51(s, p, o, m) STATICLIB_PP_FOR_51_I(s, p, o, m) # define STATICLIB_PP_FOR_52(s, p, o, m) STATICLIB_PP_FOR_52_I(s, p, o, m) # define STATICLIB_PP_FOR_53(s, p, o, m) STATICLIB_PP_FOR_53_I(s, p, o, m) # define STATICLIB_PP_FOR_54(s, p, o, m) STATICLIB_PP_FOR_54_I(s, p, o, m) # define STATICLIB_PP_FOR_55(s, p, o, m) STATICLIB_PP_FOR_55_I(s, p, o, m) # define STATICLIB_PP_FOR_56(s, p, o, m) STATICLIB_PP_FOR_56_I(s, p, o, m) # define STATICLIB_PP_FOR_57(s, p, o, m) STATICLIB_PP_FOR_57_I(s, p, o, m) # define STATICLIB_PP_FOR_58(s, p, o, m) STATICLIB_PP_FOR_58_I(s, p, o, m) # define STATICLIB_PP_FOR_59(s, p, o, m) STATICLIB_PP_FOR_59_I(s, p, o, m) # define STATICLIB_PP_FOR_60(s, p, o, m) STATICLIB_PP_FOR_60_I(s, p, o, m) # define STATICLIB_PP_FOR_61(s, p, o, m) STATICLIB_PP_FOR_61_I(s, p, o, m) # define STATICLIB_PP_FOR_62(s, p, o, m) STATICLIB_PP_FOR_62_I(s, p, o, m) # define STATICLIB_PP_FOR_63(s, p, o, m) STATICLIB_PP_FOR_63_I(s, p, o, m) # define STATICLIB_PP_FOR_64(s, p, o, m) STATICLIB_PP_FOR_64_I(s, p, o, m) # define STATICLIB_PP_FOR_65(s, p, o, m) STATICLIB_PP_FOR_65_I(s, p, o, m) # define STATICLIB_PP_FOR_66(s, p, o, m) STATICLIB_PP_FOR_66_I(s, p, o, m) # define STATICLIB_PP_FOR_67(s, p, o, m) STATICLIB_PP_FOR_67_I(s, p, o, m) # define STATICLIB_PP_FOR_68(s, p, o, m) STATICLIB_PP_FOR_68_I(s, p, o, m) # define STATICLIB_PP_FOR_69(s, p, o, m) STATICLIB_PP_FOR_69_I(s, p, o, m) # define STATICLIB_PP_FOR_70(s, p, o, m) STATICLIB_PP_FOR_70_I(s, p, o, m) # define STATICLIB_PP_FOR_71(s, p, o, m) STATICLIB_PP_FOR_71_I(s, p, o, m) # define STATICLIB_PP_FOR_72(s, p, o, m) STATICLIB_PP_FOR_72_I(s, p, o, m) # define STATICLIB_PP_FOR_73(s, p, o, m) STATICLIB_PP_FOR_73_I(s, p, o, m) # define STATICLIB_PP_FOR_74(s, p, o, m) STATICLIB_PP_FOR_74_I(s, p, o, m) # define STATICLIB_PP_FOR_75(s, p, o, m) STATICLIB_PP_FOR_75_I(s, p, o, m) # define STATICLIB_PP_FOR_76(s, p, o, m) STATICLIB_PP_FOR_76_I(s, p, o, m) # define STATICLIB_PP_FOR_77(s, p, o, m) STATICLIB_PP_FOR_77_I(s, p, o, m) # define STATICLIB_PP_FOR_78(s, p, o, m) STATICLIB_PP_FOR_78_I(s, p, o, m) # define STATICLIB_PP_FOR_79(s, p, o, m) STATICLIB_PP_FOR_79_I(s, p, o, m) # define STATICLIB_PP_FOR_80(s, p, o, m) STATICLIB_PP_FOR_80_I(s, p, o, m) # define STATICLIB_PP_FOR_81(s, p, o, m) STATICLIB_PP_FOR_81_I(s, p, o, m) # define STATICLIB_PP_FOR_82(s, p, o, m) STATICLIB_PP_FOR_82_I(s, p, o, m) # define STATICLIB_PP_FOR_83(s, p, o, m) STATICLIB_PP_FOR_83_I(s, p, o, m) # define STATICLIB_PP_FOR_84(s, p, o, m) STATICLIB_PP_FOR_84_I(s, p, o, m) # define STATICLIB_PP_FOR_85(s, p, o, m) STATICLIB_PP_FOR_85_I(s, p, o, m) # define STATICLIB_PP_FOR_86(s, p, o, m) STATICLIB_PP_FOR_86_I(s, p, o, m) # define STATICLIB_PP_FOR_87(s, p, o, m) STATICLIB_PP_FOR_87_I(s, p, o, m) # define STATICLIB_PP_FOR_88(s, p, o, m) STATICLIB_PP_FOR_88_I(s, p, o, m) # define STATICLIB_PP_FOR_89(s, p, o, m) STATICLIB_PP_FOR_89_I(s, p, o, m) # define STATICLIB_PP_FOR_90(s, p, o, m) STATICLIB_PP_FOR_90_I(s, p, o, m) # define STATICLIB_PP_FOR_91(s, p, o, m) STATICLIB_PP_FOR_91_I(s, p, o, m) # define STATICLIB_PP_FOR_92(s, p, o, m) STATICLIB_PP_FOR_92_I(s, p, o, m) # define STATICLIB_PP_FOR_93(s, p, o, m) STATICLIB_PP_FOR_93_I(s, p, o, m) # define STATICLIB_PP_FOR_94(s, p, o, m) STATICLIB_PP_FOR_94_I(s, p, o, m) # define STATICLIB_PP_FOR_95(s, p, o, m) STATICLIB_PP_FOR_95_I(s, p, o, m) # define STATICLIB_PP_FOR_96(s, p, o, m) STATICLIB_PP_FOR_96_I(s, p, o, m) # define STATICLIB_PP_FOR_97(s, p, o, m) STATICLIB_PP_FOR_97_I(s, p, o, m) # define STATICLIB_PP_FOR_98(s, p, o, m) STATICLIB_PP_FOR_98_I(s, p, o, m) # define STATICLIB_PP_FOR_99(s, p, o, m) STATICLIB_PP_FOR_99_I(s, p, o, m) # define STATICLIB_PP_FOR_100(s, p, o, m) STATICLIB_PP_FOR_100_I(s, p, o, m) # define STATICLIB_PP_FOR_101(s, p, o, m) STATICLIB_PP_FOR_101_I(s, p, o, m) # define STATICLIB_PP_FOR_102(s, p, o, m) STATICLIB_PP_FOR_102_I(s, p, o, m) # define STATICLIB_PP_FOR_103(s, p, o, m) STATICLIB_PP_FOR_103_I(s, p, o, m) # define STATICLIB_PP_FOR_104(s, p, o, m) STATICLIB_PP_FOR_104_I(s, p, o, m) # define STATICLIB_PP_FOR_105(s, p, o, m) STATICLIB_PP_FOR_105_I(s, p, o, m) # define STATICLIB_PP_FOR_106(s, p, o, m) STATICLIB_PP_FOR_106_I(s, p, o, m) # define STATICLIB_PP_FOR_107(s, p, o, m) STATICLIB_PP_FOR_107_I(s, p, o, m) # define STATICLIB_PP_FOR_108(s, p, o, m) STATICLIB_PP_FOR_108_I(s, p, o, m) # define STATICLIB_PP_FOR_109(s, p, o, m) STATICLIB_PP_FOR_109_I(s, p, o, m) # define STATICLIB_PP_FOR_110(s, p, o, m) STATICLIB_PP_FOR_110_I(s, p, o, m) # define STATICLIB_PP_FOR_111(s, p, o, m) STATICLIB_PP_FOR_111_I(s, p, o, m) # define STATICLIB_PP_FOR_112(s, p, o, m) STATICLIB_PP_FOR_112_I(s, p, o, m) # define STATICLIB_PP_FOR_113(s, p, o, m) STATICLIB_PP_FOR_113_I(s, p, o, m) # define STATICLIB_PP_FOR_114(s, p, o, m) STATICLIB_PP_FOR_114_I(s, p, o, m) # define STATICLIB_PP_FOR_115(s, p, o, m) STATICLIB_PP_FOR_115_I(s, p, o, m) # define STATICLIB_PP_FOR_116(s, p, o, m) STATICLIB_PP_FOR_116_I(s, p, o, m) # define STATICLIB_PP_FOR_117(s, p, o, m) STATICLIB_PP_FOR_117_I(s, p, o, m) # define STATICLIB_PP_FOR_118(s, p, o, m) STATICLIB_PP_FOR_118_I(s, p, o, m) # define STATICLIB_PP_FOR_119(s, p, o, m) STATICLIB_PP_FOR_119_I(s, p, o, m) # define STATICLIB_PP_FOR_120(s, p, o, m) STATICLIB_PP_FOR_120_I(s, p, o, m) # define STATICLIB_PP_FOR_121(s, p, o, m) STATICLIB_PP_FOR_121_I(s, p, o, m) # define STATICLIB_PP_FOR_122(s, p, o, m) STATICLIB_PP_FOR_122_I(s, p, o, m) # define STATICLIB_PP_FOR_123(s, p, o, m) STATICLIB_PP_FOR_123_I(s, p, o, m) # define STATICLIB_PP_FOR_124(s, p, o, m) STATICLIB_PP_FOR_124_I(s, p, o, m) # define STATICLIB_PP_FOR_125(s, p, o, m) STATICLIB_PP_FOR_125_I(s, p, o, m) # define STATICLIB_PP_FOR_126(s, p, o, m) STATICLIB_PP_FOR_126_I(s, p, o, m) # define STATICLIB_PP_FOR_127(s, p, o, m) STATICLIB_PP_FOR_127_I(s, p, o, m) # define STATICLIB_PP_FOR_128(s, p, o, m) STATICLIB_PP_FOR_128_I(s, p, o, m) # define STATICLIB_PP_FOR_129(s, p, o, m) STATICLIB_PP_FOR_129_I(s, p, o, m) # define STATICLIB_PP_FOR_130(s, p, o, m) STATICLIB_PP_FOR_130_I(s, p, o, m) # define STATICLIB_PP_FOR_131(s, p, o, m) STATICLIB_PP_FOR_131_I(s, p, o, m) # define STATICLIB_PP_FOR_132(s, p, o, m) STATICLIB_PP_FOR_132_I(s, p, o, m) # define STATICLIB_PP_FOR_133(s, p, o, m) STATICLIB_PP_FOR_133_I(s, p, o, m) # define STATICLIB_PP_FOR_134(s, p, o, m) STATICLIB_PP_FOR_134_I(s, p, o, m) # define STATICLIB_PP_FOR_135(s, p, o, m) STATICLIB_PP_FOR_135_I(s, p, o, m) # define STATICLIB_PP_FOR_136(s, p, o, m) STATICLIB_PP_FOR_136_I(s, p, o, m) # define STATICLIB_PP_FOR_137(s, p, o, m) STATICLIB_PP_FOR_137_I(s, p, o, m) # define STATICLIB_PP_FOR_138(s, p, o, m) STATICLIB_PP_FOR_138_I(s, p, o, m) # define STATICLIB_PP_FOR_139(s, p, o, m) STATICLIB_PP_FOR_139_I(s, p, o, m) # define STATICLIB_PP_FOR_140(s, p, o, m) STATICLIB_PP_FOR_140_I(s, p, o, m) # define STATICLIB_PP_FOR_141(s, p, o, m) STATICLIB_PP_FOR_141_I(s, p, o, m) # define STATICLIB_PP_FOR_142(s, p, o, m) STATICLIB_PP_FOR_142_I(s, p, o, m) # define STATICLIB_PP_FOR_143(s, p, o, m) STATICLIB_PP_FOR_143_I(s, p, o, m) # define STATICLIB_PP_FOR_144(s, p, o, m) STATICLIB_PP_FOR_144_I(s, p, o, m) # define STATICLIB_PP_FOR_145(s, p, o, m) STATICLIB_PP_FOR_145_I(s, p, o, m) # define STATICLIB_PP_FOR_146(s, p, o, m) STATICLIB_PP_FOR_146_I(s, p, o, m) # define STATICLIB_PP_FOR_147(s, p, o, m) STATICLIB_PP_FOR_147_I(s, p, o, m) # define STATICLIB_PP_FOR_148(s, p, o, m) STATICLIB_PP_FOR_148_I(s, p, o, m) # define STATICLIB_PP_FOR_149(s, p, o, m) STATICLIB_PP_FOR_149_I(s, p, o, m) # define STATICLIB_PP_FOR_150(s, p, o, m) STATICLIB_PP_FOR_150_I(s, p, o, m) # define STATICLIB_PP_FOR_151(s, p, o, m) STATICLIB_PP_FOR_151_I(s, p, o, m) # define STATICLIB_PP_FOR_152(s, p, o, m) STATICLIB_PP_FOR_152_I(s, p, o, m) # define STATICLIB_PP_FOR_153(s, p, o, m) STATICLIB_PP_FOR_153_I(s, p, o, m) # define STATICLIB_PP_FOR_154(s, p, o, m) STATICLIB_PP_FOR_154_I(s, p, o, m) # define STATICLIB_PP_FOR_155(s, p, o, m) STATICLIB_PP_FOR_155_I(s, p, o, m) # define STATICLIB_PP_FOR_156(s, p, o, m) STATICLIB_PP_FOR_156_I(s, p, o, m) # define STATICLIB_PP_FOR_157(s, p, o, m) STATICLIB_PP_FOR_157_I(s, p, o, m) # define STATICLIB_PP_FOR_158(s, p, o, m) STATICLIB_PP_FOR_158_I(s, p, o, m) # define STATICLIB_PP_FOR_159(s, p, o, m) STATICLIB_PP_FOR_159_I(s, p, o, m) # define STATICLIB_PP_FOR_160(s, p, o, m) STATICLIB_PP_FOR_160_I(s, p, o, m) # define STATICLIB_PP_FOR_161(s, p, o, m) STATICLIB_PP_FOR_161_I(s, p, o, m) # define STATICLIB_PP_FOR_162(s, p, o, m) STATICLIB_PP_FOR_162_I(s, p, o, m) # define STATICLIB_PP_FOR_163(s, p, o, m) STATICLIB_PP_FOR_163_I(s, p, o, m) # define STATICLIB_PP_FOR_164(s, p, o, m) STATICLIB_PP_FOR_164_I(s, p, o, m) # define STATICLIB_PP_FOR_165(s, p, o, m) STATICLIB_PP_FOR_165_I(s, p, o, m) # define STATICLIB_PP_FOR_166(s, p, o, m) STATICLIB_PP_FOR_166_I(s, p, o, m) # define STATICLIB_PP_FOR_167(s, p, o, m) STATICLIB_PP_FOR_167_I(s, p, o, m) # define STATICLIB_PP_FOR_168(s, p, o, m) STATICLIB_PP_FOR_168_I(s, p, o, m) # define STATICLIB_PP_FOR_169(s, p, o, m) STATICLIB_PP_FOR_169_I(s, p, o, m) # define STATICLIB_PP_FOR_170(s, p, o, m) STATICLIB_PP_FOR_170_I(s, p, o, m) # define STATICLIB_PP_FOR_171(s, p, o, m) STATICLIB_PP_FOR_171_I(s, p, o, m) # define STATICLIB_PP_FOR_172(s, p, o, m) STATICLIB_PP_FOR_172_I(s, p, o, m) # define STATICLIB_PP_FOR_173(s, p, o, m) STATICLIB_PP_FOR_173_I(s, p, o, m) # define STATICLIB_PP_FOR_174(s, p, o, m) STATICLIB_PP_FOR_174_I(s, p, o, m) # define STATICLIB_PP_FOR_175(s, p, o, m) STATICLIB_PP_FOR_175_I(s, p, o, m) # define STATICLIB_PP_FOR_176(s, p, o, m) STATICLIB_PP_FOR_176_I(s, p, o, m) # define STATICLIB_PP_FOR_177(s, p, o, m) STATICLIB_PP_FOR_177_I(s, p, o, m) # define STATICLIB_PP_FOR_178(s, p, o, m) STATICLIB_PP_FOR_178_I(s, p, o, m) # define STATICLIB_PP_FOR_179(s, p, o, m) STATICLIB_PP_FOR_179_I(s, p, o, m) # define STATICLIB_PP_FOR_180(s, p, o, m) STATICLIB_PP_FOR_180_I(s, p, o, m) # define STATICLIB_PP_FOR_181(s, p, o, m) STATICLIB_PP_FOR_181_I(s, p, o, m) # define STATICLIB_PP_FOR_182(s, p, o, m) STATICLIB_PP_FOR_182_I(s, p, o, m) # define STATICLIB_PP_FOR_183(s, p, o, m) STATICLIB_PP_FOR_183_I(s, p, o, m) # define STATICLIB_PP_FOR_184(s, p, o, m) STATICLIB_PP_FOR_184_I(s, p, o, m) # define STATICLIB_PP_FOR_185(s, p, o, m) STATICLIB_PP_FOR_185_I(s, p, o, m) # define STATICLIB_PP_FOR_186(s, p, o, m) STATICLIB_PP_FOR_186_I(s, p, o, m) # define STATICLIB_PP_FOR_187(s, p, o, m) STATICLIB_PP_FOR_187_I(s, p, o, m) # define STATICLIB_PP_FOR_188(s, p, o, m) STATICLIB_PP_FOR_188_I(s, p, o, m) # define STATICLIB_PP_FOR_189(s, p, o, m) STATICLIB_PP_FOR_189_I(s, p, o, m) # define STATICLIB_PP_FOR_190(s, p, o, m) STATICLIB_PP_FOR_190_I(s, p, o, m) # define STATICLIB_PP_FOR_191(s, p, o, m) STATICLIB_PP_FOR_191_I(s, p, o, m) # define STATICLIB_PP_FOR_192(s, p, o, m) STATICLIB_PP_FOR_192_I(s, p, o, m) # define STATICLIB_PP_FOR_193(s, p, o, m) STATICLIB_PP_FOR_193_I(s, p, o, m) # define STATICLIB_PP_FOR_194(s, p, o, m) STATICLIB_PP_FOR_194_I(s, p, o, m) # define STATICLIB_PP_FOR_195(s, p, o, m) STATICLIB_PP_FOR_195_I(s, p, o, m) # define STATICLIB_PP_FOR_196(s, p, o, m) STATICLIB_PP_FOR_196_I(s, p, o, m) # define STATICLIB_PP_FOR_197(s, p, o, m) STATICLIB_PP_FOR_197_I(s, p, o, m) # define STATICLIB_PP_FOR_198(s, p, o, m) STATICLIB_PP_FOR_198_I(s, p, o, m) # define STATICLIB_PP_FOR_199(s, p, o, m) STATICLIB_PP_FOR_199_I(s, p, o, m) # define STATICLIB_PP_FOR_200(s, p, o, m) STATICLIB_PP_FOR_200_I(s, p, o, m) # define STATICLIB_PP_FOR_201(s, p, o, m) STATICLIB_PP_FOR_201_I(s, p, o, m) # define STATICLIB_PP_FOR_202(s, p, o, m) STATICLIB_PP_FOR_202_I(s, p, o, m) # define STATICLIB_PP_FOR_203(s, p, o, m) STATICLIB_PP_FOR_203_I(s, p, o, m) # define STATICLIB_PP_FOR_204(s, p, o, m) STATICLIB_PP_FOR_204_I(s, p, o, m) # define STATICLIB_PP_FOR_205(s, p, o, m) STATICLIB_PP_FOR_205_I(s, p, o, m) # define STATICLIB_PP_FOR_206(s, p, o, m) STATICLIB_PP_FOR_206_I(s, p, o, m) # define STATICLIB_PP_FOR_207(s, p, o, m) STATICLIB_PP_FOR_207_I(s, p, o, m) # define STATICLIB_PP_FOR_208(s, p, o, m) STATICLIB_PP_FOR_208_I(s, p, o, m) # define STATICLIB_PP_FOR_209(s, p, o, m) STATICLIB_PP_FOR_209_I(s, p, o, m) # define STATICLIB_PP_FOR_210(s, p, o, m) STATICLIB_PP_FOR_210_I(s, p, o, m) # define STATICLIB_PP_FOR_211(s, p, o, m) STATICLIB_PP_FOR_211_I(s, p, o, m) # define STATICLIB_PP_FOR_212(s, p, o, m) STATICLIB_PP_FOR_212_I(s, p, o, m) # define STATICLIB_PP_FOR_213(s, p, o, m) STATICLIB_PP_FOR_213_I(s, p, o, m) # define STATICLIB_PP_FOR_214(s, p, o, m) STATICLIB_PP_FOR_214_I(s, p, o, m) # define STATICLIB_PP_FOR_215(s, p, o, m) STATICLIB_PP_FOR_215_I(s, p, o, m) # define STATICLIB_PP_FOR_216(s, p, o, m) STATICLIB_PP_FOR_216_I(s, p, o, m) # define STATICLIB_PP_FOR_217(s, p, o, m) STATICLIB_PP_FOR_217_I(s, p, o, m) # define STATICLIB_PP_FOR_218(s, p, o, m) STATICLIB_PP_FOR_218_I(s, p, o, m) # define STATICLIB_PP_FOR_219(s, p, o, m) STATICLIB_PP_FOR_219_I(s, p, o, m) # define STATICLIB_PP_FOR_220(s, p, o, m) STATICLIB_PP_FOR_220_I(s, p, o, m) # define STATICLIB_PP_FOR_221(s, p, o, m) STATICLIB_PP_FOR_221_I(s, p, o, m) # define STATICLIB_PP_FOR_222(s, p, o, m) STATICLIB_PP_FOR_222_I(s, p, o, m) # define STATICLIB_PP_FOR_223(s, p, o, m) STATICLIB_PP_FOR_223_I(s, p, o, m) # define STATICLIB_PP_FOR_224(s, p, o, m) STATICLIB_PP_FOR_224_I(s, p, o, m) # define STATICLIB_PP_FOR_225(s, p, o, m) STATICLIB_PP_FOR_225_I(s, p, o, m) # define STATICLIB_PP_FOR_226(s, p, o, m) STATICLIB_PP_FOR_226_I(s, p, o, m) # define STATICLIB_PP_FOR_227(s, p, o, m) STATICLIB_PP_FOR_227_I(s, p, o, m) # define STATICLIB_PP_FOR_228(s, p, o, m) STATICLIB_PP_FOR_228_I(s, p, o, m) # define STATICLIB_PP_FOR_229(s, p, o, m) STATICLIB_PP_FOR_229_I(s, p, o, m) # define STATICLIB_PP_FOR_230(s, p, o, m) STATICLIB_PP_FOR_230_I(s, p, o, m) # define STATICLIB_PP_FOR_231(s, p, o, m) STATICLIB_PP_FOR_231_I(s, p, o, m) # define STATICLIB_PP_FOR_232(s, p, o, m) STATICLIB_PP_FOR_232_I(s, p, o, m) # define STATICLIB_PP_FOR_233(s, p, o, m) STATICLIB_PP_FOR_233_I(s, p, o, m) # define STATICLIB_PP_FOR_234(s, p, o, m) STATICLIB_PP_FOR_234_I(s, p, o, m) # define STATICLIB_PP_FOR_235(s, p, o, m) STATICLIB_PP_FOR_235_I(s, p, o, m) # define STATICLIB_PP_FOR_236(s, p, o, m) STATICLIB_PP_FOR_236_I(s, p, o, m) # define STATICLIB_PP_FOR_237(s, p, o, m) STATICLIB_PP_FOR_237_I(s, p, o, m) # define STATICLIB_PP_FOR_238(s, p, o, m) STATICLIB_PP_FOR_238_I(s, p, o, m) # define STATICLIB_PP_FOR_239(s, p, o, m) STATICLIB_PP_FOR_239_I(s, p, o, m) # define STATICLIB_PP_FOR_240(s, p, o, m) STATICLIB_PP_FOR_240_I(s, p, o, m) # define STATICLIB_PP_FOR_241(s, p, o, m) STATICLIB_PP_FOR_241_I(s, p, o, m) # define STATICLIB_PP_FOR_242(s, p, o, m) STATICLIB_PP_FOR_242_I(s, p, o, m) # define STATICLIB_PP_FOR_243(s, p, o, m) STATICLIB_PP_FOR_243_I(s, p, o, m) # define STATICLIB_PP_FOR_244(s, p, o, m) STATICLIB_PP_FOR_244_I(s, p, o, m) # define STATICLIB_PP_FOR_245(s, p, o, m) STATICLIB_PP_FOR_245_I(s, p, o, m) # define STATICLIB_PP_FOR_246(s, p, o, m) STATICLIB_PP_FOR_246_I(s, p, o, m) # define STATICLIB_PP_FOR_247(s, p, o, m) STATICLIB_PP_FOR_247_I(s, p, o, m) # define STATICLIB_PP_FOR_248(s, p, o, m) STATICLIB_PP_FOR_248_I(s, p, o, m) # define STATICLIB_PP_FOR_249(s, p, o, m) STATICLIB_PP_FOR_249_I(s, p, o, m) # define STATICLIB_PP_FOR_250(s, p, o, m) STATICLIB_PP_FOR_250_I(s, p, o, m) # define STATICLIB_PP_FOR_251(s, p, o, m) STATICLIB_PP_FOR_251_I(s, p, o, m) # define STATICLIB_PP_FOR_252(s, p, o, m) STATICLIB_PP_FOR_252_I(s, p, o, m) # define STATICLIB_PP_FOR_253(s, p, o, m) STATICLIB_PP_FOR_253_I(s, p, o, m) # define STATICLIB_PP_FOR_254(s, p, o, m) STATICLIB_PP_FOR_254_I(s, p, o, m) # define STATICLIB_PP_FOR_255(s, p, o, m) STATICLIB_PP_FOR_255_I(s, p, o, m) # define STATICLIB_PP_FOR_256(s, p, o, m) STATICLIB_PP_FOR_256_I(s, p, o, m) # # define STATICLIB_PP_FOR_1_I(s, p, o, m) STATICLIB_PP_IF(p(2, s), m, STATICLIB_PP_TUPLE_EAT_2)(2, s) STATICLIB_PP_IF(p(2, s), STATICLIB_PP_FOR_2, STATICLIB_PP_TUPLE_EAT_4)(o(2, s), p, o, m) # define STATICLIB_PP_FOR_2_I(s, p, o, m) STATICLIB_PP_IF(p(3, s), m, STATICLIB_PP_TUPLE_EAT_2)(3, s) STATICLIB_PP_IF(p(3, s), STATICLIB_PP_FOR_3, STATICLIB_PP_TUPLE_EAT_4)(o(3, s), p, o, m) # define STATICLIB_PP_FOR_3_I(s, p, o, m) STATICLIB_PP_IF(p(4, s), m, STATICLIB_PP_TUPLE_EAT_2)(4, s) STATICLIB_PP_IF(p(4, s), STATICLIB_PP_FOR_4, STATICLIB_PP_TUPLE_EAT_4)(o(4, s), p, o, m) # define STATICLIB_PP_FOR_4_I(s, p, o, m) STATICLIB_PP_IF(p(5, s), m, STATICLIB_PP_TUPLE_EAT_2)(5, s) STATICLIB_PP_IF(p(5, s), STATICLIB_PP_FOR_5, STATICLIB_PP_TUPLE_EAT_4)(o(5, s), p, o, m) # define STATICLIB_PP_FOR_5_I(s, p, o, m) STATICLIB_PP_IF(p(6, s), m, STATICLIB_PP_TUPLE_EAT_2)(6, s) STATICLIB_PP_IF(p(6, s), STATICLIB_PP_FOR_6, STATICLIB_PP_TUPLE_EAT_4)(o(6, s), p, o, m) # define STATICLIB_PP_FOR_6_I(s, p, o, m) STATICLIB_PP_IF(p(7, s), m, STATICLIB_PP_TUPLE_EAT_2)(7, s) STATICLIB_PP_IF(p(7, s), STATICLIB_PP_FOR_7, STATICLIB_PP_TUPLE_EAT_4)(o(7, s), p, o, m) # define STATICLIB_PP_FOR_7_I(s, p, o, m) STATICLIB_PP_IF(p(8, s), m, STATICLIB_PP_TUPLE_EAT_2)(8, s) STATICLIB_PP_IF(p(8, s), STATICLIB_PP_FOR_8, STATICLIB_PP_TUPLE_EAT_4)(o(8, s), p, o, m) # define STATICLIB_PP_FOR_8_I(s, p, o, m) STATICLIB_PP_IF(p(9, s), m, STATICLIB_PP_TUPLE_EAT_2)(9, s) STATICLIB_PP_IF(p(9, s), STATICLIB_PP_FOR_9, STATICLIB_PP_TUPLE_EAT_4)(o(9, s), p, o, m) # define STATICLIB_PP_FOR_9_I(s, p, o, m) STATICLIB_PP_IF(p(10, s), m, STATICLIB_PP_TUPLE_EAT_2)(10, s) STATICLIB_PP_IF(p(10, s), STATICLIB_PP_FOR_10, STATICLIB_PP_TUPLE_EAT_4)(o(10, s), p, o, m) # define STATICLIB_PP_FOR_10_I(s, p, o, m) STATICLIB_PP_IF(p(11, s), m, STATICLIB_PP_TUPLE_EAT_2)(11, s) STATICLIB_PP_IF(p(11, s), STATICLIB_PP_FOR_11, STATICLIB_PP_TUPLE_EAT_4)(o(11, s), p, o, m) # define STATICLIB_PP_FOR_11_I(s, p, o, m) STATICLIB_PP_IF(p(12, s), m, STATICLIB_PP_TUPLE_EAT_2)(12, s) STATICLIB_PP_IF(p(12, s), STATICLIB_PP_FOR_12, STATICLIB_PP_TUPLE_EAT_4)(o(12, s), p, o, m) # define STATICLIB_PP_FOR_12_I(s, p, o, m) STATICLIB_PP_IF(p(13, s), m, STATICLIB_PP_TUPLE_EAT_2)(13, s) STATICLIB_PP_IF(p(13, s), STATICLIB_PP_FOR_13, STATICLIB_PP_TUPLE_EAT_4)(o(13, s), p, o, m) # define STATICLIB_PP_FOR_13_I(s, p, o, m) STATICLIB_PP_IF(p(14, s), m, STATICLIB_PP_TUPLE_EAT_2)(14, s) STATICLIB_PP_IF(p(14, s), STATICLIB_PP_FOR_14, STATICLIB_PP_TUPLE_EAT_4)(o(14, s), p, o, m) # define STATICLIB_PP_FOR_14_I(s, p, o, m) STATICLIB_PP_IF(p(15, s), m, STATICLIB_PP_TUPLE_EAT_2)(15, s) STATICLIB_PP_IF(p(15, s), STATICLIB_PP_FOR_15, STATICLIB_PP_TUPLE_EAT_4)(o(15, s), p, o, m) # define STATICLIB_PP_FOR_15_I(s, p, o, m) STATICLIB_PP_IF(p(16, s), m, STATICLIB_PP_TUPLE_EAT_2)(16, s) STATICLIB_PP_IF(p(16, s), STATICLIB_PP_FOR_16, STATICLIB_PP_TUPLE_EAT_4)(o(16, s), p, o, m) # define STATICLIB_PP_FOR_16_I(s, p, o, m) STATICLIB_PP_IF(p(17, s), m, STATICLIB_PP_TUPLE_EAT_2)(17, s) STATICLIB_PP_IF(p(17, s), STATICLIB_PP_FOR_17, STATICLIB_PP_TUPLE_EAT_4)(o(17, s), p, o, m) # define STATICLIB_PP_FOR_17_I(s, p, o, m) STATICLIB_PP_IF(p(18, s), m, STATICLIB_PP_TUPLE_EAT_2)(18, s) STATICLIB_PP_IF(p(18, s), STATICLIB_PP_FOR_18, STATICLIB_PP_TUPLE_EAT_4)(o(18, s), p, o, m) # define STATICLIB_PP_FOR_18_I(s, p, o, m) STATICLIB_PP_IF(p(19, s), m, STATICLIB_PP_TUPLE_EAT_2)(19, s) STATICLIB_PP_IF(p(19, s), STATICLIB_PP_FOR_19, STATICLIB_PP_TUPLE_EAT_4)(o(19, s), p, o, m) # define STATICLIB_PP_FOR_19_I(s, p, o, m) STATICLIB_PP_IF(p(20, s), m, STATICLIB_PP_TUPLE_EAT_2)(20, s) STATICLIB_PP_IF(p(20, s), STATICLIB_PP_FOR_20, STATICLIB_PP_TUPLE_EAT_4)(o(20, s), p, o, m) # define STATICLIB_PP_FOR_20_I(s, p, o, m) STATICLIB_PP_IF(p(21, s), m, STATICLIB_PP_TUPLE_EAT_2)(21, s) STATICLIB_PP_IF(p(21, s), STATICLIB_PP_FOR_21, STATICLIB_PP_TUPLE_EAT_4)(o(21, s), p, o, m) # define STATICLIB_PP_FOR_21_I(s, p, o, m) STATICLIB_PP_IF(p(22, s), m, STATICLIB_PP_TUPLE_EAT_2)(22, s) STATICLIB_PP_IF(p(22, s), STATICLIB_PP_FOR_22, STATICLIB_PP_TUPLE_EAT_4)(o(22, s), p, o, m) # define STATICLIB_PP_FOR_22_I(s, p, o, m) STATICLIB_PP_IF(p(23, s), m, STATICLIB_PP_TUPLE_EAT_2)(23, s) STATICLIB_PP_IF(p(23, s), STATICLIB_PP_FOR_23, STATICLIB_PP_TUPLE_EAT_4)(o(23, s), p, o, m) # define STATICLIB_PP_FOR_23_I(s, p, o, m) STATICLIB_PP_IF(p(24, s), m, STATICLIB_PP_TUPLE_EAT_2)(24, s) STATICLIB_PP_IF(p(24, s), STATICLIB_PP_FOR_24, STATICLIB_PP_TUPLE_EAT_4)(o(24, s), p, o, m) # define STATICLIB_PP_FOR_24_I(s, p, o, m) STATICLIB_PP_IF(p(25, s), m, STATICLIB_PP_TUPLE_EAT_2)(25, s) STATICLIB_PP_IF(p(25, s), STATICLIB_PP_FOR_25, STATICLIB_PP_TUPLE_EAT_4)(o(25, s), p, o, m) # define STATICLIB_PP_FOR_25_I(s, p, o, m) STATICLIB_PP_IF(p(26, s), m, STATICLIB_PP_TUPLE_EAT_2)(26, s) STATICLIB_PP_IF(p(26, s), STATICLIB_PP_FOR_26, STATICLIB_PP_TUPLE_EAT_4)(o(26, s), p, o, m) # define STATICLIB_PP_FOR_26_I(s, p, o, m) STATICLIB_PP_IF(p(27, s), m, STATICLIB_PP_TUPLE_EAT_2)(27, s) STATICLIB_PP_IF(p(27, s), STATICLIB_PP_FOR_27, STATICLIB_PP_TUPLE_EAT_4)(o(27, s), p, o, m) # define STATICLIB_PP_FOR_27_I(s, p, o, m) STATICLIB_PP_IF(p(28, s), m, STATICLIB_PP_TUPLE_EAT_2)(28, s) STATICLIB_PP_IF(p(28, s), STATICLIB_PP_FOR_28, STATICLIB_PP_TUPLE_EAT_4)(o(28, s), p, o, m) # define STATICLIB_PP_FOR_28_I(s, p, o, m) STATICLIB_PP_IF(p(29, s), m, STATICLIB_PP_TUPLE_EAT_2)(29, s) STATICLIB_PP_IF(p(29, s), STATICLIB_PP_FOR_29, STATICLIB_PP_TUPLE_EAT_4)(o(29, s), p, o, m) # define STATICLIB_PP_FOR_29_I(s, p, o, m) STATICLIB_PP_IF(p(30, s), m, STATICLIB_PP_TUPLE_EAT_2)(30, s) STATICLIB_PP_IF(p(30, s), STATICLIB_PP_FOR_30, STATICLIB_PP_TUPLE_EAT_4)(o(30, s), p, o, m) # define STATICLIB_PP_FOR_30_I(s, p, o, m) STATICLIB_PP_IF(p(31, s), m, STATICLIB_PP_TUPLE_EAT_2)(31, s) STATICLIB_PP_IF(p(31, s), STATICLIB_PP_FOR_31, STATICLIB_PP_TUPLE_EAT_4)(o(31, s), p, o, m) # define STATICLIB_PP_FOR_31_I(s, p, o, m) STATICLIB_PP_IF(p(32, s), m, STATICLIB_PP_TUPLE_EAT_2)(32, s) STATICLIB_PP_IF(p(32, s), STATICLIB_PP_FOR_32, STATICLIB_PP_TUPLE_EAT_4)(o(32, s), p, o, m) # define STATICLIB_PP_FOR_32_I(s, p, o, m) STATICLIB_PP_IF(p(33, s), m, STATICLIB_PP_TUPLE_EAT_2)(33, s) STATICLIB_PP_IF(p(33, s), STATICLIB_PP_FOR_33, STATICLIB_PP_TUPLE_EAT_4)(o(33, s), p, o, m) # define STATICLIB_PP_FOR_33_I(s, p, o, m) STATICLIB_PP_IF(p(34, s), m, STATICLIB_PP_TUPLE_EAT_2)(34, s) STATICLIB_PP_IF(p(34, s), STATICLIB_PP_FOR_34, STATICLIB_PP_TUPLE_EAT_4)(o(34, s), p, o, m) # define STATICLIB_PP_FOR_34_I(s, p, o, m) STATICLIB_PP_IF(p(35, s), m, STATICLIB_PP_TUPLE_EAT_2)(35, s) STATICLIB_PP_IF(p(35, s), STATICLIB_PP_FOR_35, STATICLIB_PP_TUPLE_EAT_4)(o(35, s), p, o, m) # define STATICLIB_PP_FOR_35_I(s, p, o, m) STATICLIB_PP_IF(p(36, s), m, STATICLIB_PP_TUPLE_EAT_2)(36, s) STATICLIB_PP_IF(p(36, s), STATICLIB_PP_FOR_36, STATICLIB_PP_TUPLE_EAT_4)(o(36, s), p, o, m) # define STATICLIB_PP_FOR_36_I(s, p, o, m) STATICLIB_PP_IF(p(37, s), m, STATICLIB_PP_TUPLE_EAT_2)(37, s) STATICLIB_PP_IF(p(37, s), STATICLIB_PP_FOR_37, STATICLIB_PP_TUPLE_EAT_4)(o(37, s), p, o, m) # define STATICLIB_PP_FOR_37_I(s, p, o, m) STATICLIB_PP_IF(p(38, s), m, STATICLIB_PP_TUPLE_EAT_2)(38, s) STATICLIB_PP_IF(p(38, s), STATICLIB_PP_FOR_38, STATICLIB_PP_TUPLE_EAT_4)(o(38, s), p, o, m) # define STATICLIB_PP_FOR_38_I(s, p, o, m) STATICLIB_PP_IF(p(39, s), m, STATICLIB_PP_TUPLE_EAT_2)(39, s) STATICLIB_PP_IF(p(39, s), STATICLIB_PP_FOR_39, STATICLIB_PP_TUPLE_EAT_4)(o(39, s), p, o, m) # define STATICLIB_PP_FOR_39_I(s, p, o, m) STATICLIB_PP_IF(p(40, s), m, STATICLIB_PP_TUPLE_EAT_2)(40, s) STATICLIB_PP_IF(p(40, s), STATICLIB_PP_FOR_40, STATICLIB_PP_TUPLE_EAT_4)(o(40, s), p, o, m) # define STATICLIB_PP_FOR_40_I(s, p, o, m) STATICLIB_PP_IF(p(41, s), m, STATICLIB_PP_TUPLE_EAT_2)(41, s) STATICLIB_PP_IF(p(41, s), STATICLIB_PP_FOR_41, STATICLIB_PP_TUPLE_EAT_4)(o(41, s), p, o, m) # define STATICLIB_PP_FOR_41_I(s, p, o, m) STATICLIB_PP_IF(p(42, s), m, STATICLIB_PP_TUPLE_EAT_2)(42, s) STATICLIB_PP_IF(p(42, s), STATICLIB_PP_FOR_42, STATICLIB_PP_TUPLE_EAT_4)(o(42, s), p, o, m) # define STATICLIB_PP_FOR_42_I(s, p, o, m) STATICLIB_PP_IF(p(43, s), m, STATICLIB_PP_TUPLE_EAT_2)(43, s) STATICLIB_PP_IF(p(43, s), STATICLIB_PP_FOR_43, STATICLIB_PP_TUPLE_EAT_4)(o(43, s), p, o, m) # define STATICLIB_PP_FOR_43_I(s, p, o, m) STATICLIB_PP_IF(p(44, s), m, STATICLIB_PP_TUPLE_EAT_2)(44, s) STATICLIB_PP_IF(p(44, s), STATICLIB_PP_FOR_44, STATICLIB_PP_TUPLE_EAT_4)(o(44, s), p, o, m) # define STATICLIB_PP_FOR_44_I(s, p, o, m) STATICLIB_PP_IF(p(45, s), m, STATICLIB_PP_TUPLE_EAT_2)(45, s) STATICLIB_PP_IF(p(45, s), STATICLIB_PP_FOR_45, STATICLIB_PP_TUPLE_EAT_4)(o(45, s), p, o, m) # define STATICLIB_PP_FOR_45_I(s, p, o, m) STATICLIB_PP_IF(p(46, s), m, STATICLIB_PP_TUPLE_EAT_2)(46, s) STATICLIB_PP_IF(p(46, s), STATICLIB_PP_FOR_46, STATICLIB_PP_TUPLE_EAT_4)(o(46, s), p, o, m) # define STATICLIB_PP_FOR_46_I(s, p, o, m) STATICLIB_PP_IF(p(47, s), m, STATICLIB_PP_TUPLE_EAT_2)(47, s) STATICLIB_PP_IF(p(47, s), STATICLIB_PP_FOR_47, STATICLIB_PP_TUPLE_EAT_4)(o(47, s), p, o, m) # define STATICLIB_PP_FOR_47_I(s, p, o, m) STATICLIB_PP_IF(p(48, s), m, STATICLIB_PP_TUPLE_EAT_2)(48, s) STATICLIB_PP_IF(p(48, s), STATICLIB_PP_FOR_48, STATICLIB_PP_TUPLE_EAT_4)(o(48, s), p, o, m) # define STATICLIB_PP_FOR_48_I(s, p, o, m) STATICLIB_PP_IF(p(49, s), m, STATICLIB_PP_TUPLE_EAT_2)(49, s) STATICLIB_PP_IF(p(49, s), STATICLIB_PP_FOR_49, STATICLIB_PP_TUPLE_EAT_4)(o(49, s), p, o, m) # define STATICLIB_PP_FOR_49_I(s, p, o, m) STATICLIB_PP_IF(p(50, s), m, STATICLIB_PP_TUPLE_EAT_2)(50, s) STATICLIB_PP_IF(p(50, s), STATICLIB_PP_FOR_50, STATICLIB_PP_TUPLE_EAT_4)(o(50, s), p, o, m) # define STATICLIB_PP_FOR_50_I(s, p, o, m) STATICLIB_PP_IF(p(51, s), m, STATICLIB_PP_TUPLE_EAT_2)(51, s) STATICLIB_PP_IF(p(51, s), STATICLIB_PP_FOR_51, STATICLIB_PP_TUPLE_EAT_4)(o(51, s), p, o, m) # define STATICLIB_PP_FOR_51_I(s, p, o, m) STATICLIB_PP_IF(p(52, s), m, STATICLIB_PP_TUPLE_EAT_2)(52, s) STATICLIB_PP_IF(p(52, s), STATICLIB_PP_FOR_52, STATICLIB_PP_TUPLE_EAT_4)(o(52, s), p, o, m) # define STATICLIB_PP_FOR_52_I(s, p, o, m) STATICLIB_PP_IF(p(53, s), m, STATICLIB_PP_TUPLE_EAT_2)(53, s) STATICLIB_PP_IF(p(53, s), STATICLIB_PP_FOR_53, STATICLIB_PP_TUPLE_EAT_4)(o(53, s), p, o, m) # define STATICLIB_PP_FOR_53_I(s, p, o, m) STATICLIB_PP_IF(p(54, s), m, STATICLIB_PP_TUPLE_EAT_2)(54, s) STATICLIB_PP_IF(p(54, s), STATICLIB_PP_FOR_54, STATICLIB_PP_TUPLE_EAT_4)(o(54, s), p, o, m) # define STATICLIB_PP_FOR_54_I(s, p, o, m) STATICLIB_PP_IF(p(55, s), m, STATICLIB_PP_TUPLE_EAT_2)(55, s) STATICLIB_PP_IF(p(55, s), STATICLIB_PP_FOR_55, STATICLIB_PP_TUPLE_EAT_4)(o(55, s), p, o, m) # define STATICLIB_PP_FOR_55_I(s, p, o, m) STATICLIB_PP_IF(p(56, s), m, STATICLIB_PP_TUPLE_EAT_2)(56, s) STATICLIB_PP_IF(p(56, s), STATICLIB_PP_FOR_56, STATICLIB_PP_TUPLE_EAT_4)(o(56, s), p, o, m) # define STATICLIB_PP_FOR_56_I(s, p, o, m) STATICLIB_PP_IF(p(57, s), m, STATICLIB_PP_TUPLE_EAT_2)(57, s) STATICLIB_PP_IF(p(57, s), STATICLIB_PP_FOR_57, STATICLIB_PP_TUPLE_EAT_4)(o(57, s), p, o, m) # define STATICLIB_PP_FOR_57_I(s, p, o, m) STATICLIB_PP_IF(p(58, s), m, STATICLIB_PP_TUPLE_EAT_2)(58, s) STATICLIB_PP_IF(p(58, s), STATICLIB_PP_FOR_58, STATICLIB_PP_TUPLE_EAT_4)(o(58, s), p, o, m) # define STATICLIB_PP_FOR_58_I(s, p, o, m) STATICLIB_PP_IF(p(59, s), m, STATICLIB_PP_TUPLE_EAT_2)(59, s) STATICLIB_PP_IF(p(59, s), STATICLIB_PP_FOR_59, STATICLIB_PP_TUPLE_EAT_4)(o(59, s), p, o, m) # define STATICLIB_PP_FOR_59_I(s, p, o, m) STATICLIB_PP_IF(p(60, s), m, STATICLIB_PP_TUPLE_EAT_2)(60, s) STATICLIB_PP_IF(p(60, s), STATICLIB_PP_FOR_60, STATICLIB_PP_TUPLE_EAT_4)(o(60, s), p, o, m) # define STATICLIB_PP_FOR_60_I(s, p, o, m) STATICLIB_PP_IF(p(61, s), m, STATICLIB_PP_TUPLE_EAT_2)(61, s) STATICLIB_PP_IF(p(61, s), STATICLIB_PP_FOR_61, STATICLIB_PP_TUPLE_EAT_4)(o(61, s), p, o, m) # define STATICLIB_PP_FOR_61_I(s, p, o, m) STATICLIB_PP_IF(p(62, s), m, STATICLIB_PP_TUPLE_EAT_2)(62, s) STATICLIB_PP_IF(p(62, s), STATICLIB_PP_FOR_62, STATICLIB_PP_TUPLE_EAT_4)(o(62, s), p, o, m) # define STATICLIB_PP_FOR_62_I(s, p, o, m) STATICLIB_PP_IF(p(63, s), m, STATICLIB_PP_TUPLE_EAT_2)(63, s) STATICLIB_PP_IF(p(63, s), STATICLIB_PP_FOR_63, STATICLIB_PP_TUPLE_EAT_4)(o(63, s), p, o, m) # define STATICLIB_PP_FOR_63_I(s, p, o, m) STATICLIB_PP_IF(p(64, s), m, STATICLIB_PP_TUPLE_EAT_2)(64, s) STATICLIB_PP_IF(p(64, s), STATICLIB_PP_FOR_64, STATICLIB_PP_TUPLE_EAT_4)(o(64, s), p, o, m) # define STATICLIB_PP_FOR_64_I(s, p, o, m) STATICLIB_PP_IF(p(65, s), m, STATICLIB_PP_TUPLE_EAT_2)(65, s) STATICLIB_PP_IF(p(65, s), STATICLIB_PP_FOR_65, STATICLIB_PP_TUPLE_EAT_4)(o(65, s), p, o, m) # define STATICLIB_PP_FOR_65_I(s, p, o, m) STATICLIB_PP_IF(p(66, s), m, STATICLIB_PP_TUPLE_EAT_2)(66, s) STATICLIB_PP_IF(p(66, s), STATICLIB_PP_FOR_66, STATICLIB_PP_TUPLE_EAT_4)(o(66, s), p, o, m) # define STATICLIB_PP_FOR_66_I(s, p, o, m) STATICLIB_PP_IF(p(67, s), m, STATICLIB_PP_TUPLE_EAT_2)(67, s) STATICLIB_PP_IF(p(67, s), STATICLIB_PP_FOR_67, STATICLIB_PP_TUPLE_EAT_4)(o(67, s), p, o, m) # define STATICLIB_PP_FOR_67_I(s, p, o, m) STATICLIB_PP_IF(p(68, s), m, STATICLIB_PP_TUPLE_EAT_2)(68, s) STATICLIB_PP_IF(p(68, s), STATICLIB_PP_FOR_68, STATICLIB_PP_TUPLE_EAT_4)(o(68, s), p, o, m) # define STATICLIB_PP_FOR_68_I(s, p, o, m) STATICLIB_PP_IF(p(69, s), m, STATICLIB_PP_TUPLE_EAT_2)(69, s) STATICLIB_PP_IF(p(69, s), STATICLIB_PP_FOR_69, STATICLIB_PP_TUPLE_EAT_4)(o(69, s), p, o, m) # define STATICLIB_PP_FOR_69_I(s, p, o, m) STATICLIB_PP_IF(p(70, s), m, STATICLIB_PP_TUPLE_EAT_2)(70, s) STATICLIB_PP_IF(p(70, s), STATICLIB_PP_FOR_70, STATICLIB_PP_TUPLE_EAT_4)(o(70, s), p, o, m) # define STATICLIB_PP_FOR_70_I(s, p, o, m) STATICLIB_PP_IF(p(71, s), m, STATICLIB_PP_TUPLE_EAT_2)(71, s) STATICLIB_PP_IF(p(71, s), STATICLIB_PP_FOR_71, STATICLIB_PP_TUPLE_EAT_4)(o(71, s), p, o, m) # define STATICLIB_PP_FOR_71_I(s, p, o, m) STATICLIB_PP_IF(p(72, s), m, STATICLIB_PP_TUPLE_EAT_2)(72, s) STATICLIB_PP_IF(p(72, s), STATICLIB_PP_FOR_72, STATICLIB_PP_TUPLE_EAT_4)(o(72, s), p, o, m) # define STATICLIB_PP_FOR_72_I(s, p, o, m) STATICLIB_PP_IF(p(73, s), m, STATICLIB_PP_TUPLE_EAT_2)(73, s) STATICLIB_PP_IF(p(73, s), STATICLIB_PP_FOR_73, STATICLIB_PP_TUPLE_EAT_4)(o(73, s), p, o, m) # define STATICLIB_PP_FOR_73_I(s, p, o, m) STATICLIB_PP_IF(p(74, s), m, STATICLIB_PP_TUPLE_EAT_2)(74, s) STATICLIB_PP_IF(p(74, s), STATICLIB_PP_FOR_74, STATICLIB_PP_TUPLE_EAT_4)(o(74, s), p, o, m) # define STATICLIB_PP_FOR_74_I(s, p, o, m) STATICLIB_PP_IF(p(75, s), m, STATICLIB_PP_TUPLE_EAT_2)(75, s) STATICLIB_PP_IF(p(75, s), STATICLIB_PP_FOR_75, STATICLIB_PP_TUPLE_EAT_4)(o(75, s), p, o, m) # define STATICLIB_PP_FOR_75_I(s, p, o, m) STATICLIB_PP_IF(p(76, s), m, STATICLIB_PP_TUPLE_EAT_2)(76, s) STATICLIB_PP_IF(p(76, s), STATICLIB_PP_FOR_76, STATICLIB_PP_TUPLE_EAT_4)(o(76, s), p, o, m) # define STATICLIB_PP_FOR_76_I(s, p, o, m) STATICLIB_PP_IF(p(77, s), m, STATICLIB_PP_TUPLE_EAT_2)(77, s) STATICLIB_PP_IF(p(77, s), STATICLIB_PP_FOR_77, STATICLIB_PP_TUPLE_EAT_4)(o(77, s), p, o, m) # define STATICLIB_PP_FOR_77_I(s, p, o, m) STATICLIB_PP_IF(p(78, s), m, STATICLIB_PP_TUPLE_EAT_2)(78, s) STATICLIB_PP_IF(p(78, s), STATICLIB_PP_FOR_78, STATICLIB_PP_TUPLE_EAT_4)(o(78, s), p, o, m) # define STATICLIB_PP_FOR_78_I(s, p, o, m) STATICLIB_PP_IF(p(79, s), m, STATICLIB_PP_TUPLE_EAT_2)(79, s) STATICLIB_PP_IF(p(79, s), STATICLIB_PP_FOR_79, STATICLIB_PP_TUPLE_EAT_4)(o(79, s), p, o, m) # define STATICLIB_PP_FOR_79_I(s, p, o, m) STATICLIB_PP_IF(p(80, s), m, STATICLIB_PP_TUPLE_EAT_2)(80, s) STATICLIB_PP_IF(p(80, s), STATICLIB_PP_FOR_80, STATICLIB_PP_TUPLE_EAT_4)(o(80, s), p, o, m) # define STATICLIB_PP_FOR_80_I(s, p, o, m) STATICLIB_PP_IF(p(81, s), m, STATICLIB_PP_TUPLE_EAT_2)(81, s) STATICLIB_PP_IF(p(81, s), STATICLIB_PP_FOR_81, STATICLIB_PP_TUPLE_EAT_4)(o(81, s), p, o, m) # define STATICLIB_PP_FOR_81_I(s, p, o, m) STATICLIB_PP_IF(p(82, s), m, STATICLIB_PP_TUPLE_EAT_2)(82, s) STATICLIB_PP_IF(p(82, s), STATICLIB_PP_FOR_82, STATICLIB_PP_TUPLE_EAT_4)(o(82, s), p, o, m) # define STATICLIB_PP_FOR_82_I(s, p, o, m) STATICLIB_PP_IF(p(83, s), m, STATICLIB_PP_TUPLE_EAT_2)(83, s) STATICLIB_PP_IF(p(83, s), STATICLIB_PP_FOR_83, STATICLIB_PP_TUPLE_EAT_4)(o(83, s), p, o, m) # define STATICLIB_PP_FOR_83_I(s, p, o, m) STATICLIB_PP_IF(p(84, s), m, STATICLIB_PP_TUPLE_EAT_2)(84, s) STATICLIB_PP_IF(p(84, s), STATICLIB_PP_FOR_84, STATICLIB_PP_TUPLE_EAT_4)(o(84, s), p, o, m) # define STATICLIB_PP_FOR_84_I(s, p, o, m) STATICLIB_PP_IF(p(85, s), m, STATICLIB_PP_TUPLE_EAT_2)(85, s) STATICLIB_PP_IF(p(85, s), STATICLIB_PP_FOR_85, STATICLIB_PP_TUPLE_EAT_4)(o(85, s), p, o, m) # define STATICLIB_PP_FOR_85_I(s, p, o, m) STATICLIB_PP_IF(p(86, s), m, STATICLIB_PP_TUPLE_EAT_2)(86, s) STATICLIB_PP_IF(p(86, s), STATICLIB_PP_FOR_86, STATICLIB_PP_TUPLE_EAT_4)(o(86, s), p, o, m) # define STATICLIB_PP_FOR_86_I(s, p, o, m) STATICLIB_PP_IF(p(87, s), m, STATICLIB_PP_TUPLE_EAT_2)(87, s) STATICLIB_PP_IF(p(87, s), STATICLIB_PP_FOR_87, STATICLIB_PP_TUPLE_EAT_4)(o(87, s), p, o, m) # define STATICLIB_PP_FOR_87_I(s, p, o, m) STATICLIB_PP_IF(p(88, s), m, STATICLIB_PP_TUPLE_EAT_2)(88, s) STATICLIB_PP_IF(p(88, s), STATICLIB_PP_FOR_88, STATICLIB_PP_TUPLE_EAT_4)(o(88, s), p, o, m) # define STATICLIB_PP_FOR_88_I(s, p, o, m) STATICLIB_PP_IF(p(89, s), m, STATICLIB_PP_TUPLE_EAT_2)(89, s) STATICLIB_PP_IF(p(89, s), STATICLIB_PP_FOR_89, STATICLIB_PP_TUPLE_EAT_4)(o(89, s), p, o, m) # define STATICLIB_PP_FOR_89_I(s, p, o, m) STATICLIB_PP_IF(p(90, s), m, STATICLIB_PP_TUPLE_EAT_2)(90, s) STATICLIB_PP_IF(p(90, s), STATICLIB_PP_FOR_90, STATICLIB_PP_TUPLE_EAT_4)(o(90, s), p, o, m) # define STATICLIB_PP_FOR_90_I(s, p, o, m) STATICLIB_PP_IF(p(91, s), m, STATICLIB_PP_TUPLE_EAT_2)(91, s) STATICLIB_PP_IF(p(91, s), STATICLIB_PP_FOR_91, STATICLIB_PP_TUPLE_EAT_4)(o(91, s), p, o, m) # define STATICLIB_PP_FOR_91_I(s, p, o, m) STATICLIB_PP_IF(p(92, s), m, STATICLIB_PP_TUPLE_EAT_2)(92, s) STATICLIB_PP_IF(p(92, s), STATICLIB_PP_FOR_92, STATICLIB_PP_TUPLE_EAT_4)(o(92, s), p, o, m) # define STATICLIB_PP_FOR_92_I(s, p, o, m) STATICLIB_PP_IF(p(93, s), m, STATICLIB_PP_TUPLE_EAT_2)(93, s) STATICLIB_PP_IF(p(93, s), STATICLIB_PP_FOR_93, STATICLIB_PP_TUPLE_EAT_4)(o(93, s), p, o, m) # define STATICLIB_PP_FOR_93_I(s, p, o, m) STATICLIB_PP_IF(p(94, s), m, STATICLIB_PP_TUPLE_EAT_2)(94, s) STATICLIB_PP_IF(p(94, s), STATICLIB_PP_FOR_94, STATICLIB_PP_TUPLE_EAT_4)(o(94, s), p, o, m) # define STATICLIB_PP_FOR_94_I(s, p, o, m) STATICLIB_PP_IF(p(95, s), m, STATICLIB_PP_TUPLE_EAT_2)(95, s) STATICLIB_PP_IF(p(95, s), STATICLIB_PP_FOR_95, STATICLIB_PP_TUPLE_EAT_4)(o(95, s), p, o, m) # define STATICLIB_PP_FOR_95_I(s, p, o, m) STATICLIB_PP_IF(p(96, s), m, STATICLIB_PP_TUPLE_EAT_2)(96, s) STATICLIB_PP_IF(p(96, s), STATICLIB_PP_FOR_96, STATICLIB_PP_TUPLE_EAT_4)(o(96, s), p, o, m) # define STATICLIB_PP_FOR_96_I(s, p, o, m) STATICLIB_PP_IF(p(97, s), m, STATICLIB_PP_TUPLE_EAT_2)(97, s) STATICLIB_PP_IF(p(97, s), STATICLIB_PP_FOR_97, STATICLIB_PP_TUPLE_EAT_4)(o(97, s), p, o, m) # define STATICLIB_PP_FOR_97_I(s, p, o, m) STATICLIB_PP_IF(p(98, s), m, STATICLIB_PP_TUPLE_EAT_2)(98, s) STATICLIB_PP_IF(p(98, s), STATICLIB_PP_FOR_98, STATICLIB_PP_TUPLE_EAT_4)(o(98, s), p, o, m) # define STATICLIB_PP_FOR_98_I(s, p, o, m) STATICLIB_PP_IF(p(99, s), m, STATICLIB_PP_TUPLE_EAT_2)(99, s) STATICLIB_PP_IF(p(99, s), STATICLIB_PP_FOR_99, STATICLIB_PP_TUPLE_EAT_4)(o(99, s), p, o, m) # define STATICLIB_PP_FOR_99_I(s, p, o, m) STATICLIB_PP_IF(p(100, s), m, STATICLIB_PP_TUPLE_EAT_2)(100, s) STATICLIB_PP_IF(p(100, s), STATICLIB_PP_FOR_100, STATICLIB_PP_TUPLE_EAT_4)(o(100, s), p, o, m) # define STATICLIB_PP_FOR_100_I(s, p, o, m) STATICLIB_PP_IF(p(101, s), m, STATICLIB_PP_TUPLE_EAT_2)(101, s) STATICLIB_PP_IF(p(101, s), STATICLIB_PP_FOR_101, STATICLIB_PP_TUPLE_EAT_4)(o(101, s), p, o, m) # define STATICLIB_PP_FOR_101_I(s, p, o, m) STATICLIB_PP_IF(p(102, s), m, STATICLIB_PP_TUPLE_EAT_2)(102, s) STATICLIB_PP_IF(p(102, s), STATICLIB_PP_FOR_102, STATICLIB_PP_TUPLE_EAT_4)(o(102, s), p, o, m) # define STATICLIB_PP_FOR_102_I(s, p, o, m) STATICLIB_PP_IF(p(103, s), m, STATICLIB_PP_TUPLE_EAT_2)(103, s) STATICLIB_PP_IF(p(103, s), STATICLIB_PP_FOR_103, STATICLIB_PP_TUPLE_EAT_4)(o(103, s), p, o, m) # define STATICLIB_PP_FOR_103_I(s, p, o, m) STATICLIB_PP_IF(p(104, s), m, STATICLIB_PP_TUPLE_EAT_2)(104, s) STATICLIB_PP_IF(p(104, s), STATICLIB_PP_FOR_104, STATICLIB_PP_TUPLE_EAT_4)(o(104, s), p, o, m) # define STATICLIB_PP_FOR_104_I(s, p, o, m) STATICLIB_PP_IF(p(105, s), m, STATICLIB_PP_TUPLE_EAT_2)(105, s) STATICLIB_PP_IF(p(105, s), STATICLIB_PP_FOR_105, STATICLIB_PP_TUPLE_EAT_4)(o(105, s), p, o, m) # define STATICLIB_PP_FOR_105_I(s, p, o, m) STATICLIB_PP_IF(p(106, s), m, STATICLIB_PP_TUPLE_EAT_2)(106, s) STATICLIB_PP_IF(p(106, s), STATICLIB_PP_FOR_106, STATICLIB_PP_TUPLE_EAT_4)(o(106, s), p, o, m) # define STATICLIB_PP_FOR_106_I(s, p, o, m) STATICLIB_PP_IF(p(107, s), m, STATICLIB_PP_TUPLE_EAT_2)(107, s) STATICLIB_PP_IF(p(107, s), STATICLIB_PP_FOR_107, STATICLIB_PP_TUPLE_EAT_4)(o(107, s), p, o, m) # define STATICLIB_PP_FOR_107_I(s, p, o, m) STATICLIB_PP_IF(p(108, s), m, STATICLIB_PP_TUPLE_EAT_2)(108, s) STATICLIB_PP_IF(p(108, s), STATICLIB_PP_FOR_108, STATICLIB_PP_TUPLE_EAT_4)(o(108, s), p, o, m) # define STATICLIB_PP_FOR_108_I(s, p, o, m) STATICLIB_PP_IF(p(109, s), m, STATICLIB_PP_TUPLE_EAT_2)(109, s) STATICLIB_PP_IF(p(109, s), STATICLIB_PP_FOR_109, STATICLIB_PP_TUPLE_EAT_4)(o(109, s), p, o, m) # define STATICLIB_PP_FOR_109_I(s, p, o, m) STATICLIB_PP_IF(p(110, s), m, STATICLIB_PP_TUPLE_EAT_2)(110, s) STATICLIB_PP_IF(p(110, s), STATICLIB_PP_FOR_110, STATICLIB_PP_TUPLE_EAT_4)(o(110, s), p, o, m) # define STATICLIB_PP_FOR_110_I(s, p, o, m) STATICLIB_PP_IF(p(111, s), m, STATICLIB_PP_TUPLE_EAT_2)(111, s) STATICLIB_PP_IF(p(111, s), STATICLIB_PP_FOR_111, STATICLIB_PP_TUPLE_EAT_4)(o(111, s), p, o, m) # define STATICLIB_PP_FOR_111_I(s, p, o, m) STATICLIB_PP_IF(p(112, s), m, STATICLIB_PP_TUPLE_EAT_2)(112, s) STATICLIB_PP_IF(p(112, s), STATICLIB_PP_FOR_112, STATICLIB_PP_TUPLE_EAT_4)(o(112, s), p, o, m) # define STATICLIB_PP_FOR_112_I(s, p, o, m) STATICLIB_PP_IF(p(113, s), m, STATICLIB_PP_TUPLE_EAT_2)(113, s) STATICLIB_PP_IF(p(113, s), STATICLIB_PP_FOR_113, STATICLIB_PP_TUPLE_EAT_4)(o(113, s), p, o, m) # define STATICLIB_PP_FOR_113_I(s, p, o, m) STATICLIB_PP_IF(p(114, s), m, STATICLIB_PP_TUPLE_EAT_2)(114, s) STATICLIB_PP_IF(p(114, s), STATICLIB_PP_FOR_114, STATICLIB_PP_TUPLE_EAT_4)(o(114, s), p, o, m) # define STATICLIB_PP_FOR_114_I(s, p, o, m) STATICLIB_PP_IF(p(115, s), m, STATICLIB_PP_TUPLE_EAT_2)(115, s) STATICLIB_PP_IF(p(115, s), STATICLIB_PP_FOR_115, STATICLIB_PP_TUPLE_EAT_4)(o(115, s), p, o, m) # define STATICLIB_PP_FOR_115_I(s, p, o, m) STATICLIB_PP_IF(p(116, s), m, STATICLIB_PP_TUPLE_EAT_2)(116, s) STATICLIB_PP_IF(p(116, s), STATICLIB_PP_FOR_116, STATICLIB_PP_TUPLE_EAT_4)(o(116, s), p, o, m) # define STATICLIB_PP_FOR_116_I(s, p, o, m) STATICLIB_PP_IF(p(117, s), m, STATICLIB_PP_TUPLE_EAT_2)(117, s) STATICLIB_PP_IF(p(117, s), STATICLIB_PP_FOR_117, STATICLIB_PP_TUPLE_EAT_4)(o(117, s), p, o, m) # define STATICLIB_PP_FOR_117_I(s, p, o, m) STATICLIB_PP_IF(p(118, s), m, STATICLIB_PP_TUPLE_EAT_2)(118, s) STATICLIB_PP_IF(p(118, s), STATICLIB_PP_FOR_118, STATICLIB_PP_TUPLE_EAT_4)(o(118, s), p, o, m) # define STATICLIB_PP_FOR_118_I(s, p, o, m) STATICLIB_PP_IF(p(119, s), m, STATICLIB_PP_TUPLE_EAT_2)(119, s) STATICLIB_PP_IF(p(119, s), STATICLIB_PP_FOR_119, STATICLIB_PP_TUPLE_EAT_4)(o(119, s), p, o, m) # define STATICLIB_PP_FOR_119_I(s, p, o, m) STATICLIB_PP_IF(p(120, s), m, STATICLIB_PP_TUPLE_EAT_2)(120, s) STATICLIB_PP_IF(p(120, s), STATICLIB_PP_FOR_120, STATICLIB_PP_TUPLE_EAT_4)(o(120, s), p, o, m) # define STATICLIB_PP_FOR_120_I(s, p, o, m) STATICLIB_PP_IF(p(121, s), m, STATICLIB_PP_TUPLE_EAT_2)(121, s) STATICLIB_PP_IF(p(121, s), STATICLIB_PP_FOR_121, STATICLIB_PP_TUPLE_EAT_4)(o(121, s), p, o, m) # define STATICLIB_PP_FOR_121_I(s, p, o, m) STATICLIB_PP_IF(p(122, s), m, STATICLIB_PP_TUPLE_EAT_2)(122, s) STATICLIB_PP_IF(p(122, s), STATICLIB_PP_FOR_122, STATICLIB_PP_TUPLE_EAT_4)(o(122, s), p, o, m) # define STATICLIB_PP_FOR_122_I(s, p, o, m) STATICLIB_PP_IF(p(123, s), m, STATICLIB_PP_TUPLE_EAT_2)(123, s) STATICLIB_PP_IF(p(123, s), STATICLIB_PP_FOR_123, STATICLIB_PP_TUPLE_EAT_4)(o(123, s), p, o, m) # define STATICLIB_PP_FOR_123_I(s, p, o, m) STATICLIB_PP_IF(p(124, s), m, STATICLIB_PP_TUPLE_EAT_2)(124, s) STATICLIB_PP_IF(p(124, s), STATICLIB_PP_FOR_124, STATICLIB_PP_TUPLE_EAT_4)(o(124, s), p, o, m) # define STATICLIB_PP_FOR_124_I(s, p, o, m) STATICLIB_PP_IF(p(125, s), m, STATICLIB_PP_TUPLE_EAT_2)(125, s) STATICLIB_PP_IF(p(125, s), STATICLIB_PP_FOR_125, STATICLIB_PP_TUPLE_EAT_4)(o(125, s), p, o, m) # define STATICLIB_PP_FOR_125_I(s, p, o, m) STATICLIB_PP_IF(p(126, s), m, STATICLIB_PP_TUPLE_EAT_2)(126, s) STATICLIB_PP_IF(p(126, s), STATICLIB_PP_FOR_126, STATICLIB_PP_TUPLE_EAT_4)(o(126, s), p, o, m) # define STATICLIB_PP_FOR_126_I(s, p, o, m) STATICLIB_PP_IF(p(127, s), m, STATICLIB_PP_TUPLE_EAT_2)(127, s) STATICLIB_PP_IF(p(127, s), STATICLIB_PP_FOR_127, STATICLIB_PP_TUPLE_EAT_4)(o(127, s), p, o, m) # define STATICLIB_PP_FOR_127_I(s, p, o, m) STATICLIB_PP_IF(p(128, s), m, STATICLIB_PP_TUPLE_EAT_2)(128, s) STATICLIB_PP_IF(p(128, s), STATICLIB_PP_FOR_128, STATICLIB_PP_TUPLE_EAT_4)(o(128, s), p, o, m) # define STATICLIB_PP_FOR_128_I(s, p, o, m) STATICLIB_PP_IF(p(129, s), m, STATICLIB_PP_TUPLE_EAT_2)(129, s) STATICLIB_PP_IF(p(129, s), STATICLIB_PP_FOR_129, STATICLIB_PP_TUPLE_EAT_4)(o(129, s), p, o, m) # define STATICLIB_PP_FOR_129_I(s, p, o, m) STATICLIB_PP_IF(p(130, s), m, STATICLIB_PP_TUPLE_EAT_2)(130, s) STATICLIB_PP_IF(p(130, s), STATICLIB_PP_FOR_130, STATICLIB_PP_TUPLE_EAT_4)(o(130, s), p, o, m) # define STATICLIB_PP_FOR_130_I(s, p, o, m) STATICLIB_PP_IF(p(131, s), m, STATICLIB_PP_TUPLE_EAT_2)(131, s) STATICLIB_PP_IF(p(131, s), STATICLIB_PP_FOR_131, STATICLIB_PP_TUPLE_EAT_4)(o(131, s), p, o, m) # define STATICLIB_PP_FOR_131_I(s, p, o, m) STATICLIB_PP_IF(p(132, s), m, STATICLIB_PP_TUPLE_EAT_2)(132, s) STATICLIB_PP_IF(p(132, s), STATICLIB_PP_FOR_132, STATICLIB_PP_TUPLE_EAT_4)(o(132, s), p, o, m) # define STATICLIB_PP_FOR_132_I(s, p, o, m) STATICLIB_PP_IF(p(133, s), m, STATICLIB_PP_TUPLE_EAT_2)(133, s) STATICLIB_PP_IF(p(133, s), STATICLIB_PP_FOR_133, STATICLIB_PP_TUPLE_EAT_4)(o(133, s), p, o, m) # define STATICLIB_PP_FOR_133_I(s, p, o, m) STATICLIB_PP_IF(p(134, s), m, STATICLIB_PP_TUPLE_EAT_2)(134, s) STATICLIB_PP_IF(p(134, s), STATICLIB_PP_FOR_134, STATICLIB_PP_TUPLE_EAT_4)(o(134, s), p, o, m) # define STATICLIB_PP_FOR_134_I(s, p, o, m) STATICLIB_PP_IF(p(135, s), m, STATICLIB_PP_TUPLE_EAT_2)(135, s) STATICLIB_PP_IF(p(135, s), STATICLIB_PP_FOR_135, STATICLIB_PP_TUPLE_EAT_4)(o(135, s), p, o, m) # define STATICLIB_PP_FOR_135_I(s, p, o, m) STATICLIB_PP_IF(p(136, s), m, STATICLIB_PP_TUPLE_EAT_2)(136, s) STATICLIB_PP_IF(p(136, s), STATICLIB_PP_FOR_136, STATICLIB_PP_TUPLE_EAT_4)(o(136, s), p, o, m) # define STATICLIB_PP_FOR_136_I(s, p, o, m) STATICLIB_PP_IF(p(137, s), m, STATICLIB_PP_TUPLE_EAT_2)(137, s) STATICLIB_PP_IF(p(137, s), STATICLIB_PP_FOR_137, STATICLIB_PP_TUPLE_EAT_4)(o(137, s), p, o, m) # define STATICLIB_PP_FOR_137_I(s, p, o, m) STATICLIB_PP_IF(p(138, s), m, STATICLIB_PP_TUPLE_EAT_2)(138, s) STATICLIB_PP_IF(p(138, s), STATICLIB_PP_FOR_138, STATICLIB_PP_TUPLE_EAT_4)(o(138, s), p, o, m) # define STATICLIB_PP_FOR_138_I(s, p, o, m) STATICLIB_PP_IF(p(139, s), m, STATICLIB_PP_TUPLE_EAT_2)(139, s) STATICLIB_PP_IF(p(139, s), STATICLIB_PP_FOR_139, STATICLIB_PP_TUPLE_EAT_4)(o(139, s), p, o, m) # define STATICLIB_PP_FOR_139_I(s, p, o, m) STATICLIB_PP_IF(p(140, s), m, STATICLIB_PP_TUPLE_EAT_2)(140, s) STATICLIB_PP_IF(p(140, s), STATICLIB_PP_FOR_140, STATICLIB_PP_TUPLE_EAT_4)(o(140, s), p, o, m) # define STATICLIB_PP_FOR_140_I(s, p, o, m) STATICLIB_PP_IF(p(141, s), m, STATICLIB_PP_TUPLE_EAT_2)(141, s) STATICLIB_PP_IF(p(141, s), STATICLIB_PP_FOR_141, STATICLIB_PP_TUPLE_EAT_4)(o(141, s), p, o, m) # define STATICLIB_PP_FOR_141_I(s, p, o, m) STATICLIB_PP_IF(p(142, s), m, STATICLIB_PP_TUPLE_EAT_2)(142, s) STATICLIB_PP_IF(p(142, s), STATICLIB_PP_FOR_142, STATICLIB_PP_TUPLE_EAT_4)(o(142, s), p, o, m) # define STATICLIB_PP_FOR_142_I(s, p, o, m) STATICLIB_PP_IF(p(143, s), m, STATICLIB_PP_TUPLE_EAT_2)(143, s) STATICLIB_PP_IF(p(143, s), STATICLIB_PP_FOR_143, STATICLIB_PP_TUPLE_EAT_4)(o(143, s), p, o, m) # define STATICLIB_PP_FOR_143_I(s, p, o, m) STATICLIB_PP_IF(p(144, s), m, STATICLIB_PP_TUPLE_EAT_2)(144, s) STATICLIB_PP_IF(p(144, s), STATICLIB_PP_FOR_144, STATICLIB_PP_TUPLE_EAT_4)(o(144, s), p, o, m) # define STATICLIB_PP_FOR_144_I(s, p, o, m) STATICLIB_PP_IF(p(145, s), m, STATICLIB_PP_TUPLE_EAT_2)(145, s) STATICLIB_PP_IF(p(145, s), STATICLIB_PP_FOR_145, STATICLIB_PP_TUPLE_EAT_4)(o(145, s), p, o, m) # define STATICLIB_PP_FOR_145_I(s, p, o, m) STATICLIB_PP_IF(p(146, s), m, STATICLIB_PP_TUPLE_EAT_2)(146, s) STATICLIB_PP_IF(p(146, s), STATICLIB_PP_FOR_146, STATICLIB_PP_TUPLE_EAT_4)(o(146, s), p, o, m) # define STATICLIB_PP_FOR_146_I(s, p, o, m) STATICLIB_PP_IF(p(147, s), m, STATICLIB_PP_TUPLE_EAT_2)(147, s) STATICLIB_PP_IF(p(147, s), STATICLIB_PP_FOR_147, STATICLIB_PP_TUPLE_EAT_4)(o(147, s), p, o, m) # define STATICLIB_PP_FOR_147_I(s, p, o, m) STATICLIB_PP_IF(p(148, s), m, STATICLIB_PP_TUPLE_EAT_2)(148, s) STATICLIB_PP_IF(p(148, s), STATICLIB_PP_FOR_148, STATICLIB_PP_TUPLE_EAT_4)(o(148, s), p, o, m) # define STATICLIB_PP_FOR_148_I(s, p, o, m) STATICLIB_PP_IF(p(149, s), m, STATICLIB_PP_TUPLE_EAT_2)(149, s) STATICLIB_PP_IF(p(149, s), STATICLIB_PP_FOR_149, STATICLIB_PP_TUPLE_EAT_4)(o(149, s), p, o, m) # define STATICLIB_PP_FOR_149_I(s, p, o, m) STATICLIB_PP_IF(p(150, s), m, STATICLIB_PP_TUPLE_EAT_2)(150, s) STATICLIB_PP_IF(p(150, s), STATICLIB_PP_FOR_150, STATICLIB_PP_TUPLE_EAT_4)(o(150, s), p, o, m) # define STATICLIB_PP_FOR_150_I(s, p, o, m) STATICLIB_PP_IF(p(151, s), m, STATICLIB_PP_TUPLE_EAT_2)(151, s) STATICLIB_PP_IF(p(151, s), STATICLIB_PP_FOR_151, STATICLIB_PP_TUPLE_EAT_4)(o(151, s), p, o, m) # define STATICLIB_PP_FOR_151_I(s, p, o, m) STATICLIB_PP_IF(p(152, s), m, STATICLIB_PP_TUPLE_EAT_2)(152, s) STATICLIB_PP_IF(p(152, s), STATICLIB_PP_FOR_152, STATICLIB_PP_TUPLE_EAT_4)(o(152, s), p, o, m) # define STATICLIB_PP_FOR_152_I(s, p, o, m) STATICLIB_PP_IF(p(153, s), m, STATICLIB_PP_TUPLE_EAT_2)(153, s) STATICLIB_PP_IF(p(153, s), STATICLIB_PP_FOR_153, STATICLIB_PP_TUPLE_EAT_4)(o(153, s), p, o, m) # define STATICLIB_PP_FOR_153_I(s, p, o, m) STATICLIB_PP_IF(p(154, s), m, STATICLIB_PP_TUPLE_EAT_2)(154, s) STATICLIB_PP_IF(p(154, s), STATICLIB_PP_FOR_154, STATICLIB_PP_TUPLE_EAT_4)(o(154, s), p, o, m) # define STATICLIB_PP_FOR_154_I(s, p, o, m) STATICLIB_PP_IF(p(155, s), m, STATICLIB_PP_TUPLE_EAT_2)(155, s) STATICLIB_PP_IF(p(155, s), STATICLIB_PP_FOR_155, STATICLIB_PP_TUPLE_EAT_4)(o(155, s), p, o, m) # define STATICLIB_PP_FOR_155_I(s, p, o, m) STATICLIB_PP_IF(p(156, s), m, STATICLIB_PP_TUPLE_EAT_2)(156, s) STATICLIB_PP_IF(p(156, s), STATICLIB_PP_FOR_156, STATICLIB_PP_TUPLE_EAT_4)(o(156, s), p, o, m) # define STATICLIB_PP_FOR_156_I(s, p, o, m) STATICLIB_PP_IF(p(157, s), m, STATICLIB_PP_TUPLE_EAT_2)(157, s) STATICLIB_PP_IF(p(157, s), STATICLIB_PP_FOR_157, STATICLIB_PP_TUPLE_EAT_4)(o(157, s), p, o, m) # define STATICLIB_PP_FOR_157_I(s, p, o, m) STATICLIB_PP_IF(p(158, s), m, STATICLIB_PP_TUPLE_EAT_2)(158, s) STATICLIB_PP_IF(p(158, s), STATICLIB_PP_FOR_158, STATICLIB_PP_TUPLE_EAT_4)(o(158, s), p, o, m) # define STATICLIB_PP_FOR_158_I(s, p, o, m) STATICLIB_PP_IF(p(159, s), m, STATICLIB_PP_TUPLE_EAT_2)(159, s) STATICLIB_PP_IF(p(159, s), STATICLIB_PP_FOR_159, STATICLIB_PP_TUPLE_EAT_4)(o(159, s), p, o, m) # define STATICLIB_PP_FOR_159_I(s, p, o, m) STATICLIB_PP_IF(p(160, s), m, STATICLIB_PP_TUPLE_EAT_2)(160, s) STATICLIB_PP_IF(p(160, s), STATICLIB_PP_FOR_160, STATICLIB_PP_TUPLE_EAT_4)(o(160, s), p, o, m) # define STATICLIB_PP_FOR_160_I(s, p, o, m) STATICLIB_PP_IF(p(161, s), m, STATICLIB_PP_TUPLE_EAT_2)(161, s) STATICLIB_PP_IF(p(161, s), STATICLIB_PP_FOR_161, STATICLIB_PP_TUPLE_EAT_4)(o(161, s), p, o, m) # define STATICLIB_PP_FOR_161_I(s, p, o, m) STATICLIB_PP_IF(p(162, s), m, STATICLIB_PP_TUPLE_EAT_2)(162, s) STATICLIB_PP_IF(p(162, s), STATICLIB_PP_FOR_162, STATICLIB_PP_TUPLE_EAT_4)(o(162, s), p, o, m) # define STATICLIB_PP_FOR_162_I(s, p, o, m) STATICLIB_PP_IF(p(163, s), m, STATICLIB_PP_TUPLE_EAT_2)(163, s) STATICLIB_PP_IF(p(163, s), STATICLIB_PP_FOR_163, STATICLIB_PP_TUPLE_EAT_4)(o(163, s), p, o, m) # define STATICLIB_PP_FOR_163_I(s, p, o, m) STATICLIB_PP_IF(p(164, s), m, STATICLIB_PP_TUPLE_EAT_2)(164, s) STATICLIB_PP_IF(p(164, s), STATICLIB_PP_FOR_164, STATICLIB_PP_TUPLE_EAT_4)(o(164, s), p, o, m) # define STATICLIB_PP_FOR_164_I(s, p, o, m) STATICLIB_PP_IF(p(165, s), m, STATICLIB_PP_TUPLE_EAT_2)(165, s) STATICLIB_PP_IF(p(165, s), STATICLIB_PP_FOR_165, STATICLIB_PP_TUPLE_EAT_4)(o(165, s), p, o, m) # define STATICLIB_PP_FOR_165_I(s, p, o, m) STATICLIB_PP_IF(p(166, s), m, STATICLIB_PP_TUPLE_EAT_2)(166, s) STATICLIB_PP_IF(p(166, s), STATICLIB_PP_FOR_166, STATICLIB_PP_TUPLE_EAT_4)(o(166, s), p, o, m) # define STATICLIB_PP_FOR_166_I(s, p, o, m) STATICLIB_PP_IF(p(167, s), m, STATICLIB_PP_TUPLE_EAT_2)(167, s) STATICLIB_PP_IF(p(167, s), STATICLIB_PP_FOR_167, STATICLIB_PP_TUPLE_EAT_4)(o(167, s), p, o, m) # define STATICLIB_PP_FOR_167_I(s, p, o, m) STATICLIB_PP_IF(p(168, s), m, STATICLIB_PP_TUPLE_EAT_2)(168, s) STATICLIB_PP_IF(p(168, s), STATICLIB_PP_FOR_168, STATICLIB_PP_TUPLE_EAT_4)(o(168, s), p, o, m) # define STATICLIB_PP_FOR_168_I(s, p, o, m) STATICLIB_PP_IF(p(169, s), m, STATICLIB_PP_TUPLE_EAT_2)(169, s) STATICLIB_PP_IF(p(169, s), STATICLIB_PP_FOR_169, STATICLIB_PP_TUPLE_EAT_4)(o(169, s), p, o, m) # define STATICLIB_PP_FOR_169_I(s, p, o, m) STATICLIB_PP_IF(p(170, s), m, STATICLIB_PP_TUPLE_EAT_2)(170, s) STATICLIB_PP_IF(p(170, s), STATICLIB_PP_FOR_170, STATICLIB_PP_TUPLE_EAT_4)(o(170, s), p, o, m) # define STATICLIB_PP_FOR_170_I(s, p, o, m) STATICLIB_PP_IF(p(171, s), m, STATICLIB_PP_TUPLE_EAT_2)(171, s) STATICLIB_PP_IF(p(171, s), STATICLIB_PP_FOR_171, STATICLIB_PP_TUPLE_EAT_4)(o(171, s), p, o, m) # define STATICLIB_PP_FOR_171_I(s, p, o, m) STATICLIB_PP_IF(p(172, s), m, STATICLIB_PP_TUPLE_EAT_2)(172, s) STATICLIB_PP_IF(p(172, s), STATICLIB_PP_FOR_172, STATICLIB_PP_TUPLE_EAT_4)(o(172, s), p, o, m) # define STATICLIB_PP_FOR_172_I(s, p, o, m) STATICLIB_PP_IF(p(173, s), m, STATICLIB_PP_TUPLE_EAT_2)(173, s) STATICLIB_PP_IF(p(173, s), STATICLIB_PP_FOR_173, STATICLIB_PP_TUPLE_EAT_4)(o(173, s), p, o, m) # define STATICLIB_PP_FOR_173_I(s, p, o, m) STATICLIB_PP_IF(p(174, s), m, STATICLIB_PP_TUPLE_EAT_2)(174, s) STATICLIB_PP_IF(p(174, s), STATICLIB_PP_FOR_174, STATICLIB_PP_TUPLE_EAT_4)(o(174, s), p, o, m) # define STATICLIB_PP_FOR_174_I(s, p, o, m) STATICLIB_PP_IF(p(175, s), m, STATICLIB_PP_TUPLE_EAT_2)(175, s) STATICLIB_PP_IF(p(175, s), STATICLIB_PP_FOR_175, STATICLIB_PP_TUPLE_EAT_4)(o(175, s), p, o, m) # define STATICLIB_PP_FOR_175_I(s, p, o, m) STATICLIB_PP_IF(p(176, s), m, STATICLIB_PP_TUPLE_EAT_2)(176, s) STATICLIB_PP_IF(p(176, s), STATICLIB_PP_FOR_176, STATICLIB_PP_TUPLE_EAT_4)(o(176, s), p, o, m) # define STATICLIB_PP_FOR_176_I(s, p, o, m) STATICLIB_PP_IF(p(177, s), m, STATICLIB_PP_TUPLE_EAT_2)(177, s) STATICLIB_PP_IF(p(177, s), STATICLIB_PP_FOR_177, STATICLIB_PP_TUPLE_EAT_4)(o(177, s), p, o, m) # define STATICLIB_PP_FOR_177_I(s, p, o, m) STATICLIB_PP_IF(p(178, s), m, STATICLIB_PP_TUPLE_EAT_2)(178, s) STATICLIB_PP_IF(p(178, s), STATICLIB_PP_FOR_178, STATICLIB_PP_TUPLE_EAT_4)(o(178, s), p, o, m) # define STATICLIB_PP_FOR_178_I(s, p, o, m) STATICLIB_PP_IF(p(179, s), m, STATICLIB_PP_TUPLE_EAT_2)(179, s) STATICLIB_PP_IF(p(179, s), STATICLIB_PP_FOR_179, STATICLIB_PP_TUPLE_EAT_4)(o(179, s), p, o, m) # define STATICLIB_PP_FOR_179_I(s, p, o, m) STATICLIB_PP_IF(p(180, s), m, STATICLIB_PP_TUPLE_EAT_2)(180, s) STATICLIB_PP_IF(p(180, s), STATICLIB_PP_FOR_180, STATICLIB_PP_TUPLE_EAT_4)(o(180, s), p, o, m) # define STATICLIB_PP_FOR_180_I(s, p, o, m) STATICLIB_PP_IF(p(181, s), m, STATICLIB_PP_TUPLE_EAT_2)(181, s) STATICLIB_PP_IF(p(181, s), STATICLIB_PP_FOR_181, STATICLIB_PP_TUPLE_EAT_4)(o(181, s), p, o, m) # define STATICLIB_PP_FOR_181_I(s, p, o, m) STATICLIB_PP_IF(p(182, s), m, STATICLIB_PP_TUPLE_EAT_2)(182, s) STATICLIB_PP_IF(p(182, s), STATICLIB_PP_FOR_182, STATICLIB_PP_TUPLE_EAT_4)(o(182, s), p, o, m) # define STATICLIB_PP_FOR_182_I(s, p, o, m) STATICLIB_PP_IF(p(183, s), m, STATICLIB_PP_TUPLE_EAT_2)(183, s) STATICLIB_PP_IF(p(183, s), STATICLIB_PP_FOR_183, STATICLIB_PP_TUPLE_EAT_4)(o(183, s), p, o, m) # define STATICLIB_PP_FOR_183_I(s, p, o, m) STATICLIB_PP_IF(p(184, s), m, STATICLIB_PP_TUPLE_EAT_2)(184, s) STATICLIB_PP_IF(p(184, s), STATICLIB_PP_FOR_184, STATICLIB_PP_TUPLE_EAT_4)(o(184, s), p, o, m) # define STATICLIB_PP_FOR_184_I(s, p, o, m) STATICLIB_PP_IF(p(185, s), m, STATICLIB_PP_TUPLE_EAT_2)(185, s) STATICLIB_PP_IF(p(185, s), STATICLIB_PP_FOR_185, STATICLIB_PP_TUPLE_EAT_4)(o(185, s), p, o, m) # define STATICLIB_PP_FOR_185_I(s, p, o, m) STATICLIB_PP_IF(p(186, s), m, STATICLIB_PP_TUPLE_EAT_2)(186, s) STATICLIB_PP_IF(p(186, s), STATICLIB_PP_FOR_186, STATICLIB_PP_TUPLE_EAT_4)(o(186, s), p, o, m) # define STATICLIB_PP_FOR_186_I(s, p, o, m) STATICLIB_PP_IF(p(187, s), m, STATICLIB_PP_TUPLE_EAT_2)(187, s) STATICLIB_PP_IF(p(187, s), STATICLIB_PP_FOR_187, STATICLIB_PP_TUPLE_EAT_4)(o(187, s), p, o, m) # define STATICLIB_PP_FOR_187_I(s, p, o, m) STATICLIB_PP_IF(p(188, s), m, STATICLIB_PP_TUPLE_EAT_2)(188, s) STATICLIB_PP_IF(p(188, s), STATICLIB_PP_FOR_188, STATICLIB_PP_TUPLE_EAT_4)(o(188, s), p, o, m) # define STATICLIB_PP_FOR_188_I(s, p, o, m) STATICLIB_PP_IF(p(189, s), m, STATICLIB_PP_TUPLE_EAT_2)(189, s) STATICLIB_PP_IF(p(189, s), STATICLIB_PP_FOR_189, STATICLIB_PP_TUPLE_EAT_4)(o(189, s), p, o, m) # define STATICLIB_PP_FOR_189_I(s, p, o, m) STATICLIB_PP_IF(p(190, s), m, STATICLIB_PP_TUPLE_EAT_2)(190, s) STATICLIB_PP_IF(p(190, s), STATICLIB_PP_FOR_190, STATICLIB_PP_TUPLE_EAT_4)(o(190, s), p, o, m) # define STATICLIB_PP_FOR_190_I(s, p, o, m) STATICLIB_PP_IF(p(191, s), m, STATICLIB_PP_TUPLE_EAT_2)(191, s) STATICLIB_PP_IF(p(191, s), STATICLIB_PP_FOR_191, STATICLIB_PP_TUPLE_EAT_4)(o(191, s), p, o, m) # define STATICLIB_PP_FOR_191_I(s, p, o, m) STATICLIB_PP_IF(p(192, s), m, STATICLIB_PP_TUPLE_EAT_2)(192, s) STATICLIB_PP_IF(p(192, s), STATICLIB_PP_FOR_192, STATICLIB_PP_TUPLE_EAT_4)(o(192, s), p, o, m) # define STATICLIB_PP_FOR_192_I(s, p, o, m) STATICLIB_PP_IF(p(193, s), m, STATICLIB_PP_TUPLE_EAT_2)(193, s) STATICLIB_PP_IF(p(193, s), STATICLIB_PP_FOR_193, STATICLIB_PP_TUPLE_EAT_4)(o(193, s), p, o, m) # define STATICLIB_PP_FOR_193_I(s, p, o, m) STATICLIB_PP_IF(p(194, s), m, STATICLIB_PP_TUPLE_EAT_2)(194, s) STATICLIB_PP_IF(p(194, s), STATICLIB_PP_FOR_194, STATICLIB_PP_TUPLE_EAT_4)(o(194, s), p, o, m) # define STATICLIB_PP_FOR_194_I(s, p, o, m) STATICLIB_PP_IF(p(195, s), m, STATICLIB_PP_TUPLE_EAT_2)(195, s) STATICLIB_PP_IF(p(195, s), STATICLIB_PP_FOR_195, STATICLIB_PP_TUPLE_EAT_4)(o(195, s), p, o, m) # define STATICLIB_PP_FOR_195_I(s, p, o, m) STATICLIB_PP_IF(p(196, s), m, STATICLIB_PP_TUPLE_EAT_2)(196, s) STATICLIB_PP_IF(p(196, s), STATICLIB_PP_FOR_196, STATICLIB_PP_TUPLE_EAT_4)(o(196, s), p, o, m) # define STATICLIB_PP_FOR_196_I(s, p, o, m) STATICLIB_PP_IF(p(197, s), m, STATICLIB_PP_TUPLE_EAT_2)(197, s) STATICLIB_PP_IF(p(197, s), STATICLIB_PP_FOR_197, STATICLIB_PP_TUPLE_EAT_4)(o(197, s), p, o, m) # define STATICLIB_PP_FOR_197_I(s, p, o, m) STATICLIB_PP_IF(p(198, s), m, STATICLIB_PP_TUPLE_EAT_2)(198, s) STATICLIB_PP_IF(p(198, s), STATICLIB_PP_FOR_198, STATICLIB_PP_TUPLE_EAT_4)(o(198, s), p, o, m) # define STATICLIB_PP_FOR_198_I(s, p, o, m) STATICLIB_PP_IF(p(199, s), m, STATICLIB_PP_TUPLE_EAT_2)(199, s) STATICLIB_PP_IF(p(199, s), STATICLIB_PP_FOR_199, STATICLIB_PP_TUPLE_EAT_4)(o(199, s), p, o, m) # define STATICLIB_PP_FOR_199_I(s, p, o, m) STATICLIB_PP_IF(p(200, s), m, STATICLIB_PP_TUPLE_EAT_2)(200, s) STATICLIB_PP_IF(p(200, s), STATICLIB_PP_FOR_200, STATICLIB_PP_TUPLE_EAT_4)(o(200, s), p, o, m) # define STATICLIB_PP_FOR_200_I(s, p, o, m) STATICLIB_PP_IF(p(201, s), m, STATICLIB_PP_TUPLE_EAT_2)(201, s) STATICLIB_PP_IF(p(201, s), STATICLIB_PP_FOR_201, STATICLIB_PP_TUPLE_EAT_4)(o(201, s), p, o, m) # define STATICLIB_PP_FOR_201_I(s, p, o, m) STATICLIB_PP_IF(p(202, s), m, STATICLIB_PP_TUPLE_EAT_2)(202, s) STATICLIB_PP_IF(p(202, s), STATICLIB_PP_FOR_202, STATICLIB_PP_TUPLE_EAT_4)(o(202, s), p, o, m) # define STATICLIB_PP_FOR_202_I(s, p, o, m) STATICLIB_PP_IF(p(203, s), m, STATICLIB_PP_TUPLE_EAT_2)(203, s) STATICLIB_PP_IF(p(203, s), STATICLIB_PP_FOR_203, STATICLIB_PP_TUPLE_EAT_4)(o(203, s), p, o, m) # define STATICLIB_PP_FOR_203_I(s, p, o, m) STATICLIB_PP_IF(p(204, s), m, STATICLIB_PP_TUPLE_EAT_2)(204, s) STATICLIB_PP_IF(p(204, s), STATICLIB_PP_FOR_204, STATICLIB_PP_TUPLE_EAT_4)(o(204, s), p, o, m) # define STATICLIB_PP_FOR_204_I(s, p, o, m) STATICLIB_PP_IF(p(205, s), m, STATICLIB_PP_TUPLE_EAT_2)(205, s) STATICLIB_PP_IF(p(205, s), STATICLIB_PP_FOR_205, STATICLIB_PP_TUPLE_EAT_4)(o(205, s), p, o, m) # define STATICLIB_PP_FOR_205_I(s, p, o, m) STATICLIB_PP_IF(p(206, s), m, STATICLIB_PP_TUPLE_EAT_2)(206, s) STATICLIB_PP_IF(p(206, s), STATICLIB_PP_FOR_206, STATICLIB_PP_TUPLE_EAT_4)(o(206, s), p, o, m) # define STATICLIB_PP_FOR_206_I(s, p, o, m) STATICLIB_PP_IF(p(207, s), m, STATICLIB_PP_TUPLE_EAT_2)(207, s) STATICLIB_PP_IF(p(207, s), STATICLIB_PP_FOR_207, STATICLIB_PP_TUPLE_EAT_4)(o(207, s), p, o, m) # define STATICLIB_PP_FOR_207_I(s, p, o, m) STATICLIB_PP_IF(p(208, s), m, STATICLIB_PP_TUPLE_EAT_2)(208, s) STATICLIB_PP_IF(p(208, s), STATICLIB_PP_FOR_208, STATICLIB_PP_TUPLE_EAT_4)(o(208, s), p, o, m) # define STATICLIB_PP_FOR_208_I(s, p, o, m) STATICLIB_PP_IF(p(209, s), m, STATICLIB_PP_TUPLE_EAT_2)(209, s) STATICLIB_PP_IF(p(209, s), STATICLIB_PP_FOR_209, STATICLIB_PP_TUPLE_EAT_4)(o(209, s), p, o, m) # define STATICLIB_PP_FOR_209_I(s, p, o, m) STATICLIB_PP_IF(p(210, s), m, STATICLIB_PP_TUPLE_EAT_2)(210, s) STATICLIB_PP_IF(p(210, s), STATICLIB_PP_FOR_210, STATICLIB_PP_TUPLE_EAT_4)(o(210, s), p, o, m) # define STATICLIB_PP_FOR_210_I(s, p, o, m) STATICLIB_PP_IF(p(211, s), m, STATICLIB_PP_TUPLE_EAT_2)(211, s) STATICLIB_PP_IF(p(211, s), STATICLIB_PP_FOR_211, STATICLIB_PP_TUPLE_EAT_4)(o(211, s), p, o, m) # define STATICLIB_PP_FOR_211_I(s, p, o, m) STATICLIB_PP_IF(p(212, s), m, STATICLIB_PP_TUPLE_EAT_2)(212, s) STATICLIB_PP_IF(p(212, s), STATICLIB_PP_FOR_212, STATICLIB_PP_TUPLE_EAT_4)(o(212, s), p, o, m) # define STATICLIB_PP_FOR_212_I(s, p, o, m) STATICLIB_PP_IF(p(213, s), m, STATICLIB_PP_TUPLE_EAT_2)(213, s) STATICLIB_PP_IF(p(213, s), STATICLIB_PP_FOR_213, STATICLIB_PP_TUPLE_EAT_4)(o(213, s), p, o, m) # define STATICLIB_PP_FOR_213_I(s, p, o, m) STATICLIB_PP_IF(p(214, s), m, STATICLIB_PP_TUPLE_EAT_2)(214, s) STATICLIB_PP_IF(p(214, s), STATICLIB_PP_FOR_214, STATICLIB_PP_TUPLE_EAT_4)(o(214, s), p, o, m) # define STATICLIB_PP_FOR_214_I(s, p, o, m) STATICLIB_PP_IF(p(215, s), m, STATICLIB_PP_TUPLE_EAT_2)(215, s) STATICLIB_PP_IF(p(215, s), STATICLIB_PP_FOR_215, STATICLIB_PP_TUPLE_EAT_4)(o(215, s), p, o, m) # define STATICLIB_PP_FOR_215_I(s, p, o, m) STATICLIB_PP_IF(p(216, s), m, STATICLIB_PP_TUPLE_EAT_2)(216, s) STATICLIB_PP_IF(p(216, s), STATICLIB_PP_FOR_216, STATICLIB_PP_TUPLE_EAT_4)(o(216, s), p, o, m) # define STATICLIB_PP_FOR_216_I(s, p, o, m) STATICLIB_PP_IF(p(217, s), m, STATICLIB_PP_TUPLE_EAT_2)(217, s) STATICLIB_PP_IF(p(217, s), STATICLIB_PP_FOR_217, STATICLIB_PP_TUPLE_EAT_4)(o(217, s), p, o, m) # define STATICLIB_PP_FOR_217_I(s, p, o, m) STATICLIB_PP_IF(p(218, s), m, STATICLIB_PP_TUPLE_EAT_2)(218, s) STATICLIB_PP_IF(p(218, s), STATICLIB_PP_FOR_218, STATICLIB_PP_TUPLE_EAT_4)(o(218, s), p, o, m) # define STATICLIB_PP_FOR_218_I(s, p, o, m) STATICLIB_PP_IF(p(219, s), m, STATICLIB_PP_TUPLE_EAT_2)(219, s) STATICLIB_PP_IF(p(219, s), STATICLIB_PP_FOR_219, STATICLIB_PP_TUPLE_EAT_4)(o(219, s), p, o, m) # define STATICLIB_PP_FOR_219_I(s, p, o, m) STATICLIB_PP_IF(p(220, s), m, STATICLIB_PP_TUPLE_EAT_2)(220, s) STATICLIB_PP_IF(p(220, s), STATICLIB_PP_FOR_220, STATICLIB_PP_TUPLE_EAT_4)(o(220, s), p, o, m) # define STATICLIB_PP_FOR_220_I(s, p, o, m) STATICLIB_PP_IF(p(221, s), m, STATICLIB_PP_TUPLE_EAT_2)(221, s) STATICLIB_PP_IF(p(221, s), STATICLIB_PP_FOR_221, STATICLIB_PP_TUPLE_EAT_4)(o(221, s), p, o, m) # define STATICLIB_PP_FOR_221_I(s, p, o, m) STATICLIB_PP_IF(p(222, s), m, STATICLIB_PP_TUPLE_EAT_2)(222, s) STATICLIB_PP_IF(p(222, s), STATICLIB_PP_FOR_222, STATICLIB_PP_TUPLE_EAT_4)(o(222, s), p, o, m) # define STATICLIB_PP_FOR_222_I(s, p, o, m) STATICLIB_PP_IF(p(223, s), m, STATICLIB_PP_TUPLE_EAT_2)(223, s) STATICLIB_PP_IF(p(223, s), STATICLIB_PP_FOR_223, STATICLIB_PP_TUPLE_EAT_4)(o(223, s), p, o, m) # define STATICLIB_PP_FOR_223_I(s, p, o, m) STATICLIB_PP_IF(p(224, s), m, STATICLIB_PP_TUPLE_EAT_2)(224, s) STATICLIB_PP_IF(p(224, s), STATICLIB_PP_FOR_224, STATICLIB_PP_TUPLE_EAT_4)(o(224, s), p, o, m) # define STATICLIB_PP_FOR_224_I(s, p, o, m) STATICLIB_PP_IF(p(225, s), m, STATICLIB_PP_TUPLE_EAT_2)(225, s) STATICLIB_PP_IF(p(225, s), STATICLIB_PP_FOR_225, STATICLIB_PP_TUPLE_EAT_4)(o(225, s), p, o, m) # define STATICLIB_PP_FOR_225_I(s, p, o, m) STATICLIB_PP_IF(p(226, s), m, STATICLIB_PP_TUPLE_EAT_2)(226, s) STATICLIB_PP_IF(p(226, s), STATICLIB_PP_FOR_226, STATICLIB_PP_TUPLE_EAT_4)(o(226, s), p, o, m) # define STATICLIB_PP_FOR_226_I(s, p, o, m) STATICLIB_PP_IF(p(227, s), m, STATICLIB_PP_TUPLE_EAT_2)(227, s) STATICLIB_PP_IF(p(227, s), STATICLIB_PP_FOR_227, STATICLIB_PP_TUPLE_EAT_4)(o(227, s), p, o, m) # define STATICLIB_PP_FOR_227_I(s, p, o, m) STATICLIB_PP_IF(p(228, s), m, STATICLIB_PP_TUPLE_EAT_2)(228, s) STATICLIB_PP_IF(p(228, s), STATICLIB_PP_FOR_228, STATICLIB_PP_TUPLE_EAT_4)(o(228, s), p, o, m) # define STATICLIB_PP_FOR_228_I(s, p, o, m) STATICLIB_PP_IF(p(229, s), m, STATICLIB_PP_TUPLE_EAT_2)(229, s) STATICLIB_PP_IF(p(229, s), STATICLIB_PP_FOR_229, STATICLIB_PP_TUPLE_EAT_4)(o(229, s), p, o, m) # define STATICLIB_PP_FOR_229_I(s, p, o, m) STATICLIB_PP_IF(p(230, s), m, STATICLIB_PP_TUPLE_EAT_2)(230, s) STATICLIB_PP_IF(p(230, s), STATICLIB_PP_FOR_230, STATICLIB_PP_TUPLE_EAT_4)(o(230, s), p, o, m) # define STATICLIB_PP_FOR_230_I(s, p, o, m) STATICLIB_PP_IF(p(231, s), m, STATICLIB_PP_TUPLE_EAT_2)(231, s) STATICLIB_PP_IF(p(231, s), STATICLIB_PP_FOR_231, STATICLIB_PP_TUPLE_EAT_4)(o(231, s), p, o, m) # define STATICLIB_PP_FOR_231_I(s, p, o, m) STATICLIB_PP_IF(p(232, s), m, STATICLIB_PP_TUPLE_EAT_2)(232, s) STATICLIB_PP_IF(p(232, s), STATICLIB_PP_FOR_232, STATICLIB_PP_TUPLE_EAT_4)(o(232, s), p, o, m) # define STATICLIB_PP_FOR_232_I(s, p, o, m) STATICLIB_PP_IF(p(233, s), m, STATICLIB_PP_TUPLE_EAT_2)(233, s) STATICLIB_PP_IF(p(233, s), STATICLIB_PP_FOR_233, STATICLIB_PP_TUPLE_EAT_4)(o(233, s), p, o, m) # define STATICLIB_PP_FOR_233_I(s, p, o, m) STATICLIB_PP_IF(p(234, s), m, STATICLIB_PP_TUPLE_EAT_2)(234, s) STATICLIB_PP_IF(p(234, s), STATICLIB_PP_FOR_234, STATICLIB_PP_TUPLE_EAT_4)(o(234, s), p, o, m) # define STATICLIB_PP_FOR_234_I(s, p, o, m) STATICLIB_PP_IF(p(235, s), m, STATICLIB_PP_TUPLE_EAT_2)(235, s) STATICLIB_PP_IF(p(235, s), STATICLIB_PP_FOR_235, STATICLIB_PP_TUPLE_EAT_4)(o(235, s), p, o, m) # define STATICLIB_PP_FOR_235_I(s, p, o, m) STATICLIB_PP_IF(p(236, s), m, STATICLIB_PP_TUPLE_EAT_2)(236, s) STATICLIB_PP_IF(p(236, s), STATICLIB_PP_FOR_236, STATICLIB_PP_TUPLE_EAT_4)(o(236, s), p, o, m) # define STATICLIB_PP_FOR_236_I(s, p, o, m) STATICLIB_PP_IF(p(237, s), m, STATICLIB_PP_TUPLE_EAT_2)(237, s) STATICLIB_PP_IF(p(237, s), STATICLIB_PP_FOR_237, STATICLIB_PP_TUPLE_EAT_4)(o(237, s), p, o, m) # define STATICLIB_PP_FOR_237_I(s, p, o, m) STATICLIB_PP_IF(p(238, s), m, STATICLIB_PP_TUPLE_EAT_2)(238, s) STATICLIB_PP_IF(p(238, s), STATICLIB_PP_FOR_238, STATICLIB_PP_TUPLE_EAT_4)(o(238, s), p, o, m) # define STATICLIB_PP_FOR_238_I(s, p, o, m) STATICLIB_PP_IF(p(239, s), m, STATICLIB_PP_TUPLE_EAT_2)(239, s) STATICLIB_PP_IF(p(239, s), STATICLIB_PP_FOR_239, STATICLIB_PP_TUPLE_EAT_4)(o(239, s), p, o, m) # define STATICLIB_PP_FOR_239_I(s, p, o, m) STATICLIB_PP_IF(p(240, s), m, STATICLIB_PP_TUPLE_EAT_2)(240, s) STATICLIB_PP_IF(p(240, s), STATICLIB_PP_FOR_240, STATICLIB_PP_TUPLE_EAT_4)(o(240, s), p, o, m) # define STATICLIB_PP_FOR_240_I(s, p, o, m) STATICLIB_PP_IF(p(241, s), m, STATICLIB_PP_TUPLE_EAT_2)(241, s) STATICLIB_PP_IF(p(241, s), STATICLIB_PP_FOR_241, STATICLIB_PP_TUPLE_EAT_4)(o(241, s), p, o, m) # define STATICLIB_PP_FOR_241_I(s, p, o, m) STATICLIB_PP_IF(p(242, s), m, STATICLIB_PP_TUPLE_EAT_2)(242, s) STATICLIB_PP_IF(p(242, s), STATICLIB_PP_FOR_242, STATICLIB_PP_TUPLE_EAT_4)(o(242, s), p, o, m) # define STATICLIB_PP_FOR_242_I(s, p, o, m) STATICLIB_PP_IF(p(243, s), m, STATICLIB_PP_TUPLE_EAT_2)(243, s) STATICLIB_PP_IF(p(243, s), STATICLIB_PP_FOR_243, STATICLIB_PP_TUPLE_EAT_4)(o(243, s), p, o, m) # define STATICLIB_PP_FOR_243_I(s, p, o, m) STATICLIB_PP_IF(p(244, s), m, STATICLIB_PP_TUPLE_EAT_2)(244, s) STATICLIB_PP_IF(p(244, s), STATICLIB_PP_FOR_244, STATICLIB_PP_TUPLE_EAT_4)(o(244, s), p, o, m) # define STATICLIB_PP_FOR_244_I(s, p, o, m) STATICLIB_PP_IF(p(245, s), m, STATICLIB_PP_TUPLE_EAT_2)(245, s) STATICLIB_PP_IF(p(245, s), STATICLIB_PP_FOR_245, STATICLIB_PP_TUPLE_EAT_4)(o(245, s), p, o, m) # define STATICLIB_PP_FOR_245_I(s, p, o, m) STATICLIB_PP_IF(p(246, s), m, STATICLIB_PP_TUPLE_EAT_2)(246, s) STATICLIB_PP_IF(p(246, s), STATICLIB_PP_FOR_246, STATICLIB_PP_TUPLE_EAT_4)(o(246, s), p, o, m) # define STATICLIB_PP_FOR_246_I(s, p, o, m) STATICLIB_PP_IF(p(247, s), m, STATICLIB_PP_TUPLE_EAT_2)(247, s) STATICLIB_PP_IF(p(247, s), STATICLIB_PP_FOR_247, STATICLIB_PP_TUPLE_EAT_4)(o(247, s), p, o, m) # define STATICLIB_PP_FOR_247_I(s, p, o, m) STATICLIB_PP_IF(p(248, s), m, STATICLIB_PP_TUPLE_EAT_2)(248, s) STATICLIB_PP_IF(p(248, s), STATICLIB_PP_FOR_248, STATICLIB_PP_TUPLE_EAT_4)(o(248, s), p, o, m) # define STATICLIB_PP_FOR_248_I(s, p, o, m) STATICLIB_PP_IF(p(249, s), m, STATICLIB_PP_TUPLE_EAT_2)(249, s) STATICLIB_PP_IF(p(249, s), STATICLIB_PP_FOR_249, STATICLIB_PP_TUPLE_EAT_4)(o(249, s), p, o, m) # define STATICLIB_PP_FOR_249_I(s, p, o, m) STATICLIB_PP_IF(p(250, s), m, STATICLIB_PP_TUPLE_EAT_2)(250, s) STATICLIB_PP_IF(p(250, s), STATICLIB_PP_FOR_250, STATICLIB_PP_TUPLE_EAT_4)(o(250, s), p, o, m) # define STATICLIB_PP_FOR_250_I(s, p, o, m) STATICLIB_PP_IF(p(251, s), m, STATICLIB_PP_TUPLE_EAT_2)(251, s) STATICLIB_PP_IF(p(251, s), STATICLIB_PP_FOR_251, STATICLIB_PP_TUPLE_EAT_4)(o(251, s), p, o, m) # define STATICLIB_PP_FOR_251_I(s, p, o, m) STATICLIB_PP_IF(p(252, s), m, STATICLIB_PP_TUPLE_EAT_2)(252, s) STATICLIB_PP_IF(p(252, s), STATICLIB_PP_FOR_252, STATICLIB_PP_TUPLE_EAT_4)(o(252, s), p, o, m) # define STATICLIB_PP_FOR_252_I(s, p, o, m) STATICLIB_PP_IF(p(253, s), m, STATICLIB_PP_TUPLE_EAT_2)(253, s) STATICLIB_PP_IF(p(253, s), STATICLIB_PP_FOR_253, STATICLIB_PP_TUPLE_EAT_4)(o(253, s), p, o, m) # define STATICLIB_PP_FOR_253_I(s, p, o, m) STATICLIB_PP_IF(p(254, s), m, STATICLIB_PP_TUPLE_EAT_2)(254, s) STATICLIB_PP_IF(p(254, s), STATICLIB_PP_FOR_254, STATICLIB_PP_TUPLE_EAT_4)(o(254, s), p, o, m) # define STATICLIB_PP_FOR_254_I(s, p, o, m) STATICLIB_PP_IF(p(255, s), m, STATICLIB_PP_TUPLE_EAT_2)(255, s) STATICLIB_PP_IF(p(255, s), STATICLIB_PP_FOR_255, STATICLIB_PP_TUPLE_EAT_4)(o(255, s), p, o, m) # define STATICLIB_PP_FOR_255_I(s, p, o, m) STATICLIB_PP_IF(p(256, s), m, STATICLIB_PP_TUPLE_EAT_2)(256, s) STATICLIB_PP_IF(p(256, s), STATICLIB_PP_FOR_256, STATICLIB_PP_TUPLE_EAT_4)(o(256, s), p, o, m) # define STATICLIB_PP_FOR_256_I(s, p, o, m) STATICLIB_PP_IF(p(257, s), m, STATICLIB_PP_TUPLE_EAT_2)(257, s) STATICLIB_PP_IF(p(257, s), STATICLIB_PP_FOR_257, STATICLIB_PP_TUPLE_EAT_4)(o(257, s), p, o, m) # # endif
133.53271
202
0.743267
staticlibs
4b4cc822be6cd5ec573f35b679b28f0803ea7072
3,553
cpp
C++
branch/old_angsys/angsys_beta1/angsys_android/source/angsys/angsys.shared/source/xml/xml_element.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
branch/old_angsys/angsys_beta1/angsys_android/source/angsys/angsys.shared/source/xml/xml_element.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
branch/old_angsys/angsys_beta1/angsys_android/source/angsys/angsys.shared/source/xml/xml_element.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
/*********************************************************************************************************************/ /* File Name: xml_element.cpp */ /* Author: Ing. Jesus Rocha <chuyangel.rm@gmail.com>, July 2016. */ /* Copyright (C) angsys, Jesus Angel Rocha Morales */ /* You may opt to use, copy, modify, merge, publish and/or distribute copies of the Software, and permit persons */ /* to whom the Software is furnished to do so. */ /* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. */ /* */ /*********************************************************************************************************************/ #include "pch.h" #include "ang/xml.h" #if defined _DEBUG #define NEW ANG_DEBUG_NEW() #define NEW_ARGS(...) new(__VA_ARGS__, __FILE__, __LINE__) #else #define NEW new #define NEW_ARGS(...) new(__VA_ARGS__) #endif using namespace ang; using namespace ang::xml; xml_element::xml_element() : xml_node(xml_type_t::element) { } xml_element::xml_element(mstring name, mstring value) : xml_node(xml_type_t::element) { xml_name(ang::move(name)); xml_value(ang::move(value)); } xml_element::xml_element(mstring name, xml_items_t items) : xml_node(xml_type_t::element) { xml_name(ang::move(name)); if(!items.is_empty() && items->xml_is_type_of(xml_type_t::element_list)) xml_children(ang::move(items)); if (!items.is_empty() && items->xml_is_type_of(xml_type_t::attribute_list)) xml_attributes(ang::move(items)); } xml_element::xml_element(const xml_element& att) : xml_node(xml_type_t::element) { if (!att._xml_name.is_empty()) xml_name(att._xml_name); if (att._xml_content.data_type == xml_type_t::value) xml_value(mstring(static_cast<strings::mstring_buffer*>(att._xml_content.unknown.get()))); else if (att._xml_content.data_type == xml_type_t::element_list) xml_children(static_cast<xml_element_list*>(att._xml_content.unknown.get())->xml_clone()); if (att.xml_has_attributes()) xml_attributes(att._xml_attributes->xml_clone()); } xml_element::xml_element(const xml_element* att) : xml_node(xml_type_t::element) { if (att) { if (!att->_xml_name.is_empty()) xml_name(att->_xml_name); if (att->_xml_content.data_type == xml_type_t::value) xml_value(mstring(static_cast<strings::mstring_buffer*>(att->_xml_content.unknown.get()))); else if (att->_xml_content.data_type == xml_type_t::element_list) xml_children(static_cast<xml_element_list*>(att->_xml_content.unknown.get())->xml_clone()); if (att->xml_has_attributes()) xml_attributes(att->_xml_attributes->xml_clone()); } } xml_element::~xml_element() { } ANG_IMPLEMENT_BASIC_INTERFACE(ang::xml::xml_element, xml_node); bool xml_element::xml_has_name()const { return !_xml_name.is_empty(); } bool xml_element::xml_has_value()const { return _xml_content.data_type == xml_type_t::value; } bool xml_element::xml_has_children()const { return _xml_content.data_type == xml_type_t::element_list; } bool xml_element::xml_has_attributes()const { return !_xml_attributes.is_empty(); } xml_node_t xml_element::xml_clone()const { return new xml_element(this); }
32.009009
124
0.607937
ChuyX3
4b52441f2280f91d325afc5e7a6fc73c0a008256
3,588
cpp
C++
aws-cpp-sdk-email/source/model/BounceType.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-email/source/model/BounceType.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-email/source/model/BounceType.cpp
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/email/model/BounceType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace SES { namespace Model { namespace BounceTypeMapper { static const int DoesNotExist_HASH = HashingUtils::HashString("DoesNotExist"); static const int MessageTooLarge_HASH = HashingUtils::HashString("MessageTooLarge"); static const int ExceededQuota_HASH = HashingUtils::HashString("ExceededQuota"); static const int ContentRejected_HASH = HashingUtils::HashString("ContentRejected"); static const int Undefined_HASH = HashingUtils::HashString("Undefined"); static const int TemporaryFailure_HASH = HashingUtils::HashString("TemporaryFailure"); BounceType GetBounceTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == DoesNotExist_HASH) { return BounceType::DoesNotExist; } else if (hashCode == MessageTooLarge_HASH) { return BounceType::MessageTooLarge; } else if (hashCode == ExceededQuota_HASH) { return BounceType::ExceededQuota; } else if (hashCode == ContentRejected_HASH) { return BounceType::ContentRejected; } else if (hashCode == Undefined_HASH) { return BounceType::Undefined; } else if (hashCode == TemporaryFailure_HASH) { return BounceType::TemporaryFailure; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<BounceType>(hashCode); } return BounceType::NOT_SET; } Aws::String GetNameForBounceType(BounceType enumValue) { switch(enumValue) { case BounceType::DoesNotExist: return "DoesNotExist"; case BounceType::MessageTooLarge: return "MessageTooLarge"; case BounceType::ExceededQuota: return "ExceededQuota"; case BounceType::ContentRejected: return "ContentRejected"; case BounceType::Undefined: return "Undefined"; case BounceType::TemporaryFailure: return "TemporaryFailure"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return ""; } } } // namespace BounceTypeMapper } // namespace Model } // namespace SES } // namespace Aws
33.222222
94
0.63155
ambasta
4b52aef3e4d512e34d4542bbaa0a89a472d31c52
3,589
hpp
C++
Geometry/Point.hpp
7bnx/Embedded
afb83151500b27066b571336c32aaddd9fa97fd7
[ "MIT" ]
null
null
null
Geometry/Point.hpp
7bnx/Embedded
afb83151500b27066b571336c32aaddd9fa97fd7
[ "MIT" ]
null
null
null
Geometry/Point.hpp
7bnx/Embedded
afb83151500b27066b571336c32aaddd9fa97fd7
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------------- // Author: Semyon Ivanov // e-mail: agreement90@mail.ru // github: https://github.com/7bnx/Embedded // Description: Point structures // TODO: //---------------------------------------------------------------------------------- #ifndef _POINT_HPP #define _POINT_HPP #include <cstddef> #include <array> #include "Compiler.h" /*! @brief Namespace for geometry */ namespace geometry{ /*! @brief Multi-dimensional point @tparam <T> point's type @tparam <Dimensions> number of dimensions */ template<typename T, size_t Dimensions> struct Point{ /*! @brief Array with values of dimesions */ std::array<T, Dimensions> values; /*! @brief Constructor @param [in] args values of dimensions */ template <typename ... Args> Point(const Args& ... args): values{ args... }{} /*! @brief Set all dimensions to 0 */ __FORCE_INLINE void Reset(){ for(auto v : values) v = 0; } /*! @brief Number of point's dimensions */ const size_t size = Dimensions; }; /*! @brief Two-dimensional point @tparam <T> point's type */ template<typename T> struct Point2D: public Point<T, 2>{ using base = Point<T, 2>; /*! @brief Constructor @param [in] x value of X-dimension @param [in] y value of Y-dimension */ Point2D(const T& x = 0, const T& y = 0): base(x, y) { } /*! @brief Set values of x- and y- dimensions @param [in] x value of X-dimension @param [in] y value of Y-dimension */ __FORCE_INLINE void Set(const T & x = 0, const T & y = 0){ base::values[0] = x; base::values[1] = y; } /*! @brief Set value of X-dimensions */ __FORCE_INLINE void SetX(const T & x = 0){ base::values[0] = x; } /*! @brief Set value of Y-dimensions */ __FORCE_INLINE void SetY(const T & y = 0){ base::values[1] = y; } /*! @brief Get value of X-dimensions */ __FORCE_INLINE const auto & GetX() const{ return base::values[0]; } /*! @brief Get value of Y-dimensions */ __FORCE_INLINE const auto & GetY() const{ return base::values[1]; } }; template<typename T> struct Point3D: public Point<T, 3>{ using base = Point<T, 3>; /*! @brief Set values of x-, y- and z- dimensions @param [in] x value of X-dimension @param [in] y value of Y-dimension @param [in] y value of Z-dimension */ Point3D(const T& x = 0, const T& y = 0, const T& z = 0) : base(x, y, z) { } /*! @brief Constructor @param [in] x value of X-dimension @param [in] y value of Y-dimension @param [in] y value of Z-dimension */ __FORCE_INLINE void Set(const T & x = 0, const T & y = 0, const T & z = 0){ base::values[0] = x; base::values[1] = y; base::values[2] = z; } /*! @brief Set value of X-dimensions */ __FORCE_INLINE void SetX(const T & x = 0){ base::values[0] = x; } /*! @brief Set value of Y-dimensions */ __FORCE_INLINE void SetY(const T & y = 0){ base::values[1] = y; } /*! @brief Set value of Z-dimensions */ __FORCE_INLINE void SetZ(const T & z = 0){ base::values[2] = z; } /*! @brief Get value of X-dimensions */ __FORCE_INLINE const auto & GetX() const{ return base::values[0]; } /*! @brief Get value of Y-dimensions */ __FORCE_INLINE const auto & GetY() const{ return base::values[1]; } /*! @brief Get value of Z-dimensions */ __FORCE_INLINE const auto & GetZ() const{ return base::values[2]; } }; } // !namespace geometry #endif // !_POINT_HPP
22.71519
84
0.575369
7bnx
4b56be2d124039934eb73ce3f39e9ae8a03a916a
2,415
cpp
C++
WLMatrix/src/wlmatrix/api/soap/handlers/auth/RST2Handler.cpp
aeoncl/wlmatrix
da936eaec37f06f0e379c6009962dc69bfe07eb3
[ "MIT" ]
null
null
null
WLMatrix/src/wlmatrix/api/soap/handlers/auth/RST2Handler.cpp
aeoncl/wlmatrix
da936eaec37f06f0e379c6009962dc69bfe07eb3
[ "MIT" ]
null
null
null
WLMatrix/src/wlmatrix/api/soap/handlers/auth/RST2Handler.cpp
aeoncl/wlmatrix
da936eaec37f06f0e379c6009962dc69bfe07eb3
[ "MIT" ]
null
null
null
#pragma once #include "RST2Handler.h" #include "AuthResponse.h" #include "MatrixBackend.h" #include <iostream> #include "MatrixRestServiceException.h" #include "AbstractSoapEndpointHandler.h" #include "RST2Response.h" #include "RST2TokenFactory.h" #include "UUID.h" #include "DateTime.h" #include "RST2Request.h" #include "WLMatrixLogin.h" #include "StringUtils.h" #include "MacAddressUtils.h" #include "Date.h" using namespace wlmatrix; RST2Handler::RST2Handler() : AbstractSoapEndpointHandler("/RST2.srf", ""){}; MatrixCredentials RST2Handler::getMatrixCredentials(std::string msnLogin, std::string password) { WLMatrixLogin wlmatrixLogin(msnLogin); MatrixCredentials credentials(StringUtils::convertToWString(wlmatrixLogin.getUsername()), StringUtils::convertToWString(password), L"WLMatrix", StringUtils::convertToWString(wlmatrixLogin.getTargetUrl())); auto deviceMacAddr = MacAddressUtils::getMacAddress(); if (deviceMacAddr.has_value()) { std::string deviceId = UUID::generateFromString("wlmatrix" + deviceMacAddr.value()).toString(); credentials.setDeviceId(StringUtils::convertToWString(deviceId)); } return credentials; }; SoapResponse RST2Handler::handleRequest(std::string requesBodyXML) { std::cout << "Request - RST2 : " << requesBodyXML << std::endl; RST2Request requestBody(requesBodyXML); MatrixCredentials creds = this->getMatrixCredentials(requestBody.getUsername(), requestBody.getPassword()); MatrixBackend matrix; try { AuthResponse matrixResponse = matrix.authenticate(creds); auto& tokenFactory = RST2TokenFactory::getInstance(); auto tokens = tokenFactory.getDefaultRST2Tokens(matrixResponse.getAccessToken(), Date::now().toString(), Date::now().plusDays(1).toString()); UUID uuid = UUID::generateFromString(matrixResponse.getUserId()); auto cid = uuid.toHexString(); auto puid = uuid.getLeastSignificantBytesAsHexStr(); RST2Response responseBody(tokens, cid, puid, requestBody.getUsername(), Date::now().toString(), DateTime::now(), Date::now().plusDays(1).toString(), "John", "Doe"); auto xmlPayload = responseBody.serializeXML(); std::cout << "Response - RST2 : " << xmlPayload << std::endl; return SoapResponse(xmlPayload, 200); } catch (MatrixRestServiceException &e) { return SoapResponse("", 500); } };
38.333333
209
0.721325
aeoncl
4b5a7ef857f01118558a6edfdd717beffc318411
8,895
cpp
C++
build/px4_sitl_default/msg/topics_sources/ulog_stream.cpp
amilearning/PX4-Autopilot
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
[ "BSD-3-Clause" ]
null
null
null
build/px4_sitl_default/msg/topics_sources/ulog_stream.cpp
amilearning/PX4-Autopilot
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
[ "BSD-3-Clause" ]
null
null
null
build/px4_sitl_default/msg/topics_sources/ulog_stream.cpp
amilearning/PX4-Autopilot
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * * Copyright (C) 2013-2016 PX4 Development Team. All rights reserved. * * 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 PX4 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 OWNER 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. * ****************************************************************************/ /* Auto-generated by genmsg_cpp from file /home/hojin/PX4-Autopilot/msg/ulog_stream.msg */ #include <inttypes.h> #include <px4_platform_common/log.h> #include <px4_platform_common/defines.h> #include <uORB/topics/ulog_stream.h> #include <uORB/topics/uORBTopics.hpp> #include <drivers/drv_hrt.h> #include <lib/drivers/device/Device.hpp> #include <lib/matrix/matrix/math.hpp> #include <lib/mathlib/mathlib.h> constexpr char __orb_ulog_stream_fields[] = "uint64_t timestamp;uint16_t msg_sequence;uint8_t length;uint8_t first_message_offset;uint8_t flags;uint8_t[249] data;uint8_t[2] _padding0;"; ORB_DEFINE(ulog_stream, struct ulog_stream_s, 262, __orb_ulog_stream_fields, static_cast<uint8_t>(ORB_ID::ulog_stream)); void print_message(const ulog_stream_s &message) { PX4_INFO_RAW(" ulog_stream_s\n"); const hrt_abstime now = hrt_absolute_time(); if (message.timestamp != 0) { PX4_INFO_RAW("\ttimestamp: %" PRIu64 " (%.6f seconds ago)\n", message.timestamp, (now - message.timestamp) / 1e6); } else { PX4_INFO_RAW("\n"); } PX4_INFO_RAW("\tmsg_sequence: %u\n", message.msg_sequence); PX4_INFO_RAW("\tlength: %u\n", message.length); PX4_INFO_RAW("\tfirst_message_offset: %u\n", message.first_message_offset); PX4_INFO_RAW("\tflags: %u (0b", message.flags); for (int i = (sizeof(message.flags) * 8) - 1; i >= 0; i--) { PX4_INFO_RAW("%lu%s", (unsigned long) message.flags >> i & 1, ((unsigned)i < (sizeof(message.flags) * 8) - 1 && i % 4 == 0 && i > 0) ? "'" : ""); } PX4_INFO_RAW(")\n"); PX4_INFO_RAW("\tdata: [%u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u]\n", message.data[0], message.data[1], message.data[2], message.data[3], message.data[4], message.data[5], message.data[6], message.data[7], message.data[8], message.data[9], message.data[10], message.data[11], message.data[12], message.data[13], message.data[14], message.data[15], message.data[16], message.data[17], message.data[18], message.data[19], message.data[20], message.data[21], message.data[22], message.data[23], message.data[24], message.data[25], message.data[26], message.data[27], message.data[28], message.data[29], message.data[30], message.data[31], message.data[32], message.data[33], message.data[34], message.data[35], message.data[36], message.data[37], message.data[38], message.data[39], message.data[40], message.data[41], message.data[42], message.data[43], message.data[44], message.data[45], message.data[46], message.data[47], message.data[48], message.data[49], message.data[50], message.data[51], message.data[52], message.data[53], message.data[54], message.data[55], message.data[56], message.data[57], message.data[58], message.data[59], message.data[60], message.data[61], message.data[62], message.data[63], message.data[64], message.data[65], message.data[66], message.data[67], message.data[68], message.data[69], message.data[70], message.data[71], message.data[72], message.data[73], message.data[74], message.data[75], message.data[76], message.data[77], message.data[78], message.data[79], message.data[80], message.data[81], message.data[82], message.data[83], message.data[84], message.data[85], message.data[86], message.data[87], message.data[88], message.data[89], message.data[90], message.data[91], message.data[92], message.data[93], message.data[94], message.data[95], message.data[96], message.data[97], message.data[98], message.data[99], message.data[100], message.data[101], message.data[102], message.data[103], message.data[104], message.data[105], message.data[106], message.data[107], message.data[108], message.data[109], message.data[110], message.data[111], message.data[112], message.data[113], message.data[114], message.data[115], message.data[116], message.data[117], message.data[118], message.data[119], message.data[120], message.data[121], message.data[122], message.data[123], message.data[124], message.data[125], message.data[126], message.data[127], message.data[128], message.data[129], message.data[130], message.data[131], message.data[132], message.data[133], message.data[134], message.data[135], message.data[136], message.data[137], message.data[138], message.data[139], message.data[140], message.data[141], message.data[142], message.data[143], message.data[144], message.data[145], message.data[146], message.data[147], message.data[148], message.data[149], message.data[150], message.data[151], message.data[152], message.data[153], message.data[154], message.data[155], message.data[156], message.data[157], message.data[158], message.data[159], message.data[160], message.data[161], message.data[162], message.data[163], message.data[164], message.data[165], message.data[166], message.data[167], message.data[168], message.data[169], message.data[170], message.data[171], message.data[172], message.data[173], message.data[174], message.data[175], message.data[176], message.data[177], message.data[178], message.data[179], message.data[180], message.data[181], message.data[182], message.data[183], message.data[184], message.data[185], message.data[186], message.data[187], message.data[188], message.data[189], message.data[190], message.data[191], message.data[192], message.data[193], message.data[194], message.data[195], message.data[196], message.data[197], message.data[198], message.data[199], message.data[200], message.data[201], message.data[202], message.data[203], message.data[204], message.data[205], message.data[206], message.data[207], message.data[208], message.data[209], message.data[210], message.data[211], message.data[212], message.data[213], message.data[214], message.data[215], message.data[216], message.data[217], message.data[218], message.data[219], message.data[220], message.data[221], message.data[222], message.data[223], message.data[224], message.data[225], message.data[226], message.data[227], message.data[228], message.data[229], message.data[230], message.data[231], message.data[232], message.data[233], message.data[234], message.data[235], message.data[236], message.data[237], message.data[238], message.data[239], message.data[240], message.data[241], message.data[242], message.data[243], message.data[244], message.data[245], message.data[246], message.data[247], message.data[248]); }
121.849315
5,645
0.667454
amilearning
4b5c63fe2fdbe744c951d392bfc09e1b5c739316
1,569
cpp
C++
test_suite/src/error_recovery_tests.cpp
avacore/jsoncons
0fa3104b6237b3323a749c38ebeaaaebf55e9e48
[ "BSL-1.0" ]
null
null
null
test_suite/src/error_recovery_tests.cpp
avacore/jsoncons
0fa3104b6237b3323a749c38ebeaaaebf55e9e48
[ "BSL-1.0" ]
null
null
null
test_suite/src/error_recovery_tests.cpp
avacore/jsoncons
0fa3104b6237b3323a749c38ebeaaaebf55e9e48
[ "BSL-1.0" ]
null
null
null
// Copyright 2013 Daniel Parker // Distributed under Boost license #include <boost/test/unit_test.hpp> #include "jsoncons/json.hpp" #include "jsoncons/json_serializer.hpp" #include "jsoncons/json_reader.hpp" #include <sstream> #include <vector> #include <utility> #include <ctime> using jsoncons::parsing_context; using jsoncons::json_deserializer; using jsoncons::json; using jsoncons::wjson; using jsoncons::json_reader; using jsoncons::json_input_handler; using jsoncons::parse_error_handler; using jsoncons::json_parse_exception; using jsoncons::json_parser_category; using jsoncons::parse_error_handler; using jsoncons::default_parse_error_handler; using std::string; class my_parse_error_handler : public parse_error_handler { private: virtual void do_warning(std::error_code ec, const parsing_context& context) throw(json_parse_exception) { } virtual void do_error(std::error_code ec, const parsing_context& context) throw(json_parse_exception) { if (ec.category() == json_parser_category()) { if (ec.value() != jsoncons::json_parser_errc::unexpected_value_separator && (context.last_char() == ']' || context.last_char() == '}')) { default_parse_error_handler::instance().error(ec,context); } } } }; BOOST_AUTO_TEST_CASE(test_accept_trailing_value_separator) { my_parse_error_handler err_handler; json val = json::parse_string("[1,2,3,]", err_handler); std::cout << val << std::endl; }
27.051724
147
0.699809
avacore
4b5c9706d26f960c1494e18184a2baf766faf03b
2,412
hpp
C++
IGC/common/debug/TeeOutputStream.hpp
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
IGC/common/debug/TeeOutputStream.hpp
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
IGC/common/debug/TeeOutputStream.hpp
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
/*========================== begin_copyright_notice ============================ Copyright (c) 2000-2021 Intel Corporation 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. ============================= end_copyright_notice ===========================*/ #pragma once #include "common/LLVMWarningsPush.hpp" #include <llvm/Support/raw_ostream.h> #include "common/LLVMWarningsPop.hpp" namespace IGC { namespace Debug { class TeeOutputStream : public llvm::raw_ostream { public: TeeOutputStream( llvm::raw_ostream& s0, llvm::raw_ostream& s1); TeeOutputStream( llvm::raw_ostream* pLHS, bool shouldDeleteLHS, llvm::raw_ostream* pRHS, bool shouldDeleteRHS); ~TeeOutputStream(); size_t preferred_buffer_size() const override; llvm::raw_ostream &changeColor(enum llvm::raw_ostream::Colors colors, bool bold, bool bg) override; llvm::raw_ostream &resetColor() override; llvm::raw_ostream &reverseColor() override; private: void write_impl(const char *Ptr, size_t Size) override; uint64_t current_pos() const override; private: llvm::raw_ostream* const m_LHS; llvm::raw_ostream* const m_RHS; bool const m_deleteLHS; bool const m_deleteRHS; }; } // namespace Debug } // namespace IGC
33.5
107
0.674129
bader
4b5ecaa6c3bf46afb4bf7bee5f0f94aba0637f22
6,419
cpp
C++
UnitTests/Sweep.cpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
32
2016-10-20T05:55:04.000Z
2021-11-25T16:34:41.000Z
UnitTests/Sweep.cpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
50
2017-01-07T21:40:16.000Z
2018-01-31T10:04:05.000Z
UnitTests/Sweep.cpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
7
2017-02-09T10:02:02.000Z
2020-07-23T22:49:04.000Z
/* * Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/Box2D * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors 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 software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * 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 software. * 3. This notice may not be removed or altered from any source distribution. */ #include "gtest/gtest.h" #include <Box2D/Common/Math.hpp> using namespace box2d; TEST(Sweep, ByteSizeIs_36_or_72) { switch (sizeof(Real)) { case 4: EXPECT_EQ(sizeof(Sweep), std::size_t(36)); break; case 8: EXPECT_EQ(sizeof(Sweep), std::size_t(72)); break; case 16: EXPECT_EQ(sizeof(Sweep), std::size_t(144)); break; default: FAIL(); break; } } TEST(Sweep, ConstructorSetsPos0and1) { const auto pos = Position{Length2D{Real(-0.4) * Meter, Real(2.34) * Meter}, Real{3.14f} * Radian}; Sweep sweep{pos}; EXPECT_EQ(pos, sweep.pos0); EXPECT_EQ(pos, sweep.pos1); } TEST(Sweep, ResetSetsAlpha0to0) { const auto pos = Position{Length2D{Real(-0.4) * Meter, Real(2.34) * Meter}, Real{3.14f} * Radian}; Sweep sweep{pos, pos, Length2D(0, 0), Real(0.6)}; EXPECT_NE(Real{0}, sweep.GetAlpha0()); sweep.ResetAlpha0(); EXPECT_EQ(Real{0}, sweep.GetAlpha0()); } TEST(Sweep, GetPosition) { const auto pos0 = Position{Length2D{Real(-0.4) * Meter, Real(+2.34) * Meter}, Real{3.14f} * Radian}; const auto pos1 = Position{Length2D{Real(+0.4) * Meter, Real(-2.34) * Meter}, -Real{3.14f} * Radian}; Sweep sweep{pos0, pos1, Length2D(0, 0), Real(0.6)}; EXPECT_EQ(pos0, GetPosition(sweep.pos0, sweep.pos1, 0)); EXPECT_EQ(pos1, GetPosition(sweep.pos0, sweep.pos1, 1)); } TEST(Sweep, Advance) { const auto pos0 = Position{Length2D{Real(-0.4) * Meter, Real(+2.34) * Meter}, Real{3.14f} * Radian}; const auto pos1 = Position{Length2D{Real(+0.4) * Meter, Real(-2.34) * Meter}, -Real{3.14f} * Radian}; Sweep sweep{pos0, pos1, Length2D(0, 0), 0}; EXPECT_EQ(Real{0}, sweep.GetAlpha0()); sweep.Advance0(0); EXPECT_EQ(Real{0}, sweep.GetAlpha0()); EXPECT_EQ(pos0, sweep.pos0); EXPECT_EQ(pos1, sweep.pos1); sweep.Advance0(Real{1}/Real{2}); EXPECT_EQ(Real{1}/Real{2}, sweep.GetAlpha0()); EXPECT_EQ(pos1, sweep.pos1); EXPECT_EQ((Position{Length2D(0, 0), Angle{0}}), sweep.pos0); sweep.Advance0(0); EXPECT_EQ(Real{0}, sweep.GetAlpha0()); EXPECT_EQ(pos0, sweep.pos0); EXPECT_EQ(pos1, sweep.pos1); } TEST(Sweep, GetAnglesNormalized) { const auto sweep0 = Sweep{ Position{Length2D(0, 0), Angle{0}}, Position{Length2D(0, 0), Angle{0}} }; EXPECT_EQ(GetAnglesNormalized(sweep0).pos0.angular, Angle{0}); EXPECT_EQ(GetAnglesNormalized(sweep0).pos1.angular, Angle{0}); const auto sweep1 = Sweep{ Position{Length2D(0, 0), Angle{Real{90.0f} * Degree}}, Position{Length2D(0, 0), Angle{Real{90.0f} * Degree}} }; EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep1).pos0.angular / Angle{Real(1) * Degree}}), double( 90), 0.03); EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep1).pos1.angular / Angle{Real(1) * Degree}}), double( 90), 0.03); const auto sweep2 = Sweep{ Position{Length2D(0, 0), Angle{Real{180.0f} * Degree}}, Position{Length2D(0, 0), Angle{Real{180.0f} * Degree}} }; EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep2).pos0.angular / Angle{Real(1) * Degree}}), double(180), 0.03); EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep2).pos1.angular / Angle{Real(1) * Degree}}), double(180), 0.03); const auto sweep3 = Sweep{ Position{Length2D(0, 0), Angle{Real{270.0f} * Degree}}, Position{Length2D(0, 0), Angle{Real{270.0f} * Degree}} }; EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep3).pos0.angular / Angle{Real(1) * Degree}}), double(270), 0.03); EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep3).pos1.angular / Angle{Real(1) * Degree}}), double(270), 0.03); const auto sweep4 = Sweep{ Position{Length2D(0, 0), Angle{Real{361.0f} * Degree}}, Position{Length2D(0, 0), Angle{Real{361.0f} * Degree}} }; EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep4).pos0.angular / Angle{Real(1) * Degree}}), double(1), 0.001); EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep4).pos1.angular / Angle{Real(1) * Degree}}), double(1), 0.001); const auto sweep5 = Sweep{ Position{Length2D(0, 0), Angle{Real{722.0f} * Degree}}, Position{Length2D(0, 0), Angle{Real{722.0f} * Degree}} }; EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep5).pos0.angular / Angle{Real(1) * Degree}}), double(2), 0.002); EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep5).pos1.angular / Angle{Real(1) * Degree}}), double(2), 0.002); const auto sweep6 = Sweep{ Position{Length2D(0, 0), Angle{Real{726.0f} * Degree}}, Position{Length2D(0, 0), Angle{Real{90.0f} * Degree}} }; EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep6).pos0.angular / Angle{Real(1) * Degree}}), double(6), 0.03); EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep6).pos1.angular / Angle{Real(1) * Degree}}), double(-630), 0.03); const auto sweep7 = Sweep{ Position{Length2D(0, 0), Angle{-Real{90.0f} * Degree}}, Position{Length2D(0, 0), Angle{-Real{90.0f} * Degree}} }; EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep7).pos0.angular / Angle{Real(1) * Degree}}), double( -90), 0.03); EXPECT_NEAR(double(Real{GetAnglesNormalized(sweep7).pos1.angular / Angle{Real(1) * Degree}}), double( -90), 0.03); }
41.954248
105
0.642156
louis-langholtz
4b5fc0774a6d2312d9c2ff17683c21d82ec18016
46,964
cpp
C++
lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp
AlexisPerry/kitsune-1
29c278e74f167613b8413b3c23277cdc13a656d7
[ "MIT" ]
3
2021-08-04T02:54:47.000Z
2021-11-06T08:30:00.000Z
lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp
AlexisPerry/kitsune-1
29c278e74f167613b8413b3c23277cdc13a656d7
[ "MIT" ]
2
2022-02-19T07:12:22.000Z
2022-02-27T11:21:53.000Z
llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp
ananthdurbha/llvm-mlir
a5e0b8903b83c777fa40a0fa538fbdb8176fd5ac
[ "MIT" ]
1
2022-03-31T12:52:01.000Z
2022-03-31T12:52:01.000Z
//===-- GDBRemoteCommunicationServerCommon.cpp ------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "GDBRemoteCommunicationServerCommon.h" #include <errno.h> #ifdef __APPLE__ #include <TargetConditionals.h> #endif #include <chrono> #include <cstring> #include "lldb/Core/ModuleSpec.h" #include "lldb/Host/Config.h" #include "lldb/Host/File.h" #include "lldb/Host/FileAction.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Host/SafeMachO.h" #include "lldb/Interpreter/OptionArgParser.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Platform.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/GDBRemote.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/StructuredData.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/JSON.h" #include "ProcessGDBRemoteLog.h" #include "lldb/Utility/StringExtractorGDBRemote.h" #ifdef __ANDROID__ #include "lldb/Host/android/HostInfoAndroid.h" #endif using namespace lldb; using namespace lldb_private::process_gdb_remote; using namespace lldb_private; #ifdef __ANDROID__ const static uint32_t g_default_packet_timeout_sec = 20; // seconds #else const static uint32_t g_default_packet_timeout_sec = 0; // not specified #endif // GDBRemoteCommunicationServerCommon constructor GDBRemoteCommunicationServerCommon::GDBRemoteCommunicationServerCommon( const char *comm_name, const char *listener_name) : GDBRemoteCommunicationServer(comm_name, listener_name), m_process_launch_info(), m_process_launch_error(), m_proc_infos(), m_proc_infos_index(0), m_thread_suffix_supported(false), m_list_threads_in_stop_reply(false) { RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_A, &GDBRemoteCommunicationServerCommon::Handle_A); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QEnvironment, &GDBRemoteCommunicationServerCommon::Handle_QEnvironment); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QEnvironmentHexEncoded, &GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qfProcessInfo, &GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qGroupName, &GDBRemoteCommunicationServerCommon::Handle_qGroupName); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qHostInfo, &GDBRemoteCommunicationServerCommon::Handle_qHostInfo); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QLaunchArch, &GDBRemoteCommunicationServerCommon::Handle_QLaunchArch); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess, &GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply, &GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qEcho, &GDBRemoteCommunicationServerCommon::Handle_qEcho); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qModuleInfo, &GDBRemoteCommunicationServerCommon::Handle_qModuleInfo); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_jModulesInfo, &GDBRemoteCommunicationServerCommon::Handle_jModulesInfo); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod, &GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir, &GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qPlatform_shell, &GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID, &GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError, &GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QSetSTDERR, &GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QSetSTDIN, &GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT, &GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qSpeedTest, &GDBRemoteCommunicationServerCommon::Handle_qSpeedTest); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qsProcessInfo, &GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode, &GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qSupported, &GDBRemoteCommunicationServerCommon::Handle_qSupported); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported, &GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_qUserName, &GDBRemoteCommunicationServerCommon::Handle_qUserName); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_close, &GDBRemoteCommunicationServerCommon::Handle_vFile_Close); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_exists, &GDBRemoteCommunicationServerCommon::Handle_vFile_Exists); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_md5, &GDBRemoteCommunicationServerCommon::Handle_vFile_MD5); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_mode, &GDBRemoteCommunicationServerCommon::Handle_vFile_Mode); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_open, &GDBRemoteCommunicationServerCommon::Handle_vFile_Open); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_pread, &GDBRemoteCommunicationServerCommon::Handle_vFile_pRead); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_pwrite, &GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_size, &GDBRemoteCommunicationServerCommon::Handle_vFile_Size); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_stat, &GDBRemoteCommunicationServerCommon::Handle_vFile_Stat); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_symlink, &GDBRemoteCommunicationServerCommon::Handle_vFile_symlink); RegisterMemberFunctionHandler( StringExtractorGDBRemote::eServerPacketType_vFile_unlink, &GDBRemoteCommunicationServerCommon::Handle_vFile_unlink); } // Destructor GDBRemoteCommunicationServerCommon::~GDBRemoteCommunicationServerCommon() {} GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qHostInfo( StringExtractorGDBRemote &packet) { StreamString response; // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00 ArchSpec host_arch(HostInfo::GetArchitecture()); const llvm::Triple &host_triple = host_arch.GetTriple(); response.PutCString("triple:"); response.PutStringAsRawHex8(host_triple.getTriple()); response.Printf(";ptrsize:%u;", host_arch.GetAddressByteSize()); const char *distribution_id = host_arch.GetDistributionId().AsCString(); if (distribution_id) { response.PutCString("distribution_id:"); response.PutStringAsRawHex8(distribution_id); response.PutCString(";"); } #if defined(__APPLE__) // For parity with debugserver, we'll include the vendor key. response.PutCString("vendor:apple;"); // Send out MachO info. uint32_t cpu = host_arch.GetMachOCPUType(); uint32_t sub = host_arch.GetMachOCPUSubType(); if (cpu != LLDB_INVALID_CPUTYPE) response.Printf("cputype:%u;", cpu); if (sub != LLDB_INVALID_CPUTYPE) response.Printf("cpusubtype:%u;", sub); if (cpu == llvm::MachO::CPU_TYPE_ARM || cpu == llvm::MachO::CPU_TYPE_ARM64) { // Indicate the OS type. #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1 response.PutCString("ostype:tvos;"); #elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1 response.PutCString("ostype:watchos;"); #elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1 response.PutCString("ostype:bridgeos;"); #else response.PutCString("ostype:ios;"); #endif // On arm, we use "synchronous" watchpoints which means the exception is // delivered before the instruction executes. response.PutCString("watchpoint_exceptions_received:before;"); } else { response.PutCString("ostype:macosx;"); response.Printf("watchpoint_exceptions_received:after;"); } #else if (host_arch.GetMachine() == llvm::Triple::aarch64 || host_arch.GetMachine() == llvm::Triple::aarch64_32 || host_arch.GetMachine() == llvm::Triple::aarch64_be || host_arch.GetMachine() == llvm::Triple::arm || host_arch.GetMachine() == llvm::Triple::armeb || host_arch.IsMIPS()) response.Printf("watchpoint_exceptions_received:before;"); else response.Printf("watchpoint_exceptions_received:after;"); #endif switch (endian::InlHostByteOrder()) { case eByteOrderBig: response.PutCString("endian:big;"); break; case eByteOrderLittle: response.PutCString("endian:little;"); break; case eByteOrderPDP: response.PutCString("endian:pdp;"); break; default: response.PutCString("endian:unknown;"); break; } llvm::VersionTuple version = HostInfo::GetOSVersion(); if (!version.empty()) { response.Format("os_version:{0}", version.getAsString()); response.PutChar(';'); } #if defined(__APPLE__) llvm::VersionTuple maccatalyst_version = HostInfo::GetMacCatalystVersion(); if (!maccatalyst_version.empty()) { response.Format("maccatalyst_version:{0}", maccatalyst_version.getAsString()); response.PutChar(';'); } #endif std::string s; if (HostInfo::GetOSBuildString(s)) { response.PutCString("os_build:"); response.PutStringAsRawHex8(s); response.PutChar(';'); } if (HostInfo::GetOSKernelDescription(s)) { response.PutCString("os_kernel:"); response.PutStringAsRawHex8(s); response.PutChar(';'); } #if defined(__APPLE__) #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) // For iOS devices, we are connected through a USB Mux so we never pretend to // actually have a hostname as far as the remote lldb that is connecting to // this lldb-platform is concerned response.PutCString("hostname:"); response.PutStringAsRawHex8("127.0.0.1"); response.PutChar(';'); #else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) if (HostInfo::GetHostname(s)) { response.PutCString("hostname:"); response.PutStringAsRawHex8(s); response.PutChar(';'); } #endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) #else // #if defined(__APPLE__) if (HostInfo::GetHostname(s)) { response.PutCString("hostname:"); response.PutStringAsRawHex8(s); response.PutChar(';'); } #endif // #if defined(__APPLE__) if (g_default_packet_timeout_sec > 0) response.Printf("default_packet_timeout:%u;", g_default_packet_timeout_sec); return SendPacketNoLock(response.GetString()); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qProcessInfoPID( StringExtractorGDBRemote &packet) { // Packet format: "qProcessInfoPID:%i" where %i is the pid packet.SetFilePos(::strlen("qProcessInfoPID:")); lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID); if (pid != LLDB_INVALID_PROCESS_ID) { ProcessInstanceInfo proc_info; if (Host::GetProcessInfo(pid, proc_info)) { StreamString response; CreateProcessInfoResponse(proc_info, response); return SendPacketNoLock(response.GetString()); } } return SendErrorResponse(1); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qfProcessInfo( StringExtractorGDBRemote &packet) { m_proc_infos_index = 0; m_proc_infos.Clear(); ProcessInstanceInfoMatch match_info; packet.SetFilePos(::strlen("qfProcessInfo")); if (packet.GetChar() == ':') { llvm::StringRef key; llvm::StringRef value; while (packet.GetNameColonValue(key, value)) { bool success = true; if (key.equals("name")) { StringExtractor extractor(value); std::string file; extractor.GetHexByteString(file); match_info.GetProcessInfo().GetExecutableFile().SetFile( file, FileSpec::Style::native); } else if (key.equals("name_match")) { NameMatch name_match = llvm::StringSwitch<NameMatch>(value) .Case("equals", NameMatch::Equals) .Case("starts_with", NameMatch::StartsWith) .Case("ends_with", NameMatch::EndsWith) .Case("contains", NameMatch::Contains) .Case("regex", NameMatch::RegularExpression) .Default(NameMatch::Ignore); match_info.SetNameMatchType(name_match); if (name_match == NameMatch::Ignore) return SendErrorResponse(2); } else if (key.equals("pid")) { lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; if (value.getAsInteger(0, pid)) return SendErrorResponse(2); match_info.GetProcessInfo().SetProcessID(pid); } else if (key.equals("parent_pid")) { lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; if (value.getAsInteger(0, pid)) return SendErrorResponse(2); match_info.GetProcessInfo().SetParentProcessID(pid); } else if (key.equals("uid")) { uint32_t uid = UINT32_MAX; if (value.getAsInteger(0, uid)) return SendErrorResponse(2); match_info.GetProcessInfo().SetUserID(uid); } else if (key.equals("gid")) { uint32_t gid = UINT32_MAX; if (value.getAsInteger(0, gid)) return SendErrorResponse(2); match_info.GetProcessInfo().SetGroupID(gid); } else if (key.equals("euid")) { uint32_t uid = UINT32_MAX; if (value.getAsInteger(0, uid)) return SendErrorResponse(2); match_info.GetProcessInfo().SetEffectiveUserID(uid); } else if (key.equals("egid")) { uint32_t gid = UINT32_MAX; if (value.getAsInteger(0, gid)) return SendErrorResponse(2); match_info.GetProcessInfo().SetEffectiveGroupID(gid); } else if (key.equals("all_users")) { match_info.SetMatchAllUsers( OptionArgParser::ToBoolean(value, false, &success)); } else if (key.equals("triple")) { match_info.GetProcessInfo().GetArchitecture() = HostInfo::GetAugmentedArchSpec(value); } else { success = false; } if (!success) return SendErrorResponse(2); } } if (Host::FindProcesses(match_info, m_proc_infos)) { // We found something, return the first item by calling the get subsequent // process info packet handler... return Handle_qsProcessInfo(packet); } return SendErrorResponse(3); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qsProcessInfo( StringExtractorGDBRemote &packet) { if (m_proc_infos_index < m_proc_infos.GetSize()) { StreamString response; CreateProcessInfoResponse( m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response); ++m_proc_infos_index; return SendPacketNoLock(response.GetString()); } return SendErrorResponse(4); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qUserName( StringExtractorGDBRemote &packet) { #if LLDB_ENABLE_POSIX Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); LLDB_LOGF(log, "GDBRemoteCommunicationServerCommon::%s begin", __FUNCTION__); // Packet format: "qUserName:%i" where %i is the uid packet.SetFilePos(::strlen("qUserName:")); uint32_t uid = packet.GetU32(UINT32_MAX); if (uid != UINT32_MAX) { if (llvm::Optional<llvm::StringRef> name = HostInfo::GetUserIDResolver().GetUserName(uid)) { StreamString response; response.PutStringAsRawHex8(*name); return SendPacketNoLock(response.GetString()); } } LLDB_LOGF(log, "GDBRemoteCommunicationServerCommon::%s end", __FUNCTION__); #endif return SendErrorResponse(5); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qGroupName( StringExtractorGDBRemote &packet) { #if LLDB_ENABLE_POSIX // Packet format: "qGroupName:%i" where %i is the gid packet.SetFilePos(::strlen("qGroupName:")); uint32_t gid = packet.GetU32(UINT32_MAX); if (gid != UINT32_MAX) { if (llvm::Optional<llvm::StringRef> name = HostInfo::GetUserIDResolver().GetGroupName(gid)) { StreamString response; response.PutStringAsRawHex8(*name); return SendPacketNoLock(response.GetString()); } } #endif return SendErrorResponse(6); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qSpeedTest( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("qSpeedTest:")); llvm::StringRef key; llvm::StringRef value; bool success = packet.GetNameColonValue(key, value); if (success && key.equals("response_size")) { uint32_t response_size = 0; if (!value.getAsInteger(0, response_size)) { if (response_size == 0) return SendOKResponse(); StreamString response; uint32_t bytes_left = response_size; response.PutCString("data:"); while (bytes_left > 0) { if (bytes_left >= 26) { response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); bytes_left -= 26; } else { response.Printf("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); bytes_left = 0; } } return SendPacketNoLock(response.GetString()); } } return SendErrorResponse(7); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_Open( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:open:")); std::string path; packet.GetHexByteStringTerminatedBy(path, ','); if (!path.empty()) { if (packet.GetChar() == ',') { // FIXME // The flag values for OpenOptions do not match the values used by GDB // * https://sourceware.org/gdb/onlinedocs/gdb/Open-Flags.html#Open-Flags // * rdar://problem/46788934 auto flags = File::OpenOptions(packet.GetHexMaxU32(false, 0)); if (packet.GetChar() == ',') { mode_t mode = packet.GetHexMaxU32(false, 0600); FileSpec path_spec(path); FileSystem::Instance().Resolve(path_spec); // Do not close fd. auto file = FileSystem::Instance().Open(path_spec, flags, mode, false); int save_errno = 0; int descriptor = File::kInvalidDescriptor; if (file) { descriptor = file.get()->GetDescriptor(); } else { std::error_code code = errorToErrorCode(file.takeError()); if (code.category() == std::system_category()) { save_errno = code.value(); } } StreamString response; response.PutChar('F'); response.Printf("%i", descriptor); if (save_errno) response.Printf(",%i", save_errno); return SendPacketNoLock(response.GetString()); } } } return SendErrorResponse(18); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_Close( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:close:")); int fd = packet.GetS32(-1); int err = -1; int save_errno = 0; if (fd >= 0) { NativeFile file(fd, File::OpenOptions(0), true); Status error = file.Close(); err = 0; save_errno = error.GetError(); } else { save_errno = EINVAL; } StreamString response; response.PutChar('F'); response.Printf("%i", err); if (save_errno) response.Printf(",%i", save_errno); return SendPacketNoLock(response.GetString()); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_pRead( StringExtractorGDBRemote &packet) { StreamGDBRemote response; packet.SetFilePos(::strlen("vFile:pread:")); int fd = packet.GetS32(-1); if (packet.GetChar() == ',') { size_t count = packet.GetU64(SIZE_MAX); if (packet.GetChar() == ',') { off_t offset = packet.GetU64(UINT32_MAX); if (count == SIZE_MAX) { response.Printf("F-1:%i", EINVAL); return SendPacketNoLock(response.GetString()); } std::string buffer(count, 0); NativeFile file(fd, File::eOpenOptionRead, false); Status error = file.Read(static_cast<void *>(&buffer[0]), count, offset); const ssize_t bytes_read = error.Success() ? count : -1; const int save_errno = error.GetError(); response.PutChar('F'); response.Printf("%zi", bytes_read); if (save_errno) response.Printf(",%i", save_errno); else { response.PutChar(';'); response.PutEscapedBytes(&buffer[0], bytes_read); } return SendPacketNoLock(response.GetString()); } } return SendErrorResponse(21); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_pWrite( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:pwrite:")); StreamGDBRemote response; response.PutChar('F'); int fd = packet.GetU32(UINT32_MAX); if (packet.GetChar() == ',') { off_t offset = packet.GetU64(UINT32_MAX); if (packet.GetChar() == ',') { std::string buffer; if (packet.GetEscapedBinaryData(buffer)) { NativeFile file(fd, File::eOpenOptionWrite, false); size_t count = buffer.size(); Status error = file.Write(static_cast<const void *>(&buffer[0]), count, offset); const ssize_t bytes_written = error.Success() ? count : -1; const int save_errno = error.GetError(); response.Printf("%zi", bytes_written); if (save_errno) response.Printf(",%i", save_errno); } else { response.Printf("-1,%i", EINVAL); } return SendPacketNoLock(response.GetString()); } } return SendErrorResponse(27); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_Size( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:size:")); std::string path; packet.GetHexByteString(path); if (!path.empty()) { uint64_t Size; if (llvm::sys::fs::file_size(path, Size)) return SendErrorResponse(5); StreamString response; response.PutChar('F'); response.PutHex64(Size); if (Size == UINT64_MAX) { response.PutChar(','); response.PutHex64(Size); // TODO: replace with Host::GetSyswideErrorCode() } return SendPacketNoLock(response.GetString()); } return SendErrorResponse(22); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_Mode( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:mode:")); std::string path; packet.GetHexByteString(path); if (!path.empty()) { FileSpec file_spec(path); FileSystem::Instance().Resolve(file_spec); std::error_code ec; const uint32_t mode = FileSystem::Instance().GetPermissions(file_spec, ec); StreamString response; response.Printf("F%u", mode); if (mode == 0 || ec) response.Printf(",%i", (int)Status(ec).GetError()); return SendPacketNoLock(response.GetString()); } return SendErrorResponse(23); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_Exists( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:exists:")); std::string path; packet.GetHexByteString(path); if (!path.empty()) { bool retcode = llvm::sys::fs::exists(path); StreamString response; response.PutChar('F'); response.PutChar(','); if (retcode) response.PutChar('1'); else response.PutChar('0'); return SendPacketNoLock(response.GetString()); } return SendErrorResponse(24); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_symlink( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:symlink:")); std::string dst, src; packet.GetHexByteStringTerminatedBy(dst, ','); packet.GetChar(); // Skip ',' char packet.GetHexByteString(src); FileSpec src_spec(src); FileSystem::Instance().Resolve(src_spec); Status error = FileSystem::Instance().Symlink(src_spec, FileSpec(dst)); StreamString response; response.Printf("F%u,%u", error.GetError(), error.GetError()); return SendPacketNoLock(response.GetString()); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_unlink( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:unlink:")); std::string path; packet.GetHexByteString(path); Status error(llvm::sys::fs::remove(path)); StreamString response; response.Printf("F%u,%u", error.GetError(), error.GetError()); return SendPacketNoLock(response.GetString()); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qPlatform_shell( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("qPlatform_shell:")); std::string path; std::string working_dir; packet.GetHexByteStringTerminatedBy(path, ','); if (!path.empty()) { if (packet.GetChar() == ',') { // FIXME: add timeout to qPlatform_shell packet // uint32_t timeout = packet.GetHexMaxU32(false, 32); if (packet.GetChar() == ',') packet.GetHexByteString(working_dir); int status, signo; std::string output; FileSpec working_spec(working_dir); FileSystem::Instance().Resolve(working_spec); Status err = Host::RunShellCommand(path.c_str(), working_spec, &status, &signo, &output, std::chrono::seconds(10)); StreamGDBRemote response; if (err.Fail()) { response.PutCString("F,"); response.PutHex32(UINT32_MAX); } else { response.PutCString("F,"); response.PutHex32(status); response.PutChar(','); response.PutHex32(signo); response.PutChar(','); response.PutEscapedBytes(output.c_str(), output.size()); } return SendPacketNoLock(response.GetString()); } } return SendErrorResponse(24); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_Stat( StringExtractorGDBRemote &packet) { return SendUnimplementedResponse( "GDBRemoteCommunicationServerCommon::Handle_vFile_Stat() unimplemented"); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_vFile_MD5( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("vFile:MD5:")); std::string path; packet.GetHexByteString(path); if (!path.empty()) { StreamGDBRemote response; auto Result = llvm::sys::fs::md5_contents(path); if (!Result) { response.PutCString("F,"); response.PutCString("x"); } else { response.PutCString("F,"); response.PutHex64(Result->low()); response.PutHex64(Result->high()); } return SendPacketNoLock(response.GetString()); } return SendErrorResponse(25); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qPlatform_mkdir( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("qPlatform_mkdir:")); mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX); if (packet.GetChar() == ',') { std::string path; packet.GetHexByteString(path); Status error(llvm::sys::fs::create_directory(path, mode)); StreamGDBRemote response; response.Printf("F%u", error.GetError()); return SendPacketNoLock(response.GetString()); } return SendErrorResponse(20); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qPlatform_chmod( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("qPlatform_chmod:")); auto perms = static_cast<llvm::sys::fs::perms>(packet.GetHexMaxU32(false, UINT32_MAX)); if (packet.GetChar() == ',') { std::string path; packet.GetHexByteString(path); Status error(llvm::sys::fs::setPermissions(path, perms)); StreamGDBRemote response; response.Printf("F%u", error.GetError()); return SendPacketNoLock(response.GetString()); } return SendErrorResponse(19); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qSupported( StringExtractorGDBRemote &packet) { StreamGDBRemote response; // Features common to lldb-platform and llgs. uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet // size--debugger can always use less response.Printf("PacketSize=%x", max_packet_size); response.PutCString(";QStartNoAckMode+"); response.PutCString(";QThreadSuffixSupported+"); response.PutCString(";QListThreadsInStopReply+"); response.PutCString(";qEcho+"); #if defined(__linux__) || defined(__NetBSD__) response.PutCString(";QPassSignals+"); response.PutCString(";qXfer:auxv:read+"); response.PutCString(";qXfer:libraries-svr4:read+"); #endif return SendPacketNoLock(response.GetString()); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QThreadSuffixSupported( StringExtractorGDBRemote &packet) { m_thread_suffix_supported = true; return SendOKResponse(); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QListThreadsInStopReply( StringExtractorGDBRemote &packet) { m_list_threads_in_stop_reply = true; return SendOKResponse(); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QSetDetachOnError( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("QSetDetachOnError:")); if (packet.GetU32(0)) m_process_launch_info.GetFlags().Set(eLaunchFlagDetachOnError); else m_process_launch_info.GetFlags().Clear(eLaunchFlagDetachOnError); return SendOKResponse(); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QStartNoAckMode( StringExtractorGDBRemote &packet) { // Send response first before changing m_send_acks to we ack this packet PacketResult packet_result = SendOKResponse(); m_send_acks = false; return packet_result; } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QSetSTDIN( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("QSetSTDIN:")); FileAction file_action; std::string path; packet.GetHexByteString(path); const bool read = true; const bool write = false; if (file_action.Open(STDIN_FILENO, FileSpec(path), read, write)) { m_process_launch_info.AppendFileAction(file_action); return SendOKResponse(); } return SendErrorResponse(15); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QSetSTDOUT( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("QSetSTDOUT:")); FileAction file_action; std::string path; packet.GetHexByteString(path); const bool read = false; const bool write = true; if (file_action.Open(STDOUT_FILENO, FileSpec(path), read, write)) { m_process_launch_info.AppendFileAction(file_action); return SendOKResponse(); } return SendErrorResponse(16); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QSetSTDERR( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("QSetSTDERR:")); FileAction file_action; std::string path; packet.GetHexByteString(path); const bool read = false; const bool write = true; if (file_action.Open(STDERR_FILENO, FileSpec(path), read, write)) { m_process_launch_info.AppendFileAction(file_action); return SendOKResponse(); } return SendErrorResponse(17); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qLaunchSuccess( StringExtractorGDBRemote &packet) { if (m_process_launch_error.Success()) return SendOKResponse(); StreamString response; response.PutChar('E'); response.PutCString(m_process_launch_error.AsCString("<unknown error>")); return SendPacketNoLock(response.GetString()); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QEnvironment( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("QEnvironment:")); const uint32_t bytes_left = packet.GetBytesLeft(); if (bytes_left > 0) { m_process_launch_info.GetEnvironment().insert(packet.Peek()); return SendOKResponse(); } return SendErrorResponse(12); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QEnvironmentHexEncoded( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("QEnvironmentHexEncoded:")); const uint32_t bytes_left = packet.GetBytesLeft(); if (bytes_left > 0) { std::string str; packet.GetHexByteString(str); m_process_launch_info.GetEnvironment().insert(str); return SendOKResponse(); } return SendErrorResponse(12); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_QLaunchArch( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("QLaunchArch:")); const uint32_t bytes_left = packet.GetBytesLeft(); if (bytes_left > 0) { const char *arch_triple = packet.Peek(); m_process_launch_info.SetArchitecture( HostInfo::GetAugmentedArchSpec(arch_triple)); return SendOKResponse(); } return SendErrorResponse(13); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_A(StringExtractorGDBRemote &packet) { // The 'A' packet is the most over designed packet ever here with redundant // argument indexes, redundant argument lengths and needed hex encoded // argument string values. Really all that is needed is a comma separated hex // encoded argument value list, but we will stay true to the documented // version of the 'A' packet here... Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); int actual_arg_index = 0; packet.SetFilePos(1); // Skip the 'A' bool success = true; while (success && packet.GetBytesLeft() > 0) { // Decode the decimal argument string length. This length is the number of // hex nibbles in the argument string value. const uint32_t arg_len = packet.GetU32(UINT32_MAX); if (arg_len == UINT32_MAX) success = false; else { // Make sure the argument hex string length is followed by a comma if (packet.GetChar() != ',') success = false; else { // Decode the argument index. We ignore this really because who would // really send down the arguments in a random order??? const uint32_t arg_idx = packet.GetU32(UINT32_MAX); if (arg_idx == UINT32_MAX) success = false; else { // Make sure the argument index is followed by a comma if (packet.GetChar() != ',') success = false; else { // Decode the argument string value from hex bytes back into a UTF8 // string and make sure the length matches the one supplied in the // packet std::string arg; if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2)) success = false; else { // If there are any bytes left if (packet.GetBytesLeft()) { if (packet.GetChar() != ',') success = false; } if (success) { if (arg_idx == 0) m_process_launch_info.GetExecutableFile().SetFile( arg, FileSpec::Style::native); m_process_launch_info.GetArguments().AppendArgument(arg); LLDB_LOGF(log, "LLGSPacketHandler::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str()); ++actual_arg_index; } } } } } } } if (success) { m_process_launch_error = LaunchProcess(); if (m_process_launch_error.Success()) return SendOKResponse(); LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error); } return SendErrorResponse(8); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qEcho( StringExtractorGDBRemote &packet) { // Just echo back the exact same packet for qEcho... return SendPacketNoLock(packet.GetStringRef()); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_qModuleInfo( StringExtractorGDBRemote &packet) { packet.SetFilePos(::strlen("qModuleInfo:")); std::string module_path; packet.GetHexByteStringTerminatedBy(module_path, ';'); if (module_path.empty()) return SendErrorResponse(1); if (packet.GetChar() != ';') return SendErrorResponse(2); std::string triple; packet.GetHexByteString(triple); ModuleSpec matched_module_spec = GetModuleInfo(module_path, triple); if (!matched_module_spec.GetFileSpec()) return SendErrorResponse(3); const auto file_offset = matched_module_spec.GetObjectOffset(); const auto file_size = matched_module_spec.GetObjectSize(); const auto uuid_str = matched_module_spec.GetUUID().GetAsString(""); StreamGDBRemote response; if (uuid_str.empty()) { auto Result = llvm::sys::fs::md5_contents( matched_module_spec.GetFileSpec().GetPath()); if (!Result) return SendErrorResponse(5); response.PutCString("md5:"); response.PutStringAsRawHex8(Result->digest()); } else { response.PutCString("uuid:"); response.PutStringAsRawHex8(uuid_str); } response.PutChar(';'); const auto &module_arch = matched_module_spec.GetArchitecture(); response.PutCString("triple:"); response.PutStringAsRawHex8(module_arch.GetTriple().getTriple()); response.PutChar(';'); response.PutCString("file_path:"); response.PutStringAsRawHex8(matched_module_spec.GetFileSpec().GetCString()); response.PutChar(';'); response.PutCString("file_offset:"); response.PutHex64(file_offset); response.PutChar(';'); response.PutCString("file_size:"); response.PutHex64(file_size); response.PutChar(';'); return SendPacketNoLock(response.GetString()); } GDBRemoteCommunication::PacketResult GDBRemoteCommunicationServerCommon::Handle_jModulesInfo( StringExtractorGDBRemote &packet) { namespace json = llvm::json; packet.SetFilePos(::strlen("jModulesInfo:")); StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(packet.Peek()); if (!object_sp) return SendErrorResponse(1); StructuredData::Array *packet_array = object_sp->GetAsArray(); if (!packet_array) return SendErrorResponse(2); json::Array response_array; for (size_t i = 0; i < packet_array->GetSize(); ++i) { StructuredData::Dictionary *query = packet_array->GetItemAtIndex(i)->GetAsDictionary(); if (!query) continue; llvm::StringRef file, triple; if (!query->GetValueForKeyAsString("file", file) || !query->GetValueForKeyAsString("triple", triple)) continue; ModuleSpec matched_module_spec = GetModuleInfo(file, triple); if (!matched_module_spec.GetFileSpec()) continue; const auto file_offset = matched_module_spec.GetObjectOffset(); const auto file_size = matched_module_spec.GetObjectSize(); const auto uuid_str = matched_module_spec.GetUUID().GetAsString(""); if (uuid_str.empty()) continue; const auto triple_str = matched_module_spec.GetArchitecture().GetTriple().getTriple(); const auto file_path = matched_module_spec.GetFileSpec().GetPath(); json::Object response{{"uuid", uuid_str}, {"triple", triple_str}, {"file_path", file_path}, {"file_offset", static_cast<int64_t>(file_offset)}, {"file_size", static_cast<int64_t>(file_size)}}; response_array.push_back(std::move(response)); } StreamString response; response.AsRawOstream() << std::move(response_array); StreamGDBRemote escaped_response; escaped_response.PutEscapedBytes(response.GetString().data(), response.GetSize()); return SendPacketNoLock(escaped_response.GetString()); } void GDBRemoteCommunicationServerCommon::CreateProcessInfoResponse( const ProcessInstanceInfo &proc_info, StreamString &response) { response.Printf( "pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;", proc_info.GetProcessID(), proc_info.GetParentProcessID(), proc_info.GetUserID(), proc_info.GetGroupID(), proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID()); response.PutCString("name:"); response.PutStringAsRawHex8(proc_info.GetExecutableFile().GetCString()); response.PutChar(';'); response.PutCString("args:"); response.PutStringAsRawHex8(proc_info.GetArg0()); for (auto &arg : proc_info.GetArguments()) { response.PutChar('-'); response.PutStringAsRawHex8(arg.ref()); } response.PutChar(';'); const ArchSpec &proc_arch = proc_info.GetArchitecture(); if (proc_arch.IsValid()) { const llvm::Triple &proc_triple = proc_arch.GetTriple(); response.PutCString("triple:"); response.PutStringAsRawHex8(proc_triple.getTriple()); response.PutChar(';'); } } void GDBRemoteCommunicationServerCommon:: CreateProcessInfoResponse_DebugServerStyle( const ProcessInstanceInfo &proc_info, StreamString &response) { response.Printf("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;", proc_info.GetProcessID(), proc_info.GetParentProcessID(), proc_info.GetUserID(), proc_info.GetGroupID(), proc_info.GetEffectiveUserID(), proc_info.GetEffectiveGroupID()); const ArchSpec &proc_arch = proc_info.GetArchitecture(); if (proc_arch.IsValid()) { const llvm::Triple &proc_triple = proc_arch.GetTriple(); #if defined(__APPLE__) // We'll send cputype/cpusubtype. const uint32_t cpu_type = proc_arch.GetMachOCPUType(); if (cpu_type != 0) response.Printf("cputype:%" PRIx32 ";", cpu_type); const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType(); if (cpu_subtype != 0) response.Printf("cpusubtype:%" PRIx32 ";", cpu_subtype); const std::string vendor = proc_triple.getVendorName(); if (!vendor.empty()) response.Printf("vendor:%s;", vendor.c_str()); #else // We'll send the triple. response.PutCString("triple:"); response.PutStringAsRawHex8(proc_triple.getTriple()); response.PutChar(';'); #endif std::string ostype = proc_triple.getOSName(); // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64. if (proc_triple.getVendor() == llvm::Triple::Apple) { switch (proc_triple.getArch()) { case llvm::Triple::arm: case llvm::Triple::thumb: case llvm::Triple::aarch64: case llvm::Triple::aarch64_32: ostype = "ios"; break; default: // No change. break; } } response.Printf("ostype:%s;", ostype.c_str()); switch (proc_arch.GetByteOrder()) { case lldb::eByteOrderLittle: response.PutCString("endian:little;"); break; case lldb::eByteOrderBig: response.PutCString("endian:big;"); break; case lldb::eByteOrderPDP: response.PutCString("endian:pdp;"); break; default: // Nothing. break; } // In case of MIPS64, pointer size is depend on ELF ABI For N32 the pointer // size is 4 and for N64 it is 8 std::string abi = proc_arch.GetTargetABI(); if (!abi.empty()) response.Printf("elf_abi:%s;", abi.c_str()); response.Printf("ptrsize:%d;", proc_arch.GetAddressByteSize()); } } FileSpec GDBRemoteCommunicationServerCommon::FindModuleFile( const std::string &module_path, const ArchSpec &arch) { #ifdef __ANDROID__ return HostInfoAndroid::ResolveLibraryPath(module_path, arch); #else FileSpec file_spec(module_path); FileSystem::Instance().Resolve(file_spec); return file_spec; #endif } ModuleSpec GDBRemoteCommunicationServerCommon::GetModuleInfo(llvm::StringRef module_path, llvm::StringRef triple) { ArchSpec arch(triple); FileSpec req_module_path_spec(module_path); FileSystem::Instance().Resolve(req_module_path_spec); const FileSpec module_path_spec = FindModuleFile(req_module_path_spec.GetPath(), arch); const ModuleSpec module_spec(module_path_spec, arch); ModuleSpecList module_specs; if (!ObjectFile::GetModuleSpecifications(module_path_spec, 0, 0, module_specs)) return ModuleSpec(); ModuleSpec matched_module_spec; if (!module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec)) return ModuleSpec(); return matched_module_spec; }
35.741248
90
0.709671
AlexisPerry
4b6066d14848f3f00d999b136b5b8496a01524a1
662
cpp
C++
Framework/GeomMath/cpp/MatrixUtil.cpp
kiorisyshen/newbieGameEngine
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
[ "MIT" ]
3
2019-06-07T15:29:45.000Z
2019-11-11T01:26:12.000Z
Framework/GeomMath/cpp/MatrixUtil.cpp
kiorisyshen/newbieGameEngine
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
[ "MIT" ]
null
null
null
Framework/GeomMath/cpp/MatrixUtil.cpp
kiorisyshen/newbieGameEngine
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
[ "MIT" ]
null
null
null
#include <cstdint> #include <cstring> using namespace std; namespace Dummy { void BuildIdentityMatrix(float *data, const int32_t n) { memset(data, 0x00, sizeof(float) * n * n); for (int32_t i = 0; i < n; i++) { *(data + i * n + i) = 1.0f; } } void MatrixExchangeYandZ(float *data, const int32_t rows, const int32_t cols) { for (int32_t row_index = 0; row_index < rows; row_index++) { uint32_t *p, *q; p = reinterpret_cast<uint32_t *>(data + row_index * cols + 1); q = reinterpret_cast<uint32_t *>(data + row_index * cols + 2); *p ^= *q; *q ^= *p; *p ^= *q; } } } // namespace Dummy
26.48
79
0.570997
kiorisyshen
4b61999960d490ddf3ec717ec8f743066ac849a2
2,973
cpp
C++
test/twod_test/demo/demo.cpp
billyquith/bq-twod
81d5d35cf3db22145fb4dd14cfe6b8dd927373b6
[ "MIT" ]
null
null
null
test/twod_test/demo/demo.cpp
billyquith/bq-twod
81d5d35cf3db22145fb4dd14cfe6b8dd927373b6
[ "MIT" ]
null
null
null
test/twod_test/demo/demo.cpp
billyquith/bq-twod
81d5d35cf3db22145fb4dd14cfe6b8dd927373b6
[ "MIT" ]
null
null
null
#include "demo.hpp" #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Graphics/CircleShape.hpp> #include <cassert> void InteractiveDemo::processEvent(const sf::Event &evt) { } void InteractiveDemo::draw(sf::RenderTarget &rt) {} void DemoPoints::drawLine(sf::RenderTarget &rt) { const int nb = points_.size(); sf::VertexArray va(sf::PrimitiveType::LinesStrip, nb); for (int i=0; i < nb; ++i) { va[i].position = points_[i].sfVec(); } rt.draw(va); } void DemoPoints::drawPoints(sf::RenderTarget &rt) { const int nb = points_.size(); for (int i=0; i < nb; ++i) { const float r = points_[i].radius; sf::CircleShape cs(r); cs.setPosition(points_[i].sfVec() - sf::Vector2f(r,r)); cs.setFillColor(points_[i].sfCol()); rt.draw(cs); } } bool DemoPoints::processEvent(const sf::Event &evt) { bool consumed = false; switch (evt.type) { case sf::Event::MouseMoved: { const twod::Vec2f mp(evt.mouseMove.x, evt.mouseMove.y); for (auto& pt : points_) { const bool over = (pt.pos - mp).length() <= pt.radius; pt.setState(Point::STATE_MOUSE_OVER, over); } if (dragging_) { assert(selectedPt_ != nullptr); selectedPt_->pos = mp; if (selectedPt_->onDrag) selectedPt_->onDrag(*selectedPt_); consumed = true; } break; } case sf::Event::MouseButtonPressed: case sf::Event::MouseButtonReleased: { const bool pressed = evt.type == sf::Event::MouseButtonPressed; const twod::Vec2f mp(evt.mouseButton.x, evt.mouseButton.y); if (evt.mouseButton.button == sf::Mouse::Button::Left) { if (pressed) { selectedPt_ = nullptr; for (auto& pt : points_) { const bool over = (pt.pos - mp).length() <= pt.radius; if (over) { selectedPt_ = &pt; dragging_ = true; pt.pos = mp; pt.setState(Point::STATE_MOUSE_DRAGGING, true); consumed = true; break; } } } else { dragging_ = false; if (selectedPt_) selectedPt_->setState(Point::STATE_MOUSE_DRAGGING, false); selectedPt_ = nullptr; } } } default: ; } return consumed; }
27.275229
82
0.447023
billyquith
4b64a1c25d06e716e3a861449c8ae3d89136069b
4,975
hpp
C++
include/AppStandards.hpp
john-fotis/SysPro3
79066d516edd345220d0f1cf0e83647edacfcc23
[ "MIT" ]
1
2021-08-20T11:19:46.000Z
2021-08-20T11:19:46.000Z
include/AppStandards.hpp
john-fotis/SysPro3
79066d516edd345220d0f1cf0e83647edacfcc23
[ "MIT" ]
null
null
null
include/AppStandards.hpp
john-fotis/SysPro3
79066d516edd345220d0f1cf0e83647edacfcc23
[ "MIT" ]
null
null
null
#ifndef APPSTANDARDS_HPP #define APPSTANDARDS_HPP #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <iostream> #include "List.hpp" typedef std::string string; // travelClient parameters #define PERMS 0775 #define LOGS_PATH "logs/" // monitorServer parameters #define CITIZEN_REGISTRY_SIZE 1000 #define VIRUS_COUNTRY_ENTRIES 100 // System messages - travelClient #define INPUT_TRAVEL "\n./travelMonitorClient -m numMonitors -b socketBufferSize -c cyclicBufferSize -s sizeOfBloom -i input_dir -t numThreads (-o timeOutSeconds)\n" #define SERVER_STARTING "\nStarting the server...\n" #define SERVER_STARTED "\nThe server is up.\n" #define SERVER_STOPPING "\nStopping the server...\n" #define SERVER_STOPPED "\nThe server is down.\n" #define REDUCE_MONITORS(NUM) "\nHad to reduce the number of Monitors to " << NUM #define SEARCHING_MONITOR(HOST) "\nSearching for \"" << HOST << "\" address...\n" #define ALTERNATIVE_NAME(NAME) "Alternative Name: " << NAME << "\n" #define RESOLVED_HOST(NAME, IP) NAME << " resolved to " << IP << "\n\n" #define ATTEMPTING_CONN(NAME, PORT) "Attempting connection to " << NAME << " at port " << PORT << "\n" #define CONNECTION_TIMED_OUT "\nError: Connection timed-out. Aborting...\n" #define MONITOR_REPLACE(OLD, NEW) "Replacing Monitor " << OLD << " with " << NEW << "...\n" #define MONITOR_ERROR(PID) "\nAn error occurred with monitor #" << PID #define SPOILER "\nType /help to display the available options or /exit to exit the application.\n\n" #define LOG_FILES_SAVED(PATH) "\nlog-files have been stored in " << PATH << "\n\n" #define EXIT_CODE_FROM(PID, CODE) "Exit status from " << PID << " was " << CODE // System messages - monitorServer #define INPUT_MONITOR "\n./monitorServer -p port -t numThreads -b socketBufferSize -c cyclicBufferSize -s sizeOfBloom path1 path2 ... pathn\n" #define NOT_ENOUGH_RESOURCES(DIR) " because of insufficient number of sub-directories in " << DIR #define MONITOR_STARTED(PID) "Monitor " << PID << " is up.\n" #define MONITOR_STOPPED(PID) "Monitor " << PID << " is down.\n" #define LISTENING_TO(PID, PORT) "Monitor " << PID << " listening for connections to port " << PORT << "\n" #define ACCEPTED_CONN(PID, CLI) "Monitor " << PID << " accepted new connection from \"" << CLI << "\"\n" // Query messages #define COUT_REQ_REJECTED "\nREQUEST REJECTED - YOU ARE NOT VACCINATED\n" #define COUT_REQ_REJECTED2 "\nREQUEST REJECTED - YOU WILL NEED ANOTHER VACCINATION BEFORE TRAVEL DATE\n" #define COUT_REQ_ACCEPTED "\nREQUEST ACCEPTED - HAPPY TRAVELS\n" #define STATISTICS "STATISTICS" #define TOTAL_REQUESTS "TOTAL REQUESTS" #define TOTAL_ACCEPTED "TOTAL ACCEPTED" #define TOTAL_REJECTED "TOTAL REJECTED" #define DATABASE_UPDATED "\nTHE DATABASE HAS BEEN UPDATED\n" #define VACCINATED "VACCINATED ON " #define NOT_VACCINATED "NOT YET VACCINATED" // Error messages #define ARGS_NUMBER "\nINVALID NUMBER OF ARGUMENTS\n" #define INV_ID "\nINVALID CITIZEN ID\n" #define INV_DATE "\nINVALID DATE GIVEN\n" #define DATE_IN_ORDER "\ndate1 SHOULD BE OLDER THAN date2\n" #define NO_DATA_IN_DB "\nTHERE IS NO DATA YET\n" #define NO_COUNTRY "\nNO SUCH COUNTRY FOUND\n" #define NO_COUNTRY_DATA "\nTHERE IS NO DATA FOR THIS COUNTRY YET\n" #define NO_VIRUS "\nNO SUCH VIRUS FOUND\n" #define NO_NEW_FILES "\nNO NEW FILES FOUND\n" #define USER_NOT_FOUND "\nUSER NOT FOUND IN DATABASE\n" #define UNKNOWN_ERROR "\nSOMETHING WENT WRONG...\n" #define OPEN_FAILED "COULDN'T OPEN " #define DUPLICATE_RECORD "DUPLICATE RECORD: " #define INCONSISTENT_RECORD "ERROR IN RECORD: " // Socket-message types #define REQUEST "REQUEST" #define ACCEPTED "ACCEPTED" #define REJECTED "REJECTED" #define UPDATE "UPDATE" #define NOT_FOUND "404" // travelClient error codes enum travelErrors { travelArgsNum = 1, monitorIdentifier = 2, monitorNumber = 3, bufferIdentifier = 4, bufferSize = 5, cBuffIdentifier = 6, cBuffSize = 7, bloomIdentifier = 8, bloomSize = 9, directoryIdentifier = 10, directoryNotFound = 11, threadIdentifier = 12, numOfThreads = 13, timeoutIdentifier = 14, timeoutValue = 15 }; // monitorServer error codes enum monitorErrors { monitorArgsNum = 1, portIdentifier = 2, portNumber = 3, mThreadIdentifier = 4, mNumOfThreads = 5, mBufferIdentifier = 6, mBufferSize = 7, mCBufferIdentifier = 8, mCBufferSize = 9, mBloomIdentifier = 10, mBloomSize = 11, pathNotFound = 12 }; // Main menu option codes enum menuOptions { exitProgram = 0, travelRequest = 1, travelStats = 2, addRecords = 3, searchStatus = 4, help = 5 }; bool checkTravelArgs(List<std::string> &args); bool checkMonitorArgs(List<std::string> &args); // Returns -1 on invalid option or number of selected option in enumeration int getOptions(std::string input); void printOptions(); // Exit program after printing err void die(const char *err, int code); #endif
36.050725
165
0.722814
john-fotis
4b64ef1e857fae1172aadf20742e5d722fc59c49
2,184
cpp
C++
dep/acelite/ace/Intrusive_List.cpp
muscnx/Mangos021SD2
695bb6a4822bb9173ab8e9077cb6259869ca2f32
[ "PostgreSQL", "Zlib", "OpenSSL" ]
42
2015-01-05T10:00:07.000Z
2022-02-18T14:51:33.000Z
dep/ACE_wrappers/ace/Intrusive_List.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
20
2017-04-10T18:41:58.000Z
2017-04-10T19:01:12.000Z
dep/ACE_wrappers/ace/Intrusive_List.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: Intrusive_List.cpp 92069 2010-09-28 11:38:59Z johnnyw $ #ifndef ACE_INTRUSIVE_LIST_CPP #define ACE_INTRUSIVE_LIST_CPP #include "ace/Intrusive_List.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #if !defined (__ACE_INLINE__) #include "ace/Intrusive_List.inl" #endif /* __ACE_INLINE__ */ ACE_BEGIN_VERSIONED_NAMESPACE_DECL template <class T> ACE_Intrusive_List<T>::ACE_Intrusive_List (void) : head_ (0) , tail_ (0) { } template<class T> ACE_Intrusive_List<T>::~ACE_Intrusive_List (void) { } template<class T> void ACE_Intrusive_List<T>::push_back (T *node) { if (this->tail_ == 0) { this->tail_ = node; this->head_ = node; node->next (0); node->prev (0); } else { this->tail_->next (node); node->prev (this->tail_); node->next (0); this->tail_ = node; } } template<class T> void ACE_Intrusive_List<T>::push_front (T *node) { if (this->head_ == 0) { this->tail_ = node; this->head_ = node; node->next (0); node->prev (0); } else { this->head_->prev (node); node->next (this->head_); node->prev (0); this->head_ = node; } } template<class T> T * ACE_Intrusive_List<T>::pop_front (void) { T *node = this->head_; if (node != 0) { this->unsafe_remove (node); } return node; } template<class T> T * ACE_Intrusive_List<T>::pop_back (void) { T *node = this->tail_; if (node != 0) { this->unsafe_remove (node); } return node; } template<class T> void ACE_Intrusive_List<T>::remove (T *node) { for (T *i = this->head_; i != 0; i = i->next ()) { if (node == i) { this->unsafe_remove (node); return; } } } template<class T> void ACE_Intrusive_List<T>::unsafe_remove (T *node) { if (node->prev () != 0) node->prev ()->next (node->next ()); else this->head_ = node->next (); if (node->next () != 0) node->next ()->prev (node->prev ()); else this->tail_ = node->prev (); node->next (0); node->prev (0); } ACE_END_VERSIONED_NAMESPACE_DECL #endif /* ACE_INTRUSIVE_LIST_CPP */
17.756098
63
0.590659
muscnx
4b64f252529591b0628a76d5c7afce335b30356d
14,844
cpp
C++
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheComponent.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
null
null
null
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheComponent.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
null
null
null
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheComponent.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
1
2021-01-22T09:11:51.000Z
2021-01-22T09:11:51.000Z
// Copyright Epic Games, Inc. All Rights Reserved. #include "GeometryCacheComponent.h" #include "GeometryCache.h" #include "Logging/MessageLog.h" #include "ContentStreaming.h" #include "GeometryCacheSceneProxy.h" #include "GeometryCacheTrack.h" #include "GeometryCacheMeshData.h" #include "GeometryCacheStreamingManager.h" #include "GeometryCacheModule.h" #define LOCTEXT_NAMESPACE "GeometryCacheComponent" DECLARE_CYCLE_STAT(TEXT("Component Tick"), STAT_GeometryCacheComponent_TickComponent, STATGROUP_GeometryCache); UGeometryCacheComponent::UGeometryCacheComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryComponentTick.bCanEverTick = true; ElapsedTime = 0.0f; bRunning = true; bLooping = true; PlayDirection = 1.0f; StartTimeOffset = 0.0f; PlaybackSpeed = 1.0f; Duration = 0.0f; bManualTick = false; } void UGeometryCacheComponent::BeginDestroy() { Super::BeginDestroy(); ReleaseResources(); } void UGeometryCacheComponent::FinishDestroy() { Super::FinishDestroy(); } void UGeometryCacheComponent::PostLoad() { Super::PostLoad(); } void UGeometryCacheComponent::OnRegister() { ClearTrackData(); SetupTrackData(); IGeometryCacheStreamingManager::Get().AddStreamingComponent(this); Super::OnRegister(); } void UGeometryCacheComponent::ClearTrackData() { NumTracks = 0; TrackSections.Empty(); } void UGeometryCacheComponent::SetupTrackData() { if (GeometryCache != nullptr) { // Refresh NumTracks and clear Index Arrays NumTracks = GeometryCache->Tracks.Num(); Duration = 0.0f; // Create mesh sections for each GeometryCacheTrack for (int32 TrackIndex = 0; TrackIndex < NumTracks; ++TrackIndex) { // First time so create rather than update the mesh sections CreateTrackSection(TrackIndex); const float TrackMaxSampleTime = GeometryCache->Tracks[TrackIndex]->GetMaxSampleTime(); Duration = (Duration > TrackMaxSampleTime) ? Duration : TrackMaxSampleTime; } } UpdateLocalBounds(); } void UGeometryCacheComponent::OnUnregister() { IGeometryCacheStreamingManager::Get().RemoveStreamingComponent(this); Super::OnUnregister(); ClearTrackData(); } void UGeometryCacheComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { SCOPE_CYCLE_COUNTER(STAT_GeometryCacheComponent_TickComponent); if (GeometryCache && bRunning && !bManualTick) { // Increase total elapsed time since BeginPlay according to PlayDirection and speed ElapsedTime += (DeltaTime * PlayDirection * GetPlaybackSpeed()); if (ElapsedTime < 0.0f && bLooping) { ElapsedTime += Duration; } // Game thread update: // This mainly just updates the matrix and bounding boxes. All render state (meshes) is done on the render thread bool bUpdatedBoundsOrMatrix = false; for (int32 TrackIndex = 0; TrackIndex < NumTracks; ++TrackIndex) { bUpdatedBoundsOrMatrix |= UpdateTrackSection(TrackIndex); } if (bUpdatedBoundsOrMatrix) { UpdateLocalBounds(); // Mark the transform as dirty, so the bounds are updated and sent to the render thread MarkRenderTransformDirty(); } // The actual current playback speed. The PlaybackSpeed variable contains the speed it would // play back at if it were running regardless of if we're running or not. The renderer // needs the actual playback speed if not a paused animation with explicit motion vectors // would just keep on blurring as if it were moving even when paused. float ActualPlaybackSpeed = (bRunning) ? PlaybackSpeed : 0.0f; // Schedule an update on the render thread if (FGeometryCacheSceneProxy* CastedProxy = static_cast<FGeometryCacheSceneProxy*>(SceneProxy)) { FGeometryCacheSceneProxy* InSceneProxy = CastedProxy; float AnimationTime = GetAnimationTime(); bool bInLooping = IsLooping(); bool bIsPlayingBackwards = IsPlayingReversed(); float InPlaybackSpeed = ActualPlaybackSpeed; ENQUEUE_RENDER_COMMAND(FGeometryCacheUpdateAnimation)( [InSceneProxy, AnimationTime, bInLooping, bIsPlayingBackwards, InPlaybackSpeed, ActualPlaybackSpeed](FRHICommandList& RHICmdList) { InSceneProxy->UpdateAnimation(AnimationTime, bInLooping, bIsPlayingBackwards, InPlaybackSpeed); }); } } } void UGeometryCacheComponent::SetManualTick(bool bInManualTick) { bManualTick = bInManualTick; } bool UGeometryCacheComponent::GetManualTick() const { return bManualTick; } void UGeometryCacheComponent::ResetAnimationTime() { ElapsedTime = 0.0f; } void UGeometryCacheComponent::TickAtThisTime(const float Time, bool bInIsRunning, bool bInBackwards, bool bInIsLooping) { if (bManualTick && GeometryCache && bRunning) { ElapsedTime = Time; // Game thread update: // This mainly just updates the matrix and bounding boxes. All render state (meshes) is done on the render thread bool bUpdatedBoundsOrMatrix = false; for (int32 TrackIndex = 0; TrackIndex < NumTracks; ++TrackIndex) { bUpdatedBoundsOrMatrix |= UpdateTrackSection(TrackIndex); } if (bUpdatedBoundsOrMatrix) { UpdateLocalBounds(); // Mark the transform as dirty, so the bounds are updated and sent to the render thread MarkRenderTransformDirty(); } // The actual current playback speed. The PlaybackSpeed variable contains the speed it would // play back at if it were running regardless of if we're running or not. The renderer // needs the actual playback speed if not a paused animation with explicit motion vectors // would just keep on blurring as if it were moving even when paused. float ActualPlaybackSpeed = (bInIsRunning) ? PlaybackSpeed : 0.0f; // Schedule an update on the render thread if (FGeometryCacheSceneProxy* CastedProxy = static_cast<FGeometryCacheSceneProxy*>(SceneProxy)) { FGeometryCacheSceneProxy* InSceneProxy = CastedProxy; float AnimationTime = Time; float InPlaybackSpeed = ActualPlaybackSpeed; ENQUEUE_RENDER_COMMAND(FGeometryCacheUpdateAnimation)( [InSceneProxy, AnimationTime, bInIsLooping, bInBackwards, InPlaybackSpeed](FRHICommandList& RHICmdList) { InSceneProxy->UpdateAnimation(AnimationTime, bInIsLooping, bInBackwards, InPlaybackSpeed); }); } } } FBoxSphereBounds UGeometryCacheComponent::CalcBounds(const FTransform& LocalToWorld) const { return LocalBounds.TransformBy(LocalToWorld); } /** Update the local bounds of this component based on the bounds of all the tracks in this component. This is used to accelerate CalcBounds above. */ void UGeometryCacheComponent::UpdateLocalBounds() { FBox LocalBox(ForceInit); for (const FTrackRenderData& Section : TrackSections) { // Use World matrix per section for correct bounding box LocalBox += (Section.BoundingBox.TransformBy(Section.Matrix)); } LocalBounds = LocalBox.IsValid ? FBoxSphereBounds(LocalBox) : FBoxSphereBounds(FVector(0, 0, 0), FVector(0, 0, 0), 0); // fall back to reset box sphere bounds // This calls CalcBounds above and finally stores the world bounds in the "Bounds" member variable UpdateBounds(); } FPrimitiveSceneProxy* UGeometryCacheComponent::CreateSceneProxy() { IGeometryCacheStreamingManager::Get().PrefetchData(this); return new FGeometryCacheSceneProxy(this); } #if WITH_EDITOR void UGeometryCacheComponent::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { InvalidateTrackSampleIndices(); MarkRenderStateDirty(); Super::PostEditChangeProperty(PropertyChangedEvent); } #endif int32 UGeometryCacheComponent::GetNumMaterials() const { return GeometryCache ? GeometryCache->Materials.Num() : 0; } UMaterialInterface* UGeometryCacheComponent::GetMaterial(int32 MaterialIndex) const { // If we have a base materials array, use that if (OverrideMaterials.IsValidIndex(MaterialIndex) && OverrideMaterials[MaterialIndex]) { return OverrideMaterials[MaterialIndex]; } // Otherwise get it from the geometry cache else { return GeometryCache ? ( GeometryCache->Materials.IsValidIndex(MaterialIndex) ? GeometryCache->Materials[MaterialIndex] : nullptr) : nullptr; } } void UGeometryCacheComponent::CreateTrackSection(int32 TrackIndex) { // Ensure sections array is long enough if (TrackSections.Num() <= TrackIndex) { TrackSections.SetNum(TrackIndex + 1, false); } UpdateTrackSection(TrackIndex); MarkRenderStateDirty(); // Recreate scene proxy } bool UGeometryCacheComponent::UpdateTrackSection(int32 TrackIndex) { checkf(TrackIndex < TrackSections.Num() && GeometryCache != nullptr && TrackIndex < GeometryCache->Tracks.Num(), TEXT("Invalid SectionIndex") ); UGeometryCacheTrack* Track = GeometryCache->Tracks[TrackIndex]; FTrackRenderData& UpdateSection = TrackSections[TrackIndex]; FMatrix Matrix; FBox TrackBounds; const bool bUpdateMatrix = Track->UpdateMatrixData(GetAnimationTime(), bLooping, UpdateSection.MatrixSampleIndex, Matrix); const bool bUpdateBounds = Track->UpdateBoundsData(GetAnimationTime(), bLooping, (PlayDirection < 0.0f) ? true : false, UpdateSection.BoundsSampleIndex, TrackBounds); if (bUpdateBounds) { UpdateSection.BoundingBox = TrackBounds; } if (bUpdateMatrix) { UpdateSection.Matrix = Matrix; } // Update sections according what is required if (bUpdateMatrix || bUpdateBounds) { return true; } return false; } void UGeometryCacheComponent::OnObjectReimported(UGeometryCache* ImportedGeometryCache) { if (GeometryCache == ImportedGeometryCache) { ReleaseResources(); DetachFence.Wait(); GeometryCache = ImportedGeometryCache; MarkRenderStateDirty(); } } void UGeometryCacheComponent::Play() { bRunning = true; PlayDirection = 1.0f; IGeometryCacheStreamingManager::Get().PrefetchData(this); } void UGeometryCacheComponent::PlayFromStart() { ElapsedTime = 0.0f; bRunning = true; PlayDirection = 1.0f; IGeometryCacheStreamingManager::Get().PrefetchData(this); } void UGeometryCacheComponent::Pause() { bRunning = !bRunning; } void UGeometryCacheComponent::Stop() { bRunning = false; } bool UGeometryCacheComponent::IsPlaying() const { return bRunning; } bool UGeometryCacheComponent::IsLooping() const { return bLooping; } void UGeometryCacheComponent::SetLooping(const bool bNewLooping) { bLooping = bNewLooping; } bool UGeometryCacheComponent::IsPlayingReversed() const { return FMath::IsNearlyEqual( PlayDirection, -1.0f ); } float UGeometryCacheComponent::GetPlaybackSpeed() const { return FMath::Clamp(PlaybackSpeed, 0.0f, 512.0f); } void UGeometryCacheComponent::SetPlaybackSpeed(const float NewPlaybackSpeed) { // Currently only positive play back speeds are supported PlaybackSpeed = FMath::Clamp( NewPlaybackSpeed, 0.0f, 512.0f ); } bool UGeometryCacheComponent::SetGeometryCache(UGeometryCache* NewGeomCache) { // Do nothing if we are already using the supplied geometry cache if (NewGeomCache == GeometryCache) { return false; } // Don't allow changing static meshes if "static" and registered AActor* Owner = GetOwner(); if (!AreDynamicDataChangesAllowed() && Owner != nullptr) { FMessageLog("PIE").Warning(FText::Format(LOCTEXT("SetGeometryCache", "Calling SetGeometryCache on '{0}' but Mobility is Static."), FText::FromString(GetPathName()))); return false; } ReleaseResources(); DetachFence.Wait(); GeometryCache = NewGeomCache; ClearTrackData(); SetupTrackData(); // This will cause us to prefetch the new data which is needed by the render state creation IGeometryCacheStreamingManager::Get().PrefetchData(this); // Need to send this to render thread at some point MarkRenderStateDirty(); // Update physics representation right away RecreatePhysicsState(); // Update this component streaming data. IStreamingManager::Get().NotifyPrimitiveUpdated(this); // Since we have new tracks, we need to update bounds UpdateBounds(); return true; } UGeometryCache* UGeometryCacheComponent::GetGeometryCache() const { return GeometryCache; } float UGeometryCacheComponent::GetStartTimeOffset() const { return StartTimeOffset; } void UGeometryCacheComponent::SetStartTimeOffset(const float NewStartTimeOffset) { StartTimeOffset = NewStartTimeOffset; MarkRenderStateDirty(); } float UGeometryCacheComponent::GetAnimationTime() const { const float ClampedStartTimeOffset = FMath::Clamp(StartTimeOffset, -14400.0f, 14400.0f); return ElapsedTime + ClampedStartTimeOffset; } float UGeometryCacheComponent::GetPlaybackDirection() const { return PlayDirection; } float UGeometryCacheComponent::GetDuration() const { return Duration; } void UGeometryCacheComponent::PlayReversedFromEnd() { ElapsedTime = Duration; PlayDirection = -1.0f; bRunning = true; IGeometryCacheStreamingManager::Get().PrefetchData(this); } void UGeometryCacheComponent::PlayReversed() { PlayDirection = -1.0f; bRunning = true; IGeometryCacheStreamingManager::Get().PrefetchData(this); } void UGeometryCacheComponent::InvalidateTrackSampleIndices() { for (FTrackRenderData& Track : TrackSections) { Track.MatrixSampleIndex = -1; Track.BoundsSampleIndex = -1; } } void UGeometryCacheComponent::ReleaseResources() { GeometryCache = nullptr; NumTracks = 0; TrackSections.Empty(); DetachFence.BeginFence(); } int32 UGeometryCacheComponent::GetFrameAtTime(const float Time) const { const float FrameTime = GetNumberOfFrames() > 1 ? Duration / (float)(GetNumberOfFrames() - 1) : 0.0f; const int32 NormalizedFrame = FMath::Clamp(FMath::RoundToInt(Time / FrameTime), 0, GetNumberOfFrames() - 1); const int32 StartFrame = GeometryCache != nullptr ? GeometryCache->GetStartFrame() : 0; return StartFrame + NormalizedFrame; // } float UGeometryCacheComponent::GetTimeAtFrame(const int32 Frame) const { const float FrameTime = GetNumberOfFrames() > 1 ? Duration / (float)(GetNumberOfFrames() - 1) : 0.0f; const int32 StartFrame = GeometryCache != nullptr ? GeometryCache->GetStartFrame() : 0; return FMath::Clamp(FrameTime * (Frame - StartFrame), 0.0f, Duration); } int32 UGeometryCacheComponent::GetNumberOfFrames() const { if (GeometryCache) { return GeometryCache->GetEndFrame() - GeometryCache->GetStartFrame() + 1; } return 0; } #if WITH_EDITOR void UGeometryCacheComponent::PreEditUndo() { InvalidateTrackSampleIndices(); MarkRenderStateDirty(); } void UGeometryCacheComponent::PostEditUndo() { InvalidateTrackSampleIndices(); MarkRenderStateDirty(); } #endif #undef LOCTEXT_NAMESPACE
28.879377
168
0.744139
greenrainstudios
b49d4eb424dba7825b4fdd66b6bf10b611d14eef
12,688
cpp
C++
kernel/vds_network/udp_socket.cpp
iv-soft/vds
8baea0831fe4aff7815d63f8a1df8491d5620678
[ "MIT" ]
null
null
null
kernel/vds_network/udp_socket.cpp
iv-soft/vds
8baea0831fe4aff7815d63f8a1df8491d5620678
[ "MIT" ]
null
null
null
kernel/vds_network/udp_socket.cpp
iv-soft/vds
8baea0831fe4aff7815d63f8a1df8491d5620678
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "udp_socket.h" #include "private/udp_socket_p.h" vds::udp_datagram::udp_datagram() : impl_(nullptr) { } vds::udp_datagram::udp_datagram(const udp_datagram& other) : impl_(new _udp_datagram(*other.impl_)){ } vds::udp_datagram::udp_datagram(udp_datagram && other) : impl_(other.impl_) { other.impl_ = nullptr; } vds::udp_datagram::udp_datagram(vds::_udp_datagram* impl) : impl_(impl) { } vds::udp_datagram::udp_datagram( const network_address & address, const void* data, size_t data_size) : impl_(new _udp_datagram(address, data, data_size)) { } vds::udp_datagram::udp_datagram( const network_address & address, const const_data_buffer & data) : impl_(new _udp_datagram(address, data)) { } vds::udp_datagram::~udp_datagram() { delete this->impl_; } vds::network_address vds::udp_datagram::address() const { return this->impl_->address(); } //void vds::udp_datagram::reset(const std::string & server, uint16_t port, const void * data, size_t data_size, bool check_max_safe_data_size /*= true*/) //{ // if (check_max_safe_data_size && max_safe_data_size < data_size) { // return vds::make_unexpected<std::runtime_error>("Data too long"); // } // // this->impl_.reset(new _udp_datagram(server, port, data, data_size)); //} const uint8_t * vds::udp_datagram::data() const { return this->impl_->data(); } size_t vds::udp_datagram::data_size() const { return this->impl_ ? this->impl_->data_size() : 0; } vds::udp_datagram& vds::udp_datagram::operator=(const udp_datagram& other) { delete this->impl_; this->impl_ = new _udp_datagram(*other.impl_); return *this; } vds::udp_datagram& vds::udp_datagram::operator=(udp_datagram&& other) { if (this != &other) { delete this->impl_; this->impl_ = other.impl_; other.impl_ = nullptr; } return *this; } vds::udp_socket::udp_socket() { } vds::udp_socket::~udp_socket() { delete this->impl_; } sa_family_t vds::udp_socket::family() const { return this->impl_->family(); } #ifdef _WIN32 vds::expected<void> vds::udp_socket::start(const service_provider * sp, lambda_holder_t<async_task<expected<bool>>, expected<udp_datagram>> read_handler) { auto reader = new _udp_receive(sp, this->shared_from_this(), std::move(read_handler)); reader->schedule_read(); return expected<void>(); } vds::async_task<vds::expected<void>> vds::udp_socket::write_async(const service_provider* sp, const udp_datagram& message) { return std::make_shared<_udp_send>(sp, this->shared_from_this())->write_async(message); } #else//_WIN32 vds::expected<void> vds::udp_socket::start(const service_provider * sp, lambda_holder_t<async_task<expected<bool>>, expected<udp_datagram>> read_handler) { return this->impl_->start(sp, this->shared_from_this(), std::move(read_handler)); } vds::expected<void> vds::_udp_socket::start( const vds::service_provider *sp, const std::shared_ptr<vds::socket_base> &owner, lambda_holder_t<async_task<expected<bool>>, expected<udp_datagram>> read_handler) { auto read_task = std::make_shared<_udp_receive>(sp, owner, std::move(read_handler)); this->read_task_ = read_task; CHECK_EXPECTED(read_task->schedule_read()); return vds::expected<void>(); } vds::async_task<vds::expected<void>> vds::udp_socket::write_async(const service_provider* sp, const udp_datagram& message) { return this->impl_->write_async(this->shared_from_this(), message); } #endif void vds::udp_socket::stop() { this->impl_->close(); } vds::expected<std::shared_ptr<vds::udp_socket>> vds::udp_socket::create( const service_provider * sp, sa_family_t af) { #ifdef _WIN32 auto s = WSASocket(af, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, WSA_FLAG_OVERLAPPED); if (INVALID_SOCKET == s) { auto error = WSAGetLastError(); return vds::make_unexpected<std::system_error>(error, std::system_category(), "create socket"); } /*************************************************************/ /* Allow socket descriptor to be reuseable */ /*************************************************************/ int on = 1; if (0 > setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on))) { auto error = errno; ::close(s); return vds::make_unexpected<std::system_error>(error, std::system_category(), "Allow socket descriptor to be reuseable"); } if (af == AF_INET6) { int no = 0; if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&no, sizeof(no)) < 0) { auto error = WSAGetLastError(); ::close(s); return vds::make_unexpected<std::system_error>(error, std::system_category(), "set IPV6_V6ONLY=0"); } } CHECK_EXPECTED((*sp->get<network_service>())->associate(s)); #else auto s = socket(af, SOCK_DGRAM, IPPROTO_UDP); if (0 > s) { auto error = errno; return vds::make_unexpected<std::system_error>(error, std::system_category(), "create socket"); } /*************************************************************/ /* Allow socket descriptor to be reuseable */ /*************************************************************/ int on = 1; if (0 > setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) { auto error = errno; ::close(s); return vds::make_unexpected<std::system_error>(error, std::system_category(), "Allow socket descriptor to be reuseable"); } /*************************************************************/ /* Set socket to be nonblocking. All of the sockets for */ /* the incoming connections will also be nonblocking since */ /* they will inherit that state from the listening socket. */ /*************************************************************/ if (0 > ioctl(s, FIONBIO, (char *)&on)) { auto error = errno; ::close(s); return vds::make_unexpected<std::system_error>(error, std::system_category(), "Set socket to be nonblocking"); } if (af == AF_INET6) { int no = 0; if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&no, sizeof(no)) < 0) { auto error = errno; ::close(s); return vds::make_unexpected<std::system_error>(error, std::system_category(), "set IPV6_V6ONLY=0"); } } #endif return std::shared_ptr<udp_socket>(new udp_socket(new _udp_socket(sp, s, af))); } vds::expected<void> vds::udp_socket::join_membership(sa_family_t af, const std::string & group_address) { if (AF_INET6 == af) { struct ipv6_mreq group; group.ipv6mr_interface = 0; if (0 > inet_pton(AF_INET6, group_address.c_str(), &group.ipv6mr_multiaddr)) { int error = errno; return make_unexpected<std::system_error>(error, std::generic_category(), "parse address " + group_address); } //int ifidx = 0; //if (setsockopt((*this)->handle(), IPPROTO_IPV6, IPV6_MULTICAST_IF, (const char*)&ifidx, sizeof(ifidx))) { // int error = errno; // return make_unexpected<std::system_error>(error, std::generic_category(), "set multicast interface"); //} int loopBack = 0; if (0 > setsockopt((*this)->handle(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (const char*)&loopBack, sizeof(loopBack))) { int error = errno; return make_unexpected<std::system_error>(error, std::generic_category(), "set multicast loop"); } int mcastTTL = 1; if (0 > setsockopt((*this)->handle(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (const char*)&mcastTTL, sizeof(mcastTTL))) { int error = errno; return make_unexpected<std::system_error>(error, std::generic_category(), "set multicast hops"); } if (0 > setsockopt((*this)->handle(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (const char *)&group, sizeof group)) { int error = errno; return make_unexpected<std::system_error>(error, std::generic_category(), "IPV6_ADD_MEMBERSHIP " + group_address); } } else { int broadcast = 1; if (setsockopt((*this)->handle(), SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)) < 0) { int error = errno; return make_unexpected<std::system_error>(error, std::generic_category(), "set broadcast " + group_address); } } return expected<void>(); } vds::expected<void> vds::udp_socket::broadcast(sa_family_t af, const std::string & group_address, u_short port, const const_data_buffer & message) { if (AF_INET6 == af) { struct sockaddr_in6 address = { AF_INET6, htons(port) }; if (0 > inet_pton(AF_INET6, group_address.c_str(), &address.sin6_addr)) { int error = errno; return make_unexpected<std::system_error>(error, std::generic_category(), "parse address " + group_address); } if (sendto((*this)->handle(), (const char *)message.data(), message.size(), 0, (struct sockaddr*)&address, sizeof(address)) < 0) { int error = errno; return make_unexpected<std::system_error>(error, std::generic_category(), "sendto"); } } else { struct sockaddr_in address; address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = INADDR_BROADCAST; if(sendto((*this)->handle(), (const char *)message.data(), message.size(), 0, (sockaddr *)&address, sizeof(address)) < 0) { #ifdef _WIN32 const auto error = WSAGetLastError(); return make_unexpected<std::system_error>(error, std::system_category(), "sendto"); #else const auto error = errno; return make_unexpected<std::system_error>(error, std::generic_category(), "sendto"); #endif } } return expected<void>(); } #ifndef _WIN32 vds::expected<void> vds::udp_socket::process(uint32_t events) { return this->impl_->process(this->shared_from_this(), events); } vds::expected<void> vds::_udp_socket::process_write(const std::shared_ptr<socket_base> & owner) { std::unique_lock<std::mutex> lock(this->event_masks_mutex_); auto& item = this->write_tasks_.front(); auto size = item.first->data_size(); int len = sendto( this->handle(), item.first->data(), size, 0, item.first->address(), item.first->address().size()); auto result = std::move(item.second); if (len < 0) { int error = errno; if (EAGAIN == error) { return expected<void>(); } CHECK_EXPECTED(this->change_mask_(owner, 0, EPOLLOUT)); this->sp_->get<logger>()->trace( "UDP", "Error %d at sending UDP to %s", error, item.first->address().to_string().c_str()); auto address = item.first->address().to_string(); result->set_value(make_unexpected<std::system_error>( error, std::generic_category(), "Send to " + address)); this->write_tasks_.pop(); } else { CHECK_EXPECTED(this->change_mask(owner, 0, EPOLLOUT)); this->sp_->get<logger>()->trace( "UDP", "Sent %d bytes UDP package to %s", item.first->data_size(), item.first->address().to_string().c_str()); if ((size_t)len != size) { result->set_value(make_unexpected<std::runtime_error>("Invalid send UDP")); } else { result->set_value(expected<void>()); } } return expected<void>(); } vds::expected<void> vds::_udp_socket::process(const std::shared_ptr<socket_base>& owner, uint32_t events) { if (EPOLLOUT == (EPOLLOUT & events)) { if (0 == (this->event_masks_ & EPOLLOUT)) { return vds::make_unexpected<std::runtime_error>("Invalid state"); } CHECK_EXPECTED(this->process_write(owner)); } if (EPOLLIN == (EPOLLIN & events)) { if (0 == (this->event_masks_ & EPOLLIN)) { return vds::make_unexpected<std::runtime_error>("Invalid state"); } CHECK_EXPECTED(this->read_task_->process()); } return expected<void>(); } #endif//_WIN32 vds::udp_server::udp_server() : impl_(nullptr) { } vds::udp_server::~udp_server() { delete this->impl_; } vds::expected<void> vds::udp_server::start( const service_provider * sp, const network_address & address, lambda_holder_t<async_task<expected<bool>>, expected<udp_datagram>> read_handler) { vds_assert(nullptr == this->impl_); this->impl_ = new _udp_server(address); return this->impl_->start(sp, std::move(read_handler)); } void vds::udp_server::stop() { if (nullptr != this->impl_) { this->impl_->stop(); delete this->impl_; this->impl_ = nullptr; } } const std::shared_ptr<vds::udp_socket> &vds::udp_server::socket() const { return this->impl_->socket(); } const vds::network_address& vds::udp_server::address() const { return this->impl_->address(); } vds::async_task<vds::expected<void>> vds::udp_server::write_async(const service_provider* sp, const udp_datagram& message) { return this->impl_->write_async(sp, message); } void vds::udp_server::prepare_to_stop() { this->impl_->prepare_to_stop(); }
30.066351
153
0.653373
iv-soft
b49f3438e5b7e406c9d3e3626969d6b45956e5b0
928
hpp
C++
pythran/pythonic/numpy/sum.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/sum.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/sum.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_NUMPY_SUM_HPP #define PYTHONIC_NUMPY_SUM_HPP #include "pythonic/include/numpy/sum.hpp" #include "pythonic/utils/proxy.hpp" #include "pythonic/numpy/reduce.hpp" #ifdef USE_BOOST_SIMD #include <boost/simd/include/functions/sum.hpp> #endif #include <algorithm> namespace pythonic { namespace numpy { template <class E> auto sum(E &&e) -> decltype(reduce<operator_::proxy::iadd>(std::forward<E>(e))) { return reduce<operator_::proxy::iadd>(std::forward<E>(e)); } template <class E, class Opt> auto sum(E &&e, Opt &&opt) -> decltype(reduce<operator_::proxy::iadd>(std::forward<E>(e), std::forward<Opt>(opt))) { return reduce<operator_::proxy::iadd>(std::forward<E>(e), std::forward<Opt>(opt)); } PROXY_IMPL(pythonic::numpy, sum); } } #endif
22.095238
75
0.592672
artas360
b4a80f8d8083ea0aad624723d8e217bd98d80f0c
854
hpp
C++
listener.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
1
2019-07-19T03:37:33.000Z
2019-07-19T03:37:33.000Z
listener.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
null
null
null
listener.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
null
null
null
#include "common.h" #ifndef __WRAP_LISTENER_H__ #define __WRAP_LISTENER_H__ #ifdef __cplusplus extern "C" { #endif DLL_PUBLIC listener_t* listener_set(alure::Listener ctx); DLL_PUBLIC void listener_destroy(listener_t* dm); DLL_PUBLIC void listener_setGain(listener_t* dm, ALfloat gain); DLL_PUBLIC void listener_set3DParameters(listener_t* dm, const alureVector3_t* position, const alureVector3_t* velocity, const alureOrientation_t* orientation); DLL_PUBLIC void listener_setPosition(listener_t* dm, const alureVector3_t* position); DLL_PUBLIC void listener_setVelocity(listener_t* dm, const alureVector3_t* velocity); DLL_PUBLIC void listener_setOrientation(listener_t* dm, const alureOrientation_t* orientation); DLL_PUBLIC void listener_setMetersPerUnit(listener_t* dm, ALfloat m_u); #ifdef __cplusplus } #endif #endif /* __WRAP_LISTENER_H__ */
34.16
160
0.82904
LAGonauta
b4ac1ea8256a3905dfb93005d0a35643e94ac152
863
hpp
C++
src/leaker/global.hpp
tigrangh/leaker
cb07f22184e5d58bc2abdd41b68800106c59baa9
[ "MIT" ]
null
null
null
src/leaker/global.hpp
tigrangh/leaker
cb07f22184e5d58bc2abdd41b68800106c59baa9
[ "MIT" ]
null
null
null
src/leaker/global.hpp
tigrangh/leaker
cb07f22184e5d58bc2abdd41b68800106c59baa9
[ "MIT" ]
null
null
null
#pragma once #if defined _MSC_VER #define B_OS_WINDOWS #define UNICODE #define _UNICODE #ifdef BUILD_SHARED_LIBS #define LEAKER_EXPORT __declspec(dllexport) #define LEAKER_IMPORT __declspec(dllimport) #else #define LEAKER_EXPORT #define LEAKER_IMPORT #endif #define LEAKER_LOCAL #elif defined __APPLE__ #define B_OS_MACOS #ifdef BUILD_SHARED_LIBS #define LEAKER_EXPORT __attribute__ ((visibility ("default"))) #define LEAKER_IMPORT #define LEAKER_LOCAL __attribute__ ((visibility ("hidden"))) #else #define LEAKER_EXPORT #define LEAKER_IMPORT #define LEAKER_LOCAL #endif #else #define B_OS_LINUX #ifdef BUILD_SHARED_LIBS #define LEAKER_EXPORT __attribute__ ((visibility ("default"))) #define LEAKER_IMPORT #define LEAKER_LOCAL __attribute__ ((visibility ("hidden"))) #else #define LEAKER_EXPORT #define LEAKER_IMPORT #define LEAKER_LOCAL #endif #endif
17.979167
62
0.811124
tigrangh
b4ac6674a8b36d8f121188d42dc1c55b2ac1d2c7
2,856
cc
C++
cpp/src/ray/runtime/task/native_task_submitter.cc
lharri73/ray
3e42f54910ee8fecdd09a9a69e4852d6fb946e6d
[ "Apache-2.0" ]
null
null
null
cpp/src/ray/runtime/task/native_task_submitter.cc
lharri73/ray
3e42f54910ee8fecdd09a9a69e4852d6fb946e6d
[ "Apache-2.0" ]
53
2021-10-09T07:09:35.000Z
2022-03-19T07:09:08.000Z
cpp/src/ray/runtime/task/native_task_submitter.cc
akern40/ray
d4f9d3620eecefeffc890ecf5193582bf667512e
[ "Apache-2.0" ]
null
null
null
// Copyright 2020-2021 The Ray Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 "native_task_submitter.h" #include <ray/api/ray_exception.h> #include "../abstract_ray_runtime.h" namespace ray { namespace api { RayFunction BuildRayFunction(InvocationSpec &invocation) { auto function_descriptor = FunctionDescriptorBuilder::BuildCpp( invocation.remote_function_holder.function_name); return RayFunction(ray::Language::CPP, function_descriptor); } ObjectID NativeTaskSubmitter::Submit(InvocationSpec &invocation) { auto &core_worker = CoreWorkerProcess::GetCoreWorker(); std::vector<ObjectID> return_ids; if (invocation.task_type == TaskType::ACTOR_TASK) { core_worker.SubmitActorTask(invocation.actor_id, BuildRayFunction(invocation), invocation.args, TaskOptions(), &return_ids); } else { core_worker.SubmitTask(BuildRayFunction(invocation), invocation.args, TaskOptions(), &return_ids, 1, std::make_pair(PlacementGroupID::Nil(), -1), true, ""); } return return_ids[0]; } ObjectID NativeTaskSubmitter::SubmitTask(InvocationSpec &invocation) { return Submit(invocation); } ActorID NativeTaskSubmitter::CreateActor(InvocationSpec &invocation) { auto &core_worker = CoreWorkerProcess::GetCoreWorker(); std::unordered_map<std::string, double> resources; std::string name = ""; std::string ray_namespace = ""; ActorCreationOptions actor_options{0, 0, 1, resources, resources, {}, /*is_detached=*/false, name, ray_namespace, /*is_asyncio=*/false}; ActorID actor_id; auto status = core_worker.CreateActor(BuildRayFunction(invocation), invocation.args, actor_options, "", &actor_id); if (!status.ok()) { throw RayException("Create actor error"); } return actor_id; } ObjectID NativeTaskSubmitter::SubmitActorTask(InvocationSpec &invocation) { return Submit(invocation); } } // namespace api } // namespace ray
36.151899
88
0.634454
lharri73
b4b031b7e3918a6a4dfce0fba57a8cb0b5361691
5,342
cpp
C++
1001-1500/1044-longest-duplicate-string/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
1001-1500/1044-longest-duplicate-string/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
1001-1500/1044-longest-duplicate-string/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
// Well, this does a TLE. But it shoould work! #include <iostream> #include <string> #include <unordered_map> #include <vector> class Solution { public: std::string longestDupSubstring(const std::string& s) { if (s.size() <= 1) { return ""; } if (s.size() == 2) { if (s.at(0) == s.at(1)) { return s.substr(0, 1); } return ""; } return iter(s, 0, s.size()); } private: // Find the answer that is of length [l1, l2). std::string iter(const std::string& s, size_t l1, size_t l2) { const size_t len = (l1 + l2) / 2; if (len == 0) { return ""; } std::unordered_map<long long, size_t> hashes; // hashes[<hash>] = ind <-> <hash> is the hash of s[ind:ind+len] std::pair<bool, size_t> found = { false, 0 }; // { has answer been found, starting index of the answer } long long prev_hash = computeHash(s, len); hashes.insert({ prev_hash, 0 }); for (size_t ii = len; ii < s.size(); ++ii) { const long long next_hash = computeHash(s, len, prev_hash, ii); if (hashes.count(next_hash) != 0) { const size_t ind1 = hashes.at(next_hash), ind2 = ii - len + 1; bool is_ok = true; for (size_t jj = 0; jj < len && is_ok; ++jj) { if (s.at(ind1 + jj) != s.at(ind2 + jj)) { is_ok = false; } } if (is_ok) { found = { true, ind1 }; break; } } hashes.insert({ next_hash, ii - len + 1 }); prev_hash = next_hash; } if (l1 == l2 - 1) { return found.first ? s.substr(found.second, len) : ""; } if (found.first) { std::string try_longer = iter(s, len, l2); return (try_longer != "") ? try_longer : s.substr(found.second, len); } return iter(s, l1, len); } // Take the hash of the first len characters long long computeHash(const std::string& s, size_t len = SIZE_MAX) { long long hash = 0; long long p_pow = 1; len = std::min(len, s.size()); for (size_t ii = 0; ii < len; ++ii) { const char c = s.at(ii); hash = (hash + (c - 'a' + 1) * p_pow) % _m; p_pow = (p_pow * _p) % _m; } return hash; } // prev_hash == computeHash(s[to_add-len:to_add]). // This will compute computeHash(s[to_add-len+1:to_add+1]) by adding s[to_add] into prev_hash. long long computeHash(const std::string& s, size_t len, long long prev_hash, size_t to_add) { prev_hash = (prev_hash - (s.at(to_add - len) - 'a' + 1)) % _m; prev_hash = (prev_hash * _p_inv) % _m; long long next_term = (s.at(to_add) - 'a' + 1); for (size_t ii = 0; ii < len - 1; ++ii) { next_term = (next_term * _p) % _m; } return (prev_hash + next_term) % _m; } static constexpr int _p = 31; static constexpr int _m = 1e9 + 9; static constexpr int _p_inv = 838709685; }; int main() { const std::string s = // "banana"; // "peftxylsseopntszwuwrugksyrizvatuwgiarugnmypheecnproenzyksusehuujvnpqwwqnuhdogeqnfnhdbhatcuaaniteuwhsmpmrzfxekstssaynzzvmqwdhwtnizwiejjkfovscneouvjsljzfkmtrhunaxgcaswfajczlnhacsajozjwpoqjtdcaqsubbntxlpayebjfbzjiaoiyjbmzktcnscxyhpdkfexnjfrngjesbtwnmasnwvauzlzkompxkgifxsavzfhwvdjausccrjfpnzordyfgjdyawqzbfbizqvecrbhupkdudvxdknkqwjynyrutzhcnmfabwwaerdirsnufhlktojnyrefumfhvkolrybjpadpowjoqhhbzqpmpcmrddtrplgezihshtvpnqxikgsiiqnmezybjzktpdzsmribdkvlfbvicrgnblqnaylcijqbxjcnmjdrsfpcdojwcanvkgfaappivqnocobyeavoifqgnroagelmfjprxkupbdrwnycnhffgchclumhpxnlbbbmfsjmqoxuwkzwwksraxhlvdvrnjmfqzdksnxyhbaquxidvlgpjhlskrvkbsizyfedhwqsrzlwkesslvduwksoreufeflbgodatiblhmmfeiwbtohurgprremycvkhecakofsmpiimdcecpcvuseiqkxifzktkfnaqnpshcfdrhgjalpwaqumixmrxwduhgxwtfxarwyfshsutxihpecwbgzghkfaukdfbyecpryqxooyjsurjstfwrpegyxtdbkoicorqe"; // "zxcvdqkfawuytt"; "djpqwlrroqeuwwqgxnvdftzgsgnmpnhnhezixyhlydjjekpeczwtguowubfjsyohxaihmbjzfchmbnppouguvklmiaqkgomqzvvfubklwexbnzbdkvtxjnpzmfdgomvvsekluemjqaatkbhklusgxbezjghoddwcmirwrnnsgzjzwrnfyqgjylzgwhwipinohhzkywikevsqurnirnmmkgwpgvdswttwpingslbzxzsodqvlluqetfzfzbdhilaugrxewhomtwzjyldxzwtxmufbcrxtqfpcqscbbstplqczhumhedcmmgfkhdyetexcyrlvdrkgxzsncrpoomtqwnwozbteedjozikggwkbexbibruqdpekpjpzzymxpvtsderhjwxvyfahximykcndxskcjwewnfcbvymijwkrisjtzyiegysxpyfdrblxjquytzgvajmdvylemhqcctivjzmkdojbpvucgswycfnjkyoqvzlufphsrvhcbkxamqmaoveycykirpboguhrimemgkkbdmkyvalkpmktlkhwtaafuphdksucgianjkyztzyrndfjhkemdlgnmbucmqqyvjmzqlmgerhvzdtbjsagisjsqnrzqlmimtxumlngktcptgpcevpybghuycisxbemgpwptokdqvzp"; // "uirqkccmgnpbqwfkmplmfovxkjtgxbhwzqdlydunpuzxgvodnaanxpdiuhbitfllitaufvcmtneqmvibimvxmzvysignmsfykppdktpfhhcayfcwcrtjsgnyvzytevlqfabpjwxvjtfksztmdtrzgagdjtpeozzxppnkdbjayfbxqrqaefkcdbuvteobztucgdbcmlgnxldcwtzkvhwqxbsqlbsrbvesemhnbswssqvbiketdewfauvtzmyzrrqslzagjcyuznkpkgpkkinldxcjtuoumcbcttabfuzjbtoqjqbpnsemojbtctvdmobnuutcsfmhkrbwkmpdcdncqizgtlqekvqophqxewkpxpkrgjivrtarxtwbbfhfikbrdwohppyiyyztopksdmxvqiaafswyjfnlwntldwniypzaxrscyqfrlqehqgzaxxazfwtwjajsrmwuerdqklhwoqxptcvqoqbjwfqrewirtcbskmkaqgtcnxnsqmwgwjxruhyyjtbuivvepnxiwjmtlrvexjzevctflajibxkvmbzdfwoqobmhstgpshtxitwttpkdvfmfwtwsazfgzwbtmqrowrcesyyeuwunodesrzbmjbxnchaqptfgqlknuarhgnsbwnucdhckpbwhtwhejivrmuccbwnyenyvonquscneswngwbkjysxvdwbzymwxcrnexrxhmuwvycmsiazmqavgmyurbcmvdjplloidbzacunerwobvaxsromiiwzqxnrsjpyoacfxcmmogmokhpmhxzkdzmpjcrgaeihdhczrmxmfurjatuwxriiwtfojwvkkybcdmwayhnzrnqrynwtrvmtgtrxndlbtlhyzfjtbtvqujjuwpibuonuwjdfvnhdqqzlmwwheztjkrrzrroogovapywxkjsccjnseanhxijybintgbjwlkmdzuoeclfqatffgjvcbujovunnauprhoocxzghzvsmuyhsl"; Solution soln; std::cout << soln.longestDupSubstring(s) << std::endl; }
45.271186
1,008
0.777424
janreggie
b4b42cc225e39ebdb7795d0a7565331bc17a87b6
4,233
cpp
C++
src/bench/chacha_poly_aead.cpp
devcoin/devcoin
a5a65936e31a63041434f3fce31270c518d44ebc
[ "MIT" ]
null
null
null
src/bench/chacha_poly_aead.cpp
devcoin/devcoin
a5a65936e31a63041434f3fce31270c518d44ebc
[ "MIT" ]
null
null
null
src/bench/chacha_poly_aead.cpp
devcoin/devcoin
a5a65936e31a63041434f3fce31270c518d44ebc
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2020 The Bitcoin Core and Devcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <crypto/chacha_poly_aead.h> #include <crypto/poly1305.h> // for the POLY1305_TAGLEN constant #include <hash.h> #include <assert.h> #include <limits> /* Number of bytes to process per iteration */ static constexpr uint64_t BUFFER_SIZE_TINY = 64; static constexpr uint64_t BUFFER_SIZE_SMALL = 256; static constexpr uint64_t BUFFER_SIZE_LARGE = 1024 * 1024; static const unsigned char k1[32] = {0}; static const unsigned char k2[32] = {0}; static ChaCha20Poly1305AEAD aead(k1, 32, k2, 32); static void CHACHA20_POLY1305_AEAD(benchmark::Bench& bench, size_t buffersize, bool include_decryption) { std::vector<unsigned char> in(buffersize + CHACHA20_POLY1305_AEAD_AAD_LEN + POLY1305_TAGLEN, 0); std::vector<unsigned char> out(buffersize + CHACHA20_POLY1305_AEAD_AAD_LEN + POLY1305_TAGLEN, 0); uint64_t seqnr_payload = 0; uint64_t seqnr_aad = 0; int aad_pos = 0; uint32_t len = 0; bench.batch(buffersize).unit("byte").run([&] { // encrypt or decrypt the buffer with a static key const bool crypt_ok_1 = aead.Crypt(seqnr_payload, seqnr_aad, aad_pos, out.data(), out.size(), in.data(), buffersize, true); assert(crypt_ok_1); if (include_decryption) { // if we decrypt, include the GetLength const bool get_length_ok = aead.GetLength(&len, seqnr_aad, aad_pos, in.data()); assert(get_length_ok); const bool crypt_ok_2 = aead.Crypt(seqnr_payload, seqnr_aad, aad_pos, out.data(), out.size(), in.data(), buffersize, true); assert(crypt_ok_2); } // increase main sequence number seqnr_payload++; // increase aad position (position in AAD keystream) aad_pos += CHACHA20_POLY1305_AEAD_AAD_LEN; if (aad_pos + CHACHA20_POLY1305_AEAD_AAD_LEN > CHACHA20_ROUND_OUTPUT) { aad_pos = 0; seqnr_aad++; } if (seqnr_payload + 1 == std::numeric_limits<uint64_t>::max()) { // reuse of nonce+key is okay while benchmarking. seqnr_payload = 0; seqnr_aad = 0; aad_pos = 0; } }); } static void CHACHA20_POLY1305_AEAD_64BYTES_ONLY_ENCRYPT(benchmark::Bench& bench) { CHACHA20_POLY1305_AEAD(bench, BUFFER_SIZE_TINY, false); } static void CHACHA20_POLY1305_AEAD_256BYTES_ONLY_ENCRYPT(benchmark::Bench& bench) { CHACHA20_POLY1305_AEAD(bench, BUFFER_SIZE_SMALL, false); } static void CHACHA20_POLY1305_AEAD_1MB_ONLY_ENCRYPT(benchmark::Bench& bench) { CHACHA20_POLY1305_AEAD(bench, BUFFER_SIZE_LARGE, false); } static void CHACHA20_POLY1305_AEAD_64BYTES_ENCRYPT_DECRYPT(benchmark::Bench& bench) { CHACHA20_POLY1305_AEAD(bench, BUFFER_SIZE_TINY, true); } static void CHACHA20_POLY1305_AEAD_256BYTES_ENCRYPT_DECRYPT(benchmark::Bench& bench) { CHACHA20_POLY1305_AEAD(bench, BUFFER_SIZE_SMALL, true); } static void CHACHA20_POLY1305_AEAD_1MB_ENCRYPT_DECRYPT(benchmark::Bench& bench) { CHACHA20_POLY1305_AEAD(bench, BUFFER_SIZE_LARGE, true); } // Add Hash() (dbl-sha256) bench for comparison static void HASH(benchmark::Bench& bench, size_t buffersize) { uint8_t hash[CHash256::OUTPUT_SIZE]; std::vector<uint8_t> in(buffersize,0); bench.batch(in.size()).unit("byte").run([&] { CHash256().Write(in).Finalize(hash); }); } static void HASH_64BYTES(benchmark::Bench& bench) { HASH(bench, BUFFER_SIZE_TINY); } static void HASH_256BYTES(benchmark::Bench& bench) { HASH(bench, BUFFER_SIZE_SMALL); } static void HASH_1MB(benchmark::Bench& bench) { HASH(bench, BUFFER_SIZE_LARGE); } BENCHMARK(CHACHA20_POLY1305_AEAD_64BYTES_ONLY_ENCRYPT); BENCHMARK(CHACHA20_POLY1305_AEAD_256BYTES_ONLY_ENCRYPT); BENCHMARK(CHACHA20_POLY1305_AEAD_1MB_ONLY_ENCRYPT); BENCHMARK(CHACHA20_POLY1305_AEAD_64BYTES_ENCRYPT_DECRYPT); BENCHMARK(CHACHA20_POLY1305_AEAD_256BYTES_ENCRYPT_DECRYPT); BENCHMARK(CHACHA20_POLY1305_AEAD_1MB_ENCRYPT_DECRYPT); BENCHMARK(HASH_64BYTES); BENCHMARK(HASH_256BYTES); BENCHMARK(HASH_1MB);
33.330709
135
0.72927
devcoin
b4b4650636f32cfc5189cf62e03fba2d8b5db3a3
6,874
hpp
C++
libs/full/async_colocated/include/hpx/async_colocated/async_colocated.hpp
gonidelis/hpx
8f608a97ae4f765cb8fdd166b478097267d65c4b
[ "BSL-1.0" ]
null
null
null
libs/full/async_colocated/include/hpx/async_colocated/async_colocated.hpp
gonidelis/hpx
8f608a97ae4f765cb8fdd166b478097267d65c4b
[ "BSL-1.0" ]
null
null
null
libs/full/async_colocated/include/hpx/async_colocated/async_colocated.hpp
gonidelis/hpx
8f608a97ae4f765cb8fdd166b478097267d65c4b
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2015 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under 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) #pragma once #include <hpx/config.hpp> #include <hpx/actions_base/actions_base_support.hpp> #include <hpx/actions_base/traits/extract_action.hpp> #include <hpx/agas/primary_namespace.hpp> #include <hpx/agas/server/primary_namespace.hpp> #include <hpx/assert.hpp> #include <hpx/async_colocated/async_colocated_fwd.hpp> #include <hpx/async_distributed/async_continue_fwd.hpp> #include <hpx/async_local/async_fwd.hpp> #include <hpx/datastructures/tuple.hpp> #include <hpx/functional/bind.hpp> #include <hpx/functional/unique_function.hpp> #include <hpx/futures/future.hpp> #include <hpx/futures/traits/promise_local_result.hpp> #include <hpx/naming_base/id_type.hpp> #include <hpx/traits/is_continuation.hpp> #include <hpx/type_support/pack.hpp> #include <hpx/util/bind_action.hpp> #include <hpx/util/functional/colocated_helpers.hpp> #include <type_traits> #include <utility> namespace hpx { namespace detail { template <typename Action, typename Ts = typename Action::arguments_type> struct async_colocated_bound_action; template <typename Action, typename... Ts> struct async_colocated_bound_action<Action, hpx::tuple<Ts...>> { typedef hpx::util::detail::bound_action<Action, hpx::util::make_index_pack<1 + sizeof...(Ts)>, hpx::util::detail::bound<hpx::util::functional::extract_locality, hpx::util::index_pack<0, 1>, hpx::util::detail::placeholder<2ul>, hpx::id_type>, Ts...> type; }; }} // namespace hpx::detail #define HPX_REGISTER_ASYNC_COLOCATED_DECLARATION(Action, Name) \ HPX_UTIL_REGISTER_UNIQUE_FUNCTION_DECLARATION( \ void(hpx::naming::id_type, hpx::naming::id_type), \ (hpx::util::functional::detail::async_continuation_impl< \ typename hpx::detail::async_colocated_bound_action<Action>::type, \ hpx::util::unused_type>), \ Name); \ /**/ #define HPX_REGISTER_ASYNC_COLOCATED(Action, Name) \ HPX_UTIL_REGISTER_UNIQUE_FUNCTION( \ void(hpx::naming::id_type, hpx::naming::id_type), \ (hpx::util::functional::detail::async_continuation_impl< \ typename hpx::detail::async_colocated_bound_action<Action>::type, \ hpx::util::unused_type>), \ Name); \ /**/ namespace hpx { namespace detail { /////////////////////////////////////////////////////////////////////////// template <typename Action, typename... Ts> lcos::future<typename traits::promise_local_result< typename hpx::traits::extract_action<Action>::remote_result_type>::type> async_colocated(naming::id_type const& gid, Ts&&... vs) { // Attach the requested action as a continuation to a resolve_async // call on the locality responsible for the target gid. naming::id_type service_target( agas::primary_namespace::get_service_instance(gid.get_gid()), naming::id_type::unmanaged); #if defined(HPX_COMPUTE_DEVICE_CODE) HPX_ASSERT(false); #else typedef typename hpx::traits::extract_action<Action>::remote_result_type remote_result_type; typedef agas::server::primary_namespace::colocate_action action_type; using util::placeholders::_2; return detail::async_continue_r<action_type, remote_result_type>( util::functional::async_continuation(util::bind<Action>( util::bind(util::functional::extract_locality(), _2, gid), std::forward<Ts>(vs)...)), service_target, gid.get_gid()); #endif } template <typename Component, typename Signature, typename Derived, typename... Ts> lcos::future<typename traits::promise_local_result<typename hpx::traits:: extract_action<Derived>::remote_result_type>::type> async_colocated( hpx::actions::basic_action<Component, Signature, Derived> /*act*/ , naming::id_type const& gid, Ts&&... vs) { return async_colocated<Derived>(gid, std::forward<Ts>(vs)...); } /////////////////////////////////////////////////////////////////////////// template <typename Action, typename Continuation, typename... Ts> typename std::enable_if<traits::is_continuation<Continuation>::value, lcos::future<typename traits::promise_local_result<typename hpx:: traits::extract_action<Action>::remote_result_type>::type>>:: type async_colocated( Continuation&& cont, naming::id_type const& gid, Ts&&... vs) { #if defined(HPX_COMPUTE_DEVICE_CODE) HPX_ASSERT(false); #else // Attach the requested action as a continuation to a resolve_async // call on the locality responsible for the target gid. naming::id_type service_target( agas::primary_namespace::get_service_instance(gid.get_gid()), naming::id_type::unmanaged); typedef typename hpx::traits::extract_action<Action>::remote_result_type remote_result_type; typedef agas::server::primary_namespace::colocate_action action_type; using util::placeholders::_2; return detail::async_continue_r<action_type, remote_result_type>( util::functional::async_continuation( util::bind<Action>( util::bind(util::functional::extract_locality(), _2, gid), std::forward<Ts>(vs)...), std::forward<Continuation>(cont)), service_target, gid.get_gid()); #endif } template <typename Continuation, typename Component, typename Signature, typename Derived, typename... Ts> typename std::enable_if<traits::is_continuation<Continuation>::value, lcos::future<typename traits::promise_local_result<typename hpx:: traits::extract_action<Derived>::remote_result_type>::type>>:: type async_colocated(Continuation&& cont, hpx::actions::basic_action<Component, Signature, Derived> /*act*/ , naming::id_type const& gid, Ts&&... vs) { return async_colocated<Derived>( std::forward<Continuation>(cont), gid, std::forward<Ts>(vs)...); } }} // namespace hpx::detail
44.064103
80
0.616526
gonidelis
b4b51129f1e2c579d079116b5ee3dfb6940a7fdb
58,609
cpp
C++
src/ports/SkFontHost_FreeType_common.cpp
lirongfei123/skia
ca5c3363596b91ce75f381dfde15985a71e20626
[ "BSD-3-Clause" ]
1
2021-08-07T03:44:46.000Z
2021-08-07T03:44:46.000Z
src/ports/SkFontHost_FreeType_common.cpp
blvd20/skia
fdf7b3c41f8ede5cb7f8b160f73695e9a1682e46
[ "BSD-3-Clause" ]
null
null
null
src/ports/SkFontHost_FreeType_common.cpp
blvd20/skia
fdf7b3c41f8ede5cb7f8b160f73695e9a1682e46
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2006-2012 The Android Open Source Project * Copyright 2012 Mozilla Foundation * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkPath.h" #include "include/effects/SkGradientShader.h" #include "include/private/SkColorData.h" #include "include/private/SkTo.h" #include "src/core/SkFDot6.h" #include "src/ports/SkFontHost_FreeType_common.h" #include <utility> #include <ft2build.h> #include FT_FREETYPE_H #include FT_BITMAP_H #ifdef FT_COLOR_H # include FT_COLOR_H #endif #include FT_IMAGE_H #include FT_OUTLINE_H #include FT_SIZES_H // In the past, FT_GlyphSlot_Own_Bitmap was defined in this header file. #include FT_SYNTHESIS_H #ifdef TT_SUPPORT_COLRV1 #include "src/core/SkScopeExit.h" #endif // FT_LOAD_COLOR and the corresponding FT_Pixel_Mode::FT_PIXEL_MODE_BGRA // were introduced in FreeType 2.5.0. // The following may be removed once FreeType 2.5.0 is required to build. #ifndef FT_LOAD_COLOR # define FT_LOAD_COLOR ( 1L << 20 ) # define FT_PIXEL_MODE_BGRA 7 #endif #ifdef SK_DEBUG const char* SkTraceFtrGetError(int e) { switch ((FT_Error)e) { #undef FTERRORS_H_ #define FT_ERRORDEF( e, v, s ) case v: return s; #define FT_ERROR_START_LIST #define FT_ERROR_END_LIST #include FT_ERRORS_H #undef FT_ERRORDEF #undef FT_ERROR_START_LIST #undef FT_ERROR_END_LIST default: return ""; } } #endif // SK_DEBUG #ifdef TT_SUPPORT_COLRV1 bool operator==(const FT_OpaquePaint& a, const FT_OpaquePaint& b) { return a.p == b.p && a.insert_root_transform == b.insert_root_transform; } #endif namespace { FT_Pixel_Mode compute_pixel_mode(SkMask::Format format) { switch (format) { case SkMask::kBW_Format: return FT_PIXEL_MODE_MONO; case SkMask::kA8_Format: default: return FT_PIXEL_MODE_GRAY; } } /////////////////////////////////////////////////////////////////////////////// uint16_t packTriple(U8CPU r, U8CPU g, U8CPU b) { #ifdef SK_SHOW_TEXT_BLIT_COVERAGE r = std::max(r, (U8CPU)0x40); g = std::max(g, (U8CPU)0x40); b = std::max(b, (U8CPU)0x40); #endif return SkPack888ToRGB16(r, g, b); } uint16_t grayToRGB16(U8CPU gray) { #ifdef SK_SHOW_TEXT_BLIT_COVERAGE gray = std::max(gray, (U8CPU)0x40); #endif return SkPack888ToRGB16(gray, gray, gray); } int bittst(const uint8_t data[], int bitOffset) { SkASSERT(bitOffset >= 0); int lowBit = data[bitOffset >> 3] >> (~bitOffset & 7); return lowBit & 1; } /** * Copies a FT_Bitmap into an SkMask with the same dimensions. * * FT_PIXEL_MODE_MONO * FT_PIXEL_MODE_GRAY * FT_PIXEL_MODE_LCD * FT_PIXEL_MODE_LCD_V */ template<bool APPLY_PREBLEND> void copyFT2LCD16(const FT_Bitmap& bitmap, const SkMask& mask, int lcdIsBGR, const uint8_t* tableR, const uint8_t* tableG, const uint8_t* tableB) { SkASSERT(SkMask::kLCD16_Format == mask.fFormat); if (FT_PIXEL_MODE_LCD != bitmap.pixel_mode) { SkASSERT(mask.fBounds.width() == static_cast<int>(bitmap.width)); } if (FT_PIXEL_MODE_LCD_V != bitmap.pixel_mode) { SkASSERT(mask.fBounds.height() == static_cast<int>(bitmap.rows)); } const uint8_t* src = bitmap.buffer; uint16_t* dst = reinterpret_cast<uint16_t*>(mask.fImage); const size_t dstRB = mask.fRowBytes; const int width = mask.fBounds.width(); const int height = mask.fBounds.height(); switch (bitmap.pixel_mode) { case FT_PIXEL_MODE_MONO: for (int y = height; y --> 0;) { for (int x = 0; x < width; ++x) { dst[x] = -bittst(src, x); } dst = (uint16_t*)((char*)dst + dstRB); src += bitmap.pitch; } break; case FT_PIXEL_MODE_GRAY: for (int y = height; y --> 0;) { for (int x = 0; x < width; ++x) { dst[x] = grayToRGB16(src[x]); } dst = (uint16_t*)((char*)dst + dstRB); src += bitmap.pitch; } break; case FT_PIXEL_MODE_LCD: SkASSERT(3 * mask.fBounds.width() == static_cast<int>(bitmap.width)); for (int y = height; y --> 0;) { const uint8_t* triple = src; if (lcdIsBGR) { for (int x = 0; x < width; x++) { dst[x] = packTriple(sk_apply_lut_if<APPLY_PREBLEND>(triple[2], tableR), sk_apply_lut_if<APPLY_PREBLEND>(triple[1], tableG), sk_apply_lut_if<APPLY_PREBLEND>(triple[0], tableB)); triple += 3; } } else { for (int x = 0; x < width; x++) { dst[x] = packTriple(sk_apply_lut_if<APPLY_PREBLEND>(triple[0], tableR), sk_apply_lut_if<APPLY_PREBLEND>(triple[1], tableG), sk_apply_lut_if<APPLY_PREBLEND>(triple[2], tableB)); triple += 3; } } src += bitmap.pitch; dst = (uint16_t*)((char*)dst + dstRB); } break; case FT_PIXEL_MODE_LCD_V: SkASSERT(3 * mask.fBounds.height() == static_cast<int>(bitmap.rows)); for (int y = height; y --> 0;) { const uint8_t* srcR = src; const uint8_t* srcG = srcR + bitmap.pitch; const uint8_t* srcB = srcG + bitmap.pitch; if (lcdIsBGR) { using std::swap; swap(srcR, srcB); } for (int x = 0; x < width; x++) { dst[x] = packTriple(sk_apply_lut_if<APPLY_PREBLEND>(*srcR++, tableR), sk_apply_lut_if<APPLY_PREBLEND>(*srcG++, tableG), sk_apply_lut_if<APPLY_PREBLEND>(*srcB++, tableB)); } src += 3 * bitmap.pitch; dst = (uint16_t*)((char*)dst + dstRB); } break; default: SkDEBUGF("FT_Pixel_Mode %d", bitmap.pixel_mode); SkDEBUGFAIL("unsupported FT_Pixel_Mode for LCD16"); break; } } /** * Copies a FT_Bitmap into an SkMask with the same dimensions. * * Yes, No, Never Requested, Never Produced * * kBW kA8 k3D kARGB32 kLCD16 * FT_PIXEL_MODE_MONO Y Y NR N Y * FT_PIXEL_MODE_GRAY N Y NR N Y * FT_PIXEL_MODE_GRAY2 NP NP NR NP NP * FT_PIXEL_MODE_GRAY4 NP NP NR NP NP * FT_PIXEL_MODE_LCD NP NP NR NP NP * FT_PIXEL_MODE_LCD_V NP NP NR NP NP * FT_PIXEL_MODE_BGRA N N NR Y N * * TODO: All of these N need to be Y or otherwise ruled out. */ void copyFTBitmap(const FT_Bitmap& srcFTBitmap, SkMask& dstMask) { SkASSERTF(dstMask.fBounds.width() == static_cast<int>(srcFTBitmap.width), "dstMask.fBounds.width() = %d\n" "static_cast<int>(srcFTBitmap.width) = %d", dstMask.fBounds.width(), static_cast<int>(srcFTBitmap.width) ); SkASSERTF(dstMask.fBounds.height() == static_cast<int>(srcFTBitmap.rows), "dstMask.fBounds.height() = %d\n" "static_cast<int>(srcFTBitmap.rows) = %d", dstMask.fBounds.height(), static_cast<int>(srcFTBitmap.rows) ); const uint8_t* src = reinterpret_cast<const uint8_t*>(srcFTBitmap.buffer); const FT_Pixel_Mode srcFormat = static_cast<FT_Pixel_Mode>(srcFTBitmap.pixel_mode); // FT_Bitmap::pitch is an int and allowed to be negative. const int srcPitch = srcFTBitmap.pitch; const size_t srcRowBytes = SkTAbs(srcPitch); uint8_t* dst = dstMask.fImage; const SkMask::Format dstFormat = static_cast<SkMask::Format>(dstMask.fFormat); const size_t dstRowBytes = dstMask.fRowBytes; const size_t width = srcFTBitmap.width; const size_t height = srcFTBitmap.rows; if (SkMask::kLCD16_Format == dstFormat) { copyFT2LCD16<false>(srcFTBitmap, dstMask, false, nullptr, nullptr, nullptr); return; } if ((FT_PIXEL_MODE_MONO == srcFormat && SkMask::kBW_Format == dstFormat) || (FT_PIXEL_MODE_GRAY == srcFormat && SkMask::kA8_Format == dstFormat)) { size_t commonRowBytes = std::min(srcRowBytes, dstRowBytes); for (size_t y = height; y --> 0;) { memcpy(dst, src, commonRowBytes); src += srcPitch; dst += dstRowBytes; } } else if (FT_PIXEL_MODE_MONO == srcFormat && SkMask::kA8_Format == dstFormat) { for (size_t y = height; y --> 0;) { uint8_t byte = 0; int bits = 0; const uint8_t* src_row = src; uint8_t* dst_row = dst; for (size_t x = width; x --> 0;) { if (0 == bits) { byte = *src_row++; bits = 8; } *dst_row++ = byte & 0x80 ? 0xff : 0x00; bits--; byte <<= 1; } src += srcPitch; dst += dstRowBytes; } } else if (FT_PIXEL_MODE_BGRA == srcFormat && SkMask::kARGB32_Format == dstFormat) { // FT_PIXEL_MODE_BGRA is pre-multiplied. for (size_t y = height; y --> 0;) { const uint8_t* src_row = src; SkPMColor* dst_row = reinterpret_cast<SkPMColor*>(dst); for (size_t x = 0; x < width; ++x) { uint8_t b = *src_row++; uint8_t g = *src_row++; uint8_t r = *src_row++; uint8_t a = *src_row++; *dst_row++ = SkPackARGB32(a, r, g, b); #ifdef SK_SHOW_TEXT_BLIT_COVERAGE *(dst_row-1) = SkFourByteInterp256(*(dst_row-1), SK_ColorWHITE, 0x40); #endif } src += srcPitch; dst += dstRowBytes; } } else { SkDEBUGF("FT_Pixel_Mode %d, SkMask::Format %d\n", srcFormat, dstFormat); SkDEBUGFAIL("unsupported combination of FT_Pixel_Mode and SkMask::Format"); } } inline int convert_8_to_1(unsigned byte) { SkASSERT(byte <= 0xFF); // Arbitrary decision that making the cutoff at 1/4 instead of 1/2 in general looks better. return (byte >> 6) != 0; } uint8_t pack_8_to_1(const uint8_t alpha[8]) { unsigned bits = 0; for (int i = 0; i < 8; ++i) { bits <<= 1; bits |= convert_8_to_1(alpha[i]); } return SkToU8(bits); } void packA8ToA1(const SkMask& mask, const uint8_t* src, size_t srcRB) { const int height = mask.fBounds.height(); const int width = mask.fBounds.width(); const int octs = width >> 3; const int leftOverBits = width & 7; uint8_t* dst = mask.fImage; const int dstPad = mask.fRowBytes - SkAlign8(width)/8; SkASSERT(dstPad >= 0); const int srcPad = srcRB - width; SkASSERT(srcPad >= 0); for (int y = 0; y < height; ++y) { for (int i = 0; i < octs; ++i) { *dst++ = pack_8_to_1(src); src += 8; } if (leftOverBits > 0) { unsigned bits = 0; int shift = 7; for (int i = 0; i < leftOverBits; ++i, --shift) { bits |= convert_8_to_1(*src++) << shift; } *dst++ = bits; } src += srcPad; dst += dstPad; } } inline SkMask::Format SkMaskFormat_for_SkColorType(SkColorType colorType) { switch (colorType) { case kAlpha_8_SkColorType: return SkMask::kA8_Format; case kN32_SkColorType: return SkMask::kARGB32_Format; default: SkDEBUGFAIL("unsupported SkBitmap::Config"); return SkMask::kA8_Format; } } inline SkColorType SkColorType_for_FTPixelMode(FT_Pixel_Mode pixel_mode) { switch (pixel_mode) { case FT_PIXEL_MODE_MONO: case FT_PIXEL_MODE_GRAY: return kAlpha_8_SkColorType; case FT_PIXEL_MODE_BGRA: return kN32_SkColorType; default: SkDEBUGFAIL("unsupported FT_PIXEL_MODE"); return kAlpha_8_SkColorType; } } inline SkColorType SkColorType_for_SkMaskFormat(SkMask::Format format) { switch (format) { case SkMask::kBW_Format: case SkMask::kA8_Format: case SkMask::kLCD16_Format: return kAlpha_8_SkColorType; case SkMask::kARGB32_Format: return kN32_SkColorType; default: SkDEBUGFAIL("unsupported destination SkBitmap::Config"); return kAlpha_8_SkColorType; } } // Only build COLRv1 rendering code if FreeType is new enough to have COLRv1 // additions. FreeType defines a macro in the ftoption header to tell us whether // it does support these features. #ifdef TT_SUPPORT_COLRV1 struct OpaquePaintHasher { size_t operator()(const FT_OpaquePaint& opaque_paint) { return SkGoodHash()(opaque_paint.p) ^ SkGoodHash()(opaque_paint.insert_root_transform); } }; using VisitedSet = SkTHashSet<FT_OpaquePaint, OpaquePaintHasher>; bool generateFacePathCOLRv1(FT_Face face, SkGlyphID glyphID, SkPath* path); inline float SkColrV1AlphaToFloat(uint16_t alpha) { return (alpha / float(1 << 14)); } inline SkTileMode ToSkTileMode(FT_PaintExtend extend_mode) { switch (extend_mode) { case FT_COLR_PAINT_EXTEND_REPEAT: return SkTileMode::kRepeat; case FT_COLR_PAINT_EXTEND_REFLECT: return SkTileMode::kMirror; default: return SkTileMode::kClamp; } } inline SkBlendMode ToSkBlendMode(FT_Composite_Mode composite) { switch (composite) { case FT_COLR_COMPOSITE_CLEAR: return SkBlendMode::kClear; case FT_COLR_COMPOSITE_SRC: return SkBlendMode::kSrc; case FT_COLR_COMPOSITE_DEST: return SkBlendMode::kDst; case FT_COLR_COMPOSITE_SRC_OVER: return SkBlendMode::kSrcOver; case FT_COLR_COMPOSITE_DEST_OVER: return SkBlendMode::kDstOver; case FT_COLR_COMPOSITE_SRC_IN: return SkBlendMode::kSrcIn; case FT_COLR_COMPOSITE_DEST_IN: return SkBlendMode::kDstIn; case FT_COLR_COMPOSITE_SRC_OUT: return SkBlendMode::kSrcOut; case FT_COLR_COMPOSITE_DEST_OUT: return SkBlendMode::kDstOut; case FT_COLR_COMPOSITE_SRC_ATOP: return SkBlendMode::kSrcATop; case FT_COLR_COMPOSITE_DEST_ATOP: return SkBlendMode::kDstATop; case FT_COLR_COMPOSITE_XOR: return SkBlendMode::kXor; case FT_COLR_COMPOSITE_SCREEN: return SkBlendMode::kScreen; case FT_COLR_COMPOSITE_OVERLAY: return SkBlendMode::kOverlay; case FT_COLR_COMPOSITE_DARKEN: return SkBlendMode::kDarken; case FT_COLR_COMPOSITE_LIGHTEN: return SkBlendMode::kLighten; case FT_COLR_COMPOSITE_COLOR_DODGE: return SkBlendMode::kColorDodge; case FT_COLR_COMPOSITE_COLOR_BURN: return SkBlendMode::kColorBurn; case FT_COLR_COMPOSITE_HARD_LIGHT: return SkBlendMode::kHardLight; case FT_COLR_COMPOSITE_SOFT_LIGHT: return SkBlendMode::kSoftLight; case FT_COLR_COMPOSITE_DIFFERENCE: return SkBlendMode::kDifference; case FT_COLR_COMPOSITE_EXCLUSION: return SkBlendMode::kExclusion; case FT_COLR_COMPOSITE_MULTIPLY: return SkBlendMode::kMultiply; case FT_COLR_COMPOSITE_HSL_HUE: return SkBlendMode::kHue; case FT_COLR_COMPOSITE_HSL_SATURATION: return SkBlendMode::kSaturation; case FT_COLR_COMPOSITE_HSL_COLOR: return SkBlendMode::kColor; case FT_COLR_COMPOSITE_HSL_LUMINOSITY: return SkBlendMode::kLuminosity; default: return SkBlendMode::kDst; } } inline SkMatrix ToSkMatrix(FT_Affine23 affine23) { // Adjust order to convert from FreeType's FT_Affine23 column major order to SkMatrix row-major // order. return SkMatrix::MakeAll( SkFixedToScalar(affine23.xx), -SkFixedToScalar(affine23.xy), SkFixedToScalar(affine23.dx), -SkFixedToScalar(affine23.yx), SkFixedToScalar(affine23.yy), -SkFixedToScalar(affine23.dy), 0, 0, 1); } inline SkPoint SkVectorProjection(SkPoint a, SkPoint b) { SkScalar length = b.length(); if (!length) return SkPoint(); SkPoint b_normalized = b; b_normalized.normalize(); b_normalized.scale(SkPoint::DotProduct(a, b) / length); return b_normalized; } void colrv1_configure_skpaint(FT_Face face, const FT_Color* palette, FT_COLR_Paint colrv1_paint, SkPaint* paint) { auto fetch_color_stops = [&face, &palette](FT_ColorStopIterator& color_stop_iterator, std::vector<SkScalar>& stops, std::vector<SkColor>& colors) { const FT_UInt num_color_stops = color_stop_iterator.num_color_stops; // 5.7.11.2.4 ColorIndex, ColorStop and ColorLine // "Applications shall apply the colorStops in increasing stopOffset order." struct ColorStop { SkScalar stop_pos; SkColor color; }; std::vector<ColorStop> sorted_stops; sorted_stops.resize(num_color_stops); FT_ColorStop color_stop; while (FT_Get_Colorline_Stops(face, &color_stop, &color_stop_iterator)) { FT_UInt index = color_stop_iterator.current_color_stop - 1; sorted_stops[index].stop_pos = color_stop.stop_offset / float(1 << 14); FT_UInt16& palette_index = color_stop.color.palette_index; // TODO(drott): Ensure palette_index is sanitized on the FreeType // side and 0xFFFF foreground color will be handled correctly here. sorted_stops[index].color = SkColorSetARGB( palette[palette_index].alpha * SkColrV1AlphaToFloat(color_stop.color.alpha), palette[palette_index].red, palette[palette_index].green, palette[palette_index].blue); } std::stable_sort( sorted_stops.begin(), sorted_stops.end(), [](const ColorStop& a, const ColorStop& b) { return a.stop_pos < b.stop_pos; }); stops.resize(num_color_stops); colors.resize(num_color_stops); for (size_t i = 0; i < num_color_stops; ++i) { stops[i] = sorted_stops[i].stop_pos; colors[i] = sorted_stops[i].color; } }; switch (colrv1_paint.format) { case FT_COLR_PAINTFORMAT_SOLID: { FT_PaintSolid solid = colrv1_paint.u.solid; SkColor color = SkColorSetARGB(palette[solid.color.palette_index].alpha * SkColrV1AlphaToFloat(solid.color.alpha), palette[solid.color.palette_index].red, palette[solid.color.palette_index].green, palette[solid.color.palette_index].blue); paint->setShader(nullptr); paint->setColor(color); break; } case FT_COLR_PAINTFORMAT_LINEAR_GRADIENT: { FT_PaintLinearGradient& linear_gradient = colrv1_paint.u.linear_gradient; SkPoint line_positions[2] = { SkPoint::Make(linear_gradient.p0.x, -linear_gradient.p0.y), SkPoint::Make(linear_gradient.p1.x, -linear_gradient.p1.y) }; SkPoint p0 = line_positions[0]; SkPoint p1 = line_positions[1]; SkPoint p2 = SkPoint::Make(linear_gradient.p2.x, -linear_gradient.p2.y); // Do not draw the gradient of p0p1 is parallel to p0p2. if (p1 == p0 || p2 == p0 || !SkPoint::CrossProduct(p1 - p0, p2 - p0)) break; // Follow implementation note in nanoemoji: // https://github.com/googlefonts/nanoemoji/blob/0ac6e7bb4d8202db692574d8530a9b643f1b3b3c/src/nanoemoji/svg.py#L188 // to compute a new gradient end point as the orthogonal projection of the vector from p0 to p1 onto a line // perpendicular to line p0p2 and passing through p0. SkVector perpendicular_to_p2_p0 = (p2 - p0); perpendicular_to_p2_p0 = SkPoint::Make(perpendicular_to_p2_p0.y(), -perpendicular_to_p2_p0.x()); line_positions[1] = p0 + SkVectorProjection((p1 - p0), perpendicular_to_p2_p0); std::vector<SkScalar> stops; std::vector<SkColor> colors; fetch_color_stops(linear_gradient.colorline.color_stop_iterator, stops, colors); if (stops.empty()) { break; } if (stops.size() == 1) { paint->setColor(colors[0]); break; } // Project/scale points according to stop extrema along p0p1 line, // then scale stops to to [0, 1] range so that repeat modes work. // The Skia linear gradient shader performs the repeat modes over // the 0 to 1 range, that's why we need to scale the stops to within // that range. SkVector p0p1 = p1 - p0; SkVector new_p0_offset = p0p1; new_p0_offset.scale(stops.front()); SkVector new_p1_offset = p0p1; new_p1_offset.scale(stops.back()); line_positions[0] = p0 + new_p0_offset; line_positions[1] = p0 + new_p1_offset; SkScalar scale_factor = 1 / (stops.back() - stops.front()); SkScalar start_offset = stops.front(); for (SkScalar& stop : stops) { stop = (stop - start_offset) * scale_factor; } sk_sp<SkShader> shader(SkGradientShader::MakeLinear( line_positions, colors.data(), stops.data(), stops.size(), ToSkTileMode(linear_gradient.colorline.extend))); SkASSERT(shader); // An opaque color is needed to ensure the gradient's not modulated by alpha. paint->setColor(SK_ColorBLACK); paint->setShader(shader); break; } case FT_COLR_PAINTFORMAT_RADIAL_GRADIENT: { FT_PaintRadialGradient& radial_gradient = colrv1_paint.u.radial_gradient; SkPoint start = SkPoint::Make(radial_gradient.c0.x, -radial_gradient.c0.y); SkScalar radius = radial_gradient.r0; SkPoint end = SkPoint::Make(radial_gradient.c1.x, -radial_gradient.c1.y); SkScalar end_radius = radial_gradient.r1; std::vector<SkScalar> stops; std::vector<SkColor> colors; fetch_color_stops(radial_gradient.colorline.color_stop_iterator, stops, colors); // An opaque color is needed to ensure the gradient's not modulated by alpha. paint->setColor(SK_ColorBLACK); paint->setShader(SkGradientShader::MakeTwoPointConical( start, radius, end, end_radius, colors.data(), stops.data(), stops.size(), ToSkTileMode(radial_gradient.colorline.extend))); break; } case FT_COLR_PAINTFORMAT_SWEEP_GRADIENT: { FT_PaintSweepGradient& sweep_gradient = colrv1_paint.u.sweep_gradient; SkPoint center = SkPoint::Make(sweep_gradient.center.x, -sweep_gradient.center.y); SkScalar startAngle = SkFixedToScalar(sweep_gradient.start_angle * 180.0f); SkScalar endAngle = SkFixedToScalar(sweep_gradient.end_angle * 180.0f); std::vector<SkScalar> stops; std::vector<SkColor> colors; fetch_color_stops(sweep_gradient.colorline.color_stop_iterator, stops, colors); // An opaque color is needed to ensure the gradient's not modulated by alpha. paint->setColor(SK_ColorBLACK); // Prepare angles to be within range for the shader. auto clampAngleToRange= [](SkScalar angle) { SkScalar clamped_angle = SkScalarMod(angle, 360.f); if (clamped_angle < 0) return clamped_angle + 360.f; return clamped_angle; }; startAngle = clampAngleToRange(startAngle); endAngle = clampAngleToRange(endAngle); /* TODO: Spec clarifications on which side of the gradient is to be * painted, repeat modes, how to handle 0 degrees transition, see * https://github.com/googlefonts/colr-gradients-spec/issues/250 */ if (startAngle >= endAngle) endAngle += 360.f; // Skia's angles start from the horizontal x-Axis, rotate left 90 // degrees and then mirror horizontally to correct for Skia angles // going clockwise, COLR v1 angles going counterclockwise. SkMatrix angle_adjust = SkMatrix::RotateDeg(-90.f, center); angle_adjust.postScale(-1, 1, center.x(), center.y()); paint->setShader(SkGradientShader::MakeSweep( center.x(), center.y(), colors.data(), stops.data(), stops.size(), SkTileMode::kDecal, startAngle, endAngle, 0, &angle_adjust)); break; } default: { SkASSERT(false); /* not reached */ } } } void colrv1_draw_paint(SkCanvas* canvas, const FT_Color* palette, FT_Face face, FT_COLR_Paint colrv1_paint) { SkPaint paint; switch (colrv1_paint.format) { case FT_COLR_PAINTFORMAT_GLYPH: { FT_UInt glyphID = colrv1_paint.u.glyph.glyphID; SkPath path; /* TODO: Currently this call retrieves the path at units_per_em size. If we want to get * correct hinting for the scaled size under the transforms at this point in the color * glyph graph, we need to extract at least the requested glyph width and height and * pass that to the path generation. */ if (generateFacePathCOLRv1(face, glyphID, &path)) { #ifdef SK_SHOW_TEXT_BLIT_COVERAGE SkPaint highlight_paint; highlight_paint.setColor(0x33FF0000); canvas->drawRect(path.getBounds(), highlight_paint); #endif canvas->clipPath(path, true /* doAntiAlias */); } break; } case FT_COLR_PAINTFORMAT_SOLID: case FT_COLR_PAINTFORMAT_LINEAR_GRADIENT: case FT_COLR_PAINTFORMAT_RADIAL_GRADIENT: case FT_COLR_PAINTFORMAT_SWEEP_GRADIENT: { SkPaint colrPaint; colrv1_configure_skpaint(face, palette, colrv1_paint, &colrPaint); canvas->drawPaint(colrPaint); break; } case FT_COLR_PAINTFORMAT_TRANSFORM: case FT_COLR_PAINTFORMAT_TRANSLATE: case FT_COLR_PAINTFORMAT_SCALE: case FT_COLR_PAINTFORMAT_ROTATE: case FT_COLR_PAINTFORMAT_SKEW: SkASSERT(false); // Transforms handled in colrv1_transform. break; default: paint.setShader(nullptr); paint.setColor(SK_ColorCYAN); break; } } void colrv1_draw_glyph_with_path(SkCanvas* canvas, const FT_Color* palette, FT_Face face, FT_COLR_Paint glyphPaint, FT_COLR_Paint fillPaint) { SkASSERT(glyphPaint.format == FT_COLR_PAINTFORMAT_GLYPH); SkASSERT(fillPaint.format == FT_COLR_PAINTFORMAT_SOLID || fillPaint.format == FT_COLR_PAINTFORMAT_LINEAR_GRADIENT || fillPaint.format == FT_COLR_PAINTFORMAT_RADIAL_GRADIENT || fillPaint.format == FT_COLR_PAINTFORMAT_SWEEP_GRADIENT); SkPaint skiaFillPaint; skiaFillPaint.setAntiAlias(true); colrv1_configure_skpaint(face, palette, fillPaint, &skiaFillPaint); FT_UInt glyphID = glyphPaint.u.glyph.glyphID; SkPath path; /* TODO: Currently this call retrieves the path at units_per_em size. If we want to get * correct hinting for the scaled size under the transforms at this point in the color * glyph graph, we need to extract at least the requested glyph width and height and * pass that to the path generation. */ if (generateFacePathCOLRv1(face, glyphID, &path)) { #ifdef SK_SHOW_TEXT_BLIT_COVERAGE SkPaint highlight_paint; highlight_paint.setColor(0x33FF0000); canvas->drawRect(path.getBounds(), highlight_paint); #endif { canvas->drawPath(path, skiaFillPaint); } } } void colrv1_transform(SkCanvas* canvas, FT_Face face, FT_COLR_Paint colrv1_paint) { SkMatrix transform; switch (colrv1_paint.format) { case FT_COLR_PAINTFORMAT_TRANSFORM: { transform = ToSkMatrix(colrv1_paint.u.transform.affine); break; } case FT_COLR_PAINTFORMAT_TRANSLATE: { transform = SkMatrix::Translate( SkFixedToScalar(colrv1_paint.u.translate.dx), -SkFixedToScalar(colrv1_paint.u.translate.dy)); break; } case FT_COLR_PAINTFORMAT_SCALE: { transform.setScale(SkFixedToScalar(colrv1_paint.u.scale.scale_x), SkFixedToScalar(colrv1_paint.u.scale.scale_y), SkFixedToScalar(colrv1_paint.u.scale.center_x), -SkFixedToScalar(colrv1_paint.u.scale.center_y)); break; } case FT_COLR_PAINTFORMAT_ROTATE: { transform = SkMatrix::RotateDeg( SkFixedToScalar(colrv1_paint.u.rotate.angle) * 180.0f, SkPoint::Make(SkFixedToScalar(colrv1_paint.u.rotate.center_x), -SkFixedToScalar(colrv1_paint.u.rotate.center_y))); break; } case FT_COLR_PAINTFORMAT_SKEW: { // In the PAINTFORMAT_ROTATE implementation, SkMatrix setRotate // snaps to 0 for values very close to 0. Do the same here. SkScalar rad_x = SkDegreesToRadians(-SkFixedToFloat(colrv1_paint.u.skew.x_skew_angle) * 180.0f); float tan_x = SkScalarTan(rad_x); tan_x = SkScalarNearlyZero(tan_x) ? 0.0f : tan_x; SkScalar rad_y = SkDegreesToRadians(-SkFixedToFloat(colrv1_paint.u.skew.y_skew_angle) * 180.0f); float tan_y = SkScalarTan(rad_y); tan_y = SkScalarNearlyZero(tan_y) ? 0.0f : tan_y; transform.setSkew(tan_x, tan_y, SkFixedToScalar(colrv1_paint.u.skew.center_x), -SkFixedToFloat(colrv1_paint.u.skew.center_y)); break; } default: { // Only transforms are handled in this function. SkASSERT(false); } } canvas->concat(transform); } bool colrv1_start_glyph(SkCanvas* canvas, const FT_Color* palette, FT_Face ft_face, uint16_t glyph_id, FT_Color_Root_Transform root_transform); bool colrv1_traverse_paint(SkCanvas* canvas, const FT_Color* palette, FT_Face face, FT_OpaquePaint opaque_paint, VisitedSet* visited_set) { // Cycle detection, see section "5.7.11.1.9 Color glyphs as a directed acyclic graph". if (visited_set->contains(opaque_paint)) { return false; } visited_set->add(opaque_paint); SK_AT_SCOPE_EXIT(visited_set->remove(opaque_paint)); FT_COLR_Paint paint; if (!FT_Get_Paint(face, opaque_paint, &paint)) { return false; } // Keep track of failures to retrieve the FT_COLR_Paint from FreeType in the // recursion, cancel recursion when a paint retrieval fails. bool traverse_result = true; SkAutoCanvasRestore autoRestore(canvas, true /* do_save */); switch (paint.format) { case FT_COLR_PAINTFORMAT_COLR_LAYERS: { FT_LayerIterator& layer_iterator = paint.u.colr_layers.layer_iterator; FT_OpaquePaint opaque_paint_fetch; opaque_paint_fetch.p = nullptr; while (FT_Get_Paint_Layers(face, &layer_iterator, &opaque_paint_fetch)) { colrv1_traverse_paint(canvas, palette, face, opaque_paint_fetch, visited_set); } break; } case FT_COLR_PAINTFORMAT_GLYPH: // Special case paint graph leaf situations to improve // performance. These are situations in the graph where a GlyphPaint // is followed by either a solid or a gradient fill. Here we can use // drawPath() + SkPaint directly which is faster than setting a // clipPath() followed by a drawPaint(). FT_COLR_Paint fillPaint; if (!FT_Get_Paint(face, paint.u.glyph.paint, &fillPaint)) { return false; } if (fillPaint.format == FT_COLR_PAINTFORMAT_SOLID || fillPaint.format == FT_COLR_PAINTFORMAT_LINEAR_GRADIENT || fillPaint.format == FT_COLR_PAINTFORMAT_RADIAL_GRADIENT || fillPaint.format == FT_COLR_PAINTFORMAT_SWEEP_GRADIENT) { colrv1_draw_glyph_with_path(canvas, palette, face, paint, fillPaint); } else { colrv1_draw_paint(canvas, palette, face, paint); traverse_result = colrv1_traverse_paint(canvas, palette, face, paint.u.glyph.paint, visited_set); } break; case FT_COLR_PAINTFORMAT_COLR_GLYPH: traverse_result = colrv1_start_glyph(canvas, palette, face, paint.u.colr_glyph.glyphID, FT_COLOR_NO_ROOT_TRANSFORM); break; case FT_COLR_PAINTFORMAT_TRANSFORM: colrv1_transform(canvas, face, paint); traverse_result = colrv1_traverse_paint(canvas, palette, face, paint.u.transform.paint, visited_set); break; case FT_COLR_PAINTFORMAT_TRANSLATE: colrv1_transform(canvas, face, paint); traverse_result = colrv1_traverse_paint(canvas, palette, face, paint.u.translate.paint, visited_set); break; case FT_COLR_PAINTFORMAT_SCALE: colrv1_transform(canvas, face, paint); traverse_result = colrv1_traverse_paint(canvas, palette, face, paint.u.scale.paint, visited_set); break; case FT_COLR_PAINTFORMAT_ROTATE: colrv1_transform(canvas, face, paint); traverse_result = colrv1_traverse_paint(canvas, palette, face, paint.u.rotate.paint, visited_set); break; case FT_COLR_PAINTFORMAT_SKEW: colrv1_transform(canvas, face, paint); traverse_result = colrv1_traverse_paint(canvas, palette, face, paint.u.skew.paint, visited_set); break; case FT_COLR_PAINTFORMAT_COMPOSITE: { traverse_result = colrv1_traverse_paint( canvas, palette, face, paint.u.composite.backdrop_paint, visited_set); SkPaint blend_mode_paint; blend_mode_paint.setBlendMode(ToSkBlendMode(paint.u.composite.composite_mode)); canvas->saveLayer(nullptr, &blend_mode_paint); traverse_result = traverse_result && colrv1_traverse_paint( canvas, palette, face, paint.u.composite.source_paint, visited_set); canvas->restore(); break; } case FT_COLR_PAINTFORMAT_SOLID: case FT_COLR_PAINTFORMAT_LINEAR_GRADIENT: case FT_COLR_PAINTFORMAT_RADIAL_GRADIENT: case FT_COLR_PAINTFORMAT_SWEEP_GRADIENT: { colrv1_draw_paint(canvas, palette, face, paint); break; } default: SkASSERT(false); break; } return traverse_result; } bool colrv1_start_glyph(SkCanvas* canvas, const FT_Color* palette, FT_Face ft_face, uint16_t glyph_id, FT_Color_Root_Transform root_transform) { FT_OpaquePaint opaque_paint; opaque_paint.p = nullptr; bool has_colrv1_layers = false; if (FT_Get_Color_Glyph_Paint(ft_face, glyph_id, root_transform, &opaque_paint)) { has_colrv1_layers = true; VisitedSet visited_set; colrv1_traverse_paint(canvas, palette, ft_face, opaque_paint, &visited_set); } return has_colrv1_layers; } #endif // TT_SUPPORT_COLRV1 } // namespace void SkScalerContext_FreeType_Base::generateGlyphImage( FT_Face face, const SkGlyph& glyph, const SkMatrix& bitmapTransform) { const bool doBGR = SkToBool(fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag); const bool doVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag); switch ( face->glyph->format ) { case FT_GLYPH_FORMAT_OUTLINE: { FT_Outline* outline = &face->glyph->outline; int dx = 0, dy = 0; if (this->isSubpixel()) { dx = SkFixedToFDot6(glyph.getSubXFixed()); dy = SkFixedToFDot6(glyph.getSubYFixed()); // negate dy since freetype-y-goes-up and skia-y-goes-down dy = -dy; } memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight); #ifdef FT_COLOR_H if (SkMask::kARGB32_Format == glyph.fMaskFormat) { SkBitmap dstBitmap; // TODO: mark this as sRGB when the blits will be sRGB. dstBitmap.setInfo(SkImageInfo::Make(glyph.fWidth, glyph.fHeight, kN32_SkColorType, kPremul_SkAlphaType), glyph.rowBytes()); dstBitmap.setPixels(glyph.fImage); // Scale unscaledBitmap into dstBitmap. SkCanvas canvas(dstBitmap); #ifdef SK_SHOW_TEXT_BLIT_COVERAGE canvas.clear(0x33FF0000); #else canvas.clear(SK_ColorTRANSPARENT); #endif canvas.translate(-glyph.fLeft, -glyph.fTop); if (this->isSubpixel()) { canvas.translate(SkFixedToScalar(glyph.getSubXFixed()), SkFixedToScalar(glyph.getSubYFixed())); } SkPaint paint; paint.setAntiAlias(true); FT_Color *palette; FT_Error err = FT_Palette_Select(face, 0, &palette); if (err) { SK_TRACEFTR(err, "Could not get palette from %s fontFace.", face->family_name); return; } FT_Bool haveLayers = false; #ifdef TT_SUPPORT_COLRV1 // Only attempt to draw COLRv1 glyph is FreeType is new enough // to have the COLRv1 additions, as indicated by the // TT_SUPPORT_COLRV1 flag defined by the FreeType headers in // that case. haveLayers = colrv1_start_glyph(&canvas, palette, face, glyph.getGlyphID(), FT_COLOR_INCLUDE_ROOT_TRANSFORM); #else haveLayers = false; #endif if (!haveLayers) { // If we didn't have colr v1 layers, try v0 layers. FT_LayerIterator layerIterator; layerIterator.p = NULL; FT_UInt layerGlyphIndex = 0; FT_UInt layerColorIndex = 0; while (FT_Get_Color_Glyph_Layer(face, glyph.getGlyphID(), &layerGlyphIndex, &layerColorIndex, &layerIterator)) { haveLayers = true; if (layerColorIndex == 0xFFFF) { paint.setColor(SK_ColorBLACK); } else { SkColor color = SkColorSetARGB(palette[layerColorIndex].alpha, palette[layerColorIndex].red, palette[layerColorIndex].green, palette[layerColorIndex].blue); paint.setColor(color); } SkPath path; if (this->generateFacePath(face, layerGlyphIndex, &path)) { canvas.drawPath(path, paint); } } } if (!haveLayers) { SK_TRACEFTR(err, "Could not get layers (neither v0, nor v1) from %s fontFace.", face->family_name); return; } } else #endif if (SkMask::kLCD16_Format == glyph.fMaskFormat) { FT_Outline_Translate(outline, dx, dy); FT_Error err = FT_Render_Glyph(face->glyph, doVert ? FT_RENDER_MODE_LCD_V : FT_RENDER_MODE_LCD); if (err) { SK_TRACEFTR(err, "Could not render glyph %p.", face->glyph); return; } SkMask mask = glyph.mask(); #ifdef SK_SHOW_TEXT_BLIT_COVERAGE memset(mask.fImage, 0x80, mask.fBounds.height() * mask.fRowBytes); #endif FT_GlyphSlotRec& ftGlyph = *face->glyph; if (!SkIRect::Intersects(mask.fBounds, SkIRect::MakeXYWH( ftGlyph.bitmap_left, -ftGlyph.bitmap_top, ftGlyph.bitmap.width, ftGlyph.bitmap.rows))) { return; } // If the FT_Bitmap extent is larger, discard bits of the bitmap outside the mask. // If the SkMask extent is larger, shrink mask to fit bitmap (clearing discarded). unsigned char* origBuffer = ftGlyph.bitmap.buffer; // First align the top left (origin). if (-ftGlyph.bitmap_top < mask.fBounds.fTop) { int32_t topDiff = mask.fBounds.fTop - (-ftGlyph.bitmap_top); ftGlyph.bitmap.buffer += ftGlyph.bitmap.pitch * topDiff; ftGlyph.bitmap.rows -= topDiff; ftGlyph.bitmap_top = -mask.fBounds.fTop; } if (ftGlyph.bitmap_left < mask.fBounds.fLeft) { int32_t leftDiff = mask.fBounds.fLeft - ftGlyph.bitmap_left; ftGlyph.bitmap.buffer += leftDiff; ftGlyph.bitmap.width -= leftDiff; ftGlyph.bitmap_left = mask.fBounds.fLeft; } if (mask.fBounds.fTop < -ftGlyph.bitmap_top) { mask.fImage += mask.fRowBytes * (-ftGlyph.bitmap_top - mask.fBounds.fTop); mask.fBounds.fTop = -ftGlyph.bitmap_top; } if (mask.fBounds.fLeft < ftGlyph.bitmap_left) { mask.fImage += sizeof(uint16_t) * (ftGlyph.bitmap_left - mask.fBounds.fLeft); mask.fBounds.fLeft = ftGlyph.bitmap_left; } // Origins aligned, clean up the width and height. int ftVertScale = (doVert ? 3 : 1); int ftHoriScale = (doVert ? 1 : 3); if (mask.fBounds.height() * ftVertScale < SkToInt(ftGlyph.bitmap.rows)) { ftGlyph.bitmap.rows = mask.fBounds.height() * ftVertScale; } if (mask.fBounds.width() * ftHoriScale < SkToInt(ftGlyph.bitmap.width)) { ftGlyph.bitmap.width = mask.fBounds.width() * ftHoriScale; } if (SkToInt(ftGlyph.bitmap.rows) < mask.fBounds.height() * ftVertScale) { mask.fBounds.fBottom = mask.fBounds.fTop + ftGlyph.bitmap.rows / ftVertScale; } if (SkToInt(ftGlyph.bitmap.width) < mask.fBounds.width() * ftHoriScale) { mask.fBounds.fRight = mask.fBounds.fLeft + ftGlyph.bitmap.width / ftHoriScale; } if (fPreBlend.isApplicable()) { copyFT2LCD16<true>(ftGlyph.bitmap, mask, doBGR, fPreBlend.fR, fPreBlend.fG, fPreBlend.fB); } else { copyFT2LCD16<false>(ftGlyph.bitmap, mask, doBGR, fPreBlend.fR, fPreBlend.fG, fPreBlend.fB); } // Restore the buffer pointer so FreeType can properly free it. ftGlyph.bitmap.buffer = origBuffer; } else { FT_BBox bbox; FT_Bitmap target; FT_Outline_Get_CBox(outline, &bbox); /* what we really want to do for subpixel is offset(dx, dy) compute_bounds offset(bbox & !63) but that is two calls to offset, so we do the following, which achieves the same thing with only one offset call. */ FT_Outline_Translate(outline, dx - ((bbox.xMin + dx) & ~63), dy - ((bbox.yMin + dy) & ~63)); target.width = glyph.fWidth; target.rows = glyph.fHeight; target.pitch = glyph.rowBytes(); target.buffer = reinterpret_cast<uint8_t*>(glyph.fImage); target.pixel_mode = compute_pixel_mode(glyph.fMaskFormat); target.num_grays = 256; FT_Outline_Get_Bitmap(face->glyph->library, outline, &target); #ifdef SK_SHOW_TEXT_BLIT_COVERAGE for (int y = 0; y < glyph.fHeight; ++y) { for (int x = 0; x < glyph.fWidth; ++x) { uint8_t& a = ((uint8_t*)glyph.fImage)[(glyph.rowBytes() * y) + x]; a = std::max<uint8_t>(a, 0x20); } } #endif } } break; case FT_GLYPH_FORMAT_BITMAP: { FT_Pixel_Mode pixel_mode = static_cast<FT_Pixel_Mode>(face->glyph->bitmap.pixel_mode); SkMask::Format maskFormat = static_cast<SkMask::Format>(glyph.fMaskFormat); // Assume that the other formats do not exist. SkASSERT(FT_PIXEL_MODE_MONO == pixel_mode || FT_PIXEL_MODE_GRAY == pixel_mode || FT_PIXEL_MODE_BGRA == pixel_mode); // These are the only formats this ScalerContext should request. SkASSERT(SkMask::kBW_Format == maskFormat || SkMask::kA8_Format == maskFormat || SkMask::kARGB32_Format == maskFormat || SkMask::kLCD16_Format == maskFormat); // If no scaling needed, directly copy glyph bitmap. if (bitmapTransform.isIdentity()) { SkMask dstMask = glyph.mask(); copyFTBitmap(face->glyph->bitmap, dstMask); break; } // Otherwise, scale the bitmap. // Copy the FT_Bitmap into an SkBitmap (either A8 or ARGB) SkBitmap unscaledBitmap; // TODO: mark this as sRGB when the blits will be sRGB. unscaledBitmap.allocPixels(SkImageInfo::Make(face->glyph->bitmap.width, face->glyph->bitmap.rows, SkColorType_for_FTPixelMode(pixel_mode), kPremul_SkAlphaType)); SkMask unscaledBitmapAlias; unscaledBitmapAlias.fImage = reinterpret_cast<uint8_t*>(unscaledBitmap.getPixels()); unscaledBitmapAlias.fBounds.setWH(unscaledBitmap.width(), unscaledBitmap.height()); unscaledBitmapAlias.fRowBytes = unscaledBitmap.rowBytes(); unscaledBitmapAlias.fFormat = SkMaskFormat_for_SkColorType(unscaledBitmap.colorType()); copyFTBitmap(face->glyph->bitmap, unscaledBitmapAlias); // Wrap the glyph's mask in a bitmap, unless the glyph's mask is BW or LCD. // BW requires an A8 target for resizing, which can then be down sampled. // LCD should use a 4x A8 target, which will then be down sampled. // For simplicity, LCD uses A8 and is replicated. int bitmapRowBytes = 0; if (SkMask::kBW_Format != maskFormat && SkMask::kLCD16_Format != maskFormat) { bitmapRowBytes = glyph.rowBytes(); } SkBitmap dstBitmap; // TODO: mark this as sRGB when the blits will be sRGB. dstBitmap.setInfo(SkImageInfo::Make(glyph.fWidth, glyph.fHeight, SkColorType_for_SkMaskFormat(maskFormat), kPremul_SkAlphaType), bitmapRowBytes); if (SkMask::kBW_Format == maskFormat || SkMask::kLCD16_Format == maskFormat) { dstBitmap.allocPixels(); } else { dstBitmap.setPixels(glyph.fImage); } // Scale unscaledBitmap into dstBitmap. SkCanvas canvas(dstBitmap); #ifdef SK_SHOW_TEXT_BLIT_COVERAGE canvas.clear(0x33FF0000); #else canvas.clear(SK_ColorTRANSPARENT); #endif canvas.translate(-glyph.fLeft, -glyph.fTop); canvas.concat(bitmapTransform); canvas.translate(face->glyph->bitmap_left, -face->glyph->bitmap_top); SkSamplingOptions sampling(SkFilterMode::kLinear, SkMipmapMode::kNearest); canvas.drawImage(unscaledBitmap.asImage().get(), 0, 0, sampling, nullptr); // If the destination is BW or LCD, convert from A8. if (SkMask::kBW_Format == maskFormat) { // Copy the A8 dstBitmap into the A1 glyph.fImage. SkMask dstMask = glyph.mask(); packA8ToA1(dstMask, dstBitmap.getAddr8(0, 0), dstBitmap.rowBytes()); } else if (SkMask::kLCD16_Format == maskFormat) { // Copy the A8 dstBitmap into the LCD16 glyph.fImage. uint8_t* src = dstBitmap.getAddr8(0, 0); uint16_t* dst = reinterpret_cast<uint16_t*>(glyph.fImage); for (int y = dstBitmap.height(); y --> 0;) { for (int x = 0; x < dstBitmap.width(); ++x) { dst[x] = grayToRGB16(src[x]); } dst = (uint16_t*)((char*)dst + glyph.rowBytes()); src += dstBitmap.rowBytes(); } } } break; default: SkDEBUGFAIL("unknown glyph format"); memset(glyph.fImage, 0, glyph.rowBytes() * glyph.fHeight); return; } // We used to always do this pre-USE_COLOR_LUMINANCE, but with colorlum, // it is optional #if defined(SK_GAMMA_APPLY_TO_A8) if (SkMask::kA8_Format == glyph.fMaskFormat && fPreBlend.isApplicable()) { uint8_t* SK_RESTRICT dst = (uint8_t*)glyph.fImage; unsigned rowBytes = glyph.rowBytes(); for (int y = glyph.fHeight - 1; y >= 0; --y) { for (int x = glyph.fWidth - 1; x >= 0; --x) { dst[x] = fPreBlend.fG[dst[x]]; } dst += rowBytes; } } #endif } /////////////////////////////////////////////////////////////////////////////// namespace { class SkFTGeometrySink { SkPath* fPath; bool fStarted; FT_Vector fCurrent; void goingTo(const FT_Vector* pt) { if (!fStarted) { fStarted = true; fPath->moveTo(SkFDot6ToScalar(fCurrent.x), -SkFDot6ToScalar(fCurrent.y)); } fCurrent = *pt; } bool currentIsNot(const FT_Vector* pt) { return fCurrent.x != pt->x || fCurrent.y != pt->y; } static int Move(const FT_Vector* pt, void* ctx) { SkFTGeometrySink& self = *(SkFTGeometrySink*)ctx; if (self.fStarted) { self.fPath->close(); self.fStarted = false; } self.fCurrent = *pt; return 0; } static int Line(const FT_Vector* pt, void* ctx) { SkFTGeometrySink& self = *(SkFTGeometrySink*)ctx; if (self.currentIsNot(pt)) { self.goingTo(pt); self.fPath->lineTo(SkFDot6ToScalar(pt->x), -SkFDot6ToScalar(pt->y)); } return 0; } static int Quad(const FT_Vector* pt0, const FT_Vector* pt1, void* ctx) { SkFTGeometrySink& self = *(SkFTGeometrySink*)ctx; if (self.currentIsNot(pt0) || self.currentIsNot(pt1)) { self.goingTo(pt1); self.fPath->quadTo(SkFDot6ToScalar(pt0->x), -SkFDot6ToScalar(pt0->y), SkFDot6ToScalar(pt1->x), -SkFDot6ToScalar(pt1->y)); } return 0; } static int Cubic(const FT_Vector* pt0, const FT_Vector* pt1, const FT_Vector* pt2, void* ctx) { SkFTGeometrySink& self = *(SkFTGeometrySink*)ctx; if (self.currentIsNot(pt0) || self.currentIsNot(pt1) || self.currentIsNot(pt2)) { self.goingTo(pt2); self.fPath->cubicTo(SkFDot6ToScalar(pt0->x), -SkFDot6ToScalar(pt0->y), SkFDot6ToScalar(pt1->x), -SkFDot6ToScalar(pt1->y), SkFDot6ToScalar(pt2->x), -SkFDot6ToScalar(pt2->y)); } return 0; } public: SkFTGeometrySink(SkPath* path) : fPath{path}, fStarted{false}, fCurrent{0,0} {} static constexpr const FT_Outline_Funcs Funcs{ /*move_to =*/ SkFTGeometrySink::Move, /*line_to =*/ SkFTGeometrySink::Line, /*conic_to =*/ SkFTGeometrySink::Quad, /*cubic_to =*/ SkFTGeometrySink::Cubic, /*shift = */ 0, /*delta =*/ 0, }; }; bool generateGlyphPathStatic(FT_Face face, SkPath* path) { SkFTGeometrySink sink{path}; FT_Error err = FT_Outline_Decompose(&face->glyph->outline, &SkFTGeometrySink::Funcs, &sink); if (err != 0) { path->reset(); return false; } path->close(); return true; } bool generateFacePathStatic(FT_Face face, SkGlyphID glyphID, SkPath* path) { uint32_t flags = 0; //fLoadGlyphFlags; flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline) FT_Error err = FT_Load_Glyph(face, glyphID, flags); if (err != 0) { path->reset(); return false; } if (!generateGlyphPathStatic(face, path)) { path->reset(); return false; } return true; } #ifdef TT_SUPPORT_COLRV1 bool generateFacePathCOLRv1(FT_Face face, SkGlyphID glyphID, SkPath* path) { uint32_t flags = 0; flags |= FT_LOAD_NO_BITMAP; // ignore embedded bitmaps so we're sure to get the outline flags &= ~FT_LOAD_RENDER; // don't scan convert (we just want the outline) flags |= FT_LOAD_IGNORE_TRANSFORM; using DoneFTSize = SkFunctionWrapper<decltype(FT_Done_Size), FT_Done_Size>; std::unique_ptr<std::remove_pointer_t<FT_Size>, DoneFTSize> unscaledFtSize([face]() -> FT_Size { FT_Size size; FT_Error err = FT_New_Size(face, &size); if (err != 0) { SK_TRACEFTR(err, "FT_New_Size(%s) failed in generateFacePathStaticCOLRv1.", face->family_name); return nullptr; } return size; }()); if (!unscaledFtSize) { return false; } FT_Size oldSize = face->size; auto try_generate_path = [face, &unscaledFtSize, glyphID, flags, path]() { FT_Error err = 0; err = FT_Activate_Size(unscaledFtSize.get()); if (err != 0) { return false; } err = FT_Set_Char_Size(face, SkIntToFDot6(face->units_per_EM), SkIntToFDot6(face->units_per_EM), 72, 72); if (err != 0) { return false; } err = FT_Load_Glyph(face, glyphID, flags); if (err != 0) { path->reset(); return false; } if (!generateGlyphPathStatic(face, path)) { path->reset(); return false; } return true; }; bool path_generation_result = try_generate_path(); FT_Activate_Size(oldSize); return path_generation_result; } #endif } // namespace bool SkScalerContext_FreeType_Base::generateGlyphPath(FT_Face face, SkPath* path) { return generateGlyphPathStatic(face, path); } bool SkScalerContext_FreeType_Base::generateFacePath(FT_Face face, SkGlyphID glyphID, SkPath* path) { return generateFacePathStatic(face, glyphID, path); }
40.336545
127
0.569725
lirongfei123
b4b5c319ce7869031b763ef43519c14599bb0983
137,497
cpp
C++
lib/Runtime/Library/TypedArray.cpp
wbhsm/ChakraCore
d542c725a673260f0ebeb8051d154045b46d521f
[ "MIT" ]
1
2020-06-12T14:24:25.000Z
2020-06-12T14:24:25.000Z
lib/Runtime/Library/TypedArray.cpp
wbhsm/ChakraCore
d542c725a673260f0ebeb8051d154045b46d521f
[ "MIT" ]
1
2018-10-16T15:16:09.000Z
2018-10-16T15:16:09.000Z
lib/Runtime/Library/TypedArray.cpp
wbhsm/ChakraCore
d542c725a673260f0ebeb8051d154045b46d521f
[ "MIT" ]
6
2018-09-07T05:16:47.000Z
2021-03-23T20:30:38.000Z
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- // Implementation for typed arrays based on ArrayBuffer. // There is one nested ArrayBuffer for each typed array. Multiple typed array // can share the same array buffer. //---------------------------------------------------------------------------- #include "RuntimeLibraryPch.h" #include "AtomicsOperations.h" #define INSTANTIATE_BUILT_IN_ENTRYPOINTS(typeName) \ template Var typeName::NewInstance(RecyclableObject* function, CallInfo callInfo, ...); \ template Var typeName::EntrySet(RecyclableObject* function, CallInfo callInfo, ...); namespace Js { // explicitly instantiate these function for the built in entry point FunctionInfo INSTANTIATE_BUILT_IN_ENTRYPOINTS(Int8Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Uint8Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Uint8ClampedArray) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Int16Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Uint16Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Int32Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Uint32Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Float32Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Float64Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Int64Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(Uint64Array) INSTANTIATE_BUILT_IN_ENTRYPOINTS(BoolArray) template <> bool VarIsImpl<Uint8ClampedArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint8ClampedArray && ( VirtualTableInfo<Uint8ClampedArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint8ClampedArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Uint8Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint8Array && ( VirtualTableInfo<Uint8Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint8Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Int8Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Int8Array && ( VirtualTableInfo<Int8Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Int8Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Int16Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Int16Array && ( VirtualTableInfo<Int16Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Int16Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Uint16Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint16Array && ( VirtualTableInfo<Uint16Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint16Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Int32Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Int32Array && ( VirtualTableInfo<Int32Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Int32Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Uint32Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint32Array && ( VirtualTableInfo<Uint32Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint32Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Float32Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Float32Array && ( VirtualTableInfo<Float32Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Float32Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Float64Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Float64Array && ( VirtualTableInfo<Float64Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Float64Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Int64Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Int64Array && ( VirtualTableInfo<Int64Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Int64Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Uint64Array>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint64Array && ( VirtualTableInfo<Uint64Array>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint64Array>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<BoolArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_BoolArray && ( VirtualTableInfo<BoolArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<BoolArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Uint8ClampedVirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint8ClampedArray && ( VirtualTableInfo<Uint8ClampedVirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint8ClampedVirtualArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Uint8VirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint8Array && ( VirtualTableInfo<Uint8VirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint8VirtualArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Int8VirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Int8Array && ( VirtualTableInfo<Int8VirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Int8VirtualArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Int16VirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Int16Array && ( VirtualTableInfo<Int16VirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Int16VirtualArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Uint16VirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint16Array && ( VirtualTableInfo<Uint16VirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint16VirtualArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Int32VirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Int32Array && ( VirtualTableInfo<Int32VirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Int32VirtualArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Uint32VirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Uint32Array && ( VirtualTableInfo<Uint32VirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Uint32VirtualArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Float32VirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Float32Array && ( VirtualTableInfo<Float32VirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Float32VirtualArray>>::HasVirtualTable(obj) ); } template <> bool VarIsImpl<Float64VirtualArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == TypeIds_Float64Array && ( VirtualTableInfo<Float64VirtualArray>::HasVirtualTable(obj) || VirtualTableInfo<CrossSiteObject<Float64VirtualArray>>::HasVirtualTable(obj) ); } TypedArrayBase::TypedArrayBase(ArrayBufferBase* arrayBuffer, uint32 offSet, uint mappedLength, uint elementSize, DynamicType* type) : ArrayBufferParent(type, mappedLength, arrayBuffer), byteOffset(offSet), BYTES_PER_ELEMENT(elementSize) { } inline JsUtil::List<Var, ArenaAllocator>* IteratorToList(RecyclableObject *iterator, ScriptContext *scriptContext, ArenaAllocator *alloc) { Assert(iterator != nullptr); Var nextValue; JsUtil::List<Var, ArenaAllocator>* retList = JsUtil::List<Var, ArenaAllocator>::New(alloc); RecyclableObject* nextFunc = JavascriptOperators::CacheIteratorNext(iterator, scriptContext); while (JavascriptOperators::IteratorStepAndValue(iterator, scriptContext, nextFunc, &nextValue)) { retList->Add(nextValue); } return retList; } Var TypedArrayBase::CreateNewInstanceFromIterator(RecyclableObject *iterator, ScriptContext *scriptContext, uint32 elementSize, PFNCreateTypedArray pfnCreateTypedArray) { TypedArrayBase *newArr = nullptr; DECLARE_TEMP_GUEST_ALLOCATOR(tempAlloc); ACQUIRE_TEMP_GUEST_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime")); { JsUtil::List<Var, ArenaAllocator>* tempList = IteratorToList(iterator, scriptContext, tempAlloc); uint32 len = tempList->Count(); uint32 byteLen; if (UInt32Math::Mul(len, elementSize, &byteLen)) { JavascriptError::ThrowRangeError(scriptContext, JSERR_InvalidTypedArrayLength); } ArrayBufferBase *arrayBuffer = scriptContext->GetLibrary()->CreateArrayBuffer(byteLen); newArr = static_cast<TypedArrayBase*>(pfnCreateTypedArray(arrayBuffer, 0, len, scriptContext->GetLibrary())); for (uint32 k = 0; k < len; k++) { Var kValue = tempList->Item(k); newArr->SetItem(k, kValue); } } RELEASE_TEMP_GUEST_ALLOCATOR(tempAlloc, scriptContext); return newArr; } Var TypedArrayBase::CreateNewInstance(Arguments& args, ScriptContext* scriptContext, uint32 elementSize, PFNCreateTypedArray pfnCreateTypedArray) { uint32 byteLength = 0; int32 offset = 0; int32 mappedLength = -1; uint32 elementCount = 0; ArrayBufferBase* arrayBuffer = nullptr; TypedArrayBase* typedArraySource = nullptr; RecyclableObject* jsArraySource = nullptr; bool fromExternalObject = false; // Handle first argument - see if that is ArrayBuffer/SharedArrayBuffer if (args.Info.Count > 1) { Var firstArgument = args[1]; if (!Js::JavascriptOperators::IsObject(firstArgument)) { elementCount = ArrayBuffer::ToIndex(firstArgument, JSERR_InvalidTypedArrayLength, scriptContext, ArrayBuffer::MaxArrayBufferLength / elementSize); } else { if (VarIs<TypedArrayBase>(firstArgument)) { // Constructor(TypedArray array) typedArraySource = static_cast<TypedArrayBase*>(firstArgument); if (typedArraySource->IsDetachedBuffer()) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray]")); } elementCount = typedArraySource->GetLength(); if (elementCount >= ArrayBuffer::MaxArrayBufferLength / elementSize) { JavascriptError::ThrowRangeError(scriptContext, JSERR_InvalidTypedArrayLength); } } else if (VarIs<ArrayBufferBase>(firstArgument)) { // Constructor(ArrayBuffer buffer, // optional uint32 byteOffset, optional uint32 length) arrayBuffer = VarTo<ArrayBufferBase>(firstArgument); if (arrayBuffer->IsDetached()) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray]")); } } else { // Use GetIteratorFunction instead of GetIterator to check if it is the built-in array iterator RecyclableObject* iteratorFn = JavascriptOperators::GetIteratorFunction(firstArgument, scriptContext, true /* optional */); if (iteratorFn != nullptr && (iteratorFn != scriptContext->GetLibrary()->EnsureArrayPrototypeValuesFunction() || !JavascriptArray::IsNonES5Array(firstArgument) || JavascriptLibrary::ArrayIteratorPrototypeHasUserDefinedNext(scriptContext))) { Var iterator = scriptContext->GetThreadContext()->ExecuteImplicitCall(iteratorFn, Js::ImplicitCall_Accessor, [=]()->Js::Var { return CALL_FUNCTION(scriptContext->GetThreadContext(), iteratorFn, CallInfo(Js::CallFlags_Value, 1), VarTo<RecyclableObject>(firstArgument)); }); if (!JavascriptOperators::IsObject(iterator)) { JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject); } return CreateNewInstanceFromIterator(VarTo<RecyclableObject>(iterator), scriptContext, elementSize, pfnCreateTypedArray); } if (!JavascriptConversion::ToObject(firstArgument, scriptContext, &jsArraySource)) { // REVIEW: unclear why this JavascriptConversion::ToObject() call is being made. // It ends up calling RecyclableObject::ToObject which at least Proxy objects can // hit with non-trivial behavior. Js::Throw::FatalInternalError(); } ArrayBuffer *temp = nullptr; HRESULT hr = scriptContext->GetHostScriptContext()->ArrayBufferFromExternalObject(jsArraySource, &temp); arrayBuffer = static_cast<ArrayBufferBase *> (temp); switch (hr) { case S_OK: // We found an IBuffer fromExternalObject = true; OUTPUT_TRACE(TypedArrayPhase, _u("Projection ArrayBuffer query succeeded with HR=0x%08X\n"), hr); // We have an ArrayBuffer now, so we can skip all the object probing. break; case S_FALSE: // We didn't find an IBuffer - fall through OUTPUT_TRACE(TypedArrayPhase, _u("Projection ArrayBuffer query aborted safely with HR=0x%08X (non-handled type)\n"), hr); break; default: // Any FAILURE HRESULT or unexpected HRESULT OUTPUT_TRACE(TypedArrayPhase, _u("Projection ArrayBuffer query failed with HR=0x%08X\n"), hr); JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidTypedArray_Constructor); break; } if (!fromExternalObject) { Var lengthVar = JavascriptOperators::OP_GetLength(jsArraySource, scriptContext); elementCount = ArrayBuffer::ToIndex(lengthVar, JSERR_InvalidTypedArrayLength, scriptContext, ArrayBuffer::MaxArrayBufferLength / elementSize); } } } } // If we got an ArrayBuffer, we can continue to process arguments. if (arrayBuffer != nullptr) { byteLength = arrayBuffer->GetByteLength(); if (args.Info.Count > 2) { offset = ArrayBuffer::ToIndex(args[2], JSERR_InvalidTypedArrayLength, scriptContext, byteLength, false); // we can start the mapping from the end of the incoming buffer, but with a map of 0 length. // User can't really do anything useful with the typed array but apparently this is allowed. if ((offset % elementSize) != 0) { JavascriptError::ThrowRangeError( scriptContext, JSERR_InvalidTypedArrayLength); } } if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3])) { mappedLength = ArrayBuffer::ToIndex(args[3], JSERR_InvalidTypedArrayLength, scriptContext, (byteLength - offset) / elementSize, false); } else { if ((byteLength - offset) % elementSize != 0) { JavascriptError::ThrowRangeError( scriptContext, JSERR_InvalidTypedArrayLength); } mappedLength = (byteLength - offset)/elementSize; } } else { // Null arrayBuffer - could be new constructor or copy constructor. byteLength = elementCount * elementSize; arrayBuffer = scriptContext->GetLibrary()->CreateArrayBuffer(byteLength); } if (arrayBuffer->IsDetached()) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray]")); } if (mappedLength == -1) { mappedLength = (byteLength - offset)/elementSize; } // Create and set the array based on the source. TypedArrayBase* newArray = static_cast<TypedArrayBase*>(pfnCreateTypedArray(arrayBuffer, offset, mappedLength, scriptContext->GetLibrary())); if (fromExternalObject) { // No need to copy externally provided buffer OUTPUT_TRACE(TypedArrayPhase, _u("Created a TypedArray from an external buffer source\n")); } else if (typedArraySource) { newArray->Set(typedArraySource, offset); OUTPUT_TRACE(TypedArrayPhase, _u("Created a TypedArray from a typed array source\n")); } else if (jsArraySource) { newArray->SetObjectNoDetachCheck(jsArraySource, newArray->GetLength(), offset); OUTPUT_TRACE(TypedArrayPhase, _u("Created a TypedArray from a JavaScript array source\n")); } return newArray; } Var TypedArrayBase::NewInstance(RecyclableObject* function, CallInfo callInfo, ...) { function->GetScriptContext()->GetThreadContext()->ProbeStack(Js::Constants::MinStackDefault, function->GetScriptContext()); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'"); JavascriptOperators::GetAndAssertIsConstructorSuperCall(args); JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidTypedArray_Constructor); } template <typename TypeName, bool clamped, bool virtualAllocated> Var TypedArray<TypeName, clamped, virtualAllocated>::NewInstance(RecyclableObject* function, CallInfo callInfo, ...) { function->GetScriptContext()->GetThreadContext()->ProbeStack(Js::Constants::MinStackDefault, function->GetScriptContext()); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'"); Var newTarget = args.GetNewTarget(); bool isCtorSuperCall = JavascriptOperators::IsConstructorSuperCall(args); Assert(isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr); if (!(callInfo.Flags & CallFlags_New) || (newTarget && JavascriptOperators::IsUndefinedObject(newTarget))) { JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassConstructorCannotBeCalledWithoutNew, _u("[TypedArray]")); } Var object = nullptr; BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext()) { object = TypedArray::CreateNewInstance(args, scriptContext, sizeof(TypeName), TypedArray<TypeName, clamped, virtualAllocated>::Create); } END_SAFE_REENTRANT_CALL #if ENABLE_DEBUG_CONFIG_OPTIONS if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag)) { object = Js::JavascriptProxy::AutoProxyWrapper(object); } #endif return isCtorSuperCall ? JavascriptOperators::OrdinaryCreateFromConstructor(VarTo<RecyclableObject>(newTarget), VarTo<RecyclableObject>(object), nullptr, scriptContext) : object; }; BOOL TypedArrayBase::HasOwnProperty(PropertyId propertyId) { return JavascriptConversion::PropertyQueryFlagsToBoolean(HasPropertyQuery(propertyId, nullptr /*info*/)); } inline BOOL TypedArrayBase::CanonicalNumericIndexString(PropertyId propertyId, ScriptContext *scriptContext) { PropertyString *propertyString = scriptContext->GetPropertyString(propertyId); return CanonicalNumericIndexString(propertyString, scriptContext); } inline BOOL TypedArrayBase::CanonicalNumericIndexString(JavascriptString *propertyString, ScriptContext *scriptContext) { double result; return JavascriptConversion::CanonicalNumericIndexString(propertyString, &result, scriptContext); } PropertyQueryFlags TypedArrayBase::HasPropertyQuery(PropertyId propertyId, _Inout_opt_ PropertyValueInfo* info) { uint32 index = 0; ScriptContext *scriptContext = GetScriptContext(); if (scriptContext->IsNumericPropertyId(propertyId, &index)) { // All the slots within the length of the array are valid. return index < this->GetLength() ? PropertyQueryFlags::Property_Found : PropertyQueryFlags::Property_NotFound_NoProto; } if (!scriptContext->GetPropertyName(propertyId)->IsSymbol() && CanonicalNumericIndexString(propertyId, scriptContext)) { return PropertyQueryFlags::Property_NotFound_NoProto; } return DynamicObject::HasPropertyQuery(propertyId, info); } BOOL TypedArrayBase::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags) { uint32 index = 0; if (GetScriptContext()->IsNumericPropertyId(propertyId, &index) && (index < this->GetLength())) { // All the slots within the length of the array are valid. return false; } return DynamicObject::DeleteProperty(propertyId, flags); } BOOL TypedArrayBase::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags) { PropertyRecord const *propertyRecord = nullptr; if (JavascriptOperators::ShouldTryDeleteProperty(this, propertyNameString, &propertyRecord)) { Assert(propertyRecord); return DeleteProperty(propertyRecord->GetPropertyId(), flags); } return TRUE; } PropertyQueryFlags TypedArrayBase::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext) { return TypedArrayBase::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext); } PropertyQueryFlags TypedArrayBase::GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext) { const Js::PropertyRecord* propertyRecord = requestContext->GetPropertyName(propertyId); if (propertyRecord->IsNumeric()) { *value = this->DirectGetItem(propertyRecord->GetNumericValue()); if (JavascriptOperators::GetTypeId(*value) == Js::TypeIds_Undefined) { return PropertyQueryFlags::Property_NotFound; } return PropertyQueryFlags::Property_Found; } if (!propertyRecord->IsSymbol() && CanonicalNumericIndexString(propertyId, requestContext)) { *value = requestContext->GetLibrary()->GetUndefined(); return PropertyQueryFlags::Property_NotFound_NoProto; } return DynamicObject::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext); } PropertyQueryFlags TypedArrayBase::GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext) { AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()), "Numeric property names should have been converted to uint or PropertyRecord*"); if (CanonicalNumericIndexString(propertyNameString, requestContext)) { *value = requestContext->GetLibrary()->GetUndefined(); return PropertyQueryFlags::Property_NotFound_NoProto; } return DynamicObject::GetPropertyQuery(originalInstance, propertyNameString, value, info, requestContext); } PropertyQueryFlags TypedArrayBase::HasItemQuery(uint32 index) { if (this->IsDetachedBuffer()) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_DetachedTypedArray); } if (index < GetLength()) { return PropertyQueryFlags::Property_Found; } return PropertyQueryFlags::Property_NotFound_NoProto; } BOOL TypedArrayBase::DeleteItem(uint32 index, Js::PropertyOperationFlags flags) { JavascriptError::ThrowCantDeleteIfStrictModeOrNonconfigurable( flags, GetScriptContext(), GetScriptContext()->GetIntegerString(index)->GetString()); return FALSE; } PropertyQueryFlags TypedArrayBase::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext) { *value = DirectGetItem(index); return index < GetLength() ? PropertyQueryFlags::Property_Found : PropertyQueryFlags::Property_NotFound_NoProto; } PropertyQueryFlags TypedArrayBase::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext) { *value = DirectGetItem(index); return index < GetLength() ? PropertyQueryFlags::Property_Found : PropertyQueryFlags::Property_NotFound_NoProto; } BOOL TypedArrayBase::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info) { ScriptContext *scriptContext = GetScriptContext(); const PropertyRecord* propertyRecord = scriptContext->GetPropertyName(propertyId); if (propertyRecord->IsNumeric()) { this->DirectSetItem(propertyRecord->GetNumericValue(), value); return true; } if (!propertyRecord->IsSymbol() && CanonicalNumericIndexString(propertyId, scriptContext)) { return FALSE; } else { return DynamicObject::SetProperty(propertyId, value, flags, info); } } BOOL TypedArrayBase::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info) { AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()), "Numeric property names should have been converted to uint or PropertyRecord*"); ScriptContext *requestContext = GetScriptContext(); if (CanonicalNumericIndexString(propertyNameString, requestContext)) { return FALSE; // Integer-index exotic object should not set property that is canonical numeric index string but came to this overload } return DynamicObject::SetProperty(propertyNameString, value, flags, info); } DescriptorFlags TypedArrayBase::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext) { if (!requestContext->GetPropertyName(propertyId)->IsSymbol() && CanonicalNumericIndexString(propertyId, requestContext)) { return None_NoProto; } return __super::GetSetter(propertyId, setterValue, info, requestContext); } DescriptorFlags TypedArrayBase::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext) { if (CanonicalNumericIndexString(propertyNameString, requestContext)) { return None_NoProto; } return __super::GetSetter(propertyNameString, setterValue, info, requestContext); } DescriptorFlags TypedArrayBase::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext) { #if ENABLE_COPYONACCESS_ARRAY JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this); #endif if (index >= this->GetLength()) { return None_NoProto; } return __super::GetItemSetter(index, setterValue, requestContext); } BOOL TypedArrayBase::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, EnumeratorCache * enumeratorCache) { return enumerator->Initialize(nullptr, this, this, flags, requestContext, enumeratorCache); } JavascriptEnumerator * TypedArrayBase::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext * requestContext) { return RecyclerNew(requestContext->GetRecycler(), TypedArrayIndexEnumerator, this, flags, requestContext); } BOOL TypedArrayBase::SetItem(uint32 index, Var value, PropertyOperationFlags flags) { if (flags == PropertyOperation_None && index >= GetLength()) { return false; } DirectSetItem(index, value); return true; } BOOL TypedArrayBase::IsEnumerable(PropertyId propertyId) { uint32 index = 0; if (GetScriptContext()->IsNumericPropertyId(propertyId, &index)) { return true; } return DynamicObject::IsEnumerable(propertyId); } BOOL TypedArrayBase::IsConfigurable(PropertyId propertyId) { uint32 index = 0; if (GetScriptContext()->IsNumericPropertyId(propertyId, &index)) { return false; } return DynamicObject::IsConfigurable(propertyId); } BOOL TypedArrayBase::InitProperty(Js::PropertyId propertyId, Js::Var value, PropertyOperationFlags flags, Js::PropertyValueInfo* info) { return SetProperty(propertyId, value, flags, info); } BOOL TypedArrayBase::IsWritable(PropertyId propertyId) { uint32 index = 0; if (GetScriptContext()->IsNumericPropertyId(propertyId, &index)) { return true; } return DynamicObject::IsWritable(propertyId); } BOOL TypedArrayBase::SetEnumerable(PropertyId propertyId, BOOL value) { ScriptContext* scriptContext = GetScriptContext(); uint32 index; // all numeric properties are enumerable if (scriptContext->IsNumericPropertyId(propertyId, &index) ) { if (!value) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DefineProperty_NotConfigurable, scriptContext->GetThreadContext()->GetPropertyName(propertyId)->GetBuffer()); } return true; } return __super::SetEnumerable(propertyId, value); } BOOL TypedArrayBase::SetWritable(PropertyId propertyId, BOOL value) { ScriptContext* scriptContext = GetScriptContext(); uint32 index; // default is writable if (scriptContext->IsNumericPropertyId(propertyId, &index)) { if (!value) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DefineProperty_NotConfigurable, scriptContext->GetThreadContext()->GetPropertyName(propertyId)->GetBuffer()); } return true; } return __super::SetWritable(propertyId, value); } BOOL TypedArrayBase::SetConfigurable(PropertyId propertyId, BOOL value) { ScriptContext* scriptContext = GetScriptContext(); uint32 index; // default is not configurable if (scriptContext->IsNumericPropertyId(propertyId, &index)) { if (value) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DefineProperty_NotConfigurable, scriptContext->GetThreadContext()->GetPropertyName(propertyId)->GetBuffer()); } return true; } return __super::SetConfigurable(propertyId, value); } BOOL TypedArrayBase::SetAttributes(PropertyId propertyId, PropertyAttributes attributes) { ScriptContext* scriptContext = this->GetScriptContext(); uint32 index; if (scriptContext->IsNumericPropertyId(propertyId, &index)) { VerifySetItemAttributes(propertyId, attributes); return true; } return __super::SetAttributes(propertyId, attributes); } BOOL TypedArrayBase::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags) { ScriptContext* scriptContext = this->GetScriptContext(); uint32 index; if (scriptContext->IsNumericPropertyId(propertyId, &index)) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DefineProperty_NotConfigurable, GetScriptContext()->GetThreadContext()->GetPropertyName(propertyId)->GetBuffer()); } return __super::SetAccessors(propertyId, getter, setter, flags); } BOOL TypedArrayBase::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects) { ScriptContext* scriptContext = GetScriptContext(); const PropertyRecord* propertyRecord = scriptContext->GetPropertyName(propertyId); if (propertyRecord->IsNumeric()) { VerifySetItemAttributes(propertyId, attributes); return SetItem(propertyRecord->GetNumericValue(), value); } if (!propertyRecord->IsSymbol() && CanonicalNumericIndexString(propertyId, scriptContext)) { return FALSE; } return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects); } BOOL TypedArrayBase::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes) { VerifySetItemAttributes(Constants::NoProperty, attributes); return SetItem(index, value); } BOOL TypedArrayBase::IsObjectArrayFrozen() { if (GetLength() > 0) { return false; // the backing buffer is always modifiable } return IsSealed(); } BOOL TypedArrayBase::Is(TypeId typeId) { return typeId >= TypeIds_TypedArrayMin && typeId <= TypeIds_TypedArrayMax; } BOOL TypedArrayBase::IsDetachedTypedArray(Var aValue) { TypedArrayBase* arr = JavascriptOperators::TryFromVar<TypedArrayBase>(aValue); return arr && arr->IsDetachedBuffer(); } void TypedArrayBase::Set(TypedArrayBase* source, uint32 offset) { uint32 sourceLength = source->GetLength(); uint32 totalLength; if (UInt32Math::Add(offset, sourceLength, &totalLength) || (totalLength > GetLength())) { JavascriptError::ThrowRangeError( GetScriptContext(), JSERR_InvalidTypedArrayLength); } if (source->IsDetachedBuffer()) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_DetachedTypedArray); } // memmove buffer if views have same bit representation. // types of the same size are compatible, with the following exceptions: // - we cannot memmove between float and int arrays, due to different bit pattern // - we cannot memmove to a uint8 clamped array from an int8 array, due to negatives rounding to 0 if (GetTypeId() == source->GetTypeId() || (GetBytesPerElement() == source->GetBytesPerElement() && !((VarIs<Uint8ClampedArray>(this) || VarIs<Uint8ClampedVirtualArray>(this)) && (VarIs<Int8Array>(source) || VarIs<Int8VirtualArray>(source))) && !VarIs<Float32Array>(this) && !VarIs<Float32Array>(source) && !VarIs<Float32VirtualArray>(this) && !VarIs<Float32VirtualArray>(source) && !VarIs<Float64Array>(this) && !VarIs<Float64Array>(source) && !VarIs<Float64VirtualArray>(this) && !VarIs<Float64VirtualArray>(source))) { const size_t offsetInBytes = offset * BYTES_PER_ELEMENT; memmove_s(buffer + offsetInBytes, GetByteLength() - offsetInBytes, source->GetByteBuffer(), source->GetByteLength()); } else { if (source->GetArrayBuffer() != GetArrayBuffer()) { for (uint32 i = 0; i < sourceLength; i++) { DirectSetItemNoDetachCheck(offset + i, source->DirectGetItemNoDetachCheck(i)); } } else { // We can have the source and destination coming from the same buffer. element size, start offset, and // length for source and dest typed array can be different. Use a separate tmp buffer to copy the elements. Js::JavascriptArray* tmpArray = GetScriptContext()->GetLibrary()->CreateArray(sourceLength); for (uint32 i = 0; i < sourceLength; i++) { tmpArray->SetItem(i, source->DirectGetItem(i), PropertyOperation_None); } for (uint32 i = 0; i < sourceLength; i++) { DirectSetItem(offset + i, tmpArray->DirectGetItem(i)); } } if (source->IsDetachedBuffer() || this->IsDetachedBuffer()) { Throw::FatalInternalError(); } } } uint32 TypedArrayBase::GetSourceLength(RecyclableObject* arraySource, uint32 targetLength, uint32 offset) { ScriptContext* scriptContext = GetScriptContext(); uint32 sourceLength = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetProperty(arraySource, PropertyIds::length, scriptContext), scriptContext); uint32 totalLength; if (UInt32Math::Add(offset, sourceLength, &totalLength) || (totalLength > targetLength)) { JavascriptError::ThrowRangeError( scriptContext, JSERR_InvalidTypedArrayLength); } return sourceLength; } void TypedArrayBase::SetObjectNoDetachCheck(RecyclableObject* source, uint32 targetLength, uint32 offset) { ScriptContext* scriptContext = GetScriptContext(); uint32 sourceLength = GetSourceLength(source, targetLength, offset); Assert(!this->IsDetachedBuffer()); Var itemValue; Var undefinedValue = scriptContext->GetLibrary()->GetUndefined(); for (uint32 i = 0; i < sourceLength; i++) { if (!source->GetItem(source, i, &itemValue, scriptContext)) { itemValue = undefinedValue; } DirectSetItemNoDetachCheck(offset + i, itemValue); } if (this->IsDetachedBuffer()) { // We cannot be detached when we are creating the typed array itself. Terminate if that happens. Throw::FatalInternalError(); } } // Getting length from the source object can detach the typedarray, and thus set it's length as 0, // this is observable because RangeError will be thrown instead of a TypeError further down the line void TypedArrayBase::SetObject(RecyclableObject* source, uint32 targetLength, uint32 offset) { ScriptContext* scriptContext = GetScriptContext(); uint32 sourceLength = GetSourceLength(source, targetLength, offset); Var itemValue; Var undefinedValue = scriptContext->GetLibrary()->GetUndefined(); for (uint32 i = 0; i < sourceLength; i ++) { if (!source->GetItem(source, i, &itemValue, scriptContext)) { itemValue = undefinedValue; } DirectSetItem(offset + i, itemValue); } } HRESULT TypedArrayBase::GetBuffer(Var instance, ArrayBuffer** outBuffer, uint32* outOffset, uint32* outLength) { HRESULT hr = NOERROR; if (Js::VarIs<Js::TypedArrayBase>(instance)) { Js::TypedArrayBase* typedArrayBase = Js::VarTo<Js::TypedArrayBase>(instance); *outBuffer = typedArrayBase->GetArrayBuffer()->GetAsArrayBuffer(); *outOffset = typedArrayBase->GetByteOffset(); *outLength = typedArrayBase->GetByteLength(); } else if (Js::VarIs<Js::ArrayBuffer>(instance)) { Js::ArrayBuffer* buffer = Js::VarTo<Js::ArrayBuffer>(instance); *outBuffer = buffer; *outOffset = 0; *outLength = buffer->GetByteLength(); } else if (Js::VarIs<Js::DataView>(instance)) { Js::DataView* dView = Js::VarTo<Js::DataView>(instance); *outBuffer = dView->GetArrayBuffer()->GetAsArrayBuffer(); *outOffset = dView->GetByteOffset(); *outLength = dView->GetLength(); } else { hr = E_INVALIDARG; } return hr; } void TypedArrayBase::ClearLengthAndBufferOnDetach() { AssertMsg(IsDetachedBuffer(), "Array buffer should be detached if we're calling this method"); this->length = 0; #if INT32VAR this->buffer = (BYTE*)TaggedInt::ToVarUnchecked(0); #else this->buffer = nullptr; #endif } Var TypedArrayBase::EntryGetterBuffer(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); if (args.Info.Count == 0 || !VarIs<TypedArrayBase>(args[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } TypedArrayBase* typedArray = UnsafeVarTo<TypedArrayBase>(args[0]); ArrayBufferBase* arrayBuffer = typedArray->GetArrayBuffer(); if (arrayBuffer == nullptr) { JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject); } return arrayBuffer; } Var TypedArrayBase::EntryGetterByteLength(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); if (args.Info.Count == 0 || !VarIs<TypedArrayBase>(args[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } TypedArrayBase* typedArray = UnsafeVarTo<TypedArrayBase>(args[0]); ArrayBufferBase* arrayBuffer = typedArray->GetArrayBuffer(); if (arrayBuffer == nullptr) { JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject); } else if (arrayBuffer->IsDetached()) { return TaggedInt::ToVarUnchecked(0); } return JavascriptNumber::ToVar(typedArray->GetByteLength(), scriptContext); } Var TypedArrayBase::EntryGetterByteOffset(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); if (args.Info.Count == 0 || !VarIs<TypedArrayBase>(args[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } TypedArrayBase* typedArray = UnsafeVarTo<TypedArrayBase>(args[0]); ArrayBufferBase* arrayBuffer = typedArray->GetArrayBuffer(); if (arrayBuffer == nullptr) { JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject); } else if (arrayBuffer->IsDetached()) { return TaggedInt::ToVarUnchecked(0); } return JavascriptNumber::ToVar(typedArray->GetByteOffset(), scriptContext); } Var TypedArrayBase::EntryGetterLength(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); if (args.Info.Count == 0 || !VarIs<TypedArrayBase>(args[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } TypedArrayBase* typedArray = UnsafeVarTo<TypedArrayBase>(args[0]); ArrayBufferBase* arrayBuffer = typedArray->GetArrayBuffer(); if (arrayBuffer == nullptr) { JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedArrayBufferObject); } else if (arrayBuffer->IsDetached()) { return TaggedInt::ToVarUnchecked(0); } return JavascriptNumber::ToVar(typedArray->GetLength(), scriptContext); } Var TypedArrayBase::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...) { ARGUMENTS(args, callInfo); Assert(args.Info.Count > 0); return args[0]; } // ES2017 22.2.3.32 get %TypedArray%.prototype[@@toStringTag] Var TypedArrayBase::EntryGetterSymbolToStringTag(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); // 1. Let O be the this value. // 2. If Type(O) is not Object, return undefined. // 3. If O does not have a[[TypedArrayName]] internal slot, return undefined. if (args.Info.Count == 0 || !VarIs<TypedArrayBase>(args[0])) { if (scriptContext->GetConfig()->IsES6ToStringTagEnabled()) { return scriptContext->GetLibrary()->GetUndefined(); } else { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } } // 4. Let name be O.[[TypedArrayName]]. // 5. Assert: name is a String value. // 6. Return name. Var name; switch (JavascriptOperators::GetTypeId(args[0])) { case TypeIds_Int8Array: name = scriptContext->GetPropertyString(PropertyIds::Int8Array); break; case TypeIds_Uint8Array: name = scriptContext->GetPropertyString(PropertyIds::Uint8Array); break; case TypeIds_Uint8ClampedArray: name = scriptContext->GetPropertyString(PropertyIds::Uint8ClampedArray); break; case TypeIds_Int16Array: name = scriptContext->GetPropertyString(PropertyIds::Int16Array); break; case TypeIds_Uint16Array: name = scriptContext->GetPropertyString(PropertyIds::Uint16Array); break; case TypeIds_Int32Array: name = scriptContext->GetPropertyString(PropertyIds::Int32Array); break; case TypeIds_Uint32Array: name = scriptContext->GetPropertyString(PropertyIds::Uint32Array); break; case TypeIds_Float32Array: name = scriptContext->GetPropertyString(PropertyIds::Float32Array); break; case TypeIds_Float64Array: name = scriptContext->GetPropertyString(PropertyIds::Float64Array); break; default: name = scriptContext->GetLibrary()->GetUndefinedDisplayString(); break; } return name; } Var TypedArrayBase::EntrySet(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); if (args.Info.Count == 0 || !VarIs<TypedArrayBase>(args[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } return CommonSet(args); } template <typename TypeName, bool clamped, bool virtualAllocated> Var TypedArray<TypeName, clamped, virtualAllocated>::EntrySet(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); // This method is only called in pre-ES6 compat modes. In those modes, we need to throw an error // if the this argument is not the same type as our TypedArray template instance. if (args.Info.Count == 0 || !VarIs<TypedArray>(args[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } return CommonSet(args); } Var TypedArrayBase::CommonSet(Arguments& args) { TypedArrayBase* typedArrayBase = VarTo<TypedArrayBase>(args[0]); ScriptContext* scriptContext = typedArrayBase->GetScriptContext(); uint32 offset = 0; if (args.Info.Count < 2) { JavascriptError::ThrowTypeError(scriptContext, JSERR_TypedArray_NeedSource); } if (args.Info.Count > 2) { offset = ArrayBuffer::ToIndex(args[2], JSERR_InvalidTypedArrayLength, scriptContext, ArrayBuffer::MaxArrayBufferLength, false); } TypedArrayBase* typedArraySource = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(args[1]); if (typedArraySource) { if (typedArraySource->IsDetachedBuffer() || typedArrayBase->IsDetachedBuffer()) // If IsDetachedBuffer(targetBuffer) is true, then throw a TypeError exception. { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray].prototype.set")); } typedArrayBase->Set(typedArraySource, (uint32)offset); } else { RecyclableObject* sourceArray; #if ENABLE_COPYONACCESS_ARRAY JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]); #endif if (!JavascriptConversion::ToObject(args[1], scriptContext, &sourceArray)) { JavascriptError::ThrowTypeError(scriptContext, JSERR_TypedArray_NeedSource); } else if (typedArrayBase->IsDetachedBuffer()) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray].prototype.set")); } typedArrayBase->SetObject(sourceArray, typedArrayBase->GetLength(), (uint32)offset); } return scriptContext->GetLibrary()->GetUndefined(); } Var TypedArrayBase::EntrySubarray(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_subarray); if (args.Info.Count == 0 || !VarIs<TypedArrayBase>(args[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } return CommonSubarray(args); } uint32 TypedArrayBase::GetFromIndex(Var arg, uint32 length, ScriptContext *scriptContext) { uint32 index = JavascriptArray::GetFromIndex(arg, length, scriptContext); Assert(index <= length); return index; } Var TypedArrayBase::CommonSubarray(Arguments& args) { TypedArrayBase* typedArrayBase = VarTo<TypedArrayBase>(args[0]); uint32 length = typedArrayBase->GetLength(); ScriptContext* scriptContext = typedArrayBase->GetScriptContext(); int32 begin = 0; int end = length; if (args.Info.Count > 1) { begin = TypedArrayBase::GetFromIndex(args[1], length, scriptContext); if (args.Info.Count > 2 && !JavascriptOperators::IsUndefined(args[2])) { end = TypedArrayBase::GetFromIndex(args[2], length, scriptContext); } } if (end < begin) { end = begin; } return typedArrayBase->Subarray(begin, end); } template <typename TypeName, bool clamped, bool virtualAllocated> Var TypedArray<TypeName, clamped, virtualAllocated>::Subarray(uint32 begin, uint32 end) { Assert(end >= begin); Var newTypedArray; ScriptContext* scriptContext = this->GetScriptContext(); ArrayBufferBase* buffer = this->GetArrayBuffer(); uint32 srcByteOffset = this->GetByteOffset(); uint32 beginByteOffset = srcByteOffset + begin * BYTES_PER_ELEMENT; uint32 newLength = end - begin; JavascriptFunction* defaultConstructor = TypedArrayBase::GetDefaultConstructor(this, scriptContext); RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(this, defaultConstructor, scriptContext); AssertOrFailFast(JavascriptOperators::IsConstructor(constructor)); bool isDefaultConstructor = constructor == defaultConstructor; newTypedArray = VarTo<RecyclableObject>(JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var { Js::Var constructorArgs[] = { constructor, buffer, JavascriptNumber::ToVar(beginByteOffset, scriptContext), JavascriptNumber::ToVar(newLength, scriptContext) }; Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs)); return TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), newLength, scriptContext); })); return newTypedArray; } // %TypedArray%.from as described in ES6.0 (draft 22) Section 22.2.2.1 Var TypedArrayBase::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); JavascriptLibrary* library = scriptContext->GetLibrary(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].from")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_from); if (args.Info.Count < 1 || !JavascriptOperators::IsConstructor(args[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].from")); } RecyclableObject* constructor = VarTo<RecyclableObject>(args[0]); bool isDefaultConstructor = JavascriptLibrary::IsTypedArrayConstructor(constructor, scriptContext); RecyclableObject* items = nullptr; if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items)) { JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("[TypedArray].from")); } bool mapping = false; RecyclableObject* mapFn = nullptr; Var mapFnThisArg = nullptr; if (args.Info.Count >= 3) { if (!JavascriptConversion::IsCallable(args[2])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].from")); } mapFn = VarTo<RecyclableObject>(args[2]); if (args.Info.Count >= 4) { mapFnThisArg = args[3]; } else { mapFnThisArg = library->GetUndefined(); } mapping = true; } Var newObj; RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */); if (iterator != nullptr) { DECLARE_TEMP_GUEST_ALLOCATOR(tempAlloc); ACQUIRE_TEMP_GUEST_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime")); { // Create a temporary list to hold the items returned from the iterator. // We will then iterate over this list and append those items into the object we will return. // We have to collect the items into this temporary list because we need to call the // new object constructor with a length of items and we don't know what length will be // until we iterate across all the items. // Consider: Could be possible to fast-path this in order to avoid creating the temporary list // for types we know such as TypedArray. We know the length of a TypedArray but we still // have to be careful in case there is a proxy which could return anything from [[Get]] // or the built-in @@iterator has been replaced. JsUtil::List<Var, ArenaAllocator>* tempList = IteratorToList(iterator, scriptContext, tempAlloc); uint32 len = tempList->Count(); newObj = JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var { Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) }; Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs)); return TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext); }); TypedArrayBase* newTypedArrayBase = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj); JavascriptArray* newArr = nullptr; if (!newTypedArrayBase) { newArr = JavascriptArray::TryVarToNonES5Array(newObj); } for (uint32 k = 0; k < len; k++) { Var kValue = tempList->Item(k); if (mapping) { Assert(mapFn != nullptr); Assert(mapFnThisArg != nullptr); Var kVar = JavascriptNumber::ToVar(k, scriptContext); kValue = scriptContext->GetThreadContext()->ExecuteImplicitCall(mapFn, Js::ImplicitCall_Accessor, [=]()->Js::Var { return CALL_FUNCTION(scriptContext->GetThreadContext(), mapFn, CallInfo(CallFlags_Value, 3), mapFnThisArg, kValue, kVar); }); } // We're likely to have constructed a new TypedArray, but the constructor could return any object if (newTypedArrayBase) { newTypedArrayBase->DirectSetItem(k, kValue); } else if (newArr) { newArr->SetItem(k, kValue, Js::PropertyOperation_ThrowIfNotExtensible); } else { JavascriptOperators::OP_SetElementI_UInt32(newObj, k, kValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible); } } } RELEASE_TEMP_GUEST_ALLOCATOR(tempAlloc, scriptContext); } else { Var lenValue = JavascriptOperators::OP_GetLength(items, scriptContext); uint32 len = JavascriptConversion::ToUInt32(lenValue, scriptContext); TypedArrayBase* itemsTypedArrayBase = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(items); JavascriptArray* itemsArray = nullptr; if (!itemsTypedArrayBase) { itemsArray = JavascriptArray::TryVarToNonES5Array(items); } newObj = JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var { Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) }; Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs)); return TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext); }); TypedArrayBase* newTypedArrayBase = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj); JavascriptArray* newArr = nullptr; if (!newTypedArrayBase) { newArr = JavascriptArray::TryVarToNonES5Array(newObj); } for (uint32 k = 0; k < len; k++) { Var kValue; // The items source could be anything, but we already know if it's a TypedArray or Array if (itemsTypedArrayBase) { kValue = itemsTypedArrayBase->DirectGetItem(k); } else if (itemsArray) { kValue = itemsArray->DirectGetItem(k); } else { kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext); } if (mapping) { Assert(mapFn != nullptr); Assert(mapFnThisArg != nullptr); Var kVar = JavascriptNumber::ToVar(k, scriptContext); kValue = scriptContext->GetThreadContext()->ExecuteImplicitCall(mapFn, Js::ImplicitCall_Accessor, [=]()->Js::Var { return CALL_FUNCTION(scriptContext->GetThreadContext(), mapFn, CallInfo(CallFlags_Value, 3), mapFnThisArg, kValue, kVar); }); } // If constructor built a TypedArray (likely) or Array (maybe likely) we can do a more direct set operation if (newTypedArrayBase) { newTypedArrayBase->DirectSetItem(k, kValue); } else if (newArr) { newArr->SetItem(k, kValue, Js::PropertyOperation_ThrowIfNotExtensible); } else { JavascriptOperators::OP_SetElementI_UInt32(newObj, k, kValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible); } } } return newObj; } Var TypedArrayBase::EntryOf(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_of); if (args.Info.Count < 1) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of")); } return JavascriptArray::OfHelper(true, args, scriptContext); } Var TypedArrayBase::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_copyWithin); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.copyWithin")); uint32 length = typedArrayBase->GetLength(); return JavascriptArray::CopyWithinHelper(nullptr, typedArrayBase, typedArrayBase, length, args, scriptContext); } Var TypedArrayBase::GetKeysEntriesValuesHelper(Arguments& args, ScriptContext *scriptContext, LPCWSTR apiName, JavascriptArrayIteratorKind kind) { TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, apiName); #ifdef ENABLE_JS_BUILTINS JavascriptLibrary * library = scriptContext->GetLibrary(); if (scriptContext->IsJsBuiltInEnabled()) { JavascriptString* methodName = JavascriptString::NewWithSz(_u("CreateArrayIterator"), scriptContext); PropertyIds functionIdentifier = JavascriptOperators::GetPropertyId(methodName, scriptContext); Var scriptFunction = JavascriptOperators::OP_GetProperty(library->GetChakraLib(), functionIdentifier, scriptContext); Assert(!JavascriptOperators::IsUndefinedOrNull(scriptFunction)); Assert(JavascriptConversion::IsCallable(scriptFunction)); RecyclableObject* function = VarTo<RecyclableObject>(scriptFunction); Var chakraLibObj = JavascriptOperators::OP_GetProperty(library->GetGlobalObject(), PropertyIds::__chakraLibrary, scriptContext); Var argsIt[] = { chakraLibObj, args[0], TaggedInt::ToVarUnchecked((int)kind) }; CallInfo callInfo(CallFlags_Value, 3); BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext()) { return JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), Js::Arguments(callInfo, argsIt)); } END_SAFE_REENTRANT_CALL } else #endif return scriptContext->GetLibrary()->CreateArrayIterator(typedArrayBase, kind); } Var TypedArrayBase::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_entries); return GetKeysEntriesValuesHelper(args, scriptContext, _u("[TypedArray].prototype.entries"), JavascriptArrayIteratorKind::KeyAndValue); } Var TypedArrayBase::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.every")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_every); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.every")); return JavascriptArray::EveryHelper(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } Var TypedArrayBase::EntryFill(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_fill); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.fill")); return JavascriptArray::FillHelper(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } // %TypedArray%.prototype.filter as described in ES6.0 (draft 22) Section 22.2.3.9 Var TypedArrayBase::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.filter")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_filter); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.filter")); uint32 length = typedArrayBase->GetLength(); if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.filter")); } RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]); Var thisArg = nullptr; if (args.Info.Count > 2) { thisArg = args[2]; } else { thisArg = scriptContext->GetLibrary()->GetUndefined(); } // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes CallFlags flags = CallFlags_Value; Var element = nullptr; Var selected = nullptr; RecyclableObject* newObj = nullptr; DECLARE_TEMP_GUEST_ALLOCATOR(tempAlloc); ACQUIRE_TEMP_GUEST_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime")); { // Create a temporary list to hold the items selected by the callback function. // We will then iterate over this list and append those items into the object we will return. // We have to collect the items into this temporary list because we need to call the // new object constructor with a length of items and we don't know what length will be // until we know how many items we will collect. JsUtil::List<Var, ArenaAllocator>* tempList = JsUtil::List<Var, ArenaAllocator>::New(tempAlloc); for (uint32 k = 0; k < length; k++) { // We know that the TypedArray.HasItem will be true because k < length and we can skip the check in the TypedArray version of filter. element = typedArrayBase->DirectGetItem(k); BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext()) { selected = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg, element, JavascriptNumber::ToVar(k, scriptContext), typedArrayBase); } END_SAFE_REENTRANT_CALL if (JavascriptConversion::ToBoolean(selected, scriptContext)) { tempList->Add(element); } } uint32 captured = tempList->Count(); JavascriptFunction* defaultConstructor = TypedArrayBase::GetDefaultConstructor(args[0], scriptContext); RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, defaultConstructor, scriptContext); AssertOrFailFast(JavascriptOperators::IsConstructor(constructor)); bool isDefaultConstructor = constructor == defaultConstructor; newObj = VarTo<RecyclableObject>(JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var { Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(captured, scriptContext) }; Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs)); return TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), captured, scriptContext); })); TypedArrayBase* newArr = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj); if (newArr) { // We are much more likely to have a TypedArray here than anything else for (uint32 i = 0; i < captured; i++) { newArr->DirectSetItem(i, tempList->Item(i)); } } else { for (uint32 i = 0; i < captured; i++) { JavascriptOperators::OP_SetElementI_UInt32(newObj, i, tempList->Item(i), scriptContext, PropertyOperation_ThrowIfNotExtensible); } } } RELEASE_TEMP_GUEST_ALLOCATOR(tempAlloc, scriptContext); return newObj; } Var TypedArrayBase::EntryFind(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.find")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_find); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.find")); return JavascriptArray::FindHelper<false>(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } Var TypedArrayBase::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.findIndex")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_findIndex); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.findIndex")); return JavascriptArray::FindHelper<true>(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } // %TypedArray%.prototype.forEach as described in ES6.0 (draft 22) Section 22.2.3.12 Var TypedArrayBase::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.forEach")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_forEach); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.forEach")); uint32 length = typedArrayBase->GetLength(); if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.forEach")); } RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]); Var thisArg; if (args.Info.Count > 2) { thisArg = args[2]; } else { thisArg = scriptContext->GetLibrary()->GetUndefined(); } for (uint32 k = 0; k < length; k++) { // No need for HasItem, as we have already established that this API can be called only on the TypedArray object. So Proxy scenario cannot happen. Var element = typedArrayBase->DirectGetItem(k); BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext()) { CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(CallFlags_Value, 4), thisArg, element, JavascriptNumber::ToVar(k, scriptContext), typedArrayBase); } END_SAFE_REENTRANT_CALL } return scriptContext->GetLibrary()->GetUndefined(); } Var TypedArrayBase::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_indexOf); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.indexOf")); uint32 length = typedArrayBase->GetLength(); Var search = nullptr; uint32 fromIndex; if (!JavascriptArray::GetParamForIndexOf(length, args, search, fromIndex, scriptContext)) { return TaggedInt::ToVarUnchecked(-1); } return JavascriptArray::TemplatedIndexOfHelper<false>(typedArrayBase, search, fromIndex, length, scriptContext); } Var TypedArrayBase::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_includes); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.includes")); uint32 length = typedArrayBase->GetLength(); Var search = nullptr; uint32 fromIndex; if (!JavascriptArray::GetParamForIndexOf(length, args, search, fromIndex, scriptContext)) { return scriptContext->GetLibrary()->GetFalse(); } return JavascriptArray::TemplatedIndexOfHelper<true>(typedArrayBase, search, fromIndex, length, scriptContext); } Var TypedArrayBase::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_join); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.join")); uint32 length = typedArrayBase->GetLength(); JavascriptLibrary* library = scriptContext->GetLibrary(); JavascriptString* separator = nullptr; if (args.Info.Count > 1 && !JavascriptOperators::IsUndefined(args[1])) { separator = JavascriptConversion::ToString(args[1], scriptContext); } else { separator = library->GetCommaDisplayString(); } if (length == 0) { return library->GetEmptyString(); } else if (length == 1) { return JavascriptConversion::ToString(typedArrayBase->DirectGetItem(0), scriptContext); } bool hasSeparator = (separator->GetLength() != 0); charcount_t estimatedAppendSize = min( static_cast<charcount_t>((64 << 20) / sizeof(void *)), // 64 MB worth of pointers static_cast<charcount_t>(length + (hasSeparator ? length - 1 : 0))); CompoundString* const cs = CompoundString::NewWithPointerCapacity(estimatedAppendSize, library); Assert(length >= 2); JavascriptString* element = JavascriptConversion::ToString(typedArrayBase->DirectGetItem(0), scriptContext); cs->Append(element); for (uint32 i = 1; i < length; i++) { if (hasSeparator) { cs->Append(separator); } // Since i < length, we can be certain that the TypedArray contains an item at index i and we don't have to check for undefined element = JavascriptConversion::ToString(typedArrayBase->DirectGetItem(i), scriptContext); cs->Append(element); } return cs; } Var TypedArrayBase::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_keys); return GetKeysEntriesValuesHelper(args, scriptContext, _u("[TypedArray].prototype.keys"), JavascriptArrayIteratorKind::Key); } Var TypedArrayBase::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_lastIndexOf); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.lastIndexOf")); uint32 length = typedArrayBase->GetLength(); Var search = nullptr; int64 fromIndex; if (!JavascriptArray::GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext)) { return TaggedInt::ToVarUnchecked(-1); } return JavascriptArray::LastIndexOfHelper(typedArrayBase, search, fromIndex, scriptContext); } Var TypedArrayBase::EntryMap(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.map")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_map); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.map")); return JavascriptArray::MapHelper(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } Var TypedArrayBase::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.reduce")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_reduce); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.reduce")); return JavascriptArray::ReduceHelper(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } Var TypedArrayBase::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.reduceRight")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_reduceRight); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.reduceRight")); return JavascriptArray::ReduceRightHelper(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } Var TypedArrayBase::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_reverse); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.reverse")); return JavascriptArray::ReverseHelper(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), scriptContext); } Var TypedArrayBase::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.slice")); return JavascriptArray::SliceHelper(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } Var TypedArrayBase::EntrySome(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.some")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_some); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.some")); return JavascriptArray::SomeHelper(nullptr, typedArrayBase, typedArrayBase, typedArrayBase->GetLength(), args, scriptContext); } template<typename T> int __cdecl TypedArrayCompareElementsHelper(void* context, const void* elem1, const void* elem2) { const T* element1 = static_cast<const T*>(elem1); const T* element2 = static_cast<const T*>(elem2); Assert(element1 != nullptr); Assert(element2 != nullptr); Assert(context != nullptr); const T x = *element1; const T y = *element2; if (NumberUtilities::IsNan((double)x)) { if (NumberUtilities::IsNan((double)y)) { return 0; } return 1; } else { if (NumberUtilities::IsNan((double)y)) { return -1; } } void **contextArray = (void **)context; if (contextArray[1] != nullptr) { RecyclableObject* compFn = VarTo<RecyclableObject>(contextArray[1]); ScriptContext* scriptContext = compFn->GetScriptContext(); Var undefined = scriptContext->GetLibrary()->GetUndefined(); double dblResult; Var retVal = nullptr; BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext()) { retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(CallFlags_Value, 3), undefined, JavascriptNumber::ToVarWithCheck((double)x, scriptContext), JavascriptNumber::ToVarWithCheck((double)y, scriptContext)); } END_SAFE_REENTRANT_CALL Assert(VarIs<TypedArrayBase>(contextArray[0])); if (TypedArrayBase::IsDetachedTypedArray(contextArray[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray].prototype.sort")); } if (TaggedInt::Is(retVal)) { return TaggedInt::ToInt32(retVal); } if (JavascriptNumber::Is_NoTaggedIntCheck(retVal)) { dblResult = JavascriptNumber::GetValue(retVal); } else { dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext); // ToNumber may execute user-code which can cause the array to become detached if (TypedArrayBase::IsDetachedTypedArray(contextArray[0])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray].prototype.sort")); } } if (dblResult < 0) { return -1; } else if (dblResult > 0) { return 1; } return 0; } else { if (x < y) { return -1; } else if (x > y) { return 1; } return 0; } } Var TypedArrayBase::EntrySort(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("[TypedArray].prototype.sort")); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_sort); TypedArrayBase* typedArrayBase = ValidateTypedArray(args, scriptContext, _u("[TypedArray].prototype.sort")); uint32 length = typedArrayBase->GetLength(); // If TypedArray has no length, we don't have any work to do. if (length == 0) { return typedArrayBase; } RecyclableObject* compareFn = nullptr; if (args.Info.Count > 1) { if (!JavascriptConversion::IsCallable(args[1])) { JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.sort")); } compareFn = VarTo<RecyclableObject>(args[1]); } // Get the elements comparison function for the type of this TypedArray void* elementCompare = reinterpret_cast<void*>(typedArrayBase->GetCompareElementsFunction()); Assert(elementCompare); // Cast compare to the correct function type int(__cdecl*elementCompareFunc)(void*, const void*, const void*) = (int(__cdecl*)(void*, const void*, const void*))elementCompare; void * contextToPass[] = { typedArrayBase, compareFn }; // We can always call qsort_s with the same arguments. If user compareFn is non-null, the callback will use it to do the comparison. qsort_s(typedArrayBase->GetByteBuffer(), length, typedArrayBase->GetBytesPerElement(), elementCompareFunc, contextToPass); return typedArrayBase; } Var TypedArrayBase::EntryValues(RecyclableObject* function, CallInfo callInfo, ...) { PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); Assert(!(callInfo.Flags & CallFlags_New)); CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(TypedArray_Prototype_values); return GetKeysEntriesValuesHelper(args, scriptContext, _u("[TypedArray].prototype.values"), JavascriptArrayIteratorKind::Value); } BOOL TypedArrayBase::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext) { ENTER_PINNED_SCOPE(JavascriptString, toStringResult); toStringResult = JavascriptObject::ToStringInternal(this, requestContext); stringBuilder->Append(toStringResult->GetString(), toStringResult->GetLength()); LEAVE_PINNED_SCOPE(); return TRUE; } BOOL TypedArrayBase::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext) { switch(GetTypeId()) { case TypeIds_Int8Array: stringBuilder->AppendCppLiteral(_u("Object, (Int8Array)")); break; case TypeIds_Uint8Array: stringBuilder->AppendCppLiteral(_u("Object, (Uint8Array)")); break; case TypeIds_Uint8ClampedArray: stringBuilder->AppendCppLiteral(_u("Object, (Uint8ClampedArray)")); break; case TypeIds_Int16Array: stringBuilder->AppendCppLiteral(_u("Object, (Int16Array)")); break; case TypeIds_Uint16Array: stringBuilder->AppendCppLiteral(_u("Object, (Uint16Array)")); break; case TypeIds_Int32Array: stringBuilder->AppendCppLiteral(_u("Object, (Int32Array)")); break; case TypeIds_Uint32Array: stringBuilder->AppendCppLiteral(_u("Object, (Uint32Array)")); break; case TypeIds_Float32Array: stringBuilder->AppendCppLiteral(_u("Object, (Float32Array)")); break; case TypeIds_Float64Array: stringBuilder->AppendCppLiteral(_u("Object, (Float64Array)")); break; default: Assert(false); stringBuilder->AppendCppLiteral(_u("Object")); break; } return TRUE; } bool TypedArrayBase::TryGetLengthForOptimizedTypedArray(const Var var, uint32 *const lengthRef, TypeId *const typeIdRef) { Assert(var); Assert(lengthRef); Assert(typeIdRef); if(!VarIs<RecyclableObject>(var)) { return false; } const TypeId typeId = VarTo<RecyclableObject>(var)->GetTypeId(); switch(typeId) { case TypeIds_Int8Array: case TypeIds_Uint8Array: case TypeIds_Uint8ClampedArray: case TypeIds_Int16Array: case TypeIds_Uint16Array: case TypeIds_Int32Array: case TypeIds_Uint32Array: case TypeIds_Float32Array: case TypeIds_Float64Array: Assert(ValueType::FromTypeId(typeId,false).IsOptimizedTypedArray()); *lengthRef = VarTo<TypedArrayBase>(var)->GetLength(); *typeIdRef = typeId; return true; } Assert(!ValueType::FromTypeId(typeId,false).IsOptimizedTypedArray()); return false; } _Use_decl_annotations_ BOOL TypedArrayBase::ValidateIndexAndDirectSetItem(Js::Var index, Js::Var value, bool * isNumericIndex) { bool skipSetItem = false; uint32 indexToSet = ValidateAndReturnIndex(index, &skipSetItem, isNumericIndex); // If index is not numeric, goto [[Set]] property path if (*isNumericIndex) { return skipSetItem ? DirectSetItemNoSet(indexToSet, value) : DirectSetItem(indexToSet, value); } else { return TRUE; } } // Validate the index used for typed arrays with below rules: // 1. if numeric string, let sIndex = ToNumber(index) : // a. if sIndex is not integer, skip set operation // b. if sIndex == -0, skip set operation // c. if sIndex < 0 or sIndex >= length, skip set operation // d. else return sIndex and perform set operation // 2. if tagged int, let nIndex = untag(index) : // a. if nIndex < 0 or nIndex >= length, skip set operation // 3. else: // a. if index is not integer, skip set operation // b. if index < 0 or index >= length, skip set operation // NOTE: if index == -0, it is treated as 0 and perform set operation // as per 7.1.12.1 of ES6 spec 7.1.12.1 ToString Applied to the Number Type _Use_decl_annotations_ uint32 TypedArrayBase::ValidateAndReturnIndex(Js::Var index, bool * skipOperation, bool * isNumericIndex) { *skipOperation = false; *isNumericIndex = true; uint32 length = GetLength(); if (TaggedInt::Is(index)) { int32 indexInt = TaggedInt::ToInt32(index); *skipOperation = (indexInt < 0 || (uint32)indexInt >= length); return (uint32)indexInt; } else { double dIndexValue = 0; if (VarIs<JavascriptString>(index)) { if (JavascriptConversion::CanonicalNumericIndexString(VarTo<JavascriptString>(index), &dIndexValue, GetScriptContext())) { if (JavascriptNumber::IsNegZero(dIndexValue)) { *skipOperation = true; return 0; } // If this is numeric index embedded in string, perform regular numeric index checks below } else { // not numeric index, go the [[Set]] path to add as string property *isNumericIndex = false; return 0; } } else { // JavascriptNumber::Is_NoTaggedIntCheck(index) dIndexValue = JavascriptNumber::GetValue(index); } // OK to lose data because we want to verify ToInteger() uint32 uint32Index = (uint32)dIndexValue; // IsInteger() if ((double)uint32Index != dIndexValue) { *skipOperation = true; } // index >= length else if (uint32Index >= GetLength()) { *skipOperation = true; } return uint32Index; } } // static JavascriptFunction* TypedArrayBase::GetDefaultConstructor(Var object, ScriptContext* scriptContext) { switch (JavascriptOperators::GetTypeId(object)) { case TypeId::TypeIds_Int8Array: return scriptContext->GetLibrary()->GetInt8ArrayConstructor(); case TypeId::TypeIds_Uint8Array: return scriptContext->GetLibrary()->GetUint8ArrayConstructor(); case TypeId::TypeIds_Uint8ClampedArray: return scriptContext->GetLibrary()->GetUint8ClampedArrayConstructor(); case TypeId::TypeIds_Int16Array: return scriptContext->GetLibrary()->GetInt16ArrayConstructor(); case TypeId::TypeIds_Uint16Array: return scriptContext->GetLibrary()->GetUint16ArrayConstructor(); case TypeId::TypeIds_Int32Array: return scriptContext->GetLibrary()->GetInt32ArrayConstructor(); case TypeId::TypeIds_Uint32Array: return scriptContext->GetLibrary()->GetUint32ArrayConstructor(); case TypeId::TypeIds_Float32Array: return scriptContext->GetLibrary()->GetFloat32ArrayConstructor(); case TypeId::TypeIds_Float64Array: return scriptContext->GetLibrary()->GetFloat64ArrayConstructor(); default: Assert(UNREACHED); return nullptr; } } Var TypedArrayBase::FindMinOrMax(Js::ScriptContext * scriptContext, TypeId typeId, bool findMax) { if (this->IsDetachedBuffer()) // 9.4.5.8 IntegerIndexedElementGet { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_DetachedTypedArray); } switch (typeId) { case TypeIds_Int8Array: return this->FindMinOrMax<int8, false>(scriptContext, findMax); case TypeIds_Uint8Array: case TypeIds_Uint8ClampedArray: return this->FindMinOrMax<uint8, false>(scriptContext, findMax); case TypeIds_Int16Array: return this->FindMinOrMax<int16, false>(scriptContext, findMax); case TypeIds_Uint16Array: return this->FindMinOrMax<uint16, false>(scriptContext, findMax); case TypeIds_Int32Array: return this->FindMinOrMax<int32, false>(scriptContext, findMax); case TypeIds_Uint32Array: return this->FindMinOrMax<uint32, false>(scriptContext, findMax); case TypeIds_Float32Array: return this->FindMinOrMax<float, true>(scriptContext, findMax); case TypeIds_Float64Array: return this->FindMinOrMax<double, true>(scriptContext, findMax); default: AssertMsg(false, "Unsupported array for fast path"); return nullptr; } } template<typename T, bool checkNaNAndNegZero> Var TypedArrayBase::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax) { T* typedBuffer = (T*)this->buffer; uint len = this->GetLength(); Assert(sizeof(T)+GetByteOffset() <= GetArrayBuffer()->GetByteLength()); T currentRes = typedBuffer[0]; for (uint i = 0; i < len; i++) { Assert((i + 1) * sizeof(T)+GetByteOffset() <= GetArrayBuffer()->GetByteLength()); T compare = typedBuffer[i]; if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare))) { return scriptContext->GetLibrary()->GetNaN(); } if (findMax ? currentRes < compare : currentRes > compare || (checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes)))) { currentRes = compare; } } return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext); } // static TypedArrayBase * TypedArrayBase::ValidateTypedArray(Arguments &args, ScriptContext *scriptContext, LPCWSTR apiName) { if (args.Info.Count == 0) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } return ValidateTypedArray(args[0], scriptContext, apiName); } // static TypedArrayBase* TypedArrayBase::ValidateTypedArray(Var aValue, ScriptContext *scriptContext, LPCWSTR apiName) { TypedArrayBase *typedArrayBase = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(aValue); if (!typedArrayBase) { JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedTypedArray); } if (typedArrayBase->IsDetachedBuffer()) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, apiName); } return typedArrayBase; } // static Var TypedArrayBase::TypedArrayCreate(Var constructor, Arguments *args, uint32 length, ScriptContext *scriptContext) { Var newObj = JavascriptOperators::NewScObject(constructor, *args, scriptContext); TypedArrayBase * typedArray = TypedArrayBase::ValidateTypedArray(newObj, scriptContext, nullptr); // ECMA262 22.2.4.6 TypedArrayCreate line 3. "If argumentList is a List of a single Number" (args[0] == constructor) if (args->Info.Count == 2 && typedArray->GetLength() < length) { JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidTypedArrayLength); } return newObj; } #if ENABLE_TTD TTD::NSSnapObjects::SnapObjectType TypedArrayBase::GetSnapTag_TTD() const { return TTD::NSSnapObjects::SnapObjectType::SnapTypedArrayObject; } void TypedArrayBase::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc) { TTD::NSSnapObjects::SnapTypedArrayInfo* stai = alloc.SlabAllocateStruct<TTD::NSSnapObjects::SnapTypedArrayInfo>(); stai->ArrayBufferAddr = TTD_CONVERT_VAR_TO_PTR_ID(this->GetArrayBuffer()); stai->ByteOffset = this->GetByteOffset(); stai->Length = this->GetLength(); TTD_PTR_ID* depArray = alloc.SlabAllocateArray<TTD_PTR_ID>(1); depArray[0] = TTD_CONVERT_VAR_TO_PTR_ID(this->GetArrayBuffer()); TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapTypedArrayInfo*, TTD::NSSnapObjects::SnapObjectType::SnapTypedArrayObject>(objData, stai, alloc, 1, depArray); } #endif template<> inline BOOL Int8Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToInt8); } template<> inline BOOL Int8VirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToInt8); } template<> inline BOOL Int8Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToInt8); } template<> inline BOOL Int8VirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToInt8); } template<> inline Var Int8Array::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } #define DIRECT_SET_NO_DETACH_CHECK(TypedArrayName, convertFn) \ template<> \ inline BOOL TypedArrayName##::DirectSetItemNoDetachCheck(__in uint32 index, __in Var value) \ { \ return BaseTypedDirectSetItemNoDetachCheck(index, value, convertFn); \ } DIRECT_SET_NO_DETACH_CHECK(Int8Array, JavascriptConversion::ToInt8); DIRECT_SET_NO_DETACH_CHECK(Int8VirtualArray, JavascriptConversion::ToInt8); DIRECT_SET_NO_DETACH_CHECK(Uint8Array, JavascriptConversion::ToUInt8); DIRECT_SET_NO_DETACH_CHECK(Uint8VirtualArray, JavascriptConversion::ToUInt8); DIRECT_SET_NO_DETACH_CHECK(Int16Array, JavascriptConversion::ToInt16); DIRECT_SET_NO_DETACH_CHECK(Int16VirtualArray, JavascriptConversion::ToInt16); DIRECT_SET_NO_DETACH_CHECK(Uint16Array, JavascriptConversion::ToUInt16); DIRECT_SET_NO_DETACH_CHECK(Uint16VirtualArray, JavascriptConversion::ToUInt16); DIRECT_SET_NO_DETACH_CHECK(Int32Array, JavascriptConversion::ToInt32); DIRECT_SET_NO_DETACH_CHECK(Int32VirtualArray, JavascriptConversion::ToInt32); DIRECT_SET_NO_DETACH_CHECK(Uint32Array, JavascriptConversion::ToUInt32); DIRECT_SET_NO_DETACH_CHECK(Uint32VirtualArray, JavascriptConversion::ToUInt32); DIRECT_SET_NO_DETACH_CHECK(Float32Array, JavascriptConversion::ToFloat); DIRECT_SET_NO_DETACH_CHECK(Float32VirtualArray, JavascriptConversion::ToFloat); DIRECT_SET_NO_DETACH_CHECK(Float64Array, JavascriptConversion::ToNumber); DIRECT_SET_NO_DETACH_CHECK(Float64VirtualArray, JavascriptConversion::ToNumber); DIRECT_SET_NO_DETACH_CHECK(Int64Array, JavascriptConversion::ToInt64); DIRECT_SET_NO_DETACH_CHECK(Uint64Array, JavascriptConversion::ToUInt64); DIRECT_SET_NO_DETACH_CHECK(Uint8ClampedArray, JavascriptConversion::ToUInt8Clamped); DIRECT_SET_NO_DETACH_CHECK(Uint8ClampedVirtualArray, JavascriptConversion::ToUInt8Clamped); DIRECT_SET_NO_DETACH_CHECK(BoolArray, JavascriptConversion::ToBool); #define DIRECT_GET_NO_DETACH_CHECK(TypedArrayName) \ template<> \ inline Var TypedArrayName##::DirectGetItemNoDetachCheck(__in uint32 index) \ { \ return BaseTypedDirectGetItemNoDetachCheck(index); \ } #define DIRECT_GET_VAR_CHECK_NO_DETACH_CHECK(TypedArrayName) \ template<> \ inline Var TypedArrayName##::DirectGetItemNoDetachCheck(__in uint32 index) \ { \ return DirectGetItemVarCheckNoDetachCheck(index); \ } DIRECT_GET_NO_DETACH_CHECK(Int8Array); DIRECT_GET_NO_DETACH_CHECK(Int8VirtualArray); DIRECT_GET_NO_DETACH_CHECK(Uint8Array); DIRECT_GET_NO_DETACH_CHECK(Uint8VirtualArray); DIRECT_GET_NO_DETACH_CHECK(Int16Array); DIRECT_GET_NO_DETACH_CHECK(Int16VirtualArray); DIRECT_GET_NO_DETACH_CHECK(Uint16Array); DIRECT_GET_NO_DETACH_CHECK(Uint16VirtualArray); DIRECT_GET_NO_DETACH_CHECK(Int32Array); DIRECT_GET_NO_DETACH_CHECK(Int32VirtualArray); DIRECT_GET_NO_DETACH_CHECK(Uint32Array); DIRECT_GET_NO_DETACH_CHECK(Uint32VirtualArray); DIRECT_GET_NO_DETACH_CHECK(Int64Array); DIRECT_GET_NO_DETACH_CHECK(Uint64Array); DIRECT_GET_NO_DETACH_CHECK(Uint8ClampedArray); DIRECT_GET_NO_DETACH_CHECK(Uint8ClampedVirtualArray); DIRECT_GET_VAR_CHECK_NO_DETACH_CHECK(Float32Array); DIRECT_GET_VAR_CHECK_NO_DETACH_CHECK(Float32VirtualArray); DIRECT_GET_VAR_CHECK_NO_DETACH_CHECK(Float64Array); DIRECT_GET_VAR_CHECK_NO_DETACH_CHECK(Float64VirtualArray); #define TypedArrayBeginStub(TypedArrayName) \ Assert(GetArrayBuffer() && GetArrayBuffer()->GetBuffer()); \ Assert(accessIndex < GetLength()); \ ScriptContext *scriptContext = GetScriptContext(); \ typedef TypedArrayName::TypedArrayType type; \ type *buffer = (type*)this->buffer + accessIndex; #define TypedArrayStore(TypedArrayName, fnName, convertFn) \ template<>\ Var TypedArrayName##::Typed##fnName(__in uint32 accessIndex, __in Var value) \ { \ TypedArrayBeginStub(TypedArrayName); \ double retVal = JavascriptConversion::ToInteger(value, scriptContext); \ AtomicsOperations::fnName(buffer, convertFn(retVal)); \ return JavascriptNumber::ToVarWithCheck(retVal, scriptContext); \ } #define TypedArrayOp1(TypedArrayName, fnName, convertFn) \ template<>\ Var TypedArrayName##::Typed##fnName(__in uint32 accessIndex) \ { \ TypedArrayBeginStub(TypedArrayName); \ type result = AtomicsOperations::fnName(buffer); \ return JavascriptNumber::ToVar(result, scriptContext); \ } #define TypedArrayOp2(TypedArrayName, fnName, convertFn) \ template<>\ Var TypedArrayName##::Typed##fnName(__in uint32 accessIndex, __in Var value) \ { \ TypedArrayBeginStub(TypedArrayName); \ type result = AtomicsOperations::fnName(buffer, convertFn(value, scriptContext)); \ return JavascriptNumber::ToVar(result, scriptContext); \ } #define TypedArrayOp3(TypedArrayName, fnName, convertFn) \ template<>\ Var TypedArrayName##::Typed##fnName(__in uint32 accessIndex, __in Var first, __in Var value) \ { \ TypedArrayBeginStub(TypedArrayName); \ type result = AtomicsOperations::fnName(buffer, convertFn(first, scriptContext), convertFn(value, scriptContext)); \ return JavascriptNumber::ToVar(result, scriptContext); \ } #define GenerateNotSupportedStub1(TypedArrayName, fnName) \ template<>\ Var TypedArrayName##::Typed##fnName(__in uint32 accessIndex) \ { \ JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); \ } #define GenerateNotSupportedStub2(TypedArrayName, fnName) \ template<>\ Var TypedArrayName##::Typed##fnName(__in uint32 accessIndex, __in Var value) \ { \ JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); \ } #define GenerateNotSupportedStub3(TypedArrayName, fnName) \ template<>\ Var TypedArrayName##::Typed##fnName(__in uint32 accessIndex, __in Var first, __in Var value) \ { \ JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); \ } #define GENERATE_FOREACH_TYPEDARRAY(TYPEDARRAY_DEF, NOTSUPPORTEDSTUB, OP) \ TYPEDARRAY_DEF(Int8Array, OP, JavascriptConversion::ToInt8); \ TYPEDARRAY_DEF(Int8VirtualArray, OP, JavascriptConversion::ToInt8); \ TYPEDARRAY_DEF(Uint8Array, OP, JavascriptConversion::ToUInt8); \ TYPEDARRAY_DEF(Uint8VirtualArray, OP, JavascriptConversion::ToUInt8); \ TYPEDARRAY_DEF(Int16Array, OP, JavascriptConversion::ToInt16); \ TYPEDARRAY_DEF(Int16VirtualArray, OP, JavascriptConversion::ToInt16); \ TYPEDARRAY_DEF(Uint16Array, OP, JavascriptConversion::ToUInt16); \ TYPEDARRAY_DEF(Uint16VirtualArray, OP, JavascriptConversion::ToUInt16); \ TYPEDARRAY_DEF(Int32Array, OP, JavascriptConversion::ToInt32); \ TYPEDARRAY_DEF(Int32VirtualArray, OP, JavascriptConversion::ToInt32); \ TYPEDARRAY_DEF(Uint32Array, OP, JavascriptConversion::ToUInt32); \ TYPEDARRAY_DEF(Uint32VirtualArray, OP, JavascriptConversion::ToUInt32); \ NOTSUPPORTEDSTUB(Float32Array, OP); \ NOTSUPPORTEDSTUB(Float32VirtualArray, OP); \ NOTSUPPORTEDSTUB(Float64Array, OP); \ NOTSUPPORTEDSTUB(Float64VirtualArray, OP); \ NOTSUPPORTEDSTUB(Int64Array, OP); \ NOTSUPPORTEDSTUB(Uint64Array, OP); \ NOTSUPPORTEDSTUB(Uint8ClampedArray, OP); \ NOTSUPPORTEDSTUB(Uint8ClampedVirtualArray, OP); \ NOTSUPPORTEDSTUB(BoolArray, OP); GENERATE_FOREACH_TYPEDARRAY(TypedArrayOp2, GenerateNotSupportedStub2, Add) GENERATE_FOREACH_TYPEDARRAY(TypedArrayOp2, GenerateNotSupportedStub2, And) GENERATE_FOREACH_TYPEDARRAY(TypedArrayOp3, GenerateNotSupportedStub3, CompareExchange) GENERATE_FOREACH_TYPEDARRAY(TypedArrayOp2, GenerateNotSupportedStub2, Exchange) GENERATE_FOREACH_TYPEDARRAY(TypedArrayOp1, GenerateNotSupportedStub1, Load) GENERATE_FOREACH_TYPEDARRAY(TypedArrayOp2, GenerateNotSupportedStub2, Or) GENERATE_FOREACH_TYPEDARRAY(TypedArrayStore, GenerateNotSupportedStub2, Store) GENERATE_FOREACH_TYPEDARRAY(TypedArrayOp2, GenerateNotSupportedStub2, Sub) GENERATE_FOREACH_TYPEDARRAY(TypedArrayOp2, GenerateNotSupportedStub2, Xor) template<> VTableValue Int8Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableInt8Array; } template<> inline Var Int8VirtualArray::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Int8VirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableInt8VirtualArray; } template<> inline BOOL Uint8Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt8); } template<> inline BOOL Uint8Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt8); } template<> inline Var Uint8Array::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint8Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint8Array; } template<> inline BOOL Uint8VirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt8); } template<> inline BOOL Uint8VirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt8); } template<> inline Var Uint8VirtualArray::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint8VirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint8VirtualArray; } template<> inline BOOL Uint8ClampedArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt8Clamped); } template<> inline BOOL Uint8ClampedArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt8Clamped); } template<> inline Var Uint8ClampedArray::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint8ClampedArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint8ClampedArray; } template<> inline BOOL Uint8ClampedVirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt8Clamped); } template<> inline BOOL Uint8ClampedVirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt8Clamped); } template<> inline Var Uint8ClampedVirtualArray::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint8ClampedVirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint8ClampedVirtualArray; } template<> inline BOOL Int16Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToInt16); } template<> inline BOOL Int16Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToInt16); } template<> inline Var Int16Array::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Int16Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableInt16Array; } template<> inline BOOL Int16VirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToInt16); } template<> inline BOOL Int16VirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToInt16); } template<> inline Var Int16VirtualArray::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Int16VirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableInt16VirtualArray; } template<> inline BOOL Uint16Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt16); } template<> inline BOOL Uint16Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt16); } template<> inline Var Uint16Array::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint16Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint16Array; } template<> inline BOOL Uint16VirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt16); } template<> inline BOOL Uint16VirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt16); } template<> inline Var Uint16VirtualArray::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint16VirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint16VirtualArray; } template<> inline BOOL Int32Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToInt32); } template<> inline BOOL Int32Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToInt32); } template<> inline Var Int32Array::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Int32Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableInt32Array; } template<> inline BOOL Int32VirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToInt32); } template<> inline BOOL Int32VirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToInt32); } template<> inline Var Int32VirtualArray::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Int32VirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableInt32VirtualArray; } template<> inline BOOL Uint32Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt32); } template<> inline BOOL Uint32Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt32); } template<> inline Var Uint32Array::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint32Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint32Array; } template<> inline BOOL Uint32VirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt32); } template<> inline BOOL Uint32VirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt32); } template<> inline Var Uint32VirtualArray::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint32VirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint32VirtualArray; } template<> inline BOOL Float32Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToFloat); } template<> inline BOOL Float32Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToFloat); } template<> Var Float32Array::DirectGetItem(__in uint32 index) { return TypedDirectGetItemWithCheck(index); } template<> VTableValue Float32Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableFloat32Array; } template<> inline BOOL Float32VirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToFloat); } template<> inline BOOL Float32VirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToFloat); } template<> Var Float32VirtualArray::DirectGetItem(__in uint32 index) { return TypedDirectGetItemWithCheck(index); } template<> VTableValue Float32VirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableFloat32VirtualArray; } template<> inline BOOL Float64Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToNumber); } template<> inline BOOL Float64Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToNumber); } template<> inline Var Float64Array::DirectGetItem(__in uint32 index) { return TypedDirectGetItemWithCheck(index); } template<> VTableValue Float64Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableFloat64Array; } template<> inline BOOL Float64VirtualArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToNumber); } template<> inline BOOL Float64VirtualArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToNumber); } template<> inline Var Float64VirtualArray::DirectGetItem(__in uint32 index) { return TypedDirectGetItemWithCheck(index); } template<> VTableValue Float64VirtualArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableFloat64VirtualArray; } template<> inline BOOL Int64Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToInt64); } template<> inline BOOL Int64Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToInt64); } template<> inline Var Int64Array::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Int64Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableInt64Array; } template<> inline BOOL Uint64Array::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToUInt64); } template<> inline BOOL Uint64Array::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToUInt64); } template<> inline Var Uint64Array::DirectGetItem(__in uint32 index) { return BaseTypedDirectGetItem(index); } template<> VTableValue Uint64Array::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableUint64Array; } template<> inline BOOL BoolArray::DirectSetItem(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItem(index, value, JavascriptConversion::ToBool); } template<> inline BOOL BoolArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { return BaseTypedDirectSetItemNoSet(index, value, JavascriptConversion::ToBool); } template<> inline Var BoolArray::DirectGetItem(__in uint32 index) { if (index < GetLength()) { Assert((index+1)* sizeof(bool) +GetByteOffset() <= GetArrayBuffer()->GetByteLength()); bool* typedBuffer = (bool*)buffer; return typedBuffer[index] ? GetLibrary()->GetTrue() : GetLibrary()->GetFalse(); } return GetLibrary()->GetUndefined(); } template<> inline Var BoolArray::DirectGetItemNoDetachCheck(__in uint32 index) { Assert((index + 1)* sizeof(bool) + GetByteOffset() <= GetArrayBuffer()->GetByteLength()); bool* typedBuffer = (bool*)buffer; return typedBuffer[index] ? GetLibrary()->GetTrue() : GetLibrary()->GetFalse(); } template<> VTableValue BoolArray::DummyVirtualFunctionToHinderLinkerICF() { return VTableValue::VtableBoolArray; } Var CharArray::Create(ArrayBufferBase* arrayBuffer, uint32 byteOffSet, uint32 mappedLength, JavascriptLibrary* javascriptLibrary) { CharArray* arr; uint32 totalLength, mappedByteLength; if (UInt32Math::Mul(mappedLength, sizeof(char16), &mappedByteLength) || UInt32Math::Add(byteOffSet, mappedByteLength, &totalLength) || (totalLength > arrayBuffer->GetByteLength())) { JavascriptError::ThrowRangeError(arrayBuffer->GetScriptContext(), JSERR_InvalidTypedArrayLength); } arr = RecyclerNew(javascriptLibrary->GetRecycler(), CharArray, arrayBuffer, byteOffSet, mappedLength, javascriptLibrary->GetCharArrayType()); return arr; } template <> bool VarIsImpl<CharArray>(RecyclableObject* obj) { return JavascriptOperators::GetTypeId(obj) == Js::TypeIds_CharArray; } Var CharArray::EntrySet(RecyclableObject* function, CallInfo callInfo, ...) { AssertMsg(FALSE, "not supported in char array"); JavascriptError::ThrowTypeError(function->GetScriptContext(), JSERR_This_NeedTypedArray); } Var CharArray::EntrySubarray(RecyclableObject* function, CallInfo callInfo, ...) { AssertMsg(FALSE, "not supported in char array"); JavascriptError::ThrowTypeError(function->GetScriptContext(), JSERR_This_NeedTypedArray); } inline Var CharArray::Subarray(uint32 begin, uint32 end) { AssertMsg(FALSE, "not supported in char array"); JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_This_NeedTypedArray); } inline BOOL CharArray::DirectSetItem(__in uint32 index, __in Js::Var value) { ScriptContext* scriptContext = GetScriptContext(); // A typed array is Integer Indexed Exotic object, so doing a get translates to 9.4.5.9 IntegerIndexedElementSet LPCWSTR asString = (Js::JavascriptConversion::ToString(value, scriptContext))->GetSz(); if (this->IsDetachedBuffer()) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray); } if (index >= GetLength()) { return FALSE; } AssertMsg(index < GetLength(), "Trying to set out of bound index for typed array."); Assert((index + 1)* sizeof(char16) + GetByteOffset() <= GetArrayBuffer()->GetByteLength()); char16* typedBuffer = (char16*)buffer; if (asString != NULL && ::wcslen(asString) == 1) { typedBuffer[index] = asString[0]; } else { Js::JavascriptError::MapAndThrowError(scriptContext, E_INVALIDARG); } return TRUE; } inline BOOL CharArray::DirectSetItemNoSet(__in uint32 index, __in Js::Var value) { ScriptContext* scriptContext = GetScriptContext(); // A typed array is Integer Indexed Exotic object, so doing a get translates to 9.4.5.9 IntegerIndexedElementSet Js::JavascriptConversion::ToString(value, scriptContext); if (this->IsDetachedBuffer()) { JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray); } return FALSE; } inline BOOL CharArray::DirectSetItemNoDetachCheck(__in uint32 index, __in Js::Var value) { return DirectSetItem(index, value); } inline Var CharArray::DirectGetItemNoDetachCheck(__in uint32 index) { return DirectGetItem(index); } Var CharArray::TypedAdd(__in uint32 index, __in Var second) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } Var CharArray::TypedAnd(__in uint32 index, __in Var second) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } Var CharArray::TypedCompareExchange(__in uint32 index, __in Var comparand, __in Var replacementValue) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } Var CharArray::TypedExchange(__in uint32 index, __in Var second) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } Var CharArray::TypedLoad(__in uint32 index) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } Var CharArray::TypedOr(__in uint32 index, __in Var second) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } Var CharArray::TypedStore(__in uint32 index, __in Var second) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } Var CharArray::TypedSub(__in uint32 index, __in Var second) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } Var CharArray::TypedXor(__in uint32 index, __in Var second) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_InvalidOperationOnTypedArray); } inline Var CharArray::DirectGetItem(__in uint32 index) { // A typed array is Integer Indexed Exotic object, so doing a get translates to 9.4.5.8 IntegerIndexedElementGet if (this->IsDetachedBuffer()) { JavascriptError::ThrowTypeError(GetScriptContext(), JSERR_DetachedTypedArray); } if (index < GetLength()) { Assert((index + 1)* sizeof(char16)+GetByteOffset() <= GetArrayBuffer()->GetByteLength()); char16* typedBuffer = (char16*)buffer; return GetLibrary()->GetCharStringCache().GetStringForChar(typedBuffer[index]); } return GetLibrary()->GetUndefined(); } Var CharArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...) { function->GetScriptContext()->GetThreadContext()->ProbeStack(Js::Constants::MinStackDefault, function->GetScriptContext()); ARGUMENTS(args, callInfo); ScriptContext* scriptContext = function->GetScriptContext(); AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'"); Assert(!(callInfo.Flags & CallFlags_New) || args[0] == nullptr); Var object = TypedArrayBase::CreateNewInstance(args, scriptContext, sizeof(char16), CharArray::Create); #if ENABLE_DEBUG_CONFIG_OPTIONS if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag)) { object = Js::JavascriptProxy::AutoProxyWrapper(object); } #endif return object; } }
39.544722
203
0.65312
wbhsm
b4b7f0c32acdf0be651be1b9ef899697140ad84b
13,855
cpp
C++
src/test/fork_kore_from_blockinfo.cpp
Kore-Core/Kore
d0bb166f6ad69b09ef305cdedc2a799cd3f874c3
[ "MIT" ]
13
2018-02-02T15:18:53.000Z
2019-09-27T06:00:26.000Z
src/test/fork_kore_from_blockinfo.cpp
Kore-Core/Kore
d0bb166f6ad69b09ef305cdedc2a799cd3f874c3
[ "MIT" ]
7
2018-07-05T12:05:49.000Z
2020-03-09T06:25:45.000Z
src/test/fork_kore_from_blockinfo.cpp
Kore-Core/Kore
d0bb166f6ad69b09ef305cdedc2a799cd3f874c3
[ "MIT" ]
23
2018-01-14T14:14:59.000Z
2019-08-16T03:39:05.000Z
// Copyright (c) 2011-2014 The Bitcoin Core developers // Copyright (c) 2016 The KORE developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "checkpoints.h" #include "init.h" #include "main.h" // pcoinsTip; #include "tests_util.h" #include "util.h" #include "utiltime.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(fork_kore_from_blockinfo) static const string strSecret("5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj"); //#define RUN_FORK_TESTS #ifdef RUN_FORK_TESTS BOOST_AUTO_TEST_CASE(quick_fork) { // todo how to get this parameter from argument list ?? //bool logToStdout = GetBoolArg("-logtostdout", false); bool logToStdout = true; SetMockTime(GetTime()); if (fDebug) { LogPrintf("*************************************************** \n"); LogPrintf("** Starting fork_kore_from_blockinfo/quick_fork ** \n"); LogPrintf("*************************************************** \n"); } Checkpoints::fEnabled = false; int64_t oldTargetTimespan = Params().GetTargetTimespan(); int64_t oldTargetSpacing = Params().GetTargetSpacing(); int oldHeightToFork = Params().HeightToFork(); int oldCoinBaseMaturity = Params().GetCoinMaturity(); int oldStakeMinAge = Params().GetStakeMinAge(); int oldModifier = Params().GetModifierInterval(); // confirmations : 3 // remember that the miminum spacing is 10 !!! // spacing : [confirmations-1, max(confirmations-1, value)] // modifierInterval : [spacing, spacing)] // pow blocks : [confirmations + 1, max(confirmations+1, value)], this way we will have 2 modifiers int minConfirmations = 3; ModifiableParams()->setHeightToFork(9); ModifiableParams()->setTargetSpacing(minConfirmations - 1); ModifiableParams()->setStakeModifierInterval(minConfirmations - 1); ModifiableParams()->setCoinMaturity(minConfirmations); ModifiableParams()->setStakeMinAge(0); ModifiableParams()->setTargetTimespan(1); ModifiableParams()->setEnableBigRewards(true); ModifiableParams()->setLastPowBlock(minConfirmations + 1); ScanForWalletTransactions(pwalletMain); CScript scriptPubKey = GenerateSamePubKeyScript4Wallet(strSecret, pwalletMain); // generate 4 pow blocks CreateOldBlocksFromBlockInfo(1, minConfirmations + 2, blockinfo[0], pwalletMain, scriptPubKey, false, logToStdout); // generate 4 pos blocks GeneratePOSLegacyBlocks(minConfirmations + 2, 9, pwalletMain, scriptPubKey, logToStdout); GenerateBlocks(9, 100, pwalletMain, scriptPubKey, true, logToStdout); // Leaving old values Checkpoints::fEnabled = true; ModifiableParams()->setHeightToFork(oldHeightToFork); ModifiableParams()->setEnableBigRewards(false); ModifiableParams()->setCoinMaturity(oldCoinBaseMaturity); ModifiableParams()->setStakeMinAge(oldStakeMinAge); ModifiableParams()->setStakeModifierInterval(oldModifier); ModifiableParams()->setTargetTimespan(oldTargetTimespan); ModifiableParams()->setTargetSpacing(oldTargetSpacing); } BOOST_AUTO_TEST_CASE(check_database_pow) { // todo how to get this parameter from argument list ?? //bool logToStdout = GetBoolArg("-logtostdout", false); bool logToStdout = true; SetMockTime(GetTime()); if (fDebug) { LogPrintf("*************************************************** \n"); LogPrintf("** Starting fork_kore_from_blockinfo/quick_fork ** \n"); LogPrintf("*************************************************** \n"); } Checkpoints::fEnabled = false; int64_t oldTargetTimespan = Params().GetTargetTimespan(); int64_t oldTargetSpacing = Params().GetTargetSpacing(); int oldHeightToFork = Params().HeightToFork(); int oldCoinBaseMaturity = Params().GetCoinMaturity(); int oldStakeMinAge = Params().GetStakeMinAge(); int oldModifier = Params().GetModifierInterval(); // confirmations : 3 // remember that the miminum spacing is 10 !!! // spacing : [confirmations-1, max(confirmations-1, value)] // modifierInterval : [spacing, spacing)] // pow blocks : [confirmations + 1, max(confirmations+1, value)], this way we will have 2 modifiers int minConfirmations = 3; ModifiableParams()->setHeightToFork(9); ModifiableParams()->setTargetSpacing(minConfirmations - 1); ModifiableParams()->setStakeModifierInterval(minConfirmations - 1); ModifiableParams()->setCoinMaturity(minConfirmations); ModifiableParams()->setStakeMinAge(0); ModifiableParams()->setTargetTimespan(1); ModifiableParams()->setEnableBigRewards(true); ModifiableParams()->setLastPowBlock(minConfirmations + 1); ScanForWalletTransactions(pwalletMain); CScript scriptPubKey = GenerateSamePubKeyScript4Wallet(strSecret, pwalletMain); // generate 4 pow blocks CreateOldBlocksFromBlockInfo(1, minConfirmations + 2, blockinfo[0], pwalletMain, scriptPubKey, false, logToStdout); // generate 4 pos blocks //GeneratePOSLegacyBlocks(minConfirmations + 2, 6, pwalletMain, scriptPubKey, logToStdout); //GenerateBlocks(9, 100, pwalletMain, scriptPubKey, true, logToStdout); CheckDatabaseState(pwalletMain); // Leaving old values Checkpoints::fEnabled = true; ModifiableParams()->setHeightToFork(oldHeightToFork); ModifiableParams()->setEnableBigRewards(false); ModifiableParams()->setCoinMaturity(oldCoinBaseMaturity); ModifiableParams()->setStakeMinAge(oldStakeMinAge); ModifiableParams()->setStakeModifierInterval(oldModifier); ModifiableParams()->setTargetTimespan(oldTargetTimespan); ModifiableParams()->setTargetSpacing(oldTargetSpacing); } BOOST_AUTO_TEST_CASE(check_database_pow_pow) { // todo how to get this parameter from argument list ?? //bool logToStdout = GetBoolArg("-logtostdout", false); bool logToStdout = true; SetMockTime(GetTime()); if (fDebug) { LogPrintf("*************************************************** \n"); LogPrintf("** Starting fork_kore_from_blockinfo/quick_fork ** \n"); LogPrintf("*************************************************** \n"); } Checkpoints::fEnabled = false; int64_t oldTargetTimespan = Params().GetTargetTimespan(); int64_t oldTargetSpacing = Params().GetTargetSpacing(); int oldHeightToFork = Params().HeightToFork(); int oldCoinBaseMaturity = Params().GetCoinMaturity(); int oldStakeMinAge = Params().GetStakeMinAge(); int oldModifier = Params().GetModifierInterval(); // confirmations : 3 // remember that the miminum spacing is 10 !!! // spacing : [confirmations-1, max(confirmations-1, value)] // modifierInterval : [spacing, spacing)] // pow blocks : [confirmations + 1, max(confirmations+1, value)], this way we will have 2 modifiers int minConfirmations = 3; ModifiableParams()->setHeightToFork(9); ModifiableParams()->setTargetSpacing(minConfirmations - 1); ModifiableParams()->setStakeModifierInterval(minConfirmations - 1); ModifiableParams()->setCoinMaturity(minConfirmations); ModifiableParams()->setStakeMinAge(0); ModifiableParams()->setTargetTimespan(1); ModifiableParams()->setEnableBigRewards(true); ModifiableParams()->setLastPowBlock(20); ScanForWalletTransactions(pwalletMain); CScript scriptPubKey = GenerateSamePubKeyScript4Wallet(strSecret, pwalletMain); // generate 8 pow blocks CreateOldBlocksFromBlockInfo(1, 9, blockinfo[0], pwalletMain, scriptPubKey, false, logToStdout); // generate new pow GenerateBlocks(9, 20, pwalletMain, scriptPubKey, false, logToStdout); CheckDatabaseState(pwalletMain); // Leaving old values Checkpoints::fEnabled = true; ModifiableParams()->setHeightToFork(oldHeightToFork); ModifiableParams()->setEnableBigRewards(false); ModifiableParams()->setCoinMaturity(oldCoinBaseMaturity); ModifiableParams()->setStakeMinAge(oldStakeMinAge); ModifiableParams()->setStakeModifierInterval(oldModifier); ModifiableParams()->setTargetTimespan(oldTargetTimespan); ModifiableParams()->setTargetSpacing(oldTargetSpacing); } BOOST_AUTO_TEST_CASE(check_database_pow_pos) { // todo how to get this parameter from argument list ?? //bool logToStdout = GetBoolArg("-logtostdout", false); bool logToStdout = true; SetMockTime(GetTime()); if (fDebug) { LogPrintf("*************************************************** \n"); LogPrintf("** Starting fork_kore_from_blockinfo/quick_fork ** \n"); LogPrintf("*************************************************** \n"); } Checkpoints::fEnabled = false; int64_t oldTargetTimespan = Params().GetTargetTimespan(); int64_t oldTargetSpacing = Params().GetTargetSpacing(); int oldHeightToFork = Params().HeightToFork(); int oldCoinBaseMaturity = Params().GetCoinMaturity(); int oldStakeMinAge = Params().GetStakeMinAge(); int oldModifier = Params().GetModifierInterval(); // confirmations : 3 // remember that the miminum spacing is 10 !!! // spacing : [confirmations-1, max(confirmations-1, value)] // modifierInterval : [spacing, spacing)] // pow blocks : [confirmations + 1, max(confirmations+1, value)], this way we will have 2 modifiers int minConfirmations = 3; ModifiableParams()->setHeightToFork(50); ModifiableParams()->setTargetSpacing(minConfirmations - 1); ModifiableParams()->setStakeModifierInterval(minConfirmations - 1); ModifiableParams()->setCoinMaturity(minConfirmations); ModifiableParams()->setStakeMinAge(0); ModifiableParams()->setTargetTimespan(1); ModifiableParams()->setEnableBigRewards(true); ModifiableParams()->setLastPowBlock(minConfirmations + 1); ScanForWalletTransactions(pwalletMain); CScript scriptPubKey = GenerateSamePubKeyScript4Wallet(strSecret, pwalletMain); // generate 4 pow blocks CreateOldBlocksFromBlockInfo(1, minConfirmations + 2, blockinfo[0], pwalletMain, scriptPubKey, false, logToStdout); // Lets check how it the cachedCoins // generate 1 pos blocks GeneratePOSLegacyBlocks(minConfirmations + 2, 6, pwalletMain, scriptPubKey, logToStdout); CheckDatabaseState(pwalletMain); // Leaving old values Checkpoints::fEnabled = true; ModifiableParams()->setHeightToFork(oldHeightToFork); ModifiableParams()->setEnableBigRewards(false); ModifiableParams()->setCoinMaturity(oldCoinBaseMaturity); ModifiableParams()->setStakeMinAge(oldStakeMinAge); ModifiableParams()->setStakeModifierInterval(oldModifier); ModifiableParams()->setTargetTimespan(oldTargetTimespan); ModifiableParams()->setTargetSpacing(oldTargetSpacing); } BOOST_AUTO_TEST_CASE(check_database_pow_pos_newpos) { // todo how to get this parameter from argument list ?? //bool logToStdout = GetBoolArg("-logtostdout", false); bool logToStdout = true; SetMockTime(GetTime()); if (fDebug) { LogPrintf("*************************************************** \n"); LogPrintf("** Starting fork_kore_from_blockinfo/quick_fork ** \n"); LogPrintf("*************************************************** \n"); } Checkpoints::fEnabled = false; int64_t oldTargetTimespan = Params().GetTargetTimespan(); int64_t oldTargetSpacing = Params().GetTargetSpacing(); int oldHeightToFork = Params().HeightToFork(); int oldCoinBaseMaturity = Params().GetCoinMaturity(); int oldStakeMinAge = Params().GetStakeMinAge(); int oldModifier = Params().GetModifierInterval(); // confirmations : 3 // remember that the miminum spacing is 10 !!! // spacing : [confirmations-1, max(confirmations-1, value)] // modifierInterval : [spacing, spacing)] // pow blocks : [confirmations + 1, max(confirmations+1, value)], this way we will have 2 modifiers int minConfirmations = 3; ModifiableParams()->setHeightToFork(6); ModifiableParams()->setTargetSpacing(minConfirmations - 1); ModifiableParams()->setStakeModifierInterval(minConfirmations - 1); ModifiableParams()->setCoinMaturity(minConfirmations); ModifiableParams()->setStakeMinAge(0); ModifiableParams()->setTargetTimespan(1); ModifiableParams()->setEnableBigRewards(true); ModifiableParams()->setLastPowBlock(minConfirmations + 1); ScanForWalletTransactions(pwalletMain); CScript scriptPubKey = GenerateSamePubKeyScript4Wallet(strSecret, pwalletMain); // generate 4 pow blocks CreateOldBlocksFromBlockInfo(1, minConfirmations + 2, blockinfo[0], pwalletMain, scriptPubKey, false, logToStdout); // generate 1 pos blocks GeneratePOSLegacyBlocks(minConfirmations + 2, 6, pwalletMain, scriptPubKey, logToStdout); // generate 1 new pos blocks GenerateBlocks(6, 7, pwalletMain, scriptPubKey, true, logToStdout); uint256 oldTipHash = chainActive.Tip()->GetBlockHash(); CheckDatabaseState(pwalletMain); uint256 newTipHash = chainActive.Tip()->GetBlockHash(); BOOST_ASSERT(oldTipHash == newTipHash); // Leaving old values Checkpoints::fEnabled = true; ModifiableParams()->setHeightToFork(oldHeightToFork); ModifiableParams()->setEnableBigRewards(false); ModifiableParams()->setCoinMaturity(oldCoinBaseMaturity); ModifiableParams()->setStakeMinAge(oldStakeMinAge); ModifiableParams()->setStakeModifierInterval(oldModifier); ModifiableParams()->setTargetTimespan(oldTargetTimespan); ModifiableParams()->setTargetSpacing(oldTargetSpacing); } #endif BOOST_AUTO_TEST_SUITE_END()
41.358209
119
0.693829
Kore-Core
b4bd4a499f2ad52f65baf7d80274dcd42921277a
2,571
cpp
C++
Glitter/Sources/BoundingBox.cpp
jalexanderqed/RayTracer
58de9f07b0c0f88292c3760402e29a70e1805af9
[ "MIT" ]
null
null
null
Glitter/Sources/BoundingBox.cpp
jalexanderqed/RayTracer
58de9f07b0c0f88292c3760402e29a70e1805af9
[ "MIT" ]
null
null
null
Glitter/Sources/BoundingBox.cpp
jalexanderqed/RayTracer
58de9f07b0c0f88292c3760402e29a70e1805af9
[ "MIT" ]
null
null
null
#include "BoundingBox.h" BoundingBox::BoundingBox() : vMin{ glm::vec3(INFINITY) }, vMax{ glm::vec3(-1 * INFINITY) } { } BoundingBox::BoundingBox(const PolygonIO* poly) { for (int i = 0; i < 3; i++) { vMax[i] = max(poly->vert[0].pos[i], max(poly->vert[1].pos[i], poly->vert[2].pos[i])); vMin[i] = min(poly->vert[0].pos[i], min(poly->vert[1].pos[i], poly->vert[2].pos[i])); } } BoundingBox::BoundingBox(const SphereIO* sphere) { for (int i = 0; i < 3; i++) { vMax[i] = sphere->origin[i] + sphere->radius; vMin[i] = sphere->origin[i] - sphere->radius; } } void BoundingBox::apply(const BoundingBox& box) { for (int i = 0; i < 3; i++) { vMax[i] = max(vMax[i], box.vMax[i]); vMin[i] = min(vMin[i], box.vMin[i]); } } bool BoundingBox::intersect(const glm::vec3& vec, const glm::vec3& origin, glm::vec3& res) { glm::vec3 closePlanes(0); glm::vec3 farPlanes(0); glm::vec3 invDir(1.0f / vec.x, 1.0f / vec.y, 1.0f / vec.z); for (int i = 0; i < 3; i++) { if (invDir[i] < 0) { closePlanes[i] = vMax[i]; farPlanes[i] = vMin[i]; } else { closePlanes[i] = vMin[i]; farPlanes[i] = vMax[i]; } } float tMin = (closePlanes.x - origin.x) * invDir.x; float tMax = (farPlanes.x - origin.x) * invDir.x; float tyMin = (closePlanes.y - origin.y) * invDir.y; float tyMax = (farPlanes.y - origin.y) * invDir.y; if (tMin > tyMax || tyMin > tMax) return false; if (tyMin > tMin) tMin = tyMin; if (tyMax < tMax) tMax = tyMax; float tzMin = (closePlanes.z - origin.z) * invDir.z; float tzMax = (farPlanes.z - origin.z) * invDir.z; if (tMin > tzMax || tzMin > tMax) return false; if (tzMin > tMin) tMin = tzMin; if (tzMax < tMax) tMax = tzMax; if (tMin <= 0) { if (tMax <= 0) return false; else res = origin + tMax * vec; } else { res = origin + tMin * vec; } return true; } bool BoundingBox::inside(glm::vec3 point) { return point.x < vMax.x && point.x > vMin.x && point.y < vMax.y && point.y > vMin.y && point.z < vMax.z && point.z > vMin.z; } BoundingBox boundPolySet(const PolySetIO* polySet) { BoundingBox res; PolygonIO* poly = polySet->poly; for (int i = 0; i < polySet->numPolys; i++, poly++) { res.apply(BoundingBox(poly)); } return res; } BoundingBox boundScene(SceneIO* scene) { BoundingBox res; for (ObjIO *object = scene->objects; object != NULL; object = object->next) { IntersectionPoint currPoint; if (object->type == SPHERE_OBJ) { res.apply(BoundingBox((SphereIO *)(object->data))); } else { res.apply(boundPolySet((PolySetIO*)(object->data))); } } return res; }
25.455446
92
0.610657
jalexanderqed