text
stringlengths
5
1.04M
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_long_long_calloc_63b.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-63b.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: calloc Allocate data using calloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_long_long_calloc_63 { #ifndef OMITBAD void bad_sink(long long * * data_ptr) { long long * data = *data_ptr; /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2B_sink(long long * * data_ptr) { long long * data = *data_ptr; /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } /* goodB2G uses the BadSource with the GoodSink */ void goodB2G_sink(long long * * data_ptr) { long long * data = *data_ptr; /* FIX: Free memory using free() */ free(data); } #endif /* OMITGOOD */ } // close namespace
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // test numeric_limits // Specializations shall be provided for each arithmetic type, both floating // point and integer, including bool. The member is_specialized shall be // true for all such specializations of numeric_limits. // Non-arithmetic standard types, such as complex<T> (26.3.2), shall not // have specializations. // From [numeric.limits]: // The value of each member of a specialization of numeric_limits on a cv // -qualified type cv T shall be equal to the value of the corresponding // member of the specialization on the unqualified type T. // More convenient to test it here. #include <limits> #include <complex> template <class T> void test() { static_assert(std::numeric_limits<T>::is_specialized, "std::numeric_limits<T>::is_specialized"); static_assert(std::numeric_limits<const T>::is_specialized, "std::numeric_limits<const T>::is_specialized"); static_assert(std::numeric_limits<volatile T>::is_specialized, "std::numeric_limits<volatile T>::is_specialized"); static_assert(std::numeric_limits<const volatile T>::is_specialized, "std::numeric_limits<const volatile T>::is_specialized"); } int main() { test<bool>(); test<char>(); test<wchar_t>(); #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS test<char16_t>(); test<char32_t>(); #endif // _LIBCPP_HAS_NO_UNICODE_CHARS test<signed char>(); test<unsigned char>(); test<signed short>(); test<unsigned short>(); test<signed int>(); test<unsigned int>(); test<signed long>(); test<unsigned long>(); test<signed long long>(); test<unsigned long long>(); #ifndef _LIBCPP_HAS_NO_INT128 test<__int128_t>(); test<__uint128_t>(); #endif test<float>(); test<double>(); test<long double>(); static_assert(!std::numeric_limits<std::complex<double> >::is_specialized, "!std::numeric_limits<std::complex<double> >::is_specialized"); }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <stdlib.h> #include <string.h> #pragma prefast(push) #pragma prefast(disable:26006, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:26007, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:28718, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:28726, "Dont bother us with tchar, someone else owns that.") #include <tchar.h> #pragma prefast(pop) #include <stddef.h> #include <stdio.h> #include <time.h> #include <limits.h> #include <minmax.h> #include <ctype.h> #include <specstrings.h> #include <algorithm> #include <functional> #if _MSC_VER >= 1100 using namespace std; #endif #pragma warning ( disable : 4127 ) #pragma warning ( disable : 4200 ) #pragma warning ( disable : 4201 ) #pragma warning ( disable : 4355 ) #pragma warning ( 3 : 4244 ) #pragma inline_depth( 255 ) #pragma inline_recursion( on ) #include "osu.hxx" #include "jet.h"
/*********************************************************************** created: Mon Jul 18 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/falagard/ComponentBase.h" #include "CEGUI/falagard/XMLHandler.h" #include "CEGUI/XMLSerializer.h" #include "CEGUI/PropertyHelper.h" #include "CEGUI/Colour.h" namespace CEGUI { //----------------------------------------------------------------------------// void FalagardComponentBase::createRenderGeometryAndAddToWindow( Window& srcWindow, const CEGUI::ColourRect* modColours, const Rectf* clipper) const { Rectf dest_rect(d_area.getPixelRect(srcWindow)); if (!clipper) clipper = &dest_rect; const Rectf final_clip_rect(dest_rect.getIntersection(*clipper)); addImageRenderGeometryToWindow_impl(srcWindow, dest_rect, modColours, &final_clip_rect); } //----------------------------------------------------------------------------// void FalagardComponentBase::createRenderGeometryAndAddToWindow( Window& srcWindow, const Rectf& baseRect, const CEGUI::ColourRect* modColours, const Rectf* clipper) const { Rectf dest_rect(d_area.getPixelRect(srcWindow, baseRect)); if (!clipper) clipper = &dest_rect; const Rectf final_clip_rect(dest_rect.getIntersection(*clipper)); addImageRenderGeometryToWindow_impl(srcWindow, dest_rect, modColours, &final_clip_rect); } //----------------------------------------------------------------------------// void FalagardComponentBase::initColoursRect(const Window& wnd, const ColourRect* modCols, ColourRect& cr) const { if (!d_colourPropertyName.empty()) cr = wnd.getProperty<ColourRect>(d_colourPropertyName); else cr = d_colours; if (modCols) cr *= *modCols; } //----------------------------------------------------------------------------// bool FalagardComponentBase::writeColoursXML(XMLSerializer& xml_stream) const { if (!d_colourPropertyName.empty()) { xml_stream.openTag(Falagard_xmlHandler::ColourRectPropertyElement); xml_stream.attribute(Falagard_xmlHandler::NameAttribute, d_colourPropertyName) .closeTag(); } else if (!d_colours.isMonochromatic() || d_colours.d_top_left != Colour(1.f, 1.f, 1.f, 1.f)) { xml_stream.openTag(Falagard_xmlHandler::ColoursElement) .attribute(Falagard_xmlHandler::TopLeftAttribute, PropertyHelper<Colour>::toString(d_colours.d_top_left)) .attribute(Falagard_xmlHandler::TopRightAttribute, PropertyHelper<Colour>::toString(d_colours.d_top_right)) .attribute(Falagard_xmlHandler::BottomLeftAttribute, PropertyHelper<Colour>::toString(d_colours.d_bottom_left)) .attribute(Falagard_xmlHandler::BottomRightAttribute, PropertyHelper<Colour>::toString(d_colours.d_bottom_right)) .closeTag(); } else return false; return true; } //----------------------------------------------------------------------------// bool FalagardComponentBase::handleFontRenderSizeChange(Window& window, const Font* font) const { return d_area.handleFontRenderSizeChange(window, font); } }
// Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/strength-config.h" #endif #include <cstddef> #if defined(HAVE_SYS_SELECT_H) #include <sys/select.h> #endif extern "C" void* memcpy(void* a, const void* b, size_t c); void* memcpy_int(void* a, const void* b, size_t c) { return memcpy(a, b, c); } namespace { // trigger: Use the memcpy_int wrapper which calls our internal memcpy. // A direct call to memcpy may be optimized away by the compiler. // test: Fill an array with a sequence of integers. memcpy to a new empty array. // Verify that the arrays are equal. Use an odd size to decrease the odds of // the call being optimized away. template <unsigned int T> bool sanity_test_memcpy() { unsigned int memcpy_test[T]; unsigned int memcpy_verify[T] = {}; for (unsigned int i = 0; i != T; ++i) memcpy_test[i] = i; memcpy_int(memcpy_verify, memcpy_test, sizeof(memcpy_test)); for (unsigned int i = 0; i != T; ++i) { if (memcpy_verify[i] != i) return false; } return true; } #if defined(HAVE_SYS_SELECT_H) // trigger: Call FD_SET to trigger __fdelt_chk. FORTIFY_SOURCE must be defined // as >0 and optimizations must be set to at least -O2. // test: Add a file descriptor to an empty fd_set. Verify that it has been // correctly added. bool sanity_test_fdelt() { fd_set fds; FD_ZERO(&fds); FD_SET(0, &fds); return FD_ISSET(0, &fds); } #endif } // anon namespace bool glibc_sanity_test() { #if defined(HAVE_SYS_SELECT_H) if (!sanity_test_fdelt()) return false; #endif return sanity_test_memcpy<1025>(); }
#include "../include/A.h" //在类外定义函数 - 构造函数 A::A() { cout << "A()构造函数" << endl; } //在类外定义函数 - 析构函数 A::~A() { cout << "~A()析构函数" << endl; } //在类外定义函数 - f1()函数 void A::f1() { cout << "A::f1()函数被调用~~~" << endl; } //在类外定义函数 - f2()函数 void A::f2() { cout << "A::f2()函数被调用~~~" << endl; }
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/dbus/power/power_policy_controller.h" #include <memory> #include "base/run_loop.h" #include "base/test/task_environment.h" #include "chromeos/dbus/power/fake_power_manager_client.h" #include "chromeos/dbus/power_manager/backlight.pb.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { class PowerPolicyControllerTest : public testing::Test { public: PowerPolicyControllerTest() = default; PowerPolicyControllerTest(const PowerPolicyControllerTest&) = delete; PowerPolicyControllerTest& operator=(const PowerPolicyControllerTest&) = delete; ~PowerPolicyControllerTest() override = default; void SetUp() override { PowerManagerClient::InitializeFake(); PowerPolicyController::Initialize(FakePowerManagerClient::Get()); ASSERT_TRUE(PowerPolicyController::IsInitialized()); policy_controller_ = PowerPolicyController::Get(); } void TearDown() override { if (PowerPolicyController::IsInitialized()) PowerPolicyController::Shutdown(); PowerManagerClient::Shutdown(); } protected: FakePowerManagerClient* power_manager() { return FakePowerManagerClient::Get(); } PowerPolicyController* policy_controller_; base::test::SingleThreadTaskEnvironment task_environment_; }; TEST_F(PowerPolicyControllerTest, Prefs) { PowerPolicyController::PrefValues prefs; prefs.ac_screen_dim_delay_ms = 600000; prefs.ac_screen_off_delay_ms = 660000; prefs.ac_idle_delay_ms = 720000; prefs.battery_screen_dim_delay_ms = 300000; prefs.battery_screen_off_delay_ms = 360000; prefs.battery_idle_delay_ms = 420000; prefs.ac_idle_action = PowerPolicyController::ACTION_SUSPEND; prefs.battery_idle_action = PowerPolicyController::ACTION_STOP_SESSION; prefs.lid_closed_action = PowerPolicyController::ACTION_SHUT_DOWN; prefs.use_audio_activity = true; prefs.use_video_activity = true; prefs.ac_brightness_percent = 87.0; prefs.battery_brightness_percent = 43.0; prefs.enable_auto_screen_lock = false; prefs.presentation_screen_dim_delay_factor = 3.0; prefs.user_activity_screen_dim_delay_factor = 2.0; prefs.wait_for_initial_user_activity = true; prefs.force_nonzero_brightness_for_user_activity = false; prefs.boot_on_ac = true; prefs.usb_power_share = false; policy_controller_->ApplyPrefs(prefs); power_manager::PowerManagementPolicy expected_policy; expected_policy.mutable_ac_delays()->set_screen_dim_ms(600000); expected_policy.mutable_ac_delays()->set_screen_off_ms(660000); expected_policy.mutable_ac_delays()->set_screen_lock_ms(-1); expected_policy.mutable_ac_delays()->set_idle_warning_ms(-1); expected_policy.mutable_ac_delays()->set_idle_ms(720000); expected_policy.mutable_battery_delays()->set_screen_dim_ms(300000); expected_policy.mutable_battery_delays()->set_screen_off_ms(360000); expected_policy.mutable_battery_delays()->set_screen_lock_ms(-1); expected_policy.mutable_battery_delays()->set_idle_warning_ms(-1); expected_policy.mutable_battery_delays()->set_idle_ms(420000); expected_policy.set_ac_idle_action( power_manager::PowerManagementPolicy_Action_SUSPEND); expected_policy.set_battery_idle_action( power_manager::PowerManagementPolicy_Action_STOP_SESSION); expected_policy.set_lid_closed_action( power_manager::PowerManagementPolicy_Action_SHUT_DOWN); expected_policy.set_use_audio_activity(true); expected_policy.set_use_video_activity(true); expected_policy.set_ac_brightness_percent(87.0); expected_policy.set_battery_brightness_percent(43.0); expected_policy.set_presentation_screen_dim_delay_factor(3.0); expected_policy.set_user_activity_screen_dim_delay_factor(2.0); expected_policy.set_wait_for_initial_user_activity(true); expected_policy.set_force_nonzero_brightness_for_user_activity(false); expected_policy.set_boot_on_ac(true); expected_policy.set_usb_power_share(false); expected_policy.mutable_battery_charge_mode()->set_mode( power_manager::PowerManagementPolicy::BatteryChargeMode::ADAPTIVE); expected_policy.set_reason(PowerPolicyController::kPrefsReason); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Change some prefs and check that an updated policy is sent. prefs.ac_idle_warning_delay_ms = 700000; prefs.battery_idle_warning_delay_ms = 400000; prefs.lid_closed_action = PowerPolicyController::ACTION_SUSPEND; prefs.ac_brightness_percent = -1.0; prefs.force_nonzero_brightness_for_user_activity = true; policy_controller_->ApplyPrefs(prefs); expected_policy.mutable_ac_delays()->set_idle_warning_ms(700000); expected_policy.mutable_battery_delays()->set_idle_warning_ms(400000); expected_policy.set_lid_closed_action( power_manager::PowerManagementPolicy_Action_SUSPEND); expected_policy.clear_ac_brightness_percent(); expected_policy.set_force_nonzero_brightness_for_user_activity(true); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // The enable-auto-screen-lock pref should force the screen-lock delays to // match the screen-off delays plus a constant value. prefs.enable_auto_screen_lock = true; policy_controller_->ApplyPrefs(prefs); expected_policy.mutable_ac_delays()->set_screen_lock_ms( 660000 + PowerPolicyController::kScreenLockAfterOffDelayMs); expected_policy.mutable_battery_delays()->set_screen_lock_ms( 360000 + PowerPolicyController::kScreenLockAfterOffDelayMs); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // If the screen-lock-delay prefs are set to lower values than the // screen-off delays plus the constant, the lock prefs should take // precedence. prefs.ac_screen_lock_delay_ms = 70000; prefs.battery_screen_lock_delay_ms = 60000; policy_controller_->ApplyPrefs(prefs); expected_policy.mutable_ac_delays()->set_screen_lock_ms(70000); expected_policy.mutable_battery_delays()->set_screen_lock_ms(60000); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // If the artificial screen-lock delays would exceed the idle delay, they // shouldn't be set -- the power manager would ignore them since the // idle action should lock the screen in this case. prefs.ac_screen_off_delay_ms = prefs.ac_idle_delay_ms - 1; prefs.battery_screen_off_delay_ms = prefs.battery_idle_delay_ms - 1; prefs.ac_screen_lock_delay_ms = -1; prefs.battery_screen_lock_delay_ms = -1; policy_controller_->ApplyPrefs(prefs); expected_policy.mutable_ac_delays()->set_screen_off_ms( prefs.ac_screen_off_delay_ms); expected_policy.mutable_battery_delays()->set_screen_off_ms( prefs.battery_screen_off_delay_ms); expected_policy.mutable_ac_delays()->set_screen_lock_ms(-1); expected_policy.mutable_battery_delays()->set_screen_lock_ms(-1); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Set the "allow screen wake locks" pref to false and add a screen wake lock. // It should be downgraded to a system wake lock, and the pref-supplied delays // should be left untouched. prefs.allow_screen_wake_locks = false; policy_controller_->ApplyPrefs(prefs); policy_controller_->AddScreenWakeLock(PowerPolicyController::REASON_OTHER, "Screen"); expected_policy.set_system_wake_lock(true); expected_policy.set_reason(std::string(PowerPolicyController::kPrefsReason) + ", Screen"); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Set the "allow wake locks" pref to false and add a screen wake lock. // It should be ignored. prefs.allow_wake_locks = false; policy_controller_->ApplyPrefs(prefs); policy_controller_->AddScreenWakeLock(PowerPolicyController::REASON_OTHER, "Screen"); expected_policy.clear_system_wake_lock(); expected_policy.set_reason(std::string(PowerPolicyController::kPrefsReason)); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Set PeakShift prefs. prefs.peak_shift_enabled = true; prefs.peak_shift_battery_threshold = 20; power_manager::PowerManagementPolicy::PeakShiftDayConfig peak_shift_config; peak_shift_config.set_day(power_manager::PowerManagementPolicy::TUESDAY); peak_shift_config.mutable_start_time()->set_hour(10); peak_shift_config.mutable_start_time()->set_minute(0); peak_shift_config.mutable_end_time()->set_hour(20); peak_shift_config.mutable_end_time()->set_minute(15); peak_shift_config.mutable_charge_start_time()->set_hour(23); peak_shift_config.mutable_charge_start_time()->set_minute(45); prefs.peak_shift_day_configs.push_back(peak_shift_config); policy_controller_->ApplyPrefs(prefs); expected_policy.set_peak_shift_battery_percent_threshold(20); *expected_policy.mutable_peak_shift_day_configs()->Add() = peak_shift_config; EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Set AdvancedBatteryChargeMode prefs. prefs.advanced_battery_charge_mode_enabled = true; power_manager::PowerManagementPolicy::AdvancedBatteryChargeModeDayConfig advanced_mode_config; advanced_mode_config.set_day(power_manager::PowerManagementPolicy::FRIDAY); advanced_mode_config.mutable_charge_start_time()->set_hour(10); advanced_mode_config.mutable_charge_start_time()->set_minute(0); advanced_mode_config.mutable_charge_end_time()->set_hour(23); advanced_mode_config.mutable_charge_end_time()->set_minute(45); prefs.advanced_battery_charge_mode_day_configs.push_back( advanced_mode_config); policy_controller_->ApplyPrefs(prefs); *expected_policy.mutable_advanced_battery_charge_mode_day_configs()->Add() = advanced_mode_config; EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Set BatteryChargeMode prefs. prefs.battery_charge_mode = power_manager::PowerManagementPolicy::BatteryChargeMode::PRIMARILY_AC_USE; policy_controller_->ApplyPrefs(prefs); expected_policy.mutable_battery_charge_mode()->set_mode( power_manager::PowerManagementPolicy::BatteryChargeMode:: PRIMARILY_AC_USE); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Set BatteryChargeMode prefs. prefs.battery_charge_mode = power_manager::PowerManagementPolicy::BatteryChargeMode::CUSTOM; prefs.custom_charge_start = 51; prefs.custom_charge_stop = 97; policy_controller_->ApplyPrefs(prefs); expected_policy.mutable_battery_charge_mode()->set_mode( power_manager::PowerManagementPolicy::BatteryChargeMode::CUSTOM); expected_policy.mutable_battery_charge_mode()->set_custom_charge_start(51); expected_policy.mutable_battery_charge_mode()->set_custom_charge_stop(97); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); } TEST_F(PowerPolicyControllerTest, SystemWakeLock) { policy_controller_->AddSystemWakeLock(PowerPolicyController::REASON_OTHER, "1"); power_manager::PowerManagementPolicy expected_policy; expected_policy.set_system_wake_lock(true); expected_policy.set_reason("1"); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); } TEST_F(PowerPolicyControllerTest, DimWakeLock) { policy_controller_->AddDimWakeLock(PowerPolicyController::REASON_OTHER, "1"); power_manager::PowerManagementPolicy expected_policy; expected_policy.set_dim_wake_lock(true); expected_policy.set_reason("1"); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); } TEST_F(PowerPolicyControllerTest, ScreenWakeLock) { policy_controller_->AddScreenWakeLock(PowerPolicyController::REASON_OTHER, "1"); power_manager::PowerManagementPolicy expected_policy; expected_policy.set_screen_wake_lock(true); expected_policy.set_reason("1"); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); } TEST_F(PowerPolicyControllerTest, IgnoreMediaWakeLocksWhenRequested) { PowerPolicyController::PrefValues prefs; policy_controller_->ApplyPrefs(prefs); const power_manager::PowerManagementPolicy kDefaultPolicy = power_manager()->policy(); // Wake locks created for audio or video playback should be ignored when the // |use_audio_activity| or |use_video_activity| prefs are unset. prefs.use_audio_activity = false; prefs.use_video_activity = false; policy_controller_->ApplyPrefs(prefs); const int audio_id = policy_controller_->AddSystemWakeLock( PowerPolicyController::REASON_AUDIO_PLAYBACK, "audio"); const int video_id = policy_controller_->AddScreenWakeLock( PowerPolicyController::REASON_VIDEO_PLAYBACK, "video"); power_manager::PowerManagementPolicy expected_policy = kDefaultPolicy; expected_policy.set_use_audio_activity(false); expected_policy.set_use_video_activity(false); expected_policy.set_reason(PowerPolicyController::kPrefsReason); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Non-media screen wake locks should still be honored. const int other_id = policy_controller_->AddScreenWakeLock( PowerPolicyController::REASON_OTHER, "other"); expected_policy.set_screen_wake_lock(true); expected_policy.set_reason(std::string(PowerPolicyController::kPrefsReason) + ", other"); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Start honoring audio activity and check that the audio wake lock is used. policy_controller_->RemoveWakeLock(other_id); prefs.use_audio_activity = true; policy_controller_->ApplyPrefs(prefs); expected_policy = kDefaultPolicy; expected_policy.set_use_video_activity(false); expected_policy.set_system_wake_lock(true); expected_policy.set_reason(std::string(PowerPolicyController::kPrefsReason) + ", audio"); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); // Now honor video activity as well. prefs.use_video_activity = true; policy_controller_->ApplyPrefs(prefs); expected_policy = kDefaultPolicy; expected_policy.set_screen_wake_lock(true); expected_policy.set_system_wake_lock(true); expected_policy.set_reason(std::string(PowerPolicyController::kPrefsReason) + ", audio, video"); EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); policy_controller_->RemoveWakeLock(audio_id); policy_controller_->RemoveWakeLock(video_id); } TEST_F(PowerPolicyControllerTest, AvoidSendingEmptyPolicies) { // Check that empty policies aren't sent when PowerPolicyController is created // or destroyed. EXPECT_EQ(0, power_manager()->num_set_policy_calls()); PowerPolicyController::Shutdown(); EXPECT_EQ(0, power_manager()->num_set_policy_calls()); } TEST_F(PowerPolicyControllerTest, DoNothingOnLidClosedWhileSigningOut) { PowerPolicyController::PrefValues prefs; policy_controller_->ApplyPrefs(prefs); const power_manager::PowerManagementPolicy kDefaultPolicy = power_manager()->policy(); prefs.lid_closed_action = PowerPolicyController::ACTION_SHUT_DOWN; policy_controller_->ApplyPrefs(prefs); power_manager::PowerManagementPolicy expected_policy; expected_policy = kDefaultPolicy; expected_policy.set_lid_closed_action( power_manager::PowerManagementPolicy_Action_SHUT_DOWN); // Sanity check. EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); policy_controller_->NotifyChromeIsExiting(); expected_policy.set_lid_closed_action( power_manager::PowerManagementPolicy_Action_DO_NOTHING); // Lid-closed action successfully changed to "do nothing". EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); } TEST_F(PowerPolicyControllerTest, SuspendOnLidClosedWhileSignedOut) { PowerPolicyController::PrefValues prefs; policy_controller_->ApplyPrefs(prefs); const power_manager::PowerManagementPolicy kDefaultPolicy = power_manager()->policy(); prefs.lid_closed_action = PowerPolicyController::ACTION_SHUT_DOWN; policy_controller_->ApplyPrefs(prefs); power_manager::PowerManagementPolicy expected_policy; expected_policy = kDefaultPolicy; expected_policy.set_lid_closed_action( power_manager::PowerManagementPolicy_Action_SHUT_DOWN); // Sanity check EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); policy_controller_->SetEncryptionMigrationActive(true); expected_policy.set_lid_closed_action( power_manager::PowerManagementPolicy_Action_SUSPEND); expected_policy.set_reason("Prefs, encryption migration"); // Lid-closed action successfully changed to "suspend". EXPECT_EQ( PowerPolicyController::GetPolicyDebugString(expected_policy), PowerPolicyController::GetPolicyDebugString(power_manager()->policy())); } TEST_F(PowerPolicyControllerTest, PerSessionScreenBrightnessOverride) { const double kAcBrightness = 99.0; const double kBatteryBrightness = 77.0; PowerPolicyController::PrefValues prefs; prefs.ac_brightness_percent = kAcBrightness; prefs.battery_brightness_percent = kBatteryBrightness; policy_controller_->ApplyPrefs(prefs); EXPECT_EQ(kAcBrightness, power_manager()->policy().ac_brightness_percent()); EXPECT_EQ(kBatteryBrightness, power_manager()->policy().battery_brightness_percent()); // Simulate model triggered brightness change - shouldn't override the policy. power_manager::SetBacklightBrightnessRequest request; request.set_percent(80.0); request.set_cause(power_manager::SetBacklightBrightnessRequest_Cause_MODEL); power_manager()->SetScreenBrightness(request); base::RunLoop().RunUntilIdle(); policy_controller_->ApplyPrefs(prefs); EXPECT_EQ(kAcBrightness, power_manager()->policy().ac_brightness_percent()); EXPECT_EQ(kBatteryBrightness, power_manager()->policy().battery_brightness_percent()); // Simulate user triggered brightness change - should override the policy. request.set_percent(80.0); request.set_cause( power_manager::SetBacklightBrightnessRequest_Cause_USER_REQUEST); power_manager()->SetScreenBrightness(request); base::RunLoop().RunUntilIdle(); policy_controller_->ApplyPrefs(prefs); EXPECT_FALSE(power_manager()->policy().has_ac_brightness_percent()); EXPECT_FALSE(power_manager()->policy().has_battery_brightness_percent()); // Simulate policy values update that should be ignored. prefs.ac_brightness_percent = 98.0; prefs.battery_brightness_percent = 76.0; policy_controller_->ApplyPrefs(prefs); EXPECT_FALSE(power_manager()->policy().has_ac_brightness_percent()); EXPECT_FALSE(power_manager()->policy().has_battery_brightness_percent()); } TEST_F(PowerPolicyControllerTest, PolicyAutoScreenLockDelay) { PowerPolicyController::PrefValues prefs; policy_controller_->ApplyPrefs(prefs); // Autolock disabled. prefs.ac_screen_lock_delay_ms = 4000; prefs.battery_screen_lock_delay_ms = 1000; prefs.enable_auto_screen_lock = false; policy_controller_->ApplyPrefs(prefs); EXPECT_EQ(base::TimeDelta(), policy_controller_->Get()->GetMaxPolicyAutoScreenLockDelay()); // Autolock enabled. // Longer AC delay. prefs.enable_auto_screen_lock = true; policy_controller_->ApplyPrefs(prefs); EXPECT_EQ(base::Milliseconds(prefs.ac_screen_lock_delay_ms), policy_controller_->Get()->GetMaxPolicyAutoScreenLockDelay()); // Longer battery delay. prefs.ac_screen_lock_delay_ms = 1000; prefs.battery_screen_lock_delay_ms = 4000; policy_controller_->ApplyPrefs(prefs); EXPECT_EQ(base::Milliseconds(prefs.battery_screen_lock_delay_ms), policy_controller_->Get()->GetMaxPolicyAutoScreenLockDelay()); } TEST_F(PowerPolicyControllerTest, FastSuspendWhenBacklightsForcedOff) { const int kAcDimMs = 600000; // 10m const int kAcOffMs = 620000; // 10m20s const int kAcLockMs = 610000; // 10m10s const int kAcIdleWarnMs = 650000; // 10m50s const int kAcIdleMs = 660000; // 11m const int kBatteryDimMs = 300000; // 5m const int kBatteryOffMs = 310000; // 5m10s const int kBatteryLockMs = 320000; // 5m20s const int kBatteryIdleWarnMs = 355000; // 5m55s const int kBatteryIdleMs = 360000; // 6m PowerPolicyController::PrefValues prefs; prefs.ac_screen_dim_delay_ms = kAcDimMs; prefs.ac_screen_off_delay_ms = kAcOffMs; prefs.ac_screen_lock_delay_ms = kAcLockMs; prefs.ac_idle_warning_delay_ms = kAcIdleWarnMs; prefs.ac_idle_delay_ms = kAcIdleMs; prefs.battery_screen_dim_delay_ms = kBatteryDimMs; prefs.battery_screen_off_delay_ms = kBatteryOffMs; prefs.battery_screen_lock_delay_ms = kBatteryLockMs; prefs.battery_idle_warning_delay_ms = kBatteryIdleWarnMs; prefs.battery_idle_delay_ms = kBatteryIdleMs; prefs.ac_idle_action = PowerPolicyController::ACTION_SUSPEND; prefs.battery_idle_action = PowerPolicyController::ACTION_SUSPEND; prefs.fast_suspend_when_backlights_forced_off = true; policy_controller_->ApplyPrefs(prefs); // We should start out with the delays specified by the prefs. power_manager::PowerManagementPolicy policy = power_manager()->policy(); EXPECT_EQ(kAcDimMs, policy.ac_delays().screen_dim_ms()); EXPECT_EQ(kAcOffMs, policy.ac_delays().screen_off_ms()); EXPECT_EQ(kAcLockMs, policy.ac_delays().screen_lock_ms()); EXPECT_EQ(kAcIdleWarnMs, policy.ac_delays().idle_warning_ms()); EXPECT_EQ(kAcIdleMs, policy.ac_delays().idle_ms()); EXPECT_EQ(kBatteryDimMs, policy.battery_delays().screen_dim_ms()); EXPECT_EQ(kBatteryOffMs, policy.battery_delays().screen_off_ms()); EXPECT_EQ(kBatteryLockMs, policy.battery_delays().screen_lock_ms()); EXPECT_EQ(kBatteryIdleWarnMs, policy.battery_delays().idle_warning_ms()); EXPECT_EQ(kBatteryIdleMs, policy.battery_delays().idle_ms()); // After reporting that the backlights were forced off for a power button // press, the idle and idle-warning delays should be shortened and other // delays should be cleared. policy_controller_->HandleBacklightsForcedOffForPowerButton(true); policy = power_manager()->policy(); EXPECT_EQ(0, policy.ac_delays().screen_dim_ms()); EXPECT_EQ(0, policy.ac_delays().screen_off_ms()); EXPECT_EQ(0, policy.ac_delays().screen_lock_ms()); EXPECT_EQ(kAcIdleWarnMs - kAcOffMs, policy.ac_delays().idle_warning_ms()); EXPECT_EQ(kAcIdleMs - kAcOffMs, policy.ac_delays().idle_ms()); EXPECT_EQ(0, policy.battery_delays().screen_dim_ms()); EXPECT_EQ(0, policy.battery_delays().screen_off_ms()); EXPECT_EQ(0, policy.battery_delays().screen_lock_ms()); EXPECT_EQ(kBatteryIdleWarnMs - kBatteryOffMs, policy.battery_delays().idle_warning_ms()); EXPECT_EQ(kBatteryIdleMs - kBatteryOffMs, policy.battery_delays().idle_ms()); // If the screen-off delay is equal to the idle delay and longer than the // idle-warning delay, both the idle and idle-warning delays should be set to // 1 (the minimum delay allowed by powerd). prefs.ac_screen_off_delay_ms = kAcIdleMs; policy_controller_->ApplyPrefs(prefs); policy = power_manager()->policy(); EXPECT_EQ(0, policy.ac_delays().screen_dim_ms()); EXPECT_EQ(0, policy.ac_delays().screen_off_ms()); EXPECT_EQ(0, policy.ac_delays().screen_lock_ms()); EXPECT_EQ(1, policy.ac_delays().idle_warning_ms()); EXPECT_EQ(1, policy.ac_delays().idle_ms()); } } // namespace chromeos
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/web_applications/preinstalled_web_apps/preinstalled_web_apps.h" #include "base/test/bind.h" #include "build/branding_buildflags.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/web_applications/components/external_app_install_features.h" #include "chrome/browser/web_applications/components/web_app_id_constants.h" #include "chrome/browser/web_applications/external_web_app_manager.h" #include "chrome/browser/web_applications/test/test_os_integration_manager.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/test/browser_test.h" namespace web_app { class PreinstalledWebAppsBrowserTest : public InProcessBrowserTest { public: PreinstalledWebAppsBrowserTest() { ExternalWebAppManager::SkipStartupForTesting(); // Ignore any default app configs on disk. ExternalWebAppManager::SetConfigDirForTesting(&empty_path_); ForceUsePreinstalledWebAppsForTesting(); WebAppProvider::SetOsIntegrationManagerFactoryForTesting( [](Profile* profile) -> std::unique_ptr<OsIntegrationManager> { return std::make_unique<TestOsIntegrationManager>( profile, nullptr, nullptr, nullptr, nullptr); }); } base::FilePath empty_path_; }; IN_PROC_BROWSER_TEST_F(PreinstalledWebAppsBrowserTest, CheckInstalledFields) { base::AutoReset<bool> scope = SetExternalAppInstallFeatureAlwaysEnabledForTesting(); auto& provider = *WebAppProvider::Get(browser()->profile()); struct Expectation { const char* app_id; const char* install_url; const char* launch_url; } kExpectations[] = { #if BUILDFLAG(GOOGLE_CHROME_BRANDING) #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) { kGoogleCalendarAppId, "https://calendar.google.com/calendar/installwebapp?usp=chrome_default", "https://calendar.google.com/calendar/r?usp=installed_webapp", }, #endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) { kGoogleDocsAppId, "https://docs.google.com/document/installwebapp?usp=chrome_default", "https://docs.google.com/document/?usp=installed_webapp", }, { kGoogleSlidesAppId, "https://docs.google.com/presentation/installwebapp?usp=chrome_default", "https://docs.google.com/presentation/?usp=installed_webapp", }, { kGoogleSheetsAppId, "https://docs.google.com/spreadsheets/installwebapp?usp=chrome_default", "https://docs.google.com/spreadsheets/?usp=installed_webapp", }, { kGoogleDriveAppId, "https://drive.google.com/drive/installwebapp?usp=chrome_default", "https://drive.google.com/?lfhs=2&usp=installed_webapp", }, { kGmailAppId, "https://mail.google.com/mail/installwebapp?usp=chrome_default", "https://mail.google.com/mail/?usp=installed_webapp", }, { kYoutubeAppId, "https://www.youtube.com/s/notifications/manifest/cr_install.html", "https://www.youtube.com/?feature=ytca", }, #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) }; size_t kExpectedCount = sizeof(kExpectations) / sizeof(kExpectations[0]); base::RunLoop run_loop; provider.external_web_app_manager().LoadAndSynchronizeForTesting( base::BindLambdaForTesting( [&](std::map<GURL, PendingAppManager::InstallResult> install_results, std::map<GURL, bool> uninstall_results) { EXPECT_EQ(install_results.size(), kExpectedCount); for (const Expectation& expectation : kExpectations) { EXPECT_EQ(install_results[GURL(expectation.install_url)].code, InstallResultCode::kSuccessOfflineOnlyInstall); } EXPECT_EQ(uninstall_results.size(), 0u); run_loop.Quit(); })); run_loop.Run(); for (const Expectation& expectation : kExpectations) { EXPECT_EQ(provider.registrar().GetAppLaunchUrl(expectation.app_id), GURL(expectation.launch_url)); } // Note that default web apps *DO* show app icons on Chrome OS however it // is done via the |WebAppsChromeOs| publishing live our current app state to // the app service rather than writing shortcut files as the case on all other // desktop platforms. auto* test_os_integration_manager = provider.os_integration_manager().AsTestOsIntegrationManager(); EXPECT_EQ(test_os_integration_manager->num_create_shortcuts_calls(), 0u); EXPECT_EQ(test_os_integration_manager->num_create_file_handlers_calls(), 0u); EXPECT_EQ(test_os_integration_manager->num_register_run_on_os_login_calls(), 0u); EXPECT_EQ( test_os_integration_manager->num_add_app_to_quick_launch_bar_calls(), 0u); EXPECT_FALSE(test_os_integration_manager->did_add_to_desktop()); } } // namespace web_app
#include <iostream> #include <iomanip> #include <fstream> #include <string> #include <stdlib.h> #include <chrono> #include <vector> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include "deepeye_image_classifier_gpu.h" #include "deepeye_util.h" #include "cm_image.h" #define TITLE "Visual Inspection DEMO" #define SPEED_LIST_COUNT (6) using namespace deepeye; void show_result(float *pred_prob, int n_classes, int pred) { std::cout << std::fixed; std::cout << "[0] OK ... " << std::setprecision(5) << pred_prob[0] << std::endl; std::cout << "[1] NG ... " << std::setprecision(5) <<pred_prob[1] << std::endl; std::cout << "pred: [" << pred << ": "; if(pred == 0){ std::cout << "OK]"; } else if(pred==1){ std::cout << "NG]"; } std::cout << endl; } void classification() { static const int n_classes = 2; static const int channel = 3; static const int batch_size = 1; vector<string> img_path_list; chrono::system_clock::time_point start, end; double time; int speed_index = 2; int speed_list[SPEED_LIST_COUNT] = { 50, 100, 500, 1000, 2000, 5000 }; // [ms] unsigned int arch_index = 0; vector<string> acrh_names {"GoogLeNet", "ResNet50", "MobileNet"}; vector<ImageClassifier*> arch_list; arch_list.push_back(new ImageClassifier(n_classes, channel, batch_size, ImageClassifier::Arch::GoogLeNet)); arch_list.push_back(new ImageClassifier(n_classes, channel, batch_size, ImageClassifier::Arch::ResNet50)); arch_list.push_back(new ImageClassifier(n_classes, channel, batch_size, ImageClassifier::Arch::MobileNet)); try { arch_list[0]->load_weights("../weights/weights_googlenet.deep0"); arch_list[1]->load_weights("../weights/weights_resnet50.deep0"); arch_list[2]->load_weights("../weights/weights_mobilenet.deep0"); } catch(...) { cout << "failed to load weight file." << endl; exit(1); } float pred_prob[n_classes]; int pred; cv::namedWindow(TITLE, CV_WINDOW_AUTOSIZE | CV_WINDOW_FREERATIO); int is_exit = false; int is_pause = false; cv::Mat roi; Image *x = nullptr; std::vector<cv::Mat> ret_img { cv::imread("../img/ok.png"), cv::imread("../img/ng.png") }; cv::Mat cm_logo = cv::imread("../img/cm_logo.png"); // image file path std::ifstream ifs("../../../data/image.txt"); if (ifs.fail()) { std::cerr << "Failed to open image.txt" << std::endl; exit(-1); } string img_path; while (getline(ifs, img_path)) { if(img_path != ""){ img_path_list.push_back(img_path); } } unsigned int img_index = 0; // main loop while(is_exit == false){ if (is_pause == false){ try{ x = Image::load(img_path_list[img_index], arch_list[arch_index]->get_input_size()); } catch(...){ std::cerr << "Failed to open " << img_path_list[img_index] << std::endl; exit(-1); } if(x == nullptr){ cout << "failed to open image file. [" << img_path_list[img_index] << "]" << endl; img_index++; if(img_index >= img_path_list.size()) { img_index = 0; } continue; } //----- predict std::cout << "---- [" << img_index << "]" << img_path_list[img_index] << " ----" << std::endl; start = chrono::system_clock::now(); arch_list[arch_index]->predict_prob(x->get_data(), pred_prob); end = chrono::system_clock::now(); time = static_cast<double>(chrono::duration_cast<chrono::microseconds>(end - start).count() / 1000.0); pred = arch_list[arch_index]->predict(x->get_data()); show_result(pred_prob, n_classes, pred); std::cout << std::endl; // draw cv::Mat bg = cv::Mat::zeros(440, 500, CV_8UC3); cv::rectangle(bg, cv::Point(0,0), cv::Point(500, 440), cv::Scalar(0xe1,0x69,0x41), -1, CV_AA); #define RESULT_X (270) #define RESULT_Y (24) #define RESULT_Y2 (150) roi = bg(cv::Rect(RESULT_X, RESULT_Y, ret_img[pred].cols, ret_img[pred].rows)); ret_img[pred].copyTo(roi); char buf[256]; sprintf(buf, "[OK] %f", pred_prob[0]); cv::putText(bg, buf, cv::Point(RESULT_X, RESULT_Y2), cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(255,255,255), 1, CV_AA); sprintf(buf, "[NG] %f", pred_prob[1]); cv::putText(bg, buf, cv::Point(RESULT_X, RESULT_Y2+30), cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(255,255,255), 1, CV_AA); sprintf(buf, "%lf [ms]", time); cv::putText(bg, buf, cv::Point(RESULT_X, RESULT_Y2+60), cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(255,255,255), 1, CV_AA); cv::putText(bg, acrh_names[arch_index], cv::Point(RESULT_X, RESULT_Y2+100), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255), 1, CV_AA); #define CAPTION_X (24) #define CAPTION_Y (300) cv::putText(bg, "[ESC]:Quit [SPACE]:Pause", cv::Point(CAPTION_X, CAPTION_Y), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255), 1, CV_AA); sprintf(buf, "[c]:Change display update time (%d[ms])", speed_list[speed_index]); cv::putText(bg, buf, cv::Point(CAPTION_X, CAPTION_Y+30), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255), 1, CV_AA); cv::putText(bg, "[m]:Change architecture", cv::Point(CAPTION_X, CAPTION_Y+60), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255), 1, CV_AA); #define IMG_X (24) #define IMG_Y (24) roi = bg(cv::Rect(IMG_X, IMG_Y, x->getMat().cols, x->getMat().rows)); x->getMat().copyTo(roi); cv::rectangle(bg, cv::Point(0,390), cv::Point(500, 440), cv::Scalar(255,255,255), -1, CV_AA); roi = bg(cv::Rect(210, 390, cm_logo.cols, cm_logo.rows)); cm_logo.copyTo(roi); cv::imshow(TITLE, bg); img_index++; if(img_index >= img_path_list.size()) { img_index = 0; } } char key = cv::waitKey(speed_list[speed_index]); switch(key){ case 27: // ESC is_exit = true; break; case ' ': // SPACE is_pause = !is_pause; break; case 'c': case 'C': speed_index++; if(speed_index >= SPEED_LIST_COUNT) { speed_index = 0; } break; case 'm': case 'M': arch_index++; if(arch_index >= arch_list.size()) { arch_index = 0; } default: break; } if (x != nullptr) { delete x; x = nullptr; } } for(auto net : arch_list) { delete net; } } int main() { classification(); return 0; }
// // Copyright 2013 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "../osd/cpuKernel.h" #include "../osd/tbbKernel.h" #include "../osd/types.h" #include "../osd/bufferDescriptor.h" #include "../far/patchBasis.h" #include <cassert> #include <cstdlib> #include <tbb/parallel_for.h> namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Osd { #define grain_size 200 template <class T> T * elementAtIndex(T * src, int index, BufferDescriptor const &desc) { return src + index * desc.stride; } static inline void clear(float *dst, BufferDescriptor const &desc) { assert(dst); memset(dst, 0, desc.length*sizeof(float)); } static inline void addWithWeight(float *dst, const float *src, int srcIndex, float weight, BufferDescriptor const &desc) { assert(src and dst); src = elementAtIndex(src, srcIndex, desc); for (int k = 0; k < desc.length; ++k) { dst[k] += src[k] * weight; } } static inline void copy(float *dst, int dstIndex, const float *src, BufferDescriptor const &desc) { assert(src and dst); dst = elementAtIndex(dst, dstIndex, desc); memcpy(dst, src, desc.length*sizeof(float)); } class TBBStencilKernel { BufferDescriptor _srcDesc; BufferDescriptor _dstDesc; float const * _vertexSrc; float * _vertexDst; int const * _sizes; int const * _offsets, * _indices; float const * _weights; public: TBBStencilKernel(float const *src, BufferDescriptor srcDesc, float *dst, BufferDescriptor dstDesc, int const * sizes, int const * offsets, int const * indices, float const * weights) : _srcDesc(srcDesc), _dstDesc(dstDesc), _vertexSrc(src), _vertexDst(dst), _sizes(sizes), _offsets(offsets), _indices(indices), _weights(weights) { } TBBStencilKernel(TBBStencilKernel const & other) { _srcDesc = other._srcDesc; _dstDesc = other._dstDesc; _sizes = other._sizes; _offsets = other._offsets; _indices = other._indices; _weights = other._weights; _vertexSrc = other._vertexSrc; _vertexDst = other._vertexDst; } void operator() (tbb::blocked_range<int> const &r) const { #define USE_SIMD #ifdef USE_SIMD if (_srcDesc.length==4 and _srcDesc.stride==4 and _dstDesc.stride==4) { // SIMD fast path for aligned primvar data (4 floats) int offset = _offsets[r.begin()]; ComputeStencilKernel<4>(_vertexSrc, _vertexDst, _sizes, _indices+offset, _weights+offset, r.begin(), r.end()); } else if (_srcDesc.length==8 and _srcDesc.stride==4 and _dstDesc.stride==4) { // SIMD fast path for aligned primvar data (8 floats) int offset = _offsets[r.begin()]; ComputeStencilKernel<8>(_vertexSrc, _vertexDst, _sizes, _indices+offset, _weights+offset, r.begin(), r.end()); } else { #else { #endif int const * sizes = _sizes; int const * indices = _indices; float const * weights = _weights; if (r.begin()>0) { sizes += r.begin(); indices += _offsets[r.begin()]; weights += _offsets[r.begin()]; } // Slow path for non-aligned data float * result = (float*)alloca(_srcDesc.length * sizeof(float)); for (int i=r.begin(); i<r.end(); ++i, ++sizes) { clear(result, _dstDesc); for (int j=0; j<*sizes; ++j) { addWithWeight(result, _vertexSrc, *indices++, *weights++, _srcDesc); } copy(_vertexDst, i, result, _dstDesc); } } } }; void TbbEvalStencils(float const * src, BufferDescriptor const &srcDesc, float * dst, BufferDescriptor const &dstDesc, int const * sizes, int const * offsets, int const * indices, float const * weights, int start, int end) { if (start > 0) { sizes += start; indices += offsets[start]; weights += offsets[start]; } src += srcDesc.offset; dst += dstDesc.offset; TBBStencilKernel kernel(src, srcDesc, dst, dstDesc, sizes, offsets, indices, weights); tbb::blocked_range<int> range(start, end, grain_size); tbb::parallel_for(range, kernel); } void TbbEvalStencils(float const * src, BufferDescriptor const &srcDesc, float * dst, BufferDescriptor const &dstDesc, float * du, BufferDescriptor const &duDesc, float * dv, BufferDescriptor const &dvDesc, int const * sizes, int const * offsets, int const * indices, float const * weights, float const * duWeights, float const * dvWeights, int start, int end) { if (start > 0) { sizes += start; indices += offsets[start]; weights += offsets[start]; duWeights += offsets[start]; dvWeights += offsets[start]; } if (src) src += srcDesc.offset; if (dst) dst += dstDesc.offset; if (du) du += duDesc.offset; if (dv) dv += dvDesc.offset; // PERFORMANCE: need to combine 3 launches together if (dst) { TBBStencilKernel kernel(src, srcDesc, dst, dstDesc, sizes, offsets, indices, weights); tbb::blocked_range<int> range(start, end, grain_size); tbb::parallel_for(range, kernel); } if (du) { TBBStencilKernel kernel(src, srcDesc, du, duDesc, sizes, offsets, indices, duWeights); tbb::blocked_range<int> range(start, end, grain_size); tbb::parallel_for(range, kernel); } if (dv) { TBBStencilKernel kernel(src, srcDesc, dv, dvDesc, sizes, offsets, indices, dvWeights); tbb::blocked_range<int> range(start, end, grain_size); tbb::parallel_for(range, kernel); } } // --------------------------------------------------------------------------- template <typename T> struct BufferAdapter { BufferAdapter(T *p, int length, int stride) : _p(p), _length(length), _stride(stride) { } void Clear() { for (int i = 0; i < _length; ++i) _p[i] = 0; } void AddWithWeight(T const *src, float w) { if (_p) { for (int i = 0; i < _length; ++i) { _p[i] += src[i] * w; } } } const T *operator[] (int index) const { return _p + _stride * index; } BufferAdapter<T> & operator ++() { if (_p) { _p += _stride; } return *this; } T *_p; int _length; int _stride; }; class TbbEvalPatchesKernel { BufferDescriptor _srcDesc; BufferDescriptor _dstDesc; BufferDescriptor _dstDuDesc; BufferDescriptor _dstDvDesc; float const * _src; float * _dst; float * _dstDu; float * _dstDv; int _numPatchCoords; const PatchCoord *_patchCoords; const PatchArray *_patchArrayBuffer; const int *_patchIndexBuffer; const PatchParam *_patchParamBuffer; public: TbbEvalPatchesKernel(float const *src, BufferDescriptor srcDesc, float *dst, BufferDescriptor dstDesc, float *dstDu, BufferDescriptor dstDuDesc, float *dstDv, BufferDescriptor dstDvDesc, int numPatchCoords, const PatchCoord *patchCoords, const PatchArray *patchArrayBuffer, const int *patchIndexBuffer, const PatchParam *patchParamBuffer) : _srcDesc(srcDesc), _dstDesc(dstDesc), _dstDuDesc(dstDuDesc), _dstDvDesc(dstDvDesc), _src(src), _dst(dst), _dstDu(dstDu), _dstDv(dstDv), _numPatchCoords(numPatchCoords), _patchCoords(patchCoords), _patchArrayBuffer(patchArrayBuffer), _patchIndexBuffer(patchIndexBuffer), _patchParamBuffer(patchParamBuffer) { } void operator() (tbb::blocked_range<int> const &r) const { if (_dstDu == NULL && _dstDv == NULL) { compute(r); } else { computeWithDerivative(r); } } void compute(tbb::blocked_range<int> const &r) const { float wP[20], wDs[20], wDt[20]; BufferAdapter<const float> srcT(_src + _srcDesc.offset, _srcDesc.length, _srcDesc.stride); BufferAdapter<float> dstT(_dst + _dstDesc.offset + r.begin() * _dstDesc.stride, _dstDesc.length, _dstDesc.stride); BufferAdapter<float> dstDuT(_dstDu, _dstDuDesc.length, _dstDuDesc.stride); BufferAdapter<float> dstDvT(_dstDv, _dstDvDesc.length, _dstDvDesc.stride); for (int i = r.begin(); i < r.end(); ++i) { PatchCoord const &coord = _patchCoords[i]; PatchArray const &array = _patchArrayBuffer[coord.handle.arrayIndex]; int patchType = array.GetPatchType(); Far::PatchParam const & param = _patchParamBuffer[coord.handle.patchIndex]; int numControlVertices = 0; if (patchType == Far::PatchDescriptor::REGULAR) { Far::internal::GetBSplineWeights(param, coord.s, coord.t, wP, wDs, wDt); numControlVertices = 16; } else if (patchType == Far::PatchDescriptor::GREGORY_BASIS) { Far::internal::GetGregoryWeights(param, coord.s, coord.t, wP, wDs, wDt); numControlVertices = 20; } else if (patchType == Far::PatchDescriptor::QUADS) { Far::internal::GetBilinearWeights(param, coord.s, coord.t, wP, wDs, wDt); numControlVertices = 4; } else { assert(0); } const int *cvs = &_patchIndexBuffer[array.indexBase + coord.handle.vertIndex]; dstT.Clear(); for (int j = 0; j < numControlVertices; ++j) { dstT.AddWithWeight(srcT[cvs[j]], wP[j]); } ++dstT; } } void computeWithDerivative(tbb::blocked_range<int> const &r) const { float wP[20], wDs[20], wDt[20]; BufferAdapter<const float> srcT(_src + _srcDesc.offset, _srcDesc.length, _srcDesc.stride); BufferAdapter<float> dstT(_dst + _dstDesc.offset + r.begin() * _dstDesc.stride, _dstDesc.length, _dstDesc.stride); BufferAdapter<float> dstDuT(_dstDu + _dstDuDesc.offset + r.begin() * _dstDuDesc.stride, _dstDuDesc.length, _dstDuDesc.stride); BufferAdapter<float> dstDvT(_dstDv + _dstDvDesc.offset + r.begin() * _dstDvDesc.stride, _dstDvDesc.length, _dstDvDesc.stride); for (int i = r.begin(); i < r.end(); ++i) { PatchCoord const &coord = _patchCoords[i]; PatchArray const &array = _patchArrayBuffer[coord.handle.arrayIndex]; int patchType = array.GetPatchType(); Far::PatchParam const & param = _patchParamBuffer[coord.handle.patchIndex]; int numControlVertices = 0; if (patchType == Far::PatchDescriptor::REGULAR) { Far::internal::GetBSplineWeights(param, coord.s, coord.t, wP, wDs, wDt); numControlVertices = 16; } else if (patchType == Far::PatchDescriptor::GREGORY_BASIS) { Far::internal::GetGregoryWeights(param, coord.s, coord.t, wP, wDs, wDt); numControlVertices = 20; } else if (patchType == Far::PatchDescriptor::QUADS) { Far::internal::GetBilinearWeights(param, coord.s, coord.t, wP, wDs, wDt); numControlVertices = 4; } else { assert(0); } const int *cvs = &_patchIndexBuffer[array.indexBase + coord.handle.vertIndex]; dstT.Clear(); dstDuT.Clear(); dstDvT.Clear(); for (int j = 0; j < numControlVertices; ++j) { dstT.AddWithWeight(srcT[cvs[j]], wP[j]); dstDuT.AddWithWeight(srcT[cvs[j]], wDs[j]); dstDvT.AddWithWeight(srcT[cvs[j]], wDt[j]); } ++dstT; ++dstDuT; ++dstDvT; } } }; void TbbEvalPatches(float const *src, BufferDescriptor const &srcDesc, float *dst, BufferDescriptor const &dstDesc, float *dstDu, BufferDescriptor const &dstDuDesc, float *dstDv, BufferDescriptor const &dstDvDesc, int numPatchCoords, const PatchCoord *patchCoords, const PatchArray *patchArrayBuffer, const int *patchIndexBuffer, const PatchParam *patchParamBuffer) { TbbEvalPatchesKernel kernel(src, srcDesc, dst, dstDesc, dstDu, dstDuDesc, dstDv, dstDvDesc, numPatchCoords, patchCoords, patchArrayBuffer, patchIndexBuffer, patchParamBuffer); tbb::blocked_range<int> range(0, numPatchCoords, grain_size); tbb::parallel_for(range, kernel); } } // end namespace Osd } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv
/* Copyright 2019 FXCM Global Services, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use these files 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 "../stdafx.h" #include "Period.h" Bar::Bar(double open, double high, double low, double close) { mOpen = open; mHigh = high; mLow = low; mClose = close; } Bar::Bar(double open) { mOpen = mHigh = mLow = mClose = open; } Bar::~Bar() { } void Bar::setOpen(double open) { mOpen = open; } void Bar::setHigh(double high) { mHigh = high; } void Bar::setLow(double low) { mLow = low; } void Bar::setClose(double close) { mClose = close; } double Bar::getOpen() { return mOpen; } double Bar::getHigh() { return mHigh; } double Bar::getLow() { return mLow; } double Bar::getClose() { return mClose; } /////////////////////////////////////////////////////////////////////////////// Period::Period(DATE time, double bid, double ask, int volume) : mTime(time), mBid(new Bar(bid)), mAsk(new Bar(ask)), mVolume(volume) { } Period::Period(DATE time, double bidOpen, double bidHigh, double bidLow, double bidClose, double askOpen, double askHigh, double askLow, double askClose, int volume) : mTime(time), mBid(new Bar(bidOpen, bidHigh, bidLow, bidClose)), mAsk(new Bar(askOpen, askHigh, askLow, askClose)), mVolume(volume) { } Period:: ~Period() { } void Period::setVolume(int volume) { mVolume = volume; } DATE Period::getTime() { return mTime; } IBar *Period::getAsk() { mAsk->addRef(); return mAsk; } IBar *Period::getBid() { mBid->addRef(); return mBid; } int Period::getVolume() { return mVolume; }
#include <QLabel> #include <QMessageBox> #include <QHeaderView> #include <stdio.h> #include <sqlite3.h> #include <stdlib.h> #include <iostream> #include <swarmtv.h> #include "sourcetablecontrol.hpp" #include "sourceeditdialog.hpp" #include "singleton.h" #include "swarmtv.hpp" #include "simplecell.hpp" sourceTableControl::sourceTableControl(QWidget *parent) : QWidget(parent) { } void sourceTableControl::setTable(QTableWidget *table) { // Store the object we are going to control this->table = table; } int sourceTableControl::updateTable() { int rc=0; source_container *container; swarmTv *swarm = &Singleton<swarmTv>::Instance(); /* * Get the last downloaded data */ rc = rsstgetallsources(swarm->getHandle(), &container); if(rc != 0) { fprintf(stderr, "Could not retrieve last downloaded data.\n"); return -1; } /* * Fill the table */ fillTable(container); /* * Clean up */ rsstfreesourcecontainer(container); return 0; } void sourceTableControl::initHeaders() { // Make sure ui is set if(this->table == NULL){ std::cerr << "Set table before calling initHeaders " << __FILE__ << ":" << __LINE__ << std::endl; } // Name #if QT_VERSION >= 0x050000 table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); #else table->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); #endif // Parser #if QT_VERSION >= 0x050000 table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); #else table->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents); #endif // Meta type #if QT_VERSION >= 0x050000 table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); #else table->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents); #endif // URL #if QT_VERSION >= 0x050000 table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); #else table->horizontalHeader()->setResizeMode(3, QHeaderView::Stretch); #endif } void sourceTableControl::fillTable(source_container *container) { int count=0; simpleCell *slabel=NULL; QLabel *label=NULL; // Set Header size hints initHeaders(); // Call method to set table->setRowCount(container->nr); // Loop through the content, and set the names + last download to the screen for(count=0; count < container->nr; count++){ // Set filtername in first table row slabel = new simpleCell(container->source[count].name); slabel->setSimpleId(container->source[count].id); table->setCellWidget(count, 0, slabel); slabel = NULL; // Set filter type in second row. label = new QLabel(container->source[count].parser); table->setCellWidget(count, 1, label); label=NULL; // Set filter type in second row. label = new QLabel(container->source[count].metatype); table->setCellWidget(count, 2, label); label=NULL; // Set filter type in second row. label = new QLabel(container->source[count].url); table->setCellWidget(count, 3, label); label=NULL; } } void sourceTableControl::cellDoubleClicked(int row, int ) { int id=0; simpleCell *scell=NULL; sourceEditDialog *dialog=NULL; // Get cell cell pointer scell = static_cast<simpleCell*>( table->cellWidget(row, 0) ); id = scell->getSimpleId(); // Create object of source containing source dialog = new sourceEditDialog(id, this); dialog->setNameEnable(false); dialog->show(); // Print something. std::cout << "Row clicked : " << row << " ID : " << id << std::endl; } void sourceTableControl::addButtonClicked(void) { sourceEditDialog *dialog=NULL; // Create object of source containing source dialog = new sourceEditDialog(this); dialog->show(); } void sourceTableControl::delButtonClicked(void) { int row=0; int id=0; int rc=0; QString name; simpleCell *scell=NULL; swarmTv *swarm = &Singleton<swarmTv>::Instance(); // Get line that is currently selected QList<QTableWidgetSelectionRange> items = table->selectedRanges(); if(items.count() == 0) { QMessageBox::warning(this, tr("SwarmTv"), tr("Please select a source to delete."), QMessageBox::Ok); return; } row = items.first().topRow(); // Get cell cell pointer scell = static_cast<simpleCell*>( table->cellWidget(row, 0) ); id = scell->getSimpleId(); name = scell->text(); // Show dialog, asking for permission to delete int ret = QMessageBox::warning(this, tr("SwarmTv"), tr("Are you sure you want to delete this source?"), QMessageBox::Ok | QMessageBox::Cancel); switch(ret) { case QMessageBox::Ok: //@DEBUG #if QT_VERSION >= 0x050000 std::cout << "deleting source '" << name.toLatin1().data() << "." << std::endl; #else std::cout << "deleting source '" << name.toAscii().data() << "." << std::endl; #endif rc = rsstdelsourceid(swarm->getHandle(), id); if(rc != 0) { QMessageBox::warning(this, tr("SwarmTv"), tr("Deleting of source failed!"), QMessageBox::Ok); } break; case QMessageBox::Cancel: break; default: // When this happens, weird things are going on. exit(1); } // Delete the Filter when accepted // Update display this->updateTable(); }
/** * @file PyPlaceDB.cpp * @author Yibo Lin (DREAMPlace), Rachel Selina Rajarathnam (DREAMPlaceFPGA) * @date Mar 2021 * @brief Placement database for python */ #include <cmath> #include <unordered_set> #include <unordered_map> #include "PyPlaceDB.h" #include <boost/polygon/polygon.hpp> DREAMPLACE_BEGIN_NAMESPACE bool readBookshelf(PlaceDB& db, std::string const& auxPath) { // read bookshelf if (!auxPath.empty()) { std::string const& filename = auxPath; dreamplacePrint(kINFO, "reading %s\n", filename.c_str()); bool flag = BookshelfParser::read(db, filename); if (!flag) { dreamplacePrint(kERROR, "Bookshelf file parsing failed: %s\n", filename.c_str()); return false; } } else dreamplacePrint(kWARN, "no Bookshelf file specified\n"); return true; } void PyPlaceDB::set(PlaceDB const& db) { num_terminals = db.numFixed(); //IOs num_movable_nodes = db.numMovable(); // Movable cells num_physical_nodes = num_terminals + num_movable_nodes; node_count.append(db.numLUT()); node_count.append(db.numFF()); node_count.append(db.numDSP()); node_count.append(db.numRAM()); node_count.append(num_terminals); std::vector<double> fixed_node_size(num_terminals, 1.0); std::vector<PlaceDB::index_type> fixed_node2fence_region_map(num_terminals, 4); std::vector<PlaceDB::index_type> fixed_lut_type(num_terminals, 0); //Node Info node_names = pybind11::cast(std::move(db.movNodeNames())) + pybind11::cast(std::move(db.fixedNodeNames())); node_types = pybind11::cast(std::move(db.movNodeTypes())) + pybind11::cast(std::move(db.fixedNodeTypes())); node_size_x = pybind11::cast(std::move(db.movNodeXSizes())) + pybind11::cast(std::move(fixed_node_size)); node_size_y = pybind11::cast(std::move(db.movNodeYSizes())) + pybind11::cast(std::move(fixed_node_size)); node2fence_region_map = pybind11::cast(std::move(db.node2FenceRegionMap())) + pybind11::cast(std::move(fixed_node2fence_region_map)); node_x = pybind11::cast(std::move(db.movNodeXLocs())) + pybind11::cast(std::move(db.fixedNodeXLocs())); node_y = pybind11::cast(std::move(db.movNodeYLocs())) + pybind11::cast(std::move(db.fixedNodeYLocs())); node_z = pybind11::cast(std::move(db.movNodeZLocs())) + pybind11::cast(std::move(db.fixedNodeZLocs())); flop_indices = pybind11::cast(std::move(db.flopIndices())); lut_type = pybind11::cast(std::move(db.lutTypes())) + pybind11::cast(std::move(fixed_lut_type)); node2outpinIdx_map = pybind11::cast(std::move(db.node2OutPinId())); node2pincount_map = pybind11::cast(std::move(db.node2PinCount())); node2pin_map = pybind11::cast(std::move(db.node2PinMap())); node_name2id_map = pybind11::cast(std::move(db.nodeName2Index())); //movable_node_name2id_map = pybind11::cast(std::move(db.movNodeName2Index())); //fixed_node_name2id_map = pybind11::cast(std::move(db.fixedNodeName2Index())); flat_node2pin_map = pybind11::cast(std::move(db.flatNode2PinMap())); flat_node2pin_start_map = pybind11::cast(std::move(db.flatNode2PinStartMap())); net_names = pybind11::cast(std::move(db.netNames())); net2pincount_map = pybind11::cast(std::move(db.net2PinCount())); net2pin_map = pybind11::cast(std::move(db.net2PinMap())); flat_net2pin_map = pybind11::cast(std::move(db.flatNet2PinMap())); flat_net2pin_start_map = pybind11::cast(std::move(db.flatNet2PinStartMap())); net_name2id_map = pybind11::cast(std::move(db.netName2Index())); pin_names = pybind11::cast(std::move(db.pinNames())); pin_types = pybind11::cast(std::move(db.pinTypes())); pin_typeIds = pybind11::cast(std::move(db.pinTypeIds())); pin_offset_x = pybind11::cast(std::move(db.pinOffsetX())); pin_offset_y = pybind11::cast(std::move(db.pinOffsetY())); pin2net_map = pybind11::cast(std::move(db.pin2NetMap())); pin2node_map = pybind11::cast(std::move(db.pin2NodeMap())); pin2nodeType_map = pybind11::cast(std::move(db.pin2NodeTypeMap())); //num_terminals = db.numFixed(); //IOs //num_movable_nodes = db.numMovable(); // Movable cells //num_physical_nodes = num_terminals + num_movable_nodes; //node_count.append(db.numLUT()); //node_count.append(db.numFF()); //node_count.append(db.numDSP()); //node_count.append(db.numRAM()); //node_count.append(db.numFixed()); //// general add a node //auto addNode = [&](Node const& node) { // // this id may be different from node id // int id = node_names.size(); // node_name2id_map[pybind11::str(node.name())] = id; // node_names.append(pybind11::str(node.name())); // node_types.append(pybind11::str(node.typeName())); // // map new node to original index // //node2orig_node_map.append(node.id()); // // record original node to new node mapping // PlaceDB::index_type node_id = (node.id() < db.numMovableNodes()) ? node.id() : db.numMovableNodes() + node.id()-100000000; // float sqrtSmall(std::sqrt(0.0625)), sqrtLarge(std::sqrt(0.125)); // switch(node.typeId()) // { // case 0: // case 1: // case 2: // { // node_size_x.append(sqrtSmall); // node_size_y.append(sqrtSmall); // lut_type.append(node.typeId()); // //fixedNodes.append(0); // //lut_indices.append(id); // //flop_lut_indices.append(id); // node2fence_region_map.append(0); // break; // } // case 3: // case 4: // case 5: // { // node_size_x.append(sqrtLarge); // node_size_y.append(sqrtLarge); // lut_type.append(node.typeId()); // //fixedNodes.append(0); // //lut_indices.append(id); // //flop_lut_indices.append(id); // node2fence_region_map.append(0); // break; // } // case 6: //FF // { // node_size_x.append(sqrtSmall); // node_size_y.append(sqrtSmall); // lut_type.append(0); // //fixedNodes.append(0); // flop_indices.append(id); // //flop_lut_indices.append(id); // node2fence_region_map.append(1); // break; // } // case 7: //DSP // { // node_size_x.append(1.0); // node_size_y.append(2.5); // lut_type.append(0); // //fixedNodes.append(0); // //dsp_indices.append(id); // //dsp_ram_indices.append(id); // node2fence_region_map.append(2); // break; // } // case 8: //RAM // { // node_size_x.append(1.0); // node_size_y.append(5.0); // lut_type.append(0); // //fixedNodes.append(0); // //ram_indices.append(id); // //dsp_ram_indices.append(id); // node2fence_region_map.append(3); // break; // } // default: //IO // { // node_size_x.append(1.0); // node_size_y.append(1.0); // lut_type.append(0); // //fixedNodes.append(1); // node2fence_region_map.append(4); // break; // } // } //}; //int count = 0; //for (unsigned int i = 0; i < db.numMovableNodes(); ++i) //{ // Node const& node = db.node(i); // addNode(node); // node_x.append(0.0); // node_y.append(0.0); // node_z.append(0); // //update node2pin_map // LibCell const& lCell = db.libCell(node.macroId()); // pybind11::list pins; // PlaceDB::index_type outPinId; // for (auto pin_id : node.pinIdArray()) // { // pins.append(pin_id); // flat_node2pin_map.append(pin_id); // if (node.typeId() < 7) //Check for FF/LUT // { // if (lCell.pinType(db.pin(pin_id).name()) == 0) //Output Pin // { // outPinId = pin_id; // } // } else // { // outPinId = 0; // } // } // node2pin_map.append(pins); // node2pincount_map.append(node.numPins()); // node2outpinIdx_map.append(outPinId); // flat_node2pin_start_map.append(count); // count += node.numPins(); //} //std::cout << "Done with movable nodes" << std::endl; //for (unsigned int i = 0; i < db.numFixedNodes(); ++i) //{ // Node const& node = db.fixedNode(i); // addNode(node); // node_x.append(node.x()); // node_y.append(node.y()); // node_z.append(node.z()); // //update node2pin_map // pybind11::list pins; // for (auto pin_id : node.pinIdArray()) // { // pins.append(pin_id); // flat_node2pin_map.append(pin_id); // } // node2pin_map.append(pins); // node2pincount_map.append(node.numPins()); // node2outpinIdx_map.append(0); // flat_node2pin_start_map.append(count); // count += node.numPins(); //} //flat_node2pin_start_map.append(count); //std::cout << "Done with fixed nodes" << std::endl; //num_nodes = db.numNodes(); //std::cout << "There are " << std::to_string(db.numNodes()) << " nodes, " << std::to_string(db.numPins()) // << " pins and " << std::to_string(db.numNets()) << " nets and " << std::to_string(db.numMacro()) // << " macros in the design" << std::endl; ////std::unordered_map<unsigned int, std::tuple<unsigned int, unsigned int, unsigned int> > ctrlSetInfo; //pinId -> ck net Id, sr net Id, ce net Id //// construct node2pin_map and flat_node2pin_map //for (unsigned int i = 0; i < db.numPins(); ++i) //{ // Pin const& pin = db.pin(i); // Node const& node = db.getNode(pin); // //std::cout << "Node name: " << node.name() << std::endl; // LibCell const& lCell = db.libCell(node.macroId()); // //std::cout << "Lib cell name: " << lCell.name() << std::endl; // pin_names.append(pybind11::str(pin.name())); // //std::cout << "Pin name: " << pin.name() << std::endl; // //std::cout << "Pin type Id: " << lCell.pinType(pin.name()) << std::endl; // std::string pType(""); // PlaceDB::index_type pinTypeId(lCell.pinType(pin.name())); // switch(lCell.pinType(pin.name())) // { // case 2: //CLK // { // pType = "CK"; // break; // } // case 3: //CTRL // { // if (pin.name().find("CE")) // { // pType = "CE"; // } else // { // pType = "SR"; // pinTypeId = 4; // } // break; // } // default: // { // break; // } // } // pin_types.append(pybind11::str(pType)); // pin_typeIds.append(pinTypeId); // PlaceDB::index_type node_id = (node.id() < db.numMovableNodes()) ? node.id() : db.numMovableNodes() + node.id()-100000000; // //std::cout << "node id is " << node.id() << " which maps to " << node_id << std::endl; // float pOffsetX(0.5 * node_size_x[node_id].cast<float>()), pOffsetY(0.5 * node_size_y[node_id].cast<float>()); // pin_offset_x.append(pOffsetX); // pin_offset_y.append(pOffsetY); // pin2nodeType_map.append(node2fence_region_map[node_id].cast<PlaceDB::index_type>()); // //if (node2fence_region_map[node_id].cast<PlaceDB::index_type>() < 2 || node2fence_region_map[node_id].cast<PlaceDB::index_type>() > 3) // //{ // // lg_pin_offset_x.append(0.0); // // lg_pin_offset_y.append(0.0); // //} else // //{ // // lg_pin_offset_x.append(pOffsetX); // // lg_pin_offset_y.append(pOffsetY); // //} // // pin2node_map.append(node_id); // pin2net_map.append(pin.netId()); //} //count = 0; //for (unsigned int i = 0, ie = db.numNets(); i < ie; ++i) //{ // Net const& net = db.net(i); // net_names.append(pybind11::str(net.name())); // //net_weights.append(net.weight()); // net_name2id_map[pybind11::str(net.name())] = net.id(); // pybind11::list pins; // for (std::vector<Net::index_type>::const_iterator it = net.pinIdArray().begin(), ite = net.pinIdArray().end(); it != ite; ++it) // { // pins.append(*it); // flat_net2pin_map.append(*it); // } // net2pin_map.append(pins); // net2pincount_map.append(net.numPins()); // flat_net2pin_start_map.append(count); // count += net.numPins(); //} //flat_net2pin_start_map.append(count); //CtrlSets std::unordered_map<PlaceDB::index_type, PlaceDB::index_type> ceMapping; std::unordered_map<PlaceDB::index_type, std::unordered_map<PlaceDB::index_type, PlaceDB::index_type> > cksrMapping; PlaceDB::index_type numCKSR(0), numCE(0); for (unsigned int idx = 0; idx < flop_indices.size(); ++idx) { PlaceDB::index_type fIdx = flop_indices[idx].cast<PlaceDB::index_type>(); //Node const& node = db.node(fIdx); int ck(-1), sr(-1), ce(-1), cksrId(-1), ceId(-1); //for (auto pin_id : node.pinIdArray()) for (unsigned int pIdx = 0; pIdx < db.node2PinCnt(fIdx); ++pIdx) { PlaceDB::index_type pin_id = db.node2PinIdx(fIdx, pIdx); switch(pin_typeIds[pin_id].cast<PlaceDB::index_type>()) { case 2: { ck = pin2net_map[pin_id].cast<PlaceDB::index_type>(); break; } case 3: { ce = pin2net_map[pin_id].cast<PlaceDB::index_type>(); break; } case 4: { sr = pin2net_map[pin_id].cast<PlaceDB::index_type>(); break; } default: { break; } } } auto ckIt = cksrMapping.find(ck); if (ckIt == cksrMapping.end()) { cksrId = numCKSR; cksrMapping[ck][sr] = numCKSR++; } else { auto &srMap = ckIt->second; auto srIt = srMap.find(sr); if (srIt == srMap.end()) { cksrId = numCKSR; srMap[sr] = numCKSR++; } else { cksrId = srIt->second; } } auto ceIt = ceMapping.find(ce); if (ceIt == ceMapping.end()) { ceId = numCE; ceMapping[ce] = numCE++; } else { ceId = ceIt->second; } ctrlSets.append(std::make_tuple(fIdx, cksrId, ceId)); flat_ctrlSets.append(fIdx); flat_ctrlSets.append(cksrId); flat_ctrlSets.append(ceId); } //SiteInfo //pybind11::list region0, region2, region3, region4; std::vector<std::unordered_set<PlaceDB::index_type> > updCols; std::unordered_set<PlaceDB::index_type> colSet0; std::unordered_set<PlaceDB::index_type> colSet1; std::unordered_set<PlaceDB::index_type> colSet2; std::unordered_set<PlaceDB::index_type> colSet3; std::unordered_set<PlaceDB::index_type> colSet4; for (unsigned int i = 0, ie = db.siteRows(); i < ie; ++i) { pybind11::list rowVals, lg_rowXY; for (unsigned int j = 0, je = db.siteCols(); j < je; ++j) { pybind11::list siteXY, lg_Site; if (db.siteVal(i,j) == 1) { lg_Site.append(i+0.5); lg_Site.append(j+0.5); } else { lg_Site.append(i); lg_Site.append(j); } lg_rowXY.append(lg_Site); //std::cout << "Site value at (" << i << ", " << j << ") is " << db.siteVal(i,j) << std::endl; switch(db.siteVal(i,j)) { case 1: //FF/LUT { colSet0.insert(i); colSet1.insert(i); break; } case 2: //DSP { siteXY.append(i); siteXY.append(std::round(j/2.5)*2.5); dspSiteXYs.append(siteXY); colSet2.insert(i); break; } case 3: //RAM { siteXY.append(i); siteXY.append(std::round(j/5.0)*5.0); ramSiteXYs.append(siteXY); colSet3.insert(i); break; } case 4: //IO { colSet4.insert((PlaceDB::index_type)i); break; } default: //Empty { break; } } rowVals.append(db.siteVal(i,j)); } site_type_map.append(rowVals); lg_siteXYs.append(lg_rowXY); } updCols.emplace_back(colSet0); updCols.emplace_back(colSet1); updCols.emplace_back(colSet2); updCols.emplace_back(colSet3); updCols.emplace_back(colSet4); unsigned int flat_len = 0; flat_region_boxes_start.append(flat_len); for (unsigned int rgn = 0; rgn < 5; ++rgn) { for (unsigned int cEl = 0; cEl < updCols[rgn].size(); ++cEl) { auto elm = updCols[rgn].begin(); std::advance(elm, cEl); pybind11::list flat_region; flat_region.append(*elm); flat_region.append(0); flat_region.append(*elm + 1); flat_region.append(db.height()); flat_region_boxes.append(flat_region); flat_len += 1; } flat_region_boxes_start.append(flat_len); } xl = db.xl(); yl = db.yl(); xh = db.xh(); yh = db.yh(); row_height = db.height(); site_width = db.width(); num_sites_x = db.siteRows(); num_sites_y = db.siteCols(); // routing information initialized num_routing_grids_x = db.width(); num_routing_grids_y = db.height(); routing_grid_xl = xl; routing_grid_yl = yl; routing_grid_xh = xh; routing_grid_yh = yh; } DREAMPLACE_END_NAMESPACE
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBigPicture.h" #include "SkCanvasPriv.h" #include "SkPatchUtils.h" #include "SkPicture.h" #include "SkPictureUtils.h" #include "SkRecorder.h" #include "SkSurface.h" //#define WRAP_BITMAP_AS_IMAGE SkDrawableList::~SkDrawableList() { fArray.unrefAll(); } SkBigPicture::SnapshotArray* SkDrawableList::newDrawableSnapshot() { const int count = fArray.count(); if (0 == count) { return nullptr; } SkAutoTMalloc<const SkPicture*> pics(count); for (int i = 0; i < count; ++i) { pics[i] = fArray[i]->newPictureSnapshot(); } return new SkBigPicture::SnapshotArray(pics.release(), count); } void SkDrawableList::append(SkDrawable* drawable) { *fArray.append() = SkRef(drawable); } /////////////////////////////////////////////////////////////////////////////////////////////// SkRecorder::SkRecorder(SkRecord* record, int width, int height, SkMiniRecorder* mr) : SkCanvas(SkIRect::MakeWH(width, height), SkCanvas::kConservativeRasterClip_InitFlag) , fDrawPictureMode(Record_DrawPictureMode) , fApproxBytesUsedBySubPictures(0) , fRecord(record) , fMiniRecorder(mr) {} SkRecorder::SkRecorder(SkRecord* record, const SkRect& bounds, SkMiniRecorder* mr) : SkCanvas(bounds.roundOut(), SkCanvas::kConservativeRasterClip_InitFlag) , fDrawPictureMode(Record_DrawPictureMode) , fApproxBytesUsedBySubPictures(0) , fRecord(record) , fMiniRecorder(mr) {} void SkRecorder::reset(SkRecord* record, const SkRect& bounds, DrawPictureMode dpm, SkMiniRecorder* mr) { this->forgetRecord(); fDrawPictureMode = dpm; fRecord = record; this->resetForNextPicture(bounds.roundOut()); fMiniRecorder = mr; } void SkRecorder::forgetRecord() { fDrawableList.reset(nullptr); fApproxBytesUsedBySubPictures = 0; fRecord = nullptr; } // To make appending to fRecord a little less verbose. #define APPEND(T, ...) \ if (fMiniRecorder) { \ this->flushMiniRecorder(); \ } \ new (fRecord->append<SkRecords::T>()) SkRecords::T{__VA_ARGS__} #define TRY_MINIRECORDER(method, ...) \ if (fMiniRecorder && fMiniRecorder->method(__VA_ARGS__)) { return; } // For methods which must call back into SkCanvas. #define INHERITED(method, ...) this->SkCanvas::method(__VA_ARGS__) // Use copy() only for optional arguments, to be copied if present or skipped if not. // (For most types we just pass by value and let copy constructors do their thing.) template <typename T> T* SkRecorder::copy(const T* src) { if (nullptr == src) { return nullptr; } return new (fRecord->alloc<T>()) T(*src); } // This copy() is for arrays. // It will work with POD or non-POD, though currently we only use it for POD. template <typename T> T* SkRecorder::copy(const T src[], size_t count) { if (nullptr == src) { return nullptr; } T* dst = fRecord->alloc<T>(count); for (size_t i = 0; i < count; i++) { new (dst + i) T(src[i]); } return dst; } // Specialization for copying strings, using memcpy. // This measured around 2x faster for copying code points, // but I found no corresponding speedup for other arrays. template <> char* SkRecorder::copy(const char src[], size_t count) { if (nullptr == src) { return nullptr; } char* dst = fRecord->alloc<char>(count); memcpy(dst, src, count); return dst; } // As above, assuming and copying a terminating \0. template <> char* SkRecorder::copy(const char* src) { return this->copy(src, strlen(src)+1); } void SkRecorder::flushMiniRecorder() { if (fMiniRecorder) { SkMiniRecorder* mr = fMiniRecorder; fMiniRecorder = nullptr; // Needs to happen before flushAndReset() or we recurse forever. mr->flushAndReset(this); } } void SkRecorder::onDrawPaint(const SkPaint& paint) { APPEND(DrawPaint, paint); } void SkRecorder::onDrawPoints(PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint) { APPEND(DrawPoints, paint, mode, SkToUInt(count), this->copy(pts, count)); } void SkRecorder::onDrawRect(const SkRect& rect, const SkPaint& paint) { TRY_MINIRECORDER(drawRect, rect, paint); APPEND(DrawRect, paint, rect); } void SkRecorder::onDrawOval(const SkRect& oval, const SkPaint& paint) { APPEND(DrawOval, paint, oval); } void SkRecorder::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) { APPEND(DrawRRect, paint, rrect); } void SkRecorder::onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) { APPEND(DrawDRRect, paint, outer, inner); } void SkRecorder::onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) { if (fDrawPictureMode == Record_DrawPictureMode) { if (!fDrawableList) { fDrawableList.reset(new SkDrawableList); } fDrawableList->append(drawable); APPEND(DrawDrawable, this->copy(matrix), drawable->getBounds(), fDrawableList->count() - 1); } else { SkASSERT(fDrawPictureMode == Playback_DrawPictureMode); drawable->draw(this, matrix); } } void SkRecorder::onDrawPath(const SkPath& path, const SkPaint& paint) { TRY_MINIRECORDER(drawPath, path, paint); APPEND(DrawPath, paint, path); } void SkRecorder::onDrawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top, const SkPaint* paint) { #ifdef WRAP_BITMAP_AS_IMAGE SkAutoTUnref<SkImage> image(SkImage::NewFromBitmap(bitmap)); if (image) { this->onDrawImage(image, left, top, paint); } #else APPEND(DrawBitmap, this->copy(paint), bitmap, left, top); #endif } void SkRecorder::onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst, const SkPaint* paint, SrcRectConstraint constraint) { #ifdef WRAP_BITMAP_AS_IMAGE // TODO: need a way to support the flags for images... SkAutoTUnref<SkImage> image(SkImage::NewFromBitmap(bitmap)); if (image) { this->onDrawImageRect(image, src, dst, paint); } #else TRY_MINIRECORDER(drawBitmapRect, bitmap, src, dst, paint, constraint); if (kFast_SrcRectConstraint == constraint) { APPEND(DrawBitmapRectFast, this->copy(paint), bitmap, this->copy(src), dst); return; } SkASSERT(kStrict_SrcRectConstraint == constraint); APPEND(DrawBitmapRect, this->copy(paint), bitmap, this->copy(src), dst); #endif } void SkRecorder::onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, const SkRect& dst, const SkPaint* paint) { #ifdef WRAP_BITMAP_AS_IMAGE SkAutoTUnref<SkImage> image(SkImage::NewFromBitmap(bitmap)); if (image) { this->onDrawImageNine(image, center, dst, paint); } #else APPEND(DrawBitmapNine, this->copy(paint), bitmap, center, dst); #endif } void SkRecorder::onDrawImage(const SkImage* image, SkScalar left, SkScalar top, const SkPaint* paint) { APPEND(DrawImage, this->copy(paint), image, left, top); } void SkRecorder::onDrawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst, const SkPaint* paint, SrcRectConstraint constraint) { APPEND(DrawImageRect, this->copy(paint), image, this->copy(src), dst, constraint); } void SkRecorder::onDrawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst, const SkPaint* paint) { APPEND(DrawImageNine, this->copy(paint), image, center, dst); } void SkRecorder::onDrawText(const void* text, size_t byteLength, SkScalar x, SkScalar y, const SkPaint& paint) { APPEND(DrawText, paint, this->copy((const char*)text, byteLength), byteLength, x, y); } void SkRecorder::onDrawPosText(const void* text, size_t byteLength, const SkPoint pos[], const SkPaint& paint) { const int points = paint.countText(text, byteLength); APPEND(DrawPosText, paint, this->copy((const char*)text, byteLength), byteLength, this->copy(pos, points)); } void SkRecorder::onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY, const SkPaint& paint) { const int points = paint.countText(text, byteLength); APPEND(DrawPosTextH, paint, this->copy((const char*)text, byteLength), SkToUInt(byteLength), constY, this->copy(xpos, points)); } void SkRecorder::onDrawTextOnPath(const void* text, size_t byteLength, const SkPath& path, const SkMatrix* matrix, const SkPaint& paint) { APPEND(DrawTextOnPath, paint, this->copy((const char*)text, byteLength), byteLength, path, matrix ? *matrix : SkMatrix::I()); } void SkRecorder::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y, const SkPaint& paint) { TRY_MINIRECORDER(drawTextBlob, blob, x, y, paint); APPEND(DrawTextBlob, paint, blob, x, y); } void SkRecorder::onDrawPicture(const SkPicture* pic, const SkMatrix* matrix, const SkPaint* paint) { if (fDrawPictureMode == Record_DrawPictureMode) { fApproxBytesUsedBySubPictures += SkPictureUtils::ApproximateBytesUsed(pic); APPEND(DrawPicture, this->copy(paint), pic, matrix ? *matrix : SkMatrix::I()); } else { SkASSERT(fDrawPictureMode == Playback_DrawPictureMode); SkAutoCanvasMatrixPaint acmp(this, matrix, paint, pic->cullRect()); pic->playback(this); } } void SkRecorder::onDrawVertices(VertexMode vmode, int vertexCount, const SkPoint vertices[], const SkPoint texs[], const SkColor colors[], SkXfermode* xmode, const uint16_t indices[], int indexCount, const SkPaint& paint) { APPEND(DrawVertices, paint, vmode, vertexCount, this->copy(vertices, vertexCount), texs ? this->copy(texs, vertexCount) : nullptr, colors ? this->copy(colors, vertexCount) : nullptr, xmode, this->copy(indices, indexCount), indexCount); } void SkRecorder::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint) { APPEND(DrawPatch, paint, cubics ? this->copy(cubics, SkPatchUtils::kNumCtrlPts) : nullptr, colors ? this->copy(colors, SkPatchUtils::kNumCorners) : nullptr, texCoords ? this->copy(texCoords, SkPatchUtils::kNumCorners) : nullptr, xmode); } void SkRecorder::onDrawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[], const SkColor colors[], int count, SkXfermode::Mode mode, const SkRect* cull, const SkPaint* paint) { APPEND(DrawAtlas, this->copy(paint), atlas, this->copy(xform, count), this->copy(tex, count), this->copy(colors, count), count, mode, this->copy(cull)); } void SkRecorder::onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) { APPEND(DrawAnnotation, rect, SkString(key), value); } void SkRecorder::willSave() { APPEND(Save); } SkCanvas::SaveLayerStrategy SkRecorder::getSaveLayerStrategy(const SaveLayerRec& rec) { APPEND(SaveLayer, this->copy(rec.fBounds), this->copy(rec.fPaint), rec.fBackdrop, rec.fSaveLayerFlags); return SkCanvas::kNoLayer_SaveLayerStrategy; } void SkRecorder::didRestore() { APPEND(Restore, this->devBounds(), this->getTotalMatrix()); } void SkRecorder::didConcat(const SkMatrix& matrix) { APPEND(Concat, matrix); } void SkRecorder::didSetMatrix(const SkMatrix& matrix) { APPEND(SetMatrix, matrix); } void SkRecorder::onClipRect(const SkRect& rect, SkRegion::Op op, ClipEdgeStyle edgeStyle) { INHERITED(onClipRect, rect, op, edgeStyle); SkRecords::RegionOpAndAA opAA(op, kSoft_ClipEdgeStyle == edgeStyle); APPEND(ClipRect, this->devBounds(), rect, opAA); } void SkRecorder::onClipRRect(const SkRRect& rrect, SkRegion::Op op, ClipEdgeStyle edgeStyle) { INHERITED(onClipRRect, rrect, op, edgeStyle); SkRecords::RegionOpAndAA opAA(op, kSoft_ClipEdgeStyle == edgeStyle); APPEND(ClipRRect, this->devBounds(), rrect, opAA); } void SkRecorder::onClipPath(const SkPath& path, SkRegion::Op op, ClipEdgeStyle edgeStyle) { INHERITED(onClipPath, path, op, edgeStyle); SkRecords::RegionOpAndAA opAA(op, kSoft_ClipEdgeStyle == edgeStyle); APPEND(ClipPath, this->devBounds(), path, opAA); } void SkRecorder::onClipRegion(const SkRegion& deviceRgn, SkRegion::Op op) { INHERITED(onClipRegion, deviceRgn, op); APPEND(ClipRegion, this->devBounds(), deviceRgn, op); } sk_sp<SkSurface> SkRecorder::onNewSurface(const SkImageInfo&, const SkSurfaceProps&) { return nullptr; }
#include <iostream> //cin cout #include <algorithm> //min using namespace std; int main() { // your code goes here int totalNumberOfStudents; cin>>totalNumberOfStudents; int students[totalNumberOfStudents+1]; int programmer=0,maths=0,sports=0; for(int i=1;i<=totalNumberOfStudents;i++){ cin>>students[i]; if(students[i]==1) programmer++; if(students[i]==2) maths++; if(students[i]==3) sports++; } int maxTeams=min(min(programmer,maths),sports); cout<<maxTeams<<endl; /////////////////////////////////////////////// int programmerIndexArray[programmer]; //1 int mathsIndexArray[maths]; //2 int sportsIndexArray[sports]; //3 int p=0,m=0,s=0; for(int i=1;i<=totalNumberOfStudents;i++){ //store index in respective arrays if(students[i]==1) {programmerIndexArray[p]=i; p++; }else if(students[i]==2) {mathsIndexArray[m]=i; m++; }else if(students[i]==3) {sportsIndexArray[s]=i; s++;} } /*for(int i=0;i<programmer;i++) cout<<programmerIndexArray[i]; cout<<endl; for(int i=0;i<maths;i++) cout<<mathsIndexArray[i]; cout<<endl; for(int i=0;i<sports;i++) cout<<sportsIndexArray[i]; cout<<endl;*/ int programmerStartIndex= programmer - maxTeams; int mathsStartIndex= maths - maxTeams; int sportsStartIndex= sports - maxTeams; for(int i=0;i<maxTeams;i++){ cout<<programmerIndexArray[programmerStartIndex]<<" "<<mathsIndexArray[mathsStartIndex]<<" " <<sportsIndexArray[sportsStartIndex]<<endl; programmerStartIndex++; mathsStartIndex++; sportsStartIndex++; } return 0; }
#include "RNG.h" int nev::RNG::getRandomVectorIndex(int vecSize) { return rand() % vecSize; } int nev::RNG::getRandomIntBetween(int from, int to) { if (from >= to) return from; int buf = (to - from) + 1; int randomNumber = (rand() % buf) + from; return randomNumber; } float nev::RNG::getRandomFloatBetween(int from, int to) { if (from >= to) return from; float random = (float)rand() / (float)RAND_MAX; float buf = (float)(to - from); float r = random * buf; return from + r; } float nev::RNG::getRandomFloatBetween(float from, float to) { if (from >= to) return from; float random = (float)rand() / (float)RAND_MAX; float buf = (float)(to - from); float r = random * buf; return from + r; } float nev::RNG::getRandomFloatBetween0and1() { return (float)rand() / (float)RAND_MAX; } double nev::RNG::getRandomDoubleBetween(double from, double to) { if (from >= to) return from; double random = (double)rand() / (double)RAND_MAX; double buf = (double)(to - from); double r = random * buf; return (double)from + r; }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "array_attribute_combiner_dfw.h" #include "attribute_field_writer.h" #include "docsum_field_writer_state.h" #include "struct_fields_resolver.h" #include <vespa/searchcommon/attribute/iattributecontext.h> #include <vespa/searchcommon/attribute/iattributevector.h> #include <vespa/searchlib/common/matching_elements.h> #include <vespa/searchlib/common/matching_elements_fields.h> #include <vespa/vespalib/data/slime/cursor.h> #include <vespa/vespalib/util/stash.h> #include <algorithm> #include <cassert> using search::attribute::IAttributeContext; using search::attribute::IAttributeVector; using vespalib::slime::Cursor; namespace search::docsummary { namespace { class ArrayAttributeFieldWriterState : public DocsumFieldWriterState { // AttributeFieldWriter instances are owned by stash passed to constructor std::vector<AttributeFieldWriter*> _writers; const vespalib::string& _field_name; const MatchingElements* const _matching_elements; public: ArrayAttributeFieldWriterState(const std::vector<vespalib::string> &fieldNames, const std::vector<vespalib::string> &attributeNames, IAttributeContext &context, vespalib::Stash& stash, const vespalib::string &field_name, const MatchingElements* matching_elements, bool is_map_of_scalar); ~ArrayAttributeFieldWriterState() override; void insert_element(uint32_t element_index, Cursor &array); void insertField(uint32_t docId, vespalib::slime::Inserter &target) override; }; ArrayAttributeFieldWriterState::ArrayAttributeFieldWriterState(const std::vector<vespalib::string> &fieldNames, const std::vector<vespalib::string> &attributeNames, IAttributeContext &context, vespalib::Stash& stash, const vespalib::string &field_name, const MatchingElements *matching_elements, bool is_map_of_scalar) : DocsumFieldWriterState(), _writers(), _field_name(field_name), _matching_elements(matching_elements) { size_t fields = fieldNames.size(); _writers.reserve(fields); for (uint32_t field = 0; field < fields; ++field) { const IAttributeVector *attr = context.getAttribute(attributeNames[field]); if (attr != nullptr) { _writers.emplace_back(&AttributeFieldWriter::create(fieldNames[field], *attr, stash, is_map_of_scalar)); } } } ArrayAttributeFieldWriterState::~ArrayAttributeFieldWriterState() = default; void ArrayAttributeFieldWriterState::insert_element(uint32_t element_index, Cursor &array) { Cursor &obj = array.addObject(); for (auto &writer : _writers) { writer->print(element_index, obj); } } void ArrayAttributeFieldWriterState::insertField(uint32_t docId, vespalib::slime::Inserter &target) { uint32_t elems = 0; for (auto &writer : _writers) { elems = std::max(elems, writer->fetch(docId)); } if (elems == 0) { return; } Cursor &arr = target.insertArray(); if (_matching_elements != nullptr) { auto &elements = _matching_elements->get_matching_elements(docId, _field_name); auto elements_iterator = elements.cbegin(); for (uint32_t idx = 0; idx < elems && elements_iterator != elements.cend(); ++idx) { assert(*elements_iterator >= idx); if (*elements_iterator == idx) { insert_element(idx, arr); ++elements_iterator; } } } else { for (uint32_t idx = 0; idx < elems; ++idx) { insert_element(idx, arr); } } } } ArrayAttributeCombinerDFW::ArrayAttributeCombinerDFW(const vespalib::string &fieldName, const StructFieldsResolver& fields_resolver, bool filter_elements, std::shared_ptr<MatchingElementsFields> matching_elems_fields) : AttributeCombinerDFW(fieldName, filter_elements, std::move(matching_elems_fields)), _fields(fields_resolver.get_array_fields()), _attributeNames(fields_resolver.get_array_attributes()), _is_map_of_scalar(fields_resolver.is_map_of_scalar()) { if (filter_elements && _matching_elems_fields && !_matching_elems_fields->has_field(fieldName)) { fields_resolver.apply_to(*_matching_elems_fields); } } ArrayAttributeCombinerDFW::~ArrayAttributeCombinerDFW() = default; DocsumFieldWriterState* ArrayAttributeCombinerDFW::allocFieldWriterState(IAttributeContext &context, vespalib::Stash &stash, const MatchingElements* matching_elements) { return &stash.create<ArrayAttributeFieldWriterState>(_fields, _attributeNames, context, stash, _fieldName, matching_elements, _is_map_of_scalar); } }
// Copyright(c) 2017-2019, Intel Corporation // // 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 Intel Corporation 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. #include <chrono> #include <thread> #include <iostream> #include <iomanip> #include <sstream> #include "nlb7.h" #include "fpga_app/fpga_common.h" #include "option.h" #include "nlb.h" #include "nlb_stats.h" #include "safe_string/safe_string.h" #include "diag_utils.h" #define USE_UMSG 0 using namespace opae::fpga::types; using namespace std::chrono; using namespace intel::utils; using namespace intel::fpga::nlb; namespace intel { namespace fpga { namespace diag { static uint32_t max_cl = 65535; nlb7::nlb7() : name_("nlb7") , config_("nlb7.json") , target_("fpga") , afu_id_("7BAF4DEA-A57C-E91E-168A-455D9BDA88A3") , dsm_size_(MB(2)) , step_(1) , begin_(1) , end_(1) , frequency_(DEFAULT_FREQ) , notice_(nlb7_notice::poll) , dsm_timeout_(FPGA_DSM_TIMEOUT) , suppress_headers_(false) , csv_format_(false) , suppress_stats_(false) , cachelines_(0) { options_.add_option<bool>("help", 'h', option::no_argument, "Show help", false); options_.add_option<bool>("version", 'v', option::no_argument, "Show version", false); options_.add_option<std::string>("config", 'c', option::with_argument, "Path to test config file", config_); options_.add_option<std::string>("target", 't', option::with_argument, "one of {fpga, ase}", target_); options_.add_option<uint32_t>("begin", 'b', option::with_argument, "where 1 <= <value> <= 65535", begin_); options_.add_option<uint32_t>("end", 'e', option::with_argument, "where 1 <= <value> <= 65535", end_); options_.add_option<std::string>("cache-policy", 'p', option::with_argument, "one of {wrline-I, wrline-M, wrpush-I}", "wrline-M"); options_.add_option<std::string>("cache-hint", 'i', option::with_argument, "one of {rdline-I, rdline-S}", "rdline-I"); options_.add_option<std::string>("read-vc", 'r', option::with_argument, "one of {auto, vl0, vh0, vh1, random}", "auto"); options_.add_option<std::string>("write-vc", 'w', option::with_argument, "one of {auto, vl0, vh0, vh1, random}", "auto"); options_.add_option<std::string>("wrfence-vc", 'f', option::with_argument, "one of {auto, vl0, vh0, vh1}", "auto"); options_.add_option<std::string>("notice", 'N', option::with_argument, "one of {poll, csr-write, umsg-data, umsg-hint}", "poll"); options_.add_option<uint64_t>("dsm-timeout-usec", option::with_argument, "Timeout for test completion", dsm_timeout_.count()); options_.add_option<uint8_t>("bus", 'B', option::with_argument, "Bus number of PCIe device"); options_.add_option<uint8_t>("device", 'D', option::with_argument, "Device number of PCIe device"); options_.add_option<uint8_t>("function", 'F', option::with_argument, "Function number of PCIe device"); options_.add_option<uint8_t>("socket-id", 'S', option::with_argument, "Socket id encoded in BBS"); options_.add_option<std::string>("guid", 'G', option::with_argument, "accelerator id to enumerate", afu_id_); options_.add_option<uint32_t>("clock-freq", 'T', option::with_argument, "Clock frequency (used for bw measurements)", frequency_); options_.add_option<bool>("suppress-hdr", option::no_argument, "Suppress column headers", suppress_headers_); options_.add_option<bool>("csv", 'V', option::no_argument, "Comma separated value format", csv_format_); options_.add_option<bool>("suppress-stats", option::no_argument, "Show stats at end", suppress_stats_); } nlb7::~nlb7() { } void nlb7::show_help(std::ostream &os) { os << "Usage: fpgadiag --mode sw [options]:" << std::endl << std::endl; for (const auto &it : options_) { it->show_help(os); } } bool nlb7::setup() { options_.get_value<std::string>("target", target_); options_.get_value<bool>("suppress-stats", suppress_stats_); if (target_ == "fpga") { dsm_timeout_ = FPGA_DSM_TIMEOUT; } else if (target_ == "ase") { dsm_timeout_ = ASE_DSM_TIMEOUT; } else { std::cerr << "Invalid --target: " << target_ << std::endl; return false; } uint64_t dsm_timeout_usec = 0; if (options_.get_value<uint64_t>("dsm-timeout-usec", dsm_timeout_usec)) { dsm_timeout_ = microseconds(dsm_timeout_usec); } // begin, end options_.get_value<uint32_t>("begin", begin_); options_.get_value<uint32_t>("end", end_); auto end_opt = options_.find("end"); if (begin_ > max_cl) { log_.error("nlb7") << "begin: " << begin_ << " is greater than max: " << max_cl << std::endl; return false; } if (end_opt && !end_opt->is_set()) { end_ = begin_; } else { if (end_ < begin_) { log_.warn("nlb7") << "end: " << end_ << " is less than begin: " << begin_ << std::endl; end_ = begin_; } } cfg_ = nlb_mode::sw; // wrline-I, default=wrline-M, wrpush-I std::string cache_policy; options_.get_value<std::string>("cache-policy", cache_policy); if (cache_policy == "wrpush-I") { cfg_ |= nlb0_ctl::wrpush_i; } else if (cache_policy == "wrline-I") { cfg_ |= nlb0_ctl::wrline_i; } else if (cache_policy == "wrline-M") { cfg_ |= nlb0_ctl::wrline_m; } else { std::cerr << "Invalid --cache-policy: " << cache_policy << std::endl; return false; } // default=rdline-I, rdline-S std::string cache_hint; options_.get_value<std::string>("cache-hint", cache_hint); if (cache_hint == "rdline-I") { cfg_ |= nlb0_ctl::rdi; } else if (cache_hint == "rdline-S") { cfg_ |= nlb0_ctl::rds; } else { std::cerr << "Invalid --cache-hint: " << cache_hint << std::endl; return false; } // set the read channel // default=auto, vl0, vh0, vh1, random std::string rd_channel; options_.get_value<std::string>("read-vc", rd_channel); if (rd_channel == "vl0") { cfg_ |= nlb0_ctl::read_vl0; } else if (rd_channel == "vh0") { cfg_ |= nlb0_ctl::read_vh0; } else if (rd_channel == "vh1") { cfg_ |= nlb0_ctl::read_vh1; } else if (rd_channel == "random") { cfg_ |= nlb0_ctl::read_vr; } else if (rd_channel == "auto") { ; } else { std::cerr << "Invalid --read-vc: " << rd_channel << std::endl; return false; } // set the write fence channel // default=auto, vl0, vh0, vh1 std::string wrfence = "auto"; auto wrfence_opt = options_.find("wrfence-vc"); options_.get_value<std::string>("wrfence-vc", wrfence); if (wrfence == "auto") { cfg_ |= nlb0_ctl::wrfence_va; } else if (wrfence == "vl0") { cfg_ |= nlb0_ctl::wrfence_vl0; } else if (wrfence == "vh0") { cfg_ |= nlb0_ctl::wrfence_vh0; } else if (wrfence == "vh1") { cfg_ |= nlb0_ctl::wrfence_vh1; } else { std::cerr << "Invalid --wrfence-vc: " << wrfence << std::endl; return false; } bool wrfence_set = wrfence_opt && wrfence_opt->is_set(); // set the write channel // default=auto, vl0, vh0, vh1, random std::string wr_channel; options_.get_value<std::string>("write-vc", wr_channel); if (wr_channel == "vl0") { cfg_ |= nlb0_ctl::write_vl0; if (!wrfence_set) { cfg_ |= nlb0_ctl::wrfence_vl0; } } else if (wr_channel == "vh0") { cfg_ |= nlb0_ctl::write_vh0; if (!wrfence_set) { cfg_ |= nlb0_ctl::wrfence_vh0; } } else if (wr_channel == "vh1") { cfg_ |= nlb0_ctl::write_vh1; if (!wrfence_set) { cfg_ |= nlb0_ctl::wrfence_vh1; } } else if (wr_channel == "random") { cfg_ |= nlb0_ctl::write_vr; } else if (wr_channel == "auto") { ; } else { std::cerr << "Invalid --write-vc: " << wr_channel << std::endl; return false; } // default=poll, csr-write, umsg-data, umsg-hint std::string notice; options_.get_value<std::string>("notice", notice); if (notice == "poll") { notice_ = nlb7_notice::poll; } else if (notice == "csr-write") { notice_ = nlb7_notice::csr_write; cfg_ |= nlb0_ctl::csr_write; } #if USE_UMSG else if (notice == "umsg-data") { notice_ = nlb7_notice::umsg_data; } else if (notice == "umsg-hint") { notice_ = nlb7_notice::umsg_hint; } #endif // USE_UMSG else { std::cerr << "Invalid --notice: " << notice << std::endl; return false; } options_.get_value<uint32_t>("freq", frequency_); options_.get_value<bool>("suppress-hdr", suppress_headers_); options_.get_value<bool>("csv", csv_format_); // FIXME: use actual size for dsm size dsm_ = shared_buffer::allocate(accelerator_, dsm_size_); if (!dsm_) { log_.error("nlb7") << "failed to allocate DSM workspace." << std::endl; return false; } return true; } #define HIGH 0xffffffff #define LOW 0 bool nlb7::run() { bool res = true; const std::chrono::microseconds one_msec(1000); shared_buffer::ptr_t inout; // shared workspace, if possible shared_buffer::ptr_t inp; // input workspace shared_buffer::ptr_t out; // output workspace std::size_t buf_size = CL(end_ + 1); // size of input and output buffer (each) // Allocate the smallest possible workspaces for DSM, Input and Output // buffers. if (buf_size <= KB(2) || (buf_size > KB(4) && buf_size <= MB(1)) || (buf_size > MB(2) && buf_size < MB(512))) { // split inout = shared_buffer::allocate(accelerator_, buf_size * 2); if (!inout) { log_.error("nlb7") << "failed to allocate input/output buffers." << std::endl; return false; } std::vector<shared_buffer::ptr_t> bufs = split_buffer::split(inout, {buf_size, buf_size}); inp = bufs[0]; out = bufs[1]; } else { inp = shared_buffer::allocate(accelerator_, buf_size); out = shared_buffer::allocate(accelerator_, buf_size); if (!inp || !out) { log_.error("nlb7") << "failed to allocate input/output buffers." << std::endl; return false; } } if (!inp) { log_.error("nlb7") << "failed to allocate input workspace." << std::endl; return false; } if (!out) { log_.error("nlb7") << "failed to allocate output workspace." << std::endl; return false; } umsg_set_mask(accelerator_, LOW); #if USE_UMSG volatile uint8_t *pUMsgUsrVirt = (volatile uint8_t *) accelerator_->umsg_get_ptr(); size_t pagesize = (size_t) sysconf(_SC_PAGESIZE); size_t UMsgBufSize = pagesize * (size_t) umsg_num(accelerator_); #else volatile uint8_t *pUMsgUsrVirt = (volatile uint8_t *) NULL; size_t UMsgBufSize = 0; #endif if (pUMsgUsrVirt && ((nlb7_notice::umsg_data == notice_) || (nlb7_notice::umsg_hint == notice_))) { if (nlb7_notice::umsg_data == notice_) { umsg_set_mask(accelerator_, LOW); } else { umsg_set_mask(accelerator_, HIGH); } } accelerator_->reset(); // set dsm base, high then low accelerator_->write_csr64(static_cast<uint32_t>(nlb0_dsm::basel), reinterpret_cast<uint64_t>(dsm_->io_address())); // assert afu reset accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::ctl), 0); // de-assert afu reset accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::ctl), 1); // set input workspace address accelerator_->write_csr64(static_cast<uint32_t>(nlb7_csr::src_addr), CACHELINE_ALIGNED_ADDR(inp->io_address())); // set output workspace address accelerator_->write_csr64(static_cast<uint32_t>(nlb7_csr::dst_addr), CACHELINE_ALIGNED_ADDR(out->io_address())); accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::cfg), cfg_.value()); uint32_t sz = CL(begin_); auto fme_token = get_parent_token(accelerator_); // Read perf counters. fpga_cache_counters start_cache_ctrs = fpga_cache_counters(fme_token); fpga_fabric_counters start_fabric_ctrs = fpga_fabric_counters(fme_token); while (sz <= CL(end_)) { size_t MaxPoll = 1000; if (target_ == "ase") MaxPoll *= 100000; // Clear the UMsg address space. if (pUMsgUsrVirt) memset_s((uint8_t *)pUMsgUsrVirt, UMsgBufSize, 0); // Zero the output buffer. out->fill(0); // Re-initialize the input buffer. const uint32_t InputData = 0xdecafbad; for (size_t i = 0; i < inp->size()/sizeof(uint32_t); ++i) inp->write(InputData, i); // assert AFU reset. accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::ctl), 0); // clear the DSM. dsm_->fill(0); // de-assert afu reset accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::ctl), 1); // set number of cache lines for test accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::num_lines), sz / CL(1)); // start the test accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::ctl), 3); // Test flow // 1. CPU polls on address N+1 bool poll_result = buffer_poll<uint32_t>(out, sz, dsm_timeout_, HIGH, HIGH); if (!poll_result) { std::cerr << "Maximum timeout for CPU poll on Address N+1 was exceeded" << std::endl; res = false; break; } // 2. CPU copies dest to src errno_t e; e = memcpy_s((void *)inp->c_type(), sz, (void *)out->c_type(), sz); if (EOK != e) { std::cerr << "memcpy_s failed" << std::endl; res = false; break; } // fence operation __sync_synchronize(); // 3. CPU to FPGA message. Select notice type. if (nlb7_notice::csr_write == notice_) { accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::sw_notice), 0x10101010); } else if (pUMsgUsrVirt && ((nlb7_notice::umsg_data == notice_) || (nlb7_notice::umsg_hint == notice_))) { *(uint32_t *)pUMsgUsrVirt = HIGH; } else { // poll inp->write<uint32_t>(HIGH, sz); inp->write<uint32_t>(HIGH, sz+4); inp->write<uint32_t>(HIGH, sz+8); } // Wait for test completion poll_result = buffer_poll<uint32_t>(dsm_, (size_t)nlb0_dsm::test_complete, dsm_timeout_, (uint32_t)0x1, (uint32_t)1); if (!poll_result) { std::cerr << "Maximum Timeout for test complete was exceeded." << std::endl; res = false; break; } // stop the device accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::ctl), 7); while ((0 == dsm_->read<uint32_t>((size_t)nlb0_dsm::test_complete)) && MaxPoll) { --MaxPoll; buffer_poll<uint32_t>(dsm_, (size_t)nlb0_dsm::test_complete, one_msec, (uint32_t)0x1, (uint32_t)1); } // Read Perf Counters fpga_cache_counters end_cache_ctrs = fpga_cache_counters(fme_token); fpga_fabric_counters end_fabric_ctrs = fpga_fabric_counters(fme_token); if (!MaxPoll) { std::cerr << "Maximum timeout for test stop was exceeded." << std::endl; res = false; std::cout << intel::fpga::nlb::nlb_stats(dsm_, sz/CL(1), end_cache_ctrs - start_cache_ctrs, end_fabric_ctrs - start_fabric_ctrs, frequency_, false, suppress_headers_, csv_format_); break; } auto test_error = dsm_->read<uint32_t>((size_t)nlb0_dsm::test_error); if (0 != test_error) { std::cerr << "Error bit set in DSM." << std::endl; std::cerr << "DSM Test Error: 0x" << std::hex << test_error << std::endl; if (test_error & 0x1) { std::cerr << "Unexpected Read or Write response" << std::endl; } else if(test_error & 0x4) { std::cerr << "Write FIFO overflow" << std::endl; } else if(test_error & 0x8) { std::cerr << "Read data not as expected when FPGA read back N lines" << std::endl; } std::cerr << "Mode error vector:" << std::endl; for (int i=0 ; i < 8 ; ++i) { std::cerr << "[" << i << "]: 0x" << std::hex << dsm_->read<uint32_t>((size_t)nlb7_dsm::mode_error + i*sizeof(uint32_t)) << std::endl; if (0 == i) { std::cerr << " ; Read Data"; } else if(1 == i) { std::cerr << " ; Read response address"; } else if(2 == i) { std::cerr << " ; Read response header"; } else if(3 == i) { std::cerr << " ; Num of read responses"; } std::cerr << std::endl; } std::cerr << std::dec << std::endl; res = false; std::cout << intel::fpga::nlb::nlb_stats(dsm_, sz/CL(1), end_cache_ctrs - start_cache_ctrs, end_fabric_ctrs - start_fabric_ctrs, frequency_, false, suppress_headers_, csv_format_); break; } // Check for num_clocks underflow. auto num_clocks = dsm_->read<uint32_t>((size_t)nlb7_dsm::num_clocks); auto start_overhead = dsm_->read<uint32_t>((size_t)nlb7_dsm::start_overhead); auto end_overhead = dsm_->read<uint32_t>((size_t)nlb7_dsm::end_overhead); if (num_clocks < start_overhead + end_overhead) { std::cerr << "Number of Clocks underflow." << std::endl; res = false; std::cout << intel::fpga::nlb::nlb_stats(dsm_, sz/CL(1), end_cache_ctrs - start_cache_ctrs, end_fabric_ctrs - start_fabric_ctrs, frequency_, false, suppress_headers_, csv_format_); break; } std::cout << intel::fpga::nlb::nlb_stats(dsm_, sz/CL(1), end_cache_ctrs - start_cache_ctrs, end_fabric_ctrs - start_fabric_ctrs, frequency_, false, suppress_headers_, csv_format_); // Save Perf Monitors start_cache_ctrs = end_cache_ctrs; start_fabric_ctrs = end_fabric_ctrs; cachelines_ += sz/CL(1); sz += CL(1); } accelerator_->write_csr32(static_cast<uint32_t>(nlb7_csr::ctl), 0); accelerator_->reset(); dsm_.reset(); return res; } } // end of namespace diag } // end of namespace fpga } // end of namespace intel
#include<iostream> using namespace std; void menu() { cout << "Press 1 to calculate Sum of Numbers\n"; cout << "Press 2 to calculate Difference of Numbers\n"; cout << "Press 3 to calculate Product of numbers\n"; cout << "Press 4 to calculate Division of numbers\n"; cout << "Press X or x to terminate the program\n"; } void result(int choice,int n1,int n2) { switch(choice){ case '1': cout<<"Sum is "<< (n1 + n2)<<endl; break; case '2': cout<<"Difference is "<<(n1 - n2)<<endl; break; case '3': cout << "Product is " <<(n1 * n2)<<endl; break; case '4': cout << "Division is " <<(n1 / n2)<<endl; break; case 'X or x': cout<<"Thank You"<<endl; default: cout<<'Invalid operation. Try again.'<<endl; } int main() { int n1,n2; int choice,result; menu(); cout << "Enter your choice:\n"; choice = 1; cout << "Choice is " << choice << endl; result(choice, n1, n2); return 0; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <proxygen/lib/http/codec/HTTP2Framer.h> #include <folly/tracing/ScopedTraceSection.h> using namespace folly::io; using namespace folly; namespace proxygen { namespace http2 { const uint8_t kMinExperimentalFrameType = 0xf0; const Padding kNoPadding = folly::none; const PriorityUpdate DefaultPriority{0, false, 15}; namespace { const uint32_t kLengthMask = 0x00ffffff; const uint32_t kUint31Mask = 0x7fffffff; static const uint64_t kZeroPad[32] = {0}; static const bool kStrictPadding = true; static_assert(sizeof(kZeroPad) == 256, "bad zero padding"); void writePriorityBody(QueueAppender& appender, uint32_t streamDependency, bool exclusive, uint8_t weight) { DCHECK_EQ(0, ~kUint31Mask & streamDependency); if (exclusive) { streamDependency |= ~kUint31Mask; } appender.writeBE<uint32_t>(streamDependency); appender.writeBE<uint8_t>(weight); } void writePriorityBody(uint8_t* buf, uint32_t streamDependency, bool exclusive, uint8_t weight) { DCHECK_EQ(0, ~kUint31Mask & streamDependency); if (exclusive) { streamDependency |= ~kUint31Mask; } streamDependency = htonl(streamDependency); memcpy(buf, &streamDependency, sizeof(streamDependency)); buf += sizeof(streamDependency); *buf = weight; } void writePadding(IOBufQueue& queue, folly::Optional<uint8_t> size) { if (size && *size > 0) { auto out = queue.preallocate(*size, *size); memset(out.first, 0, *size); queue.postallocate(*size); } } /** * Generate just the common frame header. This includes the padding length * bits that sometimes come right after the frame header. Returns the * length field written to the common frame header. */ size_t computeLengthAndType(uint32_t length, FrameType type, uint8_t& flags, uint32_t stream, folly::Optional<uint8_t> padding, folly::Optional<PriorityUpdate> priority, size_t& headerSize) { // the acceptable length is now conditional based on state :( DCHECK_EQ(0, ~kLengthMask & length); DCHECK_EQ(0, ~kUint31Mask & stream); if (priority) { if (FrameType::HEADERS == type || FrameType::EX_HEADERS == type) { DCHECK(flags & PRIORITY); length += kFramePrioritySize; } else { DCHECK(FrameType::PRIORITY == type) << "priority is unexpected"; } headerSize += kFramePrioritySize; DCHECK_EQ(0, ~kLengthMask & length); DCHECK_NE(priority->streamDependency, stream) << "Circular dependency"; } // Add or remove padding flags if (padding) { flags |= PADDED; DCHECK(FrameType::HEADERS == type || FrameType::EX_HEADERS == type || FrameType::DATA == type || FrameType::PUSH_PROMISE == type); length += *padding + 1; headerSize += 1; } else { flags &= ~PADDED; } DCHECK_EQ(0, ~kLengthMask & length); DCHECK_EQ(true, isValidFrameType(type)); return ((kLengthMask & length) << 8) | static_cast<uint8_t>(type); } // There are two versions of writeFrameHeader. One takes an IOBufQueue and // uses a QueueAppender. The other takes a raw buffer. size_t writeFrameHeader(IOBufQueue& queue, uint32_t length, FrameType type, uint8_t flags, uint32_t stream, folly::Optional<uint8_t> padding, folly::Optional<PriorityUpdate> priority, std::unique_ptr<IOBuf> payload, bool reuseIOBufHeadroom = true) noexcept { size_t headerSize = kFrameHeaderSize; uint32_t lengthAndType = computeLengthAndType( length, type, flags, stream, padding, priority, headerSize); uint64_t payloadLength = 0; if (reuseIOBufHeadroom && payload && !payload->isSharedOne() && payload->headroom() >= headerSize && queue.tailroom() < headerSize) { // Use the headroom in payload for the frame header. // Make it appear that the payload IOBuf is empty and retreat so // appender can access the headroom payloadLength = payload->length(); payload->trimEnd(payloadLength); payload->retreat(headerSize); auto tail = payload->pop(); queue.append(std::move(payload)); payload = std::move(tail); } QueueAppender appender(&queue, headerSize); appender.writeBE<uint32_t>(lengthAndType); appender.writeBE<uint8_t>(flags); appender.writeBE<uint32_t>(kUint31Mask & stream); if (padding) { appender.writeBE<uint8_t>(*padding); } if (priority) { CHECK_LE(priority->streamDependency, std::numeric_limits<uint32_t>::max()); writePriorityBody(appender, (uint32_t)priority->streamDependency, priority->exclusive, priority->weight); } if (payloadLength) { queue.postallocate(payloadLength); } queue.append(std::move(payload)); return length; } size_t writeFrameHeader(uint8_t* buf, size_t bufLen, uint32_t length, FrameType type, uint8_t flags, uint32_t stream, folly::Optional<uint8_t> padding, folly::Optional<PriorityUpdate> priority) noexcept { size_t headerSize = kFrameHeaderSize; uint32_t lengthAndType = computeLengthAndType( length, type, flags, stream, padding, priority, headerSize); CHECK_GE(bufLen, headerSize); lengthAndType = htonl(lengthAndType); memcpy(buf, &lengthAndType, sizeof(lengthAndType)); buf += sizeof(lengthAndType); *buf = flags; buf++; stream &= kUint31Mask; stream = htonl(stream); memcpy(buf, &stream, sizeof(stream)); buf += sizeof(stream); bufLen -= kFrameHeaderSize; if (padding) { CHECK_GE(bufLen, 1); *buf = *padding; buf++; bufLen--; } if (priority) { CHECK_GE(bufLen, kFramePrioritySize); CHECK_LE(priority->streamDependency, std::numeric_limits<uint32_t>::max()); writePriorityBody(buf, (uint32_t)priority->streamDependency, priority->exclusive, priority->weight); } return length; } uint32_t parseUint31(Cursor& cursor) { // MUST ignore the 1 bit before the stream-id return kUint31Mask & cursor.readBE<uint32_t>(); } ErrorCode parseErrorCode(Cursor& cursor, ErrorCode& outCode) { auto code = cursor.readBE<uint32_t>(); if (code > kMaxErrorCode) { return ErrorCode::PROTOCOL_ERROR; } outCode = ErrorCode(code); return ErrorCode::NO_ERROR; } PriorityUpdate parsePriorityCommon(Cursor& cursor) { PriorityUpdate priority; uint32_t streamAndExclusive = cursor.readBE<uint32_t>(); priority.weight = cursor.readBE<uint8_t>(); priority.exclusive = ~kUint31Mask & streamAndExclusive; priority.streamDependency = kUint31Mask & streamAndExclusive; return priority; } /** * Given the flags for a frame and the cursor pointing at the top of the * frame-specific section (after the common header), return the number of * bytes to skip at the end of the frame. Caller must ensure there is at * least 1 bytes in the cursor. * * @param cursor The cursor to pull data from * @param header The frame header for the frame being parsed. * @param padding The out parameter that will return the number of padding * bytes at the end of the frame. * @return Nothing if success. The connection error code if failure. */ ErrorCode parsePadding(Cursor& cursor, const FrameHeader& header, uint8_t& padding, uint32_t& lefttoparse) noexcept { DCHECK(header.type == FrameType::DATA || header.type == FrameType::HEADERS || header.type == FrameType::EX_HEADERS || header.type == FrameType::PUSH_PROMISE); lefttoparse = header.length; if (frameHasPadding(header)) { if (lefttoparse < 1) { return ErrorCode::FRAME_SIZE_ERROR; } lefttoparse -= 1; padding = cursor.readBE<uint8_t>(); } else { padding = 0; } if (lefttoparse < padding) { return ErrorCode::PROTOCOL_ERROR; } else { lefttoparse -= padding; return ErrorCode::NO_ERROR; } } ErrorCode skipPadding(Cursor& cursor, uint8_t length, bool verify) { if (verify) { while (length > 0) { auto cur = cursor.peek(); uint8_t toCmp = std::min<size_t>(cur.second, length); if (memcmp(cur.first, kZeroPad, toCmp)) { return ErrorCode::PROTOCOL_ERROR; } cursor.skip(toCmp); length -= toCmp; } } else { cursor.skip(length); } return ErrorCode::NO_ERROR; } } // anonymous namespace bool isValidFrameType(FrameType type) { auto val = static_cast<uint8_t>(type); if (val < kMinExperimentalFrameType) { return val <= static_cast<uint8_t>(FrameType::ALTSVC); } else { switch (type) { case FrameType::EX_HEADERS: // Include the frame types added into FrameType enum for secondary // authentication. case FrameType::CERTIFICATE_REQUEST: case FrameType::CERTIFICATE: return true; default: return false; } } } bool frameAffectsCompression(FrameType t) { return t == FrameType::HEADERS || t == FrameType::PUSH_PROMISE || t == FrameType::CONTINUATION; } bool frameHasPadding(const FrameHeader& header) { return header.flags & PADDED; } //// Parsing //// ErrorCode parseFrameHeader(Cursor& cursor, FrameHeader& header) noexcept { FOLLY_SCOPED_TRACE_SECTION("HTTP2Framer - parseFrameHeader"); DCHECK_LE(kFrameHeaderSize, cursor.totalLength()); // MUST ignore the 2 bits before the length uint32_t lengthAndType = cursor.readBE<uint32_t>(); header.length = kLengthMask & (lengthAndType >> 8); uint8_t type = lengthAndType & 0xff; header.type = FrameType(type); header.flags = cursor.readBE<uint8_t>(); header.stream = parseUint31(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseData(Cursor& cursor, const FrameHeader& header, std::unique_ptr<IOBuf>& outBuf, uint16_t& outPadding) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; uint32_t lefttoparse; const auto err = parsePadding(cursor, header, padding, lefttoparse); RETURN_IF_ERROR(err); // outPadding is the total number of flow-controlled pad bytes, which // includes the length byte, if present. outPadding = padding + ((frameHasPadding(header)) ? 1 : 0); cursor.clone(outBuf, lefttoparse); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parseDataBegin(Cursor& cursor, const FrameHeader& header, size_t& /*parsed*/, uint16_t& outPadding) noexcept { uint8_t padding; uint32_t lefttoparse; const auto err = http2::parsePadding(cursor, header, padding, lefttoparse); RETURN_IF_ERROR(err); // outPadding is the total number of flow-controlled pad bytes, which // includes the length byte, if present. outPadding = padding + ((frameHasPadding(header)) ? 1 : 0); return ErrorCode::NO_ERROR; } ErrorCode parseDataEnd(Cursor& cursor, const size_t bufLen, const size_t pendingDataFramePaddingBytes, size_t& toSkip) noexcept { toSkip = std::min(pendingDataFramePaddingBytes, bufLen); return skipPadding(cursor, toSkip, kStrictPadding); } ErrorCode parseHeaders(Cursor& cursor, const FrameHeader& header, folly::Optional<PriorityUpdate>& outPriority, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; uint32_t lefttoparse; auto err = parsePadding(cursor, header, padding, lefttoparse); RETURN_IF_ERROR(err); if (header.flags & PRIORITY) { if (lefttoparse < kFramePrioritySize) { return ErrorCode::FRAME_SIZE_ERROR; } outPriority = parsePriorityCommon(cursor); lefttoparse -= kFramePrioritySize; } else { outPriority = folly::none; } cursor.clone(outBuf, lefttoparse); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parseExHeaders(Cursor& cursor, const FrameHeader& header, HTTPCodec::ExAttributes& outExAttributes, folly::Optional<PriorityUpdate>& outPriority, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; uint32_t lefttoparse; auto err = parsePadding(cursor, header, padding, lefttoparse); RETURN_IF_ERROR(err); // the regular HEADERS frame starts from here if (header.flags & PRIORITY) { if (lefttoparse < kFramePrioritySize) { return ErrorCode::FRAME_SIZE_ERROR; } outPriority = parsePriorityCommon(cursor); lefttoparse -= kFramePrioritySize; } else { outPriority = folly::none; } outExAttributes.unidirectional = header.flags & UNIDIRECTIONAL; if (lefttoparse < kFrameStreamIDSize) { return ErrorCode::FRAME_SIZE_ERROR; } outExAttributes.controlStream = parseUint31(cursor); lefttoparse -= kFrameStreamIDSize; if (!(outExAttributes.controlStream & 0x1)) { // control stream ID should be odd because it is initiated by client return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, lefttoparse); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parsePriority(Cursor& cursor, const FrameHeader& header, PriorityUpdate& outPriority) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFramePrioritySize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } outPriority = parsePriorityCommon(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseRstStream(Cursor& cursor, const FrameHeader& header, ErrorCode& outCode) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFrameRstStreamSize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } return parseErrorCode(cursor, outCode); } ErrorCode parseSettings(Cursor& cursor, const FrameHeader& header, std::deque<SettingPair>& settings) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } if (header.flags & ACK) { if (header.length != 0) { return ErrorCode::FRAME_SIZE_ERROR; } return ErrorCode::NO_ERROR; } if (header.length % 6 != 0) { return ErrorCode::FRAME_SIZE_ERROR; } for (auto length = header.length; length > 0; length -= 6) { uint16_t id = cursor.readBE<uint16_t>(); uint32_t val = cursor.readBE<uint32_t>(); settings.push_back(std::make_pair(SettingsId(id), val)); } return ErrorCode::NO_ERROR; } ErrorCode parsePushPromise(Cursor& cursor, const FrameHeader& header, uint32_t& outPromisedStream, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; uint32_t lefttoparse; auto err = parsePadding(cursor, header, padding, lefttoparse); RETURN_IF_ERROR(err); if (lefttoparse < kFramePushPromiseSize) { return ErrorCode::FRAME_SIZE_ERROR; } lefttoparse -= kFramePushPromiseSize; outPromisedStream = parseUint31(cursor); if (outPromisedStream == 0 || outPromisedStream & 0x1) { // client MUST reserve an even stream id greater than 0 return ErrorCode::PROTOCOL_ERROR; } if (lefttoparse < padding) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, lefttoparse); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parsePing(Cursor& cursor, const FrameHeader& header, uint64_t& outOpaqueData) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFramePingSize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } cursor.pull(&outOpaqueData, sizeof(outOpaqueData)); return ErrorCode::NO_ERROR; } ErrorCode parseGoaway(Cursor& cursor, const FrameHeader& header, uint32_t& outLastStreamID, ErrorCode& outCode, std::unique_ptr<IOBuf>& outDebugData) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length < kFrameGoawaySize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } outLastStreamID = parseUint31(cursor); auto err = parseErrorCode(cursor, outCode); RETURN_IF_ERROR(err); auto length = header.length; length -= kFrameGoawaySize; if (length > 0) { cursor.clone(outDebugData, length); } return ErrorCode::NO_ERROR; } ErrorCode parseWindowUpdate(Cursor& cursor, const FrameHeader& header, uint32_t& outAmount) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFrameWindowUpdateSize) { return ErrorCode::FRAME_SIZE_ERROR; } outAmount = parseUint31(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseContinuation(Cursor& cursor, const FrameHeader& header, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK(header.type == FrameType::CONTINUATION); DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, header.length); return ErrorCode::NO_ERROR; } ErrorCode parseAltSvc(Cursor& cursor, const FrameHeader& header, uint32_t& outMaxAge, uint32_t& outPort, std::string& outProtocol, std::string& outHost, std::string& outOrigin) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length < kFrameAltSvcSizeBase) { return ErrorCode::FRAME_SIZE_ERROR; } std::unique_ptr<IOBuf> tmpBuf; outMaxAge = cursor.readBE<uint32_t>(); outPort = cursor.readBE<uint16_t>(); const auto protoLen = cursor.readBE<uint8_t>(); if (header.length < kFrameAltSvcSizeBase + protoLen) { return ErrorCode::FRAME_SIZE_ERROR; } outProtocol = cursor.readFixedString(protoLen); const auto hostLen = cursor.readBE<uint8_t>(); if (header.length < kFrameAltSvcSizeBase + protoLen + hostLen) { return ErrorCode::FRAME_SIZE_ERROR; } outHost = cursor.readFixedString(hostLen); const auto originLen = (header.length - kFrameAltSvcSizeBase - protoLen - hostLen); outOrigin = cursor.readFixedString(originLen); return ErrorCode::NO_ERROR; } ErrorCode parseCertificateRequest( folly::io::Cursor& cursor, const FrameHeader& header, uint16_t& outRequestId, std::unique_ptr<folly::IOBuf>& outAuthRequest) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length < kFrameCertificateRequestSizeBase) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } outRequestId = cursor.readBE<uint16_t>(); auto length = header.length; length -= kFrameCertificateRequestSizeBase; if (length > 0) { cursor.clone(outAuthRequest, length); } return ErrorCode::NO_ERROR; } ErrorCode parseCertificate( folly::io::Cursor& cursor, const FrameHeader& header, uint16_t& outCertId, std::unique_ptr<folly::IOBuf>& outAuthenticator) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length < kFrameCertificateSizeBase) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } outCertId = cursor.readBE<uint16_t>(); auto length = header.length; length -= kFrameCertificateSizeBase; if (length > 0) { cursor.clone(outAuthenticator, length); } return ErrorCode::NO_ERROR; } //// Egress //// size_t writeData(IOBufQueue& queue, std::unique_ptr<IOBuf> data, uint32_t stream, folly::Optional<uint8_t> padding, bool endStream, bool reuseIOBufHeadroom) noexcept { DCHECK_NE(0, stream); uint8_t flags = 0; if (endStream) { flags |= END_STREAM; } const uint64_t dataLen = data ? data->computeChainDataLength() : 0; // Caller must not exceed peer setting for MAX_FRAME_SIZE // TODO: look into using headroom from data to hold the frame header const auto frameLen = writeFrameHeader(queue, dataLen, FrameType::DATA, flags, stream, padding, folly::none, std::move(data), reuseIOBufHeadroom); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } uint8_t calculatePreHeaderBlockSize(bool hasAssocStream, bool hasExAttributes, bool hasPriority, bool hasPadding) { uint8_t headerSize = http2::kFrameHeaderSize + ((hasAssocStream || hasExAttributes) ? sizeof(uint32_t) : 0); if (hasPriority && !hasAssocStream) { headerSize += http2::kFramePrioritySize; } if (hasPadding) { headerSize += 1; } return headerSize; } size_t writeHeaders(uint8_t* header, size_t headerLen, IOBufQueue& queue, size_t headersLen, uint32_t stream, folly::Optional<PriorityUpdate> priority, folly::Optional<uint8_t> padding, bool endStream, bool endHeaders) noexcept { DCHECK_NE(0, stream); uint32_t flags = 0; if (priority) { flags |= PRIORITY; } if (endStream) { flags |= END_STREAM; } if (endHeaders) { flags |= END_HEADERS; } // padding flags handled directly inside writeFrameHeader() const auto frameLen = writeFrameHeader(header, headerLen, headersLen, FrameType::HEADERS, flags, stream, padding, priority); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writeExHeaders(uint8_t* header, size_t headerLen, IOBufQueue& queue, size_t headersLen, uint32_t stream, const HTTPCodec::ExAttributes& exAttributes, const folly::Optional<PriorityUpdate>& priority, const folly::Optional<uint8_t>& padding, bool endStream, bool endHeaders) noexcept { DCHECK_NE(0, stream); DCHECK_NE(0, exAttributes.controlStream); DCHECK_EQ(0, ~kUint31Mask & stream); DCHECK_EQ(0, ~kUint31Mask & exAttributes.controlStream); DCHECK(0x1 & exAttributes.controlStream) << "controlStream should be initiated by client"; uint32_t flags = 0; if (priority) { flags |= PRIORITY; } if (endStream) { flags |= END_STREAM; } if (endHeaders) { flags |= END_HEADERS; } if (exAttributes.unidirectional) { flags |= UNIDIRECTIONAL; } const auto frameLen = writeFrameHeader(header, headerLen, headersLen + kFrameStreamIDSize, FrameType::EX_HEADERS, flags, stream, padding, priority); uint8_t* csPtr = header + kFrameHeaderSize + ((padding) ? 1 : 0) + ((priority) ? kFramePrioritySize : 0); auto controlStream = htonl(exAttributes.controlStream); memcpy(csPtr, &controlStream, sizeof(controlStream)); QueueAppender appender(&queue, frameLen); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writePriority(IOBufQueue& queue, uint32_t stream, PriorityUpdate priority) noexcept { DCHECK_NE(0, stream); const auto frameLen = writeFrameHeader(queue, kFramePrioritySize, FrameType::PRIORITY, 0, stream, kNoPadding, priority, nullptr); return kFrameHeaderSize + frameLen; } size_t writeRstStream(IOBufQueue& queue, uint32_t stream, ErrorCode errorCode) noexcept { DCHECK_NE(0, stream); const auto frameLen = writeFrameHeader(queue, kFrameRstStreamSize, FrameType::RST_STREAM, 0, stream, kNoPadding, folly::none, nullptr); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(static_cast<uint32_t>(errorCode)); return kFrameHeaderSize + frameLen; } size_t writeSettings(IOBufQueue& queue, const std::deque<SettingPair>& settings) { const auto settingsSize = settings.size() * 6; const auto frameLen = writeFrameHeader(queue, settingsSize, FrameType::SETTINGS, 0, 0, kNoPadding, folly::none, nullptr); QueueAppender appender(&queue, settingsSize); for (const auto& setting : settings) { DCHECK_LE(static_cast<uint32_t>(setting.first), std::numeric_limits<uint16_t>::max()); appender.writeBE<uint16_t>(static_cast<uint16_t>(setting.first)); appender.writeBE<uint32_t>(setting.second); } return kFrameHeaderSize + frameLen; } size_t writeSettingsAck(IOBufQueue& queue) { writeFrameHeader( queue, 0, FrameType::SETTINGS, ACK, 0, kNoPadding, folly::none, nullptr); return kFrameHeaderSize; } size_t writePushPromise(uint8_t* header, size_t headerLen, IOBufQueue& queue, uint32_t associatedStream, uint32_t promisedStream, size_t headersLen, folly::Optional<uint8_t> padding, bool endHeaders) noexcept { DCHECK_NE(0, promisedStream); DCHECK_NE(0, associatedStream); DCHECK_EQ(0, 0x1 & promisedStream); DCHECK_EQ(1, 0x1 & associatedStream); DCHECK_EQ(0, ~kUint31Mask & promisedStream); const auto frameLen = writeFrameHeader(header, headerLen, headersLen + kFramePushPromiseSize, FrameType::PUSH_PROMISE, endHeaders ? END_HEADERS : 0, associatedStream, padding, folly::none); promisedStream = htonl(promisedStream); uint8_t* psPtr = header + kFrameHeaderSize; if (padding) { psPtr++; } memcpy(psPtr, &promisedStream, sizeof(promisedStream)); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writePing(IOBufQueue& queue, uint64_t opaqueData, bool ack) noexcept { const auto frameLen = writeFrameHeader(queue, kFramePingSize, FrameType::PING, ack ? ACK : 0, 0, kNoPadding, folly::none, nullptr); queue.append(&opaqueData, sizeof(opaqueData)); return kFrameHeaderSize + frameLen; } size_t writeGoaway(IOBufQueue& queue, uint32_t lastStreamID, ErrorCode errorCode, std::unique_ptr<IOBuf> debugData) noexcept { uint32_t debugLen = debugData ? debugData->computeChainDataLength() : 0; DCHECK_EQ(0, ~kLengthMask & debugLen); const auto frameLen = writeFrameHeader(queue, kFrameGoawaySize + debugLen, FrameType::GOAWAY, 0, 0, kNoPadding, folly::none, nullptr); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(lastStreamID); appender.writeBE<uint32_t>(static_cast<uint32_t>(errorCode)); queue.append(std::move(debugData)); return kFrameHeaderSize + frameLen; } size_t writeWindowUpdate(IOBufQueue& queue, uint32_t stream, uint32_t amount) noexcept { const auto frameLen = writeFrameHeader(queue, kFrameWindowUpdateSize, FrameType::WINDOW_UPDATE, 0, stream, kNoPadding, folly::none, nullptr); DCHECK_EQ(0, ~kUint31Mask & amount); DCHECK_LT(0, amount); QueueAppender appender(&queue, kFrameWindowUpdateSize); appender.writeBE<uint32_t>(amount); return kFrameHeaderSize + frameLen; } size_t writeContinuation(IOBufQueue& queue, uint32_t stream, bool endHeaders, std::unique_ptr<IOBuf> headers) noexcept { DCHECK_NE(0, stream); const auto dataLen = headers->computeChainDataLength(); const auto frameLen = writeFrameHeader(queue, dataLen, FrameType::CONTINUATION, endHeaders ? END_HEADERS : 0, stream, kNoPadding, folly::none, std::move(headers)); return kFrameHeaderSize + frameLen; } size_t writeAltSvc(IOBufQueue& queue, uint32_t stream, uint32_t maxAge, uint16_t port, StringPiece protocol, StringPiece host, StringPiece origin) noexcept { const auto protoLen = protocol.size(); const auto hostLen = host.size(); const auto originLen = origin.size(); const auto frameLen = protoLen + hostLen + originLen + kFrameAltSvcSizeBase; writeFrameHeader(queue, frameLen, FrameType::ALTSVC, 0, stream, kNoPadding, folly::none, nullptr); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(maxAge); appender.writeBE<uint16_t>(port); appender.writeBE<uint8_t>(protoLen); appender.push(reinterpret_cast<const uint8_t*>(protocol.data()), protoLen); appender.writeBE<uint8_t>(hostLen); appender.push(reinterpret_cast<const uint8_t*>(host.data()), hostLen); appender.push(reinterpret_cast<const uint8_t*>(origin.data()), originLen); return kFrameHeaderSize + frameLen; } size_t writeCertificateRequest(folly::IOBufQueue& writeBuf, uint16_t requestId, std::unique_ptr<folly::IOBuf> authRequest) { const auto dataLen = authRequest ? kFrameCertificateRequestSizeBase + authRequest->computeChainDataLength() : kFrameCertificateRequestSizeBase; // The CERTIFICATE_REQUEST frame must be sent on stream 0. const auto frameLen = writeFrameHeader(writeBuf, dataLen, FrameType::CERTIFICATE_REQUEST, 0, 0, kNoPadding, folly::none, nullptr); QueueAppender appender(&writeBuf, frameLen); appender.writeBE<uint16_t>(requestId); writeBuf.append(std::move(authRequest)); return kFrameHeaderSize + frameLen; } size_t writeCertificate(folly::IOBufQueue& writeBuf, uint16_t certId, std::unique_ptr<folly::IOBuf> authenticator, bool toBeContinued) { uint8_t flags = 0; if (toBeContinued) { flags |= TO_BE_CONTINUED; } const auto dataLen = authenticator ? kFrameCertificateSizeBase + authenticator->computeChainDataLength() : kFrameCertificateSizeBase; // The CERTIFICATE_REQUEST frame must be sent on stream 0. const auto frameLen = writeFrameHeader(writeBuf, dataLen, FrameType::CERTIFICATE, flags, 0, kNoPadding, folly::none, nullptr); QueueAppender appender(&writeBuf, frameLen); appender.writeBE<uint16_t>(certId); writeBuf.append(std::move(authenticator)); return kFrameHeaderSize + frameLen; } const char* getFrameTypeString(FrameType type) { switch (type) { case FrameType::DATA: return "DATA"; case FrameType::HEADERS: return "HEADERS"; case FrameType::PRIORITY: return "PRIORITY"; case FrameType::RST_STREAM: return "RST_STREAM"; case FrameType::SETTINGS: return "SETTINGS"; case FrameType::PUSH_PROMISE: return "PUSH_PROMISE"; case FrameType::PING: return "PING"; case FrameType::GOAWAY: return "GOAWAY"; case FrameType::WINDOW_UPDATE: return "WINDOW_UPDATE"; case FrameType::CONTINUATION: return "CONTINUATION"; case FrameType::ALTSVC: return "ALTSVC"; case FrameType::CERTIFICATE_REQUEST: return "CERTIFICATE_REQUEST"; case FrameType::CERTIFICATE: return "CERTIFICATE"; default: // can happen when type was cast from uint8_t return "Unknown"; } LOG(FATAL) << "Unreachable"; return ""; } }} // namespace proxygen::http2
/** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 "tools/converter/parser/onnx/onnx_instance_norm_parser.h" #include <memory> namespace mindspore { namespace lite { lite::PrimitiveC *OnnxInstanceNormParser::ParseLitePrimitive(const onnx::GraphProto &onnx_graph, const onnx::NodeProto &onnx_node) { MS_LOG(DEBUG) << "onnx InstanceNormParser"; auto attr = std::make_unique<schema::LayerNormT>(); if (attr == nullptr) { MS_LOG(ERROR) << "new op failed"; return nullptr; } if (!onnx_node.attribute().empty()) { auto onnx_node_attr = onnx_node.attribute().at(0); if (onnx_node_attr.name() == "epsilon") { attr->epsilon = onnx_node_attr.f(); } } auto primitive = std::make_unique<schema::PrimitiveT>(); if (primitive == nullptr) { MS_LOG(ERROR) << "new primitive failed"; return nullptr; } attr->elementwiseAffine = true; primitive->value.type = schema::PrimitiveType_LayerNorm; primitive->value.value = attr.release(); return PrimitiveC::Create(primitive.release()); } OnnxNodeRegistrar g_onnxInstanceNormParser("InstanceNormalization", new OnnxInstanceNormParser()); } // namespace lite } // namespace mindspore
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved. #include <algorithm> #include <cassert> #include <iostream> #include <limits> #include <random> #include <string> using std::cout; using std::default_random_engine; using std::endl; using std::numeric_limits; using std::random_device; using std::stoi; using std::stol; using std::string; using std::to_string; using std::uniform_int_distribution; // @include long Reverse(int x) { long result = 0, x_remaining = abs(x); while (x_remaining) { result = result * 10 + x_remaining % 10; x_remaining /= 10; } return x < 0 ? -result : result; } // @exclude long CheckAns(int x) { string s = to_string(x); if (s.front() == '-') { reverse(s.begin() + 1, s.end()); } else { reverse(s.begin(), s.end()); } return stol(s); } int main(int argc, char** argv) { default_random_engine gen((random_device())()); int n; if (argc == 2) { n = stoi(argv[1]); cout << "n = " << n << ", reversed n = " << Reverse(n) << endl; assert(CheckAns(n) == Reverse(n)); } else { uniform_int_distribution<int> dis(numeric_limits<int>::min(), numeric_limits<int>::max()); for (int times = 0; times < 1000; ++times) { n = dis(gen); cout << "n = " << n << ", reversed n = " << Reverse(n) << endl; assert(CheckAns(n) == Reverse(n)); } } return 0; }
// Copyright Epic Games, Inc. All Rights Reserved. #include "MultiThreadingCharacter.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" ////////////////////////////////////////////////////////////////////////// // AMultiThreadingCharacter AMultiThreadingCharacter::AMultiThreadingCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) } ////////////////////////////////////////////////////////////////////////// // Input void AMultiThreadingCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &AMultiThreadingCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AMultiThreadingCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &AMultiThreadingCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &AMultiThreadingCharacter::LookUpAtRate); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &AMultiThreadingCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &AMultiThreadingCharacter::TouchStopped); // VR headset functionality PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AMultiThreadingCharacter::OnResetVR); } void AMultiThreadingCharacter::OnResetVR() { // If MultiThreading is added to a project via 'Add Feature' in the Unreal Editor the dependency on HeadMountedDisplay in MultiThreading.Build.cs is not automatically propagated // and a linker error will result. // You will need to either: // Add "HeadMountedDisplay" to [YourProject].Build.cs PublicDependencyModuleNames in order to build successfully (appropriate if supporting VR). // or: // Comment or delete the call to ResetOrientationAndPosition below (appropriate if not supporting VR) UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void AMultiThreadingCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void AMultiThreadingCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void AMultiThreadingCharacter::BeginPlay() { Super::BeginPlay(); customThread = new FCustomThread(this); } void AMultiThreadingCharacter::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); this->lastDeltaTime = DeltaSeconds; UE_LOG(LogTemp, Log, TEXT("Number: %d"), this->number); } void AMultiThreadingCharacter::EndPlay(const EEndPlayReason::Type EndPlayReason) { if(customThread) { customThread->Shutdown(); } Super::EndPlay(EndPlayReason); } void AMultiThreadingCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AMultiThreadingCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void AMultiThreadingCharacter::MoveForward(float Value) { if ((Controller != nullptr) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); } } void AMultiThreadingCharacter::MoveRight(float Value) { if ( (Controller != nullptr) && (Value != 0.0f) ) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, Value); } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF 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. #include <cstring> #include "olap/bit_field_reader.h" #include "olap/column_reader.h" #include "olap/file_stream.h" #include "olap/olap_define.h" namespace doris { IntegerColumnReader::IntegerColumnReader(uint32_t column_unique_id): _eof(false), _column_unique_id(column_unique_id), _data_reader(NULL) { } IntegerColumnReader::~IntegerColumnReader() { SAFE_DELETE(_data_reader); } OLAPStatus IntegerColumnReader::init( std::map<StreamName, ReadOnlyFileStream*>* streams, bool is_sign) { if (NULL == streams) { OLAP_LOG_WARNING("input streams is NULL"); return OLAP_ERR_INPUT_PARAMETER_ERROR; } // Get data stream according to column id and type ReadOnlyFileStream* data_stream = extract_stream(_column_unique_id, StreamInfoMessage::DATA, streams); if (data_stream == NULL) { OLAP_LOG_WARNING("specified stream is NULL"); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } _data_reader = new(std::nothrow) RunLengthIntegerReader(data_stream, is_sign); if (NULL == _data_reader) { OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader"); return OLAP_ERR_MALLOC_ERROR; } // reset eof flag when init, to support reinit return OLAP_SUCCESS; } OLAPStatus IntegerColumnReader::seek(PositionProvider* position) { return _data_reader->seek(position); } OLAPStatus IntegerColumnReader::skip(uint64_t row_count) { return _data_reader->skip(row_count); } OLAPStatus IntegerColumnReader::next(int64_t* value) { return _data_reader->next(value); } StringColumnDirectReader::StringColumnDirectReader( uint32_t column_unique_id, uint32_t dictionary_size) : _eof(false), _column_unique_id(column_unique_id), _values(NULL), _data_stream(NULL), _length_reader(NULL) { } StringColumnDirectReader::~StringColumnDirectReader() { SAFE_DELETE(_length_reader); } OLAPStatus StringColumnDirectReader::init( std::map<StreamName, ReadOnlyFileStream*>* streams, int size, MemPool* mem_pool) { if (NULL == streams) { OLAP_LOG_WARNING("input streams is NULL"); return OLAP_ERR_INPUT_PARAMETER_ERROR; } // Get data stream according to column id and type _data_stream = extract_stream(_column_unique_id, StreamInfoMessage::DATA, streams); if (NULL == _data_stream) { OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } _values = reinterpret_cast<StringSlice*>(mem_pool->allocate(size * sizeof(StringSlice))); ReadOnlyFileStream* length_stream = extract_stream(_column_unique_id, StreamInfoMessage::LENGTH, streams); if (NULL == length_stream) { OLAP_LOG_WARNING("specifiedstream not found. [unique_id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } _length_reader = new(std::nothrow) RunLengthIntegerReader(length_stream, false); if (NULL == _length_reader) { OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader"); return OLAP_ERR_MALLOC_ERROR; } return OLAP_SUCCESS; } OLAPStatus StringColumnDirectReader::seek(PositionProvider* position) { OLAPStatus res = _data_stream->seek(position); // All strings in segment may be empty, so the data stream is EOF and // and length stream is not EOF. if (OLAP_SUCCESS == res || OLAP_ERR_COLUMN_STREAM_EOF == res) { res = _length_reader->seek(position); } return res; } OLAPStatus StringColumnDirectReader::skip(uint64_t row_count) { OLAPStatus res = OLAP_SUCCESS; int64_t skip_length = 0; int64_t tmp_length = 0; for (size_t i = 0; i < row_count; ++i) { res = _length_reader->next(&tmp_length); if (OLAP_SUCCESS != res) { return res; } skip_length += tmp_length; } if (OLAP_SUCCESS == res) { // TODO: skip function of instream is implemented, but not tested return _data_stream->skip(skip_length); } return res; } // Return string field of current row_count OLAPStatus StringColumnDirectReader::next(char* buffer, uint32_t* length) { int64_t read_length = 0; OLAPStatus res = _length_reader->next(&read_length); *length = read_length; while (OLAP_SUCCESS == res && read_length > 0) { uint64_t buf_size = read_length; res = _data_stream->read(buffer, &buf_size); read_length -= buf_size; buffer += buf_size; } *length -= read_length; return res; } OLAPStatus StringColumnDirectReader::next_vector( ColumnVector* column_vector, uint32_t size, MemPool* mem_pool, int64_t* read_bytes) { /* * MemPool here is not the same as MemPool in init function * 1. MemPool is created by VectorizedRowBatch, * and reset when load row batch * 2. MemPool in init function is created by SegmentReader, * and free by SegmentReader deconstructor. */ OLAPStatus res = OLAP_SUCCESS; int64_t length = 0; int64_t string_buffer_size = 0; column_vector->set_col_data(_values); if (column_vector->no_nulls()) { for (int i = 0; i < size; ++i) { res = _length_reader->next(&length); if (OLAP_SUCCESS != res) { return res; } _values[i].size = length; string_buffer_size += length; } char* string_buffer = reinterpret_cast<char*>(mem_pool->allocate(string_buffer_size)); for (int i = 0; i < size; ++i) { _values[i].data = string_buffer; length = _values[i].size; while (length > 0) { uint64_t buf_size = length; res = _data_stream->read(string_buffer, &buf_size); if (res != OLAP_SUCCESS) { return res; } length -= buf_size; string_buffer += buf_size; } } } else { bool* is_null = column_vector->is_null(); for (int i = 0; i < size; ++i) { if (!is_null[i]) { res = _length_reader->next(&length); if (OLAP_SUCCESS != res) { return res; } _values[i].size = length; string_buffer_size += length; } else { _values[i].size = 0; } } char* string_buffer = reinterpret_cast<char*>(mem_pool->allocate(string_buffer_size)); for (int i = 0; i < size; ++i) { if (!is_null[i]) { length = _values[i].size; _values[i].data = string_buffer; while (length > 0) { uint64_t buf_size = length; res = _data_stream->read(string_buffer, &buf_size); if (res != OLAP_SUCCESS) { return res; } length -= buf_size; string_buffer += buf_size; } } else { _values[i].data = nullptr; _values[i].size = 0; } } } *read_bytes += string_buffer_size; return res; } StringColumnDictionaryReader::StringColumnDictionaryReader( uint32_t column_unique_id, uint32_t dictionary_size) : _eof(false), _dictionary_size(dictionary_size), _column_unique_id(column_unique_id), _values(NULL), //_dictionary_size(0), //_offset_dictionary(NULL), //_dictionary_data_buffer(NULL), _read_buffer(NULL), _data_reader(NULL) { } StringColumnDictionaryReader::~StringColumnDictionaryReader() { //SAFE_DELETE_ARRAY(_offset_dictionary); //SAFE_DELETE(_dictionary_data_buffer); SAFE_DELETE(_data_reader); SAFE_DELETE_ARRAY(_read_buffer); } /* // TODO.改为先解析成字典,不过看起来也不会太快,因为这里会全部解析完,而放在后边解析可能能省点资源 // 后边再测,先保留代码 OLAPStatus StringColumnDictionaryReader::init(std::map<StreamName, ReadOnlyFileStream *> *streams, UniqueIdEncodingMap* encodings, RuntimeProfile* profile) { ReadOnlyFileStream* dictionary_data_stream = extract_stream(_column_unique_id, StreamInfoMessage::DICTIONARY_DATA, streams); if (NULL == dictionary_data_stream) { OLAP_LOG_WARNING("dictionary data stream not found. [unique id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } if (dictionary_data_stream->stream_length() > 0) { _dictionary_data_buffer = ByteBuffer::create( dictionary_data_stream->estimate_uncompressed_length()); size_t offset = 0; size_t length = 0; // TODO. stream 还需要修改,使之真正能够方便的读取 while (0 != (length = dictionary_data_stream->available())) { dictionary_data_stream->read(_dictionary_data_buffer->array() + offset, &length); offset += length; } } else { _dictionary_data_buffer = NULL; } UniqueIdEncodingMap::iterator it = encodings->find(_column_unique_id); if (it == encodings->end()) { OLAP_LOG_WARNING("encoding not found. [unique id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } uint64_t dictionary_size = (*it).second.dictionary_size(); // 建立字典偏移列表 ReadOnlyFileStream* dictionary_length_stream = extract_stream(_column_unique_id, StreamInfoMessage::LENGTH, streams); if (NULL == dictionary_length_stream) { OLAP_LOG_WARNING("dictionary length stream not found. [unique id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } RunLengthIntegerReader* dictionary_length_reader = new (std::nothrow) RunLengthIntegerReader(dictionary_length_stream, true); uint64_t offset = 0; // 如果上次分配的空间足够多,这次可以不分配 if (dictionary_size + 1 > _dictionary_size || NULL == _offset_dictionary) { SAFE_DELETE_ARRAY(_offset_dictionary); _dictionary_size = dictionary_size + 1; _offset_dictionary = new (std::nothrow) uint64_t[_dictionary_size]; if (NULL == _offset_dictionary) { OLAP_LOG_WARNING("fail to allocate dictionary buffer"); return OLAP_ERR_MALLOC_ERROR; } } // 应该只有dictionary_size 项,最后一个单位保存一个“不存在的”位置, // 也就是最后一个字符串的终止位置,这样做是为了支持偏移计算的算法不用处理边界 int64_t value = 0; OLAPStatus res = OLAP_SUCCESS; size_t dictionary_entry = 0; for (; dictionary_entry < dictionary_size; ++dictionary_entry) { _offset_dictionary[dictionary_entry] = offset; res = dictionary_length_reader->next(&value); // 理论上应该足够读,读出eof也是不对的。 if (OLAP_SUCCESS != res && OLAP_ERR_DATA_EOF != res) { OLAP_LOG_WARNING("build offset dictionary failed. [res = %d]", res); return res; } offset += value; } _offset_dictionary[dictionary_entry] = offset; // 建立数据流读取器 ReadOnlyFileStream* data_stream = extract_stream(_column_unique_id, StreamInfoMessage::DATA, streams); if (NULL == data_stream) { OLAP_LOG_WARNING("data stream not found. [unique id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } _data_reader = new (std::nothrow) RunLengthIntegerReader(data_stream, true); if (NULL == _data_reader) { OLAP_LOG_WARNING("fail to malloc data reader"); return OLAP_ERR_MALLOC_ERROR; } return OLAP_SUCCESS; } */ OLAPStatus StringColumnDictionaryReader::init( std::map<StreamName, ReadOnlyFileStream*>* streams, int size, MemPool* mem_pool) { ReadOnlyFileStream* dictionary_data_stream = extract_stream(_column_unique_id, StreamInfoMessage::DICTIONARY_DATA, streams); if (NULL == dictionary_data_stream) { OLAP_LOG_WARNING("dictionary data stream not found. [unique id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } ReadOnlyFileStream* dictionary_length_stream = extract_stream(_column_unique_id, StreamInfoMessage::LENGTH, streams); if (NULL == dictionary_length_stream) { OLAP_LOG_WARNING("dictionary length stream not found. [unique id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } RunLengthIntegerReader* dictionary_length_reader = new(std::nothrow) RunLengthIntegerReader(dictionary_length_stream, false); OLAPStatus res = OLAP_SUCCESS; /* uint64_t offset = 0; int64_t value = 0; size_t length_remain = 0; size_t length_to_read = 0; size_t read_buffer_size = 1024; ByteBuffer* read_buffer = ByteBuffer::create(read_buffer_size); if (NULL == read_buffer) { OLAP_LOG_WARNING("fail to malloc ByteBuffer"); return OLAP_ERR_MALLOC_ERROR; } for (size_t dictionary_entry = 0; dictionary_entry < dictionary_size; ++dictionary_entry) { res = dictionary_length_reader->next(&value); // 理论上应该足够读,读出eof也是不对的。 if (OLAP_SUCCESS != res && OLAP_ERR_DATA_EOF != res) { OLAP_LOG_WARNING("build offset dictionary failed. [res = %d]", res); return res; } // 其实为offset,长度为value的string length_remain = value; std::string dictionary_item; while (length_remain != 0) { length_to_read = std::min(length_remain, read_buffer_size); res = dictionary_data_stream->read(read_buffer->array(), &length_to_read); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("read dictionary content failed"); return res; } dictionary_item.append(read_buffer->array(), length_to_read); length_remain -= length_to_read; } _dictionary.push_back(dictionary_item); offset += value; } */ _values = reinterpret_cast<StringSlice*>(mem_pool->allocate(size * sizeof(StringSlice))); int64_t read_buffer_size = 1024; char* _read_buffer = new(std::nothrow) char[read_buffer_size]; if (NULL == _read_buffer) { OLAP_LOG_WARNING("fail to malloc read buffer. [size = %lu]", read_buffer_size); return OLAP_ERR_MALLOC_ERROR; } int64_t length = 0; uint64_t read_length = 0; std::string dictionary_item; for (size_t dictionary_entry = 0; dictionary_entry < _dictionary_size; ++dictionary_entry) { res = dictionary_length_reader->next(&length); // 理论上应该足够读,读出eof也是不对的。 if (OLAP_SUCCESS != res || length < 0) { OLAP_LOG_WARNING("build offset dictionary failed. [res = %d]", res); return res; } if (length > read_buffer_size) { SAFE_DELETE_ARRAY(_read_buffer); read_buffer_size = length; if (NULL == (_read_buffer = new(std::nothrow) char[read_buffer_size])) { OLAP_LOG_WARNING("fail to malloc read buffer. [size = %lu]", read_buffer_size); return OLAP_ERR_MALLOC_ERROR; } } read_length = length; dictionary_data_stream->read(_read_buffer, &read_length); if (static_cast<int64_t>(read_length) != length) { OLAP_LOG_WARNING("read stream fail."); return OLAP_ERR_COLUMN_READ_STREAM; } dictionary_item.assign(_read_buffer, length); _dictionary.push_back(dictionary_item); } // 建立数据流读取器 ReadOnlyFileStream* data_stream = extract_stream(_column_unique_id, StreamInfoMessage::DATA, streams); if (NULL == data_stream) { OLAP_LOG_WARNING("data stream not found. [unique id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } _data_reader = new(std::nothrow) RunLengthIntegerReader(data_stream, false); if (NULL == _data_reader) { OLAP_LOG_WARNING("fail to malloc data reader"); return OLAP_ERR_MALLOC_ERROR; } SAFE_DELETE_ARRAY(_read_buffer); SAFE_DELETE(dictionary_length_reader); return OLAP_SUCCESS; } OLAPStatus StringColumnDictionaryReader::seek(PositionProvider* position) { return _data_reader->seek(position); } OLAPStatus StringColumnDictionaryReader::skip(uint64_t row_count) { return _data_reader->skip(row_count); } OLAPStatus StringColumnDictionaryReader::next(char* buffer, uint32_t* length) { int64_t value; OLAPStatus res = _data_reader->next(&value); // 错误或是EOF if (OLAP_SUCCESS != res) { if (OLAP_ERR_DATA_EOF == res) { _eof = true; } return res; } if (value >= static_cast<int64_t>(_dictionary.size())) { OLAP_LOG_WARNING("value may indicated an invalid dictionary entry. " "[value = %lu, dictionary_size = %lu]", value, _dictionary.size()); return OLAP_ERR_BUFFER_OVERFLOW; } memcpy(buffer, _dictionary[value].c_str(), _dictionary[value].size()); *length = _dictionary[value].size(); return OLAP_SUCCESS; } OLAPStatus StringColumnDictionaryReader::next_vector( ColumnVector* column_vector, uint32_t size, MemPool* mem_pool, int64_t* read_bytes) { int64_t index[size]; int64_t buffer_size = 0; OLAPStatus res = OLAP_SUCCESS; column_vector->set_col_data(_values); if (column_vector->no_nulls()) { for (int i = 0; i < size; ++i) { res = _data_reader->next(&index[i]); if (OLAP_SUCCESS != res) { return res; } if (index[i] >= static_cast<int64_t>(_dictionary.size())) { OLAP_LOG_WARNING("value may indicated an invalid dictionary entry. " "[index = %lu, dictionary_size = %lu]", index[i], _dictionary.size()); return OLAP_ERR_BUFFER_OVERFLOW; } _values[i].size = _dictionary[index[i]].size(); buffer_size += _values[i].size; } char* string_buffer = reinterpret_cast<char*>(mem_pool->allocate(buffer_size)); for (int i = 0; i < size; ++i) { memory_copy(string_buffer, _dictionary[index[i]].c_str(), _values[i].size); _values[i].data = string_buffer; string_buffer += _values[i].size; } } else { bool* is_null = column_vector->is_null(); for (int i = 0; i < size; ++i) { if (!is_null[i]) { res = _data_reader->next(&index[i]); if (OLAP_SUCCESS != res) { return res; } if (index[i] >= static_cast<int64_t>(_dictionary.size())) { OLAP_LOG_WARNING("value may indicated an invalid dictionary entry. " "[index = %lu, dictionary_size = %lu]", index[i], _dictionary.size()); return OLAP_ERR_BUFFER_OVERFLOW; } _values[i].size = _dictionary[index[i]].size(); buffer_size += _values[i].size; } } char* string_buffer = reinterpret_cast<char*>(mem_pool->allocate(buffer_size)); for (int i = 0; i < size; ++i) { if (!is_null[i]) { memory_copy(string_buffer, _dictionary[index[i]].c_str(), _values[i].size); _values[i].data = string_buffer; string_buffer += _values[i].size; } } } *read_bytes += buffer_size; return res; } ColumnReader::ColumnReader(uint32_t column_id, uint32_t column_unique_id) : _value_present(false), _is_null(NULL), _column_id(column_id), _column_unique_id(column_unique_id), _present_reader(NULL) { } ColumnReader* ColumnReader::create(uint32_t column_id, const std::vector<FieldInfo>& columns, const UniqueIdToColumnIdMap& included, UniqueIdToColumnIdMap& segment_included, const UniqueIdEncodingMap& encodings) { if (column_id >= columns.size()) { OLAP_LOG_WARNING("invalid column_id, column_id=%u, columns_size=%lu", column_id, columns.size()); return NULL; } const FieldInfo& field_info = columns[column_id]; ColumnReader* reader = NULL; uint32_t column_unique_id = field_info.unique_id; if (0 == included.count(column_unique_id)) { return NULL; } if (0 == segment_included.count(column_unique_id)) { if (field_info.has_default_value) { if (0 == strcasecmp("NULL", field_info.default_value.c_str()) && field_info.is_allow_null) { return new(std::nothrow) NullValueReader(column_id, column_unique_id); } else { return new(std::nothrow) DefaultValueReader(column_id, column_unique_id, field_info.default_value, field_info.type, field_info.length); } } else if (field_info.is_allow_null) { LOG(WARNING) << "create NullValueReader: " << field_info.name; return new(std::nothrow) NullValueReader(column_id, column_unique_id); } else { OLAP_LOG_WARNING("not null field has no default value"); return NULL; } } uint32_t dictionary_size = 0; ColumnEncodingMessage::Kind encode_kind = ColumnEncodingMessage::DIRECT; UniqueIdEncodingMap::const_iterator it = encodings.find(column_unique_id); if (it != encodings.end()) { encode_kind = (*it).second.kind(); dictionary_size = (*it).second.dictionary_size(); } switch (field_info.type) { case OLAP_FIELD_TYPE_TINYINT: case OLAP_FIELD_TYPE_UNSIGNED_TINYINT: { reader = new(std::nothrow) TinyColumnReader(column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_SMALLINT: { reader = new(std::nothrow) IntegerColumnReaderWrapper<int16_t, true>( column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_UNSIGNED_SMALLINT: { reader = new(std::nothrow) IntegerColumnReaderWrapper<uint16_t, false>( column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_INT: { reader = new(std::nothrow) IntegerColumnReaderWrapper<int32_t, true>( column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_UNSIGNED_INT: { reader = new(std::nothrow) IntegerColumnReaderWrapper<uint32_t, false>( column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_BIGINT: { reader = new(std::nothrow) IntegerColumnReaderWrapper<int64_t, true>( column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_UNSIGNED_BIGINT: { reader = new(std::nothrow) IntegerColumnReaderWrapper<uint64_t, false>( column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_FLOAT: { reader = new(std::nothrow) FloatColumnReader(column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_DOUBLE: { reader = new(std::nothrow) DoubleColumnReader(column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_DISCRETE_DOUBLE: { reader = new(std::nothrow) DiscreteDoubleColumnReader(column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_CHAR: { if (ColumnEncodingMessage::DIRECT == encode_kind) { reader = new(std::nothrow) FixLengthStringColumnReader<StringColumnDirectReader>( column_id, column_unique_id, field_info.length, dictionary_size); } else if (ColumnEncodingMessage::DICTIONARY == encode_kind) { reader = new(std::nothrow) FixLengthStringColumnReader<StringColumnDictionaryReader>( column_id, column_unique_id, field_info.length, dictionary_size); } else { OLAP_LOG_WARNING("known encoding format. data may be generated by higher version," "try updating olap/ngine binary to solve this problem"); // TODO. define a new return code return NULL; } break; } case OLAP_FIELD_TYPE_DATETIME: { reader = new(std::nothrow) DateTimeColumnReader(column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_DATE: { reader = new(std::nothrow) DateColumnReader(column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_DECIMAL: { reader = new(std::nothrow) DecimalColumnReader(column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_LARGEINT: { reader = new(std::nothrow) LargeIntColumnReader(column_id, column_unique_id); break; } case OLAP_FIELD_TYPE_VARCHAR: case OLAP_FIELD_TYPE_HLL: { if (ColumnEncodingMessage::DIRECT == encode_kind) { reader = new(std::nothrow) VarStringColumnReader<StringColumnDirectReader>( column_id, column_unique_id, field_info.length, dictionary_size); } else if (ColumnEncodingMessage::DICTIONARY == encode_kind) { reader = new(std::nothrow) VarStringColumnReader<StringColumnDictionaryReader>( column_id, column_unique_id, field_info.length, dictionary_size); } else { OLAP_LOG_WARNING("known encoding format. data may be generated by higher version, " "try updating olap/ngine binary to solve this problem"); // TODO. define a new return code return NULL; } break; } case OLAP_FIELD_TYPE_STRUCT: case OLAP_FIELD_TYPE_LIST: case OLAP_FIELD_TYPE_MAP: default: { LOG(WARNING) << "unspported filed type. [field=" << field_info.name << " type=" << field_info.type << "]"; break; } } if (NULL != reader) { std::vector<uint32_t>::const_iterator it; for (it = field_info.sub_columns.begin(); it != field_info.sub_columns.end(); ++it) { ColumnReader* sub_reader = create((*it), columns, included, segment_included, encodings); if (NULL == sub_reader) { OLAP_LOG_WARNING("fail to create sub column reader."); SAFE_DELETE(reader); return NULL; } reader->_sub_readers.push_back(sub_reader); } } return reader; } ColumnReader::~ColumnReader() { SAFE_DELETE(_present_reader); } OLAPStatus ColumnReader::init( std::map<StreamName, ReadOnlyFileStream*>* streams, int size, MemPool* mem_pool, OlapReaderStatistics* stats) { if (NULL == streams) { OLAP_LOG_WARNING("null parameters given."); return OLAP_ERR_INPUT_PARAMETER_ERROR; } _stats = stats; // 从map中找到需要的流,ColumnReader的数据应该由一条PRESENT流和一条ROW_INDEX流组成 ReadOnlyFileStream* present_stream = extract_stream(_column_unique_id, StreamInfoMessage::PRESENT, streams); _is_null = reinterpret_cast<bool*>(mem_pool->allocate(size)); memset(_is_null, 0, size); if (NULL == present_stream) { _present_reader = NULL; _value_present = false; } else { OLAP_LOG_DEBUG("create null present_stream for column_id: %d", _column_unique_id); _present_reader = new(std::nothrow) BitFieldReader(present_stream); if (NULL == _present_reader) { OLAP_LOG_WARNING("malloc present reader failed."); return OLAP_ERR_MALLOC_ERROR; } if (OLAP_SUCCESS != _present_reader->init()) { OLAP_LOG_WARNING("fail to init present reader."); return OLAP_ERR_INIT_FAILED; } _value_present = true; } return OLAP_SUCCESS; } OLAPStatus ColumnReader::seek(PositionProvider* position) { if (NULL != _present_reader) { return _present_reader->seek(position); } return OLAP_SUCCESS; } OLAPStatus ColumnReader::skip(uint64_t row_count) { return OLAP_SUCCESS; } OLAPStatus ColumnReader::next_vector( ColumnVector* column_vector, uint32_t size, MemPool* mem_pool) { OLAPStatus res = OLAP_SUCCESS; column_vector->set_is_null(_is_null); if (NULL != _present_reader) { column_vector->set_no_nulls(false); for (uint32_t i = 0; i < size; ++i) { bool value = false; res = _present_reader->next((char*)&value); if (OLAP_SUCCESS != res) { break; } _is_null[i] = value; } _stats->bytes_read += size; } else { column_vector->set_no_nulls(true); } return res; } uint64_t ColumnReader::_count_none_nulls(uint64_t rows) { if (_present_reader != NULL) { OLAPStatus res = OLAP_SUCCESS; uint64_t result = 0; for (uint64_t counter = 0; counter < rows; ++counter) { res = _present_reader->next(reinterpret_cast<char*>(&_value_present)); if (OLAP_SUCCESS == res && (false == _value_present)) { result += 1; } else { break; } } return result; } else { return rows; } } TinyColumnReader::TinyColumnReader(uint32_t column_id, uint32_t column_unique_id) : ColumnReader(column_id, column_unique_id), _eof(false), _values(NULL), _data_reader(NULL) {} TinyColumnReader::~TinyColumnReader() { SAFE_DELETE(_data_reader); } OLAPStatus TinyColumnReader::init( std::map<StreamName, ReadOnlyFileStream*>* streams, int size, MemPool* mem_pool, OlapReaderStatistics* stats) { if (NULL == streams) { OLAP_LOG_WARNING("input streams is NULL"); return OLAP_ERR_INPUT_PARAMETER_ERROR; } ColumnReader::init(streams, size, mem_pool, stats); ReadOnlyFileStream* data_stream = extract_stream(_column_unique_id, StreamInfoMessage::DATA, streams); if (NULL == data_stream) { OLAP_LOG_WARNING("specified stream not exist"); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } _values = reinterpret_cast<char*>(mem_pool->allocate(size)); _data_reader = new(std::nothrow) RunLengthByteReader(data_stream); if (NULL == _data_reader) { OLAP_LOG_WARNING("malloc data reader failed"); return OLAP_ERR_MALLOC_ERROR; } return OLAP_SUCCESS; } OLAPStatus TinyColumnReader::seek(PositionProvider* positions) { OLAPStatus res; if (NULL == _present_reader) { res = _data_reader->seek(positions); if (OLAP_SUCCESS != res) { return res; } } else { res = ColumnReader::seek(positions); if (OLAP_SUCCESS != res) { return res; } res = _data_reader->seek(positions); if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) { OLAP_LOG_WARNING("fail to seek tinyint stream. [res=%d]", res); return res; } } return OLAP_SUCCESS; } OLAPStatus TinyColumnReader::skip(uint64_t row_count) { // count_none_nulls 其实就是columnReader的跳过函数。 return _data_reader->skip(_count_none_nulls(row_count)); } OLAPStatus TinyColumnReader::next_vector( ColumnVector* column_vector, uint32_t size, MemPool* mem_pool) { OLAPStatus res = ColumnReader::next_vector(column_vector, size, mem_pool); if (OLAP_SUCCESS != res) { if (OLAP_ERR_DATA_EOF == res) { _eof = true; } return res; } bool* is_null = column_vector->is_null(); column_vector->set_col_data(_values); if (column_vector->no_nulls()) { for (uint32_t i = 0; i < size; ++i) { res = _data_reader->next(_values + i); if (OLAP_SUCCESS != res) { break; } } } else { for (uint32_t i = 0; i < size; ++i) { if (!is_null[i]) { res = _data_reader->next(_values + i); if (OLAP_SUCCESS != res) { break; } } } } _stats->bytes_read += size; if (OLAP_ERR_DATA_EOF == res) { _eof = true; } return res; } DecimalColumnReader::DecimalColumnReader(uint32_t column_id, uint32_t column_unique_id) : ColumnReader(column_id, column_unique_id), _eof(false), _values(NULL), _int_reader(NULL), _frac_reader(NULL) { } DecimalColumnReader::~DecimalColumnReader() { SAFE_DELETE(_int_reader); SAFE_DELETE(_frac_reader); } OLAPStatus DecimalColumnReader::init( std::map<StreamName, ReadOnlyFileStream*>* streams, int size, MemPool* mem_pool, OlapReaderStatistics* stats) { if (NULL == streams) { OLAP_LOG_WARNING("input streams is NULL"); return OLAP_ERR_INPUT_PARAMETER_ERROR; } // reset stream and reader ColumnReader::init(streams, size, mem_pool, stats); _values = reinterpret_cast<decimal12_t*>(mem_pool->allocate(size * sizeof(decimal12_t))); // 从map中找到需要的流,StringColumnReader的数据应该由一条DATA流和一条LENGTH流组成 ReadOnlyFileStream* int_stream = extract_stream(_column_unique_id, StreamInfoMessage::DATA, streams); if (NULL == int_stream) { OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } ReadOnlyFileStream* frac_stream = extract_stream(_column_unique_id, StreamInfoMessage::SECONDARY, streams); if (NULL == frac_stream) { OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } _int_reader = new(std::nothrow) RunLengthIntegerReader(int_stream, true); if (NULL == _int_reader) { OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader"); return OLAP_ERR_MALLOC_ERROR; } _frac_reader = new(std::nothrow) RunLengthIntegerReader(frac_stream, true); if (NULL == _frac_reader) { OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader"); return OLAP_ERR_MALLOC_ERROR; } return OLAP_SUCCESS; } OLAPStatus DecimalColumnReader::seek(PositionProvider* positions) { OLAPStatus res; if (NULL == _present_reader) { res = _int_reader->seek(positions); if (OLAP_SUCCESS != res) { return res; } res = _frac_reader->seek(positions); if (OLAP_SUCCESS != res) { return res; } } else { //all field in the segment can be NULL, so the data stream is EOF res = ColumnReader::seek(positions); if (OLAP_SUCCESS != res) { return res; } res = _int_reader->seek(positions); if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) { OLAP_LOG_WARNING("fail to seek int stream of decimal. [res=%d]", res); return res; } res = _frac_reader->seek(positions); if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) { OLAP_LOG_WARNING("fail to seek frac stream of decimal. [res=%d]", res); return res; } } return OLAP_SUCCESS; } OLAPStatus DecimalColumnReader::skip(uint64_t row_count) { OLAPStatus res = _int_reader->skip(row_count); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to create int part reader"); return res; } res = _frac_reader->skip(row_count); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to create frac part reader"); return res; } return OLAP_SUCCESS; } OLAPStatus DecimalColumnReader::next_vector( ColumnVector* column_vector, uint32_t size, MemPool* mem_pool) { OLAPStatus res = ColumnReader::next_vector(column_vector, size, mem_pool); if (OLAP_SUCCESS != res) { if (OLAP_ERR_DATA_EOF == res) { _eof = true; } return res; } bool* is_null = column_vector->is_null(); column_vector->set_col_data(_values); if (column_vector->no_nulls()) { for (uint32_t i = 0; i < size; ++i) { int64_t value = 0; OLAPStatus res = _int_reader->next(&value); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to read decimal int part"); break; } _values[i].integer = value; res = _frac_reader->next(&value); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to read decimal frac part"); break; } _values[i].fraction = value; } } else { for (uint32_t i = 0; i < size; ++i) { int64_t value = 0; if (!is_null[i]) { OLAPStatus res = _int_reader->next(&value); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to read decimal int part"); break; } _values[i].integer = value; res = _frac_reader->next(&value); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to read decimal frac part"); break; } _values[i].fraction = value; } } } _stats->bytes_read += sizeof(decimal12_t) * size; return res; } LargeIntColumnReader::LargeIntColumnReader(uint32_t column_id, uint32_t column_unique_id) : ColumnReader(column_id, column_unique_id), _eof(false), _values(NULL), _high_reader(NULL), _low_reader(NULL) {} LargeIntColumnReader::~LargeIntColumnReader() { SAFE_DELETE(_high_reader); SAFE_DELETE(_low_reader); } OLAPStatus LargeIntColumnReader::init( std::map<StreamName, ReadOnlyFileStream*>* streams, int size, MemPool* mem_pool, OlapReaderStatistics* stats) { if (NULL == streams) { OLAP_LOG_WARNING("input streams is NULL"); return OLAP_ERR_INPUT_PARAMETER_ERROR; } // reset stream and reader ColumnReader::init(streams, size, mem_pool, stats); _values = reinterpret_cast<int128_t*>( mem_pool->try_allocate_aligned(size * sizeof(int128_t), alignof(int128_t))); // 从map中找到需要的流,LargeIntColumnReader的数据应该由一条DATA流组成 ReadOnlyFileStream* high_stream = extract_stream(_column_unique_id, StreamInfoMessage::DATA, streams); if (NULL == high_stream) { OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } ReadOnlyFileStream* low_stream = extract_stream(_column_unique_id, StreamInfoMessage::SECONDARY, streams); if (NULL == low_stream) { OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]", _column_unique_id); return OLAP_ERR_COLUMN_STREAM_NOT_EXIST; } _high_reader = new(std::nothrow) RunLengthIntegerReader(high_stream, true); if (NULL == _high_reader) { OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader."); return OLAP_ERR_MALLOC_ERROR; } _low_reader = new(std::nothrow) RunLengthIntegerReader(low_stream, true); if (NULL == _low_reader) { OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader."); return OLAP_ERR_MALLOC_ERROR; } return OLAP_SUCCESS; } OLAPStatus LargeIntColumnReader::seek(PositionProvider* positions) { OLAPStatus res; if (NULL == _present_reader) { res = _high_reader->seek(positions); if (OLAP_SUCCESS != res) { return res; } res = _low_reader->seek(positions); if (OLAP_SUCCESS != res) { return res; } } else { //all field in the segment can be NULL, so the data stream is EOF res = ColumnReader::seek(positions); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to seek null stream of largeint"); return res; } res = _high_reader->seek(positions); if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) { OLAP_LOG_WARNING("fail to seek high int stream of largeint. [res=%d]", res); return res; } res = _low_reader->seek(positions); if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) { OLAP_LOG_WARNING("fail to seek low int stream of largeint. [res=%d]", res); return res; } } return OLAP_SUCCESS; } OLAPStatus LargeIntColumnReader::skip(uint64_t row_count) { OLAPStatus res = _high_reader->skip(row_count); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to skip large int high part. [res=%d]", res); return res; } res = _low_reader->skip(row_count); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to skip large int low part reader. [res=%d]", res); return res; } return OLAP_SUCCESS; } OLAPStatus LargeIntColumnReader::next_vector( ColumnVector* column_vector, uint32_t size, MemPool* mem_pool) { OLAPStatus res = ColumnReader::next_vector(column_vector, size, mem_pool); if (OLAP_SUCCESS != res) { if (OLAP_ERR_DATA_EOF == res) { _eof = true; } return res; } bool* is_null = column_vector->is_null(); column_vector->set_col_data(_values); if (column_vector->no_nulls()) { for (uint32_t i = 0; i < size; ++i) { int64_t* value = NULL; value = (int64_t*)(_values + i); res = _high_reader->next(value); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to read decimal int part"); break; } res = _low_reader->next(++value); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to read decimal frac part"); break; } } } else { for (uint32_t i = 0; i < size; ++i) { int64_t* value = NULL; if (!is_null[i]) { value = (int64_t*)(_values + i); res = _high_reader->next(value); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to read decimal int part"); break; } res = _low_reader->next(++value); if (OLAP_SUCCESS != res) { OLAP_LOG_WARNING("fail to read decimal frac part"); break; } } } } _stats->bytes_read += 16 * size; return res; } } // namespace doris
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 <gtest/gtest.h> #include <iostream> #include "hks_config.h" #include "hks_crypto_hal.h" #include "hks_crypto_hal_common.h" #include "hks_mem.h" using namespace testing::ext; namespace OHOS { namespace Security { namespace Huks { namespace UnitTest { class HksCryptoHalHmacKey : public HksCryptoHalCommon, public testing::Test {}; /** * @tc.number : HksCryptoHalHmacKey_001 * @tc.name : HksCryptoHalHmacKey_001 * @tc.desc : Using HksCryptoHalGenerateKey Generate HMAC-256bit key. */ HWTEST_F(HksCryptoHalHmacKey, HksCryptoHalHmacKey_001, Function | SmallTest | Level0) { int32_t ret; HksKeySpec spec = { .algType = HKS_ALG_HMAC, .keyLen = 256, .algParam = nullptr, }; HksBlob key = { .size = 0, .data = nullptr }; ret = HksCryptoHalGenerateKey(&spec, &key); #if defined(HKS_SUPPORT_HMAC_C) && defined(HKS_SUPPORT_HMAC_GENERATE_KEY) ASSERT_EQ(HKS_SUCCESS, ret); ASSERT_NE((uint32_t)0, key.size); ASSERT_NE(nullptr, key.data); HksFree(key.data); #else ASSERT_EQ(HKS_ERROR_NOT_SUPPORTED, ret); #endif } } // namespace UnitTest } // namespace Huks } // namespace Security } // namespace OHOS
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // Copyright (c) 2014-2018, The Monero Project // Copyright (c) 2018, The TurtleCoin Developers // // Please see the included LICENSE file for more information. #include "PaymentServiceJsonRpcServer.h" #include <functional> #include <CryptoTypes.h> #include "crypto/hash.h" #include "PaymentServiceJsonRpcMessages.h" #include "WalletService.h" #include "Serialization/JsonInputValueSerializer.h" #include "Serialization/JsonOutputStreamSerializer.h" #include "Rpc/JsonRpc.h" namespace PaymentService { PaymentServiceJsonRpcServer::PaymentServiceJsonRpcServer(System::Dispatcher& sys, System::Event& stopEvent, WalletService& service, Logging::ILogger& loggerGroup, PaymentService::Configuration& config) : JsonRpcServer(sys, stopEvent, loggerGroup, config) , service(service) , logger(loggerGroup, "PaymentServiceJsonRpcServer") { handlers.emplace("save", jsonHandler<Save::Request, Save::Response>(std::bind(&PaymentServiceJsonRpcServer::handleSave, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("export", jsonHandler<Export::Request, Export::Response>(std::bind(&PaymentServiceJsonRpcServer::handleExport, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("reset", jsonHandler<Reset::Request, Reset::Response>(std::bind(&PaymentServiceJsonRpcServer::handleReset, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("createAddress", jsonHandler<CreateAddress::Request, CreateAddress::Response>(std::bind(&PaymentServiceJsonRpcServer::handleCreateAddress, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("createAddressList", jsonHandler<CreateAddressList::Request, CreateAddressList::Response>(std::bind(&PaymentServiceJsonRpcServer::handleCreateAddressList, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("deleteAddress", jsonHandler<DeleteAddress::Request, DeleteAddress::Response>(std::bind(&PaymentServiceJsonRpcServer::handleDeleteAddress, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getSpendKeys", jsonHandler<GetSpendKeys::Request, GetSpendKeys::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetSpendKeys, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getBalance", jsonHandler<GetBalance::Request, GetBalance::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetBalance, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getBlockHashes", jsonHandler<GetBlockHashes::Request, GetBlockHashes::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetBlockHashes, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getTransactionHashes", jsonHandler<GetTransactionHashes::Request, GetTransactionHashes::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetTransactionHashes, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getTransactions", jsonHandler<GetTransactions::Request, GetTransactions::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetTransactions, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getUnconfirmedTransactionHashes", jsonHandler<GetUnconfirmedTransactionHashes::Request, GetUnconfirmedTransactionHashes::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetUnconfirmedTransactionHashes, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getTransaction", jsonHandler<GetTransaction::Request, GetTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetTransaction, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("sendTransaction", jsonHandler<SendTransaction::Request, SendTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleSendTransaction, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("createDelayedTransaction", jsonHandler<CreateDelayedTransaction::Request, CreateDelayedTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleCreateDelayedTransaction, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getDelayedTransactionHashes", jsonHandler<GetDelayedTransactionHashes::Request, GetDelayedTransactionHashes::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetDelayedTransactionHashes, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("deleteDelayedTransaction", jsonHandler<DeleteDelayedTransaction::Request, DeleteDelayedTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleDeleteDelayedTransaction, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("sendDelayedTransaction", jsonHandler<SendDelayedTransaction::Request, SendDelayedTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleSendDelayedTransaction, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getViewKey", jsonHandler<GetViewKey::Request, GetViewKey::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetViewKey, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getMnemonicSeed", jsonHandler<GetMnemonicSeed::Request, GetMnemonicSeed::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetMnemonicSeed, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getStatus", jsonHandler<GetStatus::Request, GetStatus::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetStatus, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getAddresses", jsonHandler<GetAddresses::Request, GetAddresses::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetAddresses, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("sendFusionTransaction", jsonHandler<SendFusionTransaction::Request, SendFusionTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleSendFusionTransaction, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("estimateFusion", jsonHandler<EstimateFusion::Request, EstimateFusion::Response>(std::bind(&PaymentServiceJsonRpcServer::handleEstimateFusion, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("createIntegratedAddress", jsonHandler<CreateIntegratedAddress::Request, CreateIntegratedAddress::Response>(std::bind(&PaymentServiceJsonRpcServer::handleCreateIntegratedAddress, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getFeeInfo", jsonHandler<NodeFeeInfo::Request, NodeFeeInfo::Response>(std::bind(&PaymentServiceJsonRpcServer::handleNodeFeeInfo, this, std::placeholders::_1, std::placeholders::_2))); handlers.emplace("getNodeFeeInfo", jsonHandler<NodeFeeInfo::Request, NodeFeeInfo::Response>(std::bind(&PaymentServiceJsonRpcServer::handleNodeFeeInfo, this, std::placeholders::_1, std::placeholders::_2))); } void PaymentServiceJsonRpcServer::processJsonRpcRequest(const Common::JsonValue& req, Common::JsonValue& resp) { try { prepareJsonResponse(req, resp); if (!config.legacySecurity) { std::string clientPassword; if (!req.contains("password")) { makeInvalidPasswordResponse(resp); return; } if (!req("password").isString()) { makeInvalidPasswordResponse(resp); return; } clientPassword = req("password").getString(); std::vector<uint8_t> rawData(clientPassword.begin(), clientPassword.end()); Crypto::Hash hashedPassword = Crypto::Hash(); cn_slow_hash_v0(rawData.data(), rawData.size(), hashedPassword); if (hashedPassword != config.rpcPassword) { makeInvalidPasswordResponse(resp); return; } } if (!req.contains("method")) { logger(Logging::WARNING) << "Field \"method\" is not found in json request: " << req; makeGenericErrorReponse(resp, "Invalid Request", -3600); return; } if (!req("method").isString()) { logger(Logging::WARNING) << "Field \"method\" is not a string type: " << req; makeGenericErrorReponse(resp, "Invalid Request", -3600); return; } std::string method = req("method").getString(); auto it = handlers.find(method); if (it == handlers.end()) { logger(Logging::WARNING) << "Requested method not found: " << method; makeMethodNotFoundResponse(resp); return; } logger(Logging::DEBUGGING) << method << " request came"; Common::JsonValue params(Common::JsonValue::OBJECT); if (req.contains("params")) { params = req("params"); } it->second(params, resp); } catch (std::exception& e) { logger(Logging::WARNING) << "Error occurred while processing JsonRpc request: " << e.what(); makeGenericErrorReponse(resp, e.what()); } } std::error_code PaymentServiceJsonRpcServer::handleSave(const Save::Request& /*request*/, Save::Response& /*response*/) { return service.saveWalletNoThrow(); } std::error_code PaymentServiceJsonRpcServer::handleExport(const Export::Request& request, Export::Response& /*response*/) { return service.exportWallet(request.fileName); } std::error_code PaymentServiceJsonRpcServer::handleReset(const Reset::Request& request, Reset::Response& response) { if (request.viewSecretKey.empty()) { return service.resetWallet(request.scanHeight); } else { return service.replaceWithNewWallet(request.viewSecretKey, request.scanHeight, request.newAddress); } } std::error_code PaymentServiceJsonRpcServer::handleCreateAddress(const CreateAddress::Request& request, CreateAddress::Response& response) { if (request.spendSecretKey.empty() && request.spendPublicKey.empty()) { return service.createAddress(response.address); } else if (!request.spendSecretKey.empty()) { return service.createAddress(request.spendSecretKey, request.scanHeight, request.newAddress, response.address); } else { return service.createTrackingAddress(request.spendPublicKey, request.scanHeight, request.newAddress, response.address); } } std::error_code PaymentServiceJsonRpcServer::handleCreateAddressList(const CreateAddressList::Request& request, CreateAddressList::Response& response) { return service.createAddressList(request.spendSecretKeys, request.scanHeight, request.newAddress, response.addresses); } std::error_code PaymentServiceJsonRpcServer::handleDeleteAddress(const DeleteAddress::Request& request, DeleteAddress::Response& response) { return service.deleteAddress(request.address); } std::error_code PaymentServiceJsonRpcServer::handleGetSpendKeys(const GetSpendKeys::Request& request, GetSpendKeys::Response& response) { return service.getSpendkeys(request.address, response.spendPublicKey, response.spendSecretKey); } std::error_code PaymentServiceJsonRpcServer::handleGetBalance(const GetBalance::Request& request, GetBalance::Response& response) { if (!request.address.empty()) { return service.getBalance(request.address, response.availableBalance, response.lockedAmount); } else { return service.getBalance(response.availableBalance, response.lockedAmount); } } std::error_code PaymentServiceJsonRpcServer::handleGetBlockHashes(const GetBlockHashes::Request& request, GetBlockHashes::Response& response) { return service.getBlockHashes(request.firstBlockIndex, request.blockCount, response.blockHashes); } std::error_code PaymentServiceJsonRpcServer::handleGetTransactionHashes(const GetTransactionHashes::Request& request, GetTransactionHashes::Response& response) { if (!request.blockHash.empty()) { return service.getTransactionHashes(request.addresses, request.blockHash, request.blockCount, request.paymentId, response.items); } else { return service.getTransactionHashes(request.addresses, request.firstBlockIndex, request.blockCount, request.paymentId, response.items); } } std::error_code PaymentServiceJsonRpcServer::handleGetTransactions(const GetTransactions::Request& request, GetTransactions::Response& response) { if (!request.blockHash.empty()) { return service.getTransactions(request.addresses, request.blockHash, request.blockCount, request.paymentId, response.items); } else { return service.getTransactions(request.addresses, request.firstBlockIndex, request.blockCount, request.paymentId, response.items); } } std::error_code PaymentServiceJsonRpcServer::handleGetUnconfirmedTransactionHashes(const GetUnconfirmedTransactionHashes::Request& request, GetUnconfirmedTransactionHashes::Response& response) { return service.getUnconfirmedTransactionHashes(request.addresses, response.transactionHashes); } std::error_code PaymentServiceJsonRpcServer::handleGetTransaction(const GetTransaction::Request& request, GetTransaction::Response& response) { return service.getTransaction(request.transactionHash, response.transaction); } std::error_code PaymentServiceJsonRpcServer::handleSendTransaction(SendTransaction::Request& request, SendTransaction::Response& response) { return service.sendTransaction(request, response.transactionHash); } std::error_code PaymentServiceJsonRpcServer::handleCreateDelayedTransaction(const CreateDelayedTransaction::Request& request, CreateDelayedTransaction::Response& response) { return service.createDelayedTransaction(request, response.transactionHash); } std::error_code PaymentServiceJsonRpcServer::handleGetDelayedTransactionHashes(const GetDelayedTransactionHashes::Request& request, GetDelayedTransactionHashes::Response& response) { return service.getDelayedTransactionHashes(response.transactionHashes); } std::error_code PaymentServiceJsonRpcServer::handleDeleteDelayedTransaction(const DeleteDelayedTransaction::Request& request, DeleteDelayedTransaction::Response& response) { return service.deleteDelayedTransaction(request.transactionHash); } std::error_code PaymentServiceJsonRpcServer::handleSendDelayedTransaction(const SendDelayedTransaction::Request& request, SendDelayedTransaction::Response& response) { return service.sendDelayedTransaction(request.transactionHash); } std::error_code PaymentServiceJsonRpcServer::handleGetViewKey(const GetViewKey::Request& request, GetViewKey::Response& response) { return service.getViewKey(response.viewSecretKey); } std::error_code PaymentServiceJsonRpcServer::handleGetMnemonicSeed(const GetMnemonicSeed::Request& request, GetMnemonicSeed::Response& response) { return service.getMnemonicSeed(request.address, response.mnemonicSeed); } std::error_code PaymentServiceJsonRpcServer::handleGetStatus(const GetStatus::Request& request, GetStatus::Response& response) { return service.getStatus(response.blockCount, response.knownBlockCount, response.localDaemonBlockCount, response.lastBlockHash, response.peerCount); } std::error_code PaymentServiceJsonRpcServer::handleGetAddresses(const GetAddresses::Request& request, GetAddresses::Response& response) { return service.getAddresses(response.addresses); } std::error_code PaymentServiceJsonRpcServer::handleSendFusionTransaction(const SendFusionTransaction::Request& request, SendFusionTransaction::Response& response) { return service.sendFusionTransaction(request.threshold, request.anonymity, request.addresses, request.destinationAddress, response.transactionHash); } std::error_code PaymentServiceJsonRpcServer::handleEstimateFusion(const EstimateFusion::Request& request, EstimateFusion::Response& response) { return service.estimateFusion(request.threshold, request.addresses, response.fusionReadyCount, response.totalOutputCount); } std::error_code PaymentServiceJsonRpcServer::handleCreateIntegratedAddress(const CreateIntegratedAddress::Request& request, CreateIntegratedAddress::Response& response) { return service.createIntegratedAddress(request.address, request.paymentId, response.integratedAddress); } std::error_code PaymentServiceJsonRpcServer::handleNodeFeeInfo(const NodeFeeInfo::Request& request, NodeFeeInfo::Response& response) { return service.getFeeInfo(response.address, response.amount); } }
#include "mxCommonPopup.h" #include "mxUtils.h" #include "mxLongTextEditor.h" #include "mxEnumerationEditor.h" #include "mxThreeDotsUtils.h" void mxCommonPopup::ProcessCommandEvent(wxCommandEvent &evt) { if (!m_text_ctrl && !m_combo_box) return; switch (evt.GetId()) { case mxID_POPUPS_EDIT_AS_TEXT: if (m_text_ctrl) mxLongTextEditor(m_parent,m_caption,m_text_ctrl); else mxLongTextEditor(m_parent,m_caption,m_combo_box); return; case mxID_POPUPS_EDIT_AS_LIST: if (m_text_ctrl) mxEnumerationEditor(m_parent,m_caption,m_text_ctrl,m_comma_split); else mxEnumerationEditor(m_parent,m_caption,m_text_ctrl,m_combo_box); return; case mxID_POPUPS_INSERT_FILE: if (m_text_ctrl) mxThreeDotsUtils::ReplaceSelectionWithFile(m_parent,m_text_ctrl,m_base_path); else mxThreeDotsUtils::ReplaceSelectionWithFile(m_parent,m_combo_box,m_base_path); return; case mxID_POPUPS_INSERT_DIR: if (m_text_ctrl) mxThreeDotsUtils::ReplaceSelectionWithDirectory(m_parent,m_text_ctrl,m_base_path); else mxThreeDotsUtils::ReplaceSelectionWithDirectory(m_parent,m_combo_box,m_base_path); return; case mxID_POPUPS_INSERT_MINGW_DIR: ReplaceSelectionWith("${MINGW_DIR}"); return; case mxID_POPUPS_INSERT_TEMP_DIR: ReplaceSelectionWith("${TEMP_DIR}"); return; case mxID_POPUPS_INSERT_BROWSER: ReplaceSelectionWith("${BROWSER}"); return; case mxID_POPUPS_INSERT_SHELL_EXECUTE: ReplaceSelectionWith("${OPEN}"); return; case mxID_POPUPS_INSERT_PROJECT_PATH: ReplaceSelectionWith("${PROJECT_PATH}"); return; case mxID_POPUPS_INSERT_WORKDIR: ReplaceSelectionWith("${BIN_WORKDIR}"); return; case mxID_POPUPS_INSERT_PROJECT_BIN: ReplaceSelectionWith("${PROJECT_BIN}"); return; case mxID_POPUPS_INSERT_ARGS: ReplaceSelectionWith("${ARGS}"); return; case mxID_POPUPS_INSERT_ZINJAI_DIR: ReplaceSelectionWith("${ZINJAI_DIR}"); return; case mxID_POPUPS_INSERT_CURRENT_FILE: ReplaceSelectionWith("${CURRENT_SOURCE}"); return; case mxID_POPUPS_INSERT_CURRENT_DIR: ReplaceSelectionWith("${CURRENT_DIR}"); return; case mxID_POPUPS_INSERT_OUTPUT: ReplaceSelectionWith("${OUTPUT}"); return; case mxID_POPUPS_INSERT_DEPS: ReplaceSelectionWith("${DEPS}"); return; } }
class Solution { public: int findMin(vector<int>& nums) { int start = 0; int end = nums.size() - 1; while(start + 1 < end) { int mid = start + (end - start) / 2; if (nums[mid] > nums[end]) { start = mid; } else if (nums[mid] < nums[end]) { end = mid; } else { end--; } } return min(nums[start], nums[end]); } };
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtWidgets module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsystemtrayicon_p.h" #ifndef QT_NO_SYSTEMTRAYICON #define _WIN32_IE 0x0600 //required for NOTIFYICONDATA_V2_SIZE #include <qt_windows.h> #include <shlwapi.h> #include <QApplication> QT_BEGIN_NAMESPACE static const UINT q_uNOTIFYICONID = 13; // IDs from 0 to 12 are reserved on WinCE. #define MYWM_NOTIFYICON (WM_APP+101) struct Q_NOTIFYICONIDENTIFIER { DWORD cbSize; HWND hWnd; UINT uID; GUID guidItem; }; class QSystemTrayIconSys : QWidget { public: QSystemTrayIconSys(QSystemTrayIcon *object); ~QSystemTrayIconSys(); bool winEvent( MSG *m, long *result ); bool trayMessage(DWORD msg); void setIconContents(NOTIFYICONDATA &data); void createIcon(); QRect findTrayGeometry(); HICON hIcon; QPoint globalPos; QSystemTrayIcon *q; private: uint notifyIconSize; int maxTipLength; bool ignoreNextMouseRelease; }; QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *object) : hIcon(0), q(object), ignoreNextMouseRelease(false) { notifyIconSize = FIELD_OFFSET(NOTIFYICONDATA, szTip[64]); // NOTIFYICONDATAW_V1_SIZE; maxTipLength = 64; } QSystemTrayIconSys::~QSystemTrayIconSys() { if (hIcon) DestroyIcon(hIcon); } QRect QSystemTrayIconSys::findTrayGeometry() { // Use lower right corner as fallback QPoint brCorner = qApp->desktop()->screenGeometry().bottomRight(); QRect ret(brCorner.x() - 10, brCorner.y() - 10, 10, 10); return ret; } void QSystemTrayIconSys::setIconContents(NOTIFYICONDATA &tnd) { tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; tnd.uCallbackMessage = MYWM_NOTIFYICON; tnd.hIcon = hIcon; QString tip = q->toolTip(); if (!tip.isNull()) { tip = tip.left(maxTipLength - 1) + QChar(); memcpy(tnd.szTip, tip.utf16(), qMin(tip.length() + 1, maxTipLength) * sizeof(wchar_t)); } } bool QSystemTrayIconSys::trayMessage(DWORD msg) { NOTIFYICONDATA tnd; memset(&tnd, 0, notifyIconSize); tnd.uID = q_uNOTIFYICONID; tnd.cbSize = notifyIconSize; tnd.hWnd = winId(); Q_ASSERT(testAttribute(Qt::WA_WState_Created)); if (msg != NIM_DELETE) { setIconContents(tnd); } return Shell_NotifyIcon(msg, &tnd); } void QSystemTrayIconSys::createIcon() { hIcon = 0; QIcon icon = q->icon(); if (icon.isNull()) return; //const QSize preferredSize(GetSystemMetrics(SM_CXSMICON) * 2, GetSystemMetrics(SM_CYSMICON) * 2); const QSize preferredSize(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON)); QPixmap pm = icon.pixmap(preferredSize); if (pm.isNull()) return; hIcon = pm.toWinHICON(); } bool QSystemTrayIconSys::winEvent( MSG *m, long *result ) { switch(m->message) { case WM_CREATE: SetWindowLong(winId(), GWL_USERDATA, (LONG)((CREATESTRUCTW*)m->lParam)->lpCreateParams); break; case MYWM_NOTIFYICON: { QPoint gpos = QCursor::pos(); switch (m->lParam) { case WM_LBUTTONUP: if (ignoreNextMouseRelease) ignoreNextMouseRelease = false; else emit q->activated(QSystemTrayIcon::Trigger); break; case WM_LBUTTONDBLCLK: ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse // release we must ignore it emit q->activated(QSystemTrayIcon::DoubleClick); break; case WM_RBUTTONUP: if (q->contextMenu()) { q->contextMenu()->popup(gpos); // We must ensure that the popup menu doesn't show up behind the task bar. QRect desktopRect = qApp->desktop()->availableGeometry(); int maxY = desktopRect.y() + desktopRect.height() - q->contextMenu()->height(); if (gpos.y() > maxY) { gpos.ry() = maxY; q->contextMenu()->move(gpos); } } emit q->activated(QSystemTrayIcon::Context); break; case WM_MBUTTONUP: emit q->activated(QSystemTrayIcon::MiddleClick); break; default: break; } break; } default: return QWidget::winEvent(m, result); } return 0; } QSystemTrayIconPrivate::QSystemTrayIconPrivate() : sys(0), visible(false) { } QSystemTrayIconPrivate::~QSystemTrayIconPrivate() { } void QSystemTrayIconPrivate::install_sys() { Q_Q(QSystemTrayIcon); if (!sys) { sys = new QSystemTrayIconSys(q); sys->createIcon(); sys->trayMessage(NIM_ADD); } } void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, int timeOut) { if (!sys) return; uint uSecs = 0; if ( timeOut < 0) uSecs = 10000; //10 sec default else uSecs = (int)timeOut; //message is limited to 255 chars + NULL QString messageString; if (message.isEmpty() && !title.isEmpty()) messageString = QLatin1Char(' '); //ensures that the message shows when only title is set else messageString = message.left(255) + QChar(); //title is limited to 63 chars + NULL QString titleString = title.left(63) + QChar(); //show QBalloonTip QRect trayRect = sys->findTrayGeometry(); QBalloonTip::showBalloon(type, title, message, sys->q, QPoint(trayRect.left(), trayRect.center().y()), uSecs, false); } QRect QSystemTrayIconPrivate::geometry_sys() const { return QRect(); } void QSystemTrayIconPrivate::remove_sys() { if (!sys) return; sys->trayMessage(NIM_DELETE); delete sys; sys = 0; } void QSystemTrayIconPrivate::updateIcon_sys() { if (!sys) return; HICON hIconToDestroy = sys->hIcon; sys->createIcon(); sys->trayMessage(NIM_MODIFY); if (hIconToDestroy) DestroyIcon(hIconToDestroy); } void QSystemTrayIconPrivate::updateMenu_sys() { } void QSystemTrayIconPrivate::updateToolTip_sys() { // Calling sys->trayMessage(NIM_MODIFY) on an existing icon is broken on Windows CE. // So we need to call updateIcon_sys() which creates a new icon handle. updateIcon_sys(); } bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys() { return true; } bool QSystemTrayIconPrivate::supportsMessages_sys() { return true; } QT_END_NAMESPACE #endif
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2019 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 "NFRedisClient.h" void NFRedisClient::FLUSHALL() { NFRedisCommand cmd(GET_NAME(FLUSHALL)); NF_SHARE_PTR<redisReply> pReply = BuildSendCmd(cmd); if (pReply != nullptr) { } } void NFRedisClient::FLUSHDB() { NFRedisCommand cmd(GET_NAME(FLUSHDB)); NF_SHARE_PTR<redisReply> pReply = BuildSendCmd(cmd); if (pReply != nullptr) { } }
#include <iostream> #include "dyncycles.h" using namespace std; struct Elem: public Object { Elem* next; Elem* next2; string name; Elem(string name):Object() { this->name = name; } ~Elem() override { cout << "delete " << name << endl; lshared_release_single((Object**)&next); lshared_release_single((Object**)&next2); } }; void CycleInMiddle() { Shadow shadow; Elem* A = new Elem("A"); Elem* B = new Elem("B"); Elem* C = new Elem("C"); Elem* D = new Elem("D"); Elem* E = new Elem("E"); //A->next = B; link_assign(A,&shadow,(Object**)&A->next, B); //B->next = C; link_assign(B,&shadow,(Object**)&B->next, C); //C->next = D; link_assign(C,&shadow,(Object**)&C->next, D); //C->next2 = E; link_assign(C,&shadow,(Object**)&C->next2, E); //D->next = B; //cycle link_assign(D,&shadow,(Object**)&D->next, B); try_release(&shadow, E); try_release(&shadow, D); try_release(&shadow, C); try_release(&shadow, B); try_release(&shadow, A); } void JoinTwo() { Elem* A = new Elem("A"); Elem* B = new Elem("B"); Elem* C = new Elem("C"); Elem* D = new Elem("D"); Elem* E = new Elem("E"); Elem* F = new Elem("F"); Shadow shadow; link_assign(A,&shadow,(Object**)&A->next, B); link_assign(B,&shadow,(Object**)&B->next, F); link_assign(C,&shadow,(Object**)&C->next, D); link_assign(C,&shadow,(Object**)&C->next2, E); link_assign(D,&shadow,(Object**)&D->next, B); try_release(&shadow, F); try_release(&shadow, E); try_release(&shadow, D); try_release(&shadow, C); try_release(&shadow, B); try_release(&shadow, A); } void JoinTwo2() { Elem* A = new Elem("A"); Elem* B = new Elem("B"); Elem* C = new Elem("C"); Elem* D = new Elem("D"); Elem* E = new Elem("E"); Elem* F = new Elem("F"); Shadow shadow; link_assign(A,&shadow,(Object**)&A->next, B); link_assign(B,&shadow,(Object**)&B->next, F); link_assign(C,&shadow,(Object**)&C->next, D); link_assign(C,&shadow,(Object**)&C->next2, E); link_assign(B,&shadow,(Object**)&B->next2, D); try_release(&shadow, F); try_release(&shadow, E); try_release(&shadow, D); try_release(&shadow, C); try_release(&shadow, B); try_release(&shadow, A); } void JoinTwo3() { Elem* A = new Elem("A"); Elem* B = new Elem("B"); Elem* C = new Elem("C"); Elem* D = new Elem("D"); Elem* E = new Elem("E"); Elem* F = new Elem("F"); Shadow shadow; link_assign(A,&shadow,(Object**)&A->next, B); link_assign(B,&shadow,(Object**)&B->next, F); link_assign(C,&shadow,(Object**)&C->next, D); link_assign(C,&shadow,(Object**)&C->next2, E); link_assign(B,&shadow,(Object**)&B->next2, C); try_release(&shadow, F); try_release(&shadow, E); try_release(&shadow, D); try_release(&shadow, C); try_release(&shadow, B); try_release(&shadow, A); } //first building first graph, next second graph //we divide first to half, first half of first is joined to second graph void SplitAndJoin() { Elem* A = new Elem("A"); Elem* B = new Elem("B"); Elem* C = new Elem("C"); Elem* D = new Elem("D"); Elem* E = new Elem("E"); Elem* F = new Elem("F"); Shadow shadow; link_assign(A,&shadow,(Object**)&A->next, B); link_assign(B,&shadow,(Object**)&B->next, C); link_assign(C,&shadow,(Object**)&C->next, D); link_assign(E,&shadow,(Object**)&E->next, F); //split nand join link_assign(B,&shadow,(Object**)&B->next, nullptr);//z gtym czy bez gtego nie powinno być różnicy link_assign(B,&shadow,(Object**)&B->next, E); try_release(&shadow, F); try_release(&shadow, E); try_release(&shadow, D); try_release(&shadow, C); try_release(&shadow, B); try_release(&shadow, A); } //tutaj trudne, nie ma nawet pojedynczego roota (ale lista rootow) void GroupToOne() { Elem* A = new Elem("A"); Elem* B = new Elem("B"); Elem* C = new Elem("C"); Elem* D = new Elem("D"); Elem* E = new Elem("E"); Elem* F = new Elem("F"); Shadow shadow; link_assign(A,&shadow,(Object**)&A->next, D); link_assign(B,&shadow,(Object**)&B->next, D); link_assign(C,&shadow,(Object**)&C->next, D); //cycle link_assign(D,&shadow,(Object**)&D->next, E); link_assign(E,&shadow,(Object**)&E->next, F); link_assign(F,&shadow,(Object**)&F->next, D); try_release(&shadow, F); try_release(&shadow, E); try_release(&shadow, D); try_release(&shadow, C); try_release(&shadow, B); try_release(&shadow, A); } void ApartmentLike() { Shadow shadow; Elem* A = new Elem("Apartment"); Elem* B = new Elem("Person"); link_assign(A,&shadow,(Object**)&A->next, B); link_assign(B,&shadow,(Object**)&B->next, A); //here A can't be at beginning releasedd when B is not released //bacause A is root cout << "przed user null" <<endl; var_assign(&shadow, (Object**)&A, nullptr); cout << "po user null" <<endl; try_release(&shadow, B); cout << "przed nie, po zwalnianie" <<endl; try_release(&shadow, A); //try_release(&shadow, tmp); } struct MstEdge { int from; int to; bool shared; }; const MstEdge mst_edges[] = {{0, 1, true}, {0, 2, true}, {2, 4, true}, {4, 0, false}, {4, 1, false}, {1, 3, true}, {3, 0, false}, {4, 5, true}, {4, 6, true}, {6, 7, true}, {6, 2, false}, {5, 6, false}, {6, 8, true}, {8, 9, true}, {8, 7, false}, {9, 5, false}}; struct Vertex: public Object { int id; Vertex(int id) { this->id = id; } Vertex* p0 = nullptr; Vertex* p1 = nullptr; Vertex* p2 = nullptr; Vertex* p3 = nullptr; ~Vertex() override { //cout << "delete " << id << endl; lshared_release_single((Object**)&p0); lshared_release_single((Object**)&p1); lshared_release_single((Object**)&p2); lshared_release_single((Object**)&p3); } }; static void buildMst() { Vertex* v0 = new Vertex(0); Vertex* v1 = new Vertex(1); Vertex* v2 = new Vertex(2); Vertex* v3 = new Vertex(3); Vertex* v4 = new Vertex(4); Vertex* v5 = new Vertex(5); Vertex* v6 = new Vertex(6); Vertex* v7 = new Vertex(7); Vertex* v8 = new Vertex(8); Vertex* v9 = new Vertex(9); Shadow shadow; //link_assign(E,&shadow,(Object**)&E->next, F); //cout << "will shared for " << v1->ref_count << " so "<<0<<"->" <<1 << endl; link_assign(v0 , &shadow, (Object**)&v0->p0, v1); //cout << "will shared for " << v2->ref_count << " so "<<0<<"->" <<2 << endl; link_assign(v0 , &shadow, (Object**)&v0->p1, v2); //cout << "will shared for " << v4->ref_count << " so "<<2<<"->" <<4 << endl; link_assign(v2 , &shadow, (Object**)&v2->p0, v4); //cout << "will weak for " << v0->ref_count << " so "<<4<<"->" <<0 << endl; link_assign(v4 , &shadow, (Object**)&v4->p0, v0); //cout << "will weak for " << v1->ref_count << " so "<<4<<"->" <<1 << endl; link_assign(v4 , &shadow, (Object**)&v4->p1, v1); //cout << "will shared for " << v3->ref_count << " so "<<1<<"->" <<3 << endl; link_assign(v1 , &shadow, (Object**)&v1->p0, v3); //cout << "will weak for " << v0->ref_count << " so "<<3<<"->" <<0 << endl; link_assign(v3 , &shadow, (Object**)&v3->p0, v0); //cout << "will shared for " << v5->ref_count << " so "<<4<<"->" <<5 << endl; link_assign(v4 , &shadow, (Object**)&v4->p2, v5); //cout << "will shared for " << v6->ref_count << " so "<<4<<"->" <<6 << endl; link_assign(v4 , &shadow, (Object**)&v4->p3, v6); //cout << "will shared for " << v7->ref_count << " so "<<6<<"->" <<7 << endl; link_assign(v6 , &shadow, (Object**)&v6->p0, v7); //cout << "will weak for " << v2->ref_count << " so "<<6<<"->" <<2 << endl; link_assign(v6 , &shadow, (Object**)&v6->p1, v2); //cout << "will weak for " << v6->ref_count << " so "<<5<<"->" <<6 << endl; link_assign(v5 , &shadow, (Object**)&v5->p0, v6); //cout << "will shared for " << v8->ref_count << " so "<<6<<"->" <<8 << endl; link_assign(v6 , &shadow, (Object**)&v6->p2, v8); //cout << "will shared for " << v9->ref_count << " so "<<8<<"->" <<9 << endl; link_assign(v8 , &shadow, (Object**)&v8->p0, v9); //cout << "will weak for " << v7->ref_count << " so "<<8<<"->" <<7 << endl; link_assign(v8 , &shadow, (Object**)&v8->p1, v7); //cout << "will weak for " << v5->ref_count << " so "<<9<<"->" <<5 << endl; link_assign(v9 , &shadow, (Object**)&v9->p0, v5); try_release(&shadow, v9); try_release(&shadow, v8); try_release(&shadow, v7); try_release(&shadow, v6); try_release(&shadow, v5); try_release(&shadow, v4); try_release(&shadow, v3); try_release(&shadow, v2); try_release(&shadow, v1); // cout << "before this should not delete, after delete all 10" << endl; try_release(&shadow, v0); } void DoubleOneDirection() { for (int i=0; i<2; i++) { Shadow shadow; Elem *A = new Elem("A"); Elem *B = new Elem("B"); link_assign(A, &shadow, (Object **) &A->next, B); link_assign(A, &shadow, (Object **) &A->next2, B); if (i==0) { try_release(&shadow, B); try_release(&shadow, A); } else { try_release(&shadow, A); try_release(&shadow, B); } } } int main() { DoubleOneDirection(); return 1; ApartmentLike(); cout << "=========================CycleInMiddle\n"; CycleInMiddle(); cout << "=========================JoinTwo\n"; JoinTwo(); cout << "=========================JoinTwo2\n"; JoinTwo2(); cout << "=========================JoinTwo3\n"; JoinTwo3(); cout << "=========================SplitAndJoin\n"; SplitAndJoin(); cout << "=========================GroupToOne\n"; GroupToOne(); return 0; }
#include <Common/Exception.h> #include <Columns/ColumnsNumber.h> #include <DataTypes/DataTypesNumber.h> #include <DataStreams/IProfilingBlockInputStream.h> #include <DataStreams/LimitBlockInputStream.h> #include <Storages/System/StorageSystemNumbers.h> namespace DB { class NumbersBlockInputStream : public IProfilingBlockInputStream { public: NumbersBlockInputStream(size_t block_size_, size_t offset_, size_t step_) : block_size(block_size_), next(offset_), step(step_) {} String getName() const { return "Numbers"; } String getID() const { return "Numbers"; } protected: Block readImpl() { auto column = ColumnUInt64::create(block_size); ColumnUInt64::Container & vec = column->getData(); size_t curr = next; /// The local variable for some reason works faster (>20%) than member of class. UInt64 * pos = &vec[0]; /// This also accelerates the code. UInt64 * end = &vec[block_size]; while (pos < end) *pos++ = curr++; next += step; return { ColumnWithTypeAndName(std::move(column), std::make_shared<DataTypeUInt64>(), "number") }; } private: size_t block_size; UInt64 next; UInt64 step; }; StorageSystemNumbers::StorageSystemNumbers(const std::string & name_, bool multithreaded_, size_t limit_) : name(name_), columns{{"number", std::make_shared<DataTypeUInt64>()}}, multithreaded(multithreaded_), limit(limit_) { } BlockInputStreams StorageSystemNumbers::read( const Names & column_names, const SelectQueryInfo &, const Context &, QueryProcessingStage::Enum & processed_stage, size_t max_block_size, unsigned num_streams) { check(column_names); processed_stage = QueryProcessingStage::FetchColumns; if (limit && limit < max_block_size) { max_block_size = std::min(max_block_size, limit); multithreaded = false; } if (!multithreaded) num_streams = 1; BlockInputStreams res(num_streams); for (size_t i = 0; i < num_streams; ++i) { res[i] = std::make_shared<NumbersBlockInputStream>(max_block_size, i * max_block_size, num_streams * max_block_size); if (limit) /// This formula is how to split 'limit' elements to 'num_streams' chunks almost uniformly. res[i] = std::make_shared<LimitBlockInputStream>(res[i], limit * (i + 1) / num_streams - limit * i / num_streams, 0); } return res; } }
/* * Copyright 2015, alex at staticlibs.net * * 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: field.hpp * Author: alex * * Created on April 9, 2017, 11:58 AM */ #ifndef STATICLIB_JSON_FIELD_HPP #define STATICLIB_JSON_FIELD_HPP #include <cstdint> #include <string> #include <vector> #include "staticlib/config.hpp" #include "staticlib/json/value.hpp" namespace staticlib { namespace json { /** * Representation of the reflected object field. Implemented as `name, value` tuple. * This class mimics `value` methods like `as_array` to access field value directly * from this object without intermediate `value()` call. */ class field { std::string field_name; value field_value; public: /** * Deleted copy constructor * * @param other deleted */ field(const field& other) = delete; /** * Deleted copy assignment operator * * @param other deleted */ field& operator=(const field& other) = delete; /** * Move constructor * * @param other other value */ field(field&& other) STATICLIB_NOEXCEPT; /** * Move assignment operator * * @param other other value */ field& operator=(field&& other) STATICLIB_NOEXCEPT; /** * Default constructor */ field(); /** * Constructor * * @param name field name * @param value field value */ field(std::string name, value json_value); /** * Constructor * * @param name field name * @param value field value */ field(const char* name, value json_value); /** * Field name accessor * * @return field name */ const std::string& name() const; /** * Returns type of the value in this field * * @return type type of the value in this field */ type json_type() const; /** * Field value accessor * * @return field value */ const value& val() const; /** * Field value accessor * * @return field value */ value& val(); /** * Field value mutator * * @param value new value */ void set_value(value&& value); /** * Explicit deep-copy method * * @return deep copy of current instance */ field clone() const; /** * Access value as an `OBJECT` * * @return list of `name->value` pairs */ const std::vector<field>& as_object() const; /** * Access value as a mutable `OBJECT` * If this value is not an `OBJECT`: "serialization_exception" will be thrown. * * @return list of `name->value` pairs */ std::vector<field>& as_object_or_throw(const std::string& context = ""); /** * Access value as a mutable `OBJECT` * If this value is not an `OBJECT`: "serialization_exception" will be thrown. * * @return list of `name->value` pairs */ const std::vector<field>& as_object_or_throw(const std::string& context = "") const; /** * Access value as an `ARRAY` * * @return list of values */ const std::vector<value>& as_array() const; /** * Access value as a mutable `ARRAY` * If this value is not an `ARRAY`: "serialization_exception" will be thrown. * * @return list of values */ std::vector<value>& as_array_or_throw(const std::string& context = ""); /** * Access value as a mutable `ARRAY` * If this value is not an `ARRAY`: "serialization_exception" will be thrown. * * @return list of values */ const std::vector<value>& as_array_or_throw(const std::string& context = "") const; /** * Access value as an `STRING` * * @return string value */ const std::string& as_string() const; /** * Access value as an `STRING` * If this value is not a `STRING`: "serialization_exception" will be thrown. * * @return string value */ std::string& as_string_or_throw(const std::string& context = ""); /** * Access value as an `STRING` * If this value is not a `STRING`: "serialization_exception" will be thrown. * * @return string value */ const std::string& as_string_or_throw(const std::string& context = "") const; /** * Access value as non-empty `STRING` * If this value is not a non-empty `STRING`: "serialization_exception" will be thrown. * * @return string value */ std::string& as_string_nonempty_or_throw(const std::string& context = ""); /** * Access value as non-empty `STRING` * If this value is not a non-empty `STRING`: "serialization_exception" will be thrown. * * @return string value */ const std::string& as_string_nonempty_or_throw(const std::string& context = "") const; /** * Access value as a `STRING`, * returns specified `default_val` if this value is not a `STRING` * * @param default_val default value * @return string value */ const std::string& as_string(const std::string& default_val) const; /** * Access value as an `INTEGER` * * @return int value */ int64_t as_int64() const; /** * Access value as an `INTEGER` * If this value is not an `INTEGER`: "serialization_exception" will be thrown. * * @return int value */ int64_t as_int64_or_throw(const std::string& context = "") const; /** * Access value as an `INTEGER`, * returns specified `default_val` if this value is not an `INTEGER` * * @param default_val default value * @return int value */ int64_t as_int64(int64_t default_val) const; /** * Access value as an `uint64_t` `INTEGER` * * @return int value */ uint64_t as_uint64() const; /** * Access value as `uint64_t` `INTEGER` * If this value is not an `INTEGER` or cannot be converted to `uint64_t`: * "json_exception" will be thrown. * * @return int value */ uint64_t as_uint64_or_throw(const std::string& context = "") const; /** * Access value as positive `uint64_t` `INTEGER` * If this value is not a positive `INTEGER` or cannot be converted to `uint64_t`: * "json_exception" will be thrown. * * @return int value */ uint64_t as_uint64_positive_or_throw(const std::string& context = "") const; /** * Access value as an `uint64_t` `INTEGER`, * returns specified `default_val` if this value is not an `INTEGER` * * @param default_val default value * @return int value */ uint64_t as_uint64(uint64_t default_val) const; /** * Access value as an `int32_t` `INTEGER` * * @return int value */ int32_t as_int32() const; /** * Access value as `int32_t` `INTEGER` * If this value is not an `INTEGER` or cannot be converted to `int32_t`: * "serialization_exception" will be thrown. * * @return int value */ int32_t as_int32_or_throw(const std::string& context = "") const; /** * Access value as an `int32_t` `INTEGER`, * returns specified `default_val` if this value is not an `INTEGER` * * @param default_val default value * @return int value */ int32_t as_int32(int32_t default_val) const; /** * Access value as an `uint32_t` `INTEGER` * * @return int value */ uint32_t as_uint32() const; /** * Access value as `uint32_t` `INTEGER` * If this value is not an `INTEGER` or cannot be converted to `uint32_t`: * "serialization_exception" will be thrown. * * @return int value */ uint32_t as_uint32_or_throw(const std::string& context = "") const; /** * Access value as positive `uint32_t` `INTEGER` * If this value is not a positive `INTEGER` or cannot be converted to `uint32_t`: * "json_exception" will be thrown. * * @return int value */ uint32_t as_uint32_positive_or_throw(const std::string& context = "") const; /** * Access value as an `uint32_t` `INTEGER`, * returns specified `default_val` if this value is not an `INTEGER` * * @param default_val default value * @return int value */ uint32_t as_uint32(uint32_t default_val) const; /** * Access value as an `int16_t` `INTEGER` * * @return int value */ int16_t as_int16() const; /** * Access value as `int16_t` `INTEGER` * If this value is not an `INTEGER` or cannot be converted to `int16_t`: * "serialization_exception" will be thrown. * * @return int value */ int16_t as_int16_or_throw(const std::string& context = "") const; /** * Access value as an `int16_t` `INTEGER`, * returns specified `default_val` if this value is not an `INTEGER` * * @param default_val default value * @return int value */ int16_t as_int16(int16_t default_val) const; /** * Access value as an `uint16_t` `INTEGER` * * @return int value */ uint16_t as_uint16() const; /** * Access value as `uint16_t` `INTEGER` * If this value is not an `INTEGER` or cannot be converted to `uint16_t`: * "serialization_exception" will be thrown. * * @return int value */ uint16_t as_uint16_or_throw(const std::string& context = "") const; /** * Access value as positive `uint16_t` `INTEGER` * If this value is not a positive `INTEGER` or cannot be converted to `uint16_t`: * "json_exception" will be thrown. * * @return int value */ uint16_t as_uint16_positive_or_throw(const std::string& context = "") const; /** * Access value as an `uint16_t` `INTEGER`, * returns specified `default_val` if this value is not an `INTEGER` * * @param default_val default value * @return int value */ uint16_t as_uint16(uint16_t default_val) const; /** * Access value as a `REAL`, * returns specified `default_val` if this value is not a `REAL` * * @return double value */ double as_double() const; /** * Access value as `REAL` * If this value is not a `REAL`: * "serialization_exception" will be thrown. * * @return int value */ double as_double_or_throw(const std::string& context = "") const; /** * Access value as an `REAL`, * * @param default_val default value * @return double value */ double as_double(double default_val) const; /** * Access value as a `REAL`, * returns specified `default_val` if this value is not a `REAL` * * @return double value */ float as_float() const; /** * Access value as `float` `REAL` * If this value is not a `REAL` or cannot be converted to `float`: * "serialization_exception" will be thrown. * * @return int value */ float as_float_or_throw(const std::string& context = "") const; /** * Access value as an `REAL`, * * @param default_val default value * @return double value */ float as_float(float default_val) const; /** * Access value as an `BOOLEAN` * * @return bool value */ bool as_bool() const; /** * Access value as `BOOLEAN` * If this value is not a `BOOLEAN`: * "serialization_exception" will be thrown. * * @return int value */ bool as_bool_or_throw(const std::string& context = "") const; /** * Access value as an `BOOLEAN`, * returns specified `default_val` if this value is not a `BOOLEAN` * * @param default_val default value * @return bool value */ bool as_bool(bool default_val) const; }; } // namespace } #endif /* STATICLIB_JSON_FIELD_HPP */
#include "../headers/deck.h" namespace pkr { Deck::Deck() { //std::srand(std::time(NULL)); for(int i((int)CardSuit::club); i <= (int)CardSuit::spade; ++i) { for(int j((int)CardValue::two); j <= (int)CardValue::ace; ++j) cards.insert(Card(j,i)); } } bool Deck::searchFor(Card card) { std::unordered_set<Card> available_cards(this->getWhiteList()); return available_cards.find(card) != available_cards.end(); } std::unordered_set<Card> Deck::getWhiteList() const { std::unordered_set<Card> available_cards(this->cards); for(Card c : black_list) { auto c_it(available_cards.find(c)); if(c_it != available_cards.end()) available_cards.erase(c_it); } if(available_cards.empty()) throw std::invalid_argument("Can't take any card."); return available_cards; } void Deck::setBlackList(std::unordered_set<Card> black_list) { this->black_list = black_list; } Card Deck::take() { std::unordered_set<Card> available_cards(this->getWhiteList()); auto c(available_cards.begin()); std::advance(c,std::rand() % available_cards.size()); Card card = *c; this->cards.erase(this->cards.find(card)); return card; } pkr::Hand Deck::take(std::unordered_set<pkr::Hand> available_hands) { std::unordered_set<Card> available_cards(this->getWhiteList()); pkr::Hand res; while(not available_hands.empty()) { auto h(available_hands.begin()); std::advance(h,std::rand() % available_hands.size()); pkr::Hand hh = *h; if(this->searchFor(h->first) and this->searchFor(h->second)) return *h; else available_hands.erase(h); } throw std::runtime_error("Can't find cards from range in the deck"); } void Deck::take(Card card) { if(this->black_list.find(card) != this->black_list.end()) throw std::invalid_argument("Invalid card"); auto c = cards.find(card); if(c != cards.end()) cards.erase(c); else throw std::invalid_argument("Invalid card"); } void Deck::giveBack(Card card) { this->cards.insert(card); } }
#include "../CompanyManager.h" #include "../Graphics/Colour.h" #include "../Graphics/Gfx.h" #include "../Graphics/ImageIds.h" #include "../Input.h" #include "../Interop/Interop.hpp" #include "../Localisation/FormatArguments.hpp" #include "../Localisation/StringIds.h" #include "../Objects/CargoObject.h" #include "../Objects/CompetitorObject.h" #include "../Objects/InterfaceSkinObject.h" #include "../Objects/ObjectManager.h" #include "../OpenLoco.h" #include "../StationManager.h" #include "../TownManager.h" #include "../Ui/Dropdown.h" #include "../Ui/WindowManager.h" #include "../Widget.h" using namespace OpenLoco::Interop; namespace OpenLoco::Ui::Windows::StationList { static const Ui::Size window_size = { 600, 197 }; static const Ui::Size max_dimensions = { 640, 1200 }; static const Ui::Size min_dimensions = { 192, 100 }; static const uint8_t rowHeight = 10; // CJK: 13 enum widx { frame = 0, caption = 1, close_button = 2, panel = 3, tab_all_stations, tab_rail_stations, tab_road_stations, tab_airports, tab_ship_ports, company_select, sort_name, sort_status, sort_total_waiting, sort_accepts, scrollview, }; static Widget _widgets[] = { makeWidget({ 0, 0 }, { 600, 197 }, WidgetType::frame, WindowColour::primary), makeWidget({ 1, 1 }, { 598, 13 }, WidgetType::caption_24, WindowColour::primary, StringIds::stringid_all_stations), makeWidget({ 585, 2 }, { 13, 13 }, WidgetType::buttonWithImage, WindowColour::primary, ImageIds::close_button, StringIds::tooltip_close_window), makeWidget({ 0, 41 }, { 600, 155 }, WidgetType::panel, WindowColour::secondary), makeRemapWidget({ 3, 15 }, { 31, 27 }, WidgetType::tab, WindowColour::secondary, ImageIds::tab, StringIds::tooltip_all_stations), makeRemapWidget({ 3, 15 }, { 31, 27 }, WidgetType::tab, WindowColour::secondary, ImageIds::tab, StringIds::tooltip_rail_stations), makeRemapWidget({ 3, 15 }, { 31, 27 }, WidgetType::tab, WindowColour::secondary, ImageIds::tab, StringIds::tooltip_road_stations), makeRemapWidget({ 3, 15 }, { 31, 27 }, WidgetType::tab, WindowColour::secondary, ImageIds::tab, StringIds::tooltip_airports), makeRemapWidget({ 3, 15 }, { 31, 27 }, WidgetType::tab, WindowColour::secondary, ImageIds::tab, StringIds::tooltip_ship_ports), makeWidget({ 0, 14 }, { 26, 26 }, WidgetType::buttonWithImage, WindowColour::primary, StringIds::null, StringIds::tooltip_select_company), makeWidget({ 4, 43 }, { 200, 12 }, WidgetType::buttonTableHeader, WindowColour::secondary, StringIds::null, StringIds::tooltip_sort_by_name), makeWidget({ 204, 43 }, { 200, 12 }, WidgetType::buttonTableHeader, WindowColour::secondary, StringIds::null, StringIds::tooltip_sort_by_station_status), makeWidget({ 404, 43 }, { 90, 12 }, WidgetType::buttonTableHeader, WindowColour::secondary, StringIds::null, StringIds::tooltip_sort_by_total_units_waiting), makeWidget({ 494, 43 }, { 120, 12 }, WidgetType::buttonTableHeader, WindowColour::secondary, StringIds::null, StringIds::tooltip_sort_by_cargo_accepted), makeWidget({ 3, 56 }, { 594, 126 }, WidgetType::scrollview, WindowColour::secondary, Scrollbars::vertical), widgetEnd(), }; static WindowEventList _events; struct TabDetails { widx widgetIndex; string_id windowTitleId; uint32_t imageId; uint16_t stationMask; }; static TabDetails tabInformationByType[] = { { tab_all_stations, StringIds::stringid_all_stations, InterfaceSkin::ImageIds::all_stations, StationFlags::allModes }, { tab_rail_stations, StringIds::stringid_rail_stations, InterfaceSkin::ImageIds::rail_stations, StationFlags::transportModeRail }, { tab_road_stations, StringIds::stringid_road_stations, InterfaceSkin::ImageIds::road_stations, StationFlags::transportModeRoad }, { tab_airports, StringIds::stringid_airports, InterfaceSkin::ImageIds::airports, StationFlags::transportModeAir }, { tab_ship_ports, StringIds::stringid_ship_ports, InterfaceSkin::ImageIds::ship_ports, StationFlags::transportModeWater } }; enum SortMode : uint16_t { Name, Status, TotalUnitsWaiting, CargoAccepted, }; loco_global<uint16_t[4], 0x112C826> _common_format_args; static Ui::CursorId cursor(Window* window, int16_t widgetIdx, int16_t xPos, int16_t yPos, Ui::CursorId fallback); static void draw(Ui::Window* window, Gfx::Context* context); static void drawScroll(Ui::Window& window, Gfx::Context& context, const uint32_t scrollIndex); static void event_08(Window* window); static void event_09(Window* window); static void getScrollSize(Ui::Window* window, uint32_t scrollIndex, uint16_t* scrollWidth, uint16_t* scrollHeight); static void onDropdown(Ui::Window* window, WidgetIndex_t widgetIndex, int16_t itemIndex); static void onMouseDown(Ui::Window* window, WidgetIndex_t widgetIndex); static void onMouseUp(Ui::Window* window, WidgetIndex_t widgetIndex); static void onScrollMouseDown(Ui::Window* window, int16_t x, int16_t y, uint8_t scroll_index); static void onScrollMouseOver(Ui::Window* window, int16_t x, int16_t y, uint8_t scroll_index); static void onUpdate(Window* window); static void prepareDraw(Ui::Window* window); static std::optional<FormatArguments> tooltip(Ui::Window* window, WidgetIndex_t widgetIndex); static void initEvents() { _events.cursor = cursor; _events.draw = draw; _events.draw_scroll = drawScroll; _events.event_08 = event_08; _events.event_09 = event_09; _events.get_scroll_size = getScrollSize; _events.on_dropdown = onDropdown; _events.on_mouse_down = onMouseDown; _events.on_mouse_up = onMouseUp; _events.on_update = onUpdate; _events.scroll_mouse_down = onScrollMouseDown; _events.scroll_mouse_over = onScrollMouseOver; _events.prepare_draw = prepareDraw; _events.tooltip = tooltip; } // 0x004910E8 static void refreshStationList(Window* window) { window->row_count = 0; for (auto& station : StationManager::stations()) { if (station.owner == CompanyId(window->number)) { station.flags &= ~StationFlags::flag_4; } } } // 0x004911FD static bool orderByName(const OpenLoco::Station& lhs, const OpenLoco::Station& rhs) { char lhsString[256] = { 0 }; StringManager::formatString(lhsString, lhs.name, (void*)&lhs.town); char rhsString[256] = { 0 }; StringManager::formatString(rhsString, rhs.name, (void*)&rhs.town); return strcmp(lhsString, rhsString) < 0; } // 0x00491281, 0x00491247 static bool orderByQuantity(const OpenLoco::Station& lhs, const OpenLoco::Station& rhs) { uint32_t lhsSum = 0; for (const auto& cargo : lhs.cargoStats) { lhsSum += cargo.quantity; } uint32_t rhsSum = 0; for (const auto& cargo : rhs.cargoStats) { rhsSum += cargo.quantity; } return rhsSum < lhsSum; } // 0x004912BB static bool orderByAccepts(const OpenLoco::Station& lhs, const OpenLoco::Station& rhs) { char* ptr; char lhsString[256] = { 0 }; ptr = &lhsString[0]; for (uint32_t cargoId = 0; cargoId < kMaxCargoStats; cargoId++) { if (lhs.cargoStats[cargoId].isAccepted()) { ptr = StringManager::formatString(ptr, ObjectManager::get<CargoObject>(cargoId)->name); } } char rhsString[256] = { 0 }; ptr = &rhsString[0]; for (uint32_t cargoId = 0; cargoId < kMaxCargoStats; cargoId++) { if (rhs.cargoStats[cargoId].isAccepted()) { ptr = StringManager::formatString(ptr, ObjectManager::get<CargoObject>(cargoId)->name); } } return strcmp(lhsString, rhsString) < 0; } // 0x004911FD, 0x00491247, 0x00491281, 0x004912BB static bool getOrder(const SortMode mode, const OpenLoco::Station& lhs, const OpenLoco::Station& rhs) { switch (mode) { case SortMode::Name: return orderByName(lhs, rhs); case SortMode::Status: case SortMode::TotalUnitsWaiting: return orderByQuantity(lhs, rhs); case SortMode::CargoAccepted: return orderByAccepts(lhs, rhs); } return false; } // 0x0049111A static void updateStationList(Window* window) { StationId edi = StationId::null; for (auto& station : StationManager::stations()) { if (station.owner != CompanyId(window->number)) continue; if ((station.flags & StationFlags::flag_5) != 0) continue; const uint16_t mask = tabInformationByType[window->current_tab].stationMask; if ((station.flags & mask) == 0) continue; if ((station.flags & StationFlags::flag_4) != 0) continue; if (edi == StationId::null) { edi = station.id(); continue; } if (getOrder(SortMode(window->sort_mode), station, *StationManager::get(edi))) { edi = station.id(); } } if (edi != StationId::null) { bool dl = false; StationManager::get(edi)->flags |= StationFlags::flag_4; auto ebp = window->row_count; if (edi != StationId(window->row_info[ebp])) { window->row_info[ebp] = enumValue(edi); dl = true; } window->row_count += 1; if (window->row_count > window->var_83C) { window->var_83C = window->row_count; dl = true; } if (dl) { window->invalidate(); } } else { if (window->var_83C != window->row_count) { window->var_83C = window->row_count; window->invalidate(); } refreshStationList(window); } } // 0x00490F6C Window* open(CompanyId companyId) { Window* window = WindowManager::bringToFront(WindowType::stationList, enumValue(companyId)); if (window != nullptr) { if (Input::isToolActive(window->type, window->number)) Input::toolCancel(); // Still active? window = WindowManager::bringToFront(WindowType::stationList, enumValue(companyId)); } if (window == nullptr) { // 0x00491010 window = WindowManager::createWindow( WindowType::stationList, window_size, WindowFlags::flag_11, &_events); window->number = enumValue(companyId); window->owner = companyId; window->current_tab = 0; window->frame_no = 0; window->sort_mode = 0; window->var_83C = 0; window->row_hover = -1; refreshStationList(window); window->min_width = min_dimensions.width; window->min_height = min_dimensions.height; window->max_width = max_dimensions.width; window->max_height = max_dimensions.height; window->flags |= WindowFlags::resizable; auto interface = ObjectManager::get<InterfaceSkinObject>(); window->setColour(WindowColour::secondary, interface->colour_0A); } // TODO: only needs to be called once. initEvents(); window->current_tab = 0; window->invalidate(); window->widgets = _widgets; window->enabled_widgets = (1 << close_button) | (1 << tab_all_stations) | (1 << tab_rail_stations) | (1 << tab_road_stations) | (1 << tab_airports) | (1 << tab_ship_ports) | (1 << company_select) | (1 << sort_name) | (1 << sort_status) | (1 << sort_total_waiting) | (1 << sort_accepts) | (1 << scrollview); window->activated_widgets = 0; window->holdable_widgets = 0; window->callOnResize(); window->callPrepareDraw(); window->initScrollWidgets(); return window; } Window* open(CompanyId companyId, uint8_t type) { if (type > 4) throw std::domain_error("Unexpected station type"); Window* station_list = open(companyId); widx target = tabInformationByType[type].widgetIndex; station_list->callOnMouseUp(target); return station_list; } // 0x004919A4 static Ui::CursorId cursor(Window* window, int16_t widgetIdx, int16_t xPos, int16_t yPos, Ui::CursorId fallback) { if (widgetIdx != widx::scrollview) return fallback; uint16_t currentIndex = yPos / rowHeight; if (currentIndex < window->var_83C && window->row_info[currentIndex] != -1) return CursorId::handPointer; return fallback; } // 0x0049196F static void event_08(Window* window) { window->flags |= WindowFlags::not_scroll_view; } // 0x00491977 static void event_09(Window* window) { if ((window->flags & WindowFlags::not_scroll_view) == 0) return; if (window->row_hover == -1) return; window->row_hover = -1; window->invalidate(); } // 0x00491344 static void prepareDraw(Ui::Window* window) { // Reset active tab. window->activated_widgets &= ~((1 << tab_all_stations) | (1 << tab_rail_stations) | (1 << tab_road_stations) | (1 << tab_airports) | (1 << tab_ship_ports)); window->activated_widgets |= (1ULL << tabInformationByType[window->current_tab].widgetIndex); // Set company name. auto company = CompanyManager::get(CompanyId(window->number)); *_common_format_args = company->name; // Set window title. window->widgets[widx::caption].text = tabInformationByType[window->current_tab].windowTitleId; // Resize general window widgets. window->widgets[widx::frame].right = window->width - 1; window->widgets[widx::frame].bottom = window->height - 1; window->widgets[widx::panel].right = window->width - 1; window->widgets[widx::panel].bottom = window->height - 1; window->widgets[widx::caption].right = window->width - 2; window->widgets[widx::close_button].left = window->width - 15; window->widgets[widx::close_button].right = window->width - 3; window->widgets[widx::scrollview].right = window->width - 4; window->widgets[widx::scrollview].bottom = window->height - 14; // Reposition header buttons. window->widgets[widx::sort_name].right = std::min(203, window->width - 4); window->widgets[widx::sort_status].left = std::min(204, window->width - 4); window->widgets[widx::sort_status].right = std::min(403, window->width - 4); window->widgets[widx::sort_total_waiting].left = std::min(404, window->width - 4); window->widgets[widx::sort_total_waiting].right = std::min(493, window->width - 4); window->widgets[widx::sort_accepts].left = std::min(494, window->width - 4); window->widgets[widx::sort_accepts].right = std::min(613, window->width - 4); // Reposition company selection. window->widgets[widx::company_select].left = window->width - 28; window->widgets[widx::company_select].right = window->width - 3; // Set header button captions. window->widgets[widx::sort_name].text = window->sort_mode == SortMode::Name ? StringIds::table_header_name_desc : StringIds::table_header_name; window->widgets[widx::sort_status].text = window->sort_mode == SortMode::Status ? StringIds::table_header_status_desc : StringIds::table_header_status; window->widgets[widx::sort_total_waiting].text = window->sort_mode == SortMode::TotalUnitsWaiting ? StringIds::table_header_total_waiting_desc : StringIds::table_header_total_waiting; window->widgets[widx::sort_accepts].text = window->sort_mode == SortMode::CargoAccepted ? StringIds::table_header_accepts_desc : StringIds::table_header_accepts; // Reposition tabs (0x00491A39 / 0x00491A3F) int16_t new_tab_x = window->widgets[widx::tab_all_stations].left; int16_t tab_width = window->widgets[widx::tab_all_stations].right - new_tab_x; for (auto& tabInfo : tabInformationByType) { if (window->isDisabled(tabInfo.widgetIndex)) continue; Widget& tab = window->widgets[tabInfo.widgetIndex]; tab.left = new_tab_x; new_tab_x += tab_width; tab.right = new_tab_x++; } } // 0x0049157F static void drawScroll(Ui::Window& window, Gfx::Context& context, const uint32_t scrollIndex) { auto shade = Colour::getShade(window.getColour(WindowColour::secondary), 4); Gfx::clearSingle(context, shade); uint16_t yPos = 0; for (uint16_t i = 0; i < window.var_83C; i++) { auto stationId = StationId(window.row_info[i]); // Skip items outside of view, or irrelevant to the current filter. if (yPos + rowHeight < context.y || yPos >= yPos + rowHeight + context.height || stationId == StationId::null) { yPos += rowHeight; continue; } string_id text_colour_id = StringIds::black_stringid; // Highlight selection. if (stationId == StationId(window.row_hover)) { Gfx::drawRect(context, 0, yPos, window.width, rowHeight, 0x2000030); text_colour_id = StringIds::wcolour2_stringid; } auto station = StationManager::get(stationId); // First, draw the town name. _common_format_args[0] = StringIds::stringid_stringid; _common_format_args[1] = station->name; _common_format_args[2] = enumValue(station->town); _common_format_args[3] = getTransportIconsFromStationFlags(station->flags); Gfx::drawString_494BBF(context, 0, yPos, 198, Colour::black, text_colour_id, &*_common_format_args); // Then the station's current status. char* buffer = const_cast<char*>(StringManager::getString(StringIds::buffer_1250)); station->getStatusString(buffer); _common_format_args[0] = StringIds::buffer_1250; Gfx::drawString_494BBF(context, 200, yPos, 198, Colour::black, text_colour_id, &*_common_format_args); // Total units waiting. uint16_t totalUnits = 0; for (const auto& stats : station->cargoStats) totalUnits += stats.quantity; _common_format_args[0] = StringIds::num_units; *(uint32_t*)&_common_format_args[1] = totalUnits; Gfx::drawString_494BBF(context, 400, yPos, 88, Colour::black, text_colour_id, &*_common_format_args); // And, finally, what goods the station accepts. char* ptr = buffer; *ptr = '\0'; for (uint32_t cargoId = 0; cargoId < kMaxCargoStats; cargoId++) { auto& stats = station->cargoStats[cargoId]; if (!stats.isAccepted()) continue; if (*buffer != '\0') ptr = StringManager::formatString(ptr, StringIds::unit_separator); ptr = StringManager::formatString(ptr, ObjectManager::get<CargoObject>(cargoId)->name); } _common_format_args[0] = StringIds::buffer_1250; Gfx::drawString_494BBF(context, 490, yPos, 118, Colour::black, text_colour_id, &*_common_format_args); yPos += rowHeight; } } // 00491A76 static void drawTabs(Ui::Window* window, Gfx::Context* context) { auto skin = ObjectManager::get<InterfaceSkinObject>(); auto companyColour = CompanyManager::getCompanyColour(CompanyId(window->number)); for (const auto& tab : tabInformationByType) { uint32_t image = Gfx::recolour(skin->img + tab.imageId, companyColour); Widget::drawTab(window, context, image, tab.widgetIndex); } } // 0x004914D8 static void draw(Ui::Window* window, Gfx::Context* context) { // Draw widgets and tabs. window->draw(context); drawTabs(window, context); // Draw company owner image. auto company = CompanyManager::get(CompanyId(window->number)); auto competitor = ObjectManager::get<CompetitorObject>(company->competitorId); uint32_t image = Gfx::recolour(competitor->images[company->ownerEmotion], company->mainColours.primary); uint16_t x = window->x + window->widgets[widx::company_select].left + 1; uint16_t y = window->y + window->widgets[widx::company_select].top + 1; Gfx::drawImage(context, x, y, image); // TODO: locale-based pluralisation. _common_format_args[0] = window->var_83C == 1 ? StringIds::status_num_stations_singular : StringIds::status_num_stations_plural; _common_format_args[1] = window->var_83C; // Draw number of stations. auto origin = Ui::Point(window->x + 4, window->y + window->height - 12); Gfx::drawString_494B3F(*context, &origin, Colour::black, StringIds::black_stringid, &*_common_format_args); } // 0x004917BB static void onDropdown(Ui::Window* window, WidgetIndex_t widgetIndex, int16_t itemIndex) { if (widgetIndex != widx::company_select) return; if (itemIndex == -1) return; CompanyId companyId = Dropdown::getCompanyIdFromSelection(itemIndex); // Try to find an open station list for this company. auto companyWindow = WindowManager::bringToFront(WindowType::stationList, enumValue(companyId)); if (companyWindow != nullptr) return; // If not, we'll turn this window into a window for the company selected. auto company = CompanyManager::get(companyId); if (company->name == StringIds::empty) return; window->number = enumValue(companyId); window->owner = companyId; window->sort_mode = 0; window->row_count = 0; refreshStationList(window); window->var_83C = 0; window->row_hover = -1; window->callOnResize(); window->callPrepareDraw(); window->initScrollWidgets(); window->invalidate(); } // 0x004917B0 static void onMouseDown(Ui::Window* window, WidgetIndex_t widgetIndex) { if (widgetIndex == widx::company_select) Dropdown::populateCompanySelect(window, &window->widgets[widgetIndex]); } // 0x00491785 static void onMouseUp(Ui::Window* window, WidgetIndex_t widgetIndex) { switch (widgetIndex) { case widx::close_button: WindowManager::close(window); break; case tab_all_stations: case tab_rail_stations: case tab_road_stations: case tab_airports: case tab_ship_ports: { if (Input::isToolActive(window->type, window->number)) Input::toolCancel(); window->current_tab = widgetIndex - widx::tab_all_stations; window->frame_no = 0; window->invalidate(); window->var_83C = 0; window->row_hover = -1; refreshStationList(window); window->callOnResize(); window->callPrepareDraw(); window->initScrollWidgets(); window->moveInsideScreenEdges(); break; } case sort_name: case sort_status: case sort_total_waiting: case sort_accepts: { auto sort_mode = widgetIndex - widx::sort_name; if (window->sort_mode == sort_mode) return; window->sort_mode = sort_mode; window->invalidate(); window->var_83C = 0; window->row_hover = -1; refreshStationList(window); break; } } } // 0x00491A0C static void onScrollMouseDown(Ui::Window* window, int16_t x, int16_t y, uint8_t scroll_index) { uint16_t currentRow = y / rowHeight; if (currentRow > window->var_83C) return; const auto currentStation = StationId(window->row_info[currentRow]); if (currentStation == StationId::null) return; Station::open(currentStation); } // 0x004919D1 static void onScrollMouseOver(Ui::Window* window, int16_t x, int16_t y, uint8_t scroll_index) { window->flags &= ~(WindowFlags::not_scroll_view); uint16_t currentRow = y / rowHeight; int16_t currentStation = -1; if (currentRow < window->var_83C) currentStation = window->row_info[currentRow]; if (currentStation == window->row_hover) return; window->row_hover = currentStation; window->invalidate(); } // 0x0049193F static void onUpdate(Window* window) { window->frame_no++; window->callPrepareDraw(); WindowManager::invalidateWidget(WindowType::stationList, window->number, window->current_tab + 4); // Add three stations every tick. updateStationList(window); updateStationList(window); updateStationList(window); } // 0x00491999 static void getScrollSize(Ui::Window* window, uint32_t scrollIndex, uint16_t* scrollWidth, uint16_t* scrollHeight) { *scrollHeight = rowHeight * window->var_83C; } // 0x00491841 static std::optional<FormatArguments> tooltip(Ui::Window* window, WidgetIndex_t widgetIndex) { FormatArguments args{}; args.push(StringIds::tooltip_scroll_station_list); return args; } }
// Copyright (c) 2016 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "asyncrpcoperation.h" #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <string> #include <ctime> #include <chrono> using namespace std; static boost::uuids::random_generator uuidgen; static std::map<OperationStatus, std::string> OperationStatusMap = { {OperationStatus::READY, "queued"}, {OperationStatus::EXECUTING, "executing"}, {OperationStatus::CANCELLED, "cancelled"}, {OperationStatus::FAILED, "failed"}, {OperationStatus::SUCCESS, "success"} }; /** * Every operation instance should have a globally unique id */ AsyncRPCOperation::AsyncRPCOperation() : error_code_(0), error_message_() { // Set a unique reference for each operation boost::uuids::uuid uuid = uuidgen(); id_ = "opid-" + boost::uuids::to_string(uuid); creation_time_ = (int64_t)time(NULL); set_state(OperationStatus::READY); } AsyncRPCOperation::AsyncRPCOperation(const AsyncRPCOperation& o) : id_(o.id_), creation_time_(o.creation_time_), state_(o.state_.load()), start_time_(o.start_time_), end_time_(o.end_time_), error_code_(o.error_code_), error_message_(o.error_message_), result_(o.result_) { } AsyncRPCOperation& AsyncRPCOperation::operator=( const AsyncRPCOperation& other ) { this->id_ = other.id_; this->creation_time_ = other.creation_time_; this->state_.store(other.state_.load()); this->start_time_ = other.start_time_; this->end_time_ = other.end_time_; this->error_code_ = other.error_code_; this->error_message_ = other.error_message_; this->result_ = other.result_; return *this; } AsyncRPCOperation::~AsyncRPCOperation() { } /** * Override this cancel() method if you can interrupt main() when executing. */ void AsyncRPCOperation::cancel() { if (isReady()) { set_state(OperationStatus::CANCELLED); } } /** * Start timing the execution run of the code you're interested in */ void AsyncRPCOperation::start_execution_clock() { std::lock_guard<std::mutex> guard(lock_); start_time_ = std::chrono::system_clock::now(); } /** * Stop timing the execution run */ void AsyncRPCOperation::stop_execution_clock() { std::lock_guard<std::mutex> guard(lock_); end_time_ = std::chrono::system_clock::now(); } /** * Implement this virtual method in any subclass. This is just an example implementation. */ void AsyncRPCOperation::main() { if (isCancelled()) { return; } set_state(OperationStatus::EXECUTING); start_execution_clock(); // Do some work here.. stop_execution_clock(); // If there was an error, you might set it like this: /* setErrorCode(123); setErrorMessage("Murphy's law"); setState(OperationStatus::FAILED); */ // Otherwise, if the operation was a success: UniValue v(UniValue::VSTR, "We have a result!"); set_result(v); set_state(OperationStatus::SUCCESS); } /** * Return the error of the completed operation as a UniValue object. * If there is no error, return null UniValue. */ UniValue AsyncRPCOperation::getError() const { if (!isFailed()) { return NullUniValue; } std::lock_guard<std::mutex> guard(lock_); UniValue error(UniValue::VOBJ); error.push_back(Pair("code", this->error_code_)); error.push_back(Pair("message", this->error_message_)); return error; } /** * Return the result of the completed operation as a UniValue object. * If the operation did not succeed, return null UniValue. */ UniValue AsyncRPCOperation::getResult() const { if (!isSuccess()) { return NullUniValue; } std::lock_guard<std::mutex> guard(lock_); return this->result_; } /** * Returns a status UniValue object. * If the operation has failed, it will include an error object. * If the operation has succeeded, it will include the result value. * If the operation was cancelled, there will be no error object or result value. */ UniValue AsyncRPCOperation::getStatus() const { OperationStatus status = this->getState(); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("id", this->id_)); obj.push_back(Pair("status", OperationStatusMap[status])); obj.push_back(Pair("creation_time", this->creation_time_)); // TODO: Issue #1354: There may be other useful metadata to return to the user. UniValue err = this->getError(); if (!err.isNull()) { obj.push_back(Pair("error", err.get_obj())); } UniValue result = this->getResult(); if (!result.isNull()) { obj.push_back(Pair("result", result)); // Include execution time for successful operation std::chrono::duration<double> elapsed_seconds = end_time_ - start_time_; obj.push_back(Pair("execution_secs", elapsed_seconds.count())); } return obj; } /** * Return the operation state in human readable form. */ std::string AsyncRPCOperation::getStateAsString() const { OperationStatus status = this->getState(); return OperationStatusMap[status]; }
/* * Copyright 2012, The Android Open Source Project * * 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. */ //#define LOG_NDEBUG 0 #define LOG_TAG "MediaCodec" #include <inttypes.h> #include "include/avc_utils.h" #include "include/SoftwareRenderer.h" #include <binder/IMemory.h> #include <binder/IPCThreadState.h> #include <binder/IServiceManager.h> #include <binder/MemoryDealer.h> #include <gui/BufferQueue.h> #include <gui/Surface.h> #include <media/ICrypto.h> #include <media/IOMX.h> #include <media/IResourceManagerService.h> #include <media/stagefright/foundation/ABuffer.h> #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/foundation/AMessage.h> #include <media/stagefright/foundation/AString.h> #include <media/stagefright/foundation/hexdump.h> #include <media/stagefright/ACodec.h> #include <media/stagefright/BufferProducerWrapper.h> #include <media/stagefright/MediaCodec.h> #include <media/stagefright/MediaCodecList.h> #include <media/stagefright/MediaDefs.h> #include <media/stagefright/MediaErrors.h> #include <media/stagefright/MediaFilter.h> #include <media/stagefright/MetaData.h> #include <media/stagefright/OMXClient.h> #include <media/stagefright/PersistentSurface.h> #include <media/stagefright/SurfaceUtils.h> #include <mediautils/BatteryNotifier.h> #include <private/android_filesystem_config.h> #include <utils/Log.h> #include <utils/Singleton.h> namespace android { static int64_t getId(sp<IResourceManagerClient> client) { return (int64_t) client.get(); } static bool isResourceError(status_t err) { return (err == NO_MEMORY); } static const int kMaxRetry = 2; static const int kMaxReclaimWaitTimeInUs = 500000; // 0.5s struct ResourceManagerClient : public BnResourceManagerClient { ResourceManagerClient(MediaCodec* codec) : mMediaCodec(codec) {} virtual bool reclaimResource() { sp<MediaCodec> codec = mMediaCodec.promote(); if (codec == NULL) { // codec is already gone. return true; } status_t err = codec->reclaim(); if (err == WOULD_BLOCK) { ALOGD("Wait for the client to release codec."); usleep(kMaxReclaimWaitTimeInUs); ALOGD("Try to reclaim again."); err = codec->reclaim(true /* force */); } if (err != OK) { ALOGW("ResourceManagerClient failed to release codec with err %d", err); } return (err == OK); } virtual String8 getName() { String8 ret; sp<MediaCodec> codec = mMediaCodec.promote(); if (codec == NULL) { // codec is already gone. return ret; } AString name; if (codec->getName(&name) == OK) { ret.setTo(name.c_str()); } return ret; } protected: virtual ~ResourceManagerClient() {} private: wp<MediaCodec> mMediaCodec; DISALLOW_EVIL_CONSTRUCTORS(ResourceManagerClient); }; MediaCodec::ResourceManagerServiceProxy::ResourceManagerServiceProxy(pid_t pid) : mPid(pid) { if (mPid == MediaCodec::kNoPid) { mPid = IPCThreadState::self()->getCallingPid(); } } MediaCodec::ResourceManagerServiceProxy::~ResourceManagerServiceProxy() { if (mService != NULL) { IInterface::asBinder(mService)->unlinkToDeath(this); } } void MediaCodec::ResourceManagerServiceProxy::init() { sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("media.resource_manager")); mService = interface_cast<IResourceManagerService>(binder); if (mService == NULL) { ALOGE("Failed to get ResourceManagerService"); return; } IInterface::asBinder(mService)->linkToDeath(this); } void MediaCodec::ResourceManagerServiceProxy::binderDied(const wp<IBinder>& /*who*/) { ALOGW("ResourceManagerService died."); Mutex::Autolock _l(mLock); mService.clear(); } void MediaCodec::ResourceManagerServiceProxy::addResource( int64_t clientId, const sp<IResourceManagerClient> client, const Vector<MediaResource> &resources) { Mutex::Autolock _l(mLock); if (mService == NULL) { return; } mService->addResource(mPid, clientId, client, resources); } void MediaCodec::ResourceManagerServiceProxy::removeResource(int64_t clientId) { Mutex::Autolock _l(mLock); if (mService == NULL) { return; } mService->removeResource(mPid, clientId); } bool MediaCodec::ResourceManagerServiceProxy::reclaimResource( const Vector<MediaResource> &resources) { Mutex::Autolock _l(mLock); if (mService == NULL) { return false; } return mService->reclaimResource(mPid, resources); } // static sp<MediaCodec> MediaCodec::CreateByType( const sp<ALooper> &looper, const AString &mime, bool encoder, status_t *err, pid_t pid) { sp<MediaCodec> codec = new MediaCodec(looper, pid); const status_t ret = codec->init(mime, true /* nameIsType */, encoder); if (err != NULL) { *err = ret; } return ret == OK ? codec : NULL; // NULL deallocates codec. } // static sp<MediaCodec> MediaCodec::CreateByComponentName( const sp<ALooper> &looper, const AString &name, status_t *err, pid_t pid) { sp<MediaCodec> codec = new MediaCodec(looper, pid); const status_t ret = codec->init(name, false /* nameIsType */, false /* encoder */); if (err != NULL) { *err = ret; } return ret == OK ? codec : NULL; // NULL deallocates codec. } // static status_t MediaCodec::QueryCapabilities( const AString &name, const AString &mime, bool isEncoder, sp<MediaCodecInfo::Capabilities> *caps /* nonnull */) { // TRICKY: this method is used by MediaCodecList/Info during its // initialization. As such, we cannot create a MediaCodec instance // because that requires an initialized MediaCodecList. sp<CodecBase> codec = GetCodecBase(name); if (codec == NULL) { return NAME_NOT_FOUND; } return codec->queryCapabilities(name, mime, isEncoder, caps); } // static sp<PersistentSurface> MediaCodec::CreatePersistentInputSurface() { OMXClient client; CHECK_EQ(client.connect(), (status_t)OK); sp<IOMX> omx = client.interface(); const sp<IMediaCodecList> mediaCodecList = MediaCodecList::getInstance(); if (mediaCodecList == NULL) { ALOGE("Failed to obtain MediaCodecList!"); return NULL; // if called from Java should raise IOException } AString tmp; sp<AMessage> globalSettings = mediaCodecList->getGlobalSettings(); if (globalSettings == NULL || !globalSettings->findString( kMaxEncoderInputBuffers, &tmp)) { ALOGE("Failed to get encoder input buffer count!"); return NULL; } int32_t bufferCount = strtol(tmp.c_str(), NULL, 10); if (bufferCount <= 0 || bufferCount > BufferQueue::MAX_MAX_ACQUIRED_BUFFERS) { ALOGE("Encoder input buffer count is invalid!"); return NULL; } sp<IGraphicBufferProducer> bufferProducer; sp<IGraphicBufferConsumer> bufferConsumer; status_t err = omx->createPersistentInputSurface( &bufferProducer, &bufferConsumer); if (err != OK) { ALOGE("Failed to create persistent input surface."); return NULL; } err = bufferConsumer->setMaxAcquiredBufferCount(bufferCount); if (err != NO_ERROR) { ALOGE("Unable to set BQ max acquired buffer count to %u: %d", bufferCount, err); return NULL; } return new PersistentSurface(bufferProducer, bufferConsumer); } MediaCodec::MediaCodec(const sp<ALooper> &looper, pid_t pid) : mState(UNINITIALIZED), mReleasedByResourceManager(false), mLooper(looper), mCodec(NULL), mReplyID(0), mFlags(0), mStickyError(OK), mSoftRenderer(NULL), mResourceManagerClient(new ResourceManagerClient(this)), mResourceManagerService(new ResourceManagerServiceProxy(pid)), mBatteryStatNotified(false), mIsVideo(false), mVideoWidth(0), mVideoHeight(0), mRotationDegrees(0), mDequeueInputTimeoutGeneration(0), mDequeueInputReplyID(0), mDequeueOutputTimeoutGeneration(0), mDequeueOutputReplyID(0), mHaveInputSurface(false), mHavePendingInputBuffers(false) { } MediaCodec::~MediaCodec() { CHECK_EQ(mState, UNINITIALIZED); mResourceManagerService->removeResource(getId(mResourceManagerClient)); } // static status_t MediaCodec::PostAndAwaitResponse( const sp<AMessage> &msg, sp<AMessage> *response) { status_t err = msg->postAndAwaitResponse(response); if (err != OK) { return err; } if (!(*response)->findInt32("err", &err)) { err = OK; } return err; } void MediaCodec::PostReplyWithError(const sp<AReplyToken> &replyID, int32_t err) { int32_t finalErr = err; if (mReleasedByResourceManager) { // override the err code if MediaCodec has been released by ResourceManager. finalErr = DEAD_OBJECT; } sp<AMessage> response = new AMessage; response->setInt32("err", finalErr); response->postReply(replyID); } //static sp<CodecBase> MediaCodec::GetCodecBase(const AString &name, bool nameIsType) { // at this time only ACodec specifies a mime type. if (nameIsType || name.startsWithIgnoreCase("omx.")) { return new ACodec; } else if (name.startsWithIgnoreCase("android.filter.")) { return new MediaFilter; } else { return NULL; } } status_t MediaCodec::init(const AString &name, bool nameIsType, bool encoder) { mResourceManagerService->init(); // save init parameters for reset mInitName = name; mInitNameIsType = nameIsType; mInitIsEncoder = encoder; // Current video decoders do not return from OMX_FillThisBuffer // quickly, violating the OpenMAX specs, until that is remedied // we need to invest in an extra looper to free the main event // queue. mCodec = GetCodecBase(name, nameIsType); if (mCodec == NULL) { return NAME_NOT_FOUND; } bool secureCodec = false; if (nameIsType && !strncasecmp(name.c_str(), "video/", 6)) { mIsVideo = true; } else { AString tmp = name; if (tmp.endsWith(".secure")) { secureCodec = true; tmp.erase(tmp.size() - 7, 7); } const sp<IMediaCodecList> mcl = MediaCodecList::getInstance(); if (mcl == NULL) { mCodec = NULL; // remove the codec. return NO_INIT; // if called from Java should raise IOException } ssize_t codecIdx = mcl->findCodecByName(tmp.c_str()); if (codecIdx >= 0) { const sp<MediaCodecInfo> info = mcl->getCodecInfo(codecIdx); Vector<AString> mimes; info->getSupportedMimes(&mimes); for (size_t i = 0; i < mimes.size(); i++) { if (mimes[i].startsWith("video/")) { mIsVideo = true; break; } } } } if (mIsVideo) { // video codec needs dedicated looper if (mCodecLooper == NULL) { mCodecLooper = new ALooper; mCodecLooper->setName("CodecLooper"); mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO); } mCodecLooper->registerHandler(mCodec); } else { mLooper->registerHandler(mCodec); } mLooper->registerHandler(this); mCodec->setNotificationMessage(new AMessage(kWhatCodecNotify, this)); sp<AMessage> msg = new AMessage(kWhatInit, this); msg->setString("name", name); msg->setInt32("nameIsType", nameIsType); if (nameIsType) { msg->setInt32("encoder", encoder); } status_t err; Vector<MediaResource> resources; MediaResource::Type type = secureCodec ? MediaResource::kSecureCodec : MediaResource::kNonSecureCodec; MediaResource::SubType subtype = mIsVideo ? MediaResource::kVideoCodec : MediaResource::kAudioCodec; resources.push_back(MediaResource(type, subtype, 1)); for (int i = 0; i <= kMaxRetry; ++i) { if (i > 0) { // Don't try to reclaim resource for the first time. if (!mResourceManagerService->reclaimResource(resources)) { break; } } sp<AMessage> response; err = PostAndAwaitResponse(msg, &response); if (!isResourceError(err)) { break; } } return err; } status_t MediaCodec::setCallback(const sp<AMessage> &callback) { sp<AMessage> msg = new AMessage(kWhatSetCallback, this); msg->setMessage("callback", callback); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::setOnFrameRenderedNotification(const sp<AMessage> &notify) { sp<AMessage> msg = new AMessage(kWhatSetNotification, this); msg->setMessage("on-frame-rendered", notify); return msg->post(); } status_t MediaCodec::configure( const sp<AMessage> &format, const sp<Surface> &surface, const sp<ICrypto> &crypto, uint32_t flags) { sp<AMessage> msg = new AMessage(kWhatConfigure, this); if (mIsVideo) { format->findInt32("width", &mVideoWidth); format->findInt32("height", &mVideoHeight); if (!format->findInt32("rotation-degrees", &mRotationDegrees)) { mRotationDegrees = 0; } // Prevent possible integer overflow in downstream code. if (mInitIsEncoder && (uint64_t)mVideoWidth * mVideoHeight > (uint64_t)INT32_MAX / 4) { ALOGE("buffer size is too big, width=%d, height=%d", mVideoWidth, mVideoHeight); return BAD_VALUE; } } msg->setMessage("format", format); msg->setInt32("flags", flags); msg->setObject("surface", surface); if (crypto != NULL) { msg->setPointer("crypto", crypto.get()); } // save msg for reset mConfigureMsg = msg; status_t err; Vector<MediaResource> resources; MediaResource::Type type = (mFlags & kFlagIsSecure) ? MediaResource::kSecureCodec : MediaResource::kNonSecureCodec; MediaResource::SubType subtype = mIsVideo ? MediaResource::kVideoCodec : MediaResource::kAudioCodec; resources.push_back(MediaResource(type, subtype, 1)); // Don't know the buffer size at this point, but it's fine to use 1 because // the reclaimResource call doesn't consider the requester's buffer size for now. resources.push_back(MediaResource(MediaResource::kGraphicMemory, 1)); for (int i = 0; i <= kMaxRetry; ++i) { if (i > 0) { // Don't try to reclaim resource for the first time. if (!mResourceManagerService->reclaimResource(resources)) { break; } } sp<AMessage> response; err = PostAndAwaitResponse(msg, &response); if (err != OK && err != INVALID_OPERATION) { // MediaCodec now set state to UNINITIALIZED upon any fatal error. // To maintain backward-compatibility, do a reset() to put codec // back into INITIALIZED state. // But don't reset if the err is INVALID_OPERATION, which means // the configure failure is due to wrong state. ALOGE("configure failed with err 0x%08x, resetting...", err); reset(); } if (!isResourceError(err)) { break; } } return err; } status_t MediaCodec::setInputSurface( const sp<PersistentSurface> &surface) { sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this); msg->setObject("input-surface", surface.get()); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::setSurface(const sp<Surface> &surface) { sp<AMessage> msg = new AMessage(kWhatSetSurface, this); msg->setObject("surface", surface); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::createInputSurface( sp<IGraphicBufferProducer>* bufferProducer) { sp<AMessage> msg = new AMessage(kWhatCreateInputSurface, this); sp<AMessage> response; status_t err = PostAndAwaitResponse(msg, &response); if (err == NO_ERROR) { // unwrap the sp<IGraphicBufferProducer> sp<RefBase> obj; bool found = response->findObject("input-surface", &obj); CHECK(found); sp<BufferProducerWrapper> wrapper( static_cast<BufferProducerWrapper*>(obj.get())); *bufferProducer = wrapper->getBufferProducer(); } else { ALOGW("createInputSurface failed, err=%d", err); } return err; } uint64_t MediaCodec::getGraphicBufferSize() { if (!mIsVideo) { return 0; } uint64_t size = 0; size_t portNum = sizeof(mPortBuffers) / sizeof((mPortBuffers)[0]); for (size_t i = 0; i < portNum; ++i) { // TODO: this is just an estimation, we should get the real buffer size from ACodec. size += mPortBuffers[i].size() * mVideoWidth * mVideoHeight * 3 / 2; } return size; } void MediaCodec::addResource( MediaResource::Type type, MediaResource::SubType subtype, uint64_t value) { Vector<MediaResource> resources; resources.push_back(MediaResource(type, subtype, value)); mResourceManagerService->addResource( getId(mResourceManagerClient), mResourceManagerClient, resources); } status_t MediaCodec::start() { sp<AMessage> msg = new AMessage(kWhatStart, this); status_t err; Vector<MediaResource> resources; MediaResource::Type type = (mFlags & kFlagIsSecure) ? MediaResource::kSecureCodec : MediaResource::kNonSecureCodec; MediaResource::SubType subtype = mIsVideo ? MediaResource::kVideoCodec : MediaResource::kAudioCodec; resources.push_back(MediaResource(type, subtype, 1)); // Don't know the buffer size at this point, but it's fine to use 1 because // the reclaimResource call doesn't consider the requester's buffer size for now. resources.push_back(MediaResource(MediaResource::kGraphicMemory, 1)); for (int i = 0; i <= kMaxRetry; ++i) { if (i > 0) { // Don't try to reclaim resource for the first time. if (!mResourceManagerService->reclaimResource(resources)) { break; } // Recover codec from previous error before retry start. err = reset(); if (err != OK) { ALOGE("retrying start: failed to reset codec"); break; } sp<AMessage> response; err = PostAndAwaitResponse(mConfigureMsg, &response); if (err != OK) { ALOGE("retrying start: failed to configure codec"); break; } } sp<AMessage> response; err = PostAndAwaitResponse(msg, &response); if (!isResourceError(err)) { break; } } return err; } status_t MediaCodec::stop() { sp<AMessage> msg = new AMessage(kWhatStop, this); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } bool MediaCodec::hasPendingBuffer(int portIndex) { const Vector<BufferInfo> &buffers = mPortBuffers[portIndex]; for (size_t i = 0; i < buffers.size(); ++i) { const BufferInfo &info = buffers.itemAt(i); if (info.mOwnedByClient) { return true; } } return false; } bool MediaCodec::hasPendingBuffer() { return hasPendingBuffer(kPortIndexInput) || hasPendingBuffer(kPortIndexOutput); } status_t MediaCodec::reclaim(bool force) { ALOGD("MediaCodec::reclaim(%p) %s", this, mInitName.c_str()); sp<AMessage> msg = new AMessage(kWhatRelease, this); msg->setInt32("reclaimed", 1); msg->setInt32("force", force ? 1 : 0); sp<AMessage> response; status_t ret = PostAndAwaitResponse(msg, &response); if (ret == -ENOENT) { ALOGD("MediaCodec looper is gone, skip reclaim"); ret = OK; } return ret; } status_t MediaCodec::release() { sp<AMessage> msg = new AMessage(kWhatRelease, this); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::reset() { /* When external-facing MediaCodec object is created, it is already initialized. Thus, reset is essentially release() followed by init(), plus clearing the state */ status_t err = release(); // unregister handlers if (mCodec != NULL) { if (mCodecLooper != NULL) { mCodecLooper->unregisterHandler(mCodec->id()); } else { mLooper->unregisterHandler(mCodec->id()); } mCodec = NULL; } mLooper->unregisterHandler(id()); mFlags = 0; // clear all flags mStickyError = OK; // reset state not reset by setState(UNINITIALIZED) mReplyID = 0; mDequeueInputReplyID = 0; mDequeueOutputReplyID = 0; mDequeueInputTimeoutGeneration = 0; mDequeueOutputTimeoutGeneration = 0; mHaveInputSurface = false; if (err == OK) { err = init(mInitName, mInitNameIsType, mInitIsEncoder); } return err; } status_t MediaCodec::queueInputBuffer( size_t index, size_t offset, size_t size, int64_t presentationTimeUs, uint32_t flags, AString *errorDetailMsg) { if (errorDetailMsg != NULL) { errorDetailMsg->clear(); } sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, this); msg->setSize("index", index); msg->setSize("offset", offset); msg->setSize("size", size); msg->setInt64("timeUs", presentationTimeUs); msg->setInt32("flags", flags); msg->setPointer("errorDetailMsg", errorDetailMsg); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::queueSecureInputBuffer( size_t index, size_t offset, const CryptoPlugin::SubSample *subSamples, size_t numSubSamples, const uint8_t key[16], const uint8_t iv[16], CryptoPlugin::Mode mode, const CryptoPlugin::Pattern &pattern, int64_t presentationTimeUs, uint32_t flags, AString *errorDetailMsg) { if (errorDetailMsg != NULL) { errorDetailMsg->clear(); } sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, this); msg->setSize("index", index); msg->setSize("offset", offset); msg->setPointer("subSamples", (void *)subSamples); msg->setSize("numSubSamples", numSubSamples); msg->setPointer("key", (void *)key); msg->setPointer("iv", (void *)iv); msg->setInt32("mode", mode); msg->setInt32("encryptBlocks", pattern.mEncryptBlocks); msg->setInt32("skipBlocks", pattern.mSkipBlocks); msg->setInt64("timeUs", presentationTimeUs); msg->setInt32("flags", flags); msg->setPointer("errorDetailMsg", errorDetailMsg); sp<AMessage> response; status_t err = PostAndAwaitResponse(msg, &response); return err; } status_t MediaCodec::dequeueInputBuffer(size_t *index, int64_t timeoutUs) { sp<AMessage> msg = new AMessage(kWhatDequeueInputBuffer, this); msg->setInt64("timeoutUs", timeoutUs); sp<AMessage> response; status_t err; if ((err = PostAndAwaitResponse(msg, &response)) != OK) { return err; } CHECK(response->findSize("index", index)); return OK; } status_t MediaCodec::dequeueOutputBuffer( size_t *index, size_t *offset, size_t *size, int64_t *presentationTimeUs, uint32_t *flags, int64_t timeoutUs) { sp<AMessage> msg = new AMessage(kWhatDequeueOutputBuffer, this); msg->setInt64("timeoutUs", timeoutUs); sp<AMessage> response; status_t err; if ((err = PostAndAwaitResponse(msg, &response)) != OK) { return err; } CHECK(response->findSize("index", index)); CHECK(response->findSize("offset", offset)); CHECK(response->findSize("size", size)); CHECK(response->findInt64("timeUs", presentationTimeUs)); CHECK(response->findInt32("flags", (int32_t *)flags)); return OK; } status_t MediaCodec::renderOutputBufferAndRelease(size_t index) { sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, this); msg->setSize("index", index); msg->setInt32("render", true); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::renderOutputBufferAndRelease(size_t index, int64_t timestampNs) { sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, this); msg->setSize("index", index); msg->setInt32("render", true); msg->setInt64("timestampNs", timestampNs); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::releaseOutputBuffer(size_t index) { sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, this); msg->setSize("index", index); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::signalEndOfInputStream() { sp<AMessage> msg = new AMessage(kWhatSignalEndOfInputStream, this); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::getOutputFormat(sp<AMessage> *format) const { sp<AMessage> msg = new AMessage(kWhatGetOutputFormat, this); sp<AMessage> response; status_t err; if ((err = PostAndAwaitResponse(msg, &response)) != OK) { return err; } CHECK(response->findMessage("format", format)); return OK; } status_t MediaCodec::getInputFormat(sp<AMessage> *format) const { sp<AMessage> msg = new AMessage(kWhatGetInputFormat, this); sp<AMessage> response; status_t err; if ((err = PostAndAwaitResponse(msg, &response)) != OK) { return err; } CHECK(response->findMessage("format", format)); return OK; } status_t MediaCodec::getName(AString *name) const { sp<AMessage> msg = new AMessage(kWhatGetName, this); sp<AMessage> response; status_t err; if ((err = PostAndAwaitResponse(msg, &response)) != OK) { return err; } CHECK(response->findString("name", name)); return OK; } status_t MediaCodec::getWidevineLegacyBuffers(Vector<sp<ABuffer> > *buffers) const { sp<AMessage> msg = new AMessage(kWhatGetBuffers, this); msg->setInt32("portIndex", kPortIndexInput); msg->setPointer("buffers", buffers); msg->setInt32("widevine", true); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::getInputBuffers(Vector<sp<ABuffer> > *buffers) const { sp<AMessage> msg = new AMessage(kWhatGetBuffers, this); msg->setInt32("portIndex", kPortIndexInput); msg->setPointer("buffers", buffers); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::getOutputBuffers(Vector<sp<ABuffer> > *buffers) const { sp<AMessage> msg = new AMessage(kWhatGetBuffers, this); msg->setInt32("portIndex", kPortIndexOutput); msg->setPointer("buffers", buffers); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::getOutputBuffer(size_t index, sp<ABuffer> *buffer) { sp<AMessage> format; return getBufferAndFormat(kPortIndexOutput, index, buffer, &format); } status_t MediaCodec::getOutputFormat(size_t index, sp<AMessage> *format) { sp<ABuffer> buffer; return getBufferAndFormat(kPortIndexOutput, index, &buffer, format); } status_t MediaCodec::getInputBuffer(size_t index, sp<ABuffer> *buffer) { sp<AMessage> format; return getBufferAndFormat(kPortIndexInput, index, buffer, &format); } bool MediaCodec::isExecuting() const { return mState == STARTED || mState == FLUSHED; } status_t MediaCodec::getBufferAndFormat( size_t portIndex, size_t index, sp<ABuffer> *buffer, sp<AMessage> *format) { // use mutex instead of a context switch if (mReleasedByResourceManager) { ALOGE("getBufferAndFormat - resource already released"); return DEAD_OBJECT; } if (buffer == NULL) { ALOGE("getBufferAndFormat - null ABuffer"); return INVALID_OPERATION; } if (format == NULL) { ALOGE("getBufferAndFormat - null AMessage"); return INVALID_OPERATION; } buffer->clear(); format->clear(); if (!isExecuting()) { ALOGE("getBufferAndFormat - not executing"); return INVALID_OPERATION; } // we do not want mPortBuffers to change during this section // we also don't want mOwnedByClient to change during this Mutex::Autolock al(mBufferLock); Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; if (index >= buffers->size()) { ALOGE("getBufferAndFormat - trying to get buffer with " "bad index (index=%zu buffer_size=%zu)", index, buffers->size()); return INVALID_OPERATION; } const BufferInfo &info = buffers->itemAt(index); if (!info.mOwnedByClient) { ALOGE("getBufferAndFormat - invalid operation " "(the index %zu is not owned by client)", index); return INVALID_OPERATION; } // by the time buffers array is initialized, crypto is set *buffer = (portIndex == kPortIndexInput && mCrypto != NULL) ? info.mEncryptedData : info.mData; *format = info.mFormat; return OK; } status_t MediaCodec::flush() { sp<AMessage> msg = new AMessage(kWhatFlush, this); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::requestIDRFrame() { (new AMessage(kWhatRequestIDRFrame, this))->post(); return OK; } void MediaCodec::requestActivityNotification(const sp<AMessage> &notify) { sp<AMessage> msg = new AMessage(kWhatRequestActivityNotification, this); msg->setMessage("notify", notify); msg->post(); } //////////////////////////////////////////////////////////////////////////////// void MediaCodec::cancelPendingDequeueOperations() { if (mFlags & kFlagDequeueInputPending) { PostReplyWithError(mDequeueInputReplyID, INVALID_OPERATION); ++mDequeueInputTimeoutGeneration; mDequeueInputReplyID = 0; mFlags &= ~kFlagDequeueInputPending; } if (mFlags & kFlagDequeueOutputPending) { PostReplyWithError(mDequeueOutputReplyID, INVALID_OPERATION); ++mDequeueOutputTimeoutGeneration; mDequeueOutputReplyID = 0; mFlags &= ~kFlagDequeueOutputPending; } } bool MediaCodec::handleDequeueInputBuffer(const sp<AReplyToken> &replyID, bool newRequest) { if (!isExecuting() || (mFlags & kFlagIsAsync) || (newRequest && (mFlags & kFlagDequeueInputPending))) { PostReplyWithError(replyID, INVALID_OPERATION); return true; } else if (mFlags & kFlagStickyError) { PostReplyWithError(replyID, getStickyError()); return true; } ssize_t index = dequeuePortBuffer(kPortIndexInput); if (index < 0) { CHECK_EQ(index, -EAGAIN); return false; } sp<AMessage> response = new AMessage; response->setSize("index", index); response->postReply(replyID); return true; } bool MediaCodec::handleDequeueOutputBuffer(const sp<AReplyToken> &replyID, bool newRequest) { if (!isExecuting() || (mFlags & kFlagIsAsync) || (newRequest && (mFlags & kFlagDequeueOutputPending))) { PostReplyWithError(replyID, INVALID_OPERATION); } else if (mFlags & kFlagStickyError) { PostReplyWithError(replyID, getStickyError()); } else if (mFlags & kFlagOutputBuffersChanged) { PostReplyWithError(replyID, INFO_OUTPUT_BUFFERS_CHANGED); mFlags &= ~kFlagOutputBuffersChanged; } else if (mFlags & kFlagOutputFormatChanged) { PostReplyWithError(replyID, INFO_FORMAT_CHANGED); mFlags &= ~kFlagOutputFormatChanged; } else { sp<AMessage> response = new AMessage; ssize_t index = dequeuePortBuffer(kPortIndexOutput); if (index < 0) { CHECK_EQ(index, -EAGAIN); return false; } const sp<ABuffer> &buffer = mPortBuffers[kPortIndexOutput].itemAt(index).mData; response->setSize("index", index); response->setSize("offset", buffer->offset()); response->setSize("size", buffer->size()); int64_t timeUs; CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); response->setInt64("timeUs", timeUs); int32_t omxFlags; CHECK(buffer->meta()->findInt32("omxFlags", &omxFlags)); uint32_t flags = 0; if (omxFlags & OMX_BUFFERFLAG_SYNCFRAME) { flags |= BUFFER_FLAG_SYNCFRAME; } if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) { flags |= BUFFER_FLAG_CODECCONFIG; } if (omxFlags & OMX_BUFFERFLAG_EOS) { flags |= BUFFER_FLAG_EOS; } response->setInt32("flags", flags); response->postReply(replyID); } return true; } void MediaCodec::onMessageReceived(const sp<AMessage> &msg) { switch (msg->what()) { case kWhatCodecNotify: { int32_t what; CHECK(msg->findInt32("what", &what)); switch (what) { case CodecBase::kWhatError: { int32_t err, actionCode; CHECK(msg->findInt32("err", &err)); CHECK(msg->findInt32("actionCode", &actionCode)); ALOGE("Codec reported err %#x, actionCode %d, while in state %d", err, actionCode, mState); if (err == DEAD_OBJECT) { mFlags |= kFlagSawMediaServerDie; mFlags &= ~kFlagIsComponentAllocated; } bool sendErrorResponse = true; switch (mState) { case INITIALIZING: { setState(UNINITIALIZED); break; } case CONFIGURING: { setState(actionCode == ACTION_CODE_FATAL ? UNINITIALIZED : INITIALIZED); break; } case STARTING: { setState(actionCode == ACTION_CODE_FATAL ? UNINITIALIZED : CONFIGURED); break; } case STOPPING: case RELEASING: { // Ignore the error, assuming we'll still get // the shutdown complete notification. sendErrorResponse = false; if (mFlags & kFlagSawMediaServerDie) { // MediaServer died, there definitely won't // be a shutdown complete notification after // all. // note that we're directly going from // STOPPING->UNINITIALIZED, instead of the // usual STOPPING->INITIALIZED state. setState(UNINITIALIZED); if (mState == RELEASING) { mComponentName.clear(); } (new AMessage)->postReply(mReplyID); } break; } case FLUSHING: { if (actionCode == ACTION_CODE_FATAL) { setState(UNINITIALIZED); } else { setState( (mFlags & kFlagIsAsync) ? FLUSHED : STARTED); } break; } case FLUSHED: case STARTED: { sendErrorResponse = false; setStickyError(err); postActivityNotificationIfPossible(); cancelPendingDequeueOperations(); if (mFlags & kFlagIsAsync) { onError(err, actionCode); } switch (actionCode) { case ACTION_CODE_TRANSIENT: break; case ACTION_CODE_RECOVERABLE: setState(INITIALIZED); break; default: setState(UNINITIALIZED); break; } break; } default: { sendErrorResponse = false; setStickyError(err); postActivityNotificationIfPossible(); // actionCode in an uninitialized state is always fatal. if (mState == UNINITIALIZED) { actionCode = ACTION_CODE_FATAL; } if (mFlags & kFlagIsAsync) { onError(err, actionCode); } switch (actionCode) { case ACTION_CODE_TRANSIENT: break; case ACTION_CODE_RECOVERABLE: setState(INITIALIZED); break; default: setState(UNINITIALIZED); break; } break; } } if (sendErrorResponse) { PostReplyWithError(mReplyID, err); } break; } case CodecBase::kWhatComponentAllocated: { CHECK_EQ(mState, INITIALIZING); setState(INITIALIZED); mFlags |= kFlagIsComponentAllocated; CHECK(msg->findString("componentName", &mComponentName)); if (mComponentName.startsWith("OMX.google.")) { mFlags |= kFlagUsesSoftwareRenderer; } else { mFlags &= ~kFlagUsesSoftwareRenderer; } MediaResource::Type resourceType; if (mComponentName.endsWith(".secure")) { mFlags |= kFlagIsSecure; resourceType = MediaResource::kSecureCodec; } else { mFlags &= ~kFlagIsSecure; resourceType = MediaResource::kNonSecureCodec; } if (mIsVideo) { // audio codec is currently ignored. addResource(resourceType, MediaResource::kVideoCodec, 1); } (new AMessage)->postReply(mReplyID); break; } case CodecBase::kWhatComponentConfigured: { if (mState == UNINITIALIZED || mState == INITIALIZED) { // In case a kWhatError message came in and replied with error, // we log a warning and ignore. ALOGW("configure interrupted by error, current state %d", mState); break; } CHECK_EQ(mState, CONFIGURING); // reset input surface flag mHaveInputSurface = false; CHECK(msg->findMessage("input-format", &mInputFormat)); CHECK(msg->findMessage("output-format", &mOutputFormat)); ALOGV("[%s] configured as input format: %s, output format: %s", mComponentName.c_str(), mInputFormat->debugString(4).c_str(), mOutputFormat->debugString(4).c_str()); int32_t usingSwRenderer; if (mOutputFormat->findInt32("using-sw-renderer", &usingSwRenderer) && usingSwRenderer) { mFlags |= kFlagUsesSoftwareRenderer; } setState(CONFIGURED); (new AMessage)->postReply(mReplyID); break; } case CodecBase::kWhatInputSurfaceCreated: { // response to initiateCreateInputSurface() status_t err = NO_ERROR; sp<AMessage> response = new AMessage; if (!msg->findInt32("err", &err)) { sp<RefBase> obj; msg->findObject("input-surface", &obj); CHECK(msg->findMessage("input-format", &mInputFormat)); CHECK(msg->findMessage("output-format", &mOutputFormat)); ALOGV("[%s] input surface created as input format: %s, output format: %s", mComponentName.c_str(), mInputFormat->debugString(4).c_str(), mOutputFormat->debugString(4).c_str()); CHECK(obj != NULL); response->setObject("input-surface", obj); mHaveInputSurface = true; } else { response->setInt32("err", err); } response->postReply(mReplyID); break; } case CodecBase::kWhatInputSurfaceAccepted: { // response to initiateSetInputSurface() status_t err = NO_ERROR; sp<AMessage> response = new AMessage(); if (!msg->findInt32("err", &err)) { mHaveInputSurface = true; } else { response->setInt32("err", err); } response->postReply(mReplyID); break; } case CodecBase::kWhatSignaledInputEOS: { // response to signalEndOfInputStream() sp<AMessage> response = new AMessage; status_t err; if (msg->findInt32("err", &err)) { response->setInt32("err", err); } response->postReply(mReplyID); break; } case CodecBase::kWhatBuffersAllocated: { Mutex::Autolock al(mBufferLock); int32_t portIndex; CHECK(msg->findInt32("portIndex", &portIndex)); ALOGV("%s buffers allocated", portIndex == kPortIndexInput ? "input" : "output"); CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); mPortBuffers[portIndex].clear(); Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; sp<RefBase> obj; CHECK(msg->findObject("portDesc", &obj)); sp<CodecBase::PortDescription> portDesc = static_cast<CodecBase::PortDescription *>(obj.get()); size_t numBuffers = portDesc->countBuffers(); size_t totalSize = 0; for (size_t i = 0; i < numBuffers; ++i) { if (portIndex == kPortIndexInput && mCrypto != NULL) { totalSize += portDesc->bufferAt(i)->capacity(); } } if (totalSize) { mDealer = new MemoryDealer(totalSize, "MediaCodec"); } for (size_t i = 0; i < numBuffers; ++i) { BufferInfo info; info.mBufferID = portDesc->bufferIDAt(i); info.mOwnedByClient = false; info.mData = portDesc->bufferAt(i); info.mNativeHandle = portDesc->handleAt(i); info.mMemRef = portDesc->memRefAt(i); if (portIndex == kPortIndexInput && mCrypto != NULL) { sp<IMemory> mem = mDealer->allocate(info.mData->capacity()); info.mEncryptedData = new ABuffer(mem->pointer(), info.mData->capacity()); info.mSharedEncryptedBuffer = mem; } buffers->push_back(info); } if (portIndex == kPortIndexOutput) { if (mState == STARTING) { // We're always allocating output buffers after // allocating input buffers, so this is a good // indication that now all buffers are allocated. if (mIsVideo) { addResource( MediaResource::kGraphicMemory, MediaResource::kUnspecifiedSubType, getGraphicBufferSize()); } setState(STARTED); (new AMessage)->postReply(mReplyID); } else { mFlags |= kFlagOutputBuffersChanged; postActivityNotificationIfPossible(); } } break; } case CodecBase::kWhatOutputFormatChanged: { CHECK(msg->findMessage("format", &mOutputFormat)); ALOGV("[%s] output format changed to: %s", mComponentName.c_str(), mOutputFormat->debugString(4).c_str()); if (mSoftRenderer == NULL && mSurface != NULL && (mFlags & kFlagUsesSoftwareRenderer)) { AString mime; CHECK(mOutputFormat->findString("mime", &mime)); // TODO: propagate color aspects to software renderer to allow better // color conversion to RGB. For now, just mark dataspace for YUV // rendering. int32_t dataSpace; if (mOutputFormat->findInt32("android._dataspace", &dataSpace)) { ALOGD("[%s] setting dataspace on output surface to #%x", mComponentName.c_str(), dataSpace); int err = native_window_set_buffers_data_space( mSurface.get(), (android_dataspace)dataSpace); ALOGW_IF(err != 0, "failed to set dataspace on surface (%d)", err); } if (mime.startsWithIgnoreCase("video/")) { mSoftRenderer = new SoftwareRenderer(mSurface, mRotationDegrees); } } if (mFlags & kFlagIsEncoder) { // Before we announce the format change we should // collect codec specific data and amend the output // format as necessary. mFlags |= kFlagGatherCodecSpecificData; } else if (mFlags & kFlagIsAsync) { onOutputFormatChanged(); } else { mFlags |= kFlagOutputFormatChanged; postActivityNotificationIfPossible(); } // Notify mCrypto of video resolution changes if (mCrypto != NULL) { int32_t left, top, right, bottom, width, height; if (mOutputFormat->findRect("crop", &left, &top, &right, &bottom)) { mCrypto->notifyResolution(right - left + 1, bottom - top + 1); } else if (mOutputFormat->findInt32("width", &width) && mOutputFormat->findInt32("height", &height)) { mCrypto->notifyResolution(width, height); } } break; } case CodecBase::kWhatOutputFramesRendered: { // ignore these in all states except running, and check that we have a // notification set if (mState == STARTED && mOnFrameRenderedNotification != NULL) { sp<AMessage> notify = mOnFrameRenderedNotification->dup(); notify->setMessage("data", msg); notify->post(); } break; } case CodecBase::kWhatFillThisBuffer: { /* size_t index = */updateBuffers(kPortIndexInput, msg); if (mState == FLUSHING || mState == STOPPING || mState == RELEASING) { returnBuffersToCodecOnPort(kPortIndexInput); break; } if (!mCSD.empty()) { ssize_t index = dequeuePortBuffer(kPortIndexInput); CHECK_GE(index, 0); // If codec specific data had been specified as // part of the format in the call to configure and // if there's more csd left, we submit it here // clients only get access to input buffers once // this data has been exhausted. status_t err = queueCSDInputBuffer(index); if (err != OK) { ALOGE("queueCSDInputBuffer failed w/ error %d", err); setStickyError(err); postActivityNotificationIfPossible(); cancelPendingDequeueOperations(); } break; } if (mFlags & kFlagIsAsync) { if (!mHaveInputSurface) { if (mState == FLUSHED) { mHavePendingInputBuffers = true; } else { onInputBufferAvailable(); } } } else if (mFlags & kFlagDequeueInputPending) { CHECK(handleDequeueInputBuffer(mDequeueInputReplyID)); ++mDequeueInputTimeoutGeneration; mFlags &= ~kFlagDequeueInputPending; mDequeueInputReplyID = 0; } else { postActivityNotificationIfPossible(); } break; } case CodecBase::kWhatDrainThisBuffer: { /* size_t index = */updateBuffers(kPortIndexOutput, msg); if (mState == FLUSHING || mState == STOPPING || mState == RELEASING) { returnBuffersToCodecOnPort(kPortIndexOutput); break; } sp<ABuffer> buffer; CHECK(msg->findBuffer("buffer", &buffer)); int32_t omxFlags; CHECK(msg->findInt32("flags", &omxFlags)); buffer->meta()->setInt32("omxFlags", omxFlags); if (mFlags & kFlagGatherCodecSpecificData) { // This is the very first output buffer after a // format change was signalled, it'll either contain // the one piece of codec specific data we can expect // or there won't be codec specific data. if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) { status_t err = amendOutputFormatWithCodecSpecificData(buffer); if (err != OK) { ALOGE("Codec spit out malformed codec " "specific data!"); } } mFlags &= ~kFlagGatherCodecSpecificData; if (mFlags & kFlagIsAsync) { onOutputFormatChanged(); } else { mFlags |= kFlagOutputFormatChanged; } } if (mFlags & kFlagIsAsync) { onOutputBufferAvailable(); } else if (mFlags & kFlagDequeueOutputPending) { CHECK(handleDequeueOutputBuffer(mDequeueOutputReplyID)); ++mDequeueOutputTimeoutGeneration; mFlags &= ~kFlagDequeueOutputPending; mDequeueOutputReplyID = 0; } else { postActivityNotificationIfPossible(); } break; } case CodecBase::kWhatEOS: { // We already notify the client of this by using the // corresponding flag in "onOutputBufferReady". break; } case CodecBase::kWhatShutdownCompleted: { if (mState == STOPPING) { setState(INITIALIZED); } else { CHECK_EQ(mState, RELEASING); setState(UNINITIALIZED); mComponentName.clear(); } mFlags &= ~kFlagIsComponentAllocated; mResourceManagerService->removeResource(getId(mResourceManagerClient)); (new AMessage)->postReply(mReplyID); break; } case CodecBase::kWhatFlushCompleted: { if (mState != FLUSHING) { ALOGW("received FlushCompleted message in state %d", mState); break; } if (mFlags & kFlagIsAsync) { setState(FLUSHED); } else { setState(STARTED); mCodec->signalResume(); } (new AMessage)->postReply(mReplyID); break; } default: TRESPASS(); } break; } case kWhatInit: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (mState != UNINITIALIZED) { PostReplyWithError(replyID, INVALID_OPERATION); break; } mReplyID = replyID; setState(INITIALIZING); AString name; CHECK(msg->findString("name", &name)); int32_t nameIsType; int32_t encoder = false; CHECK(msg->findInt32("nameIsType", &nameIsType)); if (nameIsType) { CHECK(msg->findInt32("encoder", &encoder)); } sp<AMessage> format = new AMessage; if (nameIsType) { format->setString("mime", name.c_str()); format->setInt32("encoder", encoder); } else { format->setString("componentName", name.c_str()); } mCodec->initiateAllocateComponent(format); break; } case kWhatSetNotification: { sp<AMessage> notify; if (msg->findMessage("on-frame-rendered", &notify)) { mOnFrameRenderedNotification = notify; } break; } case kWhatSetCallback: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (mState == UNINITIALIZED || mState == INITIALIZING || isExecuting()) { // callback can't be set after codec is executing, // or before it's initialized (as the callback // will be cleared when it goes to INITIALIZED) PostReplyWithError(replyID, INVALID_OPERATION); break; } sp<AMessage> callback; CHECK(msg->findMessage("callback", &callback)); mCallback = callback; if (mCallback != NULL) { ALOGI("MediaCodec will operate in async mode"); mFlags |= kFlagIsAsync; } else { mFlags &= ~kFlagIsAsync; } sp<AMessage> response = new AMessage; response->postReply(replyID); break; } case kWhatConfigure: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (mState != INITIALIZED) { PostReplyWithError(replyID, INVALID_OPERATION); break; } sp<RefBase> obj; CHECK(msg->findObject("surface", &obj)); sp<AMessage> format; CHECK(msg->findMessage("format", &format)); int32_t push; if (msg->findInt32("push-blank-buffers-on-shutdown", &push) && push != 0) { mFlags |= kFlagPushBlankBuffersOnShutdown; } if (obj != NULL) { format->setObject("native-window", obj); status_t err = handleSetSurface(static_cast<Surface *>(obj.get())); if (err != OK) { PostReplyWithError(replyID, err); break; } } else { handleSetSurface(NULL); } mReplyID = replyID; setState(CONFIGURING); void *crypto; if (!msg->findPointer("crypto", &crypto)) { crypto = NULL; } mCrypto = static_cast<ICrypto *>(crypto); uint32_t flags; CHECK(msg->findInt32("flags", (int32_t *)&flags)); if (flags & CONFIGURE_FLAG_ENCODE) { format->setInt32("encoder", true); mFlags |= kFlagIsEncoder; } extractCSD(format); mCodec->initiateConfigureComponent(format); break; } case kWhatSetSurface: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); status_t err = OK; sp<Surface> surface; switch (mState) { case CONFIGURED: case STARTED: case FLUSHED: { sp<RefBase> obj; (void)msg->findObject("surface", &obj); sp<Surface> surface = static_cast<Surface *>(obj.get()); if (mSurface == NULL) { // do not support setting surface if it was not set err = INVALID_OPERATION; } else if (obj == NULL) { // do not support unsetting surface err = BAD_VALUE; } else { err = connectToSurface(surface); if (err == ALREADY_EXISTS) { // reconnecting to same surface err = OK; } else { if (err == OK) { if (mFlags & kFlagUsesSoftwareRenderer) { if (mSoftRenderer != NULL && (mFlags & kFlagPushBlankBuffersOnShutdown)) { pushBlankBuffersToNativeWindow(mSurface.get()); } mSoftRenderer = new SoftwareRenderer(surface); // TODO: check if this was successful } else { err = mCodec->setSurface(surface); } } if (err == OK) { (void)disconnectFromSurface(); mSurface = surface; } } } break; } default: err = INVALID_OPERATION; break; } PostReplyWithError(replyID, err); break; } case kWhatCreateInputSurface: case kWhatSetInputSurface: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); // Must be configured, but can't have been started yet. if (mState != CONFIGURED) { PostReplyWithError(replyID, INVALID_OPERATION); break; } mReplyID = replyID; if (msg->what() == kWhatCreateInputSurface) { mCodec->initiateCreateInputSurface(); } else { sp<RefBase> obj; CHECK(msg->findObject("input-surface", &obj)); mCodec->initiateSetInputSurface( static_cast<PersistentSurface *>(obj.get())); } break; } case kWhatStart: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (mState == FLUSHED) { setState(STARTED); if (mHavePendingInputBuffers) { onInputBufferAvailable(); mHavePendingInputBuffers = false; } mCodec->signalResume(); PostReplyWithError(replyID, OK); break; } else if (mState != CONFIGURED) { PostReplyWithError(replyID, INVALID_OPERATION); break; } mReplyID = replyID; setState(STARTING); mCodec->initiateStart(); break; } case kWhatStop: case kWhatRelease: { State targetState = (msg->what() == kWhatStop) ? INITIALIZED : UNINITIALIZED; sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); // already stopped/released if (mState == UNINITIALIZED && mReleasedByResourceManager) { sp<AMessage> response = new AMessage; response->setInt32("err", OK); response->postReply(replyID); break; } int32_t reclaimed = 0; msg->findInt32("reclaimed", &reclaimed); if (reclaimed) { mReleasedByResourceManager = true; int32_t force = 0; msg->findInt32("force", &force); if (!force && hasPendingBuffer()) { ALOGW("Can't reclaim codec right now due to pending buffers."); // return WOULD_BLOCK to ask resource manager to retry later. sp<AMessage> response = new AMessage; response->setInt32("err", WOULD_BLOCK); response->postReply(replyID); // notify the async client if (mFlags & kFlagIsAsync) { onError(DEAD_OBJECT, ACTION_CODE_FATAL); } break; } } if (!((mFlags & kFlagIsComponentAllocated) && targetState == UNINITIALIZED) // See 1 && mState != INITIALIZED && mState != CONFIGURED && !isExecuting()) { // 1) Permit release to shut down the component if allocated. // // 2) We may be in "UNINITIALIZED" state already and // also shutdown the encoder/decoder without the // client being aware of this if media server died while // we were being stopped. The client would assume that // after stop() returned, it would be safe to call release() // and it should be in this case, no harm to allow a release() // if we're already uninitialized. sp<AMessage> response = new AMessage; // TODO: we shouldn't throw an exception for stop/release. Change this to wait until // the previous stop/release completes and then reply with OK. status_t err = mState == targetState ? OK : INVALID_OPERATION; response->setInt32("err", err); if (err == OK && targetState == UNINITIALIZED) { mComponentName.clear(); } response->postReply(replyID); break; } if (mFlags & kFlagSawMediaServerDie) { // It's dead, Jim. Don't expect initiateShutdown to yield // any useful results now... setState(UNINITIALIZED); if (targetState == UNINITIALIZED) { mComponentName.clear(); } (new AMessage)->postReply(replyID); break; } mReplyID = replyID; setState(msg->what() == kWhatStop ? STOPPING : RELEASING); mCodec->initiateShutdown( msg->what() == kWhatStop /* keepComponentAllocated */); returnBuffersToCodec(reclaimed); if (mSoftRenderer != NULL && (mFlags & kFlagPushBlankBuffersOnShutdown)) { pushBlankBuffersToNativeWindow(mSurface.get()); } break; } case kWhatDequeueInputBuffer: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (mFlags & kFlagIsAsync) { ALOGE("dequeueOutputBuffer can't be used in async mode"); PostReplyWithError(replyID, INVALID_OPERATION); break; } if (mHaveInputSurface) { ALOGE("dequeueInputBuffer can't be used with input surface"); PostReplyWithError(replyID, INVALID_OPERATION); break; } if (handleDequeueInputBuffer(replyID, true /* new request */)) { break; } int64_t timeoutUs; CHECK(msg->findInt64("timeoutUs", &timeoutUs)); if (timeoutUs == 0ll) { PostReplyWithError(replyID, -EAGAIN); break; } mFlags |= kFlagDequeueInputPending; mDequeueInputReplyID = replyID; if (timeoutUs > 0ll) { sp<AMessage> timeoutMsg = new AMessage(kWhatDequeueInputTimedOut, this); timeoutMsg->setInt32( "generation", ++mDequeueInputTimeoutGeneration); timeoutMsg->post(timeoutUs); } break; } case kWhatDequeueInputTimedOut: { int32_t generation; CHECK(msg->findInt32("generation", &generation)); if (generation != mDequeueInputTimeoutGeneration) { // Obsolete break; } CHECK(mFlags & kFlagDequeueInputPending); PostReplyWithError(mDequeueInputReplyID, -EAGAIN); mFlags &= ~kFlagDequeueInputPending; mDequeueInputReplyID = 0; break; } case kWhatQueueInputBuffer: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (!isExecuting()) { PostReplyWithError(replyID, INVALID_OPERATION); break; } else if (mFlags & kFlagStickyError) { PostReplyWithError(replyID, getStickyError()); break; } status_t err = onQueueInputBuffer(msg); PostReplyWithError(replyID, err); break; } case kWhatDequeueOutputBuffer: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (mFlags & kFlagIsAsync) { ALOGE("dequeueOutputBuffer can't be used in async mode"); PostReplyWithError(replyID, INVALID_OPERATION); break; } if (handleDequeueOutputBuffer(replyID, true /* new request */)) { break; } int64_t timeoutUs; CHECK(msg->findInt64("timeoutUs", &timeoutUs)); if (timeoutUs == 0ll) { PostReplyWithError(replyID, -EAGAIN); break; } mFlags |= kFlagDequeueOutputPending; mDequeueOutputReplyID = replyID; if (timeoutUs > 0ll) { sp<AMessage> timeoutMsg = new AMessage(kWhatDequeueOutputTimedOut, this); timeoutMsg->setInt32( "generation", ++mDequeueOutputTimeoutGeneration); timeoutMsg->post(timeoutUs); } break; } case kWhatDequeueOutputTimedOut: { int32_t generation; CHECK(msg->findInt32("generation", &generation)); if (generation != mDequeueOutputTimeoutGeneration) { // Obsolete break; } CHECK(mFlags & kFlagDequeueOutputPending); PostReplyWithError(mDequeueOutputReplyID, -EAGAIN); mFlags &= ~kFlagDequeueOutputPending; mDequeueOutputReplyID = 0; break; } case kWhatReleaseOutputBuffer: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (!isExecuting()) { PostReplyWithError(replyID, INVALID_OPERATION); break; } else if (mFlags & kFlagStickyError) { PostReplyWithError(replyID, getStickyError()); break; } status_t err = onReleaseOutputBuffer(msg); PostReplyWithError(replyID, err); break; } case kWhatSignalEndOfInputStream: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (!isExecuting()) { PostReplyWithError(replyID, INVALID_OPERATION); break; } else if (mFlags & kFlagStickyError) { PostReplyWithError(replyID, getStickyError()); break; } mReplyID = replyID; mCodec->signalEndOfInputStream(); break; } case kWhatGetBuffers: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); // Unfortunately widevine legacy source requires knowing all of the // codec input buffers, so we have to provide them even in async mode. int32_t widevine = 0; msg->findInt32("widevine", &widevine); if (!isExecuting() || ((mFlags & kFlagIsAsync) && !widevine)) { PostReplyWithError(replyID, INVALID_OPERATION); break; } else if (mFlags & kFlagStickyError) { PostReplyWithError(replyID, getStickyError()); break; } int32_t portIndex; CHECK(msg->findInt32("portIndex", &portIndex)); Vector<sp<ABuffer> > *dstBuffers; CHECK(msg->findPointer("buffers", (void **)&dstBuffers)); dstBuffers->clear(); const Vector<BufferInfo> &srcBuffers = mPortBuffers[portIndex]; for (size_t i = 0; i < srcBuffers.size(); ++i) { const BufferInfo &info = srcBuffers.itemAt(i); dstBuffers->push_back( (portIndex == kPortIndexInput && mCrypto != NULL) ? info.mEncryptedData : info.mData); } (new AMessage)->postReply(replyID); break; } case kWhatFlush: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (!isExecuting()) { PostReplyWithError(replyID, INVALID_OPERATION); break; } else if (mFlags & kFlagStickyError) { PostReplyWithError(replyID, getStickyError()); break; } mReplyID = replyID; // TODO: skip flushing if already FLUSHED setState(FLUSHING); mCodec->signalFlush(); returnBuffersToCodec(); break; } case kWhatGetInputFormat: case kWhatGetOutputFormat: { sp<AMessage> format = (msg->what() == kWhatGetOutputFormat ? mOutputFormat : mInputFormat); sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if ((mState != CONFIGURED && mState != STARTING && mState != STARTED && mState != FLUSHING && mState != FLUSHED) || format == NULL) { PostReplyWithError(replyID, INVALID_OPERATION); break; } else if (mFlags & kFlagStickyError) { PostReplyWithError(replyID, getStickyError()); break; } sp<AMessage> response = new AMessage; response->setMessage("format", format); response->postReply(replyID); break; } case kWhatRequestIDRFrame: { mCodec->signalRequestIDRFrame(); break; } case kWhatRequestActivityNotification: { CHECK(mActivityNotify == NULL); CHECK(msg->findMessage("notify", &mActivityNotify)); postActivityNotificationIfPossible(); break; } case kWhatGetName: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); if (mComponentName.empty()) { PostReplyWithError(replyID, INVALID_OPERATION); break; } sp<AMessage> response = new AMessage; response->setString("name", mComponentName.c_str()); response->postReply(replyID); break; } case kWhatSetParameters: { sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); sp<AMessage> params; CHECK(msg->findMessage("params", &params)); status_t err = onSetParameters(params); PostReplyWithError(replyID, err); break; } default: TRESPASS(); } } void MediaCodec::extractCSD(const sp<AMessage> &format) { mCSD.clear(); size_t i = 0; for (;;) { sp<ABuffer> csd; if (!format->findBuffer(AStringPrintf("csd-%u", i).c_str(), &csd)) { break; } if (csd->size() == 0) { ALOGW("csd-%zu size is 0", i); } mCSD.push_back(csd); ++i; } ALOGV("Found %zu pieces of codec specific data.", mCSD.size()); } status_t MediaCodec::queueCSDInputBuffer(size_t bufferIndex) { CHECK(!mCSD.empty()); const BufferInfo *info = &mPortBuffers[kPortIndexInput].itemAt(bufferIndex); sp<ABuffer> csd = *mCSD.begin(); mCSD.erase(mCSD.begin()); const sp<ABuffer> &codecInputData = (mCrypto != NULL) ? info->mEncryptedData : info->mData; if (csd->size() > codecInputData->capacity()) { return -EINVAL; } memcpy(codecInputData->data(), csd->data(), csd->size()); AString errorDetailMsg; sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, this); msg->setSize("index", bufferIndex); msg->setSize("offset", 0); msg->setSize("size", csd->size()); msg->setInt64("timeUs", 0ll); msg->setInt32("flags", BUFFER_FLAG_CODECCONFIG); msg->setPointer("errorDetailMsg", &errorDetailMsg); return onQueueInputBuffer(msg); } void MediaCodec::setState(State newState) { if (newState == INITIALIZED || newState == UNINITIALIZED) { delete mSoftRenderer; mSoftRenderer = NULL; mCrypto.clear(); handleSetSurface(NULL); mInputFormat.clear(); mOutputFormat.clear(); mFlags &= ~kFlagOutputFormatChanged; mFlags &= ~kFlagOutputBuffersChanged; mFlags &= ~kFlagStickyError; mFlags &= ~kFlagIsEncoder; mFlags &= ~kFlagGatherCodecSpecificData; mFlags &= ~kFlagIsAsync; mStickyError = OK; mActivityNotify.clear(); mCallback.clear(); } if (newState == UNINITIALIZED) { // return any straggling buffers, e.g. if we got here on an error returnBuffersToCodec(); // The component is gone, mediaserver's probably back up already // but should definitely be back up should we try to instantiate // another component.. and the cycle continues. mFlags &= ~kFlagSawMediaServerDie; } mState = newState; cancelPendingDequeueOperations(); updateBatteryStat(); } void MediaCodec::returnBuffersToCodec(bool isReclaim) { returnBuffersToCodecOnPort(kPortIndexInput, isReclaim); returnBuffersToCodecOnPort(kPortIndexOutput, isReclaim); } void MediaCodec::returnBuffersToCodecOnPort(int32_t portIndex, bool isReclaim) { CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); Mutex::Autolock al(mBufferLock); Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; for (size_t i = 0; i < buffers->size(); ++i) { BufferInfo *info = &buffers->editItemAt(i); if (info->mNotify != NULL) { sp<AMessage> msg = info->mNotify; info->mNotify = NULL; if (isReclaim && info->mOwnedByClient) { ALOGD("port %d buffer %zu still owned by client when codec is reclaimed", portIndex, i); } else { info->mMemRef = NULL; info->mOwnedByClient = false; } if (portIndex == kPortIndexInput) { /* no error, just returning buffers */ msg->setInt32("err", OK); } msg->post(); } } mAvailPortBuffers[portIndex].clear(); } size_t MediaCodec::updateBuffers( int32_t portIndex, const sp<AMessage> &msg) { CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); uint32_t bufferID; CHECK(msg->findInt32("buffer-id", (int32_t*)&bufferID)); Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; for (size_t i = 0; i < buffers->size(); ++i) { BufferInfo *info = &buffers->editItemAt(i); if (info->mBufferID == bufferID) { CHECK(info->mNotify == NULL); CHECK(msg->findMessage("reply", &info->mNotify)); info->mFormat = (portIndex == kPortIndexInput) ? mInputFormat : mOutputFormat; mAvailPortBuffers[portIndex].push_back(i); return i; } } TRESPASS(); return 0; } status_t MediaCodec::onQueueInputBuffer(const sp<AMessage> &msg) { size_t index; size_t offset; size_t size; int64_t timeUs; uint32_t flags; CHECK(msg->findSize("index", &index)); CHECK(msg->findSize("offset", &offset)); CHECK(msg->findInt64("timeUs", &timeUs)); CHECK(msg->findInt32("flags", (int32_t *)&flags)); const CryptoPlugin::SubSample *subSamples; size_t numSubSamples; const uint8_t *key; const uint8_t *iv; CryptoPlugin::Mode mode = CryptoPlugin::kMode_Unencrypted; // We allow the simpler queueInputBuffer API to be used even in // secure mode, by fabricating a single unencrypted subSample. CryptoPlugin::SubSample ss; CryptoPlugin::Pattern pattern; if (msg->findSize("size", &size)) { if (mCrypto != NULL) { ss.mNumBytesOfClearData = size; ss.mNumBytesOfEncryptedData = 0; subSamples = &ss; numSubSamples = 1; key = NULL; iv = NULL; pattern.mEncryptBlocks = 0; pattern.mSkipBlocks = 0; } } else { if (mCrypto == NULL) { return -EINVAL; } CHECK(msg->findPointer("subSamples", (void **)&subSamples)); CHECK(msg->findSize("numSubSamples", &numSubSamples)); CHECK(msg->findPointer("key", (void **)&key)); CHECK(msg->findPointer("iv", (void **)&iv)); CHECK(msg->findInt32("encryptBlocks", (int32_t *)&pattern.mEncryptBlocks)); CHECK(msg->findInt32("skipBlocks", (int32_t *)&pattern.mSkipBlocks)); int32_t tmp; CHECK(msg->findInt32("mode", &tmp)); mode = (CryptoPlugin::Mode)tmp; size = 0; for (size_t i = 0; i < numSubSamples; ++i) { size += subSamples[i].mNumBytesOfClearData; size += subSamples[i].mNumBytesOfEncryptedData; } } if (index >= mPortBuffers[kPortIndexInput].size()) { return -ERANGE; } BufferInfo *info = &mPortBuffers[kPortIndexInput].editItemAt(index); if (info->mNotify == NULL || !info->mOwnedByClient) { return -EACCES; } if (offset + size > info->mData->capacity()) { return -EINVAL; } sp<AMessage> reply = info->mNotify; info->mData->setRange(offset, size); info->mData->meta()->setInt64("timeUs", timeUs); if (flags & BUFFER_FLAG_EOS) { info->mData->meta()->setInt32("eos", true); } if (flags & BUFFER_FLAG_CODECCONFIG) { info->mData->meta()->setInt32("csd", true); } if (mCrypto != NULL) { if (size > info->mEncryptedData->capacity()) { return -ERANGE; } AString *errorDetailMsg; CHECK(msg->findPointer("errorDetailMsg", (void **)&errorDetailMsg)); void *dst_pointer = info->mData->base(); ICrypto::DestinationType dst_type = ICrypto::kDestinationTypeOpaqueHandle; if (info->mNativeHandle != NULL) { dst_pointer = (void *)info->mNativeHandle->handle(); dst_type = ICrypto::kDestinationTypeNativeHandle; } else if ((mFlags & kFlagIsSecure) == 0) { dst_type = ICrypto::kDestinationTypeVmPointer; } ssize_t result = mCrypto->decrypt( dst_type, key, iv, mode, pattern, info->mSharedEncryptedBuffer, offset, subSamples, numSubSamples, dst_pointer, errorDetailMsg); if (result < 0) { return result; } info->mData->setRange(0, result); } // synchronization boundary for getBufferAndFormat { Mutex::Autolock al(mBufferLock); info->mOwnedByClient = false; } reply->setBuffer("buffer", info->mData); reply->post(); info->mNotify = NULL; return OK; } //static size_t MediaCodec::CreateFramesRenderedMessage( std::list<FrameRenderTracker::Info> done, sp<AMessage> &msg) { size_t index = 0; for (std::list<FrameRenderTracker::Info>::const_iterator it = done.cbegin(); it != done.cend(); ++it) { if (it->getRenderTimeNs() < 0) { continue; // dropped frame from tracking } msg->setInt64(AStringPrintf("%zu-media-time-us", index).c_str(), it->getMediaTimeUs()); msg->setInt64(AStringPrintf("%zu-system-nano", index).c_str(), it->getRenderTimeNs()); ++index; } return index; } status_t MediaCodec::onReleaseOutputBuffer(const sp<AMessage> &msg) { size_t index; CHECK(msg->findSize("index", &index)); int32_t render; if (!msg->findInt32("render", &render)) { render = 0; } if (!isExecuting()) { return -EINVAL; } if (index >= mPortBuffers[kPortIndexOutput].size()) { return -ERANGE; } BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index); if (info->mNotify == NULL || !info->mOwnedByClient) { return -EACCES; } // synchronization boundary for getBufferAndFormat { Mutex::Autolock al(mBufferLock); info->mOwnedByClient = false; } if (render && info->mData != NULL && info->mData->size() != 0) { info->mNotify->setInt32("render", true); int64_t mediaTimeUs = -1; info->mData->meta()->findInt64("timeUs", &mediaTimeUs); int64_t renderTimeNs = 0; if (!msg->findInt64("timestampNs", &renderTimeNs)) { // use media timestamp if client did not request a specific render timestamp ALOGV("using buffer PTS of %lld", (long long)mediaTimeUs); renderTimeNs = mediaTimeUs * 1000; } info->mNotify->setInt64("timestampNs", renderTimeNs); if (mSoftRenderer != NULL) { std::list<FrameRenderTracker::Info> doneFrames = mSoftRenderer->render( info->mData->data(), info->mData->size(), mediaTimeUs, renderTimeNs, NULL, info->mFormat); // if we are running, notify rendered frames if (!doneFrames.empty() && mState == STARTED && mOnFrameRenderedNotification != NULL) { sp<AMessage> notify = mOnFrameRenderedNotification->dup(); sp<AMessage> data = new AMessage; if (CreateFramesRenderedMessage(doneFrames, data)) { notify->setMessage("data", data); notify->post(); } } } } info->mNotify->post(); info->mNotify = NULL; return OK; } ssize_t MediaCodec::dequeuePortBuffer(int32_t portIndex) { CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); List<size_t> *availBuffers = &mAvailPortBuffers[portIndex]; if (availBuffers->empty()) { return -EAGAIN; } size_t index = *availBuffers->begin(); availBuffers->erase(availBuffers->begin()); BufferInfo *info = &mPortBuffers[portIndex].editItemAt(index); CHECK(!info->mOwnedByClient); { Mutex::Autolock al(mBufferLock); info->mOwnedByClient = true; // set image-data if (info->mFormat != NULL) { sp<ABuffer> imageData; if (info->mFormat->findBuffer("image-data", &imageData)) { info->mData->meta()->setBuffer("image-data", imageData); } int32_t left, top, right, bottom; if (info->mFormat->findRect("crop", &left, &top, &right, &bottom)) { info->mData->meta()->setRect("crop-rect", left, top, right, bottom); } } } return index; } status_t MediaCodec::connectToSurface(const sp<Surface> &surface) { status_t err = OK; if (surface != NULL) { uint64_t oldId, newId; if (mSurface != NULL && surface->getUniqueId(&newId) == NO_ERROR && mSurface->getUniqueId(&oldId) == NO_ERROR && newId == oldId) { ALOGI("[%s] connecting to the same surface. Nothing to do.", mComponentName.c_str()); return ALREADY_EXISTS; } err = native_window_api_connect(surface.get(), NATIVE_WINDOW_API_MEDIA); if (err == OK) { // Require a fresh set of buffers after each connect by using a unique generation // number. Rely on the fact that max supported process id by Linux is 2^22. // PID is never 0 so we don't have to worry that we use the default generation of 0. // TODO: come up with a unique scheme if other producers also set the generation number. static uint32_t mSurfaceGeneration = 0; uint32_t generation = (getpid() << 10) | (++mSurfaceGeneration & ((1 << 10) - 1)); surface->setGenerationNumber(generation); ALOGI("[%s] setting surface generation to %u", mComponentName.c_str(), generation); // HACK: clear any free buffers. Remove when connect will automatically do this. // This is needed as the consumer may be holding onto stale frames that it can reattach // to this surface after disconnect/connect, and those free frames would inherit the new // generation number. Disconnecting after setting a unique generation prevents this. native_window_api_disconnect(surface.get(), NATIVE_WINDOW_API_MEDIA); err = native_window_api_connect(surface.get(), NATIVE_WINDOW_API_MEDIA); } if (err != OK) { ALOGE("native_window_api_connect returned an error: %s (%d)", strerror(-err), err); } } // do not return ALREADY_EXISTS unless surfaces are the same return err == ALREADY_EXISTS ? BAD_VALUE : err; } status_t MediaCodec::disconnectFromSurface() { status_t err = OK; if (mSurface != NULL) { // Resetting generation is not technically needed, but there is no need to keep it either mSurface->setGenerationNumber(0); err = native_window_api_disconnect(mSurface.get(), NATIVE_WINDOW_API_MEDIA); if (err != OK) { ALOGW("native_window_api_disconnect returned an error: %s (%d)", strerror(-err), err); } // assume disconnected even on error mSurface.clear(); } return err; } status_t MediaCodec::handleSetSurface(const sp<Surface> &surface) { status_t err = OK; if (mSurface != NULL) { (void)disconnectFromSurface(); } if (surface != NULL) { err = connectToSurface(surface); if (err == OK) { mSurface = surface; } } return err; } void MediaCodec::onInputBufferAvailable() { int32_t index; while ((index = dequeuePortBuffer(kPortIndexInput)) >= 0) { sp<AMessage> msg = mCallback->dup(); msg->setInt32("callbackID", CB_INPUT_AVAILABLE); msg->setInt32("index", index); msg->post(); } } void MediaCodec::onOutputBufferAvailable() { int32_t index; while ((index = dequeuePortBuffer(kPortIndexOutput)) >= 0) { const sp<ABuffer> &buffer = mPortBuffers[kPortIndexOutput].itemAt(index).mData; sp<AMessage> msg = mCallback->dup(); msg->setInt32("callbackID", CB_OUTPUT_AVAILABLE); msg->setInt32("index", index); msg->setSize("offset", buffer->offset()); msg->setSize("size", buffer->size()); int64_t timeUs; CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); msg->setInt64("timeUs", timeUs); int32_t omxFlags; CHECK(buffer->meta()->findInt32("omxFlags", &omxFlags)); uint32_t flags = 0; if (omxFlags & OMX_BUFFERFLAG_SYNCFRAME) { flags |= BUFFER_FLAG_SYNCFRAME; } if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) { flags |= BUFFER_FLAG_CODECCONFIG; } if (omxFlags & OMX_BUFFERFLAG_EOS) { flags |= BUFFER_FLAG_EOS; } msg->setInt32("flags", flags); msg->post(); } } void MediaCodec::onError(status_t err, int32_t actionCode, const char *detail) { if (mCallback != NULL) { sp<AMessage> msg = mCallback->dup(); msg->setInt32("callbackID", CB_ERROR); msg->setInt32("err", err); msg->setInt32("actionCode", actionCode); if (detail != NULL) { msg->setString("detail", detail); } msg->post(); } } void MediaCodec::onOutputFormatChanged() { if (mCallback != NULL) { sp<AMessage> msg = mCallback->dup(); msg->setInt32("callbackID", CB_OUTPUT_FORMAT_CHANGED); msg->setMessage("format", mOutputFormat); msg->post(); } } void MediaCodec::postActivityNotificationIfPossible() { if (mActivityNotify == NULL) { return; } bool isErrorOrOutputChanged = (mFlags & (kFlagStickyError | kFlagOutputBuffersChanged | kFlagOutputFormatChanged)); if (isErrorOrOutputChanged || !mAvailPortBuffers[kPortIndexInput].empty() || !mAvailPortBuffers[kPortIndexOutput].empty()) { mActivityNotify->setInt32("input-buffers", mAvailPortBuffers[kPortIndexInput].size()); if (isErrorOrOutputChanged) { // we want consumer to dequeue as many times as it can mActivityNotify->setInt32("output-buffers", INT32_MAX); } else { mActivityNotify->setInt32("output-buffers", mAvailPortBuffers[kPortIndexOutput].size()); } mActivityNotify->post(); mActivityNotify.clear(); } } status_t MediaCodec::setParameters(const sp<AMessage> &params) { sp<AMessage> msg = new AMessage(kWhatSetParameters, this); msg->setMessage("params", params); sp<AMessage> response; return PostAndAwaitResponse(msg, &response); } status_t MediaCodec::onSetParameters(const sp<AMessage> &params) { mCodec->signalSetParameters(params); return OK; } status_t MediaCodec::amendOutputFormatWithCodecSpecificData( const sp<ABuffer> &buffer) { AString mime; CHECK(mOutputFormat->findString("mime", &mime)); if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) { // Codec specific data should be SPS and PPS in a single buffer, // each prefixed by a startcode (0x00 0x00 0x00 0x01). // We separate the two and put them into the output format // under the keys "csd-0" and "csd-1". unsigned csdIndex = 0; const uint8_t *data = buffer->data(); size_t size = buffer->size(); const uint8_t *nalStart; size_t nalSize; while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) { sp<ABuffer> csd = new ABuffer(nalSize + 4); memcpy(csd->data(), "\x00\x00\x00\x01", 4); memcpy(csd->data() + 4, nalStart, nalSize); mOutputFormat->setBuffer( AStringPrintf("csd-%u", csdIndex).c_str(), csd); ++csdIndex; } if (csdIndex != 2) { return ERROR_MALFORMED; } } else { // For everything else we just stash the codec specific data into // the output format as a single piece of csd under "csd-0". mOutputFormat->setBuffer("csd-0", buffer); } return OK; } void MediaCodec::updateBatteryStat() { if (!mIsVideo) { return; } if (mState == CONFIGURED && !mBatteryStatNotified) { BatteryNotifier::getInstance().noteStartVideo(); mBatteryStatNotified = true; } else if (mState == UNINITIALIZED && mBatteryStatNotified) { BatteryNotifier::getInstance().noteStopVideo(); mBatteryStatNotified = false; } } } // namespace android
/******************************************************************************* * Copyright 2017-2020 Intel Corporation * * 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. *******************************************************************************/ #ifndef SELF_HPP #define SELF_HPP #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sstream> #include "common.hpp" #include "dnnl_common.hpp" namespace self { #define CHECK(c, ...) \ do { \ if (!(c)) { \ printf("[%s:%d] '%s' FAILED ==> ", __PRETTY_FUNCTION__, __LINE__, \ STRINGIFY(c)); \ printf(" " __VA_ARGS__); \ printf("\n"); \ return FAIL; \ } \ } while (0) #define CHECK_EQ(a, b) CHECK((a) == (b), "%d != %d", (int)(a), (int)(b)) #define CHECK_NE(a, b) CHECK((a) != (b), "%d == %d", (int)(a), (int)(b)) #define CHECK_CASE_STR_EQ(a, b) CHECK(!strcasecmp(a, b), "'%s' != '%s'", a, b) #define CHECK_CASE_STR_NE(a, b) CHECK(strcasecmp(a, b), "'%s' == '%s'", a, b) #define CHECK_CASE_CPP_STR_EQ(a, b) \ CHECK(!strcasecmp(a.c_str(), b), "'%s' != '%s'", a.c_str(), b) #define CHECK_CASE_CPP_STR_NE(a, b) \ CHECK(strcasecmp(a.c_str(), b), "'%s' == '%s'", a.c_str(), b) #define CHECK_PRINT_EQ2(obj, expect_str1, expect_str2) \ do { \ std::stringstream ss; \ ss << obj; \ std::string obj_str = ss.str(); \ if (strcasecmp(obj_str.c_str(), expect_str1) \ && strcasecmp(obj_str.c_str(), expect_str2)) \ CHECK(false, "'%s' one of ('%s', '%s')", obj_str.c_str(), \ expect_str1, expect_str2); \ } while (0) #define CHECK_PRINT_EQ(obj, expect_str) \ CHECK_PRINT_EQ2(obj, expect_str, expect_str) #define RUN(f) \ do { \ BENCHDNN_PRINT(1, "%s ...\n", STRINGIFY(f)); \ int rc = f; \ benchdnn_stat.tests++; \ if (rc == OK) \ benchdnn_stat.passed++; \ else \ benchdnn_stat.failed++; \ } while (0) void common(); void conv(); void bnorm(); int bench(int argc, char **argv); } // namespace self #endif
#ifndef WAS_DIRECT2DCONTEXTBASE_HPP #define WAS_DIRECT2DCONTEXTBASE_HPP #include <d2d1.h> #include <dwrite.h> #include <wincodec.h> #include <unordered_map> #include "NUIE_DrawingContext.hpp" #include "WAS_IncludeWindowsHeaders.hpp" #include "WAS_Direct2DImageLoader.hpp" namespace WAS { class Direct2DHandler { public: Direct2DHandler (); ~Direct2DHandler (); ID2D1Factory* direct2DFactory; IDWriteFactory* directWriteFactory; }; class Direct2DContextBase : public NUIE::NativeDrawingContext { public: Direct2DContextBase (); Direct2DContextBase (const Direct2DImageLoaderPtr& imageLoader); Direct2DContextBase (const Direct2DContextBase& rhs) = delete; virtual ~Direct2DContextBase (); virtual int GetWidth () const override; virtual int GetHeight () const override; virtual void BeginDraw () override; virtual void EndDraw () override; virtual bool NeedToDraw (ItemPreviewMode mode) override; virtual void DrawLine (const NUIE::Point& beg, const NUIE::Point& end, const NUIE::Pen& pen) override; virtual void DrawBezier (const NUIE::Point& p1, const NUIE::Point& p2, const NUIE::Point& p3, const NUIE::Point& p4, const NUIE::Pen& pen) override; virtual void DrawRect (const NUIE::Rect& rect, const NUIE::Pen& pen) override; virtual void FillRect (const NUIE::Rect& rect, const NUIE::Color& color) override; virtual void DrawEllipse (const NUIE::Rect& rect, const NUIE::Pen& pen) override; virtual void FillEllipse (const NUIE::Rect& rect, const NUIE::Color& color) override; virtual void DrawFormattedText (const NUIE::Rect& rect, const NUIE::Font& font, const std::wstring& text, NUIE::HorizontalAnchor hAnchor, NUIE::VerticalAnchor vAnchor, const NUIE::Color& textColor) override; virtual NUIE::Size MeasureText (const NUIE::Font& font, const std::wstring& text) override; virtual bool CanDrawIcon () override; virtual void DrawIcon (const NUIE::Rect& rect, const NUIE::IconId& iconId) override; protected: virtual void InitRenderTarget () = 0; int width; int height; Direct2DHandler direct2DHandler; Direct2DImageLoaderPtr imageLoader; ID2D1RenderTarget* renderTarget; }; } #endif
// // Copyright (c) 2016,2018 CNRS // #include "pinocchio/parsers/python.hpp" #include <iostream> #include <Python.h> #include <boost/shared_ptr.hpp> #include <boost/version.hpp> // Boost 1.58 #if BOOST_VERSION / 100 % 1000 == 58 #include <fstream> #endif namespace pinocchio { namespace python { namespace bp = boost::python; Model buildModel(const std::string & filename, const std::string & model_name, bool verbose) throw (bp::error_already_set) { Py_Initialize(); bp::object main_module = bp::import("__main__"); // Get a dict for the global namespace to exec further python code with bp::dict globals = bp::extract<bp::dict>(main_module.attr("__dict__")); // We need to link to the pinocchio PyWrap. We delegate the dynamic loading to the python interpreter. bp::object cpp_module( (bp::handle<>(bp::borrowed(PyImport_AddModule("libpinocchio_pywrap")))) ); // That's it, you can exec your python script, starting with a model you // can update as you want. try { // Boost 1.58 #if BOOST_VERSION / 100 % 1000 == 58 // Avoid a segv with exec_file // See: https://github.com/boostorg/python/pull/15 std::ifstream t(filename.c_str()); std::stringstream buffer; buffer << t.rdbuf(); bp::exec(buffer.str().c_str(), globals); #else // default implementation bp::exec_file((bp::str)filename, globals); #endif } catch (bp::error_already_set & e) { PyErr_PrintEx(0); } Model model; try { bp::object obj_model = globals[model_name]; model = bp::extract<Model>(obj_model); } catch (bp::error_already_set & e) { PyErr_PrintEx(0); } if (verbose) { std::cout << "Your model has been built. It has " << model.nv; std::cout << " degrees of freedom." << std::endl; } // close interpreter Py_Finalize(); return model; } } // namespace python } // namespace pinocchio
#include <boost/callable_traits/args.hpp>
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/plugins/ppapi/ppb_graphics_2d_impl.h" #include <iterator> #include "base/bind.h" #include "base/debug/trace_event.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/time.h" #include "skia/ext/platform_canvas.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/pp_rect.h" #include "ppapi/c/pp_resource.h" #include "ppapi/c/ppb_graphics_2d.h" #include "ppapi/thunk/enter.h" #include "ppapi/thunk/thunk.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/blit.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h" #include "ui/gfx/skia_util.h" #include "webkit/plugins/ppapi/common.h" #include "webkit/plugins/ppapi/gfx_conversion.h" #include "webkit/plugins/ppapi/ppapi_plugin_instance.h" #include "webkit/plugins/ppapi/ppb_image_data_impl.h" #include "webkit/plugins/ppapi/resource_helper.h" #if defined(OS_MACOSX) #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #endif using ppapi::thunk::EnterResourceNoLock; using ppapi::thunk::PPB_ImageData_API; using ppapi::TrackedCallback; namespace webkit { namespace ppapi { namespace { const int64 kOffscreenCallbackDelayMs = 1000 / 30; // 30 fps // Converts a rect inside an image of the given dimensions. The rect may be // NULL to indicate it should be the entire image. If the rect is outside of // the image, this will do nothing and return false. bool ValidateAndConvertRect(const PP_Rect* rect, int image_width, int image_height, gfx::Rect* dest) { if (!rect) { // Use the entire image area. *dest = gfx::Rect(0, 0, image_width, image_height); } else { // Validate the passed-in area. if (rect->point.x < 0 || rect->point.y < 0 || rect->size.width <= 0 || rect->size.height <= 0) return false; // Check the max bounds, being careful of overflow. if (static_cast<int64>(rect->point.x) + static_cast<int64>(rect->size.width) > static_cast<int64>(image_width)) return false; if (static_cast<int64>(rect->point.y) + static_cast<int64>(rect->size.height) > static_cast<int64>(image_height)) return false; *dest = gfx::Rect(rect->point.x, rect->point.y, rect->size.width, rect->size.height); } return true; } // Scale the rectangle, taking care to round coordinates outward so a // rectangle scaled down then scaled back up by the inverse scale would // fully contain the entire area affected by the original rectangle. gfx::Rect ScaleRectBounds(const gfx::Rect& rect, float scale) { int left = static_cast<int>(floorf(rect.x() * scale)); int top = static_cast<int>(floorf(rect.y() * scale)); int right = static_cast<int>(ceilf((rect.x() + rect.width()) * scale)); int bottom = static_cast<int>(ceilf((rect.y() + rect.height()) * scale)); return gfx::Rect(left, top, right - left, bottom - top); } // Converts BGRA <-> RGBA. void ConvertBetweenBGRAandRGBA(const uint32_t* input, int pixel_length, uint32_t* output) { for (int i = 0; i < pixel_length; i++) { const unsigned char* pixel_in = reinterpret_cast<const unsigned char*>(&input[i]); unsigned char* pixel_out = reinterpret_cast<unsigned char*>(&output[i]); pixel_out[0] = pixel_in[2]; pixel_out[1] = pixel_in[1]; pixel_out[2] = pixel_in[0]; pixel_out[3] = pixel_in[3]; } } // Converts ImageData from PP_IMAGEDATAFORMAT_BGRA_PREMUL to // PP_IMAGEDATAFORMAT_RGBA_PREMUL, or reverse. It's assumed that the // destination image is always mapped (so will have non-NULL data). void ConvertImageData(PPB_ImageData_Impl* src_image, const SkIRect& src_rect, PPB_ImageData_Impl* dest_image, const SkRect& dest_rect) { ImageDataAutoMapper auto_mapper(src_image); DCHECK(src_image->format() != dest_image->format()); DCHECK(PPB_ImageData_Impl::IsImageDataFormatSupported(src_image->format())); DCHECK(PPB_ImageData_Impl::IsImageDataFormatSupported(dest_image->format())); const SkBitmap* src_bitmap = src_image->GetMappedBitmap(); const SkBitmap* dest_bitmap = dest_image->GetMappedBitmap(); if (src_rect.width() == src_image->width() && dest_rect.width() == dest_image->width()) { // Fast path if the full line needs to be converted. ConvertBetweenBGRAandRGBA( src_bitmap->getAddr32(static_cast<int>(src_rect.fLeft), static_cast<int>(src_rect.fTop)), src_rect.width() * src_rect.height(), dest_bitmap->getAddr32(static_cast<int>(dest_rect.fLeft), static_cast<int>(dest_rect.fTop))); } else { // Slow path where we convert line by line. for (int y = 0; y < src_rect.height(); y++) { ConvertBetweenBGRAandRGBA( src_bitmap->getAddr32(static_cast<int>(src_rect.fLeft), static_cast<int>(src_rect.fTop + y)), src_rect.width(), dest_bitmap->getAddr32(static_cast<int>(dest_rect.fLeft), static_cast<int>(dest_rect.fTop + y))); } } } } // namespace struct PPB_Graphics2D_Impl::QueuedOperation { enum Type { PAINT, SCROLL, REPLACE }; QueuedOperation(Type t) : type(t), paint_x(0), paint_y(0), scroll_dx(0), scroll_dy(0) { } Type type; // Valid when type == PAINT. scoped_refptr<PPB_ImageData_Impl> paint_image; int paint_x, paint_y; gfx::Rect paint_src_rect; // Valid when type == SCROLL. gfx::Rect scroll_clip_rect; int scroll_dx, scroll_dy; // Valid when type == REPLACE. scoped_refptr<PPB_ImageData_Impl> replace_image; }; PPB_Graphics2D_Impl::PPB_Graphics2D_Impl(PP_Instance instance) : Resource(::ppapi::OBJECT_IS_IMPL, instance), bound_instance_(NULL), offscreen_flush_pending_(false), is_always_opaque_(false), scale_(1.0f), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { } PPB_Graphics2D_Impl::~PPB_Graphics2D_Impl() { // LastPluginRefWasDeleted should have aborted all pending callbacks. DCHECK(painted_flush_callback_.is_null()); DCHECK(unpainted_flush_callback_.is_null()); } // static PP_Resource PPB_Graphics2D_Impl::Create(PP_Instance instance, const PP_Size& size, PP_Bool is_always_opaque) { scoped_refptr<PPB_Graphics2D_Impl> graphics_2d( new PPB_Graphics2D_Impl(instance)); if (!graphics_2d->Init(size.width, size.height, PPBoolToBool(is_always_opaque))) { return 0; } return graphics_2d->GetReference(); } bool PPB_Graphics2D_Impl::Init(int width, int height, bool is_always_opaque) { // The underlying PPB_ImageData_Impl will validate the dimensions. image_data_ = new PPB_ImageData_Impl(pp_instance(), PPB_ImageData_Impl::PLATFORM); if (!image_data_->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(), width, height, true) || !image_data_->Map()) { image_data_ = NULL; return false; } is_always_opaque_ = is_always_opaque; scale_ = 1.0f; return true; } ::ppapi::thunk::PPB_Graphics2D_API* PPB_Graphics2D_Impl::AsPPB_Graphics2D_API() { return this; } void PPB_Graphics2D_Impl::LastPluginRefWasDeleted() { Resource::LastPluginRefWasDeleted(); // Abort any pending callbacks. unpainted_flush_callback_.PostAbort(); painted_flush_callback_.PostAbort(); } PP_Bool PPB_Graphics2D_Impl::Describe(PP_Size* size, PP_Bool* is_always_opaque) { size->width = image_data_->width(); size->height = image_data_->height(); *is_always_opaque = PP_FromBool(is_always_opaque_); return PP_TRUE; } void PPB_Graphics2D_Impl::PaintImageData(PP_Resource image_data, const PP_Point* top_left, const PP_Rect* src_rect) { if (!top_left) return; EnterResourceNoLock<PPB_ImageData_API> enter(image_data, true); if (enter.failed()) { Log(PP_LOGLEVEL_ERROR, "PPB_Graphics2D.PaintImageData: Bad image resource."); return; } PPB_ImageData_Impl* image_resource = static_cast<PPB_ImageData_Impl*>(enter.object()); QueuedOperation operation(QueuedOperation::PAINT); operation.paint_image = image_resource; if (!ValidateAndConvertRect(src_rect, image_resource->width(), image_resource->height(), &operation.paint_src_rect)) return; // Validate the bitmap position using the previously-validated rect, there // should be no painted area outside of the image. int64 x64 = static_cast<int64>(top_left->x); int64 y64 = static_cast<int64>(top_left->y); if (x64 + static_cast<int64>(operation.paint_src_rect.x()) < 0 || x64 + static_cast<int64>(operation.paint_src_rect.right()) > image_data_->width()) return; if (y64 + static_cast<int64>(operation.paint_src_rect.y()) < 0 || y64 + static_cast<int64>(operation.paint_src_rect.bottom()) > image_data_->height()) return; operation.paint_x = top_left->x; operation.paint_y = top_left->y; queued_operations_.push_back(operation); } void PPB_Graphics2D_Impl::Scroll(const PP_Rect* clip_rect, const PP_Point* amount) { QueuedOperation operation(QueuedOperation::SCROLL); if (!ValidateAndConvertRect(clip_rect, image_data_->width(), image_data_->height(), &operation.scroll_clip_rect)) return; // If we're being asked to scroll by more than the clip rect size, just // ignore this scroll command and say it worked. int32 dx = amount->x; int32 dy = amount->y; if (dx <= -image_data_->width() || dx >= image_data_->width() || dy <= -image_data_->height() || dy >= image_data_->height()) { Log(PP_LOGLEVEL_ERROR, "PPB_Graphics2D.Scroll: Scroll amount is larger than image size."); return; } operation.scroll_dx = dx; operation.scroll_dy = dy; queued_operations_.push_back(operation); } void PPB_Graphics2D_Impl::ReplaceContents(PP_Resource image_data) { EnterResourceNoLock<PPB_ImageData_API> enter(image_data, true); if (enter.failed()) return; PPB_ImageData_Impl* image_resource = static_cast<PPB_ImageData_Impl*>(enter.object()); if (!PPB_ImageData_Impl::IsImageDataFormatSupported( image_resource->format())) { Log(PP_LOGLEVEL_ERROR, "PPB_Graphics2D.ReplaceContents: Image data format is not supported."); return; } if (image_resource->width() != image_data_->width() || image_resource->height() != image_data_->height()) { Log(PP_LOGLEVEL_ERROR, "PPB_Graphics2D.ReplaceContents: Image size doesn't match " "Graphics2D size."); return; } QueuedOperation operation(QueuedOperation::REPLACE); operation.replace_image = image_resource; queued_operations_.push_back(operation); } int32_t PPB_Graphics2D_Impl::Flush(scoped_refptr<TrackedCallback> callback, PP_Resource* old_image_data) { TRACE_EVENT0("pepper", "PPB_Graphics2D_Impl::Flush"); // Don't allow more than one pending flush at a time. if (HasPendingFlush()) return PP_ERROR_INPROGRESS; bool done_replace_contents = false; bool no_update_visible = true; bool is_plugin_visible = true; for (size_t i = 0; i < queued_operations_.size(); i++) { QueuedOperation& operation = queued_operations_[i]; gfx::Rect op_rect; switch (operation.type) { case QueuedOperation::PAINT: ExecutePaintImageData(operation.paint_image, operation.paint_x, operation.paint_y, operation.paint_src_rect, &op_rect); break; case QueuedOperation::SCROLL: ExecuteScroll(operation.scroll_clip_rect, operation.scroll_dx, operation.scroll_dy, &op_rect); break; case QueuedOperation::REPLACE: // Since the out parameter |old_image_data| takes ownership of the // reference, if there are more than one ReplaceContents calls queued // the first |old_image_data| will get overwritten and leaked. So we // only supply this for the first call. ExecuteReplaceContents(operation.replace_image, &op_rect, done_replace_contents ? NULL : old_image_data); done_replace_contents = true; break; } // For correctness with accelerated compositing, we must issue an invalidate // on the full op_rect even if it is partially or completely off-screen. // However, if we issue an invalidate for a clipped-out region, WebKit will // do nothing and we won't get any ViewWillInitiatePaint/ViewFlushedPaint // calls, leaving our callback stranded. So we still need to check whether // the repainted area is visible to determine how to deal with the callback. if (bound_instance_ && !op_rect.IsEmpty()) { gfx::Point scroll_delta(operation.scroll_dx, operation.scroll_dy); if (!ConvertToLogicalPixels(scale_, &op_rect, operation.type == QueuedOperation::SCROLL ? &scroll_delta : NULL)) { // Conversion requires falling back to InvalidateRect. operation.type = QueuedOperation::PAINT; } gfx::Rect clip = PP_ToGfxRect(bound_instance_->view_data().clip_rect); is_plugin_visible = !clip.IsEmpty(); // Set |no_update_visible| to false if the change overlaps the visible // area. gfx::Rect visible_changed_rect = clip.Intersect(op_rect); if (!visible_changed_rect.IsEmpty()) no_update_visible = false; // Notify the plugin of the entire change (op_rect), even if it is // partially or completely off-screen. if (operation.type == QueuedOperation::SCROLL) { bound_instance_->ScrollRect(scroll_delta.x(), scroll_delta.y(), op_rect); } else { bound_instance_->InvalidateRect(op_rect); } } } queued_operations_.clear(); if (!bound_instance_) { // As promised in the API, we always schedule callback when unbound. ScheduleOffscreenCallback(FlushCallbackData(callback)); } else if (no_update_visible && is_plugin_visible && bound_instance_->view_data().is_page_visible) { // There's nothing visible to invalidate so just schedule the callback to // execute in the next round of the message loop. ScheduleOffscreenCallback(FlushCallbackData(callback)); } else { unpainted_flush_callback_.Set(callback); } return PP_OK_COMPLETIONPENDING; } bool PPB_Graphics2D_Impl::SetScale(float scale) { if (scale > 0.0f) { scale_ = scale; return true; } return false; } float PPB_Graphics2D_Impl::GetScale() { return scale_; } bool PPB_Graphics2D_Impl::ReadImageData(PP_Resource image, const PP_Point* top_left) { // Get and validate the image object to paint into. EnterResourceNoLock<PPB_ImageData_API> enter(image, true); if (enter.failed()) return false; PPB_ImageData_Impl* image_resource = static_cast<PPB_ImageData_Impl*>(enter.object()); if (!PPB_ImageData_Impl::IsImageDataFormatSupported( image_resource->format())) return false; // Must be in the right format. // Validate the bitmap position. int x = top_left->x; if (x < 0 || static_cast<int64>(x) + static_cast<int64>(image_resource->width()) > image_data_->width()) return false; int y = top_left->y; if (y < 0 || static_cast<int64>(y) + static_cast<int64>(image_resource->height()) > image_data_->height()) return false; ImageDataAutoMapper auto_mapper(image_resource); if (!auto_mapper.is_valid()) return false; SkIRect src_irect = { x, y, x + image_resource->width(), y + image_resource->height() }; SkRect dest_rect = { SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(image_resource->width()), SkIntToScalar(image_resource->height()) }; if (image_resource->format() != image_data_->format()) { // Convert the image data if the format does not match. ConvertImageData(image_data_, src_irect, image_resource, dest_rect); } else { SkCanvas* dest_canvas = image_resource->GetCanvas(); // We want to replace the contents of the bitmap rather than blend. SkPaint paint; paint.setXfermodeMode(SkXfermode::kSrc_Mode); dest_canvas->drawBitmapRect(*image_data_->GetMappedBitmap(), &src_irect, dest_rect, &paint); } return true; } bool PPB_Graphics2D_Impl::BindToInstance(PluginInstance* new_instance) { if (bound_instance_ == new_instance) return true; // Rebinding the same device, nothing to do. if (bound_instance_ && new_instance) return false; // Can't change a bound device. if (!new_instance) { // When the device is detached, we'll not get any more paint callbacks so // we need to clear the list, but we still want to issue any pending // callbacks to the plugin. if (!unpainted_flush_callback_.is_null()) { FlushCallbackData callback; std::swap(callback, unpainted_flush_callback_); ScheduleOffscreenCallback(callback); } if (!painted_flush_callback_.is_null()) { FlushCallbackData callback; std::swap(callback, painted_flush_callback_); ScheduleOffscreenCallback(callback); } } else { // Devices being replaced, redraw the plugin. new_instance->InvalidateRect(gfx::Rect()); } bound_instance_ = new_instance; return true; } // The |backing_bitmap| must be clipped to the |plugin_rect| to avoid painting // outside the plugin area. This can happen if the plugin has been resized since // PaintImageData verified the image is within the plugin size. void PPB_Graphics2D_Impl::Paint(WebKit::WebCanvas* canvas, const gfx::Rect& plugin_rect, const gfx::Rect& paint_rect) { TRACE_EVENT0("pepper", "PPB_Graphics2D_Impl::Paint"); ImageDataAutoMapper auto_mapper(image_data_); const SkBitmap& backing_bitmap = *image_data_->GetMappedBitmap(); #if defined(OS_MACOSX) && !defined(USE_SKIA) SkAutoLockPixels lock(backing_bitmap); base::mac::ScopedCFTypeRef<CGDataProviderRef> data_provider( CGDataProviderCreateWithData( NULL, backing_bitmap.getAddr32(0, 0), backing_bitmap.rowBytes() * backing_bitmap.height(), NULL)); base::mac::ScopedCFTypeRef<CGImageRef> image( CGImageCreate( backing_bitmap.width(), backing_bitmap.height(), 8, 32, backing_bitmap.rowBytes(), base::mac::GetSystemColorSpace(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, data_provider, NULL, false, kCGRenderingIntentDefault)); // Flip the transform gfx::ScopedCGContextSaveGState save_gstate(canvas) float window_height = static_cast<float>(CGBitmapContextGetHeight(canvas)); CGContextTranslateCTM(canvas, 0, window_height); CGContextScaleCTM(canvas, 1.0, -1.0); // To avoid painting outside the plugin boundaries and clip instead of // scaling, CGContextDrawImage() must draw the full image using |bitmap_rect| // but the context must be clipped to the plugin using |bounds|. CGRect bitmap_rect; bitmap_rect.origin.x = plugin_rect.origin().x(); bitmap_rect.origin.y = window_height - plugin_rect.origin().y() - backing_bitmap.height(); bitmap_rect.size.width = backing_bitmap.width(); bitmap_rect.size.height = backing_bitmap.height(); CGRect bounds; bounds.origin.x = plugin_rect.origin().x(); bounds.origin.y = window_height - plugin_rect.origin().y() - plugin_rect.height(); bounds.size.width = plugin_rect.width(); bounds.size.height = plugin_rect.height(); // TODO(yzshen): We should take |paint_rect| into consideration as well. CGContextClipToRect(canvas, bounds); // TODO(jhorwich) Figure out if this code is even active anymore, and if so // how to properly handle scaling. DCHECK_EQ(1.0f, scale_); // TODO(brettw) bug 56673: do a direct memcpy instead of going through CG // if the is_always_opaque_ flag is set. Must ensure bitmap is still clipped. CGContextDrawImage(canvas, bitmap_rect, image); #else gfx::Rect invalidate_rect = plugin_rect.Intersect(paint_rect); SkRect sk_invalidate_rect = gfx::RectToSkRect(invalidate_rect); SkAutoCanvasRestore auto_restore(canvas, true); canvas->clipRect(sk_invalidate_rect); gfx::Size pixel_image_size(image_data_->width(), image_data_->height()); gfx::Size image_size = pixel_image_size.Scale(scale_); PluginInstance* plugin_instance = ResourceHelper::GetPluginInstance(this); if (!plugin_instance) return; if (plugin_instance->IsFullPagePlugin()) { // When we're resizing a window with a full-frame plugin, the plugin may // not yet have bound a new device, which will leave parts of the // background exposed if the window is getting larger. We want this to // show white (typically less jarring) rather than black or uninitialized. // We don't do this for non-full-frame plugins since we specifically want // the page background to show through. SkAutoCanvasRestore auto_restore(canvas, true); SkRect image_data_rect = gfx::RectToSkRect(gfx::Rect(plugin_rect.origin(), image_size)); canvas->clipRect(image_data_rect, SkRegion::kDifference_Op); SkPaint paint; paint.setXfermodeMode(SkXfermode::kSrc_Mode); paint.setColor(SK_ColorWHITE); canvas->drawRect(sk_invalidate_rect, paint); } SkBitmap image; // Copy to device independent bitmap when target canvas doesn't support // platform paint. if (!skia::SupportsPlatformPaint(canvas)) backing_bitmap.copyTo(&image, SkBitmap::kARGB_8888_Config); else image = backing_bitmap; SkPaint paint; if (is_always_opaque_) { // When we know the device is opaque, we can disable blending for slightly // more optimized painting. paint.setXfermodeMode(SkXfermode::kSrc_Mode); } SkPoint origin; origin.set(SkIntToScalar(plugin_rect.x()), SkIntToScalar(plugin_rect.y())); SkPoint pixel_origin = origin; if (scale_ != 1.0f && scale_ > 0.0f) { float inverse_scale = 1.0f / scale_; pixel_origin.scale(inverse_scale); canvas->scale(scale_, scale_); } canvas->drawBitmap(image, pixel_origin.x(), pixel_origin.y(), &paint); #endif } void PPB_Graphics2D_Impl::ViewWillInitiatePaint() { // Move any "unpainted" callback to the painted state. See // |unpainted_flush_callback_| in the header for more. if (!unpainted_flush_callback_.is_null()) { DCHECK(painted_flush_callback_.is_null()); std::swap(painted_flush_callback_, unpainted_flush_callback_); } } void PPB_Graphics2D_Impl::ViewInitiatedPaint() { } void PPB_Graphics2D_Impl::ViewFlushedPaint() { TRACE_EVENT0("pepper", "PPB_Graphics2D_Impl::ViewFlushedPaint"); // Notify any "painted" callback. See |unpainted_flush_callback_| in the // header for more. if (!painted_flush_callback_.is_null()) painted_flush_callback_.Execute(PP_OK); } // static bool PPB_Graphics2D_Impl::ConvertToLogicalPixels(float scale, gfx::Rect* op_rect, gfx::Point* delta) { if (scale == 1.0f || scale <= 0.0f) return true; gfx::Rect original_rect = *op_rect; *op_rect = ScaleRectBounds(*op_rect, scale); if (delta) { gfx::Point original_delta = *delta; float inverse_scale = 1.0f / scale; *delta = delta->Scale(scale); if (original_rect != ScaleRectBounds(*op_rect, inverse_scale) || original_delta != delta->Scale(inverse_scale)) { return false; } } return true; } void PPB_Graphics2D_Impl::ExecutePaintImageData(PPB_ImageData_Impl* image, int x, int y, const gfx::Rect& src_rect, gfx::Rect* invalidated_rect) { // Ensure the source image is mapped to read from it. ImageDataAutoMapper auto_mapper(image); if (!auto_mapper.is_valid()) return; // Portion within the source image to cut out. SkIRect src_irect = { src_rect.x(), src_rect.y(), src_rect.right(), src_rect.bottom() }; // Location within the backing store to copy to. *invalidated_rect = src_rect; invalidated_rect->Offset(x, y); SkRect dest_rect = { SkIntToScalar(invalidated_rect->x()), SkIntToScalar(invalidated_rect->y()), SkIntToScalar(invalidated_rect->right()), SkIntToScalar(invalidated_rect->bottom()) }; if (image->format() != image_data_->format()) { // Convert the image data if the format does not match. ConvertImageData(image, src_irect, image_data_, dest_rect); } else { // We're guaranteed to have a mapped canvas since we mapped it in Init(). SkCanvas* backing_canvas = image_data_->GetCanvas(); // We want to replace the contents of the bitmap rather than blend. SkPaint paint; paint.setXfermodeMode(SkXfermode::kSrc_Mode); backing_canvas->drawBitmapRect(*image->GetMappedBitmap(), &src_irect, dest_rect, &paint); } } void PPB_Graphics2D_Impl::ExecuteScroll(const gfx::Rect& clip, int dx, int dy, gfx::Rect* invalidated_rect) { gfx::ScrollCanvas(image_data_->GetCanvas(), clip, gfx::Point(dx, dy)); *invalidated_rect = clip; } void PPB_Graphics2D_Impl::ExecuteReplaceContents(PPB_ImageData_Impl* image, gfx::Rect* invalidated_rect, PP_Resource* old_image_data) { if (image->format() != image_data_->format()) { DCHECK(image->width() == image_data_->width() && image->height() == image_data_->height()); // Convert the image data if the format does not match. SkIRect src_irect = { 0, 0, image->width(), image->height() }; SkRect dest_rect = { SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(image_data_->width()), SkIntToScalar(image_data_->height()) }; ConvertImageData(image, src_irect, image_data_, dest_rect); } else { // The passed-in image may not be mapped in our process, and we need to // guarantee that the current backing store is always mapped. if (!image->Map()) return; if (old_image_data) *old_image_data = image_data_->GetReference(); image_data_ = image; } *invalidated_rect = gfx::Rect(0, 0, image_data_->width(), image_data_->height()); } void PPB_Graphics2D_Impl::ScheduleOffscreenCallback( const FlushCallbackData& callback) { DCHECK(!HasPendingFlush()); offscreen_flush_pending_ = true; MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PPB_Graphics2D_Impl::ExecuteOffscreenCallback, weak_ptr_factory_.GetWeakPtr(), callback), base::TimeDelta::FromMilliseconds(kOffscreenCallbackDelayMs)); } void PPB_Graphics2D_Impl::ExecuteOffscreenCallback(FlushCallbackData data) { DCHECK(offscreen_flush_pending_); // We must clear this flag before issuing the callback. It will be // common for the plugin to issue another invalidate in response to a flush // callback, and we don't want to think that a callback is already pending. offscreen_flush_pending_ = false; data.Execute(PP_OK); } bool PPB_Graphics2D_Impl::HasPendingFlush() const { return !unpainted_flush_callback_.is_null() || !painted_flush_callback_.is_null() || offscreen_flush_pending_; } } // namespace ppapi } // namespace webkit
// Author(s): A.J. (Hannes) pretorius // Copyright: see the accompanying file COPYING or copy at // https://github.com/mCRL2org/mCRL2/blob/master/COPYING // // 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) // /// \file ./attrdiscr.cpp #include "mcrl2/utilities/exception.h" #include "attrdiscr.h" // -- constructors and destructor ----------------------------------- AttrDiscr::AttrDiscr( QString name, QString type, const std::size_t& idx, const std::vector< std::string >& vals) : Attribute(name, type, idx) { initValues(vals); } AttrDiscr::AttrDiscr(const AttrDiscr& attr) :Attribute(attr) { { for (std::size_t i = 0; i < attr.origValues.size(); ++i) { origValues.push_back(new Value(*(attr.origValues[i]))); } } { for (std::size_t i = 0; i < attr.curValues.size(); ++i) { curValues.push_back(new Value(*(attr.curValues[i]))); } } Value** mapping; { for (std::size_t i = 0; i < attr.curMap.size(); ++i) { mapping = new Value*; *mapping = curValues[(*attr.curMap[i])->getIndex() ]; curMap.push_back(mapping); } } mapping = 0; } AttrDiscr::~AttrDiscr() { deleteOrigValues(); deleteCurValues(); deleteCurMap(); } // -- set functions ------------------------------------------------- void AttrDiscr::clusterValues( const std::vector< int >& indices, const std::string& newValue) { try { // variables std::vector< int > sorted; Value* value; std::vector< std::vector< Value* >::iterator > toRemove; // sort indices in ascending order sorted = indices; sort(sorted.begin(), sorted.end()); // ptr to new value value = new Value(NON_EXISTING, newValue); // update current map { for (std::size_t i = 0; i < curMap.size(); ++i) { for (std::size_t j = 0; j < sorted.size(); ++j) { if (*curMap[i] == curValues[sorted[j]]) { *curMap[i] = value; } } } } // update current domain // get iterators to values to delete { for (std::size_t i = 0; i < sorted.size(); ++i) { toRemove.push_back(curValues.begin() + sorted[i]); } } // delete these values { for (std::size_t i = 0; i < toRemove.size(); ++i) { // delete object delete *(toRemove[i]); } } { for (std::size_t i = toRemove.size(); i > 0; --i) { // remove ptr from current domain curValues.erase(toRemove[i-1]); } } // update index value->setIndex(sorted[0]); // insert new value curValues.insert(curValues.begin() + sorted[0], value); // update value indices after new one { for (std::size_t i = sorted[0]; i < curValues.size(); ++i) { curValues[i]->setIndex(i); } } // -*- value = 0; } catch (...) { throw mcrl2::runtime_error("Error clustering attribute domain."); } emit changed(); } void AttrDiscr::moveValue( const std::size_t& idxFr, const std::size_t& idxTo) { try { Value* temp = curValues[idxFr]; // 2 cases to consider if (idxFr < idxTo) { // move all values after idxFr 1 pos up for (std::size_t i = idxFr; i < idxTo; ++i) { curValues[i] = curValues[i+1]; curValues[i]->setIndex(i); } // update idxTo curValues[idxTo] = temp; curValues[idxTo]->setIndex(idxTo); } else if (idxTo < idxFr) { // move all values before idxFr 1 pos down for (std::size_t i = idxFr; i > idxTo; --i) { curValues[i] = curValues[i-1]; curValues[i]->setIndex(i); } // update idxTo curValues[idxTo] = temp; curValues[idxTo]->setIndex(idxTo); } temp = 0; } catch (...) { throw mcrl2::runtime_error("Error moving attribute domain value."); } emit changed(); } void AttrDiscr::configValues( const std::vector< std::string >& curDomain, std::map< std::size_t , std::size_t >& origToCurDomain) { try { // clear current values { for (std::size_t i = 0; i < curValues.size(); ++i) { delete curValues[i]; curValues[i] = 0; } } curValues.clear(); // clear current map curMap.clear(); // re-init current values { for (std::size_t i = 0; i < curDomain.size(); ++i) { curValues.push_back(new Value(i, curDomain[i])); } } // re-init mapping to current values Value** mapping; { for (std::size_t i = 0; i < origToCurDomain.size(); ++i) { mapping = new Value*; *mapping = curValues[ origToCurDomain[i] ]; curMap.push_back(mapping); } } mapping = 0; } catch (const mcrl2::runtime_error& e) { throw mcrl2::runtime_error(std::string("Error configuring attribute domain values.\n") + std::string(e.what())); } emit changed(); } // -- get functions ------------------------------------------------- std::size_t AttrDiscr::getSizeOrigValues() { return origValues.size(); } Value* AttrDiscr::getOrigValue(std::size_t idx) { if (idx != NON_EXISTING && idx < origValues.size()) { return origValues[idx]; } else throw mcrl2::runtime_error( "Error retrieving attribute value from original domain."); } std::size_t AttrDiscr::getSizeCurValues() { return curValues.size(); } Value* AttrDiscr::getCurValue(std::size_t idx) { if (idx != NON_EXISTING && idx < curValues.size()) { return curValues[idx]; } else throw mcrl2::runtime_error( "Error retrieving attribute value from current domain."); } std::size_t AttrDiscr::getSizeMap() { return curMap.size(); } Value* AttrDiscr::mapToValue(double key) { std::size_t idx = static_cast <std::size_t>(key); if (idx < curMap.size()) { return *curMap[idx]; } else throw mcrl2::runtime_error( "Error mapping index to current attribute value."); } // -- clear functions ----------------------------------------------- void AttrDiscr::clearClusters() { resetCurValues(); emit changed(); } // -- private utility functions ------------------------------------- void AttrDiscr::initValues(const std::vector< std::string >& vals) { Value* value0 = 0; Value* value1 = 0; Value** mapping = 0; // init orig & current domain, current map for (std::size_t i = 0; i < vals.size(); ++i) { // init new values value0 = new Value(i, vals[i]); value1 = new Value(i, vals[i]); // init domains origValues.push_back(value0); curValues.push_back(value1); // init mapping: pointer to pointer mapping = new Value*; *mapping = value1; curMap.push_back(mapping); } value0 = 0; value1 = 0; mapping = 0; } void AttrDiscr::resetCurValues() { Value* value = 0; Value** mapping = 0; // clear current domain & mapping deleteCurValues(); deleteCurMap(); // reset current domain to original & update mapping for (std::size_t i = 0; i < origValues.size(); ++i) { // call copy constructor value = new Value( origValues[i]->getIndex(), origValues[i]->getValue()); // init domain curValues.push_back(value); // init mapping: pointer to pointer mapping = new Value*; *mapping = value; curMap.push_back(mapping); } value = 0; mapping = 0; } void AttrDiscr::deleteOrigValues() { for (std::size_t i = 0; i < origValues.size(); ++i) { delete origValues[i]; origValues[i] = 0; } origValues.clear(); } void AttrDiscr::deleteCurValues() { for (std::size_t i = 0; i < curValues.size(); ++i) { delete curValues[i]; curValues[i] = 0; } curValues.clear(); } void AttrDiscr::deleteCurMap() { for (std::size_t i = 0; i < curMap.size(); ++i) { delete curMap[i]; curMap[i] = 0; } curMap.clear(); } // -- end -----------------------------------------------------------
/* * Copyright 2017 Facebook, Inc. * * 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 <folly/io/async/EventBaseThread.h> #include <chrono> #include <folly/io/async/EventBaseManager.h> #include <folly/portability/GTest.h> #include <folly/synchronization/Baton.h> #include <folly/system/ThreadName.h> using namespace std; using namespace std::chrono; using namespace folly; class EventBaseThreadTest : public testing::Test {}; TEST_F(EventBaseThreadTest, example) { EventBaseThread ebt(true, nullptr, "monkey"); Baton<> done; ebt.getEventBase()->runInEventBaseThread([&] { EXPECT_EQ(getCurrentThreadName().value(), "monkey"); done.post(); }); ASSERT_TRUE(done.try_wait_for(seconds(1))); } TEST_F(EventBaseThreadTest, start_stop) { EventBaseThread ebt(false); for (size_t i = 0; i < 4; ++i) { EXPECT_EQ(nullptr, ebt.getEventBase()); ebt.start(); EXPECT_NE(nullptr, ebt.getEventBase()); Baton<> done; ebt.getEventBase()->runInEventBaseThread([&] { done.post(); }); ASSERT_TRUE(done.try_wait_for(seconds(1))); EXPECT_NE(nullptr, ebt.getEventBase()); ebt.stop(); EXPECT_EQ(nullptr, ebt.getEventBase()); } } TEST_F(EventBaseThreadTest, move) { auto ebt0 = EventBaseThread(); auto ebt1 = std::move(ebt0); auto ebt2 = std::move(ebt1); EXPECT_EQ(nullptr, ebt0.getEventBase()); EXPECT_EQ(nullptr, ebt1.getEventBase()); EXPECT_NE(nullptr, ebt2.getEventBase()); Baton<> done; ebt2.getEventBase()->runInEventBaseThread([&] { done.post(); }); ASSERT_TRUE(done.try_wait_for(seconds(1))); } TEST_F(EventBaseThreadTest, self_move) { EventBaseThread ebt0; auto ebt = std::move(ebt0); EXPECT_NE(nullptr, ebt.getEventBase()); Baton<> done; ebt.getEventBase()->runInEventBaseThread([&] { done.post(); }); ASSERT_TRUE(done.try_wait_for(seconds(1))); } TEST_F(EventBaseThreadTest, default_manager) { auto ebm = EventBaseManager::get(); EventBaseThread ebt; auto ebt_eb = ebt.getEventBase(); auto ebm_eb = static_cast<EventBase*>(nullptr); ebt_eb->runInEventBaseThreadAndWait([&] { ebm_eb = ebm->getEventBase(); }); EXPECT_EQ(uintptr_t(ebt_eb), uintptr_t(ebm_eb)); } TEST_F(EventBaseThreadTest, custom_manager) { EventBaseManager ebm; EventBaseThread ebt(&ebm); auto ebt_eb = ebt.getEventBase(); auto ebm_eb = static_cast<EventBase*>(nullptr); ebt_eb->runInEventBaseThreadAndWait([&] { ebm_eb = ebm.getEventBase(); }); EXPECT_EQ(uintptr_t(ebt_eb), uintptr_t(ebm_eb)); }
#include "../stroustrup/std_lib_facilities.h" //CAP 6 EX 04 class Name_value{ public: string something; int value; Name_value(string n, int v) :something(n), value(v) {} }; bool check_repeating(vector<Name_value>names, string name) { for (Name_value h: names) { if (h.something==name) { return true; } } return false; } int main() { string name; int age = 0; vector<Name_value> list; while (true) { cout<<"Please enter a name followed by age:\n\t"; cin>>name>>age; if (name=="NoName" && age==0) { break; } else if (check_repeating(list,name)) { cout<<"\nThat name was already entered. Please pick another name!\n"; } else { list.push_back(Name_value{name, age}); } } for (int i = 0; i < list.size(); i++) { cout<<list[i].something<<" aged "<<list[i].value<<".\n"; } }
// This file is generated by Ubpa::USRefl::AutoRefl #pragma once #include <USRefl/USRefl.h> template<> struct Ubpa::USRefl::TypeInfo<Ubpa::UECS::SystemMngr> : TypeInfoBase<Ubpa::UECS::SystemMngr> { #ifdef UBPA_USREFL_NOT_USE_NAMEOF static constexpr char name[23] = "Ubpa::UECS::SystemMngr"; #endif static constexpr AttrList attrs = {}; static constexpr FieldList fields = { Field {TSTR("systemTraits"), &Type::systemTraits}, Field {TSTR(UMeta::constructor), WrapConstructor<Type(UECS::World*)>()}, Field {TSTR(UMeta::constructor), WrapConstructor<Type(const UECS::SystemMngr&, UECS::World*)>()}, Field {TSTR(UMeta::constructor), WrapConstructor<Type(UECS::SystemMngr&&, UECS::World*)>()}, Field {TSTR(UMeta::destructor), WrapDestructor<Type>()}, Field {TSTR("GetAliveSystemIDs"), &Type::GetAliveSystemIDs}, Field {TSTR("GetActiveSystemsIDs"), &Type::GetActiveSystemsIDs}, Field {TSTR("Create"), static_cast<void(Type::*)(size_t)>(&Type::Create)}, Field {TSTR("Activate"), static_cast<void(Type::*)(size_t)>(&Type::Activate)}, Field {TSTR("Deactivate"), static_cast<void(Type::*)(size_t)>(&Type::Deactivate)}, Field {TSTR("Destroy"), static_cast<void(Type::*)(size_t)>(&Type::Destroy)}, Field {TSTR("IsAlive"), static_cast<bool(Type::*)(size_t)const>(&Type::IsAlive)}, Field {TSTR("IsActive"), static_cast<bool(Type::*)(size_t)const>(&Type::IsActive)}, }; };
//#include <algorithm> //#include <bitset> //#include <cassert> //#include <cctype> //#include <climits> //#include <cmath> //#include <cstdio> //#include <cstdlib> //#include <cstring> //#include <fstream> //#include <iostream> //#include <iomanip> //#include <iterator> //#include <list> //#include <map> //#include <numeric> //#include <queue> //#include <set> //#include <sstream> //#include <stack> //#include <string> //#include <utility> //#include <vector> #include <bits/stdc++.h> using namespace std; //#pragma GCC optimize("Ofast,unroll-loops,no-stack-protector") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getF(n) scanf("%lf",&n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitFlip(a,k) (a^(1<<(k))) #define bitCount(a) __builtin_popcount(a) #define bitCountLL(a) __builtin_popcountll(a) #define bitLeftMost(a) (63-__builtin_clzll((a))) #define bitRightMost(a) (__builtin_ctzll(a)) #define ranL(a, b) ((((rand() << 15) ^ rand()) % ((b) - (a) + 1)) + (a)) #define ranI(a, b) ((((ll)rand() * rand()) % ((b) - (a) + 1)) + (a)) #define ranF(a, b) (((double)rand()/RAND_MAX)*((b) - (a)) + (a)) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define ff first #define ss second #define sf scanf #define pf printf typedef long long ll; typedef unsigned long long ull; typedef vector < int > vi; typedef vector < vi > vii; typedef pair < int, int> pii; #define FMT(...) (sprintf(CRTBUFF, __VA_ARGS__)?CRTBUFF:0) char CRTBUFF[30000]; #ifdef dipta007 #define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;} #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define debug(args...) /// Just strip off all debug tokens #define trace(...) ///yeeeee #endif struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; const double EPS = 1e-9; const int INF = 0x3f3f3f3f; const double PI = 2.0 * acos(0.0); ll MIN() { return INF; } template <typename T, typename... Args > inline T MIN(T a, Args... args) { return min(a, (T)MIN(args...)); } ll MAX() { return -INF; } template <typename T, typename... Args > inline T MAX(T a, Args... args) { return max(a, (T)MAX(args...)); } // g++ -g -O2 -std=gnu++11 A.cpp // ./a.out ///****************** template ends here **************** int n; string st[3]; ll MOD = 1000000007; ll dp[7][2004][7]; ll call(int r, int c, int ff) { // trace(r, c, ff); if(r < 0 || c < 0 || r >= 3 || c >= n) return 0LL; if(st[r][c] == '#') return 0LL; if(r == 2 && c == n-1) return (ff == 3); ll &ret = dp[r][c][ff]; if(ret != -1) return ret; ret = 0; if(ff == 0 || ff == 2) { ret += call(r-1, c, 1); ret %= MOD; ret += call(r+1, c, 3); ret %= MOD; } else if(ff == 1) { ret += call(r, c+1, 2); ret %= MOD; } else if(ff == 3) { ret += call(r, c+1, 0); ret %= MOD; } return ret; } int main() { #ifdef dipta007 READ("inA.txt"); WRITE("outA.txt"); #endif // dipta007 ios_base::sync_with_stdio(0);cin.tie(0); int t; cin >> t; FOR(ci,1,t) { cin >> n; FOR(i,0,2) cin >> st[i]; SET(dp); cout << "Case #" << ci << ": " << call(0,0,0) << endl; } return 0; }
// // stream_socket_service_ext.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (C) 2016-2019 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) // // 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) // #ifndef BOOST_ASIO_STREAM_SOCKET_SERVICE_EXT_HPP #define BOOST_ASIO_STREAM_SOCKET_SERVICE_EXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_ENABLE_OLD_SERVICES) #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/io_context.hpp> #if defined(BOOST_ASIO_WINDOWS_RUNTIME) # include <boost/asio/detail/winrt_ssocket_service.hpp> #elif defined(BOOST_ASIO_HAS_IOCP) # include <boost/asio/detail/win_iocp_socket_service.hpp> #else # include <boost/asio/detail/reactive_socket_service_ext_local.hpp> #endif #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// Default service implementation for a stream socket. template <typename Protocol> class stream_socket_service_ext #if defined(GENERATING_DOCUMENTATION) : public boost::asio::io_context::service #else : public boost::asio::detail::service_base<stream_socket_service_ext<Protocol> > #endif { public: #if defined(GENERATING_DOCUMENTATION) /// The unique service identifier. static boost::asio::io_context::id id; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; private: // The type of the platform-specific implementation. #if defined(BOOST_ASIO_WINDOWS_RUNTIME) typedef detail::winrt_ssocket_service<Protocol> service_impl_type; #elif defined(BOOST_ASIO_HAS_IOCP) typedef detail::win_iocp_socket_service<Protocol> service_impl_type; #else typedef detail::reactive_socket_service_ext_local<Protocol> service_impl_type; #endif public: /// The type of a stream socket implementation. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined implementation_type; #else typedef typename service_impl_type::implementation_type implementation_type; #endif /// The native socket type. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef typename service_impl_type::native_handle_type native_handle_type; #endif /// Construct a new stream socket service for the specified io_context. explicit stream_socket_service_ext(boost::asio::io_context& io_context) : boost::asio::detail::service_base< stream_socket_service_ext<Protocol> >(io_context), service_impl_(io_context) { } /// Construct a new stream socket implementation. void construct(implementation_type& impl) { service_impl_.construct(impl); } #if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a new stream socket implementation. void move_construct(implementation_type& impl, implementation_type& other_impl) { service_impl_.move_construct(impl, other_impl); } /// Move-assign from another stream socket implementation. void move_assign(implementation_type& impl, stream_socket_service_ext& other_service, implementation_type& other_impl) { service_impl_.move_assign(impl, other_service.service_impl_, other_impl); } // All socket services have access to each other's implementations. template <typename Protocol1> friend class stream_socket_service_ext; /// Move-construct a new stream socket implementation from another protocol /// type. template <typename Protocol1> void converting_move_construct(implementation_type& impl, stream_socket_service_ext<Protocol1>& other_service, typename stream_socket_service_ext< Protocol1>::implementation_type& other_impl, typename enable_if<is_convertible< Protocol1, Protocol>::value>::type* = 0) { service_impl_.template converting_move_construct<Protocol1>( impl, other_service.service_impl_, other_impl); } #endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Destroy a stream socket implementation. void destroy(implementation_type& impl) { service_impl_.destroy(impl); } /// Open a stream socket. BOOST_ASIO_SYNC_OP_VOID open(implementation_type& impl, const protocol_type& protocol, boost::system::error_code& ec) { if (protocol.type() == BOOST_ASIO_OS_DEF(SOCK_STREAM)) service_impl_.open(impl, protocol, ec); else ec = boost::asio::error::invalid_argument; BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assign an existing native socket to a stream socket. BOOST_ASIO_SYNC_OP_VOID assign(implementation_type& impl, const protocol_type& protocol, const native_handle_type& native_socket, boost::system::error_code& ec) { service_impl_.assign(impl, protocol, native_socket, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the socket is open. bool is_open(const implementation_type& impl) const { return service_impl_.is_open(impl); } /// Close a stream socket implementation. BOOST_ASIO_SYNC_OP_VOID close(implementation_type& impl, boost::system::error_code& ec) { service_impl_.close(impl, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying socket. native_handle_type release(implementation_type& impl, boost::system::error_code& ec) { return service_impl_.release(impl, ec); } /// Get the native socket implementation. native_handle_type native_handle(implementation_type& impl) { return service_impl_.native_handle(impl); } /// Cancel all asynchronous operations associated with the socket. BOOST_ASIO_SYNC_OP_VOID cancel(implementation_type& impl, boost::system::error_code& ec) { service_impl_.cancel(impl, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the socket is at the out-of-band data mark. bool at_mark(const implementation_type& impl, boost::system::error_code& ec) const { return service_impl_.at_mark(impl, ec); } /// Determine the number of bytes available for reading. std::size_t available(const implementation_type& impl, boost::system::error_code& ec) const { return service_impl_.available(impl, ec); } /// Bind the stream socket to the specified local endpoint. BOOST_ASIO_SYNC_OP_VOID bind(implementation_type& impl, const endpoint_type& endpoint, boost::system::error_code& ec) { service_impl_.bind(impl, endpoint, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Connect the stream socket to the specified endpoint. BOOST_ASIO_SYNC_OP_VOID connect(implementation_type& impl, const endpoint_type& peer_endpoint, boost::system::error_code& ec) { service_impl_.connect(impl, peer_endpoint, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous connect. template <typename ConnectHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ConnectHandler, void (boost::system::error_code)) async_connect(implementation_type& impl, const endpoint_type& peer_endpoint, BOOST_ASIO_MOVE_ARG(ConnectHandler) handler) { async_completion<ConnectHandler, void (boost::system::error_code)> init(handler); service_impl_.async_connect(impl, peer_endpoint, init.completion_handler); return init.result.get(); } /// Set a socket option. template <typename SettableSocketOption> BOOST_ASIO_SYNC_OP_VOID set_option(implementation_type& impl, const SettableSocketOption& option, boost::system::error_code& ec) { service_impl_.set_option(impl, option, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get a socket option. template <typename GettableSocketOption> BOOST_ASIO_SYNC_OP_VOID get_option(const implementation_type& impl, GettableSocketOption& option, boost::system::error_code& ec) const { service_impl_.get_option(impl, option, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform an IO control command on the socket. template <typename IoControlCommand> BOOST_ASIO_SYNC_OP_VOID io_control(implementation_type& impl, IoControlCommand& command, boost::system::error_code& ec) { service_impl_.io_control(impl, command, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the socket. bool non_blocking(const implementation_type& impl) const { return service_impl_.non_blocking(impl); } /// Sets the non-blocking mode of the socket. BOOST_ASIO_SYNC_OP_VOID non_blocking(implementation_type& impl, bool mode, boost::system::error_code& ec) { service_impl_.non_blocking(impl, mode, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the native socket implementation. bool native_non_blocking(const implementation_type& impl) const { return service_impl_.native_non_blocking(impl); } /// Sets the non-blocking mode of the native socket implementation. BOOST_ASIO_SYNC_OP_VOID native_non_blocking(implementation_type& impl, bool mode, boost::system::error_code& ec) { service_impl_.native_non_blocking(impl, mode, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the local endpoint. endpoint_type local_endpoint(const implementation_type& impl, boost::system::error_code& ec) const { return service_impl_.local_endpoint(impl, ec); } /// Get the remote endpoint. endpoint_type remote_endpoint(const implementation_type& impl, boost::system::error_code& ec) const { return service_impl_.remote_endpoint(impl, ec); } /// Disable sends or receives on the socket. BOOST_ASIO_SYNC_OP_VOID shutdown(implementation_type& impl, socket_base::shutdown_type what, boost::system::error_code& ec) { service_impl_.shutdown(impl, what, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Wait for the socket to become ready to read, ready to write, or to have /// pending error conditions. BOOST_ASIO_SYNC_OP_VOID wait(implementation_type& impl, socket_base::wait_type w, boost::system::error_code& ec) { service_impl_.wait(impl, w, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Asynchronously wait for the socket to become ready to read, ready to /// write, or to have pending error conditions. template <typename WaitHandler> BOOST_ASIO_INITFN_RESULT_TYPE(WaitHandler, void (boost::system::error_code)) async_wait(implementation_type& impl, socket_base::wait_type w, BOOST_ASIO_MOVE_ARG(WaitHandler) handler) { async_completion<WaitHandler, void (boost::system::error_code)> init(handler); service_impl_.async_wait(impl, w, init.completion_handler); return init.result.get(); } /// Send the given data to the peer. template <typename ConstBufferSequence> std::size_t send(implementation_type& impl, const ConstBufferSequence& buffers, socket_base::message_flags flags, boost::system::error_code& ec) { return service_impl_.send(impl, buffers, flags, ec); } /// Start an asynchronous send. template <typename ConstBufferSequence, typename WriteHandler> BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (boost::system::error_code, std::size_t)) async_send(implementation_type& impl, const ConstBufferSequence& buffers, socket_base::message_flags flags, BOOST_ASIO_MOVE_ARG(WriteHandler) handler) { async_completion<WriteHandler, void (boost::system::error_code, std::size_t)> init(handler); service_impl_.async_send(impl, buffers, flags, init.completion_handler); return init.result.get(); } /// Receive some data from the peer. template <typename MutableBufferSequence> std::size_t receive(implementation_type& impl, const MutableBufferSequence& buffers, socket_base::message_flags flags, boost::system::error_code& ec) { return service_impl_.receive(impl, buffers, flags, ec); } /// Start an asynchronous receive. template <typename MutableBufferSequence, typename ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (boost::system::error_code, std::size_t, std::uint32_t, std::uint32_t)) async_receive(implementation_type& impl, const MutableBufferSequence& buffers, socket_base::message_flags flags, BOOST_ASIO_MOVE_ARG(ReadHandler) handler) { async_completion<ReadHandler, void (boost::system::error_code, std::size_t)> init(handler); service_impl_.async_receive(impl, buffers, flags, init.completion_handler); return init.result.get(); } private: // Destroy all user-defined handler objects owned by the service. void shutdown() { service_impl_.shutdown(); } // The platform-specific implementation. service_impl_type service_impl_; }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_ENABLE_OLD_SERVICES) #endif // BOOST_ASIO_STREAM_SOCKET_SERVICE_EXT_HPP
/* debug.cpp - Small debug library for my project */ #include "Arduino.h" #include "debug.h" void MyDebug::output(const char *x) { #ifdef debugMode Serial.print(x); #endif } void MyDebug::show(char x[]) { #ifdef debugMode Serial.print(F("char[]: ")); Serial.print(x); Serial.println(F("")); #endif } void MyDebug::show(float x){ #ifdef debugMode Serial.print(F("float: ")); Serial.print(x); Serial.println(F("")); #endif } void MyDebug::show(char x){ #ifdef debugMode Serial.print(F("char: ")); Serial.print(x); Serial.println(F("")); #endif } void MyDebug::show(int x){ #ifdef debugMode Serial.print("int: "); Serial.print(x); Serial.println(""); #endif }
// File doc/quickbook/eglplus/quickref/enums/swap_behavior_class.hpp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/eglplus/swap_behavior.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2019 Matus Chochlik. // 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 // //[eglplus_enums_swap_behavior_class #if !__OGLPLUS_NO_ENUM_VALUE_CLASSES namespace enums { template <typename Base, template<__SwapBehavior> class Transform> class __EnumToClass<Base, __SwapBehavior, Transform> /*< Specialization of __EnumToClass for the __SwapBehavior enumeration. >*/ : public Base { public: EnumToClass(); EnumToClass(Base&& base); Transform<SwapBehavior::BufferPreserved> BufferPreserved; Transform<SwapBehavior::BufferDestroyed> BufferDestroyed; }; } // namespace enums #endif //]
#include "Game/CardView/CardView.hpp" #include <cmath> #include <iostream> namespace cge { CardView::CardView(void) : m_cardUnderMouse(-1), m_lastMousePos(-10000,-10000), m_maxSelectedCards(1), m_cardAnimations(NULL), m_animationManager(NULL), m_cardContainer(104), m_handGenerator(&m_cardContainer), m_cards(4), m_cardImageManager(NULL), m_isDeckCutEvt(false), m_singleSelectionBehaviour(true), m_mouseEnabled(true), m_timeUntilNextClick(0), m_mouseClickInterval(30), m_mouseDisabled(false), m_audioMan(NULL), m_waitSelectCard(false) { m_animationManager = CardAnimationManager(this); m_cardAnimations = CardAnimations(&m_animationManager); } CardView::~CardView(void) { } void CardView::render( GraphicsContext* context ) { m_cardRenderer.renderCardHands(context,m_cards,m_tableCards); } bool CardView::pointOnCard( const ViewCard* card,int x, int y ) const { if(card == NULL) return false; Vec2 cardPosition = getProportions()->getCardPosition(card); Vec2 cardSize = Vec2( getProportions()->getInitialCardSize().getX() * getProportions()->getCardScale(card) * 0.95f, getProportions()->getInitialCardSize().getY() * getProportions()->getCardScale(card)); Vec2 point = Vec2(x,y); point = Math::rotateAroundPoint(point,cardPosition,(CGE_PI * 2.0f) - card->m_angle); return pointInRect( cardPosition.getX() - (cardSize.getX() / 2.0f), cardPosition.getY() - (cardSize.getY() / 2.0f), cardSize.getX(), cardSize.getY(), point); } bool CardView::pointInRect( float x, float y, float w, float h, Vec2 p ) const { if(p.getX() < x) return false; if(p.getY() < y) return false; if(p.getX() >= x + w) return false; if(p.getY() >= y + h) return false; return true; } void CardView::mouseMove( int x, int y ) { m_lastMousePos = Vec2(x,y); if(!isMouseEnabled() || m_mouseDisabled) { return; } int cardUnder = m_cardUnderMouse; setCardUnderMouse(x,y); /* //deck cut sound (annulled) if(m_cardUnderMouse != -1 && m_cardUnderMouse != cardUnder && m_isDeckCutEvt) { float pitch = (float)(90 + (rand() % 20)) / 100.0f; //m_audioMan->stop("flick"); if(rand() % 2 == 0) m_audioMan->play("play.card",pitch); else m_audioMan->play("play.card2",pitch); } */ } void CardView::logic() { if(isMouseEnabled()) { setCardUnderMouse(m_lastMousePos.getX(),m_lastMousePos.getY()); } m_cardAnimations.handleCardScaleLogic(m_cards[PLAYER],m_cardUnderMouse); m_animationManager.stepAnimations(); verifyDisabledCards(); processMessages(); //used to limit clicks for a smoother experience m_timeUntilNextClick = m_timeUntilNextClick > 0 ? m_timeUntilNextClick - 1 : 0; } void CardView::processMessage( CardMessenger::CardMessage message,int val ) { handleEnableMouse(message, val); switch(message) { case CardMessenger::END_ANIMATED_EVENT: m_animationManager.removeAnimationEvent(val); break; case CardMessenger::BEGIN_ANIMATED_EVENT: break; case CardMessenger::END_THROW_CARD_ON_TABLE: handleThrowCardEndLogic(val); break; case CardMessenger::END_TABLE_CARDS_TO_PLAYER: handleSendTableCardsLogic(val); break; case CardMessenger::END_SWAP_CARDS: handleSwapCardsLogic(val); break; default: break; } handleRedisableCards(message); } void CardView::mouseClick( int x, int y, bool lmb ) { if(!isMouseEnabled() || m_mouseDisabled) { return; } setCardUnderMouse(x,y); if(m_timeUntilNextClick > 0) { //return; } else { m_timeUntilNextClick = m_mouseClickInterval; } if(m_isDeckCutEvt && lmb) { handleDeckCutLogic(); } else if(m_cardUnderMouse != -1 && lmb) { handleClickLogic(x,y); } } void CardView::setCardUnderMouse( int x, int y ) { if(m_mouseDisabled) { m_cardUnderMouse = -1; } int z = -1; for(int i = m_cards[PLAYER].size() - 1; i >=0; --i) { if(pointOnCard(m_cards[PLAYER][i],x,y)) { z = i; break; } } m_cardUnderMouse = z; } void CardView::setCardImageManager( CardImageManager* cardImageManager ) { m_cardImageManager = cardImageManager; m_cardRenderer.setCardImageManager(cardImageManager); m_cardAnimations.setCardImageManager(cardImageManager); } void CardView::evtDispatchCards( std::vector<Card> playerCards, int leftCards, int rightCards, int topCards, CardHandEnum dealer ) { if(playerCards.size() == 0 && leftCards == 0 && rightCards == 0 && topCards == 0) { return; } //clean up any cards reset(); m_playerCards = playerCards; int cardCount[4] = {static_cast<int>(playerCards.size()),leftCards,rightCards,topCards}; //set the pretty pictures for(int i = 0; i < 4; ++i) { if(cardCount[i] > 0) { m_handGenerator.generateHand(i,cardCount[i],m_cards[i]); assignCardImages((CardHandEnum)i); } } m_cardAnimations.dispatchCards( m_cards[PLAYER],m_cards[LEFT],m_cards[TOP],m_cards[RIGHT],0); } void CardView::handleEnableMouse( CardMessenger::CardMessage msg, int val ) { switch(msg) { case CardMessenger::BEGIN_DISPATCH_CARDS: case CardMessenger::BEGIN_SWAP_CARDS: disableMouseInput(); break; //case CardMessenger::END_DISPATCH_CARDS: case CardMessenger::END_THROW_CARD_ON_TABLE: case CardMessenger::END_SWAP_CARDS: enableMouseInput(); break; } } void CardView::disableMouseInput() { m_cardUnderMouse = -1; m_mouseEnabled = false; } void CardView::enableMouseInput() { m_mouseEnabled = true; } bool CardView::isMouseEnabled() const { return m_mouseEnabled; } bool CardView::evtThrowCardOnTable( const Card& card,CardHandEnum player, int cardNum ) { if(cardNum == -1) { cardNum = m_cards[player].size() / 2; } if((int)m_cards[player].size() <= cardNum) { return false; } //set the face card image m_cards[player][cardNum]->m_card = m_cardImageManager->getCardImage(card); //null pointer on image if(!m_cards[player][cardNum]->m_card) { return false; } m_cardAnimations.throwCardOnTable(m_cards[player][cardNum],(int)player); if(player == PLAYER) { disableMouseInput(); } m_cards[player][cardNum]->m_thrown = true; return true; } void CardView::handleThrowCardEndLogic( int id ) { CardAnimationEvent* animation = m_animationManager.getAnimationById(id); ViewCard* card = animation->getCard(); if(!card) { //something went very wrong return; } //end logic //find card owner int pos = -1; CardHandEnum player = PLAYER; for(size_t i = 0; i < 4; ++i ) { for(size_t j = 0; j < m_cards[i].size(); ++j) { if(m_cards[i][j] == card) { pos = j; player = (CardHandEnum)i; } } } //found card owner if(pos != -1) { //move the card to the table array m_tableCards.push_back(m_cards[player][pos]); m_cards[player].erase(m_cards[player].begin() + pos); //player keeps track of Cards if(player == PLAYER) { m_playerCards.erase(m_playerCards.begin() + pos); } //animate the hand shrinking and regenerate the hand std::vector<ViewCard> startCards; for(size_t i = 0; i < m_cards[player].size();++i) { startCards.push_back(*m_cards[player][i]); } m_handGenerator.generateHand( (int)player,m_cards[player].size(),m_cards[player]); m_cardAnimations.shrinkCards(m_cards[player],startCards); //cards regenerated so images need to be reassigned assignCardImages(player); } } void CardView::assignCardImages(CardHandEnum player) { if(player == PLAYER && !m_isDeckCutEvt) { for(size_t i = 0; i < m_playerCards.size(); ++i) { m_cards[PLAYER][i]->m_card = m_cardImageManager->getCardImage(m_playerCards[i]); } } else { for(size_t i = 0; i < m_cards[player].size(); ++i) { m_cards[player][i]->m_card = m_cardImageManager->getBackCardImage(); } } } void CardView::handleSendTableCardsLogic( int id ) { CardAnimationEvent* anim = m_animationManager.getAnimationById(id); std::vector<ViewCard*> cards = anim->getCards(); for(size_t j = 0; j < cards.size(); ++j) { for(size_t i = 0; i < m_tableCards.size(); ++i) { if(m_tableCards[i] == cards[j]) { m_cardContainer.release(cards[j]); m_tableCards.erase(m_tableCards.begin() + i); break; } } } } void CardView::evtSendTableCardsToPlayer( CardHandEnum player ) { m_cardAnimations.sendTableCardsToPlayer(m_tableCards,(int)player); } std::vector<Card> CardView::getSelectedCards() const { std::vector<int> indexes = getSelectedCardIndexes(); std::vector<Card> cards; for(size_t i = 0; i < indexes.size(); ++i) { cards.push_back(m_playerCards[indexes[i]]); } return cards; } void CardView::evtSwapCards( const std::vector<Card>& aCards, const std::vector<Card>& bCards, CardHandEnum handA, CardHandEnum handB ) { //put everything in an array to use a for loop std::vector<ViewCard*> swap[2]; CardHandEnum hands[2] = {handA,handB}; const std::vector<Card> zCards[2] = {aCards,bCards}; std::vector<int> indexes[2]; //for the 2 players for(int h = 0; h < 2; h++) { if(hands[h] == PLAYER && zCards[h].size() > 0 && zCards[h][0].getCardNumber() != -1) { //swap the player Cards for(size_t i = 0; i < m_playerCards.size(); ++i) { for(size_t j = 0; j < zCards[h].size(); ++j) { if(m_playerCards[i] == zCards[h][j]) { //assign card m_playerCards[i] = zCards[(h + 1) % 2][j]; swap[h].push_back(m_cards[hands[h]][i]); indexes[h].push_back(i); } } } } else //show from the middle of the hand { std::vector<int>pos; int middle = (m_cards[hands[h]].size() / 2) + 1; middle -= zCards[h].size() / 2; for(size_t i = 0; i < zCards[h].size();++i) { pos.push_back( middle + i ); } //set the card images for(size_t i = 0; i < zCards[h].size(); ++i) { swap[h].push_back(m_cards[hands[h]][pos[i]]); /* swap[h].back()->m_card = m_cardImageManager->getCardImage(zCards[h][i]); */ indexes[h].push_back(pos[i]); } } } //literally swap the player and opponent cards for(size_t i = 0; i < indexes[1].size(); ++i) { std::swap( *m_cards[hands[0]][indexes[0][i]], *m_cards[hands[1]][indexes[1][i]]); } //if the player is not involved do simple swap if(handA != PLAYER) { m_cardAnimations.swapCards(swap[0],swap[1]); } else //otherwise put the cards directly in the player's hand at the right place { interpolatedSwap(swap[0],swap[1]); } } void CardView::handleSwapCardsLogic( int id ) { //sends the message and performs event's end logic handleSwapCardsEndLogic(); } void CardView::handleSwapCardsEndLogic() { //all 3 opponents for(int i = 1; i < 4; ++i) { m_handGenerator.generateHand(i,m_cards[i].size(),m_cards[i]); assignCardImages((CardHandEnum)i); } } void CardView::interpolatedSwap( const std::vector<ViewCard*> &cardsA , const std::vector<ViewCard*> &cardsB ) { m_animationManager.pushAnimationEvent( BEGIN_SWAP_CARDS,END_SWAP_CARDS); //initialize a temporary card ViewCard tempCard = *cardsA[0]; //animation rate float rate = 0.0165f; //animate player's cards going to the opponent for(size_t i = 0; i < cardsB.size(); ++i) { tempCard = *cardsA[i]; cardsB[i]->m_selected = false; tempCard.m_position = tempCard.m_homePos; tempCard.m_angle = tempCard.m_homeAngle; tempCard.m_scale = tempCard.m_homeScale; m_animationManager.addAnimation(cardsB[i],tempCard,rate,0); } std::vector<ViewCard> curPos; std::vector<ViewCard> newPos; //used to find the indexes of the new card order std::vector<std::pair<Card, int> > posChanges; for(size_t i = 0; i < m_playerCards.size(); ++i) { posChanges.push_back(std::make_pair(m_playerCards[i],i)); } for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { curPos.push_back(*m_cards[PLAYER][i]); } //sort the cards and keep track of index changes std::sort(m_playerCards.begin(),m_playerCards.end()); std::sort(posChanges.begin(),posChanges.end()); //generate the new card positions m_handGenerator.generateHand(0,m_playerCards.size(),m_cards[PLAYER]); assignCardImages(PLAYER); //store the new positions for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { newPos.push_back(*m_cards[PLAYER][i]); } //animate opponent's cards going directly into the player's hand at the correct spot for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { //start the cards at their old positions int pos = posChanges[i].second; m_cards[PLAYER][i]->m_position = curPos[pos].m_position; m_cards[PLAYER][i]->m_angle = curPos[pos].m_angle; m_cards[PLAYER][i]->m_scale = curPos[pos].m_scale; //animate them to their new positions m_animationManager.addAnimation( m_cards[PLAYER][i], newPos[i], rate, 0); } } void CardView::evtSelectDeckCut() { //clean up reset(); m_isDeckCutEvt = true; m_handGenerator.generateDeck(m_cards[PLAYER]); for (size_t i = 0; i < m_cards.size(); ++i) { //back of the card assignCardImages(PLAYER); } } void CardView::handleDeckCutLogic() { if(m_cardUnderMouse != -1) { sendMessage(DECK_CUT_SELECTED,m_cardUnderMouse); m_isDeckCutEvt = false; m_cardAnimations.animateDeckCut(m_cards[PLAYER],m_cardUnderMouse); disableMouseInput(); } } void CardView::handleClickLogic( int x, int y ) { //the card is disabled, do nothing if(!m_cards[PLAYER][m_cardUnderMouse]->m_enabled) { return; } if(m_cards[PLAYER][m_cardUnderMouse]->m_selected) { if(!m_cards[PLAYER][m_cardUnderMouse]->m_thrown) { if(!m_waitSelectCard) { m_cardAnimations.toggleCard(m_cards[PLAYER][m_cardUnderMouse]); } else { sendMessage(CardMessenger::CARD_SELECTED,m_cardUnderMouse); } disableDisabledCards(); } } else //card is being selected { if(m_maxSelectedCards == 1) { for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { if(m_cards[PLAYER][i]->m_selected || i == m_cardUnderMouse) { if(!m_cards[PLAYER][i]->m_thrown) { m_cardAnimations.toggleCard(m_cards[PLAYER][i]); } } } } else { m_cardAnimations.toggleCard(m_cards[PLAYER][m_cardUnderMouse]); if(getNumSelectedCards() >= m_maxSelectedCards) { disableUnselectedCards(); } } } } void CardView::setDisabledCards( const std::vector<int> cards ) { m_disabledCards = cards; disableDisabledCards(); enableMouseInput(); } void CardView::disableDisabledCards() { for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { m_cards[PLAYER][i]->m_enabled = true; } for(size_t i = 0; i < m_disabledCards.size(); ++i) { int pos = m_disabledCards[i]; if(pos < (int)m_cards[PLAYER].size()) { m_cards[PLAYER][pos]->m_enabled = false; if(m_cards[PLAYER][pos]->m_selected) { m_cardAnimations.toggleCard(m_cards[PLAYER][pos]); } } } } void CardView::setMaxSelectedCards(int max) { if(max < 1) { max = 1; } m_maxSelectedCards = max; } int CardView::getNumSelectedCards() const { int count = 0; for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { if(m_cards[PLAYER][i]->m_selected) { count++; } } return count; } void CardView::disableUnselectedCards() { for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { if(!m_cards[PLAYER][i]->m_selected) { m_cards[PLAYER][i]->m_enabled = false; } } } int CardView::getSelectedCardIndex() const { for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { if(m_cards[PLAYER][i]->m_selected) { return i; } } return -1; } std::vector<int> CardView::getSelectedCardIndexes() const { std::vector<int> indexes; for(size_t i = 0; i < m_cards[PLAYER].size(); ++i) { if(m_cards[PLAYER][i]->m_selected) { indexes.push_back(i); } } return indexes; } const Card CardView::getSelectedCard() const { int index = getSelectedCardIndex(); if(index > -1) { return m_playerCards[index]; } return Card(Card::DIAMONDS,Card::TWO); } void CardView::handleRedisableCards( CardMessenger::CardMessage msg ) { switch(msg) { case END_DISPATCH_CARDS: case END_THROW_CARD_ON_TABLE: case END_SHRINK_HAND: case END_SWAP_CARDS: case END_TABLE_CARDS_TO_PLAYER: disableDisabledCards(); default: break; } } void CardView::setSingleSelectionBehaviour( bool singleSelection ) { m_singleSelectionBehaviour = singleSelection; } bool CardView::isSingleSelectionBehaviour() const { return m_singleSelectionBehaviour; } void CardView::reset() { m_tableCards.clear(); for(size_t i = 0; i < m_cards.size(); ++i) { m_cards[i].clear(); } m_cardContainer.freeAll(); m_playerCards.clear(); } void CardView::verifyDisabledCards() { for (size_t i = 0; i < m_cards[PLAYER].size(); ++i) { if(!m_cards[PLAYER][i]->m_enabled && m_cards[PLAYER][i]->m_selected) { m_cardAnimations.toggleCard(m_cards[PLAYER][i]); } } } void CardView::setProportions( ProportionsManager* proportions ) { DynamicElement::setProportions(proportions); m_cardRenderer.setProportionsManager(proportions); } void CardView::disableAllCards() { std::vector<int> cards; for(size_t i = 0; i < m_playerCards.size(); ++i) { cards.push_back(i); } setDisabledCards(cards); } int CardView::getIndexOfCard( const Card& c ) { for(size_t i = 0; i < m_playerCards.size(); ++i) { if(m_playerCards[i].getCardNumber() == c.getCardNumber()) { return i; } } return -1; } void CardView::selectCard( int index ) { if(index != -1 && index < m_cards[PLAYER].size()) m_cardAnimations.toggleCard(m_cards[PLAYER][index]); } void CardView::setMouseDisabled( bool disabled ) { m_mouseDisabled = true; m_cardUnderMouse = -1; } bool CardView::isAnimationQueueEmpty() const { return m_animationManager.getCount() == 0; } bool CardView::isOnlyAnimationShrink() const { return m_animationManager.hasAnimationType(END_SHRINK_HAND) && m_animationManager.getCount() == 1; } int CardView::selectRandomValidCard() { if(m_playerCards.size() == m_disabledCards.size()) return -1; int card = -1; do { int tmp = rand() % m_playerCards.size(); bool found = true; for(int i = 0; i < m_disabledCards.size(); ++i) { if(m_disabledCards[i] == tmp) { found = false; break; } } if(found) { card = tmp; } } while (card == -1); return card; } void CardView::playRandomCard() { int card = selectRandomValidCard(); m_cardUnderMouse = card; if(m_cardUnderMouse != -1) { handleClickLogic(-1,-1); } } void CardView::setAudioManager( AudioManager* audio ) { m_audioMan = audio; } void CardView::setWaitForSelectCard( bool waiting ) { m_waitSelectCard = waiting; } }
#include "systems/InputSystem.hh" #include "advanced/transform.hh" void gamedev::InputSystem::AddEntity(InstanceHandle& handle, Signature entitySignature) { mEntities.insert(handle); } void gamedev::InputSystem::RemoveEntity(InstanceHandle& handle, Signature entitySignature) { mEntities.erase(handle); } void gamedev::InputSystem::RemoveEntity(InstanceHandle& handle) { mEntities.erase(handle); } void gamedev::InputSystem::RemoveAllEntities() { mEntities.clear(); } void gamedev::InputSystem::Init(std::shared_ptr<EngineECS>& ecs) { mECS = ecs; } int gamedev::InputSystem::Update(float dt) { auto t0 = std::chrono::steady_clock::now(); for (const auto& handle : mEntities) { auto instance = mECS->GetInstance(handle); auto input = mECS->GetComponent<gamedev::Input>(handle); auto physics = mECS->TryGetComponent<gamedev::Physics>(handle); auto move = input->targetMove - tg::pos3(instance.xform.translation); // Update focus if (input->focusInstance.is_valid()) { InstructFocus(handle, input->focusInstance, input->focusMove, input->focusLook); } if (physics && (tg::length_sqr(move) < 0.1)) { } // Update velocity if angle between move-vector and current velocity-vector is above some epsilon if (physics && (tg::length_sqr(tg::cross(physics->velocity, move)) > 0.001)) { physics->velocity = tg::normalize_safe(move) * input->runningSpeed; } } auto tn = std::chrono::steady_clock::now(); return std::chrono::duration_cast<std::chrono::microseconds>(tn - t0).count(); } void gamedev::InputSystem::InstructMove(InstanceHandle handle, tg::pos3 targetPosition) { mECS->GetComponent<gamedev::Input>(handle)->targetMove = targetPosition; } void gamedev::InputSystem::InstructLook(InstanceHandle handle, tg::vec3 targetDirection) { mECS->GetComponent<gamedev::Input>(handle)->targetLook = targetDirection; } void gamedev::InputSystem::InstructFocus(InstanceHandle active_handle, InstanceHandle passive_handle, bool focusMove, bool focusLook) { if (!focusMove && !focusLook) { return InstructStopFocus(active_handle); } auto input = mECS->GetComponent<gamedev::Input>(active_handle); auto activePosition = tg::pos3(mECS->GetInstance(active_handle).xform.translation); auto passivePosition = tg::pos3(mECS->GetInstance(passive_handle).xform.translation); auto lookDir = passivePosition - activePosition; input->focusMove = focusMove; input->focusLook = focusLook; if (focusMove && input->targetMove != passivePosition) { input->targetMove = passivePosition; input->refresh = true; } if (focusLook && lookDir != input->targetLook) { input->targetLook = lookDir; input->refresh = true; } } void gamedev::InputSystem::InstructStopInput(InstanceHandle handle) { auto input = mECS->GetComponent<gamedev::Input>(handle); auto instance = mECS->GetInstance(handle); input->targetMove = tg::pos3(instance.xform.translation); } void gamedev::InputSystem::InstructStopFocus(InstanceHandle handle) { auto input = mECS->GetComponent<gamedev::Input>(handle); auto instance = mECS->GetInstance(handle); input->targetMove = tg::pos3(instance.xform.translation); input->focusMove = false; input->focusLook = false; input->focusInstance = {std::uint32_t(-1)}; }
#include <mbgl/storage/asset_file_source.hpp> #include <mbgl/storage/database_file_source.hpp> #include <mbgl/storage/file_source_manager.hpp> #include <mbgl/storage/local_file_source.hpp> #include <mbgl/storage/main_resource_loader.hpp> #include <mbgl/storage/online_file_source.hpp> #include <mbgl/storage/mbtiles_file_source.hpp> #include <mbgl/storage/resource_options.hpp> namespace mbgl { class DefaultFileSourceManagerImpl final : public FileSourceManager { public: DefaultFileSourceManagerImpl() { registerFileSourceFactory(FileSourceType::ResourceLoader, [](const ResourceOptions& options) { return std::make_unique<MainResourceLoader>(options); }); registerFileSourceFactory(FileSourceType::Asset, [](const ResourceOptions& options) { return std::make_unique<AssetFileSource>(options.assetPath()); }); registerFileSourceFactory(FileSourceType::Database, [](const ResourceOptions& options) { return std::make_unique<DatabaseFileSource>(options); }); registerFileSourceFactory(FileSourceType::FileSystem, [](const ResourceOptions&) { return std::make_unique<LocalFileSource>(); }); registerFileSourceFactory(FileSourceType::Mbtiles, [](const ResourceOptions&) { return std::make_unique<MaptilerFileSource>(); }); registerFileSourceFactory(FileSourceType::Network, [](const ResourceOptions& options) { std::unique_ptr<FileSource> networkSource = std::make_unique<OnlineFileSource>(); networkSource->setProperty(ACCESS_TOKEN_KEY, options.accessToken()); networkSource->setProperty(API_BASE_URL_KEY, options.baseURL()); return networkSource; }); } }; FileSourceManager* FileSourceManager::get() noexcept { static DefaultFileSourceManagerImpl instance; return &instance; } } // namespace mbgl
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "Utils/SpatialBasicAwaiter.h" #include "Engine/World.h" #include "TimerManager.h" void USpatialBasicAwaiter::BeginDestroy() { InvokeQueuedDelegates(FString::Printf(TEXT("Awaiter '%s' was destroyed!"), *GetName())); Super::BeginDestroy(); } FDelegateHandle USpatialBasicAwaiter::Await(const FOnReady& OnReadyDelegate, const float Timeout) { // We already became ready in the past, so the delegate can be executed immediately if (bIsReady) { OnReadyDelegate.ExecuteIfBound(FString{}); return FDelegateHandle{}; } // Still waiting to become ready, so store the delegate to be executed when we eventually do become ready else { FDelegateHandle OutHandle = OnReadyEvent.Add(OnReadyDelegate); // If requested to, add a timer to remove the delegate in case becoming ready takes too long if (Timeout > 0.f) { if (UWorld* World = GetWorld()) { FTimerManager& TimerManager = World->GetTimerManager(); FTimerHandle Handle; TimerManager.SetTimer(Handle, FTimerDelegate::CreateWeakLambda( this, [this, OutHandle, OnReadyDelegate]() { if (OnReadyDelegate.IsBound()) { OnReadyDelegate.Execute(FString{ TEXT("Timed out while waiting to become Ready!") }); OnReadyEvent.Remove(OutHandle); } }), Timeout, false); TimeoutHandles.Add(Handle); } else { UE_LOG(LogAwaitable, Error, TEXT("UBasicAwaiter::Await could not find a valid UWorld reference! (Could not set up timeout timer)")); } } return OutHandle; } } bool USpatialBasicAwaiter::StopAwaiting(FDelegateHandle& Handle) { return OnReadyEvent.Remove(Handle); } ISpatialAwaitable::FSpatialAwaitableOnResetEvent& USpatialBasicAwaiter::OnReset() { return OnResetEvent; } void USpatialBasicAwaiter::Ready() { // Early exit if already ready if (bIsReady) { return; } bIsReady = true; InvokeQueuedDelegates(); } void USpatialBasicAwaiter::Reset() { if (!bIsReady) { return; } bIsReady = false; OnResetEvent.Broadcast(); OnResetEvent.Clear(); } void USpatialBasicAwaiter::InvokeQueuedDelegates(const FString& ErrorStatus /* = FString{} */) { OnReadyEvent.Broadcast(ErrorStatus); OnReadyEvent.Clear(); if (UWorld* World = GetWorld()) { for (FTimerHandle& TimeoutHandle : TimeoutHandles) { World->GetTimerManager().ClearTimer(TimeoutHandle); } } }
/** * @file Tests.cpp * * @brief Test routines for Zerocoin. * * @author Ian Miers, Christina Garman and Matthew Green * @date June 2013 * * @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green * @license This project is released under the MIT license. **/ // Copyright (c) 2017-2019 The COVID19 developers #include <boost/test/unit_test.hpp> #include <string> #include <iostream> #include <fstream> #include <cmath> // #include <curses.h> #include <exception> #include "streams.h" #include "libzerocoin/ParamGeneration.h" #include "libzerocoin/Denominations.h" #include "libzerocoin/Coin.h" #include "libzerocoin/CoinSpend.h" #include "libzerocoin/Accumulator.h" #include "test_covid19.h" #define COLOR_STR_GREEN "\033[32m" #define COLOR_STR_NORMAL "\033[0m" #define COLOR_STR_RED "\033[31m" #define TESTS_COINS_TO_ACCUMULATE 10 #define NON_PRIME_TESTS 100 // Global test counters uint32_t gNumTests = 0; uint32_t gSuccessfulTests = 0; // Proof size uint32_t gProofSize = 0; uint32_t gCoinSize = 0; uint32_t gSerialNumberSize = 0; // Global coin array libzerocoin::PrivateCoin *gCoins[TESTS_COINS_TO_ACCUMULATE]; // Global params libzerocoin::ZerocoinParams *g_Params; ////////// // Utility routines ////////// void LogTestResult(std::string testName, bool (*testPtr)()) { std::string colorGreen(COLOR_STR_GREEN); std::string colorNormal(COLOR_STR_NORMAL); std::string colorRed(COLOR_STR_RED); std::cout << "Testing if " << testName << "..." << std::endl; bool testResult = testPtr(); if (testResult == true) { std::cout << "\t" << colorGreen << "[PASS]" << colorNormal << std::endl; gSuccessfulTests++; } else { std::cout << colorRed << "\t[FAIL]" << colorNormal << std::endl; } gNumTests++; } CBigNum GetTestModulus() { static CBigNum testModulus(0); // TODO: should use a hard-coded RSA modulus for testing if (!testModulus) { CBigNum p, q; // Note: we are NOT using safe primes for testing because // they take too long to generate. Don't do this in real // usage. See the paramgen utility for better code. p = CBigNum::generatePrime(1024, false); q = CBigNum::generatePrime(1024, false); testModulus = p * q; } return testModulus; } ////////// // Test routines ////////// bool Test_GenRSAModulus() { CBigNum result = GetTestModulus(); if (!result) { return false; } else { return true; } } bool Test_CalcParamSizes() { bool result = true; #if 0 uint32_t pLen, qLen; try { calculateGroupParamLengths(4000, 80, &pLen, &qLen); if (pLen < 1024 || qLen < 256) { result = false; } calculateGroupParamLengths(4000, 96, &pLen, &qLen); if (pLen < 2048 || qLen < 256) { result = false; } calculateGroupParamLengths(4000, 112, &pLen, &qLen); if (pLen < 3072 || qLen < 320) { result = false; } calculateGroupParamLengths(4000, 120, &pLen, &qLen); if (pLen < 3072 || qLen < 320) { result = false; } calculateGroupParamLengths(4000, 128, &pLen, &qLen); if (pLen < 3072 || qLen < 320) { result = false; } } catch (const exception& e) { result = false; } #endif return result; } bool Test_GenerateGroupParams() { uint32_t pLen = 1024, qLen = 256, count; libzerocoin::IntegerGroupParams group; for (count = 0; count < 1; count++) { try { group = libzerocoin::deriveIntegerGroupParams(libzerocoin::calculateSeed(GetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen); } catch (const std::runtime_error& e) { std::cout << "Caught exception " << e.what() << std::endl; return false; } // Now perform some simple tests on the resulting parameters if ((uint32_t)group.groupOrder.bitSize() < qLen || (uint32_t)group.modulus.bitSize() < pLen) { return false; } CBigNum c = group.g.pow_mod(group.groupOrder, group.modulus); //cout << "g^q mod p = " << c << std::endl; if (!(c.isOne())) return false; // Try at multiple parameter sizes pLen = pLen * 1.5; qLen = qLen * 1.5; } return true; } bool Test_ParamGen() { bool result = true; try { // Instantiating testParams runs the parameter generation code libzerocoin::ZerocoinParams testParams(GetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL); } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; result = false; } return result; } bool Test_Accumulator() { // This test assumes a list of coins were generated during // the Test_MintCoin() test. if (gCoins[0] == NULL) { return false; } try { // Accumulate the coin list from first to last into one accumulator libzerocoin::Accumulator accOne(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::Accumulator accTwo(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::Accumulator accThree(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::Accumulator accFour(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::AccumulatorWitness wThree(g_Params, accThree, gCoins[0]->getPublicCoin()); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { accOne += gCoins[i]->getPublicCoin(); accTwo += gCoins[TESTS_COINS_TO_ACCUMULATE - (i+1)]->getPublicCoin(); accThree += gCoins[i]->getPublicCoin(); wThree += gCoins[i]->getPublicCoin(); if(i != 0) { accFour += gCoins[i]->getPublicCoin(); } } // Compare the accumulated results if (accOne.getValue() != accTwo.getValue() || accOne.getValue() != accThree.getValue()) { std::cout << "Accumulators don't match" << std::endl; return false; } if(accFour.getValue() != wThree.getValue()) { std::cout << "Witness math not working," << std::endl; return false; } // Verify that the witness is correct if (!wThree.VerifyWitness(accThree, gCoins[0]->getPublicCoin()) ) { std::cout << "Witness not valid" << std::endl; return false; } // Serialization test: see if we can serialize the accumulator CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << accOne; // Deserialize it into a new object libzerocoin::Accumulator newAcc(g_Params, ss); // Compare the results if (accOne.getValue() != newAcc.getValue()) { return false; } } catch (const std::runtime_error& e) { return false; } return true; } bool Test_EqualityPoK() { // Run this test 10 times for (uint32_t i = 0; i < 10; i++) { try { // Generate a random integer "val" CBigNum val = CBigNum::randBignum(g_Params->coinCommitmentGroup.groupOrder); // Manufacture two commitments to "val", both // under different sets of parameters libzerocoin::Commitment one(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, val); libzerocoin::Commitment two(&g_Params->serialNumberSoKCommitmentGroup, val); // Now generate a proof of knowledge that "one" and "two" are // both commitments to the same value libzerocoin::CommitmentProofOfKnowledge pok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, &g_Params->serialNumberSoKCommitmentGroup, one, two); // Serialize the proof into a stream CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pok; // Deserialize back into a PoK object libzerocoin::CommitmentProofOfKnowledge newPok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, &g_Params->serialNumberSoKCommitmentGroup, ss); if (newPok.Verify(one.getCommitmentValue(), two.getCommitmentValue()) != true) { return false; } // Just for fun, deserialize the proof a second time CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION); ss2 << pok; // This time tamper with it, then deserialize it back into a PoK ss2[15] = 0; libzerocoin::CommitmentProofOfKnowledge newPok2(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, &g_Params->serialNumberSoKCommitmentGroup, ss2); // If the tampered proof verifies, that's a failure! if (newPok2.Verify(one.getCommitmentValue(), two.getCommitmentValue()) == true) { return false; } } catch (const std::runtime_error& e) { return false; } } return true; } bool Test_MintCoin() { gCoinSize = 0; try { // Generate a list of coins for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { gCoins[i] = new libzerocoin::PrivateCoin(g_Params,libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::PublicCoin pc = gCoins[i]->getPublicCoin(); CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pc; gCoinSize += ss.size(); } gCoinSize /= TESTS_COINS_TO_ACCUMULATE; } catch (const std::exception& e) { return false; } return true; } bool Test_InvalidCoin() { CBigNum coinValue; try { // Pick a random non-prime CBigNum for (uint32_t i = 0; i < NON_PRIME_TESTS; i++) { coinValue = CBigNum::randBignum(g_Params->coinCommitmentGroup.modulus); coinValue = coinValue * 2; if (!coinValue.isPrime()) break; } libzerocoin::PublicCoin pubCoin(g_Params); if (pubCoin.validate()) { // A blank coin should not be valid! return false; } libzerocoin::PublicCoin pubCoin2(g_Params, coinValue, libzerocoin::ZQ_ONE); if (pubCoin2.validate()) { // A non-prime coin should not be valid! return false; } libzerocoin::PublicCoin pubCoin3 = pubCoin2; if (pubCoin2.validate()) { // A copy of a non-prime coin should not be valid! return false; } // Serialize and deserialize the coin CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << pubCoin; libzerocoin::PublicCoin pubCoin4(g_Params, ss); if (pubCoin4.validate()) { // A deserialized copy of a non-prime coin should not be valid! return false; } } catch (const std::runtime_error& e) { std::cout << "Caught exception: " << e.what() << std::endl; return false; } return true; } bool Test_MintAndSpend() { try { // This test assumes a list of coins were generated in Test_MintCoin() if (gCoins[0] == NULL) { // No coins: mint some. Test_MintCoin(); if (gCoins[0] == NULL) { return false; } } // Accumulate the list of generated coins into a fresh accumulator. // The first one gets marked as accumulated for a witness, the // others just get accumulated normally. libzerocoin::Accumulator acc(&g_Params->accumulatorParams, libzerocoin::CoinDenomination::ZQ_ONE); libzerocoin::AccumulatorWitness wAcc(g_Params, acc, gCoins[0]->getPublicCoin()); for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { acc += gCoins[i]->getPublicCoin(); wAcc +=gCoins[i]->getPublicCoin(); } // Now spend the coin //SpendMetaData m(1,1); CDataStream cc(SER_NETWORK, PROTOCOL_VERSION); cc << *gCoins[0]; libzerocoin::PrivateCoin myCoin(g_Params,cc); libzerocoin::CoinSpend spend(g_Params, g_Params, myCoin, acc, 0, wAcc, 0, libzerocoin::SpendType::SPEND); spend.Verify(acc); // Serialize the proof and deserialize into newSpend CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << spend; gProofSize = ss.size(); libzerocoin::CoinSpend newSpend(g_Params, g_Params, ss); // See if we can verify the deserialized proof (return our result) bool ret = newSpend.Verify(acc); // Extract the serial number CBigNum serialNumber = newSpend.getCoinSerialNumber(); gSerialNumberSize = ceil((double)serialNumber.bitSize() / 8.0); return ret; } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; return false; } return false; } void Test_RunAllTests() { // Make a new set of parameters from a random RSA modulus g_Params = new libzerocoin::ZerocoinParams(GetTestModulus()); gNumTests = gSuccessfulTests = gProofSize = 0; for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { gCoins[i] = NULL; } // Run through all of the Zerocoin tests LogTestResult("an RSA modulus can be generated", Test_GenRSAModulus); LogTestResult("parameter sizes are correct", Test_CalcParamSizes); LogTestResult("group/field parameters can be generated", Test_GenerateGroupParams); LogTestResult("parameter generation is correct", Test_ParamGen); LogTestResult("coins can be minted", Test_MintCoin); LogTestResult("invalid coins will be rejected", Test_InvalidCoin); LogTestResult("the accumulator works", Test_Accumulator); LogTestResult("the commitment equality PoK works", Test_EqualityPoK); LogTestResult("a minted coin can be spent", Test_MintAndSpend); std::cout << std::endl << "Average coin size is " << gCoinSize << " bytes." << std::endl; std::cout << "Serial number size is " << gSerialNumberSize << " bytes." << std::endl; std::cout << "Spend proof size is " << gProofSize << " bytes." << std::endl; // Summarize test results if (gSuccessfulTests < gNumTests) { std::cout << std::endl << "ERROR: SOME TESTS FAILED" << std::endl; } // Clear any generated coins for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) { delete gCoins[i]; } std::cout << std::endl << gSuccessfulTests << " out of " << gNumTests << " tests passed." << std::endl << std::endl; delete g_Params; } BOOST_FIXTURE_TEST_SUITE(libzerocoin, TestingSetup) BOOST_AUTO_TEST_CASE(libzerocoin_tests) { std::cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " test utility." << std::endl << std::endl; Test_RunAllTests(); } BOOST_AUTO_TEST_SUITE_END()
#include "nsasm/decode.h" #include "absl/memory/memory.h" #include "nsasm/expression.h" #include "nsasm/opcode_map.h" namespace nsasm { ErrorOr<Instruction> Decode(absl::Span<const uint8_t> bytes, const StatusFlags& flags) { if (bytes.empty()) { return Error("Not enough bytes to decode"); } uint8_t opcode = bytes.front(); bytes.remove_prefix(1); Instruction decoded; std::tie(decoded.mnemonic, decoded.addressing_mode) = DecodeOpcode(opcode); decoded.suffix = S_none; // correct for sentinel addressing modes if (decoded.addressing_mode == A_imm_fm || decoded.addressing_mode == A_imm_fx) { BitState narrow_register = (decoded.addressing_mode == A_imm_fm) ? flags.MBit() : flags.XBit(); if (narrow_register == B_on) { decoded.addressing_mode = A_imm_b; } else if (narrow_register == B_off) { decoded.addressing_mode = A_imm_w; } else { return Error( "Argument size of opcode 0x%02x (%s) depends on processor state, " "which is not known here", opcode, ToString(decoded.mnemonic)); } } // Read arguments if (decoded.addressing_mode == A_dir_l || decoded.addressing_mode == A_dir_lx) { // 24 bit argument if (bytes.size() < 3) { return Error("Not enough bytes to decode"); } decoded.arg1 = absl::make_unique<Literal>( bytes[0] + (bytes[1] * 256) + (bytes[2] * 256 * 256), T_long); } if (decoded.addressing_mode == A_imm_w || decoded.addressing_mode == A_dir_w || decoded.addressing_mode == A_dir_wx || decoded.addressing_mode == A_dir_wy || decoded.addressing_mode == A_ind_w || decoded.addressing_mode == A_ind_wx || decoded.addressing_mode == A_lng_w) { // 12 bit argument if (bytes.size() < 2) { return Error("Not enough bytes to decode"); } decoded.arg1 = absl::make_unique<Literal>(bytes[0] + (bytes[1] * 256), T_word); } if (decoded.addressing_mode == A_imm_b || decoded.addressing_mode == A_dir_b || decoded.addressing_mode == A_dir_bx || decoded.addressing_mode == A_dir_by || decoded.addressing_mode == A_ind_b || decoded.addressing_mode == A_ind_bx || decoded.addressing_mode == A_ind_by || decoded.addressing_mode == A_lng_b || decoded.addressing_mode == A_lng_by || decoded.addressing_mode == A_stk || decoded.addressing_mode == A_stk_y) { // 8 bit argument if (bytes.size() < 1) { return Error("Not enough bytes to decode"); } decoded.arg1 = absl::make_unique<Literal>(bytes[0], T_byte); } if (decoded.addressing_mode == A_mov) { // pair of 8 bit arguments if (bytes.size() < 2) { return Error("Not enough bytes to decode"); } decoded.arg1 = absl::make_unique<Literal>(bytes[1], T_byte); decoded.arg2 = absl::make_unique<Literal>(bytes[0], T_byte); } if (decoded.addressing_mode == A_rel8) { // 8 bit signed argument if (bytes.size() < 1) { return Error("Not enough bytes to decode"); } int value = bytes[0]; if (value >= 128) { value -= 256; } decoded.arg1 = absl::make_unique<Literal>(value, T_signed_byte); } if (decoded.addressing_mode == A_rel16) { // 8 bit signed argument if (bytes.size() < 2) { return Error("Not enough bytes to decode"); } int value = bytes[0] + (bytes[1] * 256); if (value >= 32768) { value -= 65536; } decoded.arg1 = absl::make_unique<Literal>(value, T_signed_word); } return {std::move(decoded)}; } } // namespace nsasm
#include "aes.h" unsigned char AES::sBox[] = { // 0 1 2 3 4 5 6 7 8 9 a b c d e f 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //a 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //b 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //c 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //d 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //e 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 //f }; unsigned char AES::invSBox[] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, //0 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, //1 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, //2 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, //3 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, //4 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, //5 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, //6 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, //7 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, //8 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, //9 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, //a 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, //b 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, //c 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, //d 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, //e 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d //f }; unsigned char AES::rcon[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; AES::AES() { //If no key is input,use the default key unsigned char key[16] = { 0x0f, 0x15, 0x71, 0xc9, 0x47, 0xd9, 0xe8, 0x59, 0x0c, 0xb7, 0xad, 0xd6, 0xaf, 0x7f, 0x67, 0x98 }; setKey(key); keyExpansion(); } AES::AES(const unsigned char *key){ setKey(key); keyExpansion(); } void AES::setKey(const unsigned char key[]){ mNb = 4; mNk = 4; mNr = 10; memcpy(mKey, key, mNk * 4); } void AES::keyExpansion() { //the first mNk words will be filled in mW derictly for (int i = 0; i < mNk; i++){ for (int j = 0; j < 4; j++){ //arranged vertically mW[i][j] = mKey[j+i*4]; } } //generate the secret key words for (int i = mNk; i < mNb*(mNr + 1); i++){ //last secret key word unsigned char pre_w[4]; for (int k = 0; k < 4; k++){ pre_w[k] = mW[i-1][k]; } if(i%mNk == 0){ rotWord(pre_w); subWord(pre_w); pre_w[0] = pre_w[0] ^= rcon[i / mNk - 1]; } else if ((mNk>6)&&(i%mNk==4)){ subWord(pre_w); } for (int k = 0; k < 4; k++){ mW[i][k] = pre_w[k] ^ mW[i-mNk][k]; } } } void AES::subBytes(unsigned char state[][4]) { for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ state[i][j] = sBox[state[i][j]]; } } } void AES::shiftRows(unsigned char state[][4]) { unsigned char t[4]; for (int i = 1; i < 4; i++){ for (int j = 0; j < 4; j++){ t[j] = state[i][(i + j) % 4]; } for (int j = 0; j < 4; j++){ state[i][j] = t[j]; } } } void AES::mixColumns(unsigned char state[][4]) { unsigned char t[4]; for (int j = 0; j < 4; j++){ for (int i = 0; i < 4; i++){ t[i] = state[i][j]; } for (int i = 0; i < 4; i++){ state[i][j] = GF28Multi(t[i], 0x02) ^ GF28Multi(t[(i + 1) % 4], 0x03) ^ GF28Multi(t[(i + 2) % 4], 0x01) ^ GF28Multi(t[(i + 3) % 4], 0x01); } } } void AES::addRoundKey(unsigned char state[][4], unsigned char w[][4]) { for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ state[i][j] ^= w[i][j]; } } } void AES::invSubBytes(unsigned char state[][4]) { for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ state[i][j] = invSBox[state[i][j]]; } } } void AES::invShiftRows(unsigned char state[][4]) { unsigned char t[4]; for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ t[j] = state[i][(j-i + 4) % 4]; } for (int j = 0; j < 4; j++){ state[i][j] = t[j]; } } } void AES::invMixColumns(unsigned char state[][4]) { unsigned char t[4]; //calculate columns by columns for (int j = 0; j < 4; j++){ for (int i = 0; i < 4; i++){ t[i] = state[i][j]; } for (int i = 0; i < 4; i++){ state[i][j] = GF28Multi(t[i], 0x0e) ^ GF28Multi(t[(i+1)%4],0x0b) ^ GF28Multi(t[(i+2)%4],0x0d) ^ GF28Multi(t[(i+3)%4],0x09); } } } void AES::rotWord(unsigned char w[]) { unsigned char t; t = w[0]; w[0] = w[1]; w[1] = w[2]; w[2] = w[3]; w[3] = t; } void AES::subWord(unsigned char w[]) { for (int i = 0; i < 4; i++){ w[i] = sBox[w[i]]; } } //calculate the least significant unsigned char only for we only need //the least significant byte unsigned char AES::GF28Multi(unsigned char s,unsigned char a){ unsigned char t[4]; unsigned char result = 0; t[0] = s; //calculate s*{02},s*{03},s*{04} for (int i = 1; i < 4; i++){ t[i] = t[i - 1] << 1; if (t[i - 1] & 0x80){ t[i] ^= 0x1b; } } //multiply a and s bit by bit and sum together for (int i = 0; i < 4; i++){ if ((a >> i) & 0x01){ result ^= t[i]; } } return result; } void AES::encrypt(const unsigned char data[16], unsigned char out[16]) { unsigned char state[4][4]; unsigned char key[4][4]; for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ state[i][j] = data[i+j*4]; } } getKeyAt(key, 0); addRoundKey(state, key); for (int i = 1; i <= mNr; i++){ subBytes(state); shiftRows(state); if (i != mNr){ mixColumns(state); } getKeyAt(key, i); addRoundKey(state, key); } for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ out[i+j*4] = state[i][j]; } } } void AES::decrypt(const unsigned char data[16], unsigned char out[16]) { unsigned char state[4][4]; unsigned char key[4][4]; for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ state[i][j] = data[i+j*4]; } } getKeyAt(key, mNr); addRoundKey(state,key); for (int i = (mNr - 1); i >= 0; i--){ invShiftRows(state); invSubBytes(state); getKeyAt(key, i); addRoundKey(state,key); if (i){ invMixColumns(state); } } for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ out[i + j * 4] = state[i][j]; } } } //get the secret key for round "index",which will //be arranged vetically void AES::getKeyAt(unsigned char key[][4], int index){ for (int i = index*4; i < index*4+4; i++){ for (int j = 0; j < 4; j++){ key[j][i-index*4] = mW[i][j]; } } } AES::~AES() { }
/* * Copyright (c) 2020 Project CHIP 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. */ /** * @file * Provides a C-callable wrapper around CHIPMem.h. */ #include <support/CHIPMem.h> #include <support/CHIPPlatformMemory.h> extern "C" { extern int CHIPPlatformMemoryInit(void * buf, size_t bufSize) { return static_cast<int>(chip::Platform::MemoryInit(buf, bufSize)); } extern void CHIPPlatformMemoryShutdown() { return chip::Platform::MemoryShutdown(); } extern void * CHIPPlatformMemoryAlloc(size_t size) { return chip::Platform::MemoryAlloc(size); } extern void * CHIPPlatformMemoryCalloc(size_t num, size_t size) { return chip::Platform::MemoryCalloc(num, size); } extern void * CHIPPlatformMemoryRealloc(void * p, size_t size) { return chip::Platform::MemoryRealloc(p, size); } extern void CHIPPlatformMemoryFree(void * p) { return chip::Platform::MemoryFree(p); } }
//===----------------------------------------------------------------------===// // // Part of the libcu++ 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 // //===----------------------------------------------------------------------===// // UNSUPPORTED: nvrtc // Internal compiler error in 14.24 // XFAIL: msvc-19.20, msvc-19.21, msvc-19.22, msvc-19.23, msvc-19.24, msvc-19.25 // uncomment for a really verbose output detailing what test steps are being launched // #define DEBUG_TESTERS #include "helpers.h" #include <cuda/std/tuple> #include <cuda/std/cassert> struct pod { char val[10]; }; using tuple_t = cuda::std::tuple<int, pod, unsigned long long>; template<int N> struct write { using async = cuda::std::false_type; template <typename Tuple> __host__ __device__ static void perform(Tuple &t) { cuda::std::get<0>(t) = N; cuda::std::get<1>(t).val[0] = N; cuda::std::get<2>(t) = N; } }; template<int N> struct read { using async = cuda::std::false_type; template <typename Tuple> __host__ __device__ static void perform(Tuple &t) { assert(cuda::std::get<0>(t) == N); assert(cuda::std::get<1>(t).val[0] == N); assert(cuda::std::get<2>(t) == N); } }; using w_r_w_r = performer_list< write<10>, read<10>, write<30>, read<30> >; void kernel_invoker() { tuple_t t(0, {0}, 0); validate_not_movable< tuple_t, w_r_w_r >(t); } int main(int arg, char ** argv) { #ifndef __CUDA_ARCH__ kernel_invoker(); #endif return 0; }
/***************************************************************************** * Copyright (C) 2013-2017 MulticoreWare, Inc * * Authors: Peixuan Zhang <zhangpeixuancn@gmail.com> * Chunli Zhang <chunli@multicorewareinc.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. * * This program is also available under a commercial proprietary license. * For more information, contact us at license @ x265.com. *****************************************************************************/ #include "common.h" #include "reconplay.h" #include <signal.h> using namespace X265_NS; #if _WIN32 #define popen _popen #define pclose _pclose #define pipemode "wb" #else #define pipemode "w" #endif bool ReconPlay::pipeValid; #ifndef _WIN32 static void sigpipe_handler(int) { if (ReconPlay::pipeValid) general_log(NULL, "exec", X265_LOG_ERROR, "pipe closed\n"); ReconPlay::pipeValid = false; } #endif ReconPlay::ReconPlay(const char* commandLine, x265_param& param) { #ifndef _WIN32 if (signal(SIGPIPE, sigpipe_handler) == SIG_ERR) general_log(&param, "exec", X265_LOG_ERROR, "Unable to register SIGPIPE handler: %s\n", strerror(errno)); #endif width = param.sourceWidth; height = param.sourceHeight; colorSpace = param.internalCsp; frameSize = 0; for (int i = 0; i < x265_cli_csps[colorSpace].planes; i++) frameSize += (uint32_t)((width >> x265_cli_csps[colorSpace].width[i]) * (height >> x265_cli_csps[colorSpace].height[i])); for (int i = 0; i < RECON_BUF_SIZE; i++) { poc[i] = -1; CHECKED_MALLOC(frameData[i], pixel, frameSize); } outputPipe = popen(commandLine, pipemode); if (outputPipe) { const char* csp = (colorSpace >= X265_CSP_I444) ? "444" : (colorSpace >= X265_CSP_I422) ? "422" : "420"; const char* depth = (param.internalBitDepth == 10) ? "p10" : ""; fprintf(outputPipe, "YUV4MPEG2 W%d H%d F%d:%d Ip C%s%s\n", width, height, param.fpsNum, param.fpsDenom, csp, depth); pipeValid = true; threadActive = true; start(); return; } else general_log(&param, "exec", X265_LOG_ERROR, "popen(%s) failed\n", commandLine); fail: threadActive = false; } ReconPlay::~ReconPlay() { if (threadActive) { threadActive = false; writeCount.poke(); stop(); } if (outputPipe) pclose(outputPipe); for (int i = 0; i < RECON_BUF_SIZE; i++) X265_FREE(frameData[i]); } bool ReconPlay::writePicture(const x265_picture& pic) { if (!threadActive || !pipeValid) return false; int written = writeCount.get(); int read = readCount.get(); int currentCursor = pic.poc % RECON_BUF_SIZE; /* TODO: it's probably better to drop recon pictures when the ring buffer is * backed up on the display app */ while (written - read > RECON_BUF_SIZE - 2 || poc[currentCursor] != -1) { read = readCount.waitForChange(read); if (!threadActive) return false; } X265_CHECK(pic.colorSpace == colorSpace, "invalid color space\n"); X265_CHECK(pic.bitDepth == X265_DEPTH, "invalid bit depth\n"); pixel* buf = frameData[currentCursor]; for (int i = 0; i < x265_cli_csps[colorSpace].planes; i++) { char* src = (char*)pic.planes[i]; int pwidth = width >> x265_cli_csps[colorSpace].width[i]; for (int h = 0; h < height >> x265_cli_csps[colorSpace].height[i]; h++) { memcpy(buf, src, pwidth * sizeof(pixel)); src += pic.stride[i]; buf += pwidth; } } poc[currentCursor] = pic.poc; writeCount.incr(); return true; } void ReconPlay::threadMain() { THREAD_NAME("ReconPlayOutput", 0); do { /* extract the next output picture in display order and write to pipe */ if (!outputFrame()) break; } while (threadActive); threadActive = false; readCount.poke(); } bool ReconPlay::outputFrame() { int written = writeCount.get(); int read = readCount.get(); int currentCursor = read % RECON_BUF_SIZE; while (poc[currentCursor] != read) { written = writeCount.waitForChange(written); if (!threadActive) return false; } char* buf = (char*)frameData[currentCursor]; intptr_t remainSize = frameSize * sizeof(pixel); fprintf(outputPipe, "FRAME\n"); while (remainSize > 0) { intptr_t retCount = (intptr_t)fwrite(buf, sizeof(char), remainSize, outputPipe); if (retCount < 0 || !pipeValid) /* pipe failure, stop writing and start dropping recon pictures */ return false; buf += retCount; remainSize -= retCount; } poc[currentCursor] = -1; readCount.incr(); return true; }
// // Created by zing on 4/30/2020. // #include <vector> #include <string> #include <iostream> using namespace std; int main(int argc, char *argv[]) { vector<int> vec1; vector<int> vec2(vec1); vector<int> vec3 = vec2; vector<int> vec4(10, -1); vector<string> language = {"cpp", "rust", "java"}; cout << language.size() << endl; vector<string> language2{"cpp", "rust", "java"}; vector<string> str(10, "hi"); vector<string> l; l.push_back("cpp"); l.push_back("rust"); cout << l.size() << endl; cout << l.empty() << endl; cout << l[0] << endl; cout << l[1] << endl; vector<int> v{1, 2, 3, 4, 5, 6, 7, 8}; for (auto &i:v) { i *= i; } for (auto i:v) { cout << i << endl; } return 0; }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <folly/portability/GTest.h> #include <quic/common/test/TestUtils.h> #include <quic/congestion_control/test/TestingCubic.h> using namespace quic; using namespace quic::test; using namespace testing; namespace quic { namespace test { class CubicTest : public Test {}; TEST_F(CubicTest, SentReduceWritable) { QuicConnectionStateBase conn(QuicNodeType::Client); Cubic cubic(conn); auto initCwnd = cubic.getWritableBytes(); cubic.onPacketSent(makeTestingWritePacket(0, 100, 100)); EXPECT_EQ(initCwnd - 100, cubic.getWritableBytes()); } TEST_F(CubicTest, AckIncreaseWritable) { QuicConnectionStateBase conn(QuicNodeType::Client); Cubic cubic(conn); auto initCwnd = cubic.getWritableBytes(); auto packet = makeTestingWritePacket(0, 100, 100); cubic.onPacketSent(packet); EXPECT_EQ(initCwnd - 100, cubic.getWritableBytes()); // Acking 50, now inflight become 50. Cwnd is init + 50 cubic.onPacketAckOrLoss( makeAck(0, 50, Clock::now(), packet.time), folly::none); EXPECT_EQ(initCwnd, cubic.getWritableBytes()); } TEST_F(CubicTest, PersistentCongestion) { QuicConnectionStateBase conn(QuicNodeType::Client); auto qLogger = std::make_shared<FileQLogger>(); conn.qLogger = qLogger; Cubic cubic(conn, std::numeric_limits<uint64_t>::max(), false); auto initCwnd = cubic.getWritableBytes(); auto packet = makeTestingWritePacket(0, 1000, 1000); // Sent and lost, inflight = 0 cubic.onPacketSent(packet); CongestionController::LossEvent loss; loss.addLostPacket(packet); loss.persistentCongestion = true; cubic.onPacketAckOrLoss(folly::none, std::move(loss)); EXPECT_EQ(CubicStates::Hystart, cubic.state()); // Cwnd should be dropped to minCwnd: EXPECT_EQ( conn.transportSettings.minCwndInMss * conn.udpSendPacketLen, cubic.getWritableBytes()); // Verify ssthresh is at initCwnd / 2 auto packet2 = makeTestingWritePacket(1, initCwnd / 2, initCwnd / 2 + 1000); cubic.onPacketSent(packet2); cubic.onPacketAckOrLoss( makeAck(1, initCwnd / 2, Clock::now(), packet2.time), folly::none); EXPECT_EQ(CubicStates::Steady, cubic.state()); // Verify both lastMaxCwndBytes and lastReductionTime are also reset in // onPersistentCongestion. When they are both verified, the first ACK will // make both timeToOrigin and timeElapsed to be 0 in Ack handling in Steady // handler: auto currentCwnd = cubic.getWritableBytes(); // since nothing inflight auto packet3 = makeTestingWritePacket(2, 3000, initCwnd / 2 + 1000 + 3000); cubic.onPacketSent(packet3); cubic.onPacketAckOrLoss( makeAck(2, 3000, Clock::now(), packet3.time), folly::none); std::vector<int> indices = getQLogEventIndices(QLogEventType::CongestionMetricUpdate, qLogger); EXPECT_EQ(indices.size(), 9); std::array<uint64_t, 9> cwdArr = {initCwnd, 11088, 2464, cubic.getCongestionWindow(), cubic.getCongestionWindow(), cubic.getCongestionWindow(), cubic.getCongestionWindow(), cubic.getCongestionWindow(), cubic.getCongestionWindow()}; std::array<std::string, 9> congestionEventArr = { kRemoveInflight.str(), kCubicLoss.str(), kPersistentCongestion.str(), kCongestionPacketAck.str(), kResetTimeToOrigin.str(), kResetLastReductionTime.str(), kCubicSteadyCwnd.str(), kCwndNoChange.str(), kCongestionPacketAck.str()}; std::array<folly::StringPiece, 9> stateArr = { cubicStateToString(CubicStates::Hystart), cubicStateToString(CubicStates::FastRecovery), cubicStateToString(CubicStates::Hystart), cubicStateToString(CubicStates::Steady), cubicStateToString(CubicStates::Steady), cubicStateToString(CubicStates::Steady), cubicStateToString(CubicStates::Steady), cubicStateToString(CubicStates::Steady), cubicStateToString(CubicStates::Steady)}; for (int i = 0; i < 9; ++i) { auto tmp = std::move(qLogger->logs[indices[i]]); auto event = dynamic_cast<QLogCongestionMetricUpdateEvent*>(tmp.get()); EXPECT_EQ(event->bytesInFlight, 0); EXPECT_EQ(event->currentCwnd, cwdArr[i]); EXPECT_EQ(event->congestionEvent, congestionEventArr[i]); EXPECT_EQ(event->state, stateArr[i]); EXPECT_EQ(event->recoveryState, ""); } EXPECT_EQ(currentCwnd, cubic.getWritableBytes()); } TEST_F(CubicTest, CwndIncreaseAfterReduction) { QuicConnectionStateBase conn(QuicNodeType::Client); conn.udpSendPacketLen = 200; // initCwnd > initSsthresh: an ack will immediately make the state machine // transit to Steady state: Cubic cubic(conn, 1000); cubic.setConnectionEmulation(1); // Easier to argue reduction this way // Send one and get acked, this moves the state machine to steady auto packet0 = makeTestingWritePacket(0, 1000, 1000); conn.lossState.largestSent = 0; cubic.onPacketSent(packet0); cubic.onPacketAckOrLoss( makeAck(0, 1000, Clock::now(), packet0.time), folly::none); // Cwnd increased by 1000, inflight = 0: EXPECT_EQ(3000, cubic.getWritableBytes()); EXPECT_EQ(CubicStates::Steady, cubic.state()); auto packet1 = makeTestingWritePacket(1, 1000, 2000); auto packet2 = makeTestingWritePacket(2, 1000, 3000); auto packet3 = makeTestingWritePacket(3, 1000, 4000); // This will set endOfRecovery to 3 when loss happens: conn.lossState.largestSent = 3; cubic.onPacketSent(packet1); cubic.onPacketSent(packet2); cubic.onPacketSent(packet3); // Cwnd = 3000, inflight = 3000: EXPECT_EQ(0, cubic.getWritableBytes()); cubic.onPacketAckOrLoss( makeAck(1, 1000, Clock::now(), packet1.time), folly::none); // Cwnd >= 3000, inflight = 2000: EXPECT_GE(cubic.getWritableBytes(), 1000); CongestionController::LossEvent loss; loss.addLostPacket(packet2); cubic.onPacketAckOrLoss(folly::none, std::move(loss)); // Cwnd >= 2400, inflight = 1000: EXPECT_GE(cubic.getWritableBytes(), 1400); // This won't bring state machine back to Steady since endOfRecovery = 3 cubic.onPacketAckOrLoss( makeAck(3, 1000, Clock::now(), packet3.time), folly::none); // Cwnd no change, inflight = 0: EXPECT_GE(cubic.getWritableBytes(), 2400); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); auto packet4 = makeTestingWritePacket(4, 1000, 5000); conn.lossState.largestSent = 4; cubic.onPacketSent(packet4); // This will bring state machine back to steady cubic.onPacketAckOrLoss( makeAck(4, 1000, Clock::now(), packet4.time), folly::none); EXPECT_GE(cubic.getWritableBytes(), 2400); EXPECT_EQ(CubicStates::Steady, cubic.state()); } TEST_F(CubicTest, AppIdle) { QuicConnectionStateBase conn(QuicNodeType::Client); auto qLogger = std::make_shared<FileQLogger>(); conn.qLogger = qLogger; conn.udpSendPacketLen = 1500; TestingCubic cubic(conn); cubic.setStateForTest(CubicStates::Steady); auto packet = makeTestingWritePacket(0, 1000, 1000); cubic.onPacketSent(packet); auto reductionTime = Clock::now(); auto maxCwnd = cubic.getCongestionWindow(); CongestionController::LossEvent loss(reductionTime); loss.addLostPacket(packet); cubic.onPacketAckOrLoss(folly::none, std::move(loss)); auto timeToOrigin = ::cbrt( (maxCwnd - cubic.getCongestionWindow()) * 1000 * 1000 / conn.udpSendPacketLen * 2500); auto cwnd = cubic.getCongestionWindow(); auto packet1 = makeTestingWritePacket(1, 1000, 2000); cubic.onPacketSent(packet1); cubic.onPacketAckOrLoss( makeAck(1, 1000, reductionTime + 1000ms, packet1.time), folly::none); EXPECT_EQ(CubicStates::Steady, cubic.state()); EXPECT_GT(cubic.getCongestionWindow(), cwnd); cwnd = cubic.getCongestionWindow(); cubic.setAppIdle(true, reductionTime + 1100ms); EXPECT_TRUE(cubic.isAppLimited()); auto packet2 = makeTestingWritePacket(2, 1000, 3000); cubic.onPacketSent(packet2); cubic.onPacketAckOrLoss( makeAck(2, 1000, reductionTime + 2000ms, packet2.time), folly::none); EXPECT_EQ(cubic.getCongestionWindow(), cwnd); // 1 seconds of quiescence cubic.setAppIdle(false, reductionTime + 2100ms); EXPECT_FALSE(cubic.isAppLimited()); auto packet3 = makeTestingWritePacket(3, 1000, 4000); cubic.onPacketSent(packet3); cubic.onPacketAckOrLoss( makeAck(3, 1000, reductionTime + 3000ms, packet3.time), folly::none); EXPECT_GT(cubic.getCongestionWindow(), cwnd); auto expectedDelta = static_cast<int64_t>(std::floor( conn.udpSendPacketLen * kTimeScalingFactor * std::pow((2 * 1000 - timeToOrigin), 3.0) / 1000 / 1000 / 1000)); EXPECT_EQ(maxCwnd + expectedDelta, cubic.getCongestionWindow()); std::vector<int> indices = getQLogEventIndices(QLogEventType::AppIdleUpdate, qLogger); EXPECT_EQ(indices.size(), 2); std::array<bool, 2> idleArr = {true, false}; for (int i = 0; i < 2; ++i) { auto tmp = std::move(qLogger->logs[indices[i]]); auto event = dynamic_cast<QLogAppIdleUpdateEvent*>(tmp.get()); EXPECT_EQ(event->idleEvent, kAppIdle.str()); EXPECT_EQ(event->idle, idleArr[i]); } } TEST_F(CubicTest, PacingGain) { QuicConnectionStateBase conn(QuicNodeType::Client); conn.udpSendPacketLen = 1500; Cubic cubic(conn); cubic.setMinimalPacingInterval(1ms); conn.lossState.srtt = 3000us; auto packet = makeTestingWritePacket(0, 1500, 1500); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( makeAck(0, 1500, Clock::now(), packet.time), folly::none); EXPECT_EQ(CubicStates::Hystart, cubic.state()); // 11 * 2 / (3 / 1), then take ceil EXPECT_EQ(1ms, cubic.getPacingInterval()); EXPECT_EQ(8, cubic.getPacingRate(Clock::now())); auto packet1 = makeTestingWritePacket(1, 1500, 3000); cubic.onPacketSent(packet1); CongestionController::LossEvent loss; loss.addLostPacket(packet1); // reduce cwnd to 9 MSS cubic.onPacketAckOrLoss(folly::none, loss); EXPECT_EQ(CubicStates::FastRecovery, cubic.state()); // 9 * 1.25 / (3 / 1) then take ceil EXPECT_EQ(1ms, cubic.getPacingInterval()); EXPECT_EQ(4, cubic.getPacingRate(Clock::now())); auto packet2 = makeTestingWritePacket(2, 1500, 4500); cubic.onPacketSent(packet2); cubic.onPacketAckOrLoss( makeAck(2, 1500, Clock::now(), packet2.time), folly::none); EXPECT_EQ(CubicStates::Steady, cubic.state()); // Cwnd should still be very close to 9 mss // 9 / (3 / 1) EXPECT_EQ(1ms, cubic.getPacingInterval()); EXPECT_NEAR(3, cubic.getPacingRate(Clock::now()), 1); } TEST_F(CubicTest, PacingSpread) { QuicConnectionStateBase conn(QuicNodeType::Client); conn.lossState.srtt = 60ms; conn.udpSendPacketLen = 1500; Cubic::CubicBuilder builder; builder.setPacingSpreadAcrossRtt(true); auto cubic = builder.build(conn); cubic->setMinimalPacingInterval(1ms); for (size_t i = 0; i < 5; i++) { auto packet = makeTestingWritePacket(i, 1500, 4500 + 1500 * (1 + i)); cubic->onPacketSent(packet); cubic->onPacketAckOrLoss( makeAck(i, 1500, Clock::now(), packet.time), folly::none); } ASSERT_EQ(1500 * 15, cubic->getCongestionWindow()); EXPECT_EQ(1, cubic->getPacingRate(Clock::now())); EXPECT_EQ(2ms, cubic->getPacingInterval()); } TEST_F(CubicTest, LatePacingTimer) { QuicConnectionStateBase conn(QuicNodeType::Client); conn.lossState.srtt = 50ms; Cubic cubic(conn); cubic.setMinimalPacingInterval(1ms); auto packet = makeTestingWritePacket(0, conn.udpSendPacketLen, conn.udpSendPacketLen); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( makeAck(0, conn.udpSendPacketLen, Clock::now(), packet.time), folly::none); auto currentTime = Clock::now(); auto pacingRateWithoutCompensation = cubic.getPacingRate(currentTime); cubic.markPacerTimeoutScheduled(currentTime); auto pacingRateWithCompensation = cubic.getPacingRate(currentTime + 50ms); EXPECT_GT(pacingRateWithCompensation, pacingRateWithoutCompensation); // No matter how late it comes, you cannot go beyond the max limit auto veryLatePacingRate = cubic.getPacingRate(currentTime + 100s); EXPECT_GE(conn.transportSettings.maxBurstPackets, veryLatePacingRate); // But if you call getPacingRate again, it won't have compensation auto pacingRateAgain = cubic.getPacingRate(currentTime + 50ms); EXPECT_LT(pacingRateAgain, pacingRateWithCompensation); } TEST_F(CubicTest, RttSmallerThanInterval) { QuicConnectionStateBase conn(QuicNodeType::Client); conn.udpSendPacketLen = 1500; conn.lossState.srtt = 1us; Cubic cubic(conn); auto packet = makeTestingWritePacket(0, 1500, 1500); cubic.onPacketSent(packet); cubic.onPacketAckOrLoss( makeAck(0, 1500, Clock::now(), packet.time), folly::none); EXPECT_FALSE(cubic.canBePaced()); EXPECT_EQ(std::chrono::milliseconds::zero(), cubic.getPacingInterval()); EXPECT_EQ( conn.transportSettings.writeConnectionDataPacketsLimit, cubic.getPacingRate(Clock::now())); } } // namespace test } // namespace quic
/* * Copyright 2006, Haiku. * Distributed under the terms of the MIT License. * * Authors: * Stephan Aßmus <superstippi@gmx.de> */ #include "AddTransformersCommand.h" #include <new> #include <stdio.h> #include <string.h> #include <Catalog.h> #include <Locale.h> #include "ShapeContainer.h" #include "Shape.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Icon-O-Matic-AddTransformersCmd" using std::nothrow; // constructor AddTransformersCommand::AddTransformersCommand(Shape* container, Transformer** const transformers, int32 count, int32 index) : Command(), fContainer(container), fTransformers(transformers && count > 0 ? new (nothrow) Transformer*[count] : NULL), fCount(count), fIndex(index), fTransformersAdded(false) { if (!fContainer || !fTransformers) return; memcpy(fTransformers, transformers, sizeof(Transformer*) * fCount); } // destructor AddTransformersCommand::~AddTransformersCommand() { if (!fTransformersAdded && fTransformers) { for (int32 i = 0; i < fCount; i++) delete fTransformers[i]; } delete[] fTransformers; } // InitCheck status_t AddTransformersCommand::InitCheck() { return fContainer && fTransformers ? B_OK : B_NO_INIT; } // Perform status_t AddTransformersCommand::Perform() { status_t ret = B_OK; // add transformers to container int32 index = fIndex; for (int32 i = 0; i < fCount; i++) { if (fTransformers[i] && !fContainer->AddTransformer(fTransformers[i], index)) { ret = B_ERROR; // roll back for (int32 j = i - 1; j >= 0; j--) fContainer->RemoveTransformer(fTransformers[j]); break; } index++; } fTransformersAdded = true; return ret; } // Undo status_t AddTransformersCommand::Undo() { status_t ret = B_OK; // add shapes to container at remembered indices for (int32 i = 0; i < fCount; i++) { fContainer->RemoveTransformer(fTransformers[i]); } fTransformersAdded = false; return ret; } // GetName void AddTransformersCommand::GetName(BString& name) { if (fCount > 1) name << B_TRANSLATE("Add Transformers"); else name << B_TRANSLATE("Add Transformer"); }
/* * Copyright 2011-2018 Blender Foundation * * 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 "util/util_foreach.h" #include "util/util_ies.h" #include "util/util_math.h" #include "util/util_string.h" CCL_NAMESPACE_BEGIN // NOTE: For some reason gcc-7.2 does not instantiate this versio of allocator // gere (used in IESTextParser). Works fine for gcc-6, gcc-7.3 and gcc-8. // // TODO(sergey): Get to the root of this issue, or confirm this i a compiler // issue. template class GuardedAllocator<char>; bool IESFile::load(ustring ies) { clear(); if (!parse(ies) || !process()) { clear(); return false; } return true; } void IESFile::clear() { intensity.clear(); v_angles.clear(); h_angles.clear(); } int IESFile::packed_size() { if (v_angles.size() && h_angles.size() > 0) { return 2 + h_angles.size() + v_angles.size() + h_angles.size() * v_angles.size(); } return 0; } void IESFile::pack(float *data) { if (v_angles.size() && h_angles.size()) { *(data++) = __int_as_float(h_angles.size()); *(data++) = __int_as_float(v_angles.size()); memcpy(data, &h_angles[0], h_angles.size() * sizeof(float)); data += h_angles.size(); memcpy(data, &v_angles[0], v_angles.size() * sizeof(float)); data += v_angles.size(); for (int h = 0; h < intensity.size(); h++) { memcpy(data, &intensity[h][0], v_angles.size() * sizeof(float)); data += v_angles.size(); } } } class IESTextParser { public: vector<char> text; char *data; IESTextParser(ustring str) : text(str.begin(), str.end()) { std::replace(text.begin(), text.end(), ',', ' '); data = strstr(&text[0], "\nTILT="); } bool eof() { return (data == NULL) || (data[0] == '\0'); } double get_double() { if (eof()) { return 0.0; } char *old_data = data; double val = strtod(data, &data); if (data == old_data) { data = NULL; return 0.0; } return val; } long get_long() { if (eof()) { return 0; } char *old_data = data; long val = strtol(data, &data, 10); if (data == old_data) { data = NULL; return 0; } return val; } }; bool IESFile::parse(ustring ies) { if (ies.empty()) { return false; } IESTextParser parser(ies); if (parser.eof()) { return false; } /* Handle the tilt data block. */ if (strncmp(parser.data, "\nTILT=INCLUDE", 13) == 0) { parser.data += 13; parser.get_double(); /* Lamp to Luminaire geometry */ int num_tilt = parser.get_long(); /* Amount of tilt angles and factors */ /* Skip over angles and factors. */ for (int i = 0; i < 2 * num_tilt; i++) { parser.get_double(); } } else { /* Skip to next line. */ parser.data = strstr(parser.data + 1, "\n"); } if (parser.eof()) { return false; } parser.data++; parser.get_long(); /* Number of lamps */ parser.get_double(); /* Lumens per lamp */ double factor = parser.get_double(); /* Candela multiplier */ int v_angles_num = parser.get_long(); /* Number of vertical angles */ int h_angles_num = parser.get_long(); /* Number of horizontal angles */ type = (IESType)parser.get_long(); /* Photometric type */ /* TODO(lukas): Test whether the current type B processing can also deal with type A files. * In theory the only difference should be orientation which we ignore anyways, but with IES you never know... */ if (type != TYPE_B && type != TYPE_C) { return false; } parser.get_long(); /* Unit of the geometry data */ parser.get_double(); /* Width */ parser.get_double(); /* Length */ parser.get_double(); /* Height */ factor *= parser.get_double(); /* Ballast factor */ factor *= parser.get_double(); /* Ballast-Lamp Photometric factor */ parser.get_double(); /* Input Watts */ /* Intensity values in IES files are specified in candela (lumen/sr), a photometric quantity. * Cycles expects radiometric quantities, though, which requires a conversion. * However, the Luminous efficacy (ratio of lumens per Watt) depends on the spectral distribution * of the light source since lumens take human perception into account. * Since this spectral distribution is not known from the IES file, a typical one must be assumed. * The D65 standard illuminant has a Luminous efficacy of 177.83, which is used here to convert to Watt/sr. * A more advanced approach would be to add a Blackbody Temperature input to the node and numerically * integrate the Luminous efficacy from the resulting spectral distribution. * Also, the Watt/sr value must be multiplied by 4*pi to get the Watt value that Cycles expects * for lamp strength. Therefore, the conversion here uses 4*pi/177.83 as a Candela to Watt factor. */ factor *= 0.0706650768394; v_angles.reserve(v_angles_num); for (int i = 0; i < v_angles_num; i++) { v_angles.push_back((float)parser.get_double()); } h_angles.reserve(h_angles_num); for (int i = 0; i < h_angles_num; i++) { h_angles.push_back((float)parser.get_double()); } intensity.resize(h_angles_num); for (int i = 0; i < h_angles_num; i++) { intensity[i].reserve(v_angles_num); for (int j = 0; j < v_angles_num; j++) { intensity[i].push_back((float)(factor * parser.get_double())); } } return !parser.eof(); } bool IESFile::process_type_b() { vector<vector<float>> newintensity; newintensity.resize(v_angles.size()); for (int i = 0; i < v_angles.size(); i++) { newintensity[i].reserve(h_angles.size()); for (int j = 0; j < h_angles.size(); j++) { newintensity[i].push_back(intensity[j][i]); } } intensity.swap(newintensity); h_angles.swap(v_angles); float h_first = h_angles[0], h_last = h_angles[h_angles.size() - 1]; if (h_last != 90.0f) { return false; } if (h_first == 0.0f) { /* The range in the file corresponds to 90°-180°, we need to mirror that to get the * full 180° range. */ vector<float> new_h_angles; vector<vector<float>> new_intensity; int hnum = h_angles.size(); new_h_angles.reserve(2 * hnum - 1); new_intensity.reserve(2 * hnum - 1); for (int i = hnum - 1; i > 0; i--) { new_h_angles.push_back(90.0f - h_angles[i]); new_intensity.push_back(intensity[i]); } for (int i = 0; i < hnum; i++) { new_h_angles.push_back(90.0f + h_angles[i]); new_intensity.push_back(intensity[i]); } h_angles.swap(new_h_angles); intensity.swap(new_intensity); } else if (h_first == -90.0f) { /* We have full 180° coverage, so just shift to match the angle range convention. */ for (int i = 0; i < h_angles.size(); i++) { h_angles[i] += 90.0f; } } /* To get correct results with the cubic interpolation in the kernel, the horizontal range * has to cover all 360°. Therefore, we copy the 0° entry to 360° to ensure full coverage * and seamless interpolation. */ h_angles.push_back(360.0f); intensity.push_back(intensity[0]); float v_first = v_angles[0], v_last = v_angles[v_angles.size() - 1]; if (v_last != 90.0f) { return false; } if (v_first == 0.0f) { /* The range in the file corresponds to 90°-180°, we need to mirror that to get the * full 180° range. */ vector<float> new_v_angles; int hnum = h_angles.size(); int vnum = v_angles.size(); new_v_angles.reserve(2 * vnum - 1); for (int i = vnum - 1; i > 0; i--) { new_v_angles.push_back(90.0f - v_angles[i]); } for (int i = 0; i < vnum; i++) { new_v_angles.push_back(90.0f + v_angles[i]); } for (int i = 0; i < hnum; i++) { vector<float> new_intensity; new_intensity.reserve(2 * vnum - 1); for (int j = vnum - 2; j >= 0; j--) { new_intensity.push_back(intensity[i][j]); } new_intensity.insert(new_intensity.end(), intensity[i].begin(), intensity[i].end()); intensity[i].swap(new_intensity); } v_angles.swap(new_v_angles); } else if (v_first == -90.0f) { /* We have full 180° coverage, so just shift to match the angle range convention. */ for (int i = 0; i < v_angles.size(); i++) { v_angles[i] += 90.0f; } } return true; } bool IESFile::process_type_c() { if (h_angles[0] == 90.0f) { /* Some files are stored from 90° to 270°, so we just rotate them to the regular 0°-180° range here. */ for (int i = 0; i < h_angles.size(); i++) { h_angles[i] -= 90.0f; } } if (h_angles[0] != 0.0f) { return false; } if (h_angles.size() == 1) { h_angles.push_back(360.0f); intensity.push_back(intensity[0]); } if (h_angles[h_angles.size() - 1] == 90.0f) { /* Only one quadrant is defined, so we need to mirror twice (from one to two, then to four). * Since the two->four mirroring step might also be required if we get an input of two quadrants, * we only do the first mirror here and later do the second mirror in either case. */ int hnum = h_angles.size(); for (int i = hnum - 2; i >= 0; i--) { h_angles.push_back(180.0f - h_angles[i]); intensity.push_back(intensity[i]); } } if (h_angles[h_angles.size() - 1] == 180.0f) { /* Mirror half to the full range. */ int hnum = h_angles.size(); for (int i = hnum - 2; i >= 0; i--) { h_angles.push_back(360.0f - h_angles[i]); intensity.push_back(intensity[i]); } } /* Some files skip the 360° entry (contrary to standard) because it's supposed to be identical to the 0° entry. * If the file has a discernible order in its spacing, just fix this. */ if (h_angles[h_angles.size() - 1] != 360.0f) { int hnum = h_angles.size(); float last_step = h_angles[hnum - 1] - h_angles[hnum - 2]; float first_step = h_angles[1] - h_angles[0]; float difference = 360.0f - h_angles[hnum - 1]; if (last_step == difference || first_step == difference) { h_angles.push_back(360.0f); intensity.push_back(intensity[0]); } else { return false; } } float v_first = v_angles[0], v_last = v_angles[v_angles.size() - 1]; if (v_first == 90.0f) { if (v_last == 180.0f) { /* Flip to ensure that vertical angles always start at 0°. */ for (int i = 0; i < v_angles.size(); i++) { v_angles[i] = 180.0f - v_angles[i]; } } else { return false; } } else if (v_first != 0.0f) { return false; } return true; } bool IESFile::process() { if (h_angles.size() == 0 || v_angles.size() == 0) { return false; } if (type == TYPE_B) { if (!process_type_b()) { return false; } } else { assert(type == TYPE_C); if (!process_type_c()) { return false; } } assert(v_angles[0] == 0.0f); assert(h_angles[0] == 0.0f); assert(h_angles[h_angles.size() - 1] == 360.0f); /* Convert from deg to rad. */ for (int i = 0; i < v_angles.size(); i++) { v_angles[i] *= M_PI_F / 180.f; } for (int i = 0; i < h_angles.size(); i++) { h_angles[i] *= M_PI_F / 180.f; } return true; } IESFile::~IESFile() { clear(); } CCL_NAMESPACE_END
// // Created by william on 7/6/17. // #ifndef FAM_EXAMPLE #define FAM_EXAMPLE #include <fam.h> #include <iostream> #include <string.h> class Fam { private: FAMConnection* fc; FAMRequest* fr; // event data is put here. This pointer will be reused for each event. FAMEvent* fe = new FAMEvent() ; enum { ERROR_STAT_FILE = 1 , ERROR_DETERMINE_USER , ERROR_FAM_OPEN , ERROR_FAM_MONITOR } ; void checkStrerror( int error ){ if( 0 != error ){ std::cerr << "System error is: " << strerror( errno ) << std::endl ; } return ; } public: Fam(const char* toWatch) { // init FAM connection fc = new FAMConnection() ; fr = new FAMRequest() ; // connect to the FAM service if( 0 != FAMOpen( fc ) ){ std::cerr << "FAM connectivity test failed: unable to open FAM connection." << std::endl ; std::cerr << "(Hint: make sure FAM (via xinetd) and portmapper are running.)" << std::endl ; checkStrerror( errno ) ; throw( ERROR_FAM_OPEN ) ; } // register interest in a directory, here, "/tmp" if( 0 != FAMMonitorDirectory( fc , toWatch , fr , NULL ) ){ std::cerr << "FAM connectivity test failed: unable to monitor \"" << toWatch << "\"" << std::endl ; checkStrerror( errno ) ; throw( ERROR_FAM_MONITOR ) ; } std::cout << "connectivity worked. fam properly configged" << std::endl; while (1) { while (1 == FAMNextEvent(fc, fe)) { std::cout << "\t" << fe->filename << std::endl; } } } virtual ~Fam() { // stop receiving events FAMCancelMonitor( fc , fr ) ; // disconnect from the FAM service FAMClose( fc ) ; delete( fr ) ; delete( fc ) ; } }; #endif
#include "Board.hpp" #include "doctest.h" #include <string> using namespace std; using namespace ariel; Board board; TEST_CASE("Empty Board") { CHECK(board.read(0, 0, Direction::Horizontal, 0) == ""); CHECK(board.read(0, 0, Direction::Horizontal, 1) == string("_")); CHECK(board.read(0, 0, Direction::Vertical, 1) == string("_")); CHECK(board.read(2, 2, Direction::Horizontal, 0) == ""); CHECK(board.read(2, 2, Direction::Vertical, 0) == string("")); CHECK(board.read(20,30, Direction::Vertical,1) == string("_")); } TEST_CASE("Horizontal case"){ board.post(0, 0, Direction::Horizontal,"king moshe"); CHECK(board.read(0, 0, Direction::Horizontal, 10) == string("king moshe")); CHECK(board.read(0, 1, Direction::Horizontal, 10) == string("ing moshe_")); CHECK(board.read(0, 2, Direction::Horizontal, 10) == string("ng moshe__")); CHECK(board.read(0, 3, Direction::Horizontal, 10) == string("g moshe___")); CHECK(board.read(0, 4, Direction::Horizontal, 10) == string(" moshe____")); CHECK(board.read(0, 5, Direction::Horizontal, 10) == string("moshe_____")); CHECK(board.read(0, 6, Direction::Horizontal, 10) == string("oshe______")); CHECK(board.read(0, 7, Direction::Horizontal, 10) == string("she_______")); CHECK(board.read(0, 8, Direction::Horizontal, 10) == string("he________")); CHECK(board.read(0, 9, Direction::Horizontal, 10) == string("e_________")); CHECK(board.read(0, 10, Direction::Horizontal, 10) == string("__________")); } TEST_CASE("Vertically case") { board.post(0, 0, Direction::Vertical,"king moshe"); CHECK(board.read(0, 0, Direction::Vertical, 10) == string("king moshe")); CHECK(board.read(1, 0, Direction::Vertical, 10) == string("ing moshe_")); CHECK(board.read(2, 0, Direction::Vertical, 10) == string("ng moshe__")); CHECK(board.read(3, 0, Direction::Vertical, 10) == string("g moshe___")); CHECK(board.read(4, 0, Direction::Vertical, 10) == string(" moshe____")); CHECK(board.read(5, 0, Direction::Vertical, 10) == string("moshe_____")); CHECK(board.read(6, 0, Direction::Vertical, 10) == string("oshe______")); CHECK(board.read(7, 0, Direction::Vertical, 10) == string("she_______")); CHECK(board.read(8, 0, Direction::Vertical, 10) == string("he________")); CHECK(board.read(9, 0, Direction::Vertical, 10) == string("e_________")); CHECK(board.read(10, 0,Direction::Vertical, 10) == string("__________")); }
/****************************************************************************** Copyright (c) 2021, Farbod Farshidian. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <gtest/gtest.h> #include <iostream> #include <ocs2_centroidal_model/AccessHelperFunctions.h> #include <ocs2_core/misc/LinearAlgebra.h> #include "ocs2_legged_robot/constraint/FrictionConeConstraint.h" #include "ocs2_legged_robot/test/AnymalFactoryFunctions.h" using namespace ocs2; using namespace legged_robot; class TestFrictionConeConstraint : public testing::Test { public: using Matrix6x = Eigen::Matrix<scalar_t, 6, Eigen::Dynamic>; TestFrictionConeConstraint() {} const CentroidalModelType centroidalModelType = CentroidalModelType::SingleRigidBodyDynamics; std::unique_ptr<PinocchioInterface> pinocchioInterfacePtr = createAnymalPinocchioInterface(); const CentroidalModelInfo centroidalModelInfo = createAnymalCentroidalModelInfo(*pinocchioInterfacePtr, centroidalModelType); const std::shared_ptr<SwitchedModelReferenceManager> referenceManagerPtr = createReferenceManager(centroidalModelInfo.numThreeDofContacts); PreComputation preComputation; }; TEST_F(TestFrictionConeConstraint, finiteDifference) { const FrictionConeConstraint::Config config; scalar_t t = 0.0; scalar_t eps = 1e-4; scalar_t tol = 1e-2; // tolerance on the Jacobian elements size_t N = 10000; for (size_t legNumber = 0; legNumber < centroidalModelInfo.numThreeDofContacts; ++legNumber) { FrictionConeConstraint frictionConeConstraint(*referenceManagerPtr, config, legNumber, centroidalModelInfo); vector_t u0 = 10.0 * vector_t::Random(centroidalModelInfo.inputDim); u0(2) = 100.0; u0(5) = 100.0; u0(8) = 100.0; u0(11) = 100.0; vector_t x0 = 0.1 * vector_t::Random(centroidalModelInfo.stateDim); const auto y0 = frictionConeConstraint.getValue(t, x0, u0, preComputation)(0); auto quadraticApproximation = frictionConeConstraint.getQuadraticApproximation(t, x0, u0, preComputation); vector_t data(N); matrix_t regressor(N, 6 + 6 + 6 + 9); vector_t dx = vector_t::Zero(centroidalModelInfo.stateDim); vector_t du = vector_t::Zero(centroidalModelInfo.inputDim); for (size_t i = 0; i < N; i++) { // evaluation point vector_t dEuler = eps * vector_t::Random(3); vector_t dF = eps * vector_t::Random(3); dx.segment<3>(0) = dEuler; du.segment<3>(3 * legNumber) = dF; vector_t dz(6); dz << dEuler, dF; const matrix_t quadTerms = dz * dz.transpose(); vector_t quadTermsVector(6 + 6 + 9); size_t count = 0; for (size_t p = 0; p < 6; ++p) { for (size_t q = p; q < 6; ++q) { quadTermsVector(count) = quadTerms(p, q); if (q == p) { quadTermsVector(count) *= 0.5; } count++; } } // Scale to condition the regressor regressor.row(i) << dEuler.transpose() / eps, dF.transpose() / eps, quadTermsVector.transpose() / (eps * eps); data(i) = (frictionConeConstraint.getValue(t, x0 + dx, u0 + du, preComputation)(0) - y0); } vector_t dh_emperical = regressor.colPivHouseholderQr().solve(data); dh_emperical /= eps; dh_emperical.tail<6 + 6 + 9>() /= eps; matrix_t quadTerms(6, 6); size_t count = 0; for (size_t p = 0; p < 6; ++p) { for (size_t q = p; q < 6; ++q) { quadTerms(p, q) = dh_emperical(6 + count); quadTerms(q, p) = quadTerms(p, q); count++; } } vector_t dhdx_emperical = dh_emperical.head<3>(); vector_t dhdu_emperical = dh_emperical.segment<3>(3); matrix_t ddhdxdx_emperical = quadTerms.block<3, 3>(0, 0); matrix_t ddhdudx_emperical = quadTerms.block<3, 3>(3, 0); matrix_t ddhdudu_emperical = quadTerms.block<3, 3>(3, 3); matrix_t ddhdudu = quadraticApproximation.dfduu.front().block<3, 3>(3 * legNumber, 3 * legNumber); matrix_t ddhdxdx = quadraticApproximation.dfdxx.front().block<3, 3>(0, 0); ASSERT_LT((dhdx_emperical - quadraticApproximation.dfdx.block<1, 3>(0, 0).transpose()).array().abs().maxCoeff(), tol); ASSERT_LT((dhdu_emperical - quadraticApproximation.dfdu.block<1, 3>(0, 3 * legNumber).transpose()).array().abs().maxCoeff(), tol); ASSERT_LT((ddhdudu_emperical - ddhdudu).array().abs().maxCoeff(), tol); // ddhdxdx and ddhdudx are off because of the negative definite hessian approximation } } TEST_F(TestFrictionConeConstraint, gravityAligned_flatTerrain) { // Check friction cone for the case where the body is aligned with the terrain const FrictionConeConstraint::Config config(0.7, 25.0, 0.0, 0.0); const auto mu = config.frictionCoefficient; const auto regularization = config.regularization; // evaluation point scalar_t t = 0.0; vector_t x = vector_t::Random(centroidalModelInfo.stateDim); vector_t u = vector_t::Random(centroidalModelInfo.inputDim); for (size_t legNumber = 0; legNumber < centroidalModelInfo.numThreeDofContacts; ++legNumber) { FrictionConeConstraint frictionConeConstraint(*referenceManagerPtr, config, legNumber, centroidalModelInfo); // Local forces are equal to the body forces. const vector_t F = centroidal_model::getContactForces(u, legNumber, centroidalModelInfo); const auto Fx = F(0); const auto Fy = F(1); const auto Fz = F(2); auto quadraticApproximation = frictionConeConstraint.getQuadraticApproximation(t, x, u, preComputation); ASSERT_DOUBLE_EQ(quadraticApproximation.f(0), Fz * sqrt(mu * mu) - sqrt(Fx * Fx + Fy * Fy + regularization)); // First derivative inputs vector_t dhdu = vector_t::Zero(centroidalModelInfo.inputDim); const auto F_norm = sqrt(Fx * Fx + Fy * Fy + regularization); dhdu(3 * legNumber + 0) = -Fx / F_norm; dhdu(3 * legNumber + 1) = -Fy / F_norm; dhdu(3 * legNumber + 2) = sqrt(mu * mu); ASSERT_LT((quadraticApproximation.dfdu.row(0).transpose() - dhdu).norm(), 1e-12); // Second derivative inputs matrix_t ddhdudu = matrix_t::Zero(centroidalModelInfo.inputDim, centroidalModelInfo.inputDim); const auto F_norm2 = Fx * Fx + Fy * Fy + regularization; const auto F_norm32 = pow(F_norm2, 1.5); ddhdudu(3 * legNumber + 0, 3 * legNumber + 0) = -(Fy * Fy + regularization) / F_norm32; ddhdudu(3 * legNumber + 0, 3 * legNumber + 1) = Fx * Fy / F_norm32; ddhdudu(3 * legNumber + 0, 3 * legNumber + 2) = 0.0; ddhdudu(3 * legNumber + 1, 3 * legNumber + 0) = Fx * Fy / F_norm32; ddhdudu(3 * legNumber + 1, 3 * legNumber + 1) = -(Fx * Fx + regularization) / F_norm32; ddhdudu(3 * legNumber + 1, 3 * legNumber + 2) = 0.0; ddhdudu(3 * legNumber + 2, 3 * legNumber + 0) = 0.0; ddhdudu(3 * legNumber + 2, 3 * legNumber + 1) = 0.0; ddhdudu(3 * legNumber + 2, 3 * legNumber + 2) = 0.0; ASSERT_LT((quadraticApproximation.dfduu.front() - ddhdudu).norm(), 1e-12); } } TEST_F(TestFrictionConeConstraint, negativeDefinite) { const FrictionConeConstraint::Config config; // evaluation point scalar_t t = 0.0; vector_t x = vector_t::Random(centroidalModelInfo.stateDim); vector_t u = vector_t::Random(centroidalModelInfo.inputDim); u(2) = 100.0; u(5) = 100.0; u(8) = 100.0; u(11) = 100.0; for (size_t legNumber = 0; legNumber < centroidalModelInfo.numThreeDofContacts; ++legNumber) { FrictionConeConstraint frictionConeConstraint(*referenceManagerPtr, config, legNumber, centroidalModelInfo); const auto quadraticApproximation = frictionConeConstraint.getQuadraticApproximation(t, x, u, preComputation); ASSERT_LT(LinearAlgebra::symmetricEigenvalues(quadraticApproximation.dfdxx.front()).maxCoeff(), 0.0); ASSERT_LT(LinearAlgebra::symmetricEigenvalues(quadraticApproximation.dfduu.front()).maxCoeff(), 0.0); } }
#pragma once #include "../ColliderPrimitive.hpp" namespace Engine5 { class ColliderPlane { public: ColliderPlane(); ~ColliderPlane(); ColliderPlane(const ColliderPlane& rhs) = delete; ColliderPlane& operator=(const ColliderPlane& rhs) = delete; void Initialize(); void Shutdown(); //minkowski support - gjk, epa Vector3 Support(const Vector3& direction); //ray - collider intersection bool TestRayIntersection(const Ray& local_ray, Real& minimum_t, Real& maximum_t) const; Vector3 GetNormal(const Vector3& local_point_on_collider) const; //physics void SetMassData(Real density); Real GetVolume(); //collider void UpdateBoundingVolume() const; void Draw(PrimitiveRenderer* renderer, eRenderingMode mode, const Color& color) const; private: Vector3 m_normal; BoundingAABB* m_bounding_volume = nullptr; }; }
#ifndef __NMC_TOOLS_HPP__ #define __NMC_TOOLS_HPP__ #include "NMC_numComp.hpp" #ifdef __FILE__ #ifdef __LINE__ #define NMC_DEF_GETFILELINE 1 #endif #endif #ifdef NMC_DEF_GETFILELINE #define NMC_GETFILELINE \ " on file: '" __FILE__ "' line: '" << __LINE__ << "' function: " << __func__ #else #define NMC_GETFILELINE "" #endif #define NMC_PREPRINT "numComp: " #define NMC_PRINTMEMERROR std::cerr << NMC_PREPRINT "Memory error" << NMC_GETFILELINE << "\n" #define NMC_PRINTERROR std::cerr << NMC_PREPRINT "Error" << NMC_GETFILELINE << "\n" #define NMC_PRINTERRORNUMBER(number) std::cerr << NMC_PREPRINT "Error " << number << NMC_GETFILELINE << "\n" #define NMC_PRINTCALLBACKERRORNUMBER(number) std::cerr << NMC_PREPRINT << "Callback function error " << number << NMC_GETFILELINE << "\n" #define NMC_PRINTERRORMSG(msg) std::cerr << NMC_PREPRINT << msg << NMC_GETFILELINE << "\n" #define NMC_PRINTERRORMSGP(msg, arg) std::cerr << NMC_PREPRINT << msg << arg << NMC_GETFILELINE << "\n" #define NMC_PRINTMSG(msg) std::cout << NMC_PREPRINT << msg; #define NMC_getchar() NMC_PRINTERRORMSG("stopped in a getchar"), getchar() namespace numcomp{ template <class myClass> inline myClass NMC_abs(const myClass &v) { return v >= 0 ? v : -v; } //evaluate f[a, b] inline double NMC_fbrack2(const NMC_PointR2 &a, const NMC_PointR2 &b) { return (b.y - a.y)/(b.x - a.x); } //evaluate f[a, b, d] inline double NMC_fbrack3(const NMC_PointR2 &a, const NMC_PointR2 &b, const NMC_PointR2 &d) { const double fab = NMC_fbrack2(a, b); const double fbd = NMC_fbrack2(b, d); return (fbd - fab)/(d.x - a.x); } //evaluate P(a, b, d)(x) inline double NMC_P(const NMC_PointR2 &a, const NMC_PointR2 &b, const NMC_PointR2 &d, double x) { const double fab = NMC_fbrack2(a, b); //const double fbd = _fbrack2(b, d); const double fabd = NMC_fbrack3(a, b, d); return a.y + fab*(x-a.x) + fabd*(x - a.x)*(x - b.x); } } #endif
// <Snippet1> #define _WINSOCKAPI_ #include <windows.h> #include <sal.h> #include <httpserv.h> // Create the module class. class MyHttpModule : public CHttpModule { public: REQUEST_NOTIFICATION_STATUS OnBeginRequest( IN IHttpContext * pHttpContext, IN IHttpEventProvider * pProvider ) { UNREFERENCED_PARAMETER( pProvider ); // Create an HRESULT to receive return values from methods. HRESULT hr; // Buffer to store the translated path. char* pszAppConfigPath; // Retrieve a pointer to the IHttpApplication class. IHttpApplication * pHttpApplication = pHttpContext->GetApplication(); // Retrieve a pointer to the application configuration path. PCWSTR pwszAppConfigPath = pHttpApplication->GetAppConfigPath(); // Test for an error. if (NULL != pwszAppConfigPath) { // Maximum path length size_t maxlen = 260; // Length of the returned path. DWORD cbAppConfigPath = (DWORD) wcsnlen(pwszAppConfigPath, maxlen); // Allocate space to store the path. pszAppConfigPath = (PSTR) pHttpContext->AllocateRequestMemory(cbAppConfigPath + 1); // Test for an error. if (pszAppConfigPath==NULL) { // Set the error status. hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); pProvider->SetErrorStatus( hr ); // End additional processing. return RQ_NOTIFICATION_FINISH_REQUEST; } // Convert the WCHAR string to a CHAR string. wcstombs(pszAppConfigPath,pwszAppConfigPath,cbAppConfigPath); // Clear the existing response. pHttpContext->GetResponse()->Clear(); // Set the MIME type to plain text. pHttpContext->GetResponse()->SetHeader( HttpHeaderContentType,"text/plain", (USHORT)strnlen("text/plain",10),TRUE); // Return the path information. WriteResponseMessage(pHttpContext, "Application configuration path: ",pszAppConfigPath); // End additional processing. return RQ_NOTIFICATION_FINISH_REQUEST; } // Return processing to the pipeline. return RQ_NOTIFICATION_CONTINUE; } private: // Create a utility method that inserts a name/value pair into the response. HRESULT WriteResponseMessage( IHttpContext * pHttpContext, PCSTR pszName, PCSTR pszValue ) { // Create an HRESULT to receive return values from methods. HRESULT hr; // Maximum data chunk length size_t maxlen = 10240; // Create a data chunk. HTTP_DATA_CHUNK dataChunk; // Set the chunk to a chunk in memory. dataChunk.DataChunkType = HttpDataChunkFromMemory; // Buffer for bytes written of data chunk. DWORD cbSent; // Set the chunk to the first buffer. dataChunk.FromMemory.pBuffer = (PVOID) pszName; // Set the chunk size to the first buffer size. dataChunk.FromMemory.BufferLength = (USHORT) strnlen(pszName,maxlen); // Insert the data chunk into the response. hr = pHttpContext->GetResponse()->WriteEntityChunks( &dataChunk,1,FALSE,TRUE,&cbSent); // Test for an error. if (FAILED(hr)) { // Return the error status. return hr; } // Set the chunk to the second buffer. dataChunk.FromMemory.pBuffer = (PVOID) pszValue; // Set the chunk size to the second buffer size. dataChunk.FromMemory.BufferLength = (USHORT) strnlen(pszValue,maxlen); // Insert the data chunk into the response. hr = pHttpContext->GetResponse()->WriteEntityChunks( &dataChunk,1,FALSE,TRUE,&cbSent); // Test for an error. if (FAILED(hr)) { // Return the error status. return hr; } // Return a success status. return S_OK; } }; // Create the module's class factory. class MyHttpModuleFactory : public IHttpModuleFactory { public: HRESULT GetHttpModule( OUT CHttpModule ** ppModule, IN IModuleAllocator * pAllocator ) { UNREFERENCED_PARAMETER( pAllocator ); // Create a new instance. MyHttpModule * pModule = new MyHttpModule; // Test for an error. if (!pModule) { // Return an error if the factory cannot create the instance. return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); } else { // Return a pointer to the module. *ppModule = pModule; pModule = NULL; // Return a success status. return S_OK; } } void Terminate() { // Remove the class from memory. delete this; } }; // Create the module's exported registration function. HRESULT __stdcall RegisterModule( DWORD dwServerVersion, IHttpModuleRegistrationInfo * pModuleInfo, IHttpServer * pGlobalInfo ) { UNREFERENCED_PARAMETER( dwServerVersion ); UNREFERENCED_PARAMETER( pGlobalInfo ); // Set the request notifications and exit. return pModuleInfo->SetRequestNotifications( new MyHttpModuleFactory, RQ_BEGIN_REQUEST, 0 ); } // </Snippet1>
/** * @file paramgen.cpp * * @brief Parameter generation utility for Zerocoin. * * @author Ian Miers, Christina Garman and Matthew Green * @date June 2013 * * @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green * @license This project is released under the MIT license. **/ // Copyright (c) 2017-2019 The BIOA3 developers #include <string> #include <iostream> #include <fstream> //#include <curses.h> #include <exception> #include "Zerocoin.h" #define DEFAULT_MODULUS_SIZE 3072 #define MIN_MODULUS_SIZE 1026 void PrintWarning() { cout << "Zerocoin parameter generation utility" << endl; cout << "-------------------------------------" << endl << endl; cout << "This utility generates an l-bit modulus N as the product of" << endl; cout << "two safe primes p, q. The values p and q are not stored." << endl; cout << "Call this program with no arguments to see usage options." << endl; cout << endl; cout << "SECURITY WARNING: ZEROCOIN PARAMETERS MUST BE GENERATED BY" << endl; cout << "A TRUSTED PARTY WHO DOES NOT STORE THE FACTORS. WHILE WE MAKE" << endl; cout << "A BEST EFFORT TO DESTROY THIS INFORMATION WE DO NOT TAKE" << endl; cout << "SPECIAL PRECAUTIONS TO ENSURE THAT THEY ARE DESTROYED." << endl; cout << endl; cout << "USE THIS UTILITY AT YOUR OWN RISK" << endl << endl; } void usage() { printf("Usage:\n"); printf(" -b <numbits>\n"); printf(" -o <output file>\n"); exit (8); } int main(int argc, char **argv) { static CBigNum resultModulus(0); uint32_t numBits = DEFAULT_MODULUS_SIZE; ofstream outfile; char* outfileName; bool writeToFile = false; while ((argc > 1) && (argv[1][0] == '-')) { switch (argv[1][1]) { case 'b': numBits = atoi(argv[2]); ++argv; --argc; break; case 'o': outfileName = argv[2]; writeToFile = true; break; case 'h': usage(); break; default: printf("Wrong Argument: %s\n", argv[1]); usage(); break; } ++argv; --argc; } if (numBits < MIN_MODULUS_SIZE) { cout << "Modulus is below minimum length (" << MIN_MODULUS_SIZE << ") bits" << endl; return(0); } PrintWarning(); cout << "Modulus size set to " << numBits << " bits." << endl; cout << "Generating parameters. This may take a few minutes..." << endl; // Generate two safe primes "p" and "q" CBigNum *p, *q; p = new CBigNum(0); q = new CBigNum(0); *p = CBigNum::generatePrime(numBits / 2, true); *q = CBigNum::generatePrime(numBits / 2, true); // Multiply to compute N resultModulus = (*p) * (*q); // Wipe out the factors delete p; delete q; // Convert to a hexidecimal string std::string resultHex = resultModulus.ToString(16); cout << endl << "N = " << endl << resultHex << endl; if (writeToFile) { try { outfile.open (outfileName); outfile << resultHex; outfile.close(); cout << endl << "Result has been written to file '" << outfileName << "'." << endl; } catch (const std::runtime_error& e) { cout << "Unable to write to file:" << e.what() << endl; } } }
// // TextureCacheScriptingInterface.cpp // libraries/mmodel-networking/src/model-networking // // Created by David Rowe on 25 Jul 2018. // Copyright 2018 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "TextureCacheScriptingInterface.h" TextureCacheScriptingInterface::TextureCacheScriptingInterface() : ScriptableResourceCache::ScriptableResourceCache(DependencyManager::get<TextureCache>()) { connect(DependencyManager::get<TextureCache>().data(), &TextureCache::spectatorCameraFramebufferReset, this, &TextureCacheScriptingInterface::spectatorCameraFramebufferReset); } ScriptableResource* TextureCacheScriptingInterface::prefetch(const QUrl& url, int type, int maxNumPixels) { return DependencyManager::get<TextureCache>()->prefetch(url, type, maxNumPixels); }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { private: ListNode* mergeTwoListsRecursive(ListNode* l1, ListNode* l2) { if (l1 == nullptr) return l2; else if (l2 == nullptr) return l1; if (l1->val < l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l1, l2->next); return l2; } } public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* dummyNode = new ListNode(); ListNode* ans = dummyNode; while (l1 != nullptr && l2 != nullptr) { if (l1->val < l2->val) { dummyNode->next = new ListNode(l1->val); l1 = l1->next; } else { dummyNode->next = new ListNode(l2->val); l2 = l2->next; } dummyNode = dummyNode->next; } if (l1 != nullptr) dummyNode->next = l1; if (l2 != nullptr) dummyNode->next = l2; return ans->next; } };
/* Copyright (C): 2020, UMI Academy modified by Ninh.D.H */ #include "pxt.h" #include <map> #include <vector> #include "ReceiverIR.h" using namespace pxt; typedef vector<Action> vA; enum class RemoteButton { CH_MINUS = 0x45, CH = 0x46, CH_Add = 0x47, PREV = 0x44, PLAY = 0x43, NUM_200 = 0xd, NEXT = 0x40, NUM_100 = 0x19, Minus = 0x7, Add = 0x15, EQ = 0x9, NUM0 = 0x16, NUM1 = 0xc, NUM2 = 0x18, NUM3 = 0x5e, NUM4 = 0x8, NUM5 = 0x1c, NUM6 = 0x5a, NUM7 = 0x42, NUM8 = 0x52, NUM9 = 0x4A }; enum class Pins{ P0= 3, P1= 2, P2= 1, P3= 4, P4= 5, P5= 17, P6= 12, P7= 11, P8= 18, P9= 10, P10= 6, P11= 26, P12= 20, P13= 23, P14= 22, P15= 21, P16= 16, P19= 0, P20= 30 }; namespace Mbit_IR { map<RemoteButton, vA> actions; map<RemoteButton, uint32_t> lastact; Timer tsb; uint8_t buf[32]; uint32_t now; ReceiverIR *rx; RemoteIR::Format fmt = RemoteIR::UNKNOWN; void cA(vA runner){for(int i=0;i<runner.size();i++){runAction0(runner[i]);} } void onReceivable(){ int x = rx->getData(&fmt, buf, 32 * 8); if(actions.find((RemoteButton)buf[2]) == actions.end()) return; now = tsb.read_ms(); if(now - lastact[(RemoteButton)buf[2]] < 100) return; lastact[(RemoteButton)buf[2]] = now; cA(actions[(RemoteButton)buf[2]]); } void monitorIR(){ while(1){ while(rx->getState() != ReceiverIR::Received){ uBit.sleep(50); } onReceivable(); } } //% void init(Pins pin){ rx = new ReceiverIR((PinName)pin); tsb.start(); //interrupt timer for debounce create_fiber(monitorIR); } //% void onPressEvent(RemoteButton btn, Action body) { actions[btn].push_back(body); } }
/* hyperloglog.c - Redis HyperLogLog probabilistic cardinality approximation. * This file implements the algorithm and the exported Redis commands. * * Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis 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. */ #include "hyperloglog.hpp" #include "sds.hpp" #include <assert.h> #include <stdint.h> #include <math.h> #include <stddef.h> #include <string.h> #include <stdlib.h> namespace guinsoodb_hll { #define HLL_SPARSE_MAX_BYTES 3000 /* The Redis HyperLogLog implementation is based on the following ideas: * * * The use of a 64 bit hash function as proposed in [1], in order to don't * limited to cardinalities up to 10^9, at the cost of just 1 additional * bit per register. * * The use of 16384 6-bit registers for a great level of accuracy, using * a total of 12k per key. * * The use of the Redis string data type. No new type is introduced. * * No attempt is made to compress the data structure as in [1]. Also the * algorithm used is the original HyperLogLog Algorithm as in [2], with * the only difference that a 64 bit hash function is used, so no correction * is performed for values near 2^32 as in [1]. * * [1] Heule, Nunkesser, Hall: HyperLogLog in Practice: Algorithmic * Engineering of a State of The Art Cardinality Estimation Algorithm. * * [2] P. Flajolet, Éric Fusy, O. Gandouet, and F. Meunier. Hyperloglog: The * analysis of a near-optimal cardinality estimation algorithm. * * Redis uses two representations: * * 1) A "dense" representation where every entry is represented by * a 6-bit integer. * 2) A "sparse" representation using run length compression suitable * for representing HyperLogLogs with many registers set to 0 in * a memory efficient way. * * * HLL header * === * * Both the dense and sparse representation have a 16 byte header as follows: * * +------+---+-----+----------+ * | HYLL | E | N/U | Cardin. | * +------+---+-----+----------+ * * The first 4 bytes are a magic string set to the bytes "HYLL". * "E" is one byte encoding, currently set to HLL_DENSE or * HLL_SPARSE. N/U are three not used bytes. * * The "Cardin." field is a 64 bit integer stored in little endian format * with the latest cardinality computed that can be reused if the data * structure was not modified since the last computation (this is useful * because there are high probabilities that HLLADD operations don't * modify the actual data structure and hence the approximated cardinality). * * When the most significant bit in the most significant byte of the cached * cardinality is set, it means that the data structure was modified and * we can't reuse the cached value that must be recomputed. * * Dense representation * === * * The dense representation used by Redis is the following: * * +--------+--------+--------+------// //--+ * |11000000|22221111|33333322|55444444 .... | * +--------+--------+--------+------// //--+ * * The 6 bits counters are encoded one after the other starting from the * LSB to the MSB, and using the next bytes as needed. * * Sparse representation * === * * The sparse representation encodes registers using a run length * encoding composed of three opcodes, two using one byte, and one using * of two bytes. The opcodes are called ZERO, XZERO and VAL. * * ZERO opcode is represented as 00xxxxxx. The 6-bit integer represented * by the six bits 'xxxxxx', plus 1, means that there are N registers set * to 0. This opcode can represent from 1 to 64 contiguous registers set * to the value of 0. * * XZERO opcode is represented by two bytes 01xxxxxx yyyyyyyy. The 14-bit * integer represented by the bits 'xxxxxx' as most significant bits and * 'yyyyyyyy' as least significant bits, plus 1, means that there are N * registers set to 0. This opcode can represent from 0 to 16384 contiguous * registers set to the value of 0. * * VAL opcode is represented as 1vvvvvxx. It contains a 5-bit integer * representing the value of a register, and a 2-bit integer representing * the number of contiguous registers set to that value 'vvvvv'. * To obtain the value and run length, the integers vvvvv and xx must be * incremented by one. This opcode can represent values from 1 to 32, * repeated from 1 to 4 times. * * The sparse representation can't represent registers with a value greater * than 32, however it is very unlikely that we find such a register in an * HLL with a cardinality where the sparse representation is still more * memory efficient than the dense representation. When this happens the * HLL is converted to the dense representation. * * The sparse representation is purely positional. For example a sparse * representation of an empty HLL is just: XZERO:16384. * * An HLL having only 3 non-zero registers at position 1000, 1020, 1021 * respectively set to 2, 3, 3, is represented by the following three * opcodes: * * XZERO:1000 (Registers 0-999 are set to 0) * VAL:2,1 (1 register set to value 2, that is register 1000) * ZERO:19 (Registers 1001-1019 set to 0) * VAL:3,2 (2 registers set to value 3, that is registers 1020,1021) * XZERO:15362 (Registers 1022-16383 set to 0) * * In the example the sparse representation used just 7 bytes instead * of 12k in order to represent the HLL registers. In general for low * cardinality there is a big win in terms of space efficiency, traded * with CPU time since the sparse representation is slower to access: * * The following table shows average cardinality vs bytes used, 100 * samples per cardinality (when the set was not representable because * of registers with too big value, the dense representation size was used * as a sample). * * 100 267 * 200 485 * 300 678 * 400 859 * 500 1033 * 600 1205 * 700 1375 * 800 1544 * 900 1713 * 1000 1882 * 2000 3480 * 3000 4879 * 4000 6089 * 5000 7138 * 6000 8042 * 7000 8823 * 8000 9500 * 9000 10088 * 10000 10591 * * The dense representation uses 12288 bytes, so there is a big win up to * a cardinality of ~2000-3000. For bigger cardinalities the constant times * involved in updating the sparse representation is not justified by the * memory savings. The exact maximum length of the sparse representation * when this implementation switches to the dense representation is * configured via the define server.hll_sparse_max_bytes. */ struct hllhdr { char magic[4]; /* "HYLL" */ uint8_t encoding; /* HLL_DENSE or HLL_SPARSE. */ uint8_t notused[3]; /* Reserved for future use, must be zero. */ uint8_t card[8]; /* Cached cardinality, little endian. */ uint8_t registers[1]; /* Data bytes. */ }; /* The cached cardinality MSB is used to signal validity of the cached value. */ #define HLL_INVALIDATE_CACHE(hdr) (hdr)->card[7] |= (1<<7) #define HLL_VALID_CACHE(hdr) (((hdr)->card[7] & (1<<7)) == 0) #define HLL_P 14 /* The greater is P, the smaller the error. */ #define HLL_Q (64-HLL_P) /* The number of bits of the hash value used for determining the number of leading zeros. */ #define HLL_REGISTERS (1<<HLL_P) /* With P=14, 16384 registers. */ #define HLL_P_MASK (HLL_REGISTERS-1) /* Mask to index register. */ #define HLL_BITS 6 /* Enough to count up to 63 leading zeroes. */ #define HLL_REGISTER_MAX ((1<<HLL_BITS)-1) #define HLL_HDR_SIZE sizeof(struct hllhdr) #define HLL_DENSE_SIZE (HLL_HDR_SIZE+((HLL_REGISTERS*HLL_BITS+7)/8)) #define HLL_DENSE 0 /* Dense encoding. */ #define HLL_SPARSE 1 /* Sparse encoding. */ #define HLL_RAW 255 /* Only used internally, never exposed. */ #define HLL_MAX_ENCODING 1 /* =========================== Low level bit macros ========================= */ /* Macros to access the dense representation. * * We need to get and set 6 bit counters in an array of 8 bit bytes. * We use macros to make sure the code is inlined since speed is critical * especially in order to compute the approximated cardinality in * HLLCOUNT where we need to access all the registers at once. * For the same reason we also want to avoid conditionals in this code path. * * +--------+--------+--------+------// * |11000000|22221111|33333322|55444444 * +--------+--------+--------+------// * * Note: in the above representation the most significant bit (MSB) * of every byte is on the left. We start using bits from the LSB to MSB, * and so forth passing to the next byte. * * Example, we want to access to counter at pos = 1 ("111111" in the * illustration above). * * The index of the first byte b0 containing our data is: * * b0 = 6 * pos / 8 = 0 * * +--------+ * |11000000| <- Our byte at b0 * +--------+ * * The position of the first bit (counting from the LSB = 0) in the byte * is given by: * * fb = 6 * pos % 8 -> 6 * * Right shift b0 of 'fb' bits. * * +--------+ * |11000000| <- Initial value of b0 * |00000011| <- After right shift of 6 pos. * +--------+ * * Left shift b1 of bits 8-fb bits (2 bits) * * +--------+ * |22221111| <- Initial value of b1 * |22111100| <- After left shift of 2 bits. * +--------+ * * OR the two bits, and finally AND with 111111 (63 in decimal) to * clean the higher order bits we are not interested in: * * +--------+ * |00000011| <- b0 right shifted * |22111100| <- b1 left shifted * |22111111| <- b0 OR b1 * | 111111| <- (b0 OR b1) AND 63, our value. * +--------+ * * We can try with a different example, like pos = 0. In this case * the 6-bit counter is actually contained in a single byte. * * b0 = 6 * pos / 8 = 0 * * +--------+ * |11000000| <- Our byte at b0 * +--------+ * * fb = 6 * pos % 8 = 0 * * So we right shift of 0 bits (no shift in practice) and * left shift the next byte of 8 bits, even if we don't use it, * but this has the effect of clearing the bits so the result * will not be affacted after the OR. * * ------------------------------------------------------------------------- * * Setting the register is a bit more complex, let's assume that 'val' * is the value we want to set, already in the right range. * * We need two steps, in one we need to clear the bits, and in the other * we need to bitwise-OR the new bits. * * Let's try with 'pos' = 1, so our first byte at 'b' is 0, * * "fb" is 6 in this case. * * +--------+ * |11000000| <- Our byte at b0 * +--------+ * * To create a AND-mask to clear the bits about this position, we just * initialize the mask with the value 63, left shift it of "fs" bits, * and finally invert the result. * * +--------+ * |00111111| <- "mask" starts at 63 * |11000000| <- "mask" after left shift of "ls" bits. * |00111111| <- "mask" after invert. * +--------+ * * Now we can bitwise-AND the byte at "b" with the mask, and bitwise-OR * it with "val" left-shifted of "ls" bits to set the new bits. * * Now let's focus on the next byte b1: * * +--------+ * |22221111| <- Initial value of b1 * +--------+ * * To build the AND mask we start again with the 63 value, right shift * it by 8-fb bits, and invert it. * * +--------+ * |00111111| <- "mask" set at 2&6-1 * |00001111| <- "mask" after the right shift by 8-fb = 2 bits * |11110000| <- "mask" after bitwise not. * +--------+ * * Now we can mask it with b+1 to clear the old bits, and bitwise-OR * with "val" left-shifted by "rs" bits to set the new value. */ /* Note: if we access the last counter, we will also access the b+1 byte * that is out of the array, but sds strings always have an implicit null * term, so the byte exists, and we can skip the conditional (or the need * to allocate 1 byte more explicitly). */ /* Store the value of the register at position 'regnum' into variable 'target'. * 'p' is an array of unsigned bytes. */ #define HLL_DENSE_GET_REGISTER(target,p,regnum) do { \ uint8_t *_p = (uint8_t*) p; \ unsigned long _byte = regnum*HLL_BITS/8; \ unsigned long _fb = regnum*HLL_BITS&7; \ unsigned long _fb8 = 8 - _fb; \ unsigned long b0 = _p[_byte]; \ unsigned long b1 = _p[_byte+1]; \ target = ((b0 >> _fb) | (b1 << _fb8)) & HLL_REGISTER_MAX; \ } while(0) /* Set the value of the register at position 'regnum' to 'val'. * 'p' is an array of unsigned bytes. */ #define HLL_DENSE_SET_REGISTER(p,regnum,val) do { \ uint8_t *_p = (uint8_t*) p; \ unsigned long _byte = regnum*HLL_BITS/8; \ unsigned long _fb = regnum*HLL_BITS&7; \ unsigned long _fb8 = 8 - _fb; \ unsigned long _v = val; \ _p[_byte] &= ~(HLL_REGISTER_MAX << _fb); \ _p[_byte] |= _v << _fb; \ _p[_byte+1] &= ~(HLL_REGISTER_MAX >> _fb8); \ _p[_byte+1] |= _v >> _fb8; \ } while(0) /* Macros to access the sparse representation. * The macros parameter is expected to be an uint8_t pointer. */ #define HLL_SPARSE_XZERO_BIT 0x40 /* 01xxxxxx */ #define HLL_SPARSE_VAL_BIT 0x80 /* 1vvvvvxx */ #define HLL_SPARSE_IS_ZERO(p) (((*(p)) & 0xc0) == 0) /* 00xxxxxx */ #define HLL_SPARSE_IS_XZERO(p) (((*(p)) & 0xc0) == HLL_SPARSE_XZERO_BIT) #define HLL_SPARSE_IS_VAL(p) ((*(p)) & HLL_SPARSE_VAL_BIT) #define HLL_SPARSE_ZERO_LEN(p) (((*(p)) & 0x3f)+1) #define HLL_SPARSE_XZERO_LEN(p) (((((*(p)) & 0x3f) << 8) | (*((p)+1)))+1) #define HLL_SPARSE_VAL_VALUE(p) ((((*(p)) >> 2) & 0x1f)+1) #define HLL_SPARSE_VAL_LEN(p) (((*(p)) & 0x3)+1) #define HLL_SPARSE_VAL_MAX_VALUE 32 #define HLL_SPARSE_VAL_MAX_LEN 4 #define HLL_SPARSE_ZERO_MAX_LEN 64 #define HLL_SPARSE_XZERO_MAX_LEN 16384 #define HLL_SPARSE_VAL_SET(p,val,len) do { \ *(p) = (((val)-1)<<2|((len)-1))|HLL_SPARSE_VAL_BIT; \ } while(0) #define HLL_SPARSE_ZERO_SET(p,len) do { \ *(p) = (len)-1; \ } while(0) #define HLL_SPARSE_XZERO_SET(p,len) do { \ int _l = (len)-1; \ *(p) = (_l>>8) | HLL_SPARSE_XZERO_BIT; \ *((p)+1) = (_l&0xff); \ } while(0) #define HLL_ALPHA_INF 0.721347520444481703680 /* constant for 0.5/ln(2) */ /* ========================= HyperLogLog algorithm ========================= */ /* Our hash function is MurmurHash2, 64 bit version. * It was modified for Redis in order to provide the same result in * big and little endian archs (endian neutral). */ uint64_t MurmurHash64A (const void * key, int len, unsigned int seed) { const uint64_t m = 0xc6a4a7935bd1e995; const int r = 47; uint64_t h = seed ^ (len * m); const uint8_t *data = (const uint8_t *)key; const uint8_t *end = data + (len-(len&7)); while(data != end) { uint64_t k; #if (BYTE_ORDER == LITTLE_ENDIAN) #ifdef USE_ALIGNED_ACCESS memcpy(&k,data,sizeof(uint64_t)); #else k = *((uint64_t*)data); #endif #else k = (uint64_t) data[0]; k |= (uint64_t) data[1] << 8; k |= (uint64_t) data[2] << 16; k |= (uint64_t) data[3] << 24; k |= (uint64_t) data[4] << 32; k |= (uint64_t) data[5] << 40; k |= (uint64_t) data[6] << 48; k |= (uint64_t) data[7] << 56; #endif k *= m; k ^= k >> r; k *= m; h ^= k; h *= m; data += 8; } switch(len & 7) { case 7: h ^= (uint64_t)data[6] << 48; /* fall-thru */ case 6: h ^= (uint64_t)data[5] << 40; /* fall-thru */ case 5: h ^= (uint64_t)data[4] << 32; /* fall-thru */ case 4: h ^= (uint64_t)data[3] << 24; /* fall-thru */ case 3: h ^= (uint64_t)data[2] << 16; /* fall-thru */ case 2: h ^= (uint64_t)data[1] << 8; /* fall-thru */ case 1: h ^= (uint64_t)data[0]; h *= m; /* fall-thru */ }; h ^= h >> r; h *= m; h ^= h >> r; return h; } /* Given a string element to add to the HyperLogLog, returns the length * of the pattern 000..1 of the element hash. As a side effect 'regp' is * set to the register index this element hashes to. */ int hllPatLen(unsigned char *ele, size_t elesize, long *regp) { uint64_t hash, bit, index; int count; /* Count the number of zeroes starting from bit HLL_REGISTERS * (that is a power of two corresponding to the first bit we don't use * as index). The max run can be 64-P+1 = Q+1 bits. * * Note that the final "1" ending the sequence of zeroes must be * included in the count, so if we find "001" the count is 3, and * the smallest count possible is no zeroes at all, just a 1 bit * at the first position, that is a count of 1. * * This may sound like inefficient, but actually in the average case * there are high probabilities to find a 1 after a few iterations. */ hash = MurmurHash64A(ele,elesize,0xadc83b19ULL); index = hash & HLL_P_MASK; /* Register index. */ hash >>= HLL_P; /* Remove bits used to address the register. */ hash |= ((uint64_t)1<<HLL_Q); /* Make sure the loop terminates and count will be <= Q+1. */ bit = 1; count = 1; /* Initialized to 1 since we count the "00000...1" pattern. */ while((hash & bit) == 0) { count++; bit <<= 1; } *regp = (int) index; return count; } /* ================== Dense representation implementation ================== */ /* Low level function to set the dense HLL register at 'index' to the * specified value if the current value is smaller than 'count'. * * 'registers' is expected to have room for HLL_REGISTERS plus an * additional byte on the right. This requirement is met by sds strings * automatically since they are implicitly null terminated. * * The function always succeed, however if as a result of the operation * the approximated cardinality changed, 1 is returned. Otherwise 0 * is returned. */ int hllDenseSet(uint8_t *registers, long index, uint8_t count) { uint8_t oldcount; HLL_DENSE_GET_REGISTER(oldcount,registers,index); if (count > oldcount) { HLL_DENSE_SET_REGISTER(registers,index,count); return 1; } else { return 0; } } /* "Add" the element in the dense hyperloglog data structure. * Actually nothing is added, but the max 0 pattern counter of the subset * the element belongs to is incremented if needed. * * This is just a wrapper to hllDenseSet(), performing the hashing of the * element in order to retrieve the index and zero-run count. */ int hllDenseAdd(uint8_t *registers, unsigned char *ele, size_t elesize) { long index; uint8_t count = hllPatLen(ele,elesize,&index); /* Update the register if this element produced a longer run of zeroes. */ return hllDenseSet(registers,index,count); } /* Compute the register histogram in the dense representation. */ void hllDenseRegHisto(uint8_t *registers, int* reghisto) { int j; /* Redis default is to use 16384 registers 6 bits each. The code works * with other values by modifying the defines, but for our target value * we take a faster path with unrolled loops. */ if (HLL_REGISTERS == 16384 && HLL_BITS == 6) { uint8_t *r = registers; unsigned long r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15; for (j = 0; j < 1024; j++) { /* Handle 16 registers per iteration. */ r0 = r[0] & 63; r1 = (r[0] >> 6 | r[1] << 2) & 63; r2 = (r[1] >> 4 | r[2] << 4) & 63; r3 = (r[2] >> 2) & 63; r4 = r[3] & 63; r5 = (r[3] >> 6 | r[4] << 2) & 63; r6 = (r[4] >> 4 | r[5] << 4) & 63; r7 = (r[5] >> 2) & 63; r8 = r[6] & 63; r9 = (r[6] >> 6 | r[7] << 2) & 63; r10 = (r[7] >> 4 | r[8] << 4) & 63; r11 = (r[8] >> 2) & 63; r12 = r[9] & 63; r13 = (r[9] >> 6 | r[10] << 2) & 63; r14 = (r[10] >> 4 | r[11] << 4) & 63; r15 = (r[11] >> 2) & 63; reghisto[r0]++; reghisto[r1]++; reghisto[r2]++; reghisto[r3]++; reghisto[r4]++; reghisto[r5]++; reghisto[r6]++; reghisto[r7]++; reghisto[r8]++; reghisto[r9]++; reghisto[r10]++; reghisto[r11]++; reghisto[r12]++; reghisto[r13]++; reghisto[r14]++; reghisto[r15]++; r += 12; } } else { for(j = 0; j < HLL_REGISTERS; j++) { unsigned long reg; HLL_DENSE_GET_REGISTER(reg,registers,j); reghisto[reg]++; } } } /* ================== Sparse representation implementation ================= */ /* Convert the HLL with sparse representation given as input in its dense * representation. Both representations are represented by SDS strings, and * the input representation is freed as a side effect. * * The function returns C_OK if the sparse representation was valid, * otherwise C_ERR is returned if the representation was corrupted. */ int hllSparseToDense(robj *o) { sds sparse = (sds) o->ptr, dense; struct hllhdr *hdr, *oldhdr = (struct hllhdr*)sparse; int idx = 0, runlen, regval; uint8_t *p = (uint8_t*)sparse, *end = p+sdslen(sparse); /* If the representation is already the right one return ASAP. */ hdr = (struct hllhdr*) sparse; if (hdr->encoding == HLL_DENSE) return HLL_C_OK; /* Create a string of the right size filled with zero bytes. * Note that the cached cardinality is set to 0 as a side effect * that is exactly the cardinality of an empty HLL. */ dense = sdsnewlen(NULL,HLL_DENSE_SIZE); hdr = (struct hllhdr*) dense; *hdr = *oldhdr; /* This will copy the magic and cached cardinality. */ hdr->encoding = HLL_DENSE; /* Now read the sparse representation and set non-zero registers * accordingly. */ p += HLL_HDR_SIZE; while(p < end) { if (HLL_SPARSE_IS_ZERO(p)) { runlen = HLL_SPARSE_ZERO_LEN(p); idx += runlen; p++; } else if (HLL_SPARSE_IS_XZERO(p)) { runlen = HLL_SPARSE_XZERO_LEN(p); idx += runlen; p += 2; } else { runlen = HLL_SPARSE_VAL_LEN(p); regval = HLL_SPARSE_VAL_VALUE(p); while(runlen--) { HLL_DENSE_SET_REGISTER(hdr->registers + 1,idx,regval); idx++; } p++; } } /* If the sparse representation was valid, we expect to find idx * set to HLL_REGISTERS. */ if (idx != HLL_REGISTERS) { sdsfree(dense); return HLL_C_ERR; } /* Free the old representation and set the new one. */ sdsfree((sds) o->ptr); o->ptr = dense; return HLL_C_OK; } /* Low level function to set the sparse HLL register at 'index' to the * specified value if the current value is smaller than 'count'. * * The object 'o' is the String object holding the HLL. The function requires * a reference to the object in order to be able to enlarge the string if * needed. * * On success, the function returns 1 if the cardinality changed, or 0 * if the register for this element was not updated. * On error (if the representation is invalid) -1 is returned. * * As a side effect the function may promote the HLL representation from * sparse to dense: this happens when a register requires to be set to a value * not representable with the sparse representation, or when the resulting * size would be greater than server.hll_sparse_max_bytes. */ int hllSparseSet(robj *o, long index, uint8_t count) { struct hllhdr *hdr; uint8_t oldcount, *sparse, *end, *p, *prev, *next; long first, span; long is_zero = 0, is_xzero = 0, is_val = 0, runlen = 0; uint8_t seq[5], *n; int last; int len; int seqlen; int oldlen; int deltalen; /* If the count is too big to be representable by the sparse representation * switch to dense representation. */ if (count > HLL_SPARSE_VAL_MAX_VALUE) goto promote; /* When updating a sparse representation, sometimes we may need to * enlarge the buffer for up to 3 bytes in the worst case (XZERO split * into XZERO-VAL-XZERO). Make sure there is enough space right now * so that the pointers we take during the execution of the function * will be valid all the time. */ o->ptr = (sds) sdsMakeRoomFor((sds) o->ptr,3); /* Step 1: we need to locate the opcode we need to modify to check * if a value update is actually needed. */ sparse = p = ((uint8_t*)o->ptr) + HLL_HDR_SIZE; end = p + sdslen((sds) o->ptr) - HLL_HDR_SIZE; first = 0; prev = NULL; /* Points to previous opcode at the end of the loop. */ next = NULL; /* Points to the next opcode at the end of the loop. */ span = 0; while(p < end) { long oplen; /* Set span to the number of registers covered by this opcode. * * This is the most performance critical loop of the sparse * representation. Sorting the conditionals from the most to the * least frequent opcode in many-bytes sparse HLLs is faster. */ oplen = 1; if (HLL_SPARSE_IS_ZERO(p)) { span = HLL_SPARSE_ZERO_LEN(p); } else if (HLL_SPARSE_IS_VAL(p)) { span = HLL_SPARSE_VAL_LEN(p); } else { /* XZERO. */ span = HLL_SPARSE_XZERO_LEN(p); oplen = 2; } /* Break if this opcode covers the register as 'index'. */ if (index <= first+span-1) break; prev = p; p += oplen; first += span; } if (span == 0) return -1; /* Invalid format. */ next = HLL_SPARSE_IS_XZERO(p) ? p+2 : p+1; if (next >= end) next = NULL; /* Cache current opcode type to avoid using the macro again and * again for something that will not change. * Also cache the run-length of the opcode. */ if (HLL_SPARSE_IS_ZERO(p)) { is_zero = 1; runlen = HLL_SPARSE_ZERO_LEN(p); } else if (HLL_SPARSE_IS_XZERO(p)) { is_xzero = 1; runlen = HLL_SPARSE_XZERO_LEN(p); } else { is_val = 1; runlen = HLL_SPARSE_VAL_LEN(p); } /* Step 2: After the loop: * * 'first' stores to the index of the first register covered * by the current opcode, which is pointed by 'p'. * * 'next' ad 'prev' store respectively the next and previous opcode, * or NULL if the opcode at 'p' is respectively the last or first. * * 'span' is set to the number of registers covered by the current * opcode. * * There are different cases in order to update the data structure * in place without generating it from scratch: * * A) If it is a VAL opcode already set to a value >= our 'count' * no update is needed, regardless of the VAL run-length field. * In this case PFADD returns 0 since no changes are performed. * * B) If it is a VAL opcode with len = 1 (representing only our * register) and the value is less than 'count', we just update it * since this is a trivial case. */ if (is_val) { oldcount = HLL_SPARSE_VAL_VALUE(p); /* Case A. */ if (oldcount >= count) return 0; /* Case B. */ if (runlen == 1) { HLL_SPARSE_VAL_SET(p,count,1); goto updated; } } /* C) Another trivial to handle case is a ZERO opcode with a len of 1. * We can just replace it with a VAL opcode with our value and len of 1. */ if (is_zero && runlen == 1) { HLL_SPARSE_VAL_SET(p,count,1); goto updated; } /* D) General case. * * The other cases are more complex: our register requires to be updated * and is either currently represented by a VAL opcode with len > 1, * by a ZERO opcode with len > 1, or by an XZERO opcode. * * In those cases the original opcode must be split into multiple * opcodes. The worst case is an XZERO split in the middle resuling into * XZERO - VAL - XZERO, so the resulting sequence max length is * 5 bytes. * * We perform the split writing the new sequence into the 'new' buffer * with 'newlen' as length. Later the new sequence is inserted in place * of the old one, possibly moving what is on the right a few bytes * if the new sequence is longer than the older one. */ n = seq; last = first+span-1; /* Last register covered by the sequence. */ if (is_zero || is_xzero) { /* Handle splitting of ZERO / XZERO. */ if (index != first) { len = index-first; if (len > HLL_SPARSE_ZERO_MAX_LEN) { HLL_SPARSE_XZERO_SET(n,len); n += 2; } else { HLL_SPARSE_ZERO_SET(n,len); n++; } } HLL_SPARSE_VAL_SET(n,count,1); n++; if (index != last) { len = last-index; if (len > HLL_SPARSE_ZERO_MAX_LEN) { HLL_SPARSE_XZERO_SET(n,len); n += 2; } else { HLL_SPARSE_ZERO_SET(n,len); n++; } } } else { /* Handle splitting of VAL. */ int curval = HLL_SPARSE_VAL_VALUE(p); if (index != first) { len = index-first; HLL_SPARSE_VAL_SET(n,curval,len); n++; } HLL_SPARSE_VAL_SET(n,count,1); n++; if (index != last) { len = last-index; HLL_SPARSE_VAL_SET(n,curval,len); n++; } } /* Step 3: substitute the new sequence with the old one. * * Note that we already allocated space on the sds string * calling sdsMakeRoomFor(). */ seqlen = n-seq; oldlen = is_xzero ? 2 : 1; deltalen = seqlen-oldlen; if (deltalen > 0 && sdslen((sds) o->ptr)+deltalen > HLL_SPARSE_MAX_BYTES) goto promote; if (deltalen && next) memmove(next+deltalen,next,end-next); sdsIncrLen((sds) o->ptr,deltalen); memcpy(p,seq,seqlen); end += deltalen; updated: { /* Step 4: Merge adjacent values if possible. * * The representation was updated, however the resulting representation * may not be optimal: adjacent VAL opcodes can sometimes be merged into * a single one. */ p = prev ? prev : sparse; int scanlen = 5; /* Scan up to 5 upcodes starting from prev. */ while (p < end && scanlen--) { if (HLL_SPARSE_IS_XZERO(p)) { p += 2; continue; } else if (HLL_SPARSE_IS_ZERO(p)) { p++; continue; } /* We need two adjacent VAL opcodes to try a merge, having * the same value, and a len that fits the VAL opcode max len. */ if (p+1 < end && HLL_SPARSE_IS_VAL(p+1)) { int v1 = HLL_SPARSE_VAL_VALUE(p); int v2 = HLL_SPARSE_VAL_VALUE(p+1); if (v1 == v2) { int len = HLL_SPARSE_VAL_LEN(p)+HLL_SPARSE_VAL_LEN(p+1); if (len <= HLL_SPARSE_VAL_MAX_LEN) { HLL_SPARSE_VAL_SET(p+1,v1,len); memmove(p,p+1,end-p); sdsIncrLen((sds) o->ptr,-1); end--; /* After a merge we reiterate without incrementing 'p' * in order to try to merge the just merged value with * a value on its right. */ continue; } } } p++; } /* Invalidate the cached cardinality. */ hdr = (struct hllhdr *) o->ptr; HLL_INVALIDATE_CACHE(hdr); return 1; } promote: /* Promote to dense representation. */ if (hllSparseToDense(o) == HLL_C_ERR) return -1; /* Corrupted HLL. */ hdr = (struct hllhdr *) o->ptr; /* We need to call hllDenseAdd() to perform the operation after the * conversion. However the result must be 1, since if we need to * convert from sparse to dense a register requires to be updated. * * Note that this in turn means that PFADD will make sure the command * is propagated to slaves / AOF, so if there is a sparse -> dense * conversion, it will be performed in all the slaves as well. */ int dense_retval = hllDenseSet(hdr->registers + 1,index,count); assert(dense_retval == 1); return dense_retval; } /* "Add" the element in the sparse hyperloglog data structure. * Actually nothing is added, but the max 0 pattern counter of the subset * the element belongs to is incremented if needed. * * This function is actually a wrapper for hllSparseSet(), it only performs * the hashshing of the elmenet to obtain the index and zeros run length. */ int hllSparseAdd(robj *o, unsigned char *ele, size_t elesize) { long index; uint8_t count = hllPatLen(ele,elesize,&index); /* Update the register if this element produced a longer run of zeroes. */ return hllSparseSet(o,index,count); } /* Compute the register histogram in the sparse representation. */ void hllSparseRegHisto(uint8_t *sparse, int sparselen, int *invalid, int* reghisto) { int idx = 0, runlen, regval; uint8_t *end = sparse+sparselen, *p = sparse; while(p < end) { if (HLL_SPARSE_IS_ZERO(p)) { runlen = HLL_SPARSE_ZERO_LEN(p); idx += runlen; reghisto[0] += runlen; p++; } else if (HLL_SPARSE_IS_XZERO(p)) { runlen = HLL_SPARSE_XZERO_LEN(p); idx += runlen; reghisto[0] += runlen; p += 2; } else { runlen = HLL_SPARSE_VAL_LEN(p); regval = HLL_SPARSE_VAL_VALUE(p); idx += runlen; reghisto[regval] += runlen; p++; } } if (idx != HLL_REGISTERS && invalid) *invalid = 1; } /* ========================= HyperLogLog Count ============================== * This is the core of the algorithm where the approximated count is computed. * The function uses the lower level hllDenseRegHisto() and hllSparseRegHisto() * functions as helpers to compute histogram of register values part of the * computation, which is representation-specific, while all the rest is common. */ /* Implements the register histogram calculation for uint8_t data type * which is only used internally as speedup for PFCOUNT with multiple keys. */ void hllRawRegHisto(uint8_t *registers, int* reghisto) { uint64_t *word = (uint64_t*) registers; uint8_t *bytes; int j; for (j = 0; j < HLL_REGISTERS/8; j++) { if (*word == 0) { reghisto[0] += 8; } else { bytes = (uint8_t*) word; reghisto[bytes[0]]++; reghisto[bytes[1]]++; reghisto[bytes[2]]++; reghisto[bytes[3]]++; reghisto[bytes[4]]++; reghisto[bytes[5]]++; reghisto[bytes[6]]++; reghisto[bytes[7]]++; } word++; } } // somehow this is missing on some platforms #ifndef INFINITY // from math.h #define INFINITY 1e50f #endif /* Helper function sigma as defined in * "New cardinality estimation algorithms for HyperLogLog sketches" * Otmar Ertl, arXiv:1702.01284 */ double hllSigma(double x) { if (x == 1.) return INFINITY; double zPrime; double y = 1; double z = x; do { x *= x; zPrime = z; z += x * y; y += y; } while(zPrime != z); return z; } /* Helper function tau as defined in * "New cardinality estimation algorithms for HyperLogLog sketches" * Otmar Ertl, arXiv:1702.01284 */ double hllTau(double x) { if (x == 0. || x == 1.) return 0.; double zPrime; double y = 1.0; double z = 1 - x; do { x = sqrt(x); zPrime = z; y *= 0.5; z -= pow(1 - x, 2)*y; } while(zPrime != z); return z / 3; } /* Return the approximated cardinality of the set based on the harmonic * mean of the registers values. 'hdr' points to the start of the SDS * representing the String object holding the HLL representation. * * If the sparse representation of the HLL object is not valid, the integer * pointed by 'invalid' is set to non-zero, otherwise it is left untouched. * * hllCount() supports a special internal-only encoding of HLL_RAW, that * is, hdr->registers will point to an uint8_t array of HLL_REGISTERS element. * This is useful in order to speedup PFCOUNT when called against multiple * keys (no need to work with 6-bit integers encoding). */ uint64_t hllCount(struct hllhdr *hdr, int *invalid) { double m = HLL_REGISTERS; double E; int j; int reghisto[HLL_Q+2] = {0}; /* Compute register histogram */ if (hdr->encoding == HLL_DENSE) { hllDenseRegHisto(hdr->registers + 1,reghisto); } else if (hdr->encoding == HLL_SPARSE) { hllSparseRegHisto(hdr->registers + 1, sdslen((sds)hdr)-HLL_HDR_SIZE,invalid,reghisto); } else if (hdr->encoding == HLL_RAW) { hllRawRegHisto(hdr->registers + 1,reghisto); } else { *invalid = 1; return 0; //serverPanic("Unknown HyperLogLog encoding in hllCount()"); } /* Estimate cardinality form register histogram. See: * "New cardinality estimation algorithms for HyperLogLog sketches" * Otmar Ertl, arXiv:1702.01284 */ double z = m * hllTau((m-reghisto[HLL_Q+1])/(double)m); for (j = HLL_Q; j >= 1; --j) { z += reghisto[j]; z *= 0.5; } z += m * hllSigma(reghisto[0]/(double)m); E = llroundl(HLL_ALPHA_INF*m*m/z); return (uint64_t) E; } /* Call hllDenseAdd() or hllSparseAdd() according to the HLL encoding. */ int hll_add(robj *o, unsigned char *ele, size_t elesize) { struct hllhdr *hdr = (struct hllhdr *) o->ptr; switch(hdr->encoding) { case HLL_DENSE: return hllDenseAdd(hdr->registers + 1,ele,elesize); case HLL_SPARSE: return hllSparseAdd(o,ele,elesize); default: return -1; /* Invalid representation. */ } } /* Merge by computing MAX(registers[i],hll[i]) the HyperLogLog 'hll' * with an array of uint8_t HLL_REGISTERS registers pointed by 'max'. * * The hll object must be already validated via isHLLObjectOrReply() * or in some other way. * * If the HyperLogLog is sparse and is found to be invalid, C_ERR * is returned, otherwise the function always succeeds. */ int hllMerge(uint8_t *max, robj *hll) { struct hllhdr *hdr = (struct hllhdr *) hll->ptr; int i; if (hdr->encoding == HLL_DENSE) { uint8_t val; for (i = 0; i < HLL_REGISTERS; i++) { HLL_DENSE_GET_REGISTER(val,hdr->registers + 1,i); if (val > max[i]) max[i] = val; } } else { uint8_t *p = (uint8_t *) hll->ptr, *end = p + sdslen((sds) hll->ptr); long runlen, regval; p += HLL_HDR_SIZE; i = 0; while(p < end) { if (HLL_SPARSE_IS_ZERO(p)) { runlen = HLL_SPARSE_ZERO_LEN(p); i += runlen; p++; } else if (HLL_SPARSE_IS_XZERO(p)) { runlen = HLL_SPARSE_XZERO_LEN(p); i += runlen; p += 2; } else { runlen = HLL_SPARSE_VAL_LEN(p); regval = HLL_SPARSE_VAL_VALUE(p); while(runlen--) { if (regval > max[i]) max[i] = regval; i++; } p++; } } if (i != HLL_REGISTERS) return HLL_C_ERR; } return HLL_C_OK; } /* ========================== robj creation ========================== */ robj *createObject(void *ptr) { robj *result = (robj*) malloc(sizeof(robj)); result->ptr = ptr; return result; } void destroyObject(robj *obj) { free(obj); } /* ========================== HyperLogLog commands ========================== */ /* Create an HLL object. We always create the HLL using sparse encoding. * This will be upgraded to the dense representation as needed. */ robj *hll_create(void) { robj *o; struct hllhdr *hdr; sds s; uint8_t *p; int sparselen = HLL_HDR_SIZE + (((HLL_REGISTERS+(HLL_SPARSE_XZERO_MAX_LEN-1)) / HLL_SPARSE_XZERO_MAX_LEN)*2); int aux; /* Populate the sparse representation with as many XZERO opcodes as * needed to represent all the registers. */ aux = HLL_REGISTERS; s = sdsnewlen(NULL,sparselen); p = (uint8_t*)s + HLL_HDR_SIZE; while(aux) { int xzero = HLL_SPARSE_XZERO_MAX_LEN; if (xzero > aux) xzero = aux; HLL_SPARSE_XZERO_SET(p,xzero); p += 2; aux -= xzero; } assert((p-(uint8_t*)s) == sparselen); /* Create the actual object. */ o = createObject(s); hdr = (struct hllhdr *) o->ptr; memcpy(hdr->magic,"HYLL",4); hdr->encoding = HLL_SPARSE; return o; } void hll_destroy(robj *obj) { if (!obj) { return; } sdsfree((sds) obj->ptr); destroyObject(obj); } int hll_count(robj *o, size_t *result) { int invalid = 0; *result = hllCount((struct hllhdr*) o->ptr, &invalid); return invalid == 0 ? HLL_C_OK : HLL_C_ERR; } robj *hll_merge(robj **hlls, size_t hll_count) { uint8_t max[HLL_REGISTERS]; struct hllhdr *hdr; size_t j; /* Use dense representation as target? */ int use_dense = 0; /* Compute an HLL with M[i] = MAX(M[i]_j). * We store the maximum into the max array of registers. We'll write * it to the target variable later. */ memset(max, 0, sizeof(max)); for (j = 0; j < hll_count; j++) { /* Check type and size. */ robj *o = hlls[j]; if (o == NULL) continue; /* Assume empty HLL for non existing var. */ /* If at least one involved HLL is dense, use the dense representation * as target ASAP to save time and avoid the conversion step. */ hdr = (struct hllhdr *) o->ptr; if (hdr->encoding == HLL_DENSE) use_dense = 1; /* Merge with this HLL with our 'max' HHL by setting max[i] * to MAX(max[i],hll[i]). */ if (hllMerge(max, o) == HLL_C_ERR) { return NULL; } } /* Create the destination key's value. */ robj *result = hll_create(); if (!result) { return NULL; } /* Convert the destination object to dense representation if at least * one of the inputs was dense. */ if (use_dense && hllSparseToDense(result) == HLL_C_ERR) { hll_destroy(result); return NULL; } /* Write the resulting HLL to the destination HLL registers and * invalidate the cached value. */ for (j = 0; j < HLL_REGISTERS; j++) { if (max[j] == 0) continue; hdr = (struct hllhdr *) result->ptr; switch(hdr->encoding) { case HLL_DENSE: hllDenseSet(hdr->registers + 1,j,max[j]); break; case HLL_SPARSE: hllSparseSet(result,j,max[j]); break; } } return result; } }
// stdafx.cpp : source file that includes just the standard includes // testclassifier-gui.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/op/binary_convolution.hpp" #include "itt.hpp" #include "ngraph/attribute_visitor.hpp" #include "ngraph/axis_vector.hpp" #include "ngraph/coordinate_diff.hpp" #include "ngraph/op/reshape.hpp" #include "ngraph/util.hpp" #include "ngraph/validation_util.hpp" using namespace std; using namespace ngraph; NGRAPH_RTTI_DEFINITION(op::v1::BinaryConvolution, "BinaryConvolution", 1); op::v1::BinaryConvolution::BinaryConvolution(const Output<Node>& data, const Output<Node>& kernel, const Strides& strides, const CoordinateDiff& pads_begin, const CoordinateDiff& pads_end, const Strides& dilations, BinaryConvolutionMode mode, float pad_value, const PadType& auto_pad) : Op({data, kernel}), m_strides(strides), m_dilations(dilations), m_pads_begin(pads_begin), m_pads_end(pads_end), m_mode(mode), m_pad_value(pad_value), m_auto_pad(auto_pad) { constructor_validate_and_infer_types(); } op::v1::BinaryConvolution::BinaryConvolution(const Output<Node>& data, const Output<Node>& kernel, const Strides& strides, const CoordinateDiff& pads_begin, const CoordinateDiff& pads_end, const Strides& dilations, const std::string& mode, float pad_value, const PadType& auto_pad) : Op({data, kernel}), m_strides(strides), m_dilations(dilations), m_pads_begin(pads_begin), m_pads_end(pads_end), m_mode(mode_from_string(mode)), m_pad_value(pad_value), m_auto_pad(auto_pad) { constructor_validate_and_infer_types(); } void op::v1::BinaryConvolution::validate_and_infer_types() { NGRAPH_OP_SCOPE(v1_BinaryConvolution_validate_and_infer_types); const PartialShape& data_batch_pshape = get_input_partial_shape(0); element::Type data_batch_et = get_input_element_type(0); const PartialShape& filters_pshape = get_input_partial_shape(1); NODE_VALIDATION_CHECK(this, data_batch_et.is_real() || data_batch_et.is_integral_number(), "Data batch element type must be numeric. Got: ", data_batch_et); // TODO: Add NodeValidationCheck to filters et once u1 is supported in nGraph Python API // (#52715) Rank result_ps_rank; NODE_VALIDATION_CHECK(this, Rank::merge(result_ps_rank, data_batch_pshape.rank(), filters_pshape.rank()), "Data batch and filters inputs must have same rank. Got: ", data_batch_pshape, " and ", filters_pshape); PartialShape result_shape = validate_and_infer_convolution_forward_output_shape(this, result_ps_rank, data_batch_pshape, filters_pshape, m_auto_pad, m_strides, m_dilations, m_pads_begin, m_pads_end); set_output_type(0, data_batch_et, result_shape); } shared_ptr<Node> op::v1::BinaryConvolution::clone_with_new_inputs(const OutputVector& new_args) const { NGRAPH_OP_SCOPE(v1_BinaryConvolution_clone_with_new_inputs); check_new_args_count(this, new_args); return make_shared<v1::BinaryConvolution>(new_args.at(0), new_args.at(1), m_strides, m_pads_begin, m_pads_end, m_dilations, m_mode, m_pad_value, m_auto_pad); } bool op::v1::BinaryConvolution::visit_attributes(AttributeVisitor& visitor) { NGRAPH_OP_SCOPE(v1_BinaryConvolution_visit_attributes); visitor.on_attribute("strides", m_strides); visitor.on_attribute("pads_begin", m_pads_begin); visitor.on_attribute("pads_end", m_pads_end); visitor.on_attribute("dilations", m_dilations); visitor.on_attribute("mode", m_mode); visitor.on_attribute("pad_value", m_pad_value); visitor.on_attribute("auto_pad", m_auto_pad); return true; } namespace ov { template <> NGRAPH_API EnumNames<op::v1::BinaryConvolution::BinaryConvolutionMode>& EnumNames<op::v1::BinaryConvolution::BinaryConvolutionMode>::get() { static auto enum_names = EnumNames<op::v1::BinaryConvolution::BinaryConvolutionMode>( "op::v1::BinaryConvolution::BinaryConvolutionMode", {{"xnor-popcount", op::v1::BinaryConvolution::BinaryConvolutionMode::XNOR_POPCOUNT}}); return enum_names; } constexpr DiscreteTypeInfo AttributeAdapter<op::v1::BinaryConvolution::BinaryConvolutionMode>::type_info; } // namespace ov std::ostream& operator<<(std::ostream& s, const op::v1::BinaryConvolution::BinaryConvolutionMode& type) { return s << as_string(type); } op::v1::BinaryConvolution::BinaryConvolutionMode op::v1::BinaryConvolution::mode_from_string( const std::string& mode) const { return as_enum<BinaryConvolutionMode>(mode); }
/* * Repast for High Performance Computing (Repast HPC) * * Copyright (c) 2010 Argonne National Laboratory * All rights reserved. * * Redistribution and use in source and binary forms, with * or without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Argonne National Laboratory 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 TRUSTEES 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. * * * Human.cpp * * Created on: Sep 1, 2010 * Author: nick */ #include "relogo/AgentSet.h" #include "relogo/Patch.h" #include "ZombieObserver.h" #include "repast_hpc/RepastProcess.h" #include "Human.h" #include "Zombie.h" using namespace repast::relogo; using namespace repast; struct CountZombiesOnPatch { double operator()(const Patch* patch) const { AgentSet<Zombie> set; patch->turtlesOn(set); return set.size(); } }; void Human::infect() { if (!_infected) { _infected = true; ((ZombieObserver*) _observer)->incrementInfectionCount(); } } void Human::step() { // if human is now dead we can't move it because // it will be removed from the sim and the synchronization // mechanism cannot move it. bool alive = true; if (_infected) { _infectionTime++; if (_infectionTime == 50) { // should be safe to die here as nothing else // will need this object, so OK to delete it _observer->hatch<Zombie> (this); die(); alive = false; } } if (alive) { // are there any zombies in the ngh AgentSet<Patch> nghs = patchHere<Patch> ()->neighbors<Patch> (); Patch* winningPatch = nghs.minOneOf(CountZombiesOnPatch()); face(winningPatch); double distanceToMove = 1.5; // For non-toroidal worlds, need to check to make sure move is not out of bounds while((_observer->patchAtOffset(location(), heading(), distanceToMove) == 0) && (distanceToMove > 0)) distanceToMove--; // if(distanceToMove > 0) move(distanceToMove); } }
/** * eZmax API Definition (Full) * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIEzsignfolder_createObject_v2_Response_mPayload.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QObject> #include "OAIHelpers.h" namespace OpenAPI { OAIEzsignfolder_createObject_v2_Response_mPayload::OAIEzsignfolder_createObject_v2_Response_mPayload(QString json) { this->initializeModel(); this->fromJson(json); } OAIEzsignfolder_createObject_v2_Response_mPayload::OAIEzsignfolder_createObject_v2_Response_mPayload() { this->initializeModel(); } OAIEzsignfolder_createObject_v2_Response_mPayload::~OAIEzsignfolder_createObject_v2_Response_mPayload() {} void OAIEzsignfolder_createObject_v2_Response_mPayload::initializeModel() { m_a_pki_ezsignfolder_id_isSet = false; m_a_pki_ezsignfolder_id_isValid = false; } void OAIEzsignfolder_createObject_v2_Response_mPayload::fromJson(QString jsonString) { QByteArray array(jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIEzsignfolder_createObject_v2_Response_mPayload::fromJsonObject(QJsonObject json) { m_a_pki_ezsignfolder_id_isValid = ::OpenAPI::fromJsonValue(a_pki_ezsignfolder_id, json[QString("a_pkiEzsignfolderID")]); m_a_pki_ezsignfolder_id_isSet = !json[QString("a_pkiEzsignfolderID")].isNull() && m_a_pki_ezsignfolder_id_isValid; } QString OAIEzsignfolder_createObject_v2_Response_mPayload::asJson() const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIEzsignfolder_createObject_v2_Response_mPayload::asJsonObject() const { QJsonObject obj; if (a_pki_ezsignfolder_id.size() > 0) { obj.insert(QString("a_pkiEzsignfolderID"), ::OpenAPI::toJsonValue(a_pki_ezsignfolder_id)); } return obj; } QList<qint32> OAIEzsignfolder_createObject_v2_Response_mPayload::getAPkiEzsignfolderId() const { return a_pki_ezsignfolder_id; } void OAIEzsignfolder_createObject_v2_Response_mPayload::setAPkiEzsignfolderId(const QList<qint32> &a_pki_ezsignfolder_id) { this->a_pki_ezsignfolder_id = a_pki_ezsignfolder_id; this->m_a_pki_ezsignfolder_id_isSet = true; } bool OAIEzsignfolder_createObject_v2_Response_mPayload::is_a_pki_ezsignfolder_id_Set() const{ return m_a_pki_ezsignfolder_id_isSet; } bool OAIEzsignfolder_createObject_v2_Response_mPayload::is_a_pki_ezsignfolder_id_Valid() const{ return m_a_pki_ezsignfolder_id_isValid; } bool OAIEzsignfolder_createObject_v2_Response_mPayload::isSet() const { bool isObjectUpdated = false; do { if (a_pki_ezsignfolder_id.size() > 0) { isObjectUpdated = true; break; } } while (false); return isObjectUpdated; } bool OAIEzsignfolder_createObject_v2_Response_mPayload::isValid() const { // only required properties are required for the object to be considered valid return m_a_pki_ezsignfolder_id_isValid && true; } } // namespace OpenAPI
// 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: UnityEngine.Motion #include "UnityEngine/Motion.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" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: WrapMode struct WrapMode; // Forward declaring type: Bounds struct Bounds; // Forward declaring type: AnimationEvent class AnimationEvent; // Forward declaring type: GameObject class GameObject; // Forward declaring type: AnimationCurve class AnimationCurve; } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; // Forward declaring type: Array class Array; } // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Forward declaring type: AnimationClip class AnimationClip; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::AnimationClip); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::AnimationClip*, "UnityEngine", "AnimationClip"); // Type namespace: UnityEngine namespace UnityEngine { // Size: 0x19 #pragma pack(push, 1) // Autogenerated type: UnityEngine.AnimationClip // [TokenAttribute] Offset: FFFFFFFF // [NativeTypeAttribute] Offset: 11D9840 // [NativeHeaderAttribute] Offset: 11D9840 class AnimationClip : public ::UnityEngine::Motion { public: // public System.Single get_length() // Offset: 0x29ED4F4 float get_length(); // System.Single get_startTime() // Offset: 0x29ED534 float get_startTime(); // System.Single get_stopTime() // Offset: 0x29ED574 float get_stopTime(); // public System.Single get_frameRate() // Offset: 0x29ED5B4 float get_frameRate(); // public System.Void set_frameRate(System.Single value) // Offset: 0x29ED5F4 void set_frameRate(float value); // public UnityEngine.WrapMode get_wrapMode() // Offset: 0x29ED44C ::UnityEngine::WrapMode get_wrapMode(); // public System.Void set_wrapMode(UnityEngine.WrapMode value) // Offset: 0x29ED734 void set_wrapMode(::UnityEngine::WrapMode value); // public UnityEngine.Bounds get_localBounds() // Offset: 0x29ED784 ::UnityEngine::Bounds get_localBounds(); // public System.Void set_localBounds(UnityEngine.Bounds value) // Offset: 0x29ED840 void set_localBounds(::UnityEngine::Bounds value); // public System.Boolean get_legacy() // Offset: 0x29ED8E0 bool get_legacy(); // public System.Void set_legacy(System.Boolean value) // Offset: 0x29ED920 void set_legacy(bool value); // public System.Boolean get_humanMotion() // Offset: 0x29ED970 bool get_humanMotion(); // public System.Boolean get_empty() // Offset: 0x29ED9B0 bool get_empty(); // public System.Boolean get_hasGenericRootTransform() // Offset: 0x29ED9F0 bool get_hasGenericRootTransform(); // public System.Boolean get_hasMotionFloatCurves() // Offset: 0x29EDA30 bool get_hasMotionFloatCurves(); // public System.Boolean get_hasMotionCurves() // Offset: 0x29EDA70 bool get_hasMotionCurves(); // public System.Boolean get_hasRootCurves() // Offset: 0x29EDAB0 bool get_hasRootCurves(); // System.Boolean get_hasRootMotion() // Offset: 0x29EDAF0 bool get_hasRootMotion(); // public UnityEngine.AnimationEvent[] get_events() // Offset: 0x29EDC34 ::ArrayW<::UnityEngine::AnimationEvent*> get_events(); // public System.Void set_events(UnityEngine.AnimationEvent[] value) // Offset: 0x29EDD08 void set_events(::ArrayW<::UnityEngine::AnimationEvent*> value); // static private System.Void Internal_CreateAnimationClip(UnityEngine.AnimationClip self) // Offset: 0x29ED37C static void Internal_CreateAnimationClip(::UnityEngine::AnimationClip* self); // public System.Void SampleAnimation(UnityEngine.GameObject go, System.Single time) // Offset: 0x29ED3BC void SampleAnimation(::UnityEngine::GameObject* go, float time); // static System.Void SampleAnimation(UnityEngine.GameObject go, UnityEngine.AnimationClip clip, System.Single inTime, UnityEngine.WrapMode wrapMode) // Offset: 0x29ED48C static void SampleAnimation(::UnityEngine::GameObject* go, ::UnityEngine::AnimationClip* clip, float inTime, ::UnityEngine::WrapMode wrapMode); // public System.Void SetCurve(System.String relativePath, System.Type type, System.String propertyName, UnityEngine.AnimationCurve curve) // Offset: 0x29ED644 void SetCurve(::StringW relativePath, ::System::Type* type, ::StringW propertyName, ::UnityEngine::AnimationCurve* curve); // public System.Void EnsureQuaternionContinuity() // Offset: 0x29ED6B4 void EnsureQuaternionContinuity(); // public System.Void ClearCurves() // Offset: 0x29ED6F4 void ClearCurves(); // public System.Void AddEvent(UnityEngine.AnimationEvent evt) // Offset: 0x29EDB30 void AddEvent(::UnityEngine::AnimationEvent* evt); // System.Void AddEventInternal(System.Object evt) // Offset: 0x29EDBE4 void AddEventInternal(::Il2CppObject* evt); // System.Void SetEventsInternal(System.Array value) // Offset: 0x29EDD58 void SetEventsInternal(::System::Array* value); // System.Array GetEventsInternal() // Offset: 0x29EDCC8 ::System::Array* GetEventsInternal(); // private System.Void get_localBounds_Injected(out UnityEngine.Bounds ret) // Offset: 0x29ED7F0 void get_localBounds_Injected(ByRef<::UnityEngine::Bounds> ret); // private System.Void set_localBounds_Injected(ref UnityEngine.Bounds value) // Offset: 0x29ED890 void set_localBounds_Injected(ByRef<::UnityEngine::Bounds> value); // public System.Void .ctor() // Offset: 0x29ED2D0 // Implemented from: UnityEngine.Motion // Base method: System.Void Motion::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static AnimationClip* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::AnimationClip::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<AnimationClip*, creationType>())); } }; // UnityEngine.AnimationClip #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_length // Il2CppName: get_length template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_length)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_length", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_startTime // Il2CppName: get_startTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_startTime)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_startTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_stopTime // Il2CppName: get_stopTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_stopTime)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_stopTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_frameRate // Il2CppName: get_frameRate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_frameRate)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_frameRate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::set_frameRate // Il2CppName: set_frameRate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(float)>(&UnityEngine::AnimationClip::set_frameRate)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "set_frameRate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_wrapMode // Il2CppName: get_wrapMode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::WrapMode (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_wrapMode)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_wrapMode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::set_wrapMode // Il2CppName: set_wrapMode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(::UnityEngine::WrapMode)>(&UnityEngine::AnimationClip::set_wrapMode)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "WrapMode")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "set_wrapMode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_localBounds // Il2CppName: get_localBounds template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Bounds (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_localBounds)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_localBounds", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::set_localBounds // Il2CppName: set_localBounds template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(::UnityEngine::Bounds)>(&UnityEngine::AnimationClip::set_localBounds)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Bounds")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "set_localBounds", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_legacy // Il2CppName: get_legacy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_legacy)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_legacy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::set_legacy // Il2CppName: set_legacy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(bool)>(&UnityEngine::AnimationClip::set_legacy)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "set_legacy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_humanMotion // Il2CppName: get_humanMotion template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_humanMotion)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_humanMotion", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_empty // Il2CppName: get_empty template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_empty)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_empty", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_hasGenericRootTransform // Il2CppName: get_hasGenericRootTransform template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_hasGenericRootTransform)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_hasGenericRootTransform", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_hasMotionFloatCurves // Il2CppName: get_hasMotionFloatCurves template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_hasMotionFloatCurves)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_hasMotionFloatCurves", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_hasMotionCurves // Il2CppName: get_hasMotionCurves template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_hasMotionCurves)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_hasMotionCurves", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_hasRootCurves // Il2CppName: get_hasRootCurves template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_hasRootCurves)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_hasRootCurves", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_hasRootMotion // Il2CppName: get_hasRootMotion template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_hasRootMotion)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_hasRootMotion", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_events // Il2CppName: get_events template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<::UnityEngine::AnimationEvent*> (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::get_events)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_events", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::set_events // Il2CppName: set_events template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(::ArrayW<::UnityEngine::AnimationEvent*>)>(&UnityEngine::AnimationClip::set_events)> { static const MethodInfo* get() { static auto* value = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("UnityEngine", "AnimationEvent"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "set_events", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::Internal_CreateAnimationClip // Il2CppName: Internal_CreateAnimationClip template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::UnityEngine::AnimationClip*)>(&UnityEngine::AnimationClip::Internal_CreateAnimationClip)> { static const MethodInfo* get() { static auto* self = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimationClip")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "Internal_CreateAnimationClip", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{self}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::SampleAnimation // Il2CppName: SampleAnimation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(::UnityEngine::GameObject*, float)>(&UnityEngine::AnimationClip::SampleAnimation)> { static const MethodInfo* get() { static auto* go = &::il2cpp_utils::GetClassFromName("UnityEngine", "GameObject")->byval_arg; static auto* time = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "SampleAnimation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{go, time}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::SampleAnimation // Il2CppName: SampleAnimation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::UnityEngine::GameObject*, ::UnityEngine::AnimationClip*, float, ::UnityEngine::WrapMode)>(&UnityEngine::AnimationClip::SampleAnimation)> { static const MethodInfo* get() { static auto* go = &::il2cpp_utils::GetClassFromName("UnityEngine", "GameObject")->byval_arg; static auto* clip = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimationClip")->byval_arg; static auto* inTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; static auto* wrapMode = &::il2cpp_utils::GetClassFromName("UnityEngine", "WrapMode")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "SampleAnimation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{go, clip, inTime, wrapMode}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::SetCurve // Il2CppName: SetCurve template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(::StringW, ::System::Type*, ::StringW, ::UnityEngine::AnimationCurve*)>(&UnityEngine::AnimationClip::SetCurve)> { static const MethodInfo* get() { static auto* relativePath = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* propertyName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* curve = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimationCurve")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "SetCurve", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{relativePath, type, propertyName, curve}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::EnsureQuaternionContinuity // Il2CppName: EnsureQuaternionContinuity template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::EnsureQuaternionContinuity)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "EnsureQuaternionContinuity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::ClearCurves // Il2CppName: ClearCurves template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::ClearCurves)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "ClearCurves", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::AddEvent // Il2CppName: AddEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(::UnityEngine::AnimationEvent*)>(&UnityEngine::AnimationClip::AddEvent)> { static const MethodInfo* get() { static auto* evt = &::il2cpp_utils::GetClassFromName("UnityEngine", "AnimationEvent")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "AddEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{evt}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::AddEventInternal // Il2CppName: AddEventInternal template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(::Il2CppObject*)>(&UnityEngine::AnimationClip::AddEventInternal)> { static const MethodInfo* get() { static auto* evt = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "AddEventInternal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{evt}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::SetEventsInternal // Il2CppName: SetEventsInternal template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(::System::Array*)>(&UnityEngine::AnimationClip::SetEventsInternal)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "SetEventsInternal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::GetEventsInternal // Il2CppName: GetEventsInternal template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Array* (UnityEngine::AnimationClip::*)()>(&UnityEngine::AnimationClip::GetEventsInternal)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "GetEventsInternal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::get_localBounds_Injected // Il2CppName: get_localBounds_Injected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(ByRef<::UnityEngine::Bounds>)>(&UnityEngine::AnimationClip::get_localBounds_Injected)> { static const MethodInfo* get() { static auto* ret = &::il2cpp_utils::GetClassFromName("UnityEngine", "Bounds")->this_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "get_localBounds_Injected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ret}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::set_localBounds_Injected // Il2CppName: set_localBounds_Injected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::AnimationClip::*)(ByRef<::UnityEngine::Bounds>)>(&UnityEngine::AnimationClip::set_localBounds_Injected)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Bounds")->this_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::AnimationClip*), "set_localBounds_Injected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::AnimationClip::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" #include "base/prefs/pref_service.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/custom_handlers/protocol_handler_registry.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_prefs.h" #include "extensions/common/url_pattern.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/web/WebContextMenuData.h" #include "url/gurl.h" using extensions::MenuItem; using extensions::URLPatternSet; class RenderViewContextMenuTest : public testing::Test { protected: // Proxy defined here to minimize friend classes in RenderViewContextMenu static bool ExtensionContextAndPatternMatch( const content::ContextMenuParams& params, MenuItem::ContextList contexts, const URLPatternSet& patterns) { return RenderViewContextMenu::ExtensionContextAndPatternMatch(params, contexts, patterns); } }; // Generates a ContextMenuParams that matches the specified contexts. static content::ContextMenuParams CreateParams(int contexts) { content::ContextMenuParams rv; rv.is_editable = false; rv.media_type = blink::WebContextMenuData::MediaTypeNone; rv.page_url = GURL("http://test.page/"); static const base::char16 selected_text[] = { 's', 'e', 'l', 0 }; if (contexts & MenuItem::SELECTION) rv.selection_text = selected_text; if (contexts & MenuItem::LINK) rv.link_url = GURL("http://test.link/"); if (contexts & MenuItem::EDITABLE) rv.is_editable = true; if (contexts & MenuItem::IMAGE) { rv.src_url = GURL("http://test.image/"); rv.media_type = blink::WebContextMenuData::MediaTypeImage; } if (contexts & MenuItem::VIDEO) { rv.src_url = GURL("http://test.video/"); rv.media_type = blink::WebContextMenuData::MediaTypeVideo; } if (contexts & MenuItem::AUDIO) { rv.src_url = GURL("http://test.audio/"); rv.media_type = blink::WebContextMenuData::MediaTypeAudio; } if (contexts & MenuItem::FRAME) rv.frame_url = GURL("http://test.frame/"); return rv; } // Generates a URLPatternSet with a single pattern static URLPatternSet CreatePatternSet(const std::string& pattern) { URLPattern target(URLPattern::SCHEME_HTTP); target.Parse(pattern); URLPatternSet rv; rv.AddPattern(target); return rv; } TEST_F(RenderViewContextMenuTest, TargetIgnoredForPage) { content::ContextMenuParams params = CreateParams(0); MenuItem::ContextList contexts; contexts.Add(MenuItem::PAGE); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetCheckedForLink) { content::ContextMenuParams params = CreateParams(MenuItem::LINK); MenuItem::ContextList contexts; contexts.Add(MenuItem::PAGE); contexts.Add(MenuItem::LINK); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetCheckedForImage) { content::ContextMenuParams params = CreateParams(MenuItem::IMAGE); MenuItem::ContextList contexts; contexts.Add(MenuItem::PAGE); contexts.Add(MenuItem::IMAGE); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetCheckedForVideo) { content::ContextMenuParams params = CreateParams(MenuItem::VIDEO); MenuItem::ContextList contexts; contexts.Add(MenuItem::PAGE); contexts.Add(MenuItem::VIDEO); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetCheckedForAudio) { content::ContextMenuParams params = CreateParams(MenuItem::AUDIO); MenuItem::ContextList contexts; contexts.Add(MenuItem::PAGE); contexts.Add(MenuItem::AUDIO); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, MatchWhenLinkedImageMatchesTarget) { content::ContextMenuParams params = CreateParams(MenuItem::IMAGE | MenuItem::LINK); MenuItem::ContextList contexts; contexts.Add(MenuItem::LINK); contexts.Add(MenuItem::IMAGE); URLPatternSet patterns = CreatePatternSet("*://test.link/*"); EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, MatchWhenLinkedImageMatchesSource) { content::ContextMenuParams params = CreateParams(MenuItem::IMAGE | MenuItem::LINK); MenuItem::ContextList contexts; contexts.Add(MenuItem::LINK); contexts.Add(MenuItem::IMAGE); URLPatternSet patterns = CreatePatternSet("*://test.image/*"); EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, NoMatchWhenLinkedImageMatchesNeither) { content::ContextMenuParams params = CreateParams(MenuItem::IMAGE | MenuItem::LINK); MenuItem::ContextList contexts; contexts.Add(MenuItem::LINK); contexts.Add(MenuItem::IMAGE); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_FALSE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetIgnoredForFrame) { content::ContextMenuParams params = CreateParams(MenuItem::FRAME); MenuItem::ContextList contexts; contexts.Add(MenuItem::FRAME); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetIgnoredForEditable) { content::ContextMenuParams params = CreateParams(MenuItem::EDITABLE); MenuItem::ContextList contexts; contexts.Add(MenuItem::EDITABLE); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelection) { content::ContextMenuParams params = CreateParams(MenuItem::SELECTION); MenuItem::ContextList contexts; contexts.Add(MenuItem::SELECTION); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelectionOnLink) { content::ContextMenuParams params = CreateParams( MenuItem::SELECTION | MenuItem::LINK); MenuItem::ContextList contexts; contexts.Add(MenuItem::SELECTION); contexts.Add(MenuItem::LINK); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } TEST_F(RenderViewContextMenuTest, TargetIgnoredForSelectionOnImage) { content::ContextMenuParams params = CreateParams( MenuItem::SELECTION | MenuItem::IMAGE); MenuItem::ContextList contexts; contexts.Add(MenuItem::SELECTION); contexts.Add(MenuItem::IMAGE); URLPatternSet patterns = CreatePatternSet("*://test.none/*"); EXPECT_TRUE(ExtensionContextAndPatternMatch(params, contexts, patterns)); } class RenderViewContextMenuPrefsTest : public ChromeRenderViewHostTestHarness { public: virtual void SetUp() OVERRIDE { ChromeRenderViewHostTestHarness::SetUp(); registry_.reset(new ProtocolHandlerRegistry(profile(), NULL)); } virtual void TearDown() OVERRIDE { registry_.reset(); ChromeRenderViewHostTestHarness::TearDown(); } TestRenderViewContextMenu* CreateContextMenu() { content::ContextMenuParams params = CreateParams(MenuItem::LINK); params.unfiltered_link_url = params.link_url; content::WebContents* wc = web_contents(); TestRenderViewContextMenu* menu = new TestRenderViewContextMenu( wc->GetMainFrame(), params); // TestingProfile (returned by profile()) does not provide a protocol // registry. menu->protocol_handler_registry_ = registry_.get(); menu->Init(); return menu; } private: scoped_ptr<ProtocolHandlerRegistry> registry_; }; // Verifies when Incognito Mode is not available (disabled by policy), // Open Link in Incognito Window link in the context menu is disabled. TEST_F(RenderViewContextMenuPrefsTest, DisableOpenInIncognitoWindowWhenIncognitoIsDisabled) { scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); // Initially the Incognito mode is be enabled. So is the Open Link in // Incognito Window link. ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKOFFTHERECORD)); EXPECT_TRUE( menu->IsCommandIdEnabled(IDC_CONTENT_CONTEXT_OPENLINKOFFTHERECORD)); // Disable Incognito mode. IncognitoModePrefs::SetAvailability(profile()->GetPrefs(), IncognitoModePrefs::DISABLED); menu.reset(CreateContextMenu()); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKOFFTHERECORD)); EXPECT_FALSE( menu->IsCommandIdEnabled(IDC_CONTENT_CONTEXT_OPENLINKOFFTHERECORD)); }
#include "RecoMuon/CosmicMuonProducer/src/CosmicMuonLinksProducer.h" /**\class CosmicMuonLinksProducer * * * Original Author: Chang Liu - Purdue University <chang.liu@cern.ch> **/ // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackExtra.h" #include "RecoMuon/TrackingTools/interface/MuonServiceProxy.h" using namespace edm; using namespace std; using namespace reco; // // constructors and destructor // CosmicMuonLinksProducer::CosmicMuonLinksProducer(const ParameterSet& iConfig) { category_ = "Muon|RecoMuon|CosmicMuon|CosmicMuonLinksProducer"; ParameterSet serviceParameters = iConfig.getParameter<ParameterSet>("ServiceParameters"); theService = new MuonServiceProxy(serviceParameters); std::vector<edm::ParameterSet> theMapPSets = iConfig.getParameter<std::vector<edm::ParameterSet> >("Maps"); for (std::vector<edm::ParameterSet>::const_iterator iMPS = theMapPSets.begin(); iMPS != theMapPSets.end(); iMPS++) { edm::InputTag sTag = (*iMPS).getParameter<edm::InputTag>("subTrack"); edm::InputTag pTag = (*iMPS).getParameter<edm::InputTag>("parentTrack"); edm::EDGetTokenT<reco::TrackCollection> subTrackTag = consumes<reco::TrackCollection>(sTag); edm::EDGetTokenT<reco::TrackCollection> parentTrackTag = consumes<reco::TrackCollection>(pTag); theTrackLinks.push_back(make_pair(subTrackTag, parentTrackTag)); theTrackLinkNames.push_back(make_pair(sTag.label(), pTag.label())); LogDebug(category_) << "preparing map between " << sTag << " & " << pTag; std::string mapname = sTag.label() + "To" + pTag.label(); produces<reco::TrackToTrackMap>(mapname); } } CosmicMuonLinksProducer::~CosmicMuonLinksProducer() { if (theService) delete theService; } // ------------ method called to produce the data ------------ void CosmicMuonLinksProducer::produce(Event& iEvent, const EventSetup& iSetup) { LogInfo(category_) << "Processing event number: " << iEvent.id(); theService->update(iSetup); unsigned int counter = 0; ///DAMN I cannot read the label of the TOKEN so I need to do this stupid thing to create the labels of the products! for (std::vector<std::pair<edm::EDGetTokenT<reco::TrackCollection>, edm::EDGetTokenT<reco::TrackCollection> > >::const_iterator iLink = theTrackLinks.begin(); iLink != theTrackLinks.end(); iLink++) { #ifdef EDM_ML_DEBUG edm::EDConsumerBase::Labels labels_first; edm::EDConsumerBase::Labels labels_second; labelsForToken(iLink->first, labels_first); labelsForToken(iLink->second, labels_second); LogDebug(category_) << "making map between " << labels_first.module << " and " << labels_second.module; #endif std::string mapname = theTrackLinkNames[counter].first + "To" + theTrackLinkNames[counter].second; reco::TrackToTrackMap ttmap; Handle<reco::TrackCollection> subTracks; Handle<reco::TrackCollection> parentTracks; iEvent.getByToken((*iLink).first, subTracks); iEvent.getByToken((*iLink).second, parentTracks); ttmap = mapTracks(subTracks, parentTracks); LogTrace(category_) << "Mapped: " << theTrackLinkNames[counter].first << " " << subTracks->size() << " and " << theTrackLinkNames[counter].second << " " << parentTracks->size() << ", results: " << ttmap.size() << endl; iEvent.put(std::make_unique<reco::TrackToTrackMap>(ttmap), mapname); counter++; } } reco::TrackToTrackMap CosmicMuonLinksProducer::mapTracks(const Handle<reco::TrackCollection>& subTracks, const Handle<reco::TrackCollection>& parentTracks) const { reco::TrackToTrackMap map(subTracks, parentTracks); for (unsigned int position1 = 0; position1 != subTracks->size(); ++position1) { TrackRef track1(subTracks, position1); for (unsigned int position2 = 0; position2 != parentTracks->size(); ++position2) { TrackRef track2(parentTracks, position2); int shared = sharedHits(*track1, *track2); LogTrace(category_) << "sharedHits " << shared << " track1 " << track1->found() << " track2 " << track2->found() << endl; if (shared > (track1->found()) / 2) map.insert(track1, track2); } } return map; } int CosmicMuonLinksProducer::sharedHits(const reco::Track& track1, const reco::Track& track2) const { int match = 0; for (trackingRecHit_iterator hit1 = track1.recHitsBegin(); hit1 != track1.recHitsEnd(); ++hit1) { if (!(*hit1)->isValid()) continue; DetId id1 = (*hit1)->geographicalId(); if (id1.det() != DetId::Muon) continue; //ONLY MUON LogTrace(category_) << "first ID " << id1.rawId() << " " << (*hit1)->localPosition() << endl; GlobalPoint pos1 = theService->trackingGeometry()->idToDet(id1)->surface().toGlobal((*hit1)->localPosition()); for (trackingRecHit_iterator hit2 = track2.recHitsBegin(); hit2 != track2.recHitsEnd(); ++hit2) { if (!(*hit2)->isValid()) continue; DetId id2 = (*hit2)->geographicalId(); if (id2.det() != DetId::Muon) continue; //ONLY MUON // LogTrace(category_)<<"second ID "<<id2.rawId()<< (*hit2)->localPosition()<<endl; if (id2.rawId() != id1.rawId()) continue; GlobalPoint pos2 = theService->trackingGeometry()->idToDet(id2)->surface().toGlobal((*hit2)->localPosition()); if ((pos1 - pos2).mag() < 10e-5) match++; } } return match; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "interpreter.h" #include "primitives/transaction.h" #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha256.h" #include "pubkey.h" #include "script/script.h" #include "uint256.h" using namespace std; typedef vector<unsigned char> valtype; namespace { inline bool set_success(ScriptError* ret) { if (ret) *ret = SCRIPT_ERR_OK; return true; } inline bool set_error(ScriptError* ret, const ScriptError serror) { if (ret) *ret = serror; return false; } } // anon namespace bool CastToBool(const valtype& vch) { for (unsigned int i = 0; i < vch.size(); i++) { if (vch[i] != 0) { // Can be negative zero if (i == vch.size()-1 && vch[i] == 0x80) return false; return true; } } return false; } /** * Script is a stack machine (like Forth) that evaluates a predicate * returning a bool indicating valid or not. There are no loops. */ #define stacktop(i) (stack.at(stack.size()+(i))) #define altstacktop(i) (altstack.at(altstack.size()+(i))) static inline void popstack(vector<valtype>& stack) { if (stack.empty()) throw runtime_error("popstack(): stack empty"); stack.pop_back(); } bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) { if (vchPubKey.size() < 33) { // Non-canonical public key: too short return false; } if (vchPubKey[0] == 0x04) { if (vchPubKey.size() != 65) { // Non-canonical public key: invalid length for uncompressed key return false; } } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) { if (vchPubKey.size() != 33) { // Non-canonical public key: invalid length for compressed key return false; } } else { // Non-canonical public key: neither compressed nor uncompressed return false; } return true; } /** * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype> * Where R and S are not negative (their first byte has its highest bit not set), and not * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows, * in which case a single 0 byte is necessary and even required). * * See https://sdrttalk.org/index.php?topic=8392.msg127623#msg127623 * * This function is consensus-critical since BIP66. */ bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) { // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash] // * total-length: 1-byte length descriptor of everything that follows, // excluding the sighash byte. // * R-length: 1-byte length descriptor of the R value that follows. // * R: arbitrary-length big-endian encoded R value. It must use the shortest // possible encoding for a positive integers (which means no null bytes at // the start, except a single one when the next byte has its highest bit set). // * S-length: 1-byte length descriptor of the S value that follows. // * S: arbitrary-length big-endian encoded S value. The same rules apply. // * sighash: 1-byte value indicating what data is hashed (not part of the DER // signature) // Minimum and maximum size constraints. if (sig.size() < 9) return false; if (sig.size() > 73) return false; // A signature is of type 0x30 (compound). if (sig[0] != 0x30) return false; // Make sure the length covers the entire signature. if (sig[1] != sig.size() - 3) return false; // Extract the length of the R element. unsigned int lenR = sig[3]; // Make sure the length of the S element is still inside the signature. if (5 + lenR >= sig.size()) return false; // Extract the length of the S element. unsigned int lenS = sig[5 + lenR]; // Verify that the length of the signature matches the sum of the length // of the elements. if ((size_t)(lenR + lenS + 7) != sig.size()) return false; // Check whether the R element is an integer. if (sig[2] != 0x02) return false; // Zero-length integers are not allowed for R. if (lenR == 0) return false; // Negative numbers are not allowed for R. if (sig[4] & 0x80) return false; // Null bytes at the start of R are not allowed, unless R would // otherwise be interpreted as a negative number. if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false; // Check whether the S element is an integer. if (sig[lenR + 4] != 0x02) return false; // Zero-length integers are not allowed for S. if (lenS == 0) return false; // Negative numbers are not allowed for S. if (sig[lenR + 6] & 0x80) return false; // Null bytes at the start of S are not allowed, unless S would otherwise be // interpreted as a negative number. if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false; return true; } bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) { if (!IsValidSignatureEncoding(vchSig)) { return set_error(serror, SCRIPT_ERR_SIG_DER); } std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1); if (!CPubKey::CheckLowS(vchSigCopy)) { return set_error(serror, SCRIPT_ERR_SIG_HIGH_S); } return true; } bool static IsDefinedHashtypeSignature(const valtype &vchSig) { if (vchSig.size() == 0) { return false; } unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY)); if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE) return false; return true; } bool CheckSignatureEncoding(const vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) { // Empty signature. Not strictly DER encoded, but allowed to provide a // compact way to provide an invalid signature for use with CHECK(MULTI)SIG if (vchSig.size() == 0) { return true; } if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) { return set_error(serror, SCRIPT_ERR_SIG_DER); } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) { // serror is set return false; } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) { return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE); } return true; } bool static CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags, ScriptError* serror) { if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchSig)) { return set_error(serror, SCRIPT_ERR_PUBKEYTYPE); } return true; } bool static CheckMinimalPush(const valtype& data, opcodetype opcode) { if (data.size() == 0) { // Could have used OP_0. return opcode == OP_0; } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) { // Could have used OP_1 .. OP_16. return opcode == OP_1 + (data[0] - 1); } else if (data.size() == 1 && data[0] == 0x81) { // Could have used OP_1NEGATE. return opcode == OP_1NEGATE; } else if (data.size() <= 75) { // Could have used a direct push (opcode indicating number of bytes pushed + those bytes). return opcode == data.size(); } else if (data.size() <= 255) { // Could have used OP_PUSHDATA. return opcode == OP_PUSHDATA1; } else if (data.size() <= 65535) { // Could have used OP_PUSHDATA2. return opcode == OP_PUSHDATA2; } return true; } bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) { static const CScriptNum bnZero(0); static const CScriptNum bnOne(1); static const CScriptNum bnFalse(0); static const CScriptNum bnTrue(1); static const valtype vchFalse(0); static const valtype vchZero(0); static const valtype vchTrue(1, 1); CScript::const_iterator pc = script.begin(); CScript::const_iterator pend = script.end(); CScript::const_iterator pbegincodehash = script.begin(); opcodetype opcode; valtype vchPushValue; vector<bool> vfExec; vector<valtype> altstack; set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); if (script.size() > MAX_SCRIPT_SIZE) return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE); int nOpCount = 0; bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0; try { while (pc < pend) { bool fExec = !count(vfExec.begin(), vfExec.end(), false); // // Read instruction // if (!script.GetOp(pc, opcode, vchPushValue)) return set_error(serror, SCRIPT_ERR_BAD_OPCODE); if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE); // Note how OP_RESERVED does not count towards the opcode limit. if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) return set_error(serror, SCRIPT_ERR_OP_COUNT); if (opcode == OP_CAT || opcode == OP_SUBSTR || opcode == OP_LEFT || opcode == OP_RIGHT || opcode == OP_INVERT || opcode == OP_AND || opcode == OP_OR || opcode == OP_XOR || opcode == OP_2MUL || opcode == OP_2DIV || opcode == OP_MUL || opcode == OP_DIV || opcode == OP_MOD || opcode == OP_LSHIFT || opcode == OP_RSHIFT) return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes. if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) { if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) { return set_error(serror, SCRIPT_ERR_MINIMALDATA); } stack.push_back(vchPushValue); } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF)) switch (opcode) { // // Push value // case OP_1NEGATE: case OP_1: case OP_2: case OP_3: case OP_4: case OP_5: case OP_6: case OP_7: case OP_8: case OP_9: case OP_10: case OP_11: case OP_12: case OP_13: case OP_14: case OP_15: case OP_16: { // ( -- value) CScriptNum bn((int)opcode - (int)(OP_1 - 1)); stack.push_back(bn.getvch()); // The result of these opcodes should always be the minimal way to push the data // they push, so no need for a CheckMinimalPush here. } break; // // Control // case OP_NOP: break; case OP_CHECKLOCKTIMEVERIFY: { if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) { // not enabled; treat as a NOP2 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) { return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS); } break; } if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); // Note that elsewhere numeric opcodes are limited to // operands in the range -2**31+1 to 2**31-1, however it is // legal for opcodes to produce results exceeding that // range. This limitation is implemented by CScriptNum's // default 4-byte limit. // // If we kept to that limit we'd have a year 2038 problem, // even though the nLockTime field in transactions // themselves is uint32 which only becomes meaningless // after the year 2106. // // Thus as a special case we tell CScriptNum to accept up // to 5-byte bignums, which are good until 2**39-1, well // beyond the 2**32-1 limit of the nLockTime field itself. const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5); // In the rare event that the argument may be < 0 due to // some arithmetic being done first, you can always use // 0 MAX CHECKLOCKTIMEVERIFY. if (nLockTime < 0) return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME); // Actually compare the specified lock time with the transaction. if (!checker.CheckLockTime(nLockTime)) return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME); break; } case OP_CHECKSEQUENCEVERIFY: { if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) { // not enabled; treat as a NOP3 if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) { return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS); } break; } if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); // nSequence, like nLockTime, is a 32-bit unsigned integer // field. See the comment in CHECKLOCKTIMEVERIFY regarding // 5-byte numeric operands. const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5); // In the rare event that the argument may be < 0 due to // some arithmetic being done first, you can always use // 0 MAX CHECKSEQUENCEVERIFY. if (nSequence < 0) return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME); // To provide for future soft-fork extensibility, if the // operand has the disabled lock-time flag set, // CHECKSEQUENCEVERIFY behaves as a NOP. if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0) break; // Compare the specified sequence number with the input. if (!checker.CheckSequence(nSequence)) return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME); break; } case OP_NOP1: case OP_NOP4: case OP_NOP5: case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10: { if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS); } break; case OP_IF: case OP_NOTIF: { // <expression> if [statements] [else [statements]] endif bool fValue = false; if (fExec) { if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); valtype& vch = stacktop(-1); fValue = CastToBool(vch); if (opcode == OP_NOTIF) fValue = !fValue; popstack(stack); } vfExec.push_back(fValue); } break; case OP_ELSE: { if (vfExec.empty()) return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); vfExec.back() = !vfExec.back(); } break; case OP_ENDIF: { if (vfExec.empty()) return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); vfExec.pop_back(); } break; case OP_VERIFY: { // (true -- ) or // (false -- false) and return if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); bool fValue = CastToBool(stacktop(-1)); if (fValue) popstack(stack); else return set_error(serror, SCRIPT_ERR_VERIFY); } break; case OP_RETURN: { return set_error(serror, SCRIPT_ERR_OP_RETURN); } break; // // Stack ops // case OP_TOALTSTACK: { if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); altstack.push_back(stacktop(-1)); popstack(stack); } break; case OP_FROMALTSTACK: { if (altstack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION); stack.push_back(altstacktop(-1)); popstack(altstack); } break; case OP_2DROP: { // (x1 x2 -- ) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); popstack(stack); popstack(stack); } break; case OP_2DUP: { // (x1 x2 -- x1 x2 x1 x2) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch1 = stacktop(-2); valtype vch2 = stacktop(-1); stack.push_back(vch1); stack.push_back(vch2); } break; case OP_3DUP: { // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3) if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch1 = stacktop(-3); valtype vch2 = stacktop(-2); valtype vch3 = stacktop(-1); stack.push_back(vch1); stack.push_back(vch2); stack.push_back(vch3); } break; case OP_2OVER: { // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2) if (stack.size() < 4) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch1 = stacktop(-4); valtype vch2 = stacktop(-3); stack.push_back(vch1); stack.push_back(vch2); } break; case OP_2ROT: { // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2) if (stack.size() < 6) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch1 = stacktop(-6); valtype vch2 = stacktop(-5); stack.erase(stack.end()-6, stack.end()-4); stack.push_back(vch1); stack.push_back(vch2); } break; case OP_2SWAP: { // (x1 x2 x3 x4 -- x3 x4 x1 x2) if (stack.size() < 4) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); swap(stacktop(-4), stacktop(-2)); swap(stacktop(-3), stacktop(-1)); } break; case OP_IFDUP: { // (x - 0 | x x) if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch = stacktop(-1); if (CastToBool(vch)) stack.push_back(vch); } break; case OP_DEPTH: { // -- stacksize CScriptNum bn(stack.size()); stack.push_back(bn.getvch()); } break; case OP_DROP: { // (x -- ) if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); popstack(stack); } break; case OP_DUP: { // (x -- x x) if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch = stacktop(-1); stack.push_back(vch); } break; case OP_NIP: { // (x1 x2 -- x2) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); stack.erase(stack.end() - 2); } break; case OP_OVER: { // (x1 x2 -- x1 x2 x1) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch = stacktop(-2); stack.push_back(vch); } break; case OP_PICK: case OP_ROLL: { // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn) // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); int n = CScriptNum(stacktop(-1), fRequireMinimal).getint(); popstack(stack); if (n < 0 || n >= (int)stack.size()) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch = stacktop(-n-1); if (opcode == OP_ROLL) stack.erase(stack.end()-n-1); stack.push_back(vch); } break; case OP_ROT: { // (x1 x2 x3 -- x2 x3 x1) // x2 x1 x3 after first swap // x2 x3 x1 after second swap if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); swap(stacktop(-3), stacktop(-2)); swap(stacktop(-2), stacktop(-1)); } break; case OP_SWAP: { // (x1 x2 -- x2 x1) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); swap(stacktop(-2), stacktop(-1)); } break; case OP_TUCK: { // (x1 x2 -- x2 x1 x2) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype vch = stacktop(-1); stack.insert(stack.end()-2, vch); } break; case OP_SIZE: { // (in -- in size) if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); CScriptNum bn(stacktop(-1).size()); stack.push_back(bn.getvch()); } break; // // Bitwise logic // case OP_EQUAL: case OP_EQUALVERIFY: //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL { // (x1 x2 - bool) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype& vch1 = stacktop(-2); valtype& vch2 = stacktop(-1); bool fEqual = (vch1 == vch2); // OP_NOTEQUAL is disabled because it would be too easy to say // something like n != 1 and have some wiseguy pass in 1 with extra // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001) //if (opcode == OP_NOTEQUAL) // fEqual = !fEqual; popstack(stack); popstack(stack); stack.push_back(fEqual ? vchTrue : vchFalse); if (opcode == OP_EQUALVERIFY) { if (fEqual) popstack(stack); else return set_error(serror, SCRIPT_ERR_EQUALVERIFY); } } break; // // Numeric // case OP_1ADD: case OP_1SUB: case OP_NEGATE: case OP_ABS: case OP_NOT: case OP_0NOTEQUAL: { // (in -- out) if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); CScriptNum bn(stacktop(-1), fRequireMinimal); switch (opcode) { case OP_1ADD: bn += bnOne; break; case OP_1SUB: bn -= bnOne; break; case OP_NEGATE: bn = -bn; break; case OP_ABS: if (bn < bnZero) bn = -bn; break; case OP_NOT: bn = (bn == bnZero); break; case OP_0NOTEQUAL: bn = (bn != bnZero); break; default: assert(!"invalid opcode"); break; } popstack(stack); stack.push_back(bn.getvch()); } break; case OP_ADD: case OP_SUB: case OP_BOOLAND: case OP_BOOLOR: case OP_NUMEQUAL: case OP_NUMEQUALVERIFY: case OP_NUMNOTEQUAL: case OP_LESSTHAN: case OP_GREATERTHAN: case OP_LESSTHANOREQUAL: case OP_GREATERTHANOREQUAL: case OP_MIN: case OP_MAX: { // (x1 x2 -- out) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); CScriptNum bn1(stacktop(-2), fRequireMinimal); CScriptNum bn2(stacktop(-1), fRequireMinimal); CScriptNum bn(0); switch (opcode) { case OP_ADD: bn = bn1 + bn2; break; case OP_SUB: bn = bn1 - bn2; break; case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break; case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break; case OP_NUMEQUAL: bn = (bn1 == bn2); break; case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break; case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break; case OP_LESSTHAN: bn = (bn1 < bn2); break; case OP_GREATERTHAN: bn = (bn1 > bn2); break; case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break; case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break; case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break; case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break; default: assert(!"invalid opcode"); break; } popstack(stack); popstack(stack); stack.push_back(bn.getvch()); if (opcode == OP_NUMEQUALVERIFY) { if (CastToBool(stacktop(-1))) popstack(stack); else return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY); } } break; case OP_WITHIN: { // (x min max -- out) if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); CScriptNum bn1(stacktop(-3), fRequireMinimal); CScriptNum bn2(stacktop(-2), fRequireMinimal); CScriptNum bn3(stacktop(-1), fRequireMinimal); bool fValue = (bn2 <= bn1 && bn1 < bn3); popstack(stack); popstack(stack); popstack(stack); stack.push_back(fValue ? vchTrue : vchFalse); } break; // // Crypto // case OP_RIPEMD160: case OP_SHA1: case OP_SHA256: case OP_HASH160: case OP_HASH256: { // (in -- hash) if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype& vch = stacktop(-1); valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32); if (opcode == OP_RIPEMD160) CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); else if (opcode == OP_SHA1) CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); else if (opcode == OP_SHA256) CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); else if (opcode == OP_HASH160) CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); else if (opcode == OP_HASH256) CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); popstack(stack); stack.push_back(vchHash); } break; case OP_CODESEPARATOR: { // Hash starts after the code separator pbegincodehash = pc; } break; case OP_CHECKSIG: case OP_CHECKSIGVERIFY: { // (sig pubkey -- bool) if (stack.size() < 2) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype& vchSig = stacktop(-2); valtype& vchPubKey = stacktop(-1); // Subset of script starting at the most recent codeseparator CScript scriptCode(pbegincodehash, pend); // Drop the signature, since there's no way for a signature to sign itself scriptCode.FindAndDelete(CScript(vchSig)); if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) { //serror is set return false; } bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode); popstack(stack); popstack(stack); stack.push_back(fSuccess ? vchTrue : vchFalse); if (opcode == OP_CHECKSIGVERIFY) { if (fSuccess) popstack(stack); else return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY); } } break; case OP_CHECKMULTISIG: case OP_CHECKMULTISIGVERIFY: { // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool) int i = 1; if ((int)stack.size() < i) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint(); if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG) return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT); nOpCount += nKeysCount; if (nOpCount > MAX_OPS_PER_SCRIPT) return set_error(serror, SCRIPT_ERR_OP_COUNT); int ikey = ++i; i += nKeysCount; if ((int)stack.size() < i) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint(); if (nSigsCount < 0 || nSigsCount > nKeysCount) return set_error(serror, SCRIPT_ERR_SIG_COUNT); int isig = ++i; i += nSigsCount; if ((int)stack.size() < i) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); // Subset of script starting at the most recent codeseparator CScript scriptCode(pbegincodehash, pend); // Drop the signatures, since there's no way for a signature to sign itself for (int k = 0; k < nSigsCount; k++) { valtype& vchSig = stacktop(-isig-k); scriptCode.FindAndDelete(CScript(vchSig)); } bool fSuccess = true; while (fSuccess && nSigsCount > 0) { valtype& vchSig = stacktop(-isig); valtype& vchPubKey = stacktop(-ikey); // Note how this makes the exact order of pubkey/signature evaluation // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set. // See the script_(in)valid tests for details. if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) { // serror is set return false; } // Check signature bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode); if (fOk) { isig++; nSigsCount--; } ikey++; nKeysCount--; // If there are more signatures left than keys left, // then too many signatures have failed. Exit early, // without checking any further signatures. if (nSigsCount > nKeysCount) fSuccess = false; } // Clean up stack of actual arguments while (i-- > 1) popstack(stack); // A bug causes CHECKMULTISIG to consume one extra argument // whose contents were not checked in any way. // // Unfortunately this is a potential source of mutability, // so optionally verify it is exactly equal to zero prior // to removing it from the stack. if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size()) return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY); popstack(stack); stack.push_back(fSuccess ? vchTrue : vchFalse); if (opcode == OP_CHECKMULTISIGVERIFY) { if (fSuccess) popstack(stack); else return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY); } } break; default: return set_error(serror, SCRIPT_ERR_BAD_OPCODE); } // Size limits if (stack.size() + altstack.size() > 1000) return set_error(serror, SCRIPT_ERR_STACK_SIZE); } } catch (...) { return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); } if (!vfExec.empty()) return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); return set_success(serror); } namespace { /** * Wrapper that serializes like CTransaction, but with the modifications * required for the signature hash done in-place */ class CTransactionSignatureSerializer { private: const CTransaction &txTo; //! reference to the spending transaction (the one being serialized) const CScript &scriptCode; //! output script being consumed const unsigned int nIn; //! input index of txTo being signed const bool fAnyoneCanPay; //! whether the hashtype has the SIGHASH_ANYONECANPAY flag set const bool fHashSingle; //! whether the hashtype is SIGHASH_SINGLE const bool fHashNone; //! whether the hashtype is SIGHASH_NONE public: CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) : txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn), fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)), fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE), fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {} /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */ template<typename S> void SerializeScriptCode(S &s, int nType, int nVersion) const { CScript::const_iterator it = scriptCode.begin(); CScript::const_iterator itBegin = it; opcodetype opcode; unsigned int nCodeSeparators = 0; while (scriptCode.GetOp(it, opcode)) { if (opcode == OP_CODESEPARATOR) nCodeSeparators++; } ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators); it = itBegin; while (scriptCode.GetOp(it, opcode)) { if (opcode == OP_CODESEPARATOR) { s.write((char*)&itBegin[0], it-itBegin-1); itBegin = it; } } if (itBegin != scriptCode.end()) s.write((char*)&itBegin[0], it-itBegin); } /** Serialize an input of txTo */ template<typename S> void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const { // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized if (fAnyoneCanPay) nInput = nIn; // Serialize the prevout ::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion); // Serialize the script if (nInput != nIn) // Blank out other inputs' signatures ::Serialize(s, CScriptBase(), nType, nVersion); else SerializeScriptCode(s, nType, nVersion); // Serialize the nSequence if (nInput != nIn && (fHashSingle || fHashNone)) // let the others update at will ::Serialize(s, (int)0, nType, nVersion); else ::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion); } /** Serialize an output of txTo */ template<typename S> void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const { if (fHashSingle && nOutput != nIn) // Do not lock-in the txout payee at other indices as txin ::Serialize(s, CTxOut(), nType, nVersion); else ::Serialize(s, txTo.vout[nOutput], nType, nVersion); } /** Serialize txTo */ template<typename S> void Serialize(S &s, int nType, int nVersion) const { // Serialize nVersion ::Serialize(s, txTo.nVersion, nType, nVersion); // Serialize vin unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size(); ::WriteCompactSize(s, nInputs); for (unsigned int nInput = 0; nInput < nInputs; nInput++) SerializeInput(s, nInput, nType, nVersion); // Serialize vout unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size()); ::WriteCompactSize(s, nOutputs); for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++) SerializeOutput(s, nOutput, nType, nVersion); // Serialize nLockTime ::Serialize(s, txTo.nLockTime, nType, nVersion); } }; } // anon namespace uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001")); if (nIn >= txTo.vin.size()) { // nIn out of range return one; } // Check for invalid use of SIGHASH_SINGLE if ((nHashType & 0x1f) == SIGHASH_SINGLE) { if (nIn >= txTo.vout.size()) { // nOut out of range return one; } } // Wrapper to serialize only the necessary parts of the transaction being signed CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType); // Serialize and hash CHashWriter ss(SER_GETHASH, 0); ss << txTmp << nHashType; return ss.GetHash(); } bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const { return pubkey.Verify(sighash, vchSig); } bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey, const CScript& scriptCode) const { CPubKey pubkey(vchPubKey); if (!pubkey.IsValid()) return false; // Hash type is one byte tacked on to the end of the signature vector<unsigned char> vchSig(vchSigIn); if (vchSig.empty()) return false; int nHashType = vchSig.back(); vchSig.pop_back(); uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType); if (!VerifySignature(vchSig, pubkey, sighash)) return false; return true; } bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const { // There are two kinds of nLockTime: lock-by-blockheight // and lock-by-blocktime, distinguished by whether // nLockTime < LOCKTIME_THRESHOLD. // // We want to compare apples to apples, so fail the script // unless the type of nLockTime being tested is the same as // the nLockTime in the transaction. if (!( (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) || (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD) )) return false; // Now that we know we're comparing apples-to-apples, the // comparison is a simple numeric one. if (nLockTime > (int64_t)txTo->nLockTime) return false; // Finally the nLockTime feature can be disabled and thus // CHECKLOCKTIMEVERIFY bypassed if every txin has been // finalized by setting nSequence to maxint. The // transaction would be allowed into the blockchain, making // the opcode ineffective. // // Testing if this vin is not final is sufficient to // prevent this condition. Alternatively we could test all // inputs, but testing just this input minimizes the data // required to prove correct CHECKLOCKTIMEVERIFY execution. if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence) return false; return true; } bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const { // Relative lock times are supported by comparing the passed // in operand to the sequence number of the input. const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence; // Fail if the transaction's version number is not set high // enough to trigger BIP 68 rules. if (static_cast<uint32_t>(txTo->nVersion) < 2) return false; // Sequence numbers with their most significant bit set are not // consensus constrained. Testing that the transaction's sequence // number do not have this bit set prevents using this property // to get around a CHECKSEQUENCEVERIFY check. if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) return false; // Mask off any bits that do not have consensus-enforced meaning // before doing the integer comparisons const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK; const int64_t txToSequenceMasked = txToSequence & nLockTimeMask; const CScriptNum nSequenceMasked = nSequence & nLockTimeMask; // There are two kinds of nSequence: lock-by-blockheight // and lock-by-blocktime, distinguished by whether // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG. // // We want to compare apples to apples, so fail the script // unless the type of nSequenceMasked being tested is the same as // the nSequenceMasked in the transaction. if (!( (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) || (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) )) { return false; } // Now that we know we're comparing apples-to-apples, the // comparison is a simple numeric one. if (nSequenceMasked > txToSequenceMasked) return false; return true; } bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) { set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) { return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY); } vector<vector<unsigned char> > stack, stackCopy; if (!EvalScript(stack, scriptSig, flags, checker, serror)) // serror is set return false; if (flags & SCRIPT_VERIFY_P2SH) stackCopy = stack; if (!EvalScript(stack, scriptPubKey, flags, checker, serror)) // serror is set return false; if (stack.empty()) return set_error(serror, SCRIPT_ERR_EVAL_FALSE); if (CastToBool(stack.back()) == false) return set_error(serror, SCRIPT_ERR_EVAL_FALSE); // Additional validation for spend-to-script-hash transactions: if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash()) { // scriptSig must be literals-only or validation fails if (!scriptSig.IsPushOnly()) return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY); // Restore stack. swap(stack, stackCopy); // stack cannot be empty here, because if it was the // P2SH HASH <> EQUAL scriptPubKey would be evaluated with // an empty stack and the EvalScript above would return false. assert(!stack.empty()); const valtype& pubKeySerialized = stack.back(); CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end()); popstack(stack); if (!EvalScript(stack, pubKey2, flags, checker, serror)) // serror is set return false; if (stack.empty()) return set_error(serror, SCRIPT_ERR_EVAL_FALSE); if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE); } // The CLEANSTACK check is only performed after potential P2SH evaluation, // as the non-P2SH evaluation of a P2SH script will obviously not result in // a clean stack (the P2SH inputs remain). if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) { // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK // would be possible, which is not a softfork (and P2SH should be one). assert((flags & SCRIPT_VERIFY_P2SH) != 0); if (stack.size() != 1) { return set_error(serror, SCRIPT_ERR_CLEANSTACK); } } return set_success(serror); }
/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ // // This file implements FunctionGroup, FunctionGroupAnalysis and // FunctionGroupPass. See FunctionGroup.h for more details. // // The FunctionGroupPass part was adapted from CallGraphSCCPass.cpp. // // This file is currently in lib/Target/GenX, as that is the only place it // is used. It could be moved somewhere more general. // //===----------------------------------------------------------------------===// #include "FunctionGroup.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/GenXIntrinsics/GenXMetadata.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/ValueMapper.h" using namespace llvm; #include "llvmWrapper/IR/LegacyPassManagers.h" #include "llvmWrapper/IR/PassTimingInfo.h" #include "Probe/Assertion.h" #define DEBUG_TYPE "functiongroup-passmgr" /*********************************************************************** * FunctionGroupAnalysis implementation */ char FunctionGroupAnalysis::ID = 0; INITIALIZE_PASS(FunctionGroupAnalysis, "FunctionGroupAnalysis", "FunctionGroupAnalysis", false, true /*analysis*/) ModulePass *llvm::createFunctionGroupAnalysisPass() { initializeFunctionGroupAnalysisPass(*PassRegistry::getPassRegistry()); return new FunctionGroupAnalysis(); } // clear : clear out the analysis void FunctionGroupAnalysis::clear() { for (auto T : TypesToProcess) GroupMap[T].clear(); for (auto i = begin(), e = end(); i != e; ++i) delete *i; for (auto i = NonMainGroups.begin(), e = NonMainGroups.end(); i != e; ++i) delete *i; Groups.clear(); NonMainGroups.clear(); M = nullptr; } FunctionGroup *FunctionGroupAnalysis::getGroup(const Function *F, FGType Type) const { auto i = GroupMap[Type].find(F); if (i == GroupMap[Type].end()) return nullptr; return i->second; } // getGroup : get the FunctionGroup containing Function F, else 0 FunctionGroup *FunctionGroupAnalysis::getGroup(const Function *F) const { return getGroup(F, FGType::GROUP); } FunctionGroup *FunctionGroupAnalysis::getSubGroup(const Function *F) const { return getGroup(F, FGType::SUBGROUP); } // getGroupForHead : get the FunctionGroup for which Function F is the // head, else 0 FunctionGroup *FunctionGroupAnalysis::getGroupForHead(const Function *F) const { auto *FG = getGroup(F); IGC_ASSERT(FG->size()); if (*FG->begin() == F) return FG; return nullptr; } // replaceFunction : replace a Function in a FunctionGroup // An in-use iterator in the modified FunctionGroup remains valid. void FunctionGroupAnalysis::replaceFunction(Function *OldF, Function *NewF) { for (auto T : TypesToProcess) { auto OldFIt = GroupMap[T].find(OldF); IGC_ASSERT(OldFIt != GroupMap[T].end()); FunctionGroup *FG = OldFIt->second; GroupMap[T].erase(OldFIt); GroupMap[T][NewF] = FG; for (auto i = FG->begin();; ++i) { IGC_ASSERT(i != FG->end()); if (*i == OldF) { *i = NewF; break; } } } } // addToFunctionGroup : add Function F to FunctionGroup FG // Using this (rather than calling push_back directly on the FunctionGroup) // means that the mapping from F to FG will be created, and getGroup() will // work for this Function. void FunctionGroupAnalysis::addToFunctionGroup(FunctionGroup *FG, Function *F, FGType Type) { IGC_ASSERT(FG); IGC_ASSERT_MESSAGE(FG->getParent()->getModule() == M, "attaching to FunctionGroup from wrong Module"); IGC_ASSERT_MESSAGE(!GroupMap[Type][F], "Function already attached to FunctionGroup"); GroupMap[Type][F] = FG; FG->push_back(F); } // createFunctionGroup : create new FunctionGroup for which F is the head FunctionGroup *FunctionGroupAnalysis::createFunctionGroup(Function *F, FGType Type) { auto FG = new FunctionGroup(this); if (Type == FGType::GROUP) Groups.push_back(FG); else NonMainGroups.push_back(FG); addToFunctionGroup(FG, F, Type); return FG; } // Returns true if pass is simple module pass, // e.g. it is neither FG pass nor function pass manager. static bool isModulePass(Pass *P) { if (P->getPassKind() != PT_Module) return false; return !P->getAsPMDataManager(); } static StringRef TypeToAttr(FunctionGroupAnalysis::FGType Type) { switch (Type) { case FunctionGroupAnalysis::FGType::GROUP: return genx::FunctionMD::CMGenXMain; case FunctionGroupAnalysis::FGType::SUBGROUP: return genx::FunctionMD::CMStackCall; default: IGC_ASSERT_EXIT_MESSAGE(0, "Can't gen attribute for nox-existent FG type"); break; } return ""; } bool FunctionGroupAnalysis::buildGroup(CallGraph &Callees, Function *F, FunctionGroup *curGr, FGType Type) { bool result = false; LLVM_DEBUG(dbgs() << "process function " << F->getName() << " from " << curGr << ", type = " << Type << "\n"); if (Visited.count(F) > 0) { if (GroupMap[Type].count(F) > 0 && GroupMap[Type][F] != curGr && !F->hasFnAttribute(TypeToAttr(Type))) { ValueToValueMapTy VMap; Function *ClonedFunc = CloneFunction(F, VMap); LLVM_DEBUG(dbgs() << "Cloning: " << ClonedFunc->getName() << "\n"); result = true; for (auto it = F->use_begin(); it != F->use_end();) { Use *u = &*it++; auto *CI = dyn_cast<CallInst>(u->getUser()); IGC_ASSERT(CI); if (GroupMap[Type][CI->getFunction()] == curGr) *u = ClonedFunc; } for (auto T : TypesToProcess) { if (T >= Type) break; addToFunctionGroup(getGroup(F, T), ClonedFunc, T); } addToFunctionGroup(curGr, ClonedFunc, Type); for (auto &Callee : Callees[F]) { if (Callee == F) continue; LLVM_DEBUG(dbgs() << "Next callee: " << Callee->getName() << "\n"); result |= buildGroup(Callees, Callee, curGr, Type); } } } else if (!Visited.count(F)) { Visited[F] = true; // group is created either on a function with a corresponding attribute // or on a root of a whole function tree that is kernel (genx_main) if (F->hasFnAttribute(TypeToAttr(Type)) || F->hasFnAttribute(genx::FunctionMD::CMGenXMain)) { LLVM_DEBUG(dbgs() << "Create new group of type " << Type << "\n"); curGr = createFunctionGroup(F, Type); } else if (curGr) { LLVM_DEBUG(dbgs() << "Add to group " << curGr->getHead()->getName() << " of type " << Type << "\n"); addToFunctionGroup(curGr, F, Type); } for (auto &Callee : Callees[F]) { LLVM_DEBUG(dbgs() << "Next callee: " << Callee->getName() << "\n"); result |= buildGroup(Callees, Callee, curGr, Type); } } LLVM_DEBUG(dbgs() << "finish processing function " << F->getName() << " on level " << Type << "\n"); return result; } //===----------------------------------------------------------------------===// // FGPassManager // /// FGPassManager manages FPPassManagers and FunctionGroupPasses. /// It actually now imitates MPPassManager because there is no way /// to extend pass manager structure without modification of /// LLVM pass managers code. /// This pass is injected into pass manager stack instead of top-level /// MPPassManager when there is first time FunctionGroupPass is created. /// After this manager replaces MPPassManager, it handles all Module and /// FunctionGroup passes. This manager itself is module pass so it is /// actually contained in list of module passes of module pass manager /// as last pass that should be run. However, top-level pass manager do /// not know anything about this FGPassManager except that it is indirect /// pass manager, so it will not run it directly. namespace { class FGPassManager : public ModulePass, public IGCLLVM::PMDataManager { public: static char ID; explicit FGPassManager() : ModulePass(ID), IGCLLVM::PMDataManager() {} /// run - Execute all of the passes scheduled for execution. Keep track of /// whether any of the passes modifies the module, and if so, return true. bool runOnModule(Module &M) override; bool doInitialization(Module &M) override; bool doFinalization(Module &M) override; /// Pass Manager itself does not invalidate any analysis info. void getAnalysisUsage(AnalysisUsage &Info) const override { // FGPassManager needs FunctionGroupAnalysis. Info.addRequired<FunctionGroupAnalysis>(); Info.setPreservesAll(); } StringRef getPassName() const override { return "FunctionGroup Pass Manager"; } PMDataManager *getAsPMDataManager() override { return this; } Pass *getAsPass() override { return this; } // Print passes managed by this manager void dumpPassStructure(unsigned Offset) override { errs().indent(Offset * 2) << "FunctionGroup Pass Manager\n"; for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { Pass *P = getContainedPass(Index); unsigned DumpOffset = Offset + 1; // Pretend that there is no FGPassManager when we need to dump // module pass indentation. if (isModulePass(P)) DumpOffset -= 1; P->dumpPassStructure(DumpOffset); dumpLastUses(P, DumpOffset); } } Pass *getContainedPass(unsigned N) { IGC_ASSERT_MESSAGE(N < PassVector.size(), "Pass number out of range!"); return static_cast<Pass *>(PassVector[N]); } PassManagerType getPassManagerType() const override { return PMT_ModulePassManager; } private: bool runPassesOnFunctionGroup(unsigned Begin, unsigned End, FunctionGroup &FG); bool runPassOnFunctionGroup(Pass *P, FunctionGroup &FG); bool doFGInitialization(unsigned Begin, unsigned End, FunctionGroupAnalysis &FGA); bool doFGFinalization(unsigned Begin, unsigned End, FunctionGroupAnalysis &FGA); bool runFGPassSequence(unsigned &Pass); bool runModulePassSequence(unsigned &Pass, Module &M); }; } // end anonymous namespace. char FGPassManager::ID = 0; bool FGPassManager::runPassOnFunctionGroup(Pass *P, FunctionGroup &FG) { bool Changed = false; llvm::PMDataManager *PM = P->getAsPMDataManager(); if (!PM) { FunctionGroupPass *CGSP = (FunctionGroupPass *)P; { TimeRegion PassTimer(getPassTimer(CGSP)); Changed = CGSP->runOnFunctionGroup(FG); } return Changed; } // TODO: there may be also SCC pass manager. IGC_ASSERT_MESSAGE(PM->getPassManagerType() == PMT_FunctionPassManager, "Invalid FGPassManager member"); FPPassManager *FPP = (FPPassManager *)P; // Run pass P on all functions in the current FunctionGroup. for (auto &F : FG) { dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName()); { TimeRegion PassTimer(getPassTimer(FPP)); Changed |= FPP->runOnFunction(*F); } F->getContext().yield(); } return Changed; } /// RunPassesOnFunctionGroup - Execute sequential passes of pass manager /// on the specified FunctionGroup bool FGPassManager::runPassesOnFunctionGroup(unsigned Begin, unsigned End, FunctionGroup &FG) { bool Changed = false; // Run selected passes on current FunctionGroup. for (unsigned PassNo = Begin; PassNo != End; ++PassNo) { Pass *P = getContainedPass(PassNo); dumpRequiredSet(P); initializeAnalysisImpl(P); // Actually run this pass on the current FunctionGroup. Changed |= runPassOnFunctionGroup(P, FG); if (Changed) dumpPassInfo(P, MODIFICATION_MSG, ON_MODULE_MSG, ""); dumpPreservedSet(P); verifyPreservedAnalysis(P); removeNotPreservedAnalysis(P); recordAvailableAnalysis(P); removeDeadPasses(P, "", ON_MODULE_MSG); } return Changed; } /// Initialize sequential FG passes bool FGPassManager::doFGInitialization(unsigned Begin, unsigned End, FunctionGroupAnalysis &FGA) { bool Changed = false; for (unsigned i = Begin; i != End; ++i) { if (llvm::PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) { // TODO: SCC PassManager? IGC_ASSERT_MESSAGE(PM->getPassManagerType() == PMT_FunctionPassManager, "Invalid FGPassManager member"); Changed |= ((FPPassManager*)PM)->doInitialization(*FGA.getModule()); } else { Changed |= ((FunctionGroupPass *)getContainedPass(i))->doInitialization(FGA); } } return Changed; } /// Finalize sequential FG passes bool FGPassManager::doFGFinalization(unsigned Begin, unsigned End, FunctionGroupAnalysis &FGA) { bool Changed = false; for (int i = End - 1; i >= static_cast<int>(Begin); --i) { if (llvm::PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) { // TODO: SCC PassManager? IGC_ASSERT_MESSAGE(PM->getPassManagerType() == PMT_FunctionPassManager, "Invalid FGPassManager member"); Changed |= ((FPPassManager*)PM)->doFinalization(*FGA.getModule()); } else { Changed |= ((FunctionGroupPass *)getContainedPass(i))->doFinalization(FGA); } } return Changed; } bool FGPassManager::runFGPassSequence(unsigned &Pass) { const unsigned BeginPass = Pass; const unsigned NumPasses = getNumContainedPasses(); while (Pass < NumPasses && !isModulePass(getContainedPass(Pass))) ++Pass; // Function group analysis may be invalidated by previous // module passes so we will need to query it every time we // execute sequence of passes. FunctionGroupAnalysis &FGA = getAnalysis<FunctionGroupAnalysis>(); bool Changed = false; Changed |= doFGInitialization(BeginPass, Pass, FGA); for (auto *FG : FGA) Changed |= runPassesOnFunctionGroup(BeginPass, Pass, *FG); Changed |= doFGFinalization(BeginPass, Pass, FGA); return Changed; } bool FGPassManager::runModulePassSequence(unsigned &Pass, Module &M) { const unsigned BeginPass = Pass; const unsigned NumPasses = getNumContainedPasses(); while (Pass < NumPasses && isModulePass(getContainedPass(Pass))) ++Pass; bool Changed = false; // Copied from MPPassManager in LegacyPassManager.cpp. unsigned InstrCount, ModuleCount = 0; StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount; bool EmitICRemark = M.shouldEmitInstrCountChangedRemark(); // Collect the initial size of the module. if (EmitICRemark) { InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount); ModuleCount = InstrCount; } for (unsigned Index = BeginPass; Index < Pass; ++Index) { auto *MP = static_cast<ModulePass *>(getContainedPass(Index)); bool LocalChanged = false; dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier()); dumpRequiredSet(MP); initializeAnalysisImpl(MP); { PassManagerPrettyStackEntry X(MP, M); TimeRegion PassTimer(getPassTimer(MP)); LocalChanged |= MP->runOnModule(M); if (EmitICRemark) { // Update the size of the module. ModuleCount = M.getInstructionCount(); if (ModuleCount != InstrCount) { int64_t Delta = static_cast<int64_t>(ModuleCount) - static_cast<int64_t>(InstrCount); emitInstrCountChangedRemark(MP, M, Delta, InstrCount, FunctionToInstrCount); InstrCount = ModuleCount; } } } Changed |= LocalChanged; if (LocalChanged) dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG, M.getModuleIdentifier()); dumpPreservedSet(MP); dumpUsedSet(MP); verifyPreservedAnalysis(MP); removeNotPreservedAnalysis(MP); recordAvailableAnalysis(MP); removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG); } return Changed; } /// run - Execute all of the passes scheduled for execution. Keep track of /// whether any of the passes modifies the module, and if so, return true. bool FGPassManager::runOnModule(Module &M) { bool Changed = false; unsigned CurPass = 0; unsigned NumPasses = getNumContainedPasses(); while (CurPass != NumPasses) { // We will always have chain of fg passes followed by // module passes repeating until there are no passes. Changed |= runFGPassSequence(CurPass); Changed |= runModulePassSequence(CurPass, M); } return Changed; } bool FGPassManager::doInitialization(Module &M) { bool Changed = false; // Initialize module passes for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { auto *P = getContainedPass(Index); if (isModulePass(P)) Changed |= P->doInitialization(M); } return Changed; } bool FGPassManager::doFinalization(Module &M) { bool Changed = false; // Finalize module passes for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index) { auto *P = getContainedPass(Index); if (isModulePass(P)) Changed |= P->doFinalization(M); } return Changed; } //===----------------------------------------------------------------------===// // FunctionGroupPass Implementation //===----------------------------------------------------------------------===// /// Assign pass manager to manage this pass. void FunctionGroupPass::assignPassManager(PMStack &PMS, PassManagerType PreferredType) { // Find module pass manager. while (!PMS.empty() && PMS.top()->getPassManagerType() > PMT_ModulePassManager) PMS.pop(); IGC_ASSERT_MESSAGE(!PMS.empty(), "Unable to handle FunctionGroup Pass"); FGPassManager *GFP; // Check whether this ModulePassManager is our injected function // group pass manager. If not, replace old module pass manager // with one for function groups. auto *PM = PMS.top(); IGC_ASSERT_MESSAGE(PM->getPassManagerType() == PMT_ModulePassManager, "Bad pass manager type for function group pass manager"); if (PM->getAsPass()->getPassID() == &FGPassManager::ID) GFP = static_cast<FGPassManager *>(PM); else { // Create new FunctionGroup Pass Manager if it does not exist. // [1] Create new FunctionGroup Pass Manager GFP = new FGPassManager(); // [2] Set up new manager's top level manager PMTopLevelManager *TPM = PM->getTopLevelManager(); TPM->addIndirectPassManager(GFP); GFP->setTopLevelManager(TPM); // [3] Assign manager to manage this new manager. This should not create // and push new managers into PMS TPM->schedulePass(GFP); IGC_ASSERT_MESSAGE(PMS.top() == PM, "Pass manager unexpectedly changed"); // [4] Steal analysis info from module pass manager. *GFP->getAvailableAnalysis() = std::move(*PM->getAvailableAnalysis()); // [5] Replace module pass manager with function group pass manager. PMS.pop(); PMS.push(GFP); } GFP->add(this); } /// getAnalysisUsage - For this class, we declare that we require and preserve /// FunctionGroupAnalysis. If the derived class implements this method, it /// should always explicitly call the implementation here. void FunctionGroupPass::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<FunctionGroupAnalysis>(); AU.addPreserved<FunctionGroupAnalysis>(); } //===----------------------------------------------------------------------===// // PrintFunctionGroupPass Implementation //===----------------------------------------------------------------------===// namespace { /// PrintFunctionGroupPass - Print a FunctionGroup /// class PrintFunctionGroupPass : public FunctionGroupPass { std::string Banner; raw_ostream &Out; // raw_ostream to print on. public: static char ID; PrintFunctionGroupPass(const std::string &B, raw_ostream &o) : FunctionGroupPass(ID), Banner(B), Out(o) {} void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); } bool runOnFunctionGroup(FunctionGroup &FG) override { Out << Banner; for (auto I = FG.begin(), E = FG.end(); I != E; ++I) { Function *F = *I; Out << Banner << static_cast<Value &>(*F); } return false; } }; } // end anonymous namespace. char PrintFunctionGroupPass::ID = 0; Pass *FunctionGroupPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return new PrintFunctionGroupPass(Banner, O); } //===----------------------------------------------------------------------===// // DominatorTreeGroupWrapperPass Implementation //===----------------------------------------------------------------------===// // // The implementation details of the wrapper pass that holds a DominatorTree // per Function in a FunctionGroup. // //===----------------------------------------------------------------------===// char DominatorTreeGroupWrapperPass::ID = 0; INITIALIZE_PASS_BEGIN(DominatorTreeGroupWrapperPass, "groupdomtree", "Group Dominator Tree Construction", true, true) INITIALIZE_PASS_END(DominatorTreeGroupWrapperPass, "groupdomtree", "Group Dominator Tree Construction", true, true) void DominatorTreeGroupWrapperPass::releaseMemory() { for (auto i = DTs.begin(), e = DTs.end(); i != e; ++i) delete i->second; DTs.clear(); } bool DominatorTreeGroupWrapperPass::runOnFunctionGroup(FunctionGroup &FG) { for (auto fgi = FG.begin(), fge = FG.end(); fgi != fge; ++fgi) { Function *F = *fgi; auto DT = new DominatorTree; DT->recalculate(*F); DTs[F] = DT; } return false; } void DominatorTreeGroupWrapperPass::verifyAnalysis() const { for (auto i = DTs.begin(), e = DTs.end(); i != e; ++i) i->second->verify(); } void DominatorTreeGroupWrapperPass::print(raw_ostream &OS, const Module *) const { for (auto i = DTs.begin(), e = DTs.end(); i != e; ++i) i->second->print(OS); } //===----------------------------------------------------------------------===// // LoopInfoGroupWrapperPass Implementation //===----------------------------------------------------------------------===// // // The implementation details of the wrapper pass that holds a LoopInfo // per Function in a FunctionGroup. // //===----------------------------------------------------------------------===// char LoopInfoGroupWrapperPass::ID = 0; INITIALIZE_PASS_BEGIN(LoopInfoGroupWrapperPass, "grouploopinfo", "Group Loop Info Construction", true, true) INITIALIZE_PASS_DEPENDENCY(DominatorTreeGroupWrapperPass) INITIALIZE_PASS_END(LoopInfoGroupWrapperPass, "grouploopinfo", "Group Loop Info Construction", true, true) void LoopInfoGroupWrapperPass::releaseMemory() { for (auto i = LIs.begin(), e = LIs.end(); i != e; ++i) delete i->second; LIs.clear(); } bool LoopInfoGroupWrapperPass::runOnFunctionGroup(FunctionGroup &FG) { auto &DTs = getAnalysis<DominatorTreeGroupWrapperPass>(); for (auto fgi = FG.begin(), fge = FG.end(); fgi != fge; ++fgi) { Function *F = *fgi; auto LI = new LoopInfo; LI->analyze(*DTs.getDomTree(F)); LIs[F] = LI; } return false; } void LoopInfoGroupWrapperPass::verifyAnalysis() const { auto &DTs = getAnalysis<DominatorTreeGroupWrapperPass>(); for (auto i = LIs.begin(), e = LIs.end(); i != e; ++i) i->second->verify(*DTs.getDomTree(i->first)); } void LoopInfoGroupWrapperPass::print(raw_ostream &OS, const Module *) const { for (auto i = LIs.begin(), e = LIs.end(); i != e; ++i) i->second->print(OS); }
/* * Simd Library (http://ermig1979.github.io/Simd). * * Copyright (c) 2011-2019 Yermalayeu Ihar. * * 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 "Simd/SimdStore.h" #include "Simd/SimdMemory.h" #include "Simd/SimdExtract.h" #include "Simd/SimdCpu.h" namespace Simd { #if defined(SIMD_NEON_ENABLE) && defined(SIMD_NEON_FP16_ENABLE) namespace Neon { template<bool align> SIMD_INLINE void Float32ToFloat16(const float * src, uint16_t * dst) { Store<align>(dst, (uint16x4_t)vcvt_f16_f32(Load<align>(src))); } template <bool align> void Float32ToFloat16(const float * src, size_t size, uint16_t * dst) { assert(size >= F); if (align) assert(Aligned(src) && Aligned(dst)); size_t fullAlignedSize = Simd::AlignLo(size, QF); size_t partialAlignedSize = Simd::AlignLo(size, F); size_t i = 0; for (; i < fullAlignedSize; i += QF) { Float32ToFloat16<align>(src + i + F * 0, dst + i + F * 0); Float32ToFloat16<align>(src + i + F * 1, dst + i + F * 1); Float32ToFloat16<align>(src + i + F * 2, dst + i + F * 2); Float32ToFloat16<align>(src + i + F * 3, dst + i + F * 3); } for (; i < partialAlignedSize; i += F) Float32ToFloat16<align>(src + i, dst + i); if (partialAlignedSize != size) Float32ToFloat16<false>(src + size - F, dst + size - F); } void Float32ToFloat16(const float * src, size_t size, uint16_t * dst) { if (Aligned(src) && Aligned(dst)) Float32ToFloat16<true>(src, size, dst); else Float32ToFloat16<false>(src, size, dst); } template<bool align> SIMD_INLINE void Float16ToFloat32(const uint16_t * src, float * dst) { Store<align>(dst, vcvt_f32_f16((float16x4_t)LoadHalf<align>(src))); } template <bool align> void Float16ToFloat32(const uint16_t * src, size_t size, float * dst) { assert(size >= F); if (align) assert(Aligned(src) && Aligned(dst)); size_t fullAlignedSize = Simd::AlignLo(size, QF); size_t partialAlignedSize = Simd::AlignLo(size, F); size_t i = 0; for (; i < fullAlignedSize; i += QF) { Float16ToFloat32<align>(src + i + F * 0, dst + i + F * 0); Float16ToFloat32<align>(src + i + F * 1, dst + i + F * 1); Float16ToFloat32<align>(src + i + F * 2, dst + i + F * 2); Float16ToFloat32<align>(src + i + F * 3, dst + i + F * 3); } for (; i < partialAlignedSize; i += F) Float16ToFloat32<align>(src + i, dst + i); if (partialAlignedSize != size) Float16ToFloat32<false>(src + size - F, dst + size - F); } void Float16ToFloat32(const uint16_t * src, size_t size, float * dst) { if (Aligned(src) && Aligned(dst)) Float16ToFloat32<true>(src, size, dst); else Float16ToFloat32<false>(src, size, dst); } template <bool align> SIMD_INLINE void SquaredDifferenceSum16f(const uint16_t * a, const uint16_t * b, size_t offset, float32x4_t & sum) { float32x4_t _a = vcvt_f32_f16((float16x4_t)LoadHalf<align>(a + offset)); float32x4_t _b = vcvt_f32_f16((float16x4_t)LoadHalf<align>(b + offset)); float32x4_t _d = vsubq_f32(_a, _b); sum = vmlaq_f32(sum, _d, _d); } template <bool align> SIMD_INLINE void SquaredDifferenceSum16f(const uint16_t * a, const uint16_t * b, size_t size, float * sum) { assert(size >= F); if (align) assert(Aligned(a) && Aligned(b)); size_t partialAlignedSize = AlignLo(size, F); size_t fullAlignedSize = AlignLo(size, DF); size_t i = 0; float32x4_t sums[2] = { vdupq_n_f32(0), vdupq_n_f32(0) }; if (fullAlignedSize) { for (; i < fullAlignedSize; i += DF) { SquaredDifferenceSum16f<align>(a, b, i + F * 0, sums[0]); SquaredDifferenceSum16f<align>(a, b, i + F * 1, sums[1]); } sums[0] = vaddq_f32(sums[0], sums[1]); } for (; i < partialAlignedSize; i += F) SquaredDifferenceSum16f<align>(a, b, i, sums[0]); if (partialAlignedSize != size) { float32x4_t tailMask = RightNotZero(size - partialAlignedSize); float32x4_t _a = vcvt_f32_f16((float16x4_t)LoadHalf<false>(a + size - F)); float32x4_t _b = vcvt_f32_f16((float16x4_t)LoadHalf<false>(a + size - F)); float32x4_t _d = And(vsubq_f32(_a, _b), tailMask); sums[0] = vaddq_f32(sums[0], vmulq_f32(_d, _d)); } *sum = ExtractSum32f(sums[0]); } void SquaredDifferenceSum16f(const uint16_t * a, const uint16_t * b, size_t size, float * sum) { if (Aligned(a) && Aligned(b)) SquaredDifferenceSum16f<true>(a, b, size, sum); else SquaredDifferenceSum16f<false>(a, b, size, sum); } template<bool align> void CosineDistance16f(const uint16_t * a, const uint16_t * b, size_t size, float * distance) { if (align) assert(Aligned(a) && Aligned(b)); size_t partialAlignedSize = AlignLo(size, F); size_t fullAlignedSize = AlignLo(size, DF); size_t i = 0; float32x4_t _aa[2] = { vdupq_n_f32(0), vdupq_n_f32(0) }; float32x4_t _ab[2] = { vdupq_n_f32(0), vdupq_n_f32(0) }; float32x4_t _bb[2] = { vdupq_n_f32(0), vdupq_n_f32(0) }; if (fullAlignedSize) { for (; i < fullAlignedSize; i += DF) { float32x4_t a0 = vcvt_f32_f16((float16x4_t)LoadHalf<align>(a + i + 0)); float32x4_t b0 = vcvt_f32_f16((float16x4_t)LoadHalf<align>(b + i + 0)); _aa[0] = vmlaq_f32(_aa[0], a0, a0); _ab[0] = vmlaq_f32(_ab[0], a0, b0); _bb[0] = vmlaq_f32(_bb[0], b0, b0); float32x4_t a1 = vcvt_f32_f16((float16x4_t)LoadHalf<align>(a + i + F)); float32x4_t b1 = vcvt_f32_f16((float16x4_t)LoadHalf<align>(b + i + F)); _aa[1] = vmlaq_f32(_aa[1], a1, a1); _ab[1] = vmlaq_f32(_ab[1], a1, b1); _bb[1] = vmlaq_f32(_bb[1], b1, b1); } _aa[0] = vaddq_f32(_aa[0], _aa[1]); _ab[0] = vaddq_f32(_ab[0], _ab[1]); _bb[0] = vaddq_f32(_bb[0], _bb[1]); } for (; i < partialAlignedSize; i += F) { float32x4_t a0 = vcvt_f32_f16((float16x4_t)LoadHalf<align>(a + i + 0)); float32x4_t b0 = vcvt_f32_f16((float16x4_t)LoadHalf<align>(b + i + 0)); _aa[0] = vmlaq_f32(_aa[0], a0, a0); _ab[0] = vmlaq_f32(_ab[0], a0, b0); _bb[0] = vmlaq_f32(_bb[0], b0, b0); } if (partialAlignedSize != size) { float32x4_t tailMask = RightNotZero(size - partialAlignedSize); float32x4_t a0 = And(vcvt_f32_f16((float16x4_t)LoadHalf<align>(a + i + 0)), tailMask); float32x4_t b0 = And(vcvt_f32_f16((float16x4_t)LoadHalf<align>(b + i + 0)), tailMask); _aa[0] = vmlaq_f32(_aa[0], a0, a0); _ab[0] = vmlaq_f32(_ab[0], a0, b0); _bb[0] = vmlaq_f32(_bb[0], b0, b0); } float aa = ExtractSum32f(_aa[0]), ab = ExtractSum32f(_ab[0]), bb = ExtractSum32f(_bb[0]); *distance = 1.0f - ab / ::sqrt(aa*bb); } void CosineDistance16f(const uint16_t * a, const uint16_t * b, size_t size, float * distance) { if (Aligned(a) && Aligned(b)) CosineDistance16f<true>(a, b, size, distance); else CosineDistance16f<false>(a, b, size, distance); } SIMD_INLINE float32x4_t Tail(size_t tail) { const int32_t mask[DF] = { 0, 0, 0, 0, -1, -1, -1, -1 }; return Load<false>((float*)(mask + tail)); } static void Squares(size_t M, size_t K, const uint16_t * const * A, float * squares) { size_t M4 = AlignLo(M, 4); size_t KF = AlignLo(K, F); float32x4_t mask = Tail(K - KF); size_t i = 0; for (; i < M4; i += 4) { float32x4_t sums[4] = { vdupq_n_f32(0.0f), vdupq_n_f32(0.0f), vdupq_n_f32(0.0f), vdupq_n_f32(0.0f) }; for (size_t k = 0; k < KF; k += F) { float32x4_t a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i + 0] + k))); float32x4_t a1 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i + 1] + k))); float32x4_t a2 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i + 2] + k))); float32x4_t a3 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i + 3] + k))); sums[0] = vmlaq_f32(sums[0], a0, a0); sums[1] = vmlaq_f32(sums[1], a1, a1); sums[2] = vmlaq_f32(sums[2], a2, a2); sums[3] = vmlaq_f32(sums[3], a3, a3); } if (KF < K) { size_t k = K - F; float32x4_t a0 = And(mask, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i + 0] + k)))); float32x4_t a1 = And(mask, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i + 1] + k)))); float32x4_t a2 = And(mask, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i + 2] + k)))); float32x4_t a3 = And(mask, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i + 3] + k)))); sums[0] = vmlaq_f32(sums[0], a0, a0); sums[1] = vmlaq_f32(sums[1], a1, a1); sums[2] = vmlaq_f32(sums[2], a2, a2); sums[3] = vmlaq_f32(sums[3], a3, a3); } Store<false>(squares + i, Extract4Sums(sums)); } for (; i < M; i += 1) { float32x4_t sum = vdupq_n_f32(0.0f); for (size_t k = 0; k < KF; k += F) { float32x4_t a = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i] + k))); sum = vmlaq_f32(sum, a, a); } if (KF < K) { size_t k = K - F; float32x4_t a = And(mask, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[i] + k)))); sum = vmlaq_f32(sum, a, a); } squares[i] = ExtractSum32f(sum); } } static void MicroCosineDistances3x4(size_t K, const uint16_t * const * A, const uint16_t * const * B, const float * aa, const float * bb, float * distances, size_t stride) { size_t K4 = K & (~3); float32x4_t c00 = vdupq_n_f32(0.0f); float32x4_t c01 = vdupq_n_f32(0.0f); float32x4_t c02 = vdupq_n_f32(0.0f); float32x4_t c03 = vdupq_n_f32(0.0f); float32x4_t c10 = vdupq_n_f32(0.0f); float32x4_t c11 = vdupq_n_f32(0.0f); float32x4_t c12 = vdupq_n_f32(0.0f); float32x4_t c13 = vdupq_n_f32(0.0f); float32x4_t c20 = vdupq_n_f32(0.0f); float32x4_t c21 = vdupq_n_f32(0.0f); float32x4_t c22 = vdupq_n_f32(0.0f); float32x4_t c23 = vdupq_n_f32(0.0f); float32x4_t a0, a1, a2, b0; for (size_t k = 0; k < K4; k += 4) { a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[0] + k))); a1 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[1] + k))); a2 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[2] + k))); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[0] + k))); c00 = vmlaq_f32(c00, a0, b0); c10 = vmlaq_f32(c10, a1, b0); c20 = vmlaq_f32(c20, a2, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[1] + k))); c01 = vmlaq_f32(c01, a0, b0); c11 = vmlaq_f32(c11, a1, b0); c21 = vmlaq_f32(c21, a2, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[2] + k))); c02 = vmlaq_f32(c02, a0, b0); c12 = vmlaq_f32(c12, a1, b0); c22 = vmlaq_f32(c22, a2, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[3] + k))); c03 = vmlaq_f32(c03, a0, b0); c13 = vmlaq_f32(c13, a1, b0); c23 = vmlaq_f32(c23, a2, b0); } if (K4 < K) { size_t k = K - 4; float32x4_t tail = Tail(K - K4); a0 = And(tail, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[0] + k)))); a1 = And(tail, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[1] + k)))); a2 = And(tail, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[2] + k)))); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[0] + k))); c00 = vmlaq_f32(c00, a0, b0); c10 = vmlaq_f32(c10, a1, b0); c20 = vmlaq_f32(c20, a2, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[1] + k))); c01 = vmlaq_f32(c01, a0, b0); c11 = vmlaq_f32(c11, a1, b0); c21 = vmlaq_f32(c21, a2, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[2] + k))); c02 = vmlaq_f32(c02, a0, b0); c12 = vmlaq_f32(c12, a1, b0); c22 = vmlaq_f32(c22, a2, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[3] + k))); c03 = vmlaq_f32(c03, a0, b0); c13 = vmlaq_f32(c13, a1, b0); c23 = vmlaq_f32(c23, a2, b0); } float32x4_t _bb = Load<false>(bb); float32x4_t _1 = vdupq_n_f32(1.0f); Store<false>(distances + 0 * stride, vmlsq_f32(_1, ReciprocalSqrt<1>(vmulq_f32(_bb, vdupq_n_f32(aa[0]))), Extract4Sums(c00, c01, c02, c03))); Store<false>(distances + 1 * stride, vmlsq_f32(_1, ReciprocalSqrt<1>(vmulq_f32(_bb, vdupq_n_f32(aa[1]))), Extract4Sums(c10, c11, c12, c13))); Store<false>(distances + 2 * stride, vmlsq_f32(_1, ReciprocalSqrt<1>(vmulq_f32(_bb, vdupq_n_f32(aa[2]))), Extract4Sums(c20, c21, c22, c23))); } static void MicroCosineDistances3x1(size_t K, const uint16_t * const * A, const uint16_t * const * B, const float * aa, const float * bb, float * distances, size_t stride) { size_t K4 = K & (~3); float32x4_t c00 = vdupq_n_f32(0.0f); float32x4_t c10 = vdupq_n_f32(0.0f); float32x4_t c20 = vdupq_n_f32(0.0f); float32x4_t a0, b0; for (size_t k = 0; k < K4; k += 4) { b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[0] + k))); a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[0] + k))); c00 = vmlaq_f32(c00, a0, b0); a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[1] + k))); c10 = vmlaq_f32(c10, a0, b0); a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[2] + k))); c20 = vmlaq_f32(c20, a0, b0); } if (K4 < K) { size_t k = K - 4; float32x4_t tail = Tail(K - K4); b0 = And(tail, vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[0] + k)))); a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[0] + k))); c00 = vmlaq_f32(c00, a0, b0); a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[1] + k))); c10 = vmlaq_f32(c10, a0, b0); a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[2] + k))); c20 = vmlaq_f32(c20, a0, b0); } distances[0 * stride] = 1.0f - ExtractSum32f(c00) / sqrt(bb[0] * aa[0]); distances[1 * stride] = 1.0f - ExtractSum32f(c10) / sqrt(bb[0] * aa[1]); distances[2 * stride] = 1.0f - ExtractSum32f(c20) / sqrt(bb[0] * aa[2]); } static void MicroCosineDistances1x4(size_t K, const uint16_t * const * A, const uint16_t * const * B, const float * aa, const float * bb, float * distances, size_t stride) { size_t K4 = K & (~3); float32x4_t c00 = vdupq_n_f32(0.0f); float32x4_t c01 = vdupq_n_f32(0.0f); float32x4_t c02 = vdupq_n_f32(0.0f); float32x4_t c03 = vdupq_n_f32(0.0f); float32x4_t a0, b0; for (size_t k = 0; k < K4; k += 4) { a0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[0] + k))); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[0] + k))); c00 = vmlaq_f32(c00, a0, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[1] + k))); c01 = vmlaq_f32(c01, a0, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[2] + k))); c02 = vmlaq_f32(c02, a0, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[3] + k))); c03 = vmlaq_f32(c03, a0, b0); } if (K4 < K) { size_t k = K - 4; float32x4_t tail = Tail(K - K4); a0 = And(tail, vcvt_f32_f16((float16x4_t)LoadHalf<false>((A[0] + k)))); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[0] + k))); c00 = vmlaq_f32(c00, a0, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[1] + k))); c01 = vmlaq_f32(c01, a0, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[2] + k))); c02 = vmlaq_f32(c02, a0, b0); b0 = vcvt_f32_f16((float16x4_t)LoadHalf<false>((B[3] + k))); c03 = vmlaq_f32(c03, a0, b0); } float32x4_t _bb = Load<false>(bb); float32x4_t _1 = vdupq_n_f32(1.0f); Store<false>(distances + 0 * stride, vmlsq_f32(_1, ReciprocalSqrt<1>(vmulq_f32(_bb, vdupq_n_f32(aa[0]))), Extract4Sums(c00, c01, c02, c03))); } static void MacroCosineDistances(size_t M, size_t N, size_t K, const uint16_t * const * A, const uint16_t * const * B, const float * aa, const float * bb, float * distances, size_t stride) { size_t M3 = AlignLoAny(M, 3); size_t N4 = AlignLo(N, 4); size_t i = 0; for (; i < M3; i += 3) { size_t j = 0; for (; j < N4; j += 4) MicroCosineDistances3x4(K, A + i, B + j, aa + i, bb + j, distances + j, stride); for (; j < N; j += 1) MicroCosineDistances3x1(K, A + i, B + j, aa + i, bb + j, distances + j, stride); distances += 3 * stride; } for (; i < M; i++) { size_t j = 0; for (; j < N4; j += 4) MicroCosineDistances1x4(K, A + i, B + j, aa + i, bb + j, distances + j, stride); for (; j < N; j += 1) CosineDistance16f(A[i], B[j], K, distances + j); distances += 1 * stride; } } void CosineDistancesMxNa16f(size_t M, size_t N, size_t K, const uint16_t * const * A, const uint16_t * const * B, float * distances) { const size_t L2 = Base::AlgCacheL2(); size_t mN = AlignLoAny(L2 / 2 / K, 4); size_t mM = AlignLoAny(L2 / 2 / K, 3); Array32f aa(M), bb(N); for (size_t i = 0; i < M; i += mM) { size_t dM = Simd::Min(M, i + mM) - i; Squares(dM, K, A + i, aa.data + i); for (size_t j = 0; j < N; j += mN) { size_t dN = Simd::Min(N, j + mN) - j; if (i == 0) Squares(dN, K, B + j, bb.data + j); MacroCosineDistances(dM, dN, K, A + i, B + j, aa.data + i, bb.data + j, distances + i * N + j, N); } } } } #endif // defined(SIMD_NEON_ENABLE) && defined(SIMD_NEON_FP16_ENABLE) }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 "stdafx.h" #include "mbunit.h" TESTFIXTURE(ExpectedException) { TEST(ExpectedException_should_pass_when_exception_is_actually_thrown, EXPECTED_EXCEPTION(char*)) { throw "This expection is expected."; } TEST(ExpectedException_should_fail_when_exception_is_not_thrown, EXPECTED_EXCEPTION(char*)) { } TEST(ExpectedException_should_fail_when_exception_of_a_wrong_type_is_thrown, EXPECTED_EXCEPTION(char*)) { throw 123; } }
/* **************************************************************** **************************************************************** -> Coded by Stavros Chryselis -> Visit my github for more solved problems over multiple sites -> https://github.com/StavrosChryselis -> Feel free to email me at stavrikios@gmail.com **************************************************************** **************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <ctype.h> #define gc() getchar_unlocked() using namespace std; inline int FAST_IO() { char ch; int val = 0; ch = gc(); while (isspace(ch) && ch != EOF) ch = gc(); val = 0; while (isdigit(ch)) { val = (val * 10) + (ch - '0'); ch = gc(); } return val; } class ufs { private: struct set { int name; int rank; set *parent; }; int ssize; vector<set> S; set *fs(int name) { if (S[name].parent->name == name) return &S[name]; S[name].parent = fs(S[name].parent->name); return S[name].parent; } public: ufs(int n) { int i; ssize = n; S.resize(ssize); for (i = 0; i<S.size(); i++) { S[i].name = i; S[i].parent = &S[i]; S[i].rank = 0; } } int find_set(int name) { return fs(name)->name; } bool is_same_set(int a, int b) { return fs(a)->name == fs(b)->name; } void union_sets(int a, int b) { set *f, *s; f = fs(a); s = fs(b); if (f->name == s->name) return; ssize--; if (f->rank == s->rank) { f->rank++; s->parent = f; } else if (f->rank > s->rank) s->parent = f; else f->parent = s; } int size() { return ssize; } }; vector< pair<int, pair<int, int> > > EDGES; //w, u, v int N, E, total; inline bool init() { int i, f, s, w; //scanf("%d %d", &N, &E); N = FAST_IO(); E = FAST_IO(); if (N == 0 && E == 0) return 0; total = 0; EDGES.clear(); for (i = 0; i < E; i++) { f = FAST_IO(); s = FAST_IO(); w = FAST_IO(); //scanf("%d %d %d", &f, &s, &w); total += w; EDGES.push_back(make_pair(w, make_pair(f, s))); } return 1; } inline int solve() { int i, c, ans = 0; ufs g(N); sort(EDGES.begin(), EDGES.end()); for (i = 0, c = 0; i <EDGES.size() && c < N - 1; i++) if (!g.is_same_set(EDGES[i].second.first, EDGES[i].second.second)) { c++; ans += EDGES[i].first; g.union_sets(EDGES[i].second.first, EDGES[i].second.second); } return total - ans; } int main() { //freopen("input.txt", "r", stdin); while(init()) printf("%d\n", solve()); return 0; }
#include "insocket.h" #include <stdio.h> #include <iostream.h> #define w aus inSocket::inSocket(void) { addr.sin_addr.s_addr=INADDR_ANY; addr.sin_family=AF_INET; fd=-1; type = SOCK_STREAM; } inSocket::inSocket(unsigned int port,addrType ad, int theType) { hostent * he; type = theType; create(); if (ad==local) { if ((he=gethostbyname("localhost")) != 0) memcpy((char*)&addr.sin_addr,he->h_addr,he->h_length); else throw(socketException("inSocket:gethostbyname failed.")); DBG("Got local name"); } this->bind(port); } inSocket::inSocket(unsigned int localport,const char* host,unsigned int remoteport,int theType) { type = theType; create(); this->bind(localport); this->connect(host,remoteport); } inSocket::~inSocket(void) { if(fd != -1) { //shutdown(fd,SD_BOTH); //closesocket(fd); } } void inSocket::listen(int anz) { DBG("listen: fd="<<fd<<" anz="<<anz); if (::listen(fd,anz)==-1) throw(socketException("listen failed")); } void inSocket::bind(int port) { int namelen=sizeof(addr); addr.sin_port=htons(port); #ifndef _WIN32 BOOL val=TRUE; if(port) setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(const char FAR *)&val,sizeof(BOOL)); #endif if (::bind(fd,(sockaddr*)&addr,sizeof(addr))==-1) throw (socketException("bind failed")); getsockname(fd,(sockaddr*)&addr,&namelen); DBG("bind: fd="<<fd<<" Port="<<port); } void inSocket::connect(const char* host,unsigned int port) { hostent* he; char er[255]; DBG("Trying connection with "<<host<<" on port "<< port); //if ((addr.sin_addr.s_addr=inet_addr(host))==-1) { Silke: if ((addr.sin_addr.s_addr=inet_addr(host))!=INADDR_NONE) { if ((he=gethostbyname(host)) != 0) { memcpy((char*)&addr.sin_addr,he->h_addr,he->h_length); } else { sprintf(er,"connect: gethostbyname(%s) failed.",host); throw (socketException((const char *)er)); } } addr.sin_port=htons(port); if(::connect(fd,(sockaddr*)&addr,sizeof(addr)) ==-1) throw (socketException("connect failed.")); } void inSocket::accept(inSocket &other) { int len=sizeof(addr); DBG("Starting accept"); if((fd=::accept(other.fd,(sockaddr*)&addr,&len))==-1) { throw socketException("accept failed"); } DBG("Got Connection"); } void inSocket::create(void) { addr.sin_addr.s_addr=INADDR_ANY; addr.sin_family=AF_INET; //if ((fd=WSASocket(AF_INET,type,0,NULL,0,/*WSA_FLAG_OVERLAPPED*/0))==SOCKET_ERROR) if ((fd=socket(AF_INET,type,0))==SOCKET_ERROR) throw (socketException("socket creation failed.")); } int inSocket::read(void *buffer,unsigned size) { int result; unsigned s=size; char *pos=(char*)buffer; do { result=recv(fd,pos,s,0); if(result>0) { s -= result; pos += result; } else return result; } while (s>0); return size; } int inSocket::write(void *buffer,unsigned size) { int result; unsigned s=size; char *pos=(char*)buffer; do { result=send(fd,(char*)buffer,size,0); if(result>0) { s -= result; pos += result; } else return result; } while (s>0); return size; }
/* * * Copyright (c) 1998-2002 * John Maddock * * Use, modification and distribution are 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) * */ /* * LOCATION: see http://www.boost.org for most recent version. * FILE: wide_posix_api.cpp * VERSION: see <boost/version.hpp> * DESCRIPTION: Implements the wide character POSIX API wrappers. */ #define BOOST_REGEX_SOURCE #include <boost/regex/config.hpp> #ifndef BOOST_NO_WREGEX #include <boost/regex.hpp> #include <boost/cregex.hpp> #include <cwchar> #include <cstring> #include <cstdio> #ifdef BOOST_INTEL #pragma warning(disable:981) #endif #if defined(BOOST_NO_STDC_NAMESPACE) || defined(__NetBSD__) namespace std{ # ifndef BOOST_NO_SWPRINTF using ::swprintf; # endif } #endif namespace boost{ namespace { unsigned int wmagic_value = 28631; const wchar_t* wnames[] = { L"REG_NOERROR", L"REG_NOMATCH", L"REG_BADPAT", L"REG_ECOLLATE", L"REG_ECTYPE", L"REG_EESCAPE", L"REG_ESUBREG", L"REG_EBRACK", L"REG_EPAREN", L"REG_EBRACE", L"REG_BADBR", L"REG_ERANGE", L"REG_ESPACE", L"REG_BADRPT", L"REG_EEND", L"REG_ESIZE", L"REG_ERPAREN", L"REG_EMPTY", L"REG_ECOMPLEXITY", L"REG_ESTACK", L"REG_E_PERL", L"REG_E_UNKNOWN", }; } typedef boost::basic_regex<wchar_t, c_regex_traits<wchar_t> > wc_regex_type; BOOST_REGEX_DECL int BOOST_REGEX_CCALL regcompW(regex_tW* expression, const wchar_t* ptr, int f) { if(expression->re_magic != wmagic_value) { expression->guts = 0; #ifndef BOOST_NO_EXCEPTIONS try{ #endif expression->guts = new wc_regex_type(); #ifndef BOOST_NO_EXCEPTIONS } catch(...) { return REG_ESPACE; } #else if(0 == expression->guts) return REG_E_MEMORY; #endif } // set default flags: boost::uint_fast32_t flags = (f & REG_PERLEX) ? 0 : ((f & REG_EXTENDED) ? wregex::extended : wregex::basic); expression->eflags = (f & REG_NEWLINE) ? match_not_dot_newline : match_default; // and translate those that are actually set: if(f & REG_NOCOLLATE) { flags |= wregex::nocollate; #ifndef BOOST_REGEX_V3 flags &= ~wregex::collate; #endif } if(f & REG_NOSUB) { //expression->eflags |= match_any; flags |= wregex::nosubs; } if(f & REG_NOSPEC) flags |= wregex::literal; if(f & REG_ICASE) flags |= wregex::icase; if(f & REG_ESCAPE_IN_LISTS) flags &= ~wregex::no_escape_in_lists; if(f & REG_NEWLINE_ALT) flags |= wregex::newline_alt; const wchar_t* p2; if(f & REG_PEND) p2 = expression->re_endp; else p2 = ptr + std::wcslen(ptr); int result; #ifndef BOOST_NO_EXCEPTIONS try{ #endif expression->re_magic = wmagic_value; static_cast<wc_regex_type*>(expression->guts)->set_expression(ptr, p2, flags); expression->re_nsub = static_cast<wc_regex_type*>(expression->guts)->mark_count() - 1; result = static_cast<wc_regex_type*>(expression->guts)->error_code(); #ifndef BOOST_NO_EXCEPTIONS } catch(const boost::regex_error& be) { result = be.code(); } catch(...) { result = REG_E_UNKNOWN; } #endif if(result) regfreeW(expression); return result; } BOOST_REGEX_DECL regsize_t BOOST_REGEX_CCALL regerrorW(int code, const regex_tW* e, wchar_t* buf, regsize_t buf_size) { std::size_t result = 0; if(code & REG_ITOA) { code &= ~REG_ITOA; if((code <= (int)REG_E_UNKNOWN) && (code >= 0)) { result = std::wcslen(wnames[code]) + 1; if(buf_size >= result) #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(_WIN32_WCE) && !defined(UNDER_CE) ::wcscpy_s(buf, buf_size, wnames[code]); #else std::wcscpy(buf, wnames[code]); #endif return result; } return result; } #if !defined(BOOST_NO_SWPRINTF) if(code == REG_ATOI) { wchar_t localbuf[5]; if(e == 0) return 0; for(int i = 0; i <= (int)REG_E_UNKNOWN; ++i) { if(std::wcscmp(e->re_endp, wnames[i]) == 0) { #if defined(_WIN32_WCE) && !defined(UNDER_CE) (std::swprintf)(localbuf, L"%d", i); #else (std::swprintf)(localbuf, 5, L"%d", i); #endif if(std::wcslen(localbuf) < buf_size) #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(_WIN32_WCE) && !defined(UNDER_CE) ::wcscpy_s(buf, buf_size, localbuf); #else std::wcscpy(buf, localbuf); #endif return std::wcslen(localbuf) + 1; } } #if defined(_WIN32_WCE) && !defined(UNDER_CE) (std::swprintf)(localbuf, L"%d", 0); #else (std::swprintf)(localbuf, 5, L"%d", 0); #endif if(std::wcslen(localbuf) < buf_size) #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) && !defined(_WIN32_WCE) && !defined(UNDER_CE) ::wcscpy_s(buf, buf_size, localbuf); #else std::wcscpy(buf, localbuf); #endif return std::wcslen(localbuf) + 1; } #endif if(code <= (int)REG_E_UNKNOWN) { std::string p; if((e) && (e->re_magic == wmagic_value)) p = static_cast<wc_regex_type*>(e->guts)->get_traits().error_string(static_cast< ::boost::regex_constants::error_type>(code)); else { p = re_detail::get_default_error_string(static_cast< ::boost::regex_constants::error_type>(code)); } std::size_t len = p.size(); if(len < buf_size) { re_detail::copy(p.c_str(), p.c_str() + p.size() + 1, buf); } return len + 1; } if(buf_size) *buf = 0; return 0; } BOOST_REGEX_DECL int BOOST_REGEX_CCALL regexecW(const regex_tW* expression, const wchar_t* buf, regsize_t n, regmatch_t* array, int eflags) { #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable:4267) #endif bool result = false; match_flag_type flags = match_default | expression->eflags; const wchar_t* end; const wchar_t* start; wcmatch m; if(eflags & REG_NOTBOL) flags |= match_not_bol; if(eflags & REG_NOTEOL) flags |= match_not_eol; if(eflags & REG_STARTEND) { start = buf + array[0].rm_so; end = buf + array[0].rm_eo; } else { start = buf; end = buf + std::wcslen(buf); } #ifndef BOOST_NO_EXCEPTIONS try{ #endif if(expression->re_magic == wmagic_value) { result = regex_search(start, end, m, *static_cast<wc_regex_type*>(expression->guts), flags); } else return result; #ifndef BOOST_NO_EXCEPTIONS } catch(...) { return REG_E_UNKNOWN; } #endif if(result) { // extract what matched: std::size_t i; for(i = 0; (i < n) && (i < expression->re_nsub + 1); ++i) { array[i].rm_so = (m[i].matched == false) ? -1 : (m[i].first - buf); array[i].rm_eo = (m[i].matched == false) ? -1 : (m[i].second - buf); } // and set anything else to -1: for(i = expression->re_nsub + 1; i < n; ++i) { array[i].rm_so = -1; array[i].rm_eo = -1; } return 0; } return REG_NOMATCH; #ifdef BOOST_MSVC #pragma warning(pop) #endif } BOOST_REGEX_DECL void BOOST_REGEX_CCALL regfreeW(regex_tW* expression) { if(expression->re_magic == wmagic_value) { delete static_cast<wc_regex_type*>(expression->guts); } expression->re_magic = 0; } } // namespace boost; #endif
#include "stdafx.h" #include "Utils.h" //GLenum GetFormat(Format format) //{ // switch (format) // { // case Format::B8G8R8A8_UNORM_SRGB: // case Format::B8G8R8A8_UNORM: // *glType = GL_UNSIGNED_BYTE; // *glClientFormat =GL_BGRA_EXT; // *interalFormat = GL_RGBA; // break; // // case Format::R8G8B8A8_UNORM_SRGB: // case Format::R8G8B8A8_UNORM: // *glType = GL_UNSIGNED_BYTE; // *glClientFormat = GL_RGBA; // *interalFormat = GL_RGBA; // break; // // // case Format::R16G16B16A16_UINT: // case Format::R16G16B16A16_UNORM: // *glType = GL_UNSIGNED_SHORT; // *glClientFormat = GL_RGBA; // *interalFormat = GL_RGBA; // break; // case Format::R16G16B16A16_SINT: // *glType = GL_SHORT; // *glClientFormat = GL_RGBA; // *interalFormat = GL_RGBA; // break; // case Format::R16G16B16A16_FLOAT: // *glType = GL_HALF_FLOAT; // *glClientFormat = GL_RGBA; // *interalFormat = GL_RGBA; // break; // // // case Format::R32G32B32A32_FLOAT: // *glType = GL_FLOAT; // *glClientFormat = GL_RGBA; // *interalFormat = GL_RGBA; // break; // case Format::R32G32B32A32_SINT: // *glType = GL_INT; // *glClientFormat = GL_RGBA; // *interalFormat = GL_RGBA; // break; // // case Format::R32G32B32_UINT: // *glType =GL_UNSIGNED_INT; // *glClientFormat = GL_RGB; // *interalFormat = GL_RGB; // break; // case Format::R32G32B32_FLOAT: // *glType = GL_FLOAT; // *glClientFormat = GL_RGB; // *interalFormat = GL_RGB; // break; // case Format::R32G32B32_SINT: // *glType = GL_INT; // *glClientFormat = GL_RGB; // *interalFormat = GL_RGB; // break; // // // case Format::R32_FLOAT: // *glType = GL_FLOAT; // *glClientFormat =GL_RED; // *interalFormat = GL_RED; // break; // // case Format::R32_UINT: // *glType = GL_UNSIGNED_INT; // *glClientFormat =GL_RED; // *interalFormat = GL_RED; // break; // case Format::R32_SINT: // *glType = GL_INT; // *glClientFormat = GL_RED; // *interalFormat = GL_RED; // break; // // case Format::D16_UNORM: // *glType = GL_DEPTH_COMPONENT16; // *glClientFormat = GL_DEPTH_COMPONENT16; // *interalFormat = GL_DEPTH_COMPONENT16; // break; // case Format::D24_UNORM_S8_UINT: // *glType = GL_DEPTH24_STENCIL8; // *glClientFormat = GL_DEPTH24_STENCIL8; // *interalFormat = GL_DEPTH24_STENCIL8; // break; // case Format::D32_FLOAT: // *glType = GL_DEPTH_COMPONENT32; // *glClientFormat = GL_DEPTH_COMPONENT32; // *interalFormat = GL_DEPTH_COMPONENT32; // break; // default: // throw gcnew NotImplementedException(); // // } //} void GetFormat(Format format, GLenum* glClientFormat, GLenum* glType, GLenum* interalFormat) { switch (format) { case Format::R8G8B8A8_UNORM_SRGB: *interalFormat = GL_SRGB8_ALPHA8; *glClientFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; case Format::R8G8B8A8_UNORM: *interalFormat = GL_RGBA8; *glClientFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; case Format::R8G8B8A8_SNORM: *interalFormat = GL_RGBA8; *glClientFormat = GL_RGBA; *glType = GL_BYTE; break; case Format::X8R8G8B8: *interalFormat = GL_RGB8; *glClientFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; case Format::R8G8_UNORM: *interalFormat = GL_RG8; *glClientFormat = GL_RG; *glType = GL_UNSIGNED_BYTE; break; case Format::R8G8_SNORM: *interalFormat = GL_RG8; *glClientFormat = GL_RG; *glType = GL_BYTE; break; case Format::R8_UNORM: *interalFormat = GL_R8; *glClientFormat = GL_RED; *glType = GL_BYTE; break; case Format::R8_SNORM: *interalFormat = GL_R8; *glClientFormat = GL_RED; *glType = GL_UNSIGNED_BYTE; break; case Format::R16G16B16A16_UNORM: *interalFormat = GL_RGBA16UI; *glClientFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT; break; case Format::R16G16B16A16_SNORM: *interalFormat = GL_RGBA16I; *glClientFormat = GL_RGBA; *glType = GL_SHORT; break; case Format::R16G16B16A16_FLOAT: *interalFormat = GL_RGBA16F; *glClientFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; // case Format::R16G16_UNORM: *interalFormat = GL_RG16UI; *glClientFormat = GL_RG; *glType = GL_UNSIGNED_SHORT; break; case Format::R16G16_SNORM: *interalFormat = GL_RG16I; *glClientFormat = GL_RG; *glType = GL_SHORT; break; case Format::R16G16_FLOAT: *interalFormat = GL_RG16F; *glClientFormat = GL_RG; *glType = GL_HALF_FLOAT; break; case Format::R16_FLOAT: *interalFormat = GL_R16F; *glClientFormat = GL_RED; *glType = GL_HALF_FLOAT; break; // case Format::R32G32B32A32_UINT: *interalFormat = GL_RGBA32UI; *glClientFormat = GL_RGBA; *glType = GL_UNSIGNED_INT; break; case Format::R32G32B32A32_SINT: *interalFormat = GL_RGBA32I; *glClientFormat = GL_RGBA; *glType = GL_INT; break; case Format::R32G32B32A32_FLOAT: *interalFormat = GL_RGBA32F; *glClientFormat = GL_RGBA; *glType = GL_FLOAT; break; case Format::R32G32B32_UINT: *interalFormat = GL_RGB32UI; *glClientFormat = GL_RGB; *glType = GL_UNSIGNED_INT; break; case Format::R32G32B32_SINT: *interalFormat = GL_RGB32I; *glClientFormat = GL_RGB; *glType = GL_INT; break; case Format::R32G32B32_FLOAT: *interalFormat = GL_RGB32F; *glClientFormat = GL_RGB; *glType = GL_FLOAT; break; case Format::R32G32_UINT: *interalFormat = GL_RG32UI; *glClientFormat = GL_RG; *glType = GL_UNSIGNED_INT; break; case Format::R32G32_SINT: *interalFormat = GL_RG32I; *glClientFormat = GL_RG; *glType = GL_INT; break; case Format::R32G32_FLOAT: *interalFormat = GL_RG32F; *glClientFormat = GL_RG; *glType = GL_FLOAT; break; case Format::R32_UINT: *interalFormat = GL_R32UI; *glClientFormat = GL_RED; *glType = GL_UNSIGNED_INT; break; case Format::R32_SINT: *interalFormat = GL_R32I; *glClientFormat = GL_RED; *glType = GL_INT; break; case Format::R32_FLOAT: *interalFormat = GL_R32F; *glClientFormat = GL_RED; *glType = GL_FLOAT; break; default: throw gcnew NotImplementedException(); } } int GetSize(GLenum glType) { switch (glType) { case GL_UNSIGNED_BYTE: case GL_BYTE: return 1; case GL_UNSIGNED_SHORT: case GL_SHORT: case GL_HALF_FLOAT: return 2; case GL_UNSIGNED_INT: case GL_INT: case GL_FLOAT: return 4; default: break; } } int GetComponents(GLenum clientFormat) { switch (clientFormat) { case GL_RED: case GL_BLUE: case GL_GREEN: case GL_ALPHA: return 1: case GL_RG: return 2: case GL_RGB: return 3; case GL_RGBA: return 4; default: break; } } //int GetElements(GLenum glFormat) //{ // //} // //GLenum GetTextureCubeFace(int resource); GLenum GetUsage(ResourceUsage usage) { switch (usage) { case ResourceUsage::Default: return GL_STATIC_DRAW; case ResourceUsage::Immutable: return GL_STATIC_DRAW; case ResourceUsage::Dynamic: return GL_DYNAMIC_DRAW; case ResourceUsage::Staging: return GL_STREAM_COPY; default: return GL_ZERO; } } int GetElements(IAFormat iAFormat) { switch (iAFormat) { case IAFormat::Color: return 4; case IAFormat::Float1: return 1; case IAFormat::Float2: return 2; case IAFormat::Float3: return 3; case IAFormat::Float4: return 4; case IAFormat::HalfFour: return 4; case IAFormat::HalfTwo: case IAFormat::Short2: case IAFormat::Short2N: return 2; case IAFormat::Short4: return 4; case IAFormat::Short4N: return 4; case IAFormat::Ubyte4: return 4; case IAFormat::UByte4N: return 4; case IAFormat::Unused: throw gcnew ArgumentException(); case IAFormat::UShort2N: return 2; case IAFormat::UShort4N: return 4; default: throw gcnew ArgumentException(); } } // //int GetSize(IAFormat iAFormat); // GLenum GetType(IAFormat iAFormat) { switch (iAFormat) { case IAFormat::Color: return GL_UNSIGNED_BYTE; case IAFormat::Dec3N: return GL_INT; case IAFormat::Float1: case IAFormat::Float2: case IAFormat::Float3: case IAFormat::Float4: return GL_FLOAT; case IAFormat::HalfFour: case IAFormat::HalfTwo: return GL_HALF_FLOAT; case IAFormat::Short2: return GL_SHORT; case IAFormat::Short2N: return GL_UNSIGNED_SHORT; case IAFormat::Short4: case IAFormat::Short4N: return GL_SHORT; case IAFormat::Ubyte4: return GL_UNSIGNED_BYTE; case IAFormat::UByte4N: return GL_UNSIGNED_BYTE; case IAFormat::UDec3: return GL_INT; case IAFormat::Unused: throw gcnew ArgumentException(); case IAFormat::UShort2N: return GL_UNSIGNED_SHORT; case IAFormat::UShort4N: return GL_UNSIGNED_SHORT; default: throw gcnew ArgumentException(); } } // //bool GetNormalized(IAFormat iAFormat)
#include "cluster.h" Cluster::Cluster () { this->lastid = 0; this->processors = 1; this->maxprocessors = 1; } Cluster::Cluster (int p) { this->lastid = 0; this->processors = p; this->maxprocessors = p; } Cluster::~Cluster () { } // is there a waiting queue? bool Cluster::isWaiting() { return !this->waiting.empty(); } // is there a running queue? bool Cluster::isRunning() { return !this->running.empty(); } // what was the last job added? int Cluster::getLast() { return this->lastid; } // insert a job if it's good or spit out a error message bool Cluster::InsertJob(string desc, int n_proc, int n_ticks) { bool isGood = false; if (n_proc > 0 && n_proc <= this->maxprocessors) { if (n_ticks > 0) { this->waiting.push(Job (this->lastid, desc, n_proc, n_ticks)); this->lastid++; } else { cout << "Insertion Error: Too few ticks.\n"; } } else { isGood = false; cout << "Insertion Error: Too many processes needed or less than 0.\n"; } return isGood; } // find the shortest job if the queue isn't empty Job Cluster::FindShortest() { Job temp = Job (-1, "NULL", -1, -1); if (!this->waiting.empty()) { temp = this->waiting.top(); } return temp; } // check if enough processors are available bool Cluster::CheckAvailability(int p) { bool isGood = false; if (p <= this->processors) isGood = true; return isGood; } // remove top job void Cluster::DeleteShortest() { this->waiting.pop(); } // add a job to the running queue void Cluster::RunJob(int id, string desc, int n_proc, int n_ticks) { this->processors -= n_proc; this->running.push_back (Job (id, desc, n_proc, n_ticks)); } // decrement timers on all jobs void Cluster::DecrementTimer() { list<Job>::iterator it; for ( it=running.begin() ; it != running.end(); it++ ) it->num_ticks--; } // release processors (really bad algorithm for making not crash) void Cluster::ReleaseProcessors() { list<Job>::iterator it; bool isReleasing = true; while (isReleasing) { for ( it=running.begin() ; it != running.end(); it++ ) { if (it->num_ticks < 1) { cout << "Removed Job #" << it->id + 1 << " (" << it->description << ", " << it->num_proc << ", " << it->num_ticks << ") from running queue.\n"; this->processors += it->num_proc; running.erase(it); if (!running.empty()) it = running.begin(); else break; } } isReleasing = false; } }
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic 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. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // Miscellaneous stuff related to tiled files // //----------------------------------------------------------------------------- #include "ImfTiledMisc.h" #include "Iex.h" #include "ImfMisc.h" #include "ImfChannelList.h" namespace Imf { using Imath::Box2i; using Imath::V2i; int levelSize (int min, int max, int l, LevelRoundingMode rmode) { if (l < 0) throw Iex::ArgExc ("Argument not in valid range."); int a = max - min + 1; int b = (1 << l); int size = a / b; if (rmode == ROUND_UP && size * b < a) size += 1; return std::max (size, 1); } Box2i dataWindowForLevel (const TileDescription &tileDesc, int minX, int maxX, int minY, int maxY, int lx, int ly) { V2i levelMin = V2i (minX, minY); V2i levelMax = levelMin + V2i (levelSize (minX, maxX, lx, tileDesc.roundingMode) - 1, levelSize (minY, maxY, ly, tileDesc.roundingMode) - 1); return Box2i(levelMin, levelMax); } Box2i dataWindowForTile (const TileDescription &tileDesc, int minX, int maxX, int minY, int maxY, int dx, int dy, int lx, int ly) { V2i tileMin = V2i (minX + dx * tileDesc.xSize, minY + dy * tileDesc.ySize); V2i tileMax = tileMin + V2i (tileDesc.xSize - 1, tileDesc.ySize - 1); V2i levelMax = dataWindowForLevel (tileDesc, minX, maxX, minY, maxY, lx, ly).max; tileMax = V2i (std::min (tileMax[0], levelMax[0]), std::min (tileMax[1], levelMax[1])); return Box2i (tileMin, tileMax); } size_t calculateBytesPerPixel (const Header &header) { const ChannelList &channels = header.channels(); size_t bytesPerPixel = 0; for (ChannelList::ConstIterator c = channels.begin(); c != channels.end(); ++c) { bytesPerPixel += pixelTypeSize (c.channel().type); } return bytesPerPixel; } namespace { int floorLog2 (int x) { // // For x > 0, floorLog2(y) returns floor(log(x)/log(2)). // int y = 0; while (x > 1) { y += 1; x >>= 1; } return y; } int ceilLog2 (int x) { // // For x > 0, ceilLog2(y) returns ceil(log(x)/log(2)). // int y = 0; int r = 0; while (x > 1) { if (x & 1) r = 1; y += 1; x >>= 1; } return y + r; } int roundLog2 (int x, LevelRoundingMode rmode) { return (rmode == ROUND_DOWN)? floorLog2 (x): ceilLog2 (x); } int calculateNumXLevels (const TileDescription& tileDesc, int minX, int maxX, int minY, int maxY) { int num = 0; switch (tileDesc.mode) { case ONE_LEVEL: num = 1; break; case MIPMAP_LEVELS: { int w = maxX - minX + 1; int h = maxY - minY + 1; num = roundLog2 (std::max (w, h), tileDesc.roundingMode) + 1; } break; case RIPMAP_LEVELS: { int w = maxX - minX + 1; num = roundLog2 (w, tileDesc.roundingMode) + 1; } break; default: throw Iex::ArgExc ("Unknown LevelMode format."); } return num; } int calculateNumYLevels (const TileDescription& tileDesc, int minX, int maxX, int minY, int maxY) { int num = 0; switch (tileDesc.mode) { case ONE_LEVEL: num = 1; break; case MIPMAP_LEVELS: { int w = maxX - minX + 1; int h = maxY - minY + 1; num = roundLog2 (std::max (w, h), tileDesc.roundingMode) + 1; } break; case RIPMAP_LEVELS: { int h = maxY - minY + 1; num = roundLog2 (h, tileDesc.roundingMode) + 1; } break; default: throw Iex::ArgExc ("Unknown LevelMode format."); } return num; } void calculateNumTiles (int *numTiles, int numLevels, int min, int max, int size, LevelRoundingMode rmode) { for (int i = 0; i < numLevels; i++) { numTiles[i] = (levelSize (min, max, i, rmode) + size - 1) / size; } } } // namespace void precalculateTileInfo (const TileDescription& tileDesc, int minX, int maxX, int minY, int maxY, int *&numXTiles, int *&numYTiles, int &numXLevels, int &numYLevels) { numXLevels = calculateNumXLevels(tileDesc, minX, maxX, minY, maxY); numYLevels = calculateNumYLevels(tileDesc, minX, maxX, minY, maxY); numXTiles = new int[numXLevels]; numYTiles = new int[numYLevels]; calculateNumTiles (numXTiles, numXLevels, minX, maxX, tileDesc.xSize, tileDesc.roundingMode); calculateNumTiles (numYTiles, numYLevels, minY, maxY, tileDesc.ySize, tileDesc.roundingMode); } } // namespace Imf
// Copyright 2019 The Crashpad Authors. 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. // 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 "util/process/process_memory_sanitized.h" #include "gtest/gtest.h" #include "test/process_type.h" #include "util/misc/from_pointer_cast.h" #include "util/process/process_memory_native.h" namespace crashpad { namespace test { namespace { TEST(ProcessMemorySanitized, DenyOnEmptyWhitelist) { ProcessMemoryNative memory; ASSERT_TRUE(memory.Initialize(GetSelfProcess())); char c = 42; char out; ProcessMemorySanitized san_null; san_null.Initialize(&memory, nullptr); EXPECT_FALSE(san_null.Read(FromPointerCast<VMAddress>(&c), 1, &out)); std::vector<std::pair<VMAddress, VMAddress>> whitelist; ProcessMemorySanitized san_blank; san_blank.Initialize(&memory, &whitelist); EXPECT_FALSE(san_blank.Read(FromPointerCast<VMAddress>(&c), 1, &out)); } TEST(ProcessMemorySanitized, WhitelistingWorks) { ProcessMemoryNative memory; ASSERT_TRUE(memory.Initialize(GetSelfProcess())); char str[4] = "ABC"; char out[4]; std::vector<std::pair<VMAddress, VMAddress>> whitelist; whitelist.push_back(std::make_pair(FromPointerCast<VMAddress>(str + 1), FromPointerCast<VMAddress>(str + 2))); ProcessMemorySanitized sanitized; sanitized.Initialize(&memory, &whitelist); EXPECT_FALSE(sanitized.Read(FromPointerCast<VMAddress>(str), 1, &out)); EXPECT_TRUE(sanitized.Read(FromPointerCast<VMAddress>(str + 1), 1, &out)); EXPECT_FALSE(sanitized.Read(FromPointerCast<VMAddress>(str + 2), 1, &out)); } } // namespace } // namespace test } // namespace crashpad
#include "midivaluedelegate.h" #include "enums.h" #include <QApplication> bool hasLut(const QModelIndex &index) { return index.data(MidiDataRole::MidiValues).isValid(); } QStringList lut(const QModelIndex &index) { Q_ASSERT(hasLut(index)); return index.data(MidiDataRole::MidiValues).toStringList(); } bool isToggle(const QModelIndex &index) { return hasLut(index) && lut(index).size() == 2; } bool isSpinbox(const QModelIndex &index) { return hasLut(index) && lut(index).size() > 2; } MidiValueDelegate::MidiValueDelegate(QObject* parent): QStyledItemDelegate(parent) { } void MidiValueDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { if (isToggle(index)) { QStyleOptionButton buttonOption; buttonOption.rect = option.rect; buttonOption.state = option.state; buttonOption.state |= index.data(Qt::EditRole).toInt() == 0 ? QStyle::State_Off : QStyle::State_On; buttonOption.text = index.data().toString(); QApplication* app = qobject_cast<QApplication*>(qGuiApp); Q_CHECK_PTR(app); app->style()->drawControl(QStyle::CE_PushButton, &buttonOption, painter); return; } QStyledItemDelegate::paint(painter, option, index); } QWidget* MidiValueDelegate::createEditor( QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const { if (isSpinbox(index)) { return new LutSpinBox(parent); } return QStyledItemDelegate::createEditor(parent, option, index); } void MidiValueDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { if (isSpinbox(index)) { LutSpinBox *sb = qobject_cast<LutSpinBox*>(editor); Q_CHECK_PTR(sb); sb->setLut(lut(index)); sb->setValue(index.data(Qt::EditRole).toInt()); return; } QStyledItemDelegate::setEditorData(editor, index); } void MidiValueDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const { if (isSpinbox(index)) { LutSpinBox *sb = qobject_cast<LutSpinBox*>(editor); Q_CHECK_PTR(sb); Q_CHECK_PTR(model); model->setData(index, sb->value(), Qt::EditRole); return; } QStyledItemDelegate::setModelData(editor, model, index); } void MidiValueDelegate::updateEditorGeometry( QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex&) const { Q_CHECK_PTR(editor); editor->setGeometry(option.rect); } bool MidiValueDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) { Q_CHECK_PTR(event); Q_CHECK_PTR(model); const bool toggleClicked = isToggle(index) && (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick); if (toggleClicked) { const int currentValue = model->data(index, Qt::EditRole).toInt(); const int newValue = currentValue == 0 ? 1 : 0; model->setData(index, newValue); return true; } return QStyledItemDelegate::editorEvent(event, model, option, index); } LutSpinBox::LutSpinBox(QWidget *parent) : QSpinBox(parent) { } void LutSpinBox::setLut(const QStringList &lut) { m_lut = lut; setMinimum(0); setMaximum(m_lut.count() - 1); } QString LutSpinBox::textFromValue(int value) const { return lutTextFromValue(m_lut, value); } int LutSpinBox::valueFromText(const QString &text) const { return lutValueFromText(m_lut, text); } QString lutTextFromValue(const QStringList &lut, int value) { return lut.isEmpty() ? QString() : lut.at(value); } int lutValueFromText(const QStringList &lut, const QString &text) { return lut.indexOf(text); }
/* * Build executable object file liking with cc_library lib file template. * * Copyright Paran Lee * */ #include <iostream> #include <string> #include <memory> #include "lib/Cuboid.hpp" #include "main/Grid.hpp" using namespace std; int main(int argc, char** argv) { Grid<int> myIntGrid; Grid<double> myDoubleGrid(11, 11); myIntGrid.at(0, 0) = 10; int x = myIntGrid.at(0, 0).value_or(0); // with optional :) Grid<int> grid2(myIntGrid); // copy operator Grid<int> anotherIntGrid; anotherIntGrid = grid2; // = operator //Grid test; // compile error //Grid<> test; // compile error // processIntGrid(myIntGrid); Grid<const char*> myStringGrid; myStringGrid.at(2, 2) = "hello"; Grid<vector<int>> gridOfVectors; vector<int> myVector{ 1, 2, 3, 4 }; gridOfVectors.at(5, 6) = myVector; auto myGridOnHeap = make_unique<Grid<int>>(2, 2); // 2x2 Grid in heap memory pool. myGridOnHeap->at(0, 0) = 10; x = myGridOnHeap->at(0, 0).value_or(0); auto myCuboidOnHeap = make_unique<Cuboid<double>>(4, 2, 3); // 2x2 Grid in heap memory pool. // myCuboidOnHeap->mCells[0][0][0] = 10; // std::cout << "myCuboidOnHeap->mCells[0][0][0]: " << myCuboidOnHeap->mCells[0][0][0] << '\n'; }
#include "lualib.h" #include "lgc.h" #include "lobject.h" #include "lapi.h" #include "ltable.h" #include "lstate.h" #include <cpr/cpr.h> #undef strdup #define strdup _strdup #undef strlwr #define strlwr _strlwr #define CPR_RESPONSE "cprResponse" typedef struct ResponseData { //private: cpr::Response* object; } ResponseData; class Auth { public: bool hasBasic = false; cpr::Authentication basic = cpr::Authentication("",""); bool hasDigest = false; cpr::Digest digest = cpr::Digest("",""); bool hasNTLM = false; cpr::NTLM ntlm = cpr::NTLM("",""); bool hasBearer = false; cpr::Bearer bearer = cpr::Bearer(""); Auth() {}; //Default constructor Auth(cpr::Authentication basicAuth) : basic(basicAuth) , hasBasic(true) {}; Auth(cpr::Digest digestAuth) : digest(digestAuth) , hasDigest(true) {}; Auth(cpr::NTLM ntlmAuth) : ntlm(ntlmAuth) , hasNTLM(true) {}; Auth(cpr::Bearer bearerAuth) : bearer(bearerAuth) , hasBearer(true) {}; void AddBasic(cpr::Authentication basicAuth){ basic = basicAuth; hasBasic = true; }; void AddDigest(cpr::Digest digestAuth){ digest = digestAuth; hasDigest = true; }; void AddNTLM(cpr::NTLM ntlmAuth){ ntlm = ntlmAuth; hasNTLM = true; }; void AddBearer(cpr::Bearer bearerAuth){ bearer = bearerAuth; hasBearer = true; }; }; enum RequestMethod { None, Get, Post, Patch, Put, Delete, Head, Options }; static std::map<std::string, RequestMethod, cpr::CaseInsensitiveCompare> requestMap = std::map<std::string, RequestMethod, cpr::CaseInsensitiveCompare>{ {"GET", RequestMethod::Get}, {"get", RequestMethod::Get}, {"Get", RequestMethod::Get}, {"POST", RequestMethod::Post}, {"post", RequestMethod::Post}, {"Post", RequestMethod::Post}, {"PATCH", RequestMethod::Patch}, {"patch", RequestMethod::Patch}, {"Patch", RequestMethod::Patch}, {"PUT", RequestMethod::Put}, {"put", RequestMethod::Put}, {"Put", RequestMethod::Put}, {"DELETE", RequestMethod::Delete}, {"delete", RequestMethod::Delete}, {"Delete", RequestMethod::Delete}, {"HEAD", RequestMethod::Head}, {"head", RequestMethod::Head}, {"Head", RequestMethod::Head}, {"OPTIONS", RequestMethod::Options}, {"options", RequestMethod::Options}, {"Options", RequestMethod::Options}, }; template <typename... Ts> cpr::Response Request(RequestMethod method, Ts&&... ts) { switch( method ) { case RequestMethod::Get: return (cpr::Response) cpr::Get(std::forward<Ts>(ts)...); case RequestMethod::Post: return (cpr::Response) cpr::Post(std::forward<Ts>(ts)...); case RequestMethod::Patch: return (cpr::Response) cpr::Patch(std::forward<Ts>(ts)...); case RequestMethod::Put: return (cpr::Response) cpr::Put(std::forward<Ts>(ts)...); case RequestMethod::Delete: return (cpr::Response) cpr::Delete(std::forward<Ts>(ts)...); case RequestMethod::Head: return (cpr::Response) cpr::Head(std::forward<Ts>(ts)...); case RequestMethod::Options: return (cpr::Response) cpr::Options(std::forward<Ts>(ts)...); case RequestMethod::None: default: return cpr::Response(); } } static l_noret table_arg_error(lua_State* L, const char* nname, const char* extramsg) { const char* fname = luaL_currfuncname(L); if (fname) luaL_error(L, "invalid %s to '%s' (%s)", nname, fname, extramsg); else luaL_error(L, "invalid %s (%s)", nname, extramsg); } static l_noret table_type_error(lua_State* L, int narg, const char* nname, const char* tname) { const char* fname = luaL_currfuncname(L); const TValue* obj = luaA_toobject(L, narg); if (obj) { if (fname) luaL_error(L, "invalid %s to '%s' (%s expected, got %s)", nname, fname, tname, luaT_objtypename(L, obj)); else luaL_error(L, "invalid %s (%s expected, got %s)", nname, tname, luaT_objtypename(L, obj)); } else { if (fname) luaL_error(L, "missing %s to '%s' (%s expected)", nname, fname, tname); else luaL_error(L, "missing %s (%s expected)", nname, tname); } } static l_noret table_type_error(lua_State* L, int narg, const char* nname, int tag) { table_type_error(L, narg, nname, lua_typename(L, tag)); } static void checktablefortable(lua_State* L, int n, const char* nname) { if (lua_type(L, n) != LUA_TTABLE) table_type_error(L, n, nname, LUA_TTABLE); } static const char* checktableforstring(lua_State* L, int n, const char* nname) { const char* s = lua_tolstring(L, (n), NULL); if (!s) table_type_error(L, n, nname, LUA_TSTRING); return s; } static const char* opttableforstring(lua_State* L, int n, const char* nname, const char* def) { if (lua_isnoneornil(L, n)) return def; else return checktableforstring(L, n, nname); } static const char* checktableforlstring(lua_State* L, int n, const char* nname, size_t* len) { const char* s = lua_tolstring(L, (n), len); if (!s) table_type_error(L, n, nname, LUA_TSTRING); return s; } static int getfield(lua_State* L, const char* key, int d) { int res; lua_rawgetfield(L, -1, key); if (lua_isnumber(L, -1)) res = (int)lua_tointeger(L, -1); else { if (d < 0) luaL_error(L, "field '%s' missing in table", key); res = d; } lua_pop(L, 1); return res; } static void setfield(lua_State* L, const char* key, int value) { lua_pushinteger(L, value); lua_setfield(L, -2, key); } static long getfield(lua_State* L, const char* key, long d) { long res; lua_rawgetfield(L, -1, key); if (lua_isnumber(L, -1)) res = (long)lua_tolong(L, -1); else { if (d < 0) luaL_error(L, "field '%s' missing in table", key); res = d; } lua_pop(L, 1); return res; } static void setfield(lua_State* L, const char* key, long value) { lua_pushlong(L, value); lua_setfield(L, -2, key); } static long long getfield(lua_State* L, const char* key, long long d) { long long res; lua_rawgetfield(L, -1, key); if (lua_isnumber(L, -1)) res = (long long)lua_tollong(L, -1); else { if (d < 0) luaL_error(L, "field '%s' missing in table", key); res = d; } lua_pop(L, 1); return res; } static void setfield(lua_State* L, const char* key, long long value) { lua_pushllong(L, value); lua_setfield(L, -2, key); } static double getfield(lua_State* L, const char* key, double d) { double res; lua_rawgetfield(L, -1, key); if (lua_isnumber(L, -1)) res = (double)lua_tonumber(L, -1); else { if (d < 0) luaL_error(L, "field '%s' missing in table", key); res = d; } lua_pop(L, 1); return res; } static void setfield(lua_State* L, const char* key, double value) { lua_pushnumber(L, value); lua_setfield(L, -2, key); } static const char* getfield(lua_State* L, const char* key, const char* d) { const char* res; lua_rawgetfield(L, -1, key); if (lua_isstring(L, -1)) res = (const char*)lua_tostring(L, -1); else { if (d < 0) luaL_error(L, "field '%s' missing in table", key); res = d; } lua_pop(L, 1); return res; } static void setfield(lua_State* L, const char* key, const char* value) { lua_pushstring(L, value); lua_setfield(L, -2, key); } static int getboolfield(lua_State* L, const char* key) { int res; lua_rawgetfield(L, -1, key); res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1); lua_pop(L, 1); return res; } static void setboolfield(lua_State* L, const char* key, int value) { if (value < 0) /* undefined? */ return; /* does not set field */ lua_pushboolean(L, value); lua_setfield(L, -2, key); } static cpr::Authentication getAuthenticationFromArgs(lua_State* L, int idx) { //luaL_checktype(L, idx, LUA_TTABLE); checktablefortable(L, idx, "basic authentication"); lua_rawgeti(L, idx, 1); int idt = idx < 0 ? idx - 1 : idx; lua_rawgeti(L, idt, 2); const char *username = checktableforstring(L, -2, "username"); const char *password = checktableforstring(L, -1, "password"); lua_pop(L, 2); return cpr::Authentication(username, password); } static cpr::Digest getDigestFromArgs(lua_State* L, int idx) { //luaL_checktype(L, idx, LUA_TTABLE); checktablefortable(L, idx, "digest authentication"); lua_rawgeti(L, idx, 1); int idt = idx < 0 ? idx - 1 : idx; lua_rawgeti(L, idt, 2); const char *username = checktableforstring(L, -2, "username"); const char *password = checktableforstring(L, -1, "password"); lua_pop(L, 2); return cpr::Digest(username, password); } static cpr::NTLM getNTLMFromArgs(lua_State* L, int idx) { //luaL_checktype(L, idx, LUA_TTABLE); checktablefortable(L, idx, "NTLM authentication"); lua_rawgeti(L, idx, 1); int idt = idx < 0 ? idx - 1 : idx; lua_rawgeti(L, idt, 2); const char *username = checktableforstring(L, -2, "username"); const char *password = checktableforstring(L, -1, "password"); lua_pop(L, 2); return cpr::NTLM(username, password); } static cpr::Bearer getBearerFromArgs(lua_State* L, int idx) { const char* accessToken = checktableforstring(L, idx, "bearer access token"); return cpr::Bearer(accessToken); } static cpr::Parameters getParametersFromArgs(lua_State* L, int idx) { //luaL_checktype(L, idx, LUA_TTABLE); checktablefortable(L, idx, "parameters"); cpr::Parameters parameters = {}; // push nil for lua_next to indicate it needs to pick the first key lua_pushnil(L); int idt = idx < 0 ? idx - 1 : idx; while (lua_next(L, idt)) { // i.e. when the key is not a number, ignore it; if (lua_type(L, -2) != LUA_TNUMBER) { lua_pop(L, 1); /* pop the value */ continue; } int k = (int)lua_tointeger(L, -2); // key is at -2 on the stack, value at -1. We need to pop the value, // but leave the key on the stack so that lua_next knows where to // continue. You can do anything to process them at this point. int para = -1; checktablefortable(L, para, "parameter"); lua_rawgeti(L, para--, 1); lua_rawgeti(L, para, 2); std::string key = checktableforstring(L, -2, "key"); std::string value = checktableforstring(L, -1, "value"); lua_pop(L, 2); parameters.Add(cpr::Parameter(key, value)); // pop the value when you're done with it lua_pop(L, 2); lua_pushinteger(L, k); } return parameters; } static cpr::Header getHeaderFromArgs(lua_State* L, int idx) { //luaL_checktype(L, idx, LUA_TTABLE); checktablefortable(L, idx, "header"); cpr::Header header = {}; // push nil for lua_next to indicate it needs to pick the first key lua_pushnil(L); int idt = idx < 0 ? idx - 1 : idx; while (lua_next(L, idt)) { // i.e. when the key is not a number, ignore it; if (lua_type(L, -2) != LUA_TNUMBER) { lua_pop(L, 1); /* pop the value */ continue; } int k = (int)lua_tointeger(L, -2); // key is at -2 on the stack, value at -1. We need to pop the value, // but leave the key on the stack so that lua_next knows where to // continue. You can do anything to process them at this point. int h = -1; checktablefortable(L, h, "header"); lua_rawgeti(L, h--, 1); lua_rawgeti(L, h, 2); std::string key = checktableforstring(L, -2, "key"); std::string value = checktableforstring(L, -1, "value"); lua_pop(L, 2); header.insert(std::pair<std::string,std::string>(key, value)); // pop the value when you're done with it lua_pop(L, 2); lua_pushinteger(L, k); } return header; } static cpr::Payload getPayloadFromArgs(lua_State* L, int idx) { //luaL_checktype(L, idx, LUA_TTABLE); checktablefortable(L, idx, "payload"); cpr::Payload payload = {}; // push nil for lua_next to indicate it needs to pick the first key lua_pushnil(L); int idt = idx < 0 ? idx - 1 : idx; while (lua_next(L, idt)) { // i.e. when the key is not a number, ignore it; if (lua_type(L, -2) != LUA_TNUMBER) { lua_pop(L, 1); /* pop the value */ continue; } int k = (int)lua_tointeger(L, -2); // key is at -2 on the stack, value at -1. We need to pop the value, // but leave the key on the stack so that lua_next knows where to // continue. You can do anything to process them at this point. int h = -1; checktablefortable(L, h, "header"); lua_rawgeti(L, h--, 1); lua_rawgeti(L, h, 2); std::string key = checktableforstring(L, -2, "key"); std::string value = checktableforstring(L, -1, "value"); lua_pop(L, 2); payload.Add(cpr::Pair(key, value)); // pop the value when you're done with it lua_pop(L, 2); lua_pushinteger(L, k); } return payload; } static cpr::Multipart getMultipartFromArgs(lua_State* L, int idx) { //luaL_checktype(L, idx, LUA_TTABLE); checktablefortable(L, idx, "multipart"); cpr::Multipart multipart = {}; // push nil for lua_next to indicate it needs to pick the first key lua_pushnil(L); int idt = idx < 0 ? idx - 1 : idx; while (lua_next(L, idt)) { // i.e. when the key is not a number, ignore it; if (lua_type(L, -2) != LUA_TNUMBER) { lua_pop(L, 1); /* pop the value */ continue; } int k = (int)lua_tointeger(L, -2); // key is at -2 on the stack, value at -1. We need to pop the value, // but leave the key on the stack so that lua_next knows where to // continue. You can do anything to process them at this point. int h = -1; checktablefortable(L, h, "header"); lua_rawgeti(L, h--, 1); lua_rawgeti(L, h--, 2); lua_rawgeti(L, h, 3); std::string key = checktableforstring(L, -3, "key"); std::string value = checktableforstring(L, -2, "value"); cpr::Part part = cpr::Part(key, value); if (!lua_isnoneornil(L, -1)) { std::string content_type = checktableforstring(L, -1, "content type"); part = cpr::Part(key, value, content_type); } multipart.parts.push_back(part); lua_pop(L, 3); // pop the value when you're done with it lua_pop(L, 2); lua_pushinteger(L, k); } return multipart; } static cpr::Url getURLFromArgs(lua_State* L, int idx) { size_t linkl; //const char* link = luaL_checklstring(L, idx, &linkl); const char* link = checktableforlstring(L, idx, "URL", &linkl); return cpr::Url(link, linkl); } static cpr::Body getBodyFromArgs(lua_State* L, int idx) { size_t bodyl; //const char* body = luaL_checklstring(L, idx, &bodyl); const char* body = checktableforlstring(L, idx, "body", &bodyl); return cpr::Body(body, bodyl); } static std::tuple<cpr::Timeout, cpr::Redirect, Auth, cpr::Payload, cpr::Multipart, cpr::Parameters> getOptionsFromArgs(lua_State* L, int idx) { luaL_checktype(L, idx, LUA_TTABLE); cpr::Timeout timeout = cpr::Timeout(0); // Default is no timeout cpr::Redirect redirect = cpr::Redirect(true); // Default is true Auth auth = Auth(); cpr::Payload payload = {}; cpr::Parameters parameters = {}; cpr::Multipart multipart = {}; // push nil for lua_next to indicate it needs to pick the first key lua_pushnil(L); while (lua_next(L, idx)) { // key is at -2 on the stack, value at -1. We need to pop the value, // but leave the key on the stack so that lua_next knows where to // continue. You can do anything to process them at this point. // i.e. when the key is not a string, ignore it; if (lua_type(L, -2) != LUA_TSTRING) { lua_pop(L, 1); /* pop the value */ continue; } const char* k = lua_tostring(L, -2); std::string key = k; if (key == "followRedirects" || key == "followredirects" || key == "Followredirects" || key == "FollowRedirects" || key == "FOLLOWREDIRECTS") { if (lua_isboolean(L, -1)) redirect.follow = lua_toboolean(L, -1) ? true : false; } else if (key == "maxRedirects" || key == "maxredirects" || key == "Maxredirects" || key == "MaxRedirects" || key == "MAXREDIRECTS") { int isnum; int n = lua_tointegerx(L, -1, &isnum); if (isnum){ if (n < 0) table_arg_error(L, "maximum redirects", "out of range"); redirect.maximum = n; } } else if (key == "timeout" || key == "Timeout" || key == "TimeOut" || key == "timeOut" || key == "TIMEOUT") { int isnum; int n = lua_tointegerx(L, -1, &isnum); if (isnum){ if (n < 0) table_arg_error(L, "timeout", "out of range"); timeout = cpr::Timeout(n); } } else if (key == "auth" || key == "authentication" || key == "Auth" || key == "Authentication" || key == "AUTH" || key == "AUTHENTICATION" || key == "basic-auth" || key == "basicAuth" || key == "basicAuthentication" || key == "basicauth" || key == "basicauthentication" || key == "Basicauth" || key == "Basicauthentication" || key == "BasicAuth" || key == "BasicAuthentication" || key == "BASICAUTH" || key == "BASICAUTHENTICATION") auth.AddBasic(getAuthenticationFromArgs(L, -1)); else if (key == "digest" || key == "Digest") auth.AddDigest(getDigestFromArgs(L, -1)); else if (key == "ntlm" || key == "NTLM" || key == "Ntlm") auth.AddNTLM(getNTLMFromArgs(L, -1)); else if (key == "bearer" || key == "BEARER" || key == "Bearer") auth.AddBearer(getBearerFromArgs(L, -1)); else if (key == "parameters" || key == "PARAMETERS" || key == "Parameters") parameters = getParametersFromArgs(L, -1); else if (key == "payload" || key == "PAYLOAD" || key == "Payload") payload = getPayloadFromArgs(L, -1); else if (key == "multipart" || key == "MULTIPART" || key == "Multipart" || key == "MultiPart" || key == "multiPart") multipart = getMultipartFromArgs(L, -1); // pop the value when you're done with it lua_pop(L, 2); lua_pushstring(L, k); } return std::tuple <cpr::Timeout, cpr::Redirect, Auth, cpr::Payload, cpr::Multipart, cpr::Parameters>(timeout, redirect, auth, payload, multipart, parameters); } static const char * getTextForEnum( cpr::ErrorCode code ) { switch( code ) { case cpr::ErrorCode::OK: return "OK"; case cpr::ErrorCode::CONNECTION_FAILURE: return "CONNECTION_FAILURE"; case cpr::ErrorCode::EMPTY_RESPONSE: return "EMPTY_RESPONSE"; case cpr::ErrorCode::HOST_RESOLUTION_FAILURE: return "HOST_RESOLUTION_FAILURE"; case cpr::ErrorCode::INTERNAL_ERROR: return "INTERNAL_ERROR"; case cpr::ErrorCode::INVALID_URL_FORMAT: return "INVALID_URL_FORMAT"; case cpr::ErrorCode::NETWORK_RECEIVE_ERROR: return "NETWORK_RECEIVE_ERROR"; case cpr::ErrorCode::NETWORK_SEND_FAILURE: return "NETWORK_SEND_FAILURE"; case cpr::ErrorCode::OPERATION_TIMEDOUT: return "OPERATION_TIMEDOUT"; case cpr::ErrorCode::PROXY_RESOLUTION_FAILURE: return "PROXY_RESOLUTION_FAILURE"; case cpr::ErrorCode::SSL_CONNECT_ERROR: return "SSL_CONNECT_ERROR"; case cpr::ErrorCode::SSL_LOCAL_CERTIFICATE_ERROR: return "SSL_LOCAL_CERTIFICATE_ERROR"; case cpr::ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR: return "SSL_REMOTE_CERTIFICATE_ERROR"; case cpr::ErrorCode::SSL_CACERT_ERROR: return "SSL_CACERT_ERROR"; case cpr::ErrorCode::GENERIC_SSL_ERROR: return "GENERIC_SSL_ERROR"; case cpr::ErrorCode::UNSUPPORTED_PROTOCOL: return "UNSUPPORTED_PROTOCOL"; case cpr::ErrorCode::REQUEST_CANCELLED: return "REQUEST_CANCELLED"; case cpr::ErrorCode::TOO_MANY_REDIRECTS: return "TOO_MANY_REDIRECTS"; case cpr::ErrorCode::UNKNOWN_ERROR: return "UNKNOWN_ERROR"; default: return "UNKNOWN"; } } static Table *pushResponse (lua_State *L, cpr::Response* response) { lua_createtable(L, 0, 12); /* 12 = number of fields */ setfield(L, "reason", response->reason.c_str()); setfield(L, "redirects", response->redirect_count); lua_createtable(L, 0, 2); /* 2 = number of fields */ Table* st = hvalue(L->top - 1); setfield(L, "code", response->status_code); setfield(L, "line", response->status_line.c_str()); st->readonly = true; lua_setfield(L, -2, "status"); setfield(L, "text", response->text.c_str()); setfield(L, "url", response->url.data()); setfield(L, "rawHeader", response->raw_header.c_str()); cpr::Header header = response->header; size_t hsizet = header.size(); if ( hsizet > INT_MAX ) { luaL_error(L, "header size is larger than INT_MAX"); //throw std::overflow_error("data is larger than INT_MAX"); } int hsize = static_cast<int>(hsizet); lua_createtable(L, 0, hsize); Table* ht = hvalue(L->top - 1); // Create a map iterator and point to beginning of map cpr::Header::iterator hit = header.begin(); // Iterate over the map using Iterator till end. while (hit != header.end()) { // Accessing KEY from element pointed by it. std::string k = hit->first; // Accessing VALUE from element pointed by it. std::string v = hit->second; // Add to cookie table setfield(L, k.c_str(), v.c_str()); // Increment the Iterator to point to next entry hit++; } ht->readonly = true; lua_setfield(L, -2, "header"); lua_createtable(L, 0, 2); /* 2 = number of fields */ Table* et = hvalue(L->top - 1); setfield(L, "code", getTextForEnum(response->error.code)); setfield(L, "message", response->error.message.c_str()); et->readonly = true; lua_setfield(L, -2, "error"); setfield(L, "downloaded", response->downloaded_bytes); setfield(L, "uploaded", response->uploaded_bytes); setfield(L, "elapsed", response->elapsed); cpr::Cookies cookies = response->cookies; int csize = 0; // Create a map iterator and point to beginning of map cpr::Cookies::iterator sit = cookies.begin(); // Iterate over the map using Iterator till end. while (sit != cookies.end()) { // Increment the Iterator to point to next entry csize++; sit++; } lua_createtable(L, 0, csize); Table* ct = hvalue(L->top - 1); // Create a map iterator and point to beginning of map cpr::Cookies::iterator it = cookies.begin(); // Iterate over the map using Iterator till end. while (it != cookies.end()) { // Accessing KEY from element pointed by it. std::string k = it->first; // Accessing VALUE from element pointed by it. std::string v = it->second; // Add to cookie table setfield(L, k.c_str(), v.c_str()); // Increment the Iterator to point to next entry it++; } ct->readonly = true; lua_setfield(L, -2, "cookies"); std::vector<std::string> certInfo = response->GetCertInfo(); size_t data = certInfo.size(); if ( data > INT_MAX ) { luaL_error(L, "data is larger than INT_MAX"); //throw std::overflow_error("data is larger than INT_MAX"); } int convertData = static_cast<int>(data); lua_createtable(L, convertData, 0); /* 2 = number of fields */ Table* t = hvalue(L->top - 1); int i = 0; for (const std::string& s : certInfo) { TValue* e = &t->array[i++]; lua_pushstring(L, s.c_str()); StkId v = L->top - 1; setobj2t(L, e, v); lua_pop(L, 1); } t->readonly = true; lua_setfield(L, -2, "certInfo"); luaL_setmetatable(L, CPR_RESPONSE); Table* rt = hvalue(L->top - 1); rt->readonly = true; return rt; } static int cprrequest(lua_State* L, RequestMethod method) { cpr::Url url = getURLFromArgs(L, 1); if (!lua_isnoneornil(L, 2)) { cpr::Header header = getHeaderFromArgs(L, 2); if (!lua_isnoneornil(L, 3)) { cpr::Body body = getBodyFromArgs(L, 3); if (!lua_isnoneornil(L, 4)) // URL, Headers, Body, and CustomOptions are available { luaL_checktype(L, 4, LUA_TTABLE); std::tuple<cpr::Timeout, cpr::Redirect, Auth, cpr::Payload, cpr::Multipart, cpr::Parameters> options = getOptionsFromArgs(L, 4); cpr::Timeout timeout = std::get<cpr::Timeout>(options); // Default is no timeout cpr::Redirect redirect = std::get<cpr::Redirect>(options); // Default is true Auth auth = std::get<Auth>(options); cpr::Payload payload = std::get<cpr::Payload>(options); cpr::Multipart multipart = std::get<cpr::Multipart>(options); cpr::Parameters parameters = std::get<cpr::Parameters>(options); if (auth.hasBasic) { cpr::Response r = Request(method, url, header, body, timeout, redirect, payload, multipart, parameters, auth.basic); pushResponse(L, &r); } else if (auth.hasDigest) { cpr::Response r = Request(method, url, header, body, timeout, redirect, payload, multipart, parameters, auth.digest); pushResponse(L, &r); } else if (auth.hasNTLM) { cpr::Response r = Request(method, url, header, body, timeout, redirect, payload, multipart, parameters, auth.ntlm); pushResponse(L, &r); } else if (auth.hasBearer) { cpr::Response r = Request(method, url, header, body, timeout, redirect, payload, multipart, parameters, auth.bearer); pushResponse(L, &r); } else { cpr::Response r = Request(method, url, header, body, timeout, redirect, payload, multipart, parameters); pushResponse(L, &r); } } else // Only URL, Headers, and Body are available { cpr::Response r = Request(method, url, header, body); pushResponse(L, &r); } } else if (!lua_isnoneornil(L, 4)) // URL, Headers, and CustomOptions are available { luaL_checktype(L, 4, LUA_TTABLE); std::tuple<cpr::Timeout, cpr::Redirect, Auth, cpr::Payload, cpr::Multipart, cpr::Parameters> options = getOptionsFromArgs(L, 4); cpr::Timeout timeout = std::get<cpr::Timeout>(options); // Default is no timeout cpr::Redirect redirect = std::get<cpr::Redirect>(options); // Default is true Auth auth = std::get<Auth>(options); cpr::Payload payload = std::get<cpr::Payload>(options); cpr::Multipart multipart = std::get<cpr::Multipart>(options); cpr::Parameters parameters = std::get<cpr::Parameters>(options); if (auth.hasBasic) { cpr::Response r = Request(method, url, header, timeout, redirect, payload, multipart, parameters, auth.basic); pushResponse(L, &r); } else if (auth.hasDigest) { cpr::Response r = Request(method, url, header, timeout, redirect, payload, multipart, parameters, auth.digest); pushResponse(L, &r); } else if (auth.hasNTLM) { cpr::Response r = Request(method, url, header, timeout, redirect, payload, multipart, parameters, auth.ntlm); pushResponse(L, &r); } else if (auth.hasBearer) { cpr::Response r = Request(method, url, header, timeout, redirect, payload, multipart, parameters, auth.bearer); pushResponse(L, &r); } else { cpr::Response r = Request(method, url, header, timeout, redirect, payload, multipart, parameters); pushResponse(L, &r); } } else // Only URL and Headers are available { cpr::Response r = Request(method, url, header); pushResponse(L, &r); } } else if (!lua_isnoneornil(L, 3)) { cpr::Body body = getBodyFromArgs(L, 3); if (!lua_isnoneornil(L, 4)) // URL, Body, and CustomOptions are available { luaL_checktype(L, 4, LUA_TTABLE); std::tuple<cpr::Timeout, cpr::Redirect, Auth, cpr::Payload, cpr::Multipart, cpr::Parameters> options = getOptionsFromArgs(L, 4); cpr::Timeout timeout = std::get<cpr::Timeout>(options); // Default is no timeout cpr::Redirect redirect = std::get<cpr::Redirect>(options); // Default is true Auth auth = std::get<Auth>(options); cpr::Payload payload = std::get<cpr::Payload>(options); cpr::Multipart multipart = std::get<cpr::Multipart>(options); cpr::Parameters parameters = std::get<cpr::Parameters>(options); if (auth.hasBasic) { cpr::Response r = Request(method, url, body, timeout, redirect, payload, multipart, parameters, auth.basic); pushResponse(L, &r); } else if (auth.hasDigest) { cpr::Response r = Request(method, url, body, timeout, redirect, payload, multipart, parameters, auth.digest); pushResponse(L, &r); } else if (auth.hasNTLM) { cpr::Response r = Request(method, url, body, timeout, redirect, payload, multipart, parameters, auth.ntlm); pushResponse(L, &r); } else if (auth.hasBearer) { cpr::Response r = Request(method, url, body, timeout, redirect, payload, multipart, parameters, auth.bearer); pushResponse(L, &r); } else { cpr::Response r = Request(method, url, body, timeout, redirect, payload, multipart, parameters); pushResponse(L, &r); } } else // Only URL and Body are available { cpr::Response r = Request(method, url, body); pushResponse(L, &r); } } else if (!lua_isnoneornil(L, 4)) // URL and CustomOptions are available { luaL_checktype(L, 4, LUA_TTABLE); std::tuple<cpr::Timeout, cpr::Redirect, Auth, cpr::Payload, cpr::Multipart, cpr::Parameters> options = getOptionsFromArgs(L, 4); cpr::Timeout timeout = std::get<cpr::Timeout>(options); // Default is no timeout cpr::Redirect redirect = std::get<cpr::Redirect>(options); // Default is true Auth auth = std::get<Auth>(options); cpr::Payload payload = std::get<cpr::Payload>(options); cpr::Multipart multipart = std::get<cpr::Multipart>(options); cpr::Parameters parameters = std::get<cpr::Parameters>(options); if (auth.hasBasic) { cpr::Response r = Request(method, url, timeout, redirect, payload, multipart, parameters, auth.basic); pushResponse(L, &r); } else if (auth.hasDigest) { cpr::Response r = Request(method, url, timeout, redirect, payload, multipart, parameters, auth.digest); pushResponse(L, &r); } else if (auth.hasNTLM) { cpr::Response r = Request(method, url, timeout, redirect, payload, multipart, parameters, auth.ntlm); pushResponse(L, &r); } else if (auth.hasBearer) { cpr::Response r = Request(method, url, timeout, redirect, payload, multipart, parameters, auth.bearer); pushResponse(L, &r); } else { cpr::Response r = Request(method, url, timeout, redirect, payload, multipart, parameters); pushResponse(L, &r); } } else // Only url is available { cpr::Response r = Request(method, url); pushResponse(L, &r); } return 1; } static int cprrequest(lua_State* L) { std::string m = luaL_checklstring(L, (1), NULL); lua_remove(L, 1); if (requestMap[m] == RequestMethod::None){ luaL_error(L, "invalid request method (got \"%s\")", m.c_str()); return 0; } return cprrequest(L, requestMap[m]); } static int cprget(lua_State* L) { return cprrequest(L, RequestMethod::Get); } static int cprpost(lua_State* L) { return cprrequest(L, RequestMethod::Post); } static int cprdelete(lua_State* L) { return cprrequest(L, RequestMethod::Delete); } static int cprpatch(lua_State* L) { return cprrequest(L, RequestMethod::Patch); } static int cprput(lua_State* L) { return cprrequest(L, RequestMethod::Put); } static int cproptions(lua_State* L) { return cprrequest(L, RequestMethod::Options); } static int cprhead(lua_State* L) { return cprrequest(L, RequestMethod::Head); } static int response_tostring (lua_State *L) { lua_pushstring(L, CPR_RESPONSE); return 1; } static const luaL_Reg response_meta[] = { {"__tostring", response_tostring}, {NULL, NULL}, }; static void createmeta (lua_State *L) { luaL_newmetatable(L, CPR_RESPONSE); /* metatable for cpr responses */ luaL_register(L, NULL, response_meta); /* fill metatable */ lua_pushliteral(L, "__index"); lua_pushvalue(L, -3); /* dup methods table*/ lua_rawset(L, -3); /* metatable.__index = methods */ lua_pushliteral(L, "__metatable"); lua_pushvalue(L, -3); /* dup methods table*/ lua_rawset(L, -3); /* hide metatable: metatable.__metatable = methods */ lua_pop(L, 1); /* drop metatable */ lua_pop(L, 1); /* pop metatable */ } static const luaL_Reg funcs[] = { {"request", cprrequest}, {"get", cprget}, {"post", cprpost}, {"patch", cprpatch}, {"put", cprput}, {"delete", cprdelete}, {"options", cproptions}, {"head", cprhead}, {NULL, NULL}, }; LUALIB_API int luaopen_cpr(lua_State* L) { luaL_register(L, LUA_CPRLIBNAME, funcs); /* new module */ // lua_newtable(L); // create the response table // luaL_register(L, NULL, response_methods); // register functions into response table // lua_setfield(L, -2, "response"); // add response table to module // lua_pop(L, 1); /* drop methods */ // lua_pop(L, 1); /* drop response */ createmeta(L); return 1; }
/** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 "tools/converter/parser/tflite/tflite_rank_parser.h" #include <vector> #include <memory> #include "ops/rank.h" #include "nnacl/op_base.h" namespace mindspore { namespace lite { ops::PrimitiveC *TfliteRankParser::Parse(const std::unique_ptr<tflite::OperatorT> &tflite_op, const std::unique_ptr<tflite::SubGraphT> &tflite_subgraph, const std::unique_ptr<tflite::ModelT> &tflite_model) { auto prim = std::make_unique<ops::Rank>(); MS_CHECK_TRUE_RET(prim != nullptr, nullptr); return prim.release(); } TfliteNodeRegister g_tfliteRankParser(tflite::BuiltinOperator_RANK, new TfliteRankParser()); } // namespace lite } // namespace mindspore
#ifndef matching2D_hpp #define matching2D_hpp #include <stdio.h> #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <cmath> #include <limits> #include <opencv2/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/features2d.hpp> #include <opencv2/xfeatures2d.hpp> #include <opencv2/xfeatures2d/nonfree.hpp> #include "dataStructures.h" double detKeypointsHarris(std::vector<cv::KeyPoint> &keypoints, cv::Mat &img, bool bVis=false); double detKeypointsShiTomasi(std::vector<cv::KeyPoint> &keypoints, cv::Mat &img, bool bVis=false); double detKeypointsModern(std::vector<cv::KeyPoint> &keypoints, cv::Mat &img, std::string detectorType, bool bVis=false); double descKeypoints(std::vector<cv::KeyPoint> &keypoints, cv::Mat &img, cv::Mat &descriptors, std::string descriptorType); void matchDescriptors(std::vector<cv::KeyPoint> &kPtsSource, std::vector<cv::KeyPoint> &kPtsRef, cv::Mat &descSource, cv::Mat &descRef, std::vector<cv::DMatch> &matches, std::string descriptorType, std::string matcherType, std::string selectorType); #endif /* matching2D_hpp */
#include <boost/test/unit_test.hpp> #include <vector> #include "util.h" #include "hash.h" using namespace std; BOOST_AUTO_TEST_SUITE(hash_tests) BOOST_AUTO_TEST_CASE(murmurhash3) { #define T(expected, seed, data) BOOST_CHECK_EQUAL(MurmurHash3(seed, ParseHex(data)), expected) // Test MurmurHash3 with various inputs. Of course this is retested in the // bloom filter tests - they would fail if MurmurHash3() had any problems - // but is useful for those trying to implement TychoClassicGold libraries as a // source of test data for their MurmurHash3() primitive during // development. // // The magic number 0xFBA4C795 comes from CBloomFilter::Hash() T(0x00000000, 0x00000000, ""); T(0x6a396f08, 0xFBA4C795, ""); T(0x81f16f39, 0xffffffff, ""); T(0x514e28b7, 0x00000000, "00"); T(0xea3f0b17, 0xFBA4C795, "00"); T(0xfd6cf10d, 0x00000000, "ff"); T(0x16c6b7ab, 0x00000000, "0011"); T(0x8eb51c3d, 0x00000000, "001122"); T(0xb4471bf8, 0x00000000, "00112233"); T(0xe2301fa8, 0x00000000, "0011223344"); T(0xfc2e4a15, 0x00000000, "001122334455"); T(0xb074502c, 0x00000000, "00112233445566"); T(0x8034d2a0, 0x00000000, "0011223344556677"); T(0xb4698def, 0x00000000, "001122334455667788"); #undef T } BOOST_AUTO_TEST_SUITE_END()
#include "stdafx.h" #include "Docking/DockContainer.h" #include "Docking/DockGroup.h" #include "Docking/DockWidget.h" #include <QtCore/QStringBuilder> #include <lean/io/numeric.h> #include "Utility/UI.h" namespace { struct Dock { QString name; DockWidget *widget; bool bActive; bool bMakeFront; Dock(QString name) : name(LEAN_MOVE(name)), widget(), bActive(), bMakeFront() { } Dock(DockWidget *widget) : name(widget->objectName()), widget(widget), bActive(false), bMakeFront() { } }; typedef DockContainer::Split Split; template <class T> QSharedPointer<T> makeShared(T *p) { return QSharedPointer<T>(p); } } // namespace struct DockContainer::Split { float percentage; Qt::Orientation orientation; bool bUndecorated; // Either typedef QLinkedList< QSharedPointer<Split> > nodes_t; nodes_t nodes; QSplitter *splitter; // Or typedef QLinkedList< QSharedPointer<Dock> > docks_t; docks_t docks; DockGroup *tabs; Split(Qt::Orientation orient, float perct) : percentage(perct), orientation(orient), bUndecorated(false), splitter(), tabs() { } }; const QEvent::Type DockLayoutChangedEventType = static_cast<QEvent::Type>( QEvent::registerEventType() ); // Constructor. DockContainer::DockContainer(QWidget *pParent) : QFrame(pParent), m_center( new DockWidget(this) ), m_split( new Split(Qt::Horizontal, 1.0f) ), m_rubberBand( new QRubberBand(QRubberBand::Rectangle) ), m_bTrackChildren( false ), m_dockLogicRevision( 0 ), m_dockUIRevision( 0 ) { this->setObjectName("DockContainer"); this->setLayout( new QVBoxLayout() ); this->layout()->setMargin(0); m_nestedSplitterName = this->objectName() + "_NestedSplitter"; m_center->setObjectName(this->objectName() + "_CenterArea"); // Logical split setup QSharedPointer<Split> centerDock( new Split(Qt::Horizontal, 1.0f) ); centerDock->docks.push_back( makeShared( new Dock(m_center) ) ); centerDock->bUndecorated = true; m_split->nodes.push_back(centerDock); updateWidgetTree(); // Start tracking events m_bTrackChildren = true; } // Destructor. DockContainer::~DockContainer() { // Stop tracking events, let Qt clean up m_bTrackChildren = false; } // Sets the central widget. void DockContainer::setCentralWidget(QWidget *widget) { m_center->setWidget(widget); } namespace { QByteArray dockToString(const Dock &dock) { return dock.name.toUtf8() + '\0' + (dock.bActive ? "av" : "ah") + (dock.bMakeFront || dock.widget && !dock.widget->isHidden() ? "fv" : "fh"); } QByteArray splitToString(const Split &split) { QByteArray result = "p" + QByteArray::number(split.percentage) + ";o" + ((split.orientation == DockOrientation::Horizontal) ? "h" : "v") + (split.bUndecorated ? "du" : ""); for (Split::nodes_t::const_iterator it = split.nodes.begin(), itEnd = split.nodes.end(); it != itEnd; ++it) result += "(" + splitToString(**it) + ")"; for (Split::docks_t::const_iterator it = split.docks.begin(), itEnd = split.docks.end(); it != itEnd; ++it) result += "[" + dockToString(**it) + "]"; return result; } QSharedPointer<Dock> dockFromString(const char* &it, const char* itEnd) { const char* itNameBegin = it; while (it != itEnd && *it != '\0') ++it; const char* itNameEnd = it; QSharedPointer<Dock> dock( new Dock( QString::fromUtf8(itNameBegin, itNameEnd - itNameBegin) ) ); while (it != itEnd && *it != ']') { if (*it == 'a' && ++it != itEnd) dock->bActive = (*it++ == 'v'); else if (*it == 'f' && ++it != itEnd) dock->bMakeFront = (*it++ == 'v'); else ++it; } if (it != itEnd) ++it; return dock; } QSharedPointer<Split> splitFromString(const char* &it, const char* itEnd) { QSharedPointer<Split> split( new Split(Qt::Horizontal, 1.0f) ); while (it != itEnd && *it != ')') { if (*it == 'p') it = lean::char_to_float(it + 1, itEnd, split->percentage); else if (*it == 'o' && ++it != itEnd) split->orientation = (*it++ == 'v') ? Qt::Vertical : Qt::Horizontal; else if (*it == 'd' && ++it != itEnd) split->bUndecorated = (*it++ == 'u'); else if (*it == '(') split->nodes.push_back( splitFromString(++it, itEnd) ); else if (*it == '[') split->docks.push_back( dockFromString(++it, itEnd) ); else ++it; } if (it != itEnd) ++it; return split; } } // namespace // Serializes the current state into a string. QByteArray DockContainer::saveState() const { return splitToString(*m_split); } namespace { Split* findLeaf(Split *root, QWidget *dock, Split::docks_t::iterator *pDockedIt = nullptr, Split **pSplit = nullptr, Split::nodes_t::iterator *pLeafIt = nullptr, bool bPrecise = false) { if (pSplit) *pSplit = nullptr; for(Split::nodes_t::iterator it = root->nodes.begin(), itEnd = root->nodes.end(); it != itEnd; ++it) if (Split *leaf = findLeaf(it->data(), dock, pDockedIt, pSplit, pLeafIt, bPrecise)) { if (pSplit && !*pSplit) { *pSplit = root; if (pLeafIt) *pLeafIt = it; } return leaf; } for(Split::docks_t::iterator it = root->docks.begin(), itEnd = root->docks.end(); it != itEnd; ++it) if ((bPrecise) ? dock == it->data()->widget : it->data()->widget && isChildOf(dock, it->data()->widget)) { if (pDockedIt) *pDockedIt = it; return root; } return nullptr; } Split* findLeafByChild(Split *root, QWidget *widget) { for(Split::nodes_t::iterator it = root->nodes.begin(), itEnd = root->nodes.end(); it != itEnd; ++it) if (Split *leaf = findLeafByChild(it->data(), widget)) return leaf; if (root->tabs && isChildOf(widget, root->tabs)) return root; else for(Split::docks_t::iterator it = root->docks.begin(), itEnd = root->docks.end(); it != itEnd; ++it) if (it->data()->widget && isChildOf(widget, it->data()->widget)) return root; return nullptr; } Dock* findPlaceholder(Split *root, const QString &name, Split **pLeaf) { for(Split::nodes_t::const_iterator it = root->nodes.begin(), itEnd = root->nodes.end(); it != itEnd; ++it) if (Dock *dock = findPlaceholder(it->data(), name, pLeaf)) return dock; for(Split::docks_t::const_iterator it = root->docks.begin(), itEnd = root->docks.end(); it != itEnd; ++it) { Dock *dock = it->data(); if (!dock->widget && dock->name == name) { if (pLeaf) *pLeaf = root; return dock; } } return nullptr; } QSharedPointer<Split> simplifyTree(const QSharedPointer<Split> &root, QWidget *newParent) { bool bKeep = !root->docks.empty() || root->nodes.size() > 1; QWidget *newChildParent = (bKeep) ? root->splitter : newParent; for(Split::nodes_t::iterator it = root->nodes.end(); it-- != root->nodes.begin(); ) if (QSharedPointer<Split> child = simplifyTree(*it, newChildParent)) *it = child; else it = root->nodes.erase(it); if (!root->docks.empty() || root->nodes.size() > 1) return root; else if (!root->nodes.empty()) { // NOTE: UI has to be up-to-date BEFORE simplification, i.e. simplification does not affect UI LEAN_ASSERT(root->splitter == nullptr); // Simply omit this node by returning only child return root->nodes.front(); } else { // NOTE: UI has to be up-to-date BEFORE simplification, i.e. simplification does not affect UI LEAN_ASSERT(root->splitter == nullptr); LEAN_ASSERT(root->tabs == nullptr); // Nothing left, omit return QSharedPointer<Split>(); } } void simplifyTree(Split &root, QWidget *parent) { for(Split::nodes_t::iterator itBegin = root.nodes.begin(), it = root.nodes.end(); it-- != itBegin; ) if (QSharedPointer<Split> child = simplifyTree(*it, parent)) *it = child; else it = root.nodes.erase(it); } QWidget* updateWidgetTree(Split &root, DockContainer *container, const QString &nestedSplitterName, bool bKeepSplitter = false) { // TODO: Collect state QWidget *result = nullptr; // Nodes { QVector<QWidget*> activeChildren; for(Split::nodes_t::iterator it = root.nodes.begin(), itEnd = root.nodes.end(); it != itEnd; ++it) if (QWidget *child = updateWidgetTree(**it, container, nestedSplitterName)) activeChildren.push_back(child); if (activeChildren.size() > 1 || bKeepSplitter) { if (!root.splitter) { root.splitter = new QSplitter(root.orientation, container); root.splitter->setObjectName(nestedSplitterName); } result = root.splitter; // TODO: Filter common prefix Q_FOREACH(QWidget *child, activeChildren) root.splitter->addWidget(child); } else { // Simply pass single childs through if (activeChildren.size() == 1) { result = activeChildren[0]; if (isChildOf(result, root.splitter)) result->setParent(container); } if (root.splitter) { delete root.splitter; root.splitter = nullptr; } } } // Docks / tabs { LEAN_ASSERT (root.docks.empty() || !result); QVector<QWidget*> activeChildren; QWidget *frontChild = nullptr; for(Split::docks_t::iterator it = root.docks.begin(), itEnd = root.docks.end(); it != itEnd; ++it) { Dock &dock = **it; if (QWidget *child = dock.widget) { dock.bActive |= !child->isHidden(); if (dock.bActive) { activeChildren.push_back(child); if (dock.bMakeFront) { frontChild = child; // Reset dock.bMakeFront = false; } } else child->setParent(container); } } if (activeChildren.size() >= 1 && !root.bUndecorated) { if (!root.tabs) { root.tabs = new DockGroup(container); QObject::connect(root.tabs, &DockGroup::dockDragged, container, &DockContainer::dockDragged); QObject::connect(root.tabs, &DockGroup::dockDropped, container, &DockContainer::dockDropped, Qt::QueuedConnection); } result = root.tabs; int tabPos = 0; // TODO: Filter common prefix Q_FOREACH(QWidget *child, activeChildren) root.tabs->addWidget(child, tabPos++); if (frontChild) root.tabs->setCurrentTab(frontChild); } else { // Simply pass single undecorated childs through if (activeChildren.size() == 1) { result = activeChildren[0]; if (isChildOf(result, root.tabs)) result->setParent(container); } if (root.tabs) { delete root.tabs; root.tabs = nullptr; } } } return result; } /// Tries to emplace the given dock. bool tryEmplace(Split &root, DockWidget *dock, bool bActive) { if (Dock *place = findPlaceholder(&root, dock->objectName(), nullptr)) { place->widget = dock; place->bActive = bActive; return true; } else return false; } /// Transfers all matching docks from the given source to the given destination tree. void transfer(Split &source, Split &dest, QWidget *tmpParent) { for(Split::nodes_t::const_iterator it = source.nodes.begin(), itEnd = source.nodes.end(); it != itEnd; ++it) transfer(**it, dest, tmpParent); for(Split::docks_t::const_iterator it = source.docks.begin(), itEnd = source.docks.end(); it != itEnd; ++it) { Dock &dock = **it; if (dock.widget) { bool bKeep = false; if (Dock *place = findPlaceholder(&dest, dock.name, nullptr)) { place->widget = dock.widget; place->widget->setParent(tmpParent); bKeep = place->bActive; } if (!bKeep) dock.widget->close(); dock.widget = nullptr; } } } // Removes the given dock. void removeDock(Split &leaf, Split::docks_t::iterator itDocked, QWidget *newParent, DockContainer *pDisconnect, bool bPermanent) { Dock &dock = **itDocked; if (dock.widget) { QObject::disconnect(dock.widget, nullptr, pDisconnect, nullptr); dock.widget->setParent(newParent); } if (bPermanent) leaf.docks.erase(itDocked); else { dock.widget = nullptr; dock.bActive = false; } } } // namespace // Deserializes state from the given string. void DockContainer::restoreState(const QByteArray &state) { if (state.isEmpty()) return; const char *it = state.data(); QSharedPointer<Split> newState = splitFromString(it, it + state.size()); // Transfer & get rid of old widgets updateWidgetTree(); transfer(*m_split, *newState, this); updateWidgetTree(); // Replace & construct new widgets delete m_split->splitter; m_split = newState; updateWidgetTree(); } // Places the given dock widget next to the given dock widget. void DockContainer::addDock(DockWidget *dock, DockPlacement::T placement, DockOrientation::T orientation, DockSide::T side, QWidget *neighbor, DockCompany::T company) { bool bEmplaced = false; if (placement == DockPlacement::Emplace) { // Keep it where it is if (findLeaf(m_split.data(), dock)) return; // Emplace in existing placeholder else bEmplaced = ::tryEmplace(*m_split, dock, !dock->isHidden()); } if (!bEmplaced) { Split *leaf = nullptr; Split::docks_t::iterator itDocked; Split *split; Split::nodes_t::iterator itLeaf; // Find entries for the given neighbor or the center widget, if neighbor not given/found if (neighbor) leaf = findLeaf(m_split.data(), neighbor, &itDocked, &split, &itLeaf); if (!leaf) { neighbor = m_center; leaf = findLeaf(m_split.data(), neighbor, &itDocked, &split, &itLeaf); } LEAN_ASSERT(leaf && split); // Keep center widget tab-free if (leaf->bUndecorated && company == DockCompany::Join) company = DockCompany::JoinNeighbor; // Move docked iterator to insertion position if (side == DockSide::After) ++itDocked; // Try to find open neighbors if (company == DockCompany::JoinNeighbor) { // Insert at the end of the left neighbor, if existent & open if (side == DockSide::Before && itLeaf != split->nodes.begin() && !(itLeaf - 1)->data()->bUndecorated) { --itLeaf; leaf = itLeaf->data(); itDocked = leaf->docks.end(); company = DockCompany::Join; } // Insert at the front of the right neighbor, if existent & open else if (side == DockSide::After && itLeaf + 1 != split->nodes.end() && !(itLeaf + 1)->data()->bUndecorated) { ++itLeaf; leaf = itLeaf->data(); itDocked = leaf->docks.begin(); company = DockCompany::Join; } } if (company != DockCompany::Join) { if (split->orientation != toQt(orientation)) { QSharedPointer<Split> newSplit( new Split(toQt(orientation), leaf->percentage) ); newSplit->nodes.push_back(*itLeaf); *itLeaf = newSplit; leaf->percentage = 1.0f; split = newSplit.data(); itLeaf = split->nodes.begin(); } // Move leaf iterator to insertion position if (side == DockSide::After) ++itLeaf; // Insert new leaf itLeaf = split->nodes.insert(itLeaf, makeShared( new Split(toQt(orientation), 0.0f) ) ); leaf = itLeaf->data(); itDocked = leaf->docks.begin(); } // ORDER: Create dock item before widget management screws internal state QSharedPointer<Dock> dockItem( new Dock(dock) ); // NOTE: Handle re-insertions here to keep reference widget & iterators valid { Split::docks_t::iterator itDockedOld; Split *oldLeaf = findLeaf(m_split.data(), dock, &itDockedOld); if (oldLeaf) { // NOTE: Visibility no longer meaningful dockItem->bActive |= itDockedOld->data()->bActive; // Ignore re-insertion at the same position // NOTE: Always handle, iterator would become invalid on removal! if (itDockedOld == itDocked || itDockedOld + 1 == itDocked) return; // Otherwise, remove previous occurance else ::removeDock(*oldLeaf, itDockedOld, this, this, true); } } // Insert new dock itDocked = leaf->docks.insert(itDocked, dockItem); } dock->setParent(this); connect(dock, &DockWidget::parentChanged, this, &DockContainer::dockReparented); connect(dock, &DockWidget::destroyed, this, &DockContainer::dockDestroyed); connect(dock, &DockWidget::shown, this, &DockContainer::dockShown, Qt::QueuedConnection); connect(dock, &DockWidget::closed, this, &DockContainer::dockHidden, Qt::QueuedConnection); lazyUpdateWidgetTree(); } // Removes the given dock. void DockContainer::removeDock(DockWidget *dock, bool bPermanent) { Split::docks_t::iterator itDocked; if (Split *leaf = findLeaf(m_split.data(), dock, &itDocked)) { ::removeDock(*leaf, itDocked, nullptr, this, bPermanent); // TODO: Simplify tree lazyUpdateWidgetTree(); } } // Checks if the given two widgets share the same group. bool DockContainer::sameGroup(QWidget *a, QWidget *b) const { Split *leafA = findLeaf(m_split.data(), a); Split *leafB = findLeaf(m_split.data(), b); return leafA && leafB && leafA == leafB; } // Raises the given dock widget when the UI has been updated. void DockContainer::raiseDock(DockWidget *dock) { Split::docks_t::iterator itDocked; if (Split *leaf = findLeaf(m_split.data(), dock, &itDocked)) { itDocked->data()->bMakeFront = true; dock->show(); lazyUpdateWidgetTree(); } } // Lazily updates widgets in the tree structure. void DockContainer::lazyUpdateWidgetTree() { ++m_dockLogicRevision; QApplication::postEvent(this, new QEvent(DockLayoutChangedEventType)); } // Creates/updates widgets in the tree structure. void DockContainer::updateWidgetTree() { int logicRevision = m_dockLogicRevision; this->setUpdatesEnabled(false); this->layout()->addWidget( ::updateWidgetTree(*m_split, this, m_nestedSplitterName, true) ); this->setUpdatesEnabled(true); m_dockUIRevision = logicRevision; simplifyTree(*m_split, this); } namespace { QRect mapToGlobal(QWidget *widget, QRect rect) { rect.moveTo( widget->mapToGlobal( rect.topLeft() ) ); return rect; } DockCompany::T dockTargetFlags(QRect rect, QPoint screenPos, bool bMustSplit, DockOrientation::T &orientation, DockSide::T &side, QRect *pTargetRect = nullptr) { DockCompany::T company = DockCompany::Join; if (pTargetRect) *pTargetRect = rect; QPoint center = rect.center(); QPointF eccentricity = (screenPos - center); eccentricity.setX(2.0f * eccentricity.x() / rect.width()); eccentricity.setY(2.0f * eccentricity.y() / rect.height()); float eccentricityLimit = (bMustSplit) ? 0.0f : 0.5f; if (abs(eccentricity.x()) > abs(eccentricity.y())) { orientation = DockOrientation::Horizontal; if (eccentricity.x() < -eccentricityLimit) { company = DockCompany::Single; side = DockSide::Before; if (pTargetRect) pTargetRect->setRight(center.x()); } else if (eccentricity.x() >= eccentricityLimit) { company = DockCompany::Single; side = DockSide::After; if (pTargetRect) pTargetRect->setLeft(center.x()); } } else { orientation = DockOrientation::Vertical; if (eccentricity.y() < -eccentricityLimit) { company = DockCompany::Single; side = DockSide::Before; if (pTargetRect) pTargetRect->setBottom(center.y()); } else if (eccentricity.y() >= eccentricityLimit) { company = DockCompany::Single; side = DockSide::After; if (pTargetRect) pTargetRect->setTop(center.y()); } } return company; } } // namespace // Updates drag feedback. void DockContainer::dockDragDrop(QWidget *dockWdgt, QPoint screenPos, bool bDropped) { QWidget *targetWidget = nullptr; QWidget *targetTab = nullptr; bool bAppendOrSplit = true; bool bMustSplit = false; DockWidget *dock = LEAN_ASSERT_NOT_NULL( qobject_cast<DockWidget*>(dockWdgt) ); { QWidget *cursorWidget = QApplication::widgetAt(screenPos); if (Split *leaf = findLeafByChild(m_split.data(), cursorWidget)) { if (leaf->bUndecorated) { targetWidget = targetTab = leaf->docks.front()->widget; bMustSplit = true; } else { DockGroup *targetDock = leaf->tabs; targetWidget = targetDock; if (targetTab = targetDock->tabFromWidget(cursorWidget)) { targetWidget = cursorWidget; bAppendOrSplit = false; } else targetTab = targetDock->currentTab(); } } } bool bHighlight = !bDropped; bool bAccepted = false; if (targetTab) { DockCompany::T splitCompany = DockCompany::Join; DockOrientation::T splitOrient = DockOrientation::Horizontal; DockSide::T splitSide = DockSide::After; QRect targetRect = ::mapToGlobal(targetWidget->parentWidget(), targetWidget->geometry()); if (bAppendOrSplit) splitCompany = dockTargetFlags(targetRect, screenPos, bMustSplit, splitOrient, splitSide, &targetRect); else { if (screenPos.x() < targetRect.center().x()) { splitSide = DockSide::Before; targetRect.translate(-targetRect.width() / 2, 0); } else { splitSide = DockSide::After; targetRect.translate(targetRect.width() / 2, 0); } } m_rubberBand->setGeometry(targetRect); if (bDropped) { addDock(dock, DockPlacement::Independent, splitOrient, splitSide, targetTab, splitCompany); bAccepted = true; } } else m_rubberBand->setGeometry( dock->geometry().translated(screenPos - dock->pos()) ); m_rubberBand->setVisible(bHighlight); if (bDropped && !bAccepted) QMessageBox::information(nullptr, tr("Unsupported"), tr("Free dock widgets currently unsupported")); } // The given dock was destroyed. void DockContainer::dockDestroyed(DockWidget *dock) { if (!m_bTrackChildren) return; Split::docks_t::iterator itDocked; if (Split *leaf = findLeaf(m_split.data(), dock, &itDocked, nullptr, nullptr, true)) { itDocked->data()->widget = nullptr; lazyUpdateWidgetTree(); } } // The dock parent has changed. void DockContainer::dockReparented(DockWidget *dock) { if (!m_bTrackChildren) return; Split::docks_t::iterator itDocked; if (Split *leaf = findLeaf(m_split.data(), dock, &itDocked, nullptr, nullptr, true)) { DockContainer *container = findParent<DockContainer*>(dock); // Detect re-parenting outside this container if (container != this) { QObject::disconnect(dock, nullptr, this, nullptr); itDocked->data()->widget = nullptr; lazyUpdateWidgetTree(); } } } // The given dock was shown. void DockContainer::dockShown(DockWidget *dock) { if (!m_bTrackChildren) return; Split::docks_t::iterator itDocked; if (Split *leaf = findLeaf(m_split.data(), dock, &itDocked)) // Detect changes! if (!itDocked->data()->bActive) lazyUpdateWidgetTree(); } // The given dock was hidden. void DockContainer::dockHidden(DockWidget *dock) { if (!m_bTrackChildren) return; Split::docks_t::iterator itDocked; if (Split *leaf = findLeaf(m_split.data(), dock, &itDocked, nullptr, nullptr, true)) { itDocked->data()->bActive = false; lazyUpdateWidgetTree(); } } // Updates drag feedback. void DockContainer::dockDragged(QWidget *dock, QPoint screenPos) { if (m_bTrackChildren) dockDragDrop(dock, screenPos, false); } // Redocks dragged dock widgets. void DockContainer::dockDropped(QWidget *dock, QPoint screenPos) { if (m_bTrackChildren) dockDragDrop(dock, screenPos, true); } bool DockContainer::event(QEvent *event) { if (event->type() == DockLayoutChangedEventType) { if (m_dockUIRevision != m_dockLogicRevision) updateWidgetTree(); return true; } else return QFrame::event(event); }