blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
e9b3af9529d78d404405ea32d38fbbace0364340
27c1cb57c1608b65639c6194dc945a440df25473
/cg_exercise_02/cglib/lib/glm/glm/gtx/rotate_normalized_axis.hpp
25e2722492030374fa14b3de83fac22edc61f4c0
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "LicenseRef-scancode-happy-bunny" ]
permissive
brankyy/CG
41c7de721ffdba2aefda48db823521fb0d409710
217960504e0c723b73dab664e6ca0ccf3aeeeec8
refs/heads/master
2020-04-05T00:36:27.888286
2019-01-06T22:02:49
2019-01-06T22:02:49
156,395,913
0
0
null
null
null
null
UTF-8
C++
false
false
2,355
hpp
/// @ref gtx_rotate_normalized_axis /// @file glm/gtx/rotate_normalized_axis.hpp /// /// @see core (dependence) /// @see gtc_matrix_transform /// @see gtc_quaternion /// /// @defgroup gtx_rotate_normalized_axis GLM_GTX_rotate_normalized_axis /// @ingroup gtx /// /// Include <glm/gtx/rotate_normalized_axis.hpp> to use the features of this extension. /// /// Quaternions and matrices rotations around normalized axis. #pragma once // Dependency: #include "../glm.hpp" #include "../gtc/epsilon.hpp" #include "../gtc/quaternion.hpp" #ifndef GLM_ENABLE_EXPERIMENTAL # error "GLM: GLM_GTX_rotate_normalized_axis is an experimental extension and may change in the future. Use #define GLM_ENABLE_EXPERIMENTAL before including it, if you really want to use it." #endif #if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED) # pragma message("GLM: GLM_GTX_rotate_normalized_axis extension included") #endif namespace glm { /// @addtogroup gtx_rotate_normalized_axis /// @{ /// Builds a rotation 4 * 4 matrix created from a normalized axis and an angle. /// /// @param m Input matrix multiplied by this rotation matrix. /// @param angle Rotation angle expressed in radians. /// @param axis Rotation axis, must be normalized. /// @tparam T Value type used to build the matrix. Currently supported: half (not recommended), float or double. /// /// @see gtx_rotate_normalized_axis /// @see - rotate(T angle, T x, T y, T z) /// @see - rotate(mat<4, 4, T, Q> const& m, T angle, T x, T y, T z) /// @see - rotate(T angle, vec<3, T, Q> const& v) template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 4, T, Q> rotateNormalizedAxis( mat<4, 4, T, Q> const& m, T const& angle, vec<3, T, Q> const& axis); /// Rotates a quaternion from a vector of 3 components normalized axis and an angle. /// /// @param q Source orientation /// @param angle Angle expressed in radians. /// @param axis Normalized axis of the rotation, must be normalized. /// /// @see gtx_rotate_normalized_axis template<typename T, qualifier Q> GLM_FUNC_DECL tquat<T, Q> rotateNormalizedAxis( tquat<T, Q> const& q, T const& angle, vec<3, T, Q> const& axis); /// @} }//namespace glm #include "rotate_normalized_axis.inl" // CG_REVISION 81651e9d3440cf57bc693b5ac8ad23edb0a3bee0
b28026bbd189dab769b5d4b30b74ed26a1109c25
0c644d9604f248080bf49073ae61c4ff02a0feab
/C10/p566-4/소스.cpp
caf116cc552cc4cb517c2f7de88365f43739a669
[]
no_license
0083tony/Core-C-Programming
12bbcc3b5b6dbdda692678cd95590e28f8bfe64f
d846e1544e170c4d010d88a09cf2fd5f91adaf6d
refs/heads/master
2020-08-10T00:19:16.341746
2019-11-08T10:57:04
2019-11-08T10:57:04
214,206,173
2
1
null
null
null
null
WINDOWS-1252
C++
false
false
439
cpp
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> struct AA { int year = 0; int month = 0; int date = 0; }; void print_date(int year, int month, int date) { printf("%d / %d / %d\n", year, month, date); } int main(void) { struct AA a; printf("¿¬? "); scanf("%d", &a.year); printf("¿ù? "); scanf("%d", &a.month); printf("ÀÏ? "); scanf("%d", &a.date); print_date(a.year, a.month, a.date); return 0; }
c3dc78c791abcf5609fc5de37ca7567435ee778a
736e7201d8133f7b5262bbe3f313441c70367a3d
/misc/internal/windows/src/Winport/Include/CxImage/ximapng.h
57915562c1c96cbde0f33b0be47c2ce2bbe93c9d
[]
no_license
KarlHegbloom/texmacs
32eea6e344fd27ff02ff6a8027c065b32ff2b976
ddc05600d3d15a0fbc72a50cb657e6c8ebe7d638
refs/heads/master
2021-01-16T23:52:33.776123
2018-06-08T07:47:26
2018-06-08T07:47:26
57,338,153
24
4
null
2017-07-17T05:47:17
2016-04-28T22:37:14
Tcl
UTF-8
C++
false
false
3,101
h
/* * File: ximapng.h * Purpose: PNG Image Class Loader and Writer */ /* === C R E D I T S & D I S C L A I M E R S ============== * CxImagePNG (c) 07/Aug/2001 <[email protected]> * Permission is given by the author to freely redistribute and include * this code in any program as long as this credit is given where due. * * CxImage version 5.71 25/Apr/2003 * See the file history.htm for the complete bugfix and news report. * * Special thanks to Troels Knakkergaard for new features, enhancements and bugfixes * * original CImagePNG and CImageIterator implementation are: * Copyright: (c) 1995, Alejandro Aguilar Sierra <asierra(at)servidor(dot)unam(dot)mx> * * libpng version 1.2.1 - December 12, 2001 * Copyright (c) 1998-2001 Glenn Randers-Pehrson * * COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE * OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED * CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT * THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY * SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL * PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. * * Use at your own risk! * ========================================================== */ #if !defined(__ximaPNG_h) #define __ximaPNG_h #include "ximage.h" #if CXIMAGE_SUPPORT_PNG extern "C" { #include "../png/png.h" } class CxImagePNG: public CxImage { public: CxImagePNG(): CxImage(CXIMAGE_FORMAT_PNG) {} // bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_PNG);} // bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_PNG);} bool Decode(CxFile * hFile); bool Encode(CxFile * hFile); bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } protected: void ima_png_error(png_struct *png_ptr, char *message); void expand2to4bpp(BYTE* prow); static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length) { CxFile* hFile = (CxFile*)png_ptr->io_ptr; if (hFile->Read(data,1,length) != length) png_error(png_ptr, "Read Error"); } static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { CxFile* hFile = (CxFile*)png_ptr->io_ptr; if (hFile->Write(data,1,length) != length) png_error(png_ptr, "Write Error"); } static void user_flush_data(png_structp png_ptr) { CxFile* hFile = (CxFile*)png_ptr->io_ptr; if (!hFile->Flush()) png_error(png_ptr, "Flush Error"); } static void user_error_fn(png_structp png_ptr,png_const_charp error_msg) { strncpy((char*)png_ptr->error_ptr,error_msg,255); longjmp(png_ptr->jmpbuf, 1); } }; #endif #endif
fa2b4c2ae8e2c4c1c665b29e582d0fb73999ca0d
536205b4438d409e2bc6349efaa19d4603622249
/求最大公约数/main.cpp
958495f0310db1cd863ab17c887a45c9c7d75a79
[]
no_license
cyendra/ACM_Training_Chapter_One
78a8b38f6465dfe5e4238057830fed788769f5c4
8268a66edf1cc5ba9a0e5019b34b4ec97ce55268
refs/heads/master
2020-12-30T10:37:10.269991
2013-11-17T08:40:03
2013-11-17T08:40:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
319
cpp
#include <iostream> #include <cstdio> using namespace std; int gcd(int a,int b) { if (a<b) { swap(a,b); } if (b==0) { return a; } else { return gcd(b,a % b); } } int main() { int a,b; scanf("%d%d",&a,&b); printf("%d",gcd(a,b)); return 0; }
fd846a870302a9edbb23ea60d45ad53732d9138e
5456502f97627278cbd6e16d002d50f1de3da7bb
/media/base/audio_buffer_converter.cc
a60dec571fb00403aefdbbb0b12c4ba5fa38575b
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,729
cc
// 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 "media/base/audio_buffer_converter.h" #include <algorithm> #include <cmath> #include "base/logging.h" #include "media/base/audio_buffer.h" #include "media/base/audio_bus.h" #include "media/base/audio_decoder_config.h" #include "media/base/audio_timestamp_helper.h" #include "media/base/sinc_resampler.h" #include "media/base/timestamp_constants.h" #include "media/base/vector_math.h" namespace media { // Is the config presented by |buffer| a config change from |params|? static bool IsConfigChange(const AudioParameters& params, const scoped_refptr<AudioBuffer>& buffer) { return buffer->sample_rate() != params.sample_rate() || buffer->channel_count() != params.channels() || buffer->channel_layout() != params.channel_layout(); } AudioBufferConverter::AudioBufferConverter(const AudioParameters& output_params) : output_params_(output_params), input_params_(output_params), last_input_buffer_offset_(0), input_frames_(0), buffered_input_frames_(0.0), io_sample_rate_ratio_(1.0), timestamp_helper_(output_params_.sample_rate()), is_flushing_(false) {} AudioBufferConverter::~AudioBufferConverter() {} void AudioBufferConverter::AddInput(const scoped_refptr<AudioBuffer>& buffer) { // On EOS flush any remaining buffered data. if (buffer->end_of_stream()) { Flush(); queued_outputs_.push_back(buffer); return; } // We'll need a new |audio_converter_| if there was a config change. if (IsConfigChange(input_params_, buffer)) ResetConverter(buffer); // Pass straight through if there's no work to be done. if (!audio_converter_) { queued_outputs_.push_back(buffer); return; } if (timestamp_helper_.base_timestamp() == kNoTimestamp) timestamp_helper_.SetBaseTimestamp(buffer->timestamp()); queued_inputs_.push_back(buffer); input_frames_ += buffer->frame_count(); ConvertIfPossible(); } bool AudioBufferConverter::HasNextBuffer() { return !queued_outputs_.empty(); } scoped_refptr<AudioBuffer> AudioBufferConverter::GetNextBuffer() { DCHECK(!queued_outputs_.empty()); scoped_refptr<AudioBuffer> out = queued_outputs_.front(); queued_outputs_.pop_front(); return out; } void AudioBufferConverter::Reset() { audio_converter_.reset(); queued_inputs_.clear(); queued_outputs_.clear(); timestamp_helper_.SetBaseTimestamp(kNoTimestamp); input_params_ = output_params_; input_frames_ = 0; buffered_input_frames_ = 0.0; last_input_buffer_offset_ = 0; } void AudioBufferConverter::ResetTimestampState() { Flush(); timestamp_helper_.SetBaseTimestamp(kNoTimestamp); } double AudioBufferConverter::ProvideInput(AudioBus* audio_bus, uint32_t frames_delayed) { DCHECK(is_flushing_ || input_frames_ >= audio_bus->frames()); int requested_frames_left = audio_bus->frames(); int dest_index = 0; while (requested_frames_left > 0 && !queued_inputs_.empty()) { scoped_refptr<AudioBuffer> input_buffer = queued_inputs_.front(); int frames_to_read = std::min(requested_frames_left, input_buffer->frame_count() - last_input_buffer_offset_); input_buffer->ReadFrames( frames_to_read, last_input_buffer_offset_, dest_index, audio_bus); last_input_buffer_offset_ += frames_to_read; if (last_input_buffer_offset_ == input_buffer->frame_count()) { // We've consumed all the frames in |input_buffer|. queued_inputs_.pop_front(); last_input_buffer_offset_ = 0; } requested_frames_left -= frames_to_read; dest_index += frames_to_read; } // If we're flushing, zero any extra space, otherwise we should always have // enough data to completely fulfill the request. if (is_flushing_ && requested_frames_left > 0) { audio_bus->ZeroFramesPartial(audio_bus->frames() - requested_frames_left, requested_frames_left); } else { DCHECK_EQ(requested_frames_left, 0); } input_frames_ -= audio_bus->frames() - requested_frames_left; DCHECK_GE(input_frames_, 0); buffered_input_frames_ += audio_bus->frames() - requested_frames_left; // Full volume. return 1.0; } void AudioBufferConverter::ResetConverter( const scoped_refptr<AudioBuffer>& buffer) { Flush(); audio_converter_.reset(); input_params_.Reset( input_params_.format(), buffer->channel_layout(), buffer->sample_rate(), input_params_.bits_per_sample(), // If resampling is needed and the FIFO disabled, the AudioConverter will // always request SincResampler::kDefaultRequestSize frames. Otherwise it // will use the output frame size. buffer->sample_rate() == output_params_.sample_rate() ? output_params_.frames_per_buffer() : SincResampler::kDefaultRequestSize); input_params_.set_channels_for_discrete(buffer->channel_count()); io_sample_rate_ratio_ = static_cast<double>(input_params_.sample_rate()) / output_params_.sample_rate(); // If |buffer| matches |output_params_| we don't need an AudioConverter at // all, and can early-out here. if (!IsConfigChange(output_params_, buffer)) return; // Note: The FIFO is disabled to avoid extraneous memcpy(). audio_converter_.reset( new AudioConverter(input_params_, output_params_, true)); audio_converter_->AddInput(this); } void AudioBufferConverter::ConvertIfPossible() { DCHECK(audio_converter_); int request_frames = 0; if (is_flushing_) { // If we're flushing we want to convert *everything* even if this means // we'll have to pad some silence in ProvideInput(). request_frames = ceil((buffered_input_frames_ + input_frames_) / io_sample_rate_ratio_); } else { // How many calls to ProvideInput() we can satisfy completely. int chunks = input_frames_ / input_params_.frames_per_buffer(); // How many output frames that corresponds to: request_frames = chunks * audio_converter_->ChunkSize(); } if (!request_frames) return; scoped_refptr<AudioBuffer> output_buffer = AudioBuffer::CreateBuffer(kSampleFormatPlanarF32, output_params_.channel_layout(), output_params_.channels(), output_params_.sample_rate(), request_frames); std::unique_ptr<AudioBus> output_bus = AudioBus::CreateWrapper(output_buffer->channel_count()); int frames_remaining = request_frames; // The AudioConverter wants requests of a fixed size, so we'll slide an // AudioBus of that size across the |output_buffer|. while (frames_remaining != 0) { // It's important that this is a multiple of AudioBus::kChannelAlignment in // all requests except for the last, otherwise downstream SIMD optimizations // will crash on unaligned data. const int frames_this_iteration = std::min( static_cast<int>(SincResampler::kDefaultRequestSize), frames_remaining); const int offset_into_buffer = output_buffer->frame_count() - frames_remaining; // Wrap the portion of the AudioBuffer in an AudioBus so the AudioConverter // can fill it. output_bus->set_frames(frames_this_iteration); for (int ch = 0; ch < output_buffer->channel_count(); ++ch) { output_bus->SetChannelData( ch, reinterpret_cast<float*>(output_buffer->channel_data()[ch]) + offset_into_buffer); } // Do the actual conversion. audio_converter_->Convert(output_bus.get()); frames_remaining -= frames_this_iteration; buffered_input_frames_ -= frames_this_iteration * io_sample_rate_ratio_; } // Compute the timestamp. output_buffer->set_timestamp(timestamp_helper_.GetTimestamp()); timestamp_helper_.AddFrames(request_frames); queued_outputs_.push_back(output_buffer); } void AudioBufferConverter::Flush() { if (!audio_converter_) return; is_flushing_ = true; ConvertIfPossible(); is_flushing_ = false; audio_converter_->Reset(); DCHECK_EQ(input_frames_, 0); DCHECK_EQ(last_input_buffer_offset_, 0); DCHECK_LT(buffered_input_frames_, 1.0); DCHECK(queued_inputs_.empty()); buffered_input_frames_ = 0.0; } } // namespace media
4d7519c6c0dccdb9a3466832f4e745614b3aa648
b1af8bb863a6730e6e4e93129efbad89d33cf509
/SDK/SCUM_MovableWindow_functions.cpp
a98717a34b0e48d5af9a429c8717837cff74089d
[]
no_license
frankie-11/SCUM_SDK7.13.2020
b3bbd8fb9b6c03120b865a6254eca6a2389ea654
7b48bcf9e8088aa8917c07dd6756eac90e3f693a
refs/heads/master
2022-11-16T05:48:55.729087
2020-07-13T23:48:50
2020-07-13T23:48:50
279,433,512
0
1
null
null
null
null
UTF-8
C++
false
false
7,432
cpp
// SCUM (4.24) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function MovableWindow.MovableWindow_C.AttachContentWidget // (NetReliable, Static, NetMulticast, Private, Protected, Delegate, NetServer, HasDefaults, NetClient, DLLImport, BlueprintEvent, BlueprintPure, Const, NetValidate) // Parameters: // bool* NewParam (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UMovableWindow_C::STATIC_AttachContentWidget(bool* NewParam) { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.AttachContentWidget"); UMovableWindow_C_AttachContentWidget_Params params; params.NewParam = NewParam; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MovableWindow.MovableWindow_C.OnMouseButtonUp // (Net, Native, Static, NetMulticast, Private, Protected, Delegate, NetServer, HasDefaults, NetClient, DLLImport, BlueprintEvent, BlueprintPure, Const, NetValidate) // Parameters: // struct FGeometry* MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) // struct FPointerEvent* MouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) // struct FEventReply ReturnValue (Parm, OutParm, ReturnParm) struct FEventReply UMovableWindow_C::STATIC_OnMouseButtonUp(struct FGeometry* MyGeometry, struct FPointerEvent* MouseEvent) { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.OnMouseButtonUp"); UMovableWindow_C_OnMouseButtonUp_Params params; params.MyGeometry = MyGeometry; params.MouseEvent = MouseEvent; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function MovableWindow.MovableWindow_C.OnDragDetected // (Net, NetRequest, Event, Static, MulticastDelegate, Public, Delegate, HasDefaults, NetClient, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) // struct FPointerEvent* PointerEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) // class UDragDropOperation* Operation (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UMovableWindow_C::STATIC_OnDragDetected(struct FGeometry* MyGeometry, struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation) { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.OnDragDetected"); UMovableWindow_C_OnDragDetected_Params params; params.MyGeometry = MyGeometry; params.PointerEvent = PointerEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Operation != nullptr) *Operation = params.Operation; } // Function MovableWindow.MovableWindow_C.Construct // (NetRequest, Event, Static, MulticastDelegate, Public, Delegate, HasDefaults, NetClient, BlueprintCallable, BlueprintEvent) void UMovableWindow_C::STATIC_Construct() { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.Construct"); UMovableWindow_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MovableWindow.MovableWindow_C.Tick // (Net, NetReliable, NetRequest, Exec, Native, Event, NetResponse, NetMulticast, Private, Protected, Delegate, NetServer, HasDefaults, NetClient, DLLImport, BlueprintEvent, BlueprintPure, Const, NetValidate) // Parameters: // struct FGeometry* MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) // float* InDeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UMovableWindow_C::Tick(struct FGeometry* MyGeometry, float* InDeltaTime) { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.Tick"); UMovableWindow_C_Tick_Params params; params.MyGeometry = MyGeometry; params.InDeltaTime = InDeltaTime; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MovableWindow.MovableWindow_C.StartDrag // (Net, NetReliable, Event, Static, MulticastDelegate, Public, Delegate, HasDefaults, NetClient, BlueprintCallable, BlueprintEvent) void UMovableWindow_C::STATIC_StartDrag() { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.StartDrag"); UMovableWindow_C_StartDrag_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MovableWindow.MovableWindow_C.Init // (Net, Exec, Native, Static, NetMulticast, Protected, Delegate, NetServer, HasOutParms, HasDefaults, NetClient, DLLImport, BlueprintEvent, BlueprintPure, Const, NetValidate) // Parameters: // struct FVector2D* Dimensions (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // struct FString* Title (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) void UMovableWindow_C::STATIC_Init(struct FVector2D* Dimensions, struct FString* Title) { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.Init"); UMovableWindow_C_Init_Params params; params.Dimensions = Dimensions; params.Title = Title; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MovableWindow.MovableWindow_C.OnStartDrag // (NetReliable, Event, Static, MulticastDelegate, Public, Delegate, HasDefaults, NetClient, BlueprintCallable, BlueprintEvent) void UMovableWindow_C::STATIC_OnStartDrag() { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.OnStartDrag"); UMovableWindow_C_OnStartDrag_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function MovableWindow.MovableWindow_C.ExecuteUbergraph_MovableWindow // (NetReliable, NetRequest, Event, NetResponse, NetMulticast, MulticastDelegate, Private, Delegate, HasDefaults, NetClient, BlueprintCallable, BlueprintEvent) // Parameters: // int* EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UMovableWindow_C::ExecuteUbergraph_MovableWindow(int* EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function MovableWindow.MovableWindow_C.ExecuteUbergraph_MovableWindow"); UMovableWindow_C_ExecuteUbergraph_MovableWindow_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
e4ba383c5a65824ea07ef3506356be1b117757d2
df37112a73ede94bd1a712e59d4e3aaca474a250
/lab6/lab6.cpp
9fef53c742ff01aab33987a0911b10de0c9376e1
[]
no_license
xsthunder/rpi-data-structure
3d5b21e479304473ac2ebcc9bc2a8a7074f7c426
b072b3af03d8db1eedde348411144cbe96d36770
refs/heads/master
2020-06-01T16:52:17.957826
2019-07-27T08:21:20
2019-07-27T08:21:20
190,856,112
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
cpp
#include <iostream> #include <cmath> #include <list> #include "dslist.h" int main() { // ======================================= // CHECKPOINT 1 // create a list of the sqrt of the first 10 integers dslist<double> a; for (int i = 0; i < 10; ++i) a.push_back(sqrt(i)); // print out details of the list assert (a.size() == 10); assert (a.front() == 0); assert (a.back() == 3); dslist<double>::iterator itr; std::cout << "Elements = "; for (itr = a.begin(); itr != a.end(); ++itr) std::cout << " " << *itr; std::cout << std::endl; // clear out the list a.clear(); assert (a.size() == 0); // simple tests of push_front, pop_front, and pop_back a.push_front(5); a.push_back(7); a.push_front(3); a.push_back(9); assert (a.size() == 4); assert (*(a.begin()) == 3); assert (*(++a.begin()) == 5); assert (*(++(++a.begin())) == 7); assert (*(++(++(++a.begin()))) == 9); std::cout << "Elements = "; for (itr = a.begin(); itr != a.end(); ++itr) std::cout << " " << *itr; std::cout << std::endl; a.pop_back(); a.pop_front(); assert (a.size() == 2); assert (*(a.begin()) == 5); assert (*(++a.begin()) == 7); std::cout << "Elements = "; for (itr = a.begin(); itr != a.end(); ++itr) std::cout << " " << *itr; std::cout << std::endl; a.pop_back(); a.pop_front(); assert (a.size() == 0); assert (a.begin() == a.end()); return 0; }
cb1d767a78fdc4e25140f0805453cb0eda30bb51
c6ecad18dd41ea69c22baf78dfeb95cf9ba547d0
/src/boost_1_42_0/libs/units/test/fail_quantity_add_assign.cpp
900e0af71d1c4c55a62e4ea99d96768d5ccd2eeb
[ "BSL-1.0" ]
permissive
neuschaefer/qnap-gpl
b1418d504ebe17d7a31a504d315edac309430fcf
7bb76f6cfe7abef08777451a75924f667cca335b
refs/heads/master
2022-08-16T17:47:37.015870
2020-05-24T18:56:05
2020-05-24T18:56:05
266,605,194
3
2
null
null
null
null
UTF-8
C++
false
false
740
cpp
// Boost.Units - A C++ library for zero-overhead dimensional analysis and // unit/quantity manipulation and conversion // // Copyright (C) 2003-2008 Matthias Christian Schabel // Copyright (C) 2008 Steven Watanabe // // 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 \brief fail_quantity_add_assign.cpp \detailed Test += of quantity from different dimensions. Output: @verbatim @endverbatim **/ #include <boost/units/quantity.hpp> #include <boost/units/systems/si.hpp> namespace bu = boost::units; int main(int,char *[]) { bu::quantity<bu::si::length> T1; T1 += 2.0 * bu::si::seconds; return 0; }
cba02995d8711654f57aa252c4a21d576ca034af
bb910965169bfbb1fd36753fd0209e77cabffb05
/tests/stdgpu/openmp/vector.cpp
b3a3d3f2d56ddb3a9abf941220b54f354f887359
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
stotko/stdgpu
8659aeacf82c807c1162e796d09a422c23a431bf
e085756a2cc5f99a6610301211ffc12b44aa2f65
refs/heads/master
2023-09-02T01:23:10.271531
2023-08-28T13:36:02
2023-08-28T13:56:17
202,712,923
1,012
75
Apache-2.0
2023-09-13T13:54:36
2019-08-16T11:04:33
C++
UTF-8
C++
false
false
635
cpp
/* * Copyright 2019 Patrick Stotko * 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 <stdgpu/vector.inc>
05089a39f3dacce4cecea4798575e6844938682d
5b50e221121bd40d97f2fd7f4a3f6852865a146b
/newdev2population.h
5dfbdd2ecc0cce5f25c656113ef51a82706d9f40
[]
no_license
nb-/ParticleSwarms
925d7419d011895333c1e4f1ddf07cc66faafac7
583bd3ed34bcf5cb2d011353e16f785e30d33c65
refs/heads/master
2016-09-11T03:17:56.317861
2013-11-23T17:30:35
2013-11-23T17:30:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,519
h
#ifndef NEWDEV2POPULATION_H #define NEWDEV2POPULATION_H //================================================================== // Second Implemented Idea // Eval DParticles // Sort by val // Assign pool size based on ranking // Assign neighbour based on ranking // Best is special case, gauss range over itself somehow // generate points with own pos and neighbour // set point to best found //================================================================== #include <vector> #include <stdlib.h> #include "population.h" class NewDev2Population : public Population { protected: const int mDSize; //'Distribution' Particles double* mDValues; //Similar to PrevBest, but act differently double* mDPositions; double* mDAPValues; //seperate values used for apriori int* mPoolIndices; //points assigned to each dPoint std::vector<std::pair<double,int> > mValSort;//for sorting, maintained for better performance public: NewDev2Population(int pointPopSize, int dPopSize, OptimizationFunction* optFunc); virtual ~NewDev2Population(); int getDSize() const; virtual double getBestValueFound() const; virtual double* getBestPositionFoundPointer() const ; double getDValue(int individualIndex) const; double* getDPositionPointer(int individualIndex) const; virtual void initializePopulation(double* range = 0); virtual void evaluatePopulation(); virtual void updatePopulation(); }; #endif // NEWDEV2POPULATION_H
75d5f12c66ade9342c05fbb64f2b72f48eeb48bc
5a60d60fca2c2b8b44d602aca7016afb625bc628
/aws-cpp-sdk-iot/include/aws/iot/model/RemoveThingFromBillingGroupResult.h
7b8a94b0bc5c8d7958904b311d5d78a0ea8dd601
[ "Apache-2.0", "MIT", "JSON" ]
permissive
yuatpocketgems/aws-sdk-cpp
afaa0bb91b75082b63236cfc0126225c12771ed0
a0dcbc69c6000577ff0e8171de998ccdc2159c88
refs/heads/master
2023-01-23T10:03:50.077672
2023-01-04T22:42:53
2023-01-04T22:42:53
134,497,260
0
1
null
2018-05-23T01:47:14
2018-05-23T01:47:14
null
UTF-8
C++
false
false
808
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/iot/IoT_EXPORTS.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace IoT { namespace Model { class RemoveThingFromBillingGroupResult { public: AWS_IOT_API RemoveThingFromBillingGroupResult(); AWS_IOT_API RemoveThingFromBillingGroupResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); AWS_IOT_API RemoveThingFromBillingGroupResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); }; } // namespace Model } // namespace IoT } // namespace Aws
3792ef941c66c35a4185b9e04c3c8ffd49ef3d4c
2e18997d050334d9a8bc52401d2243b6ecfe811c
/main/main.ino
9025a814ff75f1b108ce2f9e336138765b2a958c
[]
no_license
Alfarie/SHM1.0-MCU
4ae7af574b1606514b9e3796bc0022aed9268873
30b57bf31e09b277ad1c7e54e6572cc0a5ddab35
refs/heads/master
2020-03-23T14:50:32.076121
2019-06-06T10:10:32
2019-06-06T10:10:32
141,703,024
0
0
null
null
null
null
UTF-8
C++
false
false
3,816
ino
#define VERSION "1.0.1" #include <Task.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> #include <EEPROM.h> #include <SPI.h> // #include <MCP320X.h> #include <LibHumidity.h> HardwareSerial &mpuCom = Serial3; HardwareSerial &debugCom = Serial; LibHumidity humidity = LibHumidity(0); // MCP320X adc(53); LiquidCrystal_I2C lcd(0x3E, 16, 2); struct Timer { int start; int end; }; TaskManager taskManager; boolean DEBUG = false; int ON_S = HIGH; int OFF_S = LOW; #include "./global/gpio.h" #include "./global/eeprom_addr.h" #include "./global/global_control.h" #include "./modules/mode/debug.h" #include "./modules/DateTime.h" DateTimeTask dt; #include "./modules/RTC.h" void FreshWaterCallback(uint8_t); void CookCallback(uint8_t); void CirculateCallback(uint8_t); #include "./modules/Sensor.h" Sensor sensor; #include "./modules/control_process/co2Control.h" #include "./modules/control_process/eccontrol.h" #include "./modules/control_process/ectimercontrol.h" #include "./modules/control_process/phcontrol.h" #include "./modules/control_process/timercontrol.h" #include "./modules/communication.h" PHControl phcontrol(&sensor); ECControl eccontrol(&sensor); CO2Control co2control(&sensor); TimerControl timercontrol(&dt); ECTimerControl ectimercontrol(&dt); #include "./modules/wt_process/FreshWater.h" #include "./modules/wt_process/Cook.h" #include "./modules/wt_process/CirculateWater.h" FreshWater freshWater(FreshWaterCallback); Cook cook(CookCallback, &eccontrol, &phcontrol); CirculateWater circulateWater(CirculateCallback); Communication com(&sensor, &eccontrol,&ectimercontrol, &phcontrol, &co2control, &timercontrol, &dt); DebugCheck debug; void setup() { SPI.begin(); // adc.begin(); Wire.begin(); mpuCom.begin(57600); debugCom.begin(57600); SerialOnStart(); // Initialize EEPROM GlobalControl::InitEEPROM(); // set pin mode to all pin Gpio::InitPin(); taskManager.StartTask(&dt); taskManager.StartTask(RTC::instance()); taskManager.StartTask(&com); //start Water process taskManager.StartTask(&sensor); //control module if(GlobalControl::EC_MODE == 0){ taskManager.StartTask(&eccontrol); } else if (GlobalControl::EC_MODE == 1){ taskManager.StartTask(&ectimercontrol); } } void loop() { taskManager.Loop(); } void ProcessStart() { taskManager.StartTask(&freshWater); lcd.setCursor(0, 0); lcd.print("State: FreshWater"); } void FreshWaterCallback(uint8_t state) { //mpuCom.println("FreshWater Callback" + String(state)); taskManager.StopTask(&freshWater); lcd.clear(); lcd.setCursor(0, 0); lcd.print("State: Cook"); taskManager.StartTask(&cook); } void CookCallback(uint8_t state) { //mpuCom.println("Cook Callback" + String(state)); taskManager.StopTask(&cook); lcd.clear(); lcd.setCursor(0, 0); lcd.print("State: Circulate"); taskManager.StartTask(&circulateWater); } void CirculateCallback(uint8_t state) { //mpuCom.println("FeedWater Callback" + String(state)); taskManager.StopTask(&circulateWater); lcd.clear(); lcd.setCursor(0, 0); lcd.print("State: FreshWater"); taskManager.StartTask(&freshWater); } void SerialOnStart() { String debugMode = (DEBUG) ? "true" : "false"; mpuCom.println(); mpuCom.println("[Info] PlantLab Demo Version."); mpuCom.println("[Info] Initialize..."); mpuCom.println("[Info] Debug Mode: " + debugMode); mpuCom.println("[Info] successful."); mpuCom.println(); debugCom.println(); debugCom.println("[Info] PlantLab Demo Version."); debugCom.println("[Info] Initialize..."); debugCom.println("[Info] Debug Mode: " + debugMode); debugCom.println("[Info] successful."); debugCom.println(); }
9c8786f0b5d905101f5379d2149de68f82fa0d4f
ddd15715b110587ca5ffeb75fba1f7d47c76dfeb
/EmojiGame/GUILoadEmoji.cpp
0f0e9c07fe01f22b01f2aad87173bd5f05b9d474
[]
no_license
Andy608/CSI-140-EmojiGame
7727b8a201f7ebacfd971a76fc943519113e786c
9872b1f633b36a0fbd55c9e9fd9ce4d35833b041
refs/heads/master
2020-12-15T14:20:00.943730
2020-01-20T15:28:17
2020-01-20T15:28:17
235,132,913
0
0
null
null
null
null
UTF-8
C++
false
false
3,734
cpp
/* Author: Andrew Rimpici Class: CSI-140-07 Assignment: Final Project Date Assigned: 11/30/2016 Due Date: 12/9/2016 Description: An emoji pet simulator program where you take care of your emoji's and keeping them alive. Certification of Authenticity: I certify that this is entirely my own work, except where I have given fully-documented references to the work of others. I understand the definition and consequences of plagiarism and acknowledge that the assessor of this assignment may, for the purpose of assessing this assignment: - Reproduce this assignment and provide a copy to another member of academic staff; and/or - Communicate a copy of this assignment to a plagiarism checking service (which may then retain a copy of this assignment on its database for the purpose of future plagiarism checking) */ #include "GUILoadEmoji.h" #include "GUIPlayScreen.h" #include "GUIMainMenu.h" #include "Loop.h" /* Draws the base load emoji menu. */ void drawLoadEmojiMenu() { drawLine(0); setCursorForCenterText(guiWidth); cout << endl; setCursorForCenterText(guiWidth); cout << endl; setCursorForCenterText(guiWidth); cout << endl; setCursorForCenterText(guiWidth); cout << centerText(guiWidth, "This is the Emoji Pet Loader Menu") << endl; setCursorForCenterText(guiWidth); cout << centerText(guiWidth, "---") << endl; setCursorForCenterText(guiWidth); cout << centerText(guiWidth, "All of your saved pets are listed below.") << endl; setCursorForCenterText(guiWidth); cout << endl; drawLine(8); cout << endl; setCursorForCenterText(guiWidth); int cursorX = getConsoleCursorX(); int cursorY = getConsoleCursorY(); if (emojiCount == 0) { cout << "You currently do not have any Emoji Pets." << endl; } else { printAllEmojiNames(cursorX + 1, cursorY, false); } setCursorPos(cursorX, cursorY + 12); cout << "Press ESC to return to the Main Menu." << endl; } /* Prints all of the emojis saved in the file out in a nice list. */ void printAllEmojiNames(int cursorX, int cursorY, bool isDeleting) { for (int i = 0; i < emojiCount; i++) { if (i >= MAX_SLOT_PER_COLUMN) { setCursorPos(cursorX + SLOT_OFFSET_X, cursorY + ((i - MAX_SLOT_PER_COLUMN) * 2)); } else { setCursorPos(cursorX, cursorY + (i * 2)); } if (isDeleting) { cout << " - Press " << (i + 1) << " to delete your emoji pet, " << emojiName[i] << endl << endl; } else { cout << " - Press " << (i + 1) << " to go to your emoji pet, " << emojiName[i] << endl << endl; } } } /* Updates the load emoji menu every tick. */ void updateLoadEmojiMenu() { setCursorForCenterText(guiWidth); int cursorX = getConsoleCursorX(); setCursorPos(cursorX, TITLE_EMOJI_Y); clearScreenPortion(cursorX, TITLE_EMOJI_Y, guiWidth, TITLE_EMOJI_LENGTH_Y); setCursorForCenterText(guiWidth); cout << centerText(guiWidth, getEmoji(Awake, Happy)); clearScreenPortion(cursorX + ERROR_MESSAGE_X, ERROR_LOAD_EMOJI_MENU_MESSAGE_Y, ERROR_MESSAGE_LENGTH_X, ERROR_MESSAGE_LENGTH_Y); cout.flush(); setCursorPos(cursorX + ERROR_MESSAGE_X, ERROR_LOAD_EMOJI_MENU_MESSAGE_Y); } /* Handles load emoji menu input. */ void handleEmojiLoadMenuInput(char input) { if (input == ESC_KEY) { switchScreen(MainMenu); return; } for (int i = ONE; i < ONE + emojiCount; i++) { if (input == i) { currentEmojiIndex = i - ONE; switchScreen(PlayScreen); return; } } setCursorForCenterText(guiWidth); int cursorX = getConsoleCursorX(); clearScreenPortion(cursorX + ERROR_MESSAGE_X, ERROR_LOAD_EMOJI_MENU_MESSAGE_Y, ERROR_MESSAGE_LENGTH_X, ERROR_MESSAGE_LENGTH_Y); cout.flush(); setCursorPos(cursorX + ERROR_MESSAGE_X, ERROR_LOAD_EMOJI_MENU_MESSAGE_Y); cout << "Please enter a valid menu option!" << endl; }
f5eebf90068fb691081bcc606ad9635f297d8e34
21611ce560980fa6f5f53563c44f8cde79d89f1e
/DialogMFC/DialogMFC/DialogMFC.h
5cfb58b42002fff20ccf2b9a6f2b0f0faa41a163
[]
no_license
TomShiDi/git-Lib
80ffcb2b5a3a6fe3657c8ec23bba67502b9c3c8b
eaf908dd15003dd437f32623584524819dbdc052
refs/heads/master
2020-04-15T01:22:19.173862
2019-01-06T04:53:03
2019-01-06T04:53:03
164,273,598
0
1
null
null
null
null
GB18030
C++
false
false
474
h
// DialogMFC.h : PROJECT_NAME 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件" #endif #include "resource.h" // 主符号 // CDialogMFCApp: // 有关此类的实现,请参阅 DialogMFC.cpp // class CDialogMFCApp : public CWinApp { public: CDialogMFCApp(); // 重写 public: virtual BOOL InitInstance(); // 实现 DECLARE_MESSAGE_MAP() }; extern CDialogMFCApp theApp;
d741743c0f83f585c824d4ef67ecfd213ddeada4
7fe3e44cf771a7a811890a7d2ac78ed6708ddedf
/Engine/source/gui/editor/guiInspector.cpp
f08b3f5bac63e7871792fd2f342eb5487b2eb855
[]
no_license
konradkiss/meshloop
988ee721fb6463fbfece183c70f678c047215dd5
25b98ce223d21e232593a6c4dc2d6d863aace02c
refs/heads/master
2021-03-19T13:36:21.104735
2015-05-21T13:00:55
2015-05-21T13:00:55
36,012,137
0
0
null
null
null
null
UTF-8
C++
false
false
14,911
cpp
//----------------------------------------------------------------------------- // Torque 3D // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- #include "gui/editor/guiInspector.h" #include "gui/editor/inspector/field.h" #include "gui/editor/inspector/group.h" #include "gui/buttons/guiIconButtonCtrl.h" #include "gui/editor/inspector/dynamicGroup.h" #include "gui/containers/guiScrollCtrl.h" #include "gui/editor/inspector/customField.h" GuiInspector::GuiInspector() : mTarget( NULL ), mDividerPos( 0.35f ), mDividerMargin( 5 ), mOverDivider( false ), mMovingDivider( false ), mHLField( NULL ) { mPadding = 1; } GuiInspector::~GuiInspector() { clearGroups(); } IMPLEMENT_CONOBJECT(GuiInspector); // ConsoleObject bool GuiInspector::onAdd() { if( !Parent::onAdd() ) return false; return true; } void GuiInspector::initPersistFields() { addField( "dividerMargin", TypeS32, Offset( mDividerMargin, GuiInspector ) ); addField( "groupFilters", TypeRealString, Offset( mGroupFilters, GuiInspector ), "Specify groups that should be shown or not. Specifying 'shown' implicitly does 'not show' all other groups. Example string: +name -otherName" ); Parent::initPersistFields(); } // SimObject void GuiInspector::onDeleteNotify( SimObject *object ) { if ( object == mTarget ) clearGroups(); } // GuiControl void GuiInspector::parentResized(const RectI &oldParentRect, const RectI &newParentRect) { GuiControl *parent = getParent(); if ( parent && dynamic_cast<GuiScrollCtrl*>(parent) != NULL ) { GuiScrollCtrl *scroll = dynamic_cast<GuiScrollCtrl*>(parent); setWidth( ( newParentRect.extent.x - ( scroll->scrollBarThickness() + 4 ) ) ); } else Parent::parentResized(oldParentRect,newParentRect); } bool GuiInspector::resize( const Point2I &newPosition, const Point2I &newExtent ) { //F32 dividerPerc = (F32)getWidth() / (F32)mDividerPos; bool result = Parent::resize( newPosition, newExtent ); //mDividerPos = (F32)getWidth() * dividerPerc; updateDivider(); return result; } GuiControl* GuiInspector::findHitControl( const Point2I &pt, S32 initialLayer ) { if ( mOverDivider || mMovingDivider ) return this; return Parent::findHitControl( pt, initialLayer ); } void GuiInspector::getCursor( GuiCursor *&cursor, bool &showCursor, const GuiEvent &lastGuiEvent ) { GuiCanvas *pRoot = getRoot(); if( !pRoot ) return; S32 desiredCursor = mOverDivider ? PlatformCursorController::curResizeVert : PlatformCursorController::curArrow; // Bail if we're already at the desired cursor if ( pRoot->mCursorChanged == desiredCursor ) return; PlatformWindow *pWindow = static_cast<GuiCanvas*>(getRoot())->getPlatformWindow(); AssertFatal(pWindow != NULL,"GuiControl without owning platform window! This should not be possible."); PlatformCursorController *pController = pWindow->getCursorController(); AssertFatal(pController != NULL,"PlatformWindow without an owned CursorController!"); // Now change the cursor shape pController->popCursor(); pController->pushCursor(desiredCursor); pRoot->mCursorChanged = desiredCursor; } void GuiInspector::onMouseMove(const GuiEvent &event) { if ( collideDivider( globalToLocalCoord( event.mousePoint ) ) ) mOverDivider = true; else mOverDivider = false; } void GuiInspector::onMouseDown(const GuiEvent &event) { if ( mOverDivider ) { mMovingDivider = true; } } void GuiInspector::onMouseUp(const GuiEvent &event) { mMovingDivider = false; } void GuiInspector::onMouseDragged(const GuiEvent &event) { if ( !mMovingDivider ) return; Point2I localPnt = globalToLocalCoord( event.mousePoint ); S32 inspectorWidth = getWidth(); // Distance from mouse/divider position in local space // to the right edge of the inspector mDividerPos = inspectorWidth - localPnt.x; mDividerPos = mClamp( mDividerPos, 0, inspectorWidth ); // Divide that by the inspectorWidth to get a percentage mDividerPos /= inspectorWidth; updateDivider(); } bool GuiInspector::findExistentGroup( StringTableEntry groupName ) { // If we have no groups, it couldn't possibly exist if( mGroups.empty() ) return false; // Attempt to find it in the group list Vector<GuiInspectorGroup*>::iterator i = mGroups.begin(); for( ; i != mGroups.end(); i++ ) { if( dStricmp( (*i)->getGroupName(), groupName ) == 0 ) return true; } return false; } void GuiInspector::updateFieldValue( StringTableEntry fieldName, StringTableEntry arrayIdx ) { // We don't know which group contains the field of this name, // so ask each group in turn, and break when a group returns true // signifying it contained and updated that field. Vector<GuiInspectorGroup*>::iterator groupIter = mGroups.begin(); for( ; groupIter != mGroups.end(); groupIter++ ) { if ( (*groupIter)->updateFieldValue( fieldName, arrayIdx ) ) break; } } void GuiInspector::clearGroups() { // If we're clearing the groups, we want to clear our target too. mTarget = NULL; // And the HL field mHLField = NULL; // If we have no groups, there's nothing to clear! if( mGroups.empty() ) return; // Attempt to find it in the group list Vector<GuiInspectorGroup*>::iterator i = mGroups.begin(); freeze(true); // Delete Groups for( ; i != mGroups.end(); i++ ) { if((*i) && (*i)->isProperlyAdded()) (*i)->deleteObject(); } mGroups.clear(); freeze(false); updatePanes(); } void GuiInspector::inspectObject( SimObject *object ) { //GuiCanvas *guiCanvas = getRoot(); //if( !guiCanvas ) // return; //SimObjectPtr<GuiControl> currResponder = guiCanvas->getFirstResponder(); // If our target is the same as our current target, just update the groups. if( mTarget == object ) { Vector<GuiInspectorGroup*>::iterator i = mGroups.begin(); for ( ; i != mGroups.end(); i++ ) (*i)->updateAllFields(); // Don't steal first responder //if( !currResponder.isNull() ) // guiCanvas->setFirstResponder( currResponder ); return; } // Give users a chance to customize fields on this object if( object->isMethod("onDefineFieldTypes") ) Con::executef( object, "onDefineFieldTypes" ); // Clear our current groups clearGroups(); // Set Target if ( mTarget ) clearNotify( mTarget ); mTarget = object; deleteNotify( mTarget ); // Special group for fields which should appear at the top of the // list outside of a rollout control. GuiInspectorGroup *ungroup = new GuiInspectorGroup( mTarget, "Ungrouped", this ); ungroup->mHideHeader = true; ungroup->mCanCollapse = false; if( ungroup != NULL ) { ungroup->registerObject(); mGroups.push_back( ungroup ); addObject( ungroup ); } // Put the 'transform' group first GuiInspectorGroup *transform = new GuiInspectorGroup( mTarget, "Transform", this ); if( transform != NULL ) { transform->registerObject(); mGroups.push_back( transform ); addObject( transform ); } // Always create the 'general' group (for un-grouped fields) GuiInspectorGroup *general = new GuiInspectorGroup( mTarget, "General", this ); if( general != NULL ) { general->registerObject(); mGroups.push_back( general ); addObject( general ); } // Grab this objects field list AbstractClassRep::FieldList &fieldList = mTarget->getModifiableFieldList(); AbstractClassRep::FieldList::iterator itr; // Iterate through, identifying the groups and create necessary GuiInspectorGroups for(itr = fieldList.begin(); itr != fieldList.end(); itr++) { if ( itr->type == AbstractClassRep::StartGroupFieldType ) { if ( !findExistentGroup( itr->pGroupname ) && !isGroupFiltered( itr->pGroupname ) ) { GuiInspectorGroup *group = new GuiInspectorGroup( mTarget, itr->pGroupname, this ); if( group != NULL ) { group->registerObject(); mGroups.push_back( group ); addObject( group ); } } } } // Deal with dynamic fields if ( !isGroupFiltered( "Dynamic Fields" ) ) { GuiInspectorGroup *dynGroup = new GuiInspectorDynamicGroup( mTarget, "Dynamic Fields", this); if( dynGroup != NULL ) { dynGroup->registerObject(); mGroups.push_back( dynGroup ); addObject( dynGroup ); } } // Add the SimObjectID field to the ungrouped group GuiInspectorCustomField *field = new GuiInspectorCustomField(); field->init(this, ungroup, object); if( field->registerObject() ) { ungroup->mChildren.push_back( field ); ungroup->mStack->addObject( field ); StringTableEntry caption = StringTable->insert( String("Id"), true ); field->setCaption( caption ); field->setData( StringTable->insert( object->getIdString() ) ); field->setDoc( StringTable->insert("SimObjectId of this object. [Read Only]")); } else delete field; // Add the Source Class field to the ungrouped group field = new GuiInspectorCustomField(); field->init(this, ungroup, object); if( field->registerObject() ) { ungroup->mChildren.push_back( field ); ungroup->mStack->addObject( field ); StringTableEntry caption = StringTable->insert( String("Source Class"), true ); field->setCaption( caption ); if(object->getClassRep()) { field->setData( StringTable->insert( object->getClassRep()->getClassName(), true )); Namespace* ns = object->getClassRep()->getNameSpace(); field->setToolTip( StringTable->insert( Con::getNamespaceList(ns), true )); } else { field->setData( StringTable->insert( String("") )); } field->setDoc( StringTable->insert( "Source code class of this object. [Read Only]") ); } else delete field; // If the general group is still empty at this point ( or filtered ), kill it. if ( isGroupFiltered( "General" ) || general->mStack->size() == 0 ) { for(S32 i=0; i<mGroups.size(); i++) { if ( mGroups[i] == general ) { mGroups.erase(i); general->deleteObject(); updatePanes(); break; } } } // If transform turns out to be empty or filtered, remove it if( isGroupFiltered( "Transform" ) || transform->mStack->size() == 0 ) { for(S32 i=0; i<mGroups.size(); i++) { if ( mGroups[i] == transform ) { mGroups.erase(i); transform->deleteObject(); updatePanes(); break; } } } } void GuiInspector::setName( StringTableEntry newName ) { if( mTarget == NULL ) return; StringTableEntry name = StringTable->insert(newName); // Only assign a new name if we provide one mTarget->assignName(name); } bool GuiInspector::collideDivider( const Point2I &localPnt ) { RectI divisorRect( getWidth() - getWidth() * mDividerPos - mDividerMargin, 0, mDividerMargin * 2, getHeight() ); if ( divisorRect.pointInRect( localPnt ) ) return true; return false; } void GuiInspector::updateDivider() { for ( U32 i = 0; i < mGroups.size(); i++ ) for ( U32 j = 0; j < mGroups[i]->mChildren.size(); j++ ) mGroups[i]->mChildren[j]->updateRects(); //setUpdate(); } void GuiInspector::getDivider( S32 &pos, S32 &margin ) { pos = (F32)getWidth() * mDividerPos; margin = mDividerMargin; } void GuiInspector::setHighlightField( GuiInspectorField *field ) { if ( mHLField == field ) return; if ( mHLField.isValid() ) mHLField->setHLEnabled( false ); mHLField = field; // We could have been passed a null field, meaning, set no field highlighted. if ( mHLField.isNull() ) return; mHLField->setHLEnabled( true ); } bool GuiInspector::isGroupFiltered( const char *groupName ) const { // Internal and Ungrouped always filtered, we never show them. if ( dStricmp( groupName, "Internal" ) == 0 || dStricmp( groupName, "Ungrouped" ) == 0 || dStricmp( groupName, "AdvCoordManipulation" ) == 0) return true; // Normal case, determine if filtered by looking at the mGroupFilters string. String searchStr; // Is this group explicitly show? Does it immediately follow a + char. searchStr = String::ToString( "+%s", groupName ); if ( mGroupFilters.find( searchStr ) != String::NPos ) return false; // Were there any other + characters, if so, we are implicitly hidden. if ( mGroupFilters.find( "+" ) != String::NPos ) return true; // Is this group explicitly hidden? Does it immediately follow a - char. searchStr = String::ToString( "-%s", groupName ); if ( mGroupFilters.find( searchStr ) != String::NPos ) return true; return false; } ConsoleMethod( GuiInspector, inspect, void, 3, 3, "Inspect(Object)") { SimObject * target = Sim::findObject(argv[2]); if(!target) { if(dAtoi(argv[2]) > 0) Con::warnf("%s::inspect(): invalid object: %s", argv[0], argv[2]); object->clearGroups(); return; } object->inspectObject(target); } ConsoleMethod( GuiInspector, refresh, void, 2, 2, "Reinspect the currently selected object." ) { SimObject *target = object->getInspectObject(); if ( target ) object->inspectObject( target ); } ConsoleMethod( GuiInspector, getInspectObject, const char*, 2, 2, "getInspectObject() - Returns currently inspected object" ) { SimObject *pSimObject = object->getInspectObject(); if( pSimObject != NULL ) return pSimObject->getIdString(); return ""; } ConsoleMethod( GuiInspector, setName, void, 3, 3, "setName(NewObjectName)") { object->setName(argv[2]); } ConsoleMethod( GuiInspector, apply, void, 2, 2, "apply() - Force application of inspected object's attributes" ) { SimObject *target = object->getInspectObject(); if ( target ) target->inspectPostApply(); }
a14c385514a338cba42d7a6b14c655c8563fcc86
63a5a4751cd43a65d15ffc7fcf5fe9c1360354cf
/Source/NZGame/HUD/NZHUDWidgetMessage.cpp
2ca40f98e30d00afef833b66cb5ccb37d626b8e9
[]
no_license
terryzhong/NZGame
f13eecfd51cf329a8427ddb3b440d51e115ef77b
6de8d3e071e48e865492aa3ebeeb1f2a7f40b3ba
refs/heads/master
2021-01-19T02:54:57.677135
2017-03-25T17:37:12
2017-03-25T17:37:12
48,650,520
9
4
null
null
null
null
UTF-8
C++
false
false
378
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "NZGame.h" #include "NZHUDWidgetMessage.h" void UNZHUDWidgetMessage::ReceiveLocalMessage(TSubclassOf<class UNZLocalMessage> MessageClass, APlayerState* RelatedPlayerState_1, APlayerState* RelatedPlayerState_2, uint32 MessageIndex, FText LocalMessageText, UObject* OptionalObject) { }
f056d4b87c61b06d2a4804d9da7aaa2e9386b0c5
a6352828dbdfc70485bfe96518d8de6c20d64f65
/Net/include/TcpClient.h
9223970e8bd4bfa32ec39ddd416ef38b57fea69e
[]
no_license
lxj362343/framework-nd
cbbed6ccb29e9a5ae130b17947d5b324604a810d
9fe9d770af2bf0a96308fc92811c908b883ed21d
refs/heads/master
2022-01-07T13:07:21.845762
2019-01-11T03:05:50
2019-01-11T03:05:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,170
h
#ifndef TCPCLIENT_H #define TCPCLIENT_H #include "SocketConnection.h" #include <string> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #include <event.h> namespace Net { class IClientProtocol; namespace Client { class TcpClient { public: TcpClient( IClientProtocol* theProtocol, Reactor::Reactor* theReactor, Processor::BoostProcessor* theProcessor); ~TcpClient(); /** * connect in a async way. * return: * -1 : there is an error. * 0 : connected or blocked */ int connect(); int close(); bool isClose() { boost::lock_guard<boost::mutex> lock(connectionMutexM); if (connectionM.get()) { return connectionM->isClose(); } return true; } bool isConnected() { boost::lock_guard<boost::mutex> lock(connectionMutexM); return connectionM.get() && isConnectedM; } unsigned sendn(char* const theBuffer, const unsigned theLen); /** * onXxx * Description: TcpClient will be notified if it is xxx. * And do not rmClient in these functions */ void onClientTimeout(); void onConnected(int theFd, Connection::SocketConnectionPtr theConnection); void onError(); private: IClientProtocol* protocolM; Reactor::Reactor* reactorM; Processor::BoostProcessor* processorM; std::string peerAddrM; int peerPortM; mutable bool isClosedM; boost::mutex connectionMutexM; bool isConnectedM; Net::Connection::SocketConnectionPtr connectionM; }; inline unsigned TcpClient::sendn(char* const theBuffer, const unsigned theLen) { boost::lock_guard<boost::mutex> lock(connectionMutexM); if (isConnectedM && connectionM.get()) { return connectionM->sendn(theBuffer, theLen); } else { return 0; } } } } #endif /* TCPCLIENT_H */
24927ff50d29907e50ef3b6de1a5658cc811bcc5
0757852d8712bbebb0ee57b587469ea5422cb4a8
/Calculator/Calculator.cpp
e1d0ef3511d9a0ca5664f832dcabfed1b6f0e992
[]
no_license
zhivotnoe22/Calculator-MFC
3a629957c7219bec8bff0c32eecd5bdd44b8e4e3
0f86360ccd7a3ad761da6b64f09dd4662568fc0a
refs/heads/master
2023-03-16T22:38:12.416170
2016-03-08T16:01:54
2016-03-08T16:01:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,865
cpp
// Calculator.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "Calculator.h" #include "CalculatorDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CCalculatorApp BEGIN_MESSAGE_MAP(CCalculatorApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CCalculatorApp construction CCalculatorApp::CCalculatorApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CCalculatorApp object CCalculatorApp theApp; // CCalculatorApp initialization BOOL CCalculatorApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // Create the shell manager, in case the dialog contains // any shell tree view or shell list view controls. CShellManager *pShellManager = new CShellManager; // Activate "Windows Native" visual manager for enabling themes in MFC controls CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CCalculatorDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } else if (nResponse == -1) { TRACE(traceAppMsg, 0, "Warning: dialog creation failed, so application is terminating unexpectedly.\n"); TRACE(traceAppMsg, 0, "Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n"); } // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
ac4841f4150987bb5327461d768500965ac94210
555f0e159a88951f27b7f6303a9db1336ee74522
/source/s23.cpp
fc347d91f3eadc36194315be17a01f9c77afa3c5
[]
no_license
mashanivas/gplus
6942bccbc9cd46556f243018213d5e724d45efee
a22896b7099d3860bd45d47af72ee262af5b4de5
refs/heads/master
2023-02-28T05:02:15.418097
2021-02-10T19:43:00
2021-02-10T19:43:00
337,835,313
0
0
null
null
null
null
UTF-8
C++
false
false
286
cpp
#include <iostream> using namespace std; template <class T> T sum (T a, T b) { T result; result = a + b; return result; } int main () { int i=5, j=6, k; double f=2.0, g=0.5, h; k=sum<int>(i,j); h=sum<double>(f,g); cout << k << '\n'; cout << h << '\n'; return 0; }
552262cd601a8d368d91edf77cf70fe6f7eaa8b7
623a81d04ac1e0755e8fda2b33860ec37867fc01
/URI_1071.cpp
8e541a55262026450abda089c135fb42c65bc9c0
[]
no_license
lalchan123/Contest-Programing-Code
aa4aade42413383916cafaa0653b5ec616fc0293
8e26e9a413723f7f2fb6a9172fa365b8e58ffaa8
refs/heads/main
2023-07-15T11:24:56.929980
2021-09-01T18:33:41
2021-09-01T18:33:41
301,860,777
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
#include <iostream> using namespace std; int main() { int a,b,i,sum=0; cin >> a >> b; for (i=b+1; i<a; i++) { if (i%2 != 0) { sum = sum + i; } } cout << sum << endl; return 0; }
0ddc13980b44d6fc1e5d0cc9dd1dadeb48bec73c
b19b7e9a3e69e28c0961a0567f63bee0dd9b58b9
/Editor/Plugins/GCore/Source/GCore/Private/System/GameDirector.cpp
a7c795df30083c569d22695e6eec51648a615ed2
[]
no_license
1097195326/Editor
ef80d49379675815ba2e3e58d524a7f000e6e7ca
9bbb97bca0fcd648a9a8a68afc00b9d4bd00212b
refs/heads/master
2020-03-17T20:59:25.173542
2018-05-18T10:20:36
2018-05-18T10:20:36
118,855,172
0
0
null
null
null
null
UTF-8
C++
false
false
6,517
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "GCore.h" #include "GTimerMgr.h" #include "GPlatformMgr.h" #include "AARefClasses.h" #include "GController.h" #include "UIManager.h" #include "GResourceManager.h" #include "GSchedulerManager.h" #include "DownloadImageTool.h" #include "GameDirector.h" #include "PrototypeManager.h" #include "Runtime/Engine/Classes/Kismet/KismetSystemLibrary.h" #include "GameDirector.h" UGameDirector * UGameDirector::m_instance = nullptr; UGameDirector::UGameDirector(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } UGameDirector * UGameDirector::GetInstance() { return m_instance; } // 初始化的方法. void UGameDirector::Init() { Super::Init(); m_instance = this; if (!m_isInit) { m_isInit = true; GLoad(); } } void UGameDirector::Shutdown() { m_isInit = false; GRelease(); } void UGameDirector::GLoad() { UGResourceManager::GetInstance()->GLoad(); GTimerMgr::GetInstance()->GLoad(); GPlatformMgr::GetInstance()->GLoad(); GSchedulerManager::GetInstance()->GLoad(); OnLoad(); if (GController::m_platform == ENUM_PLATFORM::GWINDOWS) { m_scenePrototype = PrototypeManager::GetInstance()->GetPrototypeByPID<ScenePrototype>(100); } else if (GController::m_platform == ENUM_PLATFORM::GMAC) { m_scenePrototype = PrototypeManager::GetInstance()->GetPrototypeByPID<ScenePrototype>(101); } else if (GController::m_platform == ENUM_PLATFORM::GANDROID) { m_scenePrototype = PrototypeManager::GetInstance()->GetPrototypeByPID<ScenePrototype>(102); } else if (GController::m_platform == ENUM_PLATFORM::GIOS) { m_scenePrototype = PrototypeManager::GetInstance()->GetPrototypeByPID<ScenePrototype>(103); } // 启动定时器. timer_task_ptr task(new TimerTask(this, &UGameDirector::OnUpdateReceived, 2.0f, true)); m_updateID = GTimerMgr::GetInstance()->RegisterTimer(task); } bool UGameDirector::OnUpdateReceived(float DeltaTime) { GWorld->GetWorld()->ForceGarbageCollection(true); return false; } void UGameDirector::GRelease() { GTimerMgr::GetInstance()->RemoveTimer(m_updateID); GSchedulerManager::GetInstance()->GRelease(); CloseAllLogicScene(); UGResourceManager::GetInstance()->GRelease(); // 先释放所有单利管理里的类. for (int32 i = m_gameInstanceArr.Num() - 1; i >= 0; i--) { ILoad * task = m_gameInstanceArr[i]; // 从数组中删除. m_gameInstanceArr.RemoveAt(i); task->GRelease(); task = nullptr; } m_gameInstanceArr.RemoveAll([](ILoad* Val) { return true; }); // 释放掉所有的反射管理. AARefClasses::GetInstance()->GRelease(); m_gameInstanceArr.Empty(); GTimerMgr::GetInstance()->GRelease(); GPlatformMgr::GetInstance()->GRelease(); OnRelease(); UDownloadImageTool::GetInstance()->GRelease(); } void UGameDirector::OnLoad() { } void UGameDirector::OnRelease() { } void UGameDirector::QuitGame() { #if PLATFORM_IOS exit(0); #else UWorld * mWorld = GetWorld(); APlayerController * mPlayerCtr = mWorld->GetFirstPlayerController(); if (mPlayerCtr) { UKismetSystemLibrary::QuitGame((UObject*)mWorld, mPlayerCtr, EQuitPreference::Quit); } #endif } void UGameDirector::RegisterInstanceClass(ILoad * _class_s) { m_gameInstanceArr.Push(_class_s); } FStreamableManager & UGameDirector::StreamableManager() { return m_streamable; } void UGameDirector::OpenLevel(const FString & _levelName) { UUIManager::GetInstance()->RemoveAllAlertUI(); FString mScenePath = m_scenePrototype->GetLevelName(_levelName); UGameplayStatics::OpenLevel(UGameDirector::GetInstance(), *mScenePath); } BaseLogicScene * UGameDirector::GetCurrentLogicScene() { if (m_sceneMgr.Num() > 0) { int32 i = m_sceneMgr.Num() - 1; return m_sceneMgr[i]; } return nullptr; } void UGameDirector::CloseCurrentLogicScene() { UUIManager::GetInstance()->RemoveAllAlertUI(); if (m_sceneMgr.Num() > 0) { int32 i = m_sceneMgr.Num() - 1; BaseLogicScene * mScene = m_sceneMgr[i]; // 从数组中删除. m_sceneMgr.RemoveAt(i); mScene->GRelease(); } } void UGameDirector::CloseAllLogicScene() { // 先释放所有单利管理里的类. for (int32 i = m_sceneMgr.Num() - 1; i >= 0; i--) { BaseLogicScene * mScene = m_sceneMgr[i]; // 从数组中删除. m_sceneMgr.RemoveAt(i); mScene->GRelease(); } } void UGameDirector::LoadLevelAsync(const FString & _levelName) { if (nullptr != m_scenePrototype) { FString mLanguage = GLanguageTool::GetInstance()->GetLanguage(TEXT("key133")); UUIManager::GetInstance()->OpenMiddleTip(mLanguage, 0.0f); FString mScenePath = m_scenePrototype->GetLevelName(_levelName); LoadPackageAsync(mScenePath, FLoadPackageAsyncDelegate::CreateLambda([=](const FName& PackageName, UPackage* LoadedPackage, EAsyncLoadingResult::Type Result) { UUIManager::GetInstance()->RemoveAllAlertUI(); UGameplayStatics::OpenLevel(UGameDirector::GetInstance(), *mScenePath); }), 0, EPackageFlags::PKG_ContainsMap); } } void UGameDirector::OpenLogicScene(const FString & _sceneName, AGBaseGameMode * _gameMode, const FString & _levelName) { // 关闭所有其他的场景. BaseLogicScene * mLogicScene = GetCurrentLogicScene(); if (nullptr != mLogicScene && mLogicScene->m_currentLogicName.Equals(_sceneName)) { mLogicScene->SetGameMode(_gameMode, _levelName); } else { CloseAllLogicScene(); mLogicScene = (BaseLogicScene*)AARefClasses::GetInstance()->CreateClassByName(TCHAR_TO_UTF8(*_sceneName)); mLogicScene->m_currentLogicName = _sceneName; m_sceneMgr.Add(mLogicScene); mLogicScene->GLoad(); if (nullptr != _gameMode) mLogicScene->SetGameMode(_gameMode, _levelName); } } void UGameDirector::ChangeLevel(AGBaseGameMode * _gameMode, const FString & _levelName /*= TEXT("")*/) { // 获取当前UI. BaseLogicScene * mScene = GetCurrentLogicScene(); if (nullptr != mScene) { mScene->SetGameMode(_gameMode, _levelName); } } void UGameDirector::OnEndPlayGameModeEvent(const FString & _levelName /*= TEXT("")*/) { // 获取当前场景. BaseLogicScene * mScene = GetCurrentLogicScene(); if (nullptr != mScene) { mScene->BackstageLevel(_levelName); } } void UGameDirector::ShowMouseCursor() { GetWorld()->GetFirstPlayerController()->bShowMouseCursor = true; }
0605af32bd20e2df7315abcb3563e10bc31fcec4
bb59806476b9657eddda932a3a0e21388c43fba9
/atcoder/codefes_2015_yosen_a/d.cpp
dfeab74f22be30b5c4e9589b4a187891decae6b0
[]
no_license
atri-konami/kyo-pro
b0d53b196e0526774816df2aeb6f4c0a7fbc4745
bf72a14da29828a29a5e59d2582f1e27ee65d545
refs/heads/master
2020-07-16T19:08:16.163064
2019-09-02T12:09:38
2019-09-02T12:09:38
205,849,043
0
0
null
null
null
null
UTF-8
C++
false
false
1,023
cpp
#include <bits/stdc++.h> using namespace std; int n,m; vector<int> x,d; bool ok(int t){ long long lb,ub,l; d[0]=0; for(int i=1;i<=m;i++){ l=x[i-1]-d[i-1]-1; if(l>t) return false; if (i==m){ return min(l*2+(n-x[i-1]),l+2*(n-x[i-1])) <= t; }else{ lb=0,ub=2*n; while(lb+1<ub){ long long mid=(lb+ub)/2; if(min(l*2+mid,l+2*mid)<=t && x[i-1]+mid < x[i]){ lb=mid; }else{ ub=mid; } } if((d[i] = x[i-1]+lb)>=n) return true; } } } int main(){ cin>>n>>m; d.resize(m+5); for(int i=0;i<m;i++){ int t; cin>>t; x.push_back(t); } long long lb=-1,ub=2*n; while(lb+1<ub){ long long mid = (lb+ub)/2; if(ok(mid)){ ub=mid; }else{ lb=mid; } } cout << ub << endl; }
d6b07565651e31a181c788dcb04101d9c0cebb30
8992a0d6d36574525b0df1b6b322063135f46ad9
/include/fileloader.h
e5b3eda31b3c09481109ecd5ec3b35a6715983f6
[]
no_license
yyjxx2010xyu/KTruss
f137dce4b43b29e195238f2dedd53e3906e222c3
10bcac564acfe8c3867d737e66d0e563217cbc25
refs/heads/main
2023-02-16T17:13:20.095539
2021-01-10T08:20:06
2021-01-10T08:20:06
328,335,226
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
h
#ifndef FILELOADER #define FILELOADER #include <cstdio> #include <cstdlib> #include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> class fileLoader { private: void *addr; int fd; int len; public: fileLoader() { fd = -1; len = 0; addr = NULL; } ~fileLoader() { } void release() { if (fd != -1) { close(fd); munmap(addr, len); } } void loadFile(const char *path) { struct stat statbuf; fd = open(path, O_RDONLY); if (fd < 0) { puts("can not open file"); exit(-1); } int ret = fstat(fd, &statbuf); if (ret < 0) { puts("can not fstat"); exit(-1); } len = statbuf.st_size; addr = mmap(0, len, PROT_READ, MAP_SHARED, fd, 0); if (addr == (void *)-1) { puts("can not mmap"); exit(-1); } } int getLen() { return len; } void *getAddr() { return addr; } }; #endif
970814b68fdd5928b64b07c43a8cd07c113319b4
effce69116f96b9e9fc490920869224c536e1d6f
/Config.cpp
d589b215f6fcb11310bbc8c7347c2f4ace35e244
[]
no_license
Just1045523143/sqlite-server
82654f1594db7031f4df13163ec1281da87e6b6f
a9b254d3aead8495196cc8156602ca6d266b3cf0
refs/heads/master
2021-10-09T03:04:03.102379
2018-12-20T09:51:03
2018-12-20T09:51:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,761
cpp
// // Created by Miroslav Kudrnac on 06/03/2018. // #include <nlohmann/json.hpp> #include <fmt/printf.h> #include "Config.h" using json = nlohmann::json; boost::asio::ip::tcp::endpoint resolve_endpoint(const std::string& listen_ip, const uint16_t listen_port) { boost::asio::io_service io_service; boost::asio::ip::tcp::resolver resolver(io_service); const auto endpoint_iterator = resolver.resolve(boost::asio::ip::tcp::resolver::query(listen_ip, std::to_string(listen_port))); for(const auto& it : endpoint_iterator) { if(it.endpoint().address().is_v4()) { return it.endpoint(); } } return boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 3333); } boost::filesystem::path resolve_database_path(const std::string& path) { const auto databases_folder = boost::filesystem::path(boost::filesystem::system_complete(path)); if(!boost::filesystem::exists(databases_folder)) { throw ConfigException(fmt::format("Databases folder does not exist in: {}", databases_folder)); } return databases_folder; } auto get_config_value(const json& j, const std::string& key) { if(j.find(key) == j.end()) { throw ConfigException(fmt::format("Missing key: {} in config", key)); } return j[key]; } void Config::init(const boost::program_options::variables_map& vm) { //load from config if specified or use cmd line arguments const auto config = vm.find("config"); if(config != vm.end()) { const auto config_path = config->second.as<std::string>(); if(!boost::filesystem::exists(config_path)) { throw ConfigException(fmt::format("Config file does not exist in: {}", config_path)); } json j; try { j = json::parse(std::ifstream(config_path)); }catch(const nlohmann::detail::parse_error& e) { throw ConfigException(fmt::format("Config parse error: {}", e.what())); } client_max_packet_size = get_config_value(j, "client_max_packet_size"); workers = get_config_value(j, "workers"); listen_endpoint = resolve_endpoint(get_config_value(j, "listen_ip"), get_config_value(j, "listen_port")); databases_folder = resolve_database_path(get_config_value(j, "databases_folder")); } else { client_max_packet_size = vm["client-max-packet-size"].as<uint32_t>(); workers = vm["workers"].as<uint16_t>(); listen_endpoint = resolve_endpoint(vm["ip"].as<std::string>(), vm["port"].as<uint16_t>()); databases_folder = resolve_database_path(vm["databases-folder"].as<std::string>()); } }
f0836ccf16f7cbe0b49500489ae509e58f0045c0
edb8583175255ff8b54812cb9d1a26151abd11b0
/Yanity/SphereColider.h
46dbf84d3251a24bf7ba82bb9644a3274443b745
[]
no_license
egod1537/Yanity_SDL
f5145354f602238107170ca42681793795f7d7c7
81186d4ca25c896265a31f59a0d2ac0c44d2f3c6
refs/heads/master
2022-03-31T04:34:57.499088
2019-11-27T15:53:48
2019-11-27T15:53:48
null
0
0
null
null
null
null
UHC
C++
false
false
364
h
#pragma once #include "Colider.h" ///@brief Sphere 형태의 Colider 컴포넌트 입니다. class SphereColider : public Colider { public: float Radius; ///< SphereColider의 반지름 SphereColider() { } void Awake(); void Update(); bool isCollision(Vector2); bool isCollision(BoxColider*); bool isCollision(SphereColider*); void Collision(); };
ebe8a044965fc48d815294940ed84fe57e5aef40
28c000caf6617ba2074e0f2a8fc936ccb8c01fb3
/LeetCode/Flatten Binary Tree to Linked List.cpp
242937b21b366b8f2039fea17786429bea1d925f
[]
no_license
ATM006/acm_problem_code
f597fa31033fd663b14d74ad94cae3f7c1629b99
ac40d230cd450bcce60df801eb3b8ce9409dfaac
refs/heads/master
2020-08-31T21:34:00.707529
2014-01-23T05:30:42
2014-01-23T05:30:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,614
cpp
class Solution { public: void flatten(TreeNode *root) { stack<TreeNode *> st; stack<int> state; if(root) { st.push(root); state.push(0); } vector<TreeNode *> node; while(!st.empty()) { TreeNode *child = st.top(); int child_state = state.top(); if(child_state == 0) { node.push_back(child); state.pop(); state.push(1); if(child->left != NULL) { st.push(child->left); state.push(0); } } else if(child_state == 1) { state.pop(); state.push(2); if(child->right != NULL) { st.push(child->right); state.push(0); } } else { state.pop(); st.pop(); } } int n = node.size(); for(int i = 0; i < n; i++)node[i]->left = node[i]->right = NULL; --n; for(int i = 0; i < n; i++) { node[i]->right = node[i + 1]; } root = (n == -1 ? NULL : node[0]); } };
[ "wangjunyong@wangjunyong-PC.(none)" ]
wangjunyong@wangjunyong-PC.(none)
51e97480f932b71df1909feebc276f4340ceb278
14355f60733dce9b2f73daca94afe507981fb99d
/exec/modules/verify_revoke.h
def30a9244682d94bcd8083c09aeb982239b8bbf
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
r4yan2/OpenPGP
86906fd33440b1c567b4fc0f13ad4f11a925d632
0299d96ee3b60d1d29b2d59f43610603a1135a5e
refs/heads/master
2021-12-31T09:19:32.855072
2018-02-13T12:36:55
2018-02-13T12:36:55
150,585,547
0
0
MIT
2018-09-27T12:45:55
2018-09-27T12:45:55
null
UTF-8
C++
false
false
2,807
h
/* verify_revoke.h OpenPGP exectuable module Copyright (c) 2013 - 2017 Jason Lee @ calccrypto at gmail.com 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. */ #ifndef __COMMAND_VERIFY_REVOKE__ #define __COMMAND_VERIFY_REVOKE__ #include "../../OpenPGP.h" #include "module.h" namespace module { const Module verify_revoke( // name "verify-revoke", // positional arguments { "key", "revocation-certificate", }, // optional arguments { }, // optional flags { }, // function to run [](const std::map <std::string, std::string> & args, const std::map <std::string, bool> & flags, std::ostream & out, std::ostream & err) -> int { std::ifstream key(args.at("key"), std::ios::binary); if (!key){ err << "Error: Public key file \"" + args.at("key") + "\" not opened." << std::endl; return -1; } std::ifstream cert(args.at("revocation-certificate"), std::ios::binary); if (!cert){ err << "Error: Revocation certificate file \"" + args.at("revocation-certificate") + "\" not opened." << std::endl; return -1; } const OpenPGP::Key signer(key); const OpenPGP::RevocationCertificate rev(cert); const int verified = OpenPGP::Verify::revoke(signer, rev); if (verified == -1){ err << "Error: Bad PKA value" << std::endl; return -1; } out << "The certificate in \"" << args.at("revocation-certificate") << "\" " << ((verified == 1)?std::string("revokes"):std::string("does not revoke")) << " key in \"" << args.at("key") << "\" (" << signer << ")." << std::endl; return !verified; } ); } #endif
04e7cf987c9faf9e8ab0f8025e938ca2b91ab3fd
36184239a2d964ed5f587ad8e83f66355edb17aa
/.history/hw3/main_20211016170701.cpp
3a2831d36c34159637a9c86b8c307722c754b0a5
[]
no_license
xich4932/csci3010
89c342dc445f5ec15ac7885cd7b7c26a225dae3e
23f0124a99c4e8e44a28ff31ededc42d9f326ccc
refs/heads/master
2023-08-24T04:03:12.748713
2021-10-22T08:22:58
2021-10-22T08:22:58
415,140,207
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
#include<iostream> #include<vector> #include<map> #include"ElectoralMap.h" using namespace std; int main(){ srand((unsigned int)TIME(NULL)); ElectoralMap firstmap = ElectoralMap::getInstance(); std::cout << firstmap << std::endl; return 0; }
ad99dbdaaa3a9dafe71e6058082e45184cbcd467
439176618be20e13ee147046d4d395cdfb52bc33
/IUnknownInterface.h
827b17bfb5c6433f98c4c12ac498d4590aadf21c
[]
no_license
Daendaralus/AIMP-Discord-Presence
0ed0215ca341e6d508a74f5e84219a1daa797b98
a9df416d6ce638d6174cd390200ef6ac9623e2e5
refs/heads/master
2022-04-26T03:45:54.850677
2020-04-29T20:09:55
2020-04-29T20:09:55
259,918,958
3
2
null
2020-04-29T12:27:33
2020-04-29T12:27:33
null
UTF-8
C++
false
false
939
h
#pragma once template <typename T> class IUnknownInterface : public T { public: IUnknownInterface() : m_cRef(0) {} virtual ~IUnknownInterface() {} virtual HRESULT WINAPI QueryInterface(REFIID riid, LPVOID* ppvObj) { // Always set out parameter to NULL, validating it first. if (!ppvObj) return E_INVALIDARG; *ppvObj = NULL; if (riid == IID_IUnknown) { // Increment the reference count and return the pointer. *ppvObj = (LPVOID)this; AddRef(); return S_OK; } return E_NOINTERFACE; } virtual ULONG WINAPI AddRef() { return ++m_cRef; } virtual ULONG WINAPI Release() { // Decrement the object's internal counter. if (0 == --m_cRef) { delete this; } return m_cRef; } private: ULONG m_cRef; };
3537d551c90dd12e4d519d7800828f52d4d92e43
47c3c9b9f6d05e514da1d9fb2901bbc9b28a6f40
/GameQuiz.cpp
c1f12220fcc938f4092f7d4a5c7c45f9507c585c
[]
no_license
Grubanosh/QuizGameC
8dbcf1dc7b15fd2b33d8163757539cb10b22c54b
a11badbe756aa1ed7f686d7589aeff1d504a3298
refs/heads/master
2020-09-10T01:38:15.556562
2019-11-14T05:16:01
2019-11-14T05:16:01
221,617,248
0
0
null
null
null
null
ISO-8859-1
C++
false
false
44,397
cpp
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> char player1[15], player2[15], escolha1, escolha2; int pontuacao1, pontuacao2, opc; main(){ srand(time(NULL)); printf("Player 1: "); scanf("%s", player1); printf("Player 2: "); scanf("%s", player2); do{ opc=(rand()%100)/2; switch(opc){ case 0: system("cls"); printf("=================================================================================================\n"); printf("Atualmente, quantos elementos quimicos a tabela periodica possui?\n\n a) 113\n b) 109\n c) 108\n d) 118\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) 108"); sleep(6); break; case 1: system("cls"); printf("=================================================================================================\n"); printf("\n Normalmente, quantos litros de sangue uma pessoa tem?\n\n a) Entre 2 e 4 litros\n b) Entre 4 e 6 litros\n c) 10 litros\n d) 7 litros\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Entre 4 e 6 litros"); sleep(6); break; case 2: system("cls"); printf("=================================================================================================\n"); printf("Qual pais tem a menor expectativa de vida do mundo?\n\n a) Serra Leoa\n b) Afeganistão\n c) Chade\n d) Congo\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) Serra Leoa"); sleep(6); break; case 3: system("cls"); printf("=================================================================================================\n"); printf("Quanto tempo a luz do Sol demora para chegar a Terra?\n\n a) 1 dia\n b) 8 horas\n c) 8 minutos\n d) 8 segundos\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) 8 minutos"); sleep(6); break; case 4: system("cls"); printf("=================================================================================================\n"); printf("Qual a altura da rede no volei masculino?\n\n a) 2,24m\n b) 2,52m\n c) 2,12m\n d) 2,43m\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) 2,43m"); sleep(6); break; case 5: system("cls"); printf("=================================================================================================\n"); printf("Em que periodo da pre-historia o fogo foi descoberto?\n\n a) Neolitico\n b) Paleolitico\n c) Idade dos Metais\n d) Idade Media\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Paleolitico"); sleep(6); break; case 6: system("cls"); printf("=================================================================================================\n"); printf("Qual a montanha mais alta do Brasil?\n\n a) Pico da Neblina\n b) Pico Parana\n c) Pico da Bandeira\n d) Monte Roraima\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) Pico da Neblina"); sleep(6); break; case 7: system("cls"); printf("=================================================================================================\n"); printf("Qual a velocidade da luz?\n\n a) 300 000 000 metros por segundo (m/s)\n b) 150 000 000 metros por segundo (m/s)\n c) 199 792 458 metros por segundo (m/s)\n d) 299 792 458 metros por segundo (m/s)\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) 299 792 458 metros por segundo (m/s)"); sleep(6); break; case 8: system("cls"); printf("=================================================================================================\n"); printf("Quem e o autor de \"O Principe\"?\n\n a) Montesquieu\n b) Rousseau\n c) Maquiavel\n d) Thomas Hobbes\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) Maquiavel"); sleep(6); break; case 9: system("cls"); printf("=================================================================================================\n"); printf("Que lider mundial ficou conhecida como \"Dama de Ferro\"\n\n a) Angela Merkel\n b) Margaret Thatcher\n c) Christine Lagarde\n d) Hillary Clinton\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Margaret Thatcher"); sleep(6); break; case 10: system("cls"); printf("=================================================================================================\n"); printf("Em que ano derrubaram as Torres Gemeas?\n\n a) 2001\n b) 2003\n c) 1998\n d) 2000\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) 2001"); sleep(6); break; case 11: system("cls"); printf("=================================================================================================\n"); printf("Quantos dentes uma pessoa adulta possui, se nao perdeu nenhum?\n\n a) 30\n b) 28\n c) 36\n d) 32\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) 32"); sleep(6); break; case 12: system("cls"); printf("=================================================================================================\n"); printf("Quantas cores ha no arco-iris?\n\n a) 6\n b) 7\n c) 8\n d) 9\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) 7"); sleep(6); break; case 13: system("cls"); printf("=================================================================================================\n"); printf("Qual e o maior osso do corpo humano? \n\n a) Tibia\n b) Femur\n c) Fibula\n d) Umero\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Femur"); sleep(6); break; case 14: system("cls"); printf("=================================================================================================\n"); printf("Quantos ossos tem o corpo humano?\n\n a) 197\n b) 201\n c) 204\n d) 209\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) 204"); sleep(6); break; case 15: system("cls"); printf("=================================================================================================\n"); printf("Quantos estados existem no Brasil?\n\n a) 26\n b) 22\n c) 32\n d) 30\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) 26"); sleep(6); break; case 16: system("cls"); printf("=================================================================================================\n"); printf("Quantos paises fazem parte de America Latina?\n\n a) 12\n b) 19\n c) 21\n d) 30\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) 21"); sleep(6); break; case 17: system("cls"); printf("=================================================================================================\n"); printf("Qual e o maior oceano do planeta terra?\n\n a) Oceano Antartico\n b) Oceano Atlantico\n c) Oceano Indico\n d) Oceano Pacifico\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) Oceano Pacifico"); sleep(6); break; case 18: system("cls"); printf("=================================================================================================\n"); printf("Quantos planetas Terra cabem dentro no Sol?\n\n a) Um milhao\n b) Cem\n c) Seiscentos\n d) Dois milhoes\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) Um milhao"); sleep(6); break; case 19: system("cls"); printf("=================================================================================================\n"); printf("O que mede a Escala Mercalli?\n\n a) A intensidade dos ventos\n b) A intensidade sismica de acordo com os danos provocados\n c) A magnitude de um terremoto\n d) A resistencia dos minerais\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) A intensidade sismica de acordo com os danos provocados"); sleep(6); break; case 20: system("cls"); printf("=================================================================================================\n"); printf("Quanto mede uma girafa?\n\n a) Entre 4,8 e 5,5 metros\n b) Entre 5 e 6 metros\n c) Entre 2,5 e 3,3 metros\n d) entre 3,5 e 4,2 metros\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) Entre 4,8 e 5,5 metros"); sleep(6); break; case 21: system("cls"); printf("=================================================================================================\n"); printf("Quantos bracos tem um polvo?\n\n a) 10\n b) 12\n c) 8\n d) 6\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) 8"); sleep(6); break; case 22: system("cls"); printf("=================================================================================================\n"); printf("De que sao constituidos os diamantes?\n\n a) Grafite\n b) Osmio\n c) Carbono\n d) Bohrio\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) Carbono"); sleep(6); break; case 23: system("cls"); printf("=================================================================================================\n"); printf("O que e um Papiloscopista?\n\n a) Especialista em copias\n b) Individuo que se dedica ao estudo de papiros\n c) Individuo responsavel por criancas orfas\n d) Profissional especializado em identificacao humana\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) Profissional especializado em identificacao humana"); sleep(6); break; case 24: system("cls"); printf("=================================================================================================\n"); printf("O que e Ortorexia?\n\n a) Obsessao pelo consumo de alimentos saudaveis\n b) Disturbio alimentar que provoca a ingestao excessiva de alimentos\n c) Transtorno alimentar caracterizado pela perda de apetite\n d) Obsessao em falar de forma correta\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) Obsessao pelo consumo de alimentos saudaveis"); sleep(6); break; case 25: system("cls"); printf("=================================================================================================\n"); printf("O etanol e produzido atraves de qual fonte de energia?\n\n a) Biomassa\n b) Eolica\n c) Geotermica\n d) Hidreletrica\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) Biomassa"); sleep(6); break; case 26: system("cls"); printf("=================================================================================================\n"); printf("Qual a velocidade maxima que um velociraptor poderia desenvolver?\n\n a) 20 km/h\n b) 50 km/h\n c) 100 km/h\n d) 200 km/h\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) 100 km/h"); sleep(6); break; case 27: system("cls"); printf("=================================================================================================\n"); printf("Que anfibio tem uma grande glandula de veneno atras de cada olho?\n\n a) Sapo\n b) Salamandra\n c) Rã\n d) Cobra\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) Sapo"); sleep(6); break; case 28: system("cls"); printf("=================================================================================================\n"); printf("Qual a formula quimica do monoxido de carbono?\n\n a) CO\n b) CO2\n c) NaCl\n d) CH3\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) CO"); sleep(6); break; case 29: system("cls"); printf("=================================================================================================\n"); printf("Quem e considerado o pai da quimica moderna?\n\n a) Isaac Newton\n b) Antoine Lavoisier\n c) Albert Einstein\n d) John Dalton\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Antoine Lavoisier"); sleep(6); break; case 30: system("cls"); printf("=================================================================================================\n"); printf("Tenochtitlan era a capital de que imperio?\n\n a) Mongol\n b) Otomano\n c) Romano\n d) Asteca\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) Asteca"); sleep(6); break; case 31: system("cls"); printf("=================================================================================================\n"); printf("Qual destas flores e toxica?\n\n a) margarida\n b) lirio\n c) copo-de-leite\n d) begonia\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) copo-de-leite"); sleep(6); break; case 32: system("cls"); printf("=================================================================================================\n"); printf("Onde ficam nossas cordas vocais?\n\n a) Na faringe\n b) Na laringe\n c) Na traqueia\n d) Nos bronquios\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Na laringe"); sleep(6); break; case 33: system("cls"); printf("=================================================================================================\n"); printf("Quantas casas tem um tabuleiro de xadrez\n\n a) 36\n b) 81\n c) 49\n d) 64\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) 64"); sleep(6); break; case 34: system("cls"); printf("=================================================================================================\n"); printf("O cerebro de um homem adulto pesa cerca de: \n\n a) 1,5 kg\n b) 3 kg\n c) 4,5 kg\n d) 6 kg\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) 1,5 kg"); sleep(6); break; case 35: system("cls"); printf("=================================================================================================\n"); printf("Que orgao produz a insulina?\n\n a) Baco\n b) Figado\n c) Rim\n d) Pancreas\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) Pancreas"); sleep(6); break; case 36: system("cls"); printf("=================================================================================================\n"); printf("Quantas faces tem um icosaedro?\n\n a) 14\n b) 16\n c) 18\n d) 20\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) 20"); sleep(6); break; case 37: system("cls"); printf("=================================================================================================\n"); printf("Qual destes primatas tem cauda?\n\n a) Chimpanze\n b) Orangotango\n c) Babuino\n d) Gorila\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) Babuino"); sleep(6); break; case 38: system("cls"); printf("=================================================================================================\n"); printf("Qual e o planeta mais proximo do sol?\n\n a) Venus\n b) Netuno\n c) Urano\n d) Mercurio\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) Mercurio"); sleep(6); break; case 39: system("cls"); printf("=================================================================================================\n"); printf("Qual desses angulos nao esta incluido entre os chamados \"angulos notaveis\" da trigonometria: \n\n a) 30\n b) 45\n c) 60\n d) 75\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) 75"); sleep(6); break; case 40: system("cls"); printf("=================================================================================================\n"); printf("Quantas vezes um kilobyte por segundo e maior que um kilobit por segundo?\n\n a) 8\n b) 100\n c) 254\n d) 1024\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) 8"); sleep(6); break; case 41: system("cls"); printf("=================================================================================================\n"); printf("Offset e um tipo de: \n\n a) Escritorio eletronico\n b) Veiculo para todo terreno\n c) Impressao\n d) Tecnologia de celular\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) Impressao"); sleep(6); break; case 42: system("cls"); printf("=================================================================================================\n"); printf("Fotofobia designa horror a que? \n\n a) A luz\n b) A ser fotografado\n c) Ver fotos antigas\n d) Perder a visao\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) A luz"); sleep(6); break; case 43: system("cls"); printf("=================================================================================================\n"); printf("Qual e a unidade de medida de resistencia eletrica segundo o Sistema Internacional?\n\n a) Volt\n b) Ohm\n c) Watt\n d) Hertz\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Ohm"); sleep(6); break; case 44: system("cls"); printf("=================================================================================================\n"); printf("Amarelo, pele de sapo e galia sao tipos de: \n\n a) Mamao\n b) Abacate\n c) Melao\n d) Morango\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) Melao"); sleep(6); break; case 45: system("cls"); printf("=================================================================================================\n"); printf("Quem foi o grego que, em 200 a.C., explicou o principo da alavanca? \n\n a) Democrito\n b) Pitagoras\n c) Arquimedes\n d) Aristoteles\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'c'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'c'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: c) Arquimedes"); sleep(6); break; case 46: system("cls"); printf("=================================================================================================\n"); printf("Quem e considerado o \"Pai da medicina\"?\n\n a) Socrates\n b) Platao\n c) Herodoto\n d) Hipocrates\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) Hipocrates"); sleep(6); break; case 47: system("cls"); printf("=================================================================================================\n"); printf("Qual desses elementos tem o maior numero atomico?\n\n a) Prata\n b) Oxigenio\n c) Carbono\n d) Hidrogenio\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'a'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'a'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: a) Prata"); sleep(6); break; case 48: system("cls"); printf("=================================================================================================\n"); printf("Carl Sagan esta associado a: \n\n a) Astrologia\n b) Arqueologia\n c) Geologia\n d) Astronomia\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'd'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'd'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: d) Astronomia"); sleep(6); break; case 49: system("cls"); printf("=================================================================================================\n"); printf("Qual destes nao e uma das sete maravilhas do mundo?\n\n a) Coliseu\n b) Farol de Alexandria\n c) Muralha da China\n d) Cristo Redentor\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Farol de Alexandria"); sleep(6); break; case 50: system("cls"); printf("=================================================================================================\n"); printf("Carpelo, estame e pedunculo sao partes que constituem a:\n\n a) Folha\n b) Flor\n c) Fruto\n d) Semente\n\n"); printf("=================================================================================================\n"); do{ printf(" %s: ", player1); scanf(" %c", &escolha1); }while(escolha1>'d' || escolha1<'a'); if(escolha1 == 'b'){ pontuacao1=pontuacao1+100; } do{ printf(" %s: ", player2); scanf(" %c", &escolha2); }while(escolha2>'d' || escolha2<'a'); if(escolha2 == 'b'){ pontuacao2=pontuacao2+100; } printf("\nResposta correta: b) Flor"); sleep(6); break; } }while(pontuacao1<500 && pontuacao2<500); system("cls"); printf("\n%s: %d \n%s: %d\n\n\n", player1, pontuacao1, player2, pontuacao2); if(pontuacao1>pontuacao2){ printf("%s ganhou!\n\n\n", player1); } else if(pontuacao1==pontuacao2){ printf("Empate!\n\n\n"); } else{ printf("%s ganhou!\n\n\n", player2); } system("pause"); }
9267ab4601d8aa6ccde0b7cc0ceb95b9a5f6f6ee
e8da41785e3264a9506ece8b65b25e5c6e7ac574
/oneflow/user/kernels/arg_where_kernel.cpp
0598b44072d9b3afec50325d507a9a22a59a4bd9
[ "Apache-2.0" ]
permissive
runner42195/oneflow
91007547251ff02a2d725847457a2c9f128e8da3
2778e023dff3771d9da8b91abb40462333cc2fa4
refs/heads/master
2023-08-29T19:38:27.863610
2021-11-05T02:30:49
2021-11-05T02:30:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,796
cpp
/* Copyright 2020 The OneFlow 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 "oneflow/core/framework/framework.h" #include "oneflow/core/common/data_type_seq.h" #include "oneflow/core/common/switch_func.h" #include "oneflow/user/kernels/arg_where_kernel_util.h" namespace oneflow { namespace { template<DeviceType device_type, typename IN_T, typename OUT_T> class ArgWhereKernel final : public user_op::OpKernel { public: ArgWhereKernel() = default; ~ArgWhereKernel() = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { int64_t ndims = ctx->Tensor4ArgNameAndIndex("input", 0)->shape().NumAxes(); if (ndims == 0) { return; } SwitchNdimCompute(SwitchCase(ndims), ctx); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } #define COMPUTE_SWITCH_ENTRY(func_name, ndim) func_name<ndim> DEFINE_STATIC_SWITCH_FUNC(void, NdimCompute, COMPUTE_SWITCH_ENTRY, MAKE_NDIM_CTRV_SEQ(DIM_SEQ)); #undef COMPUTE_SWITCH_ENTRY template<int NDIM> static void NdimCompute(user_op::KernelComputeContext* ctx) { const user_op::Tensor* input = ctx->Tensor4ArgNameAndIndex("input", 0); user_op::Tensor* output = ctx->Tensor4ArgNameAndIndex("output", 0); user_op::Tensor* output_size = ctx->Tensor4ArgNameAndIndex("output_size", 0); user_op::Tensor* tmp = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); void* tmp_ptr = tmp ? tmp->mut_dptr() : nullptr; size_t tmp_size = tmp ? tmp->shape().elem_cnt() * GetSizeOfDataType(tmp->data_type()) : 0; ArgWhereKernelUtil<device_type, IN_T, OUT_T, NDIM>::ArgWhere( ctx->device_ctx(), input->shape(), input->dptr<IN_T>(), tmp_ptr, tmp_size, output->mut_dptr<OUT_T>(), output_size->mut_dptr<OUT_T>()); } }; template<DeviceType device_type, typename IN_T, typename OUT_T, int NDIM> size_t GetWorkspaceBytesSize(int64_t elem_cnt) { return ArgWhereKernelUtil<device_type, IN_T, OUT_T, NDIM>::GetWorkspaceBytesSize(nullptr, elem_cnt); } struct SwitchUtil { #define SWITCH_ENTRY(func_name, device, itype, otype, ndim) func_name<device, itype, otype, ndim> DEFINE_STATIC_SWITCH_FUNC( size_t, GetWorkspaceBytesSize, SWITCH_ENTRY, MAKE_DEVICE_TYPE_CTRV_SEQ(DEVICE_TYPE_SEQ), MAKE_DATA_TYPE_CTRV_SEQ(ARITHMETIC_DATA_TYPE_SEQ UNSIGNED_INT_DATA_TYPE_SEQ), MAKE_DATA_TYPE_CTRV_SEQ(INDEX_DATA_TYPE_SEQ), MAKE_NDIM_CTRV_SEQ(DIM_SEQ)); #undef SWITCH_ENTRY }; size_t InferTempStorageBytesSize(user_op::InferContext* ctx) { const std::string& device_tag = ctx->device_tag(); DeviceType device_type = CHECK_JUST(DeviceType4DeviceTag(device_tag)); const Shape& input_shape = ctx->InputShape("input", 0); if (input_shape.NumAxes() == 0) { return 0; } const DataType& input_dtype = ctx->InputDType("input", 0); DataType output_dtype = *ctx->OutputDType("output", 0); return SwitchUtil::SwitchGetWorkspaceBytesSize( SwitchCase(device_type, input_dtype, output_dtype, input_shape.NumAxes()), input_shape.elem_cnt()); } } // namespace #define REGISTER_ARG_WHERE_KERNEL(device, itype, otype) \ REGISTER_USER_KERNEL("argwhere") \ .SetCreateFn<ArgWhereKernel<device, itype, otype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == device) \ & (user_op::HobDataType("input", 0) == GetDataType<itype>::value) \ & (user_op::HobDataType("output", 0) == GetDataType<otype>::value) \ & (user_op::HobDataType("output_size", 0) == GetDataType<otype>::value)) \ .SetInferTmpSizeFn(InferTempStorageBytesSize); #define REGISTER_ARG_WHERE_KERNEL_WITH_DTYPE_PAIR(device, itype_pair, otype_pair) \ REGISTER_ARG_WHERE_KERNEL(device, OF_PP_PAIR_FIRST(itype_pair), OF_PP_PAIR_FIRST(otype_pair)) OF_PP_SEQ_PRODUCT_FOR_EACH_TUPLE(REGISTER_ARG_WHERE_KERNEL_WITH_DTYPE_PAIR, DEVICE_TYPE_SEQ, ARITHMETIC_DATA_TYPE_SEQ UNSIGNED_INT_DATA_TYPE_SEQ, INDEX_DATA_TYPE_SEQ) } // namespace oneflow
62d621eef2d04b105c84f2408cf6df58ebde79b0
ac4b68220b471230602a936538dfe9fbd84dc44e
/Doctor.cpp
3d49698ba942a9b6199a28bc2cf9b8123ffac914
[ "MIT" ]
permissive
DonnC/Hospital-Management-System
493e320eb12a16604e52a180df3b4bf555564b02
5eb1d3d0e95b6bcd4aac179b6109f7ae5cc5af75
refs/heads/master
2022-12-14T22:51:31.043134
2020-09-04T07:26:24
2020-09-04T07:26:24
292,638,606
1
0
null
null
null
null
UTF-8
C++
false
false
3,790
cpp
#include <iostream> #include <iomanip> #include <Windows.h> #include "Doctor.h" using namespace std; void Doctor::regPersonnel() { string nam, gendr, file_pw; int i_d, eg; getchar(); cout << "Doctor Registration. Provide registration details." << endl; cout << "Name: " << endl; getline(cin, nam); cout << "Gender: " << endl; getline(cin, gendr); cout << "File access password: " << endl; getline(cin, file_pw); cout << "Age: " << endl; cin >> eg; cout << "Unique ID: " << endl; cin >> i_d; setName(nam); setId(i_d); setAge(eg); setSex(gendr); setFilePwd(file_pw); cout << "\n"; cout << "Registering Doctor."; for(int animate= 0; animate < 5; animate++) { cout << "."; Sleep(500); } cout << " " << endl; clog << personnel_post << ": '" << getName() << "' registered. Now available for work!\n" << endl; } void Doctor::retrivePatientDetails() { int id; string f_pwd; cout << "To view Patient record, enter your credentials below " << endl; cout << "Unique ID: " << endl; cin >> id; cout << "Enter record file name to access" << endl; cin >> patient_file; cout << "File access password: " << endl; cin >> f_pwd; if ((validate_id(id)) && (getFilePwd() == f_pwd )) { displayPatientData(); } else{ cerr << "Error: Authorization to Patient Record declined!" << endl; } } string Doctor::acknwNurseMedPrescription() { time_t now = time(0); char *dt = ctime(&now); // give access to medication to nurses cout << "\nYou can go ahead to give patient the following drug details:" << endl; cout << setw(75) << setfill('_') << " " << endl; cout << "Drug: " << setw(60) << setfill(' ') << "Panado(Pain Killer)" << endl; cout << "Duration: " << setw(60) << "2 weeks course" << endl; cout << "Instructions: " << setw(60) << "2 tablets/day after every meal" << endl; cout << "Prescribed at: " << setw(60) << dt; cout << "Personnel: " << setw(60) << personnel_post << endl; prescription = "Drug: \t\tPanado(Pain Killer)\n"; prescription += "Duration: \t\t2 weeks course\n"; prescription += "Instructions: \t\t2 pills/day after every meal\n"; prescription += "Prescriber: \t\t" + personnel_post + "\n"; return prescription; } void Doctor::checkNurseAppointments() { // check appointments from Nurses, saved to a file int id; cout << "Welcome Doctor. To check Nurse appointments, enter your 'id' below: " << endl; cin >> id; cout << "Enter record name to access" << endl; cin >> appointments_file; if (validate_id(id)) { clog << "\nStatus: searching for appointments."; for(int animate= 0; animate < 4; animate++) { cout << "."; Sleep(500); } cout << " " << endl; string f_hand = HospitalDatabaseSearch(appointments_file); if(f_hand != "None") { Save appointments_record; string app_records = appointments_record.read_from_disk(f_hand); cout << app_records << endl; } else { HospitalDatabaseSearch(f_hand); } } else { cerr << "Error: You are not authorized to access Nurse Appointments!\n" << endl; } } void Doctor::displayPatientData() { string f_hand = HospitalDatabaseSearch(patient_file); if(f_hand != "None") { Save patient_record; string p_data = patient_record.read_from_disk(f_hand); cout << p_data << endl; } else { HospitalDatabaseSearch(f_hand); } } Doctor::~Doctor() { //dtor }
86a8595f20eed2adc08d4ddfae349d8496c91227
3d2d8493bac65238cfb624f5d1c0438810ecff55
/JaalMesh/include/Doublet.hpp
dd6c3c99bdd725dbd75c0ea8bf98aef155c95945
[]
no_license
csv610/JaalGeometry
238033bdac1e650b7b126a1721c7fe478304173d
f6c714e7bf1c24f2663a234ea300c02cd9ebb47b
refs/heads/master
2020-12-30T22:43:36.729295
2017-02-14T19:41:50
2017-02-14T19:41:50
80,649,641
10
2
null
null
null
null
UTF-8
C++
false
false
858
hpp
#pragma once #include "Mesh.hpp" #include "MeshOptimization.hpp" /////////////////////////////////////////////////////////////////////////////// class JDoublet : public JMeshTopologyOptimization { static JLogger *logger; public: static bool isDoublet(const JNodePtr &v); static void addAttribute(const JMeshPtr &m, const string &s = "Doublet" ); int removeAll(); int getSize(); JNodeSequence getDoublets(); JNodeSequence getDoublets( const JNodeSequence &v); int remove(const JNodePtr &v); JNodePtr insert( const JFacePtr &f); JNodePtr insert(const JFacePtr &face, const JNodePtr &v0, const JNodePtr &v2); private: bool searched = 0; JNodeSequence doublets; JFaceSequence faceneighs; void searchDoublets(); }; ///////////////////////////////////////////////////////////////////////////////
[ "csverma@blackhole2" ]
csverma@blackhole2
d82ef20545f94445fd60d8450a76ff8f55a4ec41
be3167504c0e32d7708e7d13725c2dbc9232f2cb
/mame/src/mame/includes/djmain.h
79bfe453dd3e37339c66283004ed953e0e461a98
[]
no_license
sysfce2/MAME-Plus-Plus-Kaillera
83b52085dda65045d9f5e8a0b6f3977d75179e78
9692743849af5a808e217470abc46e813c9068a5
refs/heads/master
2023-08-10T06:12:47.451039
2016-08-01T09:44:21
2016-08-01T09:44:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,060
h
class djmain_state : public driver_device { public: djmain_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_obj_ram(*this, "obj_ram"){ } int m_sndram_bank; UINT8 *m_sndram; int m_turntable_select; UINT8 m_turntable_last_pos[2]; UINT16 m_turntable_pos[2]; UINT8 m_pending_vb_int; UINT16 m_v_ctrl; UINT32 m_obj_regs[0xa0/4]; const UINT8 *m_ide_user_password; const UINT8 *m_ide_master_password; required_shared_ptr<UINT32> m_obj_ram; DECLARE_WRITE32_MEMBER(paletteram32_w); DECLARE_WRITE32_MEMBER(sndram_bank_w); DECLARE_READ32_MEMBER(sndram_r); DECLARE_WRITE32_MEMBER(sndram_w); DECLARE_READ32_MEMBER(obj_ctrl_r); DECLARE_WRITE32_MEMBER(obj_ctrl_w); DECLARE_READ32_MEMBER(obj_rom_r); DECLARE_WRITE32_MEMBER(v_ctrl_w); DECLARE_READ32_MEMBER(v_rom_r); DECLARE_READ8_MEMBER(inp1_r); DECLARE_READ8_MEMBER(inp2_r); DECLARE_READ32_MEMBER(turntable_r); DECLARE_WRITE32_MEMBER(turntable_select_w); DECLARE_WRITE32_MEMBER(light_ctrl_1_w); DECLARE_WRITE32_MEMBER(light_ctrl_2_w); DECLARE_WRITE32_MEMBER(unknown590000_w); DECLARE_WRITE32_MEMBER(unknown802000_w); DECLARE_WRITE32_MEMBER(unknownc02000_w); DECLARE_READ32_MEMBER(ide_std_r); DECLARE_WRITE32_MEMBER(ide_std_w); DECLARE_READ32_MEMBER(ide_alt_r); DECLARE_WRITE32_MEMBER(ide_alt_w); DECLARE_DRIVER_INIT(bm7thmix); DECLARE_DRIVER_INIT(bm6thmix); DECLARE_DRIVER_INIT(hmcompmx); DECLARE_DRIVER_INIT(bmfinal); DECLARE_DRIVER_INIT(hmcompm2); DECLARE_DRIVER_INIT(bm5thmix); DECLARE_DRIVER_INIT(bm4thmix); DECLARE_DRIVER_INIT(beatmania); DECLARE_DRIVER_INIT(bmdct); DECLARE_DRIVER_INIT(bmcompm2); DECLARE_DRIVER_INIT(bmcorerm); DECLARE_DRIVER_INIT(bmclubmx); virtual void machine_start(); virtual void machine_reset(); virtual void video_start(); }; /*----------- defined in video/djmain.c -----------*/ SCREEN_UPDATE_RGB32( djmain ); void djmain_tile_callback(running_machine& machine, int layer, int *code, int *color, int *flags);
[ "mameppk@199a702f-54f1-4ac0-8451-560dfe28270b" ]
mameppk@199a702f-54f1-4ac0-8451-560dfe28270b
25da0ac266139f67fe2017fa77fba176c2e69f7a
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Applications/Imagics/ExtractLevelCurves/ImageInterp2D.h
0b7eddea6012c07dcc1755c37e5ec9b06fa86b96
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
3,147
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef IMAGEINTERP2D_H #define IMAGEINTERP2D_H #include "WmlEdgeKey.h" #include "WmlImages.h" using namespace Wml; #include <vector> using namespace std; class ImageInterp2D : public ImageInt2D { public: ImageInterp2D (int iXBound, int iYBound, int* aiData); ImageInterp2D (const char* acFilename); float LinearInterpolate (float fX, float fY) const; float BilinearInterpolate (float fX, float fY) const; class Vertex { public: Vertex (int iXNumer = 0, int iXDenom = 0, int iYNumer = 0, int iYDenom = 0); // for STL map bool operator< (const Vertex& rkVertex) const; void GetPair (float& rfX, float& rfY) const; void GetPair (double& rdX, double& rdY) const; // vertices stored as rational numbers (xnumer/xdenom,ynumer/ydenom) int m_iXNumer, m_iXDenom, m_iYNumer, m_iYDenom; }; // The extraction assumes linear interpolation (decomposition of image // domain into tetrahedra). To make the extraction fast, the arrays // make no attempt to store only unique values. This supports rapid // interactive exploration of various level sets in an image until a // desired one is found. At that time call MakeUnique to eliminate the // redundant information. void ExtractLevelSetLinear (int iLevel, int& riVertexQuantity, Vertex*& rakVertex, int& riEdgeQuantity, EdgeKey*& rakEdge); // The extraction assumes bilinear interpolation. void ExtractLevelSetBilinear (int iLevel, int& riVertexQuantity, Vertex*& rakVertex, int& riEdgeQuantity, EdgeKey*& rakEdge); // Remove redundant vertices and edges. static void MakeUnique (int& riVertexQuantity, Vertex*& rakVertex, int& riEdgeQuantity, EdgeKey*& rakEdge); protected: // support for extraction of level sets typedef vector<Vertex> VertexArray; typedef vector<EdgeKey> EdgeArray; void AddVertex (VertexArray& rkVArray, int iXNumer, int iXDenom, int iYNumer, int iYDenom); void AddEdge (VertexArray& rkVArray, EdgeArray& rkEArray, int iXNumer0, int iXDenom0, int iYNumer0, int iYDenom0, int iXNumer1, int iXDenom1, int iYNumer1, int iYDenom1); // support for extraction with linear interpolation void ProcessTriangle (int iLevel, VertexArray& rkVA, EdgeArray& rkEA, int iX0, int iY0, int iF0, int iX1, int iY1, int iF1, int iX2, int iY2, int iF2); // support for extraction with bilinear interpolation void ProcessSquare (int iLevel, VertexArray& rkVA, EdgeArray& rkEA, int iX, int iXP, int iY, int iYP, int iF00, int iF10, int iF11, int iF01); }; #endif
db8f7249a6f46a6513d4b057d0d4f7b4a7065bf7
6ff98b8b145d494c37233e7606de1471cea06434
/Bitest/print/PrintView.h
89884914d30c7bfbcf75f057ee669dbe087a9b6e
[]
no_license
EasyMapOrg/Bitest
c3cff115a0fc2416763fe179ab17ce4966f4e3fd
3b51889f1cb0c901733cc95e8ebdf9bcf6dc13c2
refs/heads/master
2020-03-07T20:26:37.970541
2016-05-21T06:41:25
2016-05-21T06:41:25
null
0
0
null
null
null
null
GB18030
C++
false
false
8,240
h
#if !defined(AFX_PRINTVIEW_H__2AF9CEDE_8D19_4688_94ED_3995497B2427__INCLUDED_) #define AFX_PRINTVIEW_H__2AF9CEDE_8D19_4688_94ED_3995497B2427__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // PrintView.h : header file // #include "DATASTRUCT.h" #include "Util.h" ///////////////////////////////////////////////////////////////////////////// // CPrintView view // CMyView 视图 const float FONTSIZE_RATIO[5] = {1.0, 0.8, 0.6, 0.45, 0.4}; //报表输出时用的字体的缩放比例,[0]表示单报表,[1]表示2图/页,[2]表示4图/页,[3]表示6图/页,[4]表示8图每页 typedef struct PrintQuest { CString strTitle;//任务标题 CString strID;//任务编号 CString strContractor; //承包商 CString strCustomer; //用户 CString strSorFileName; //文件名 CString strTestDate; //测试日期 CString strPlayer; //操作员 //value CString QuestID; //任务编号 CString Contractor; //承包商 CString Customer; //用户 CString SorFileName; //文件名 CString TestDate; //测试日期 CString Player; //操作员 }; typedef struct PrintConfig { //name CString strTitle; //标题文字 CString strWavelength; //测量波长 CString strPulse; //脉宽 CString strOrigin; //起点 CString strOriCable; //起点光缆号 CString strOriFiber; //起点光纤号 CString strOriColor; //起点关纤颜色 CString strRange; //距离 CString strAverage; //平均的次数 CString strEnd; //终点 CString strEndCable; //终点光缆号 CString strEndFiber; //终点光纤号 CString strEndColor; //终点颜色 CString strOriLocation;//起点位置 CString strEndLocation; //终点位置 CString strBackScatter; //背向散射系数 CString strLossThreshold; //衰减门限 CString strRefThreshold; //反射门限 CString strEndThreshold; //光纤末端门限 CString strIndex; //测量时用的折射率 CString strResolution; //解析度 CString strTitleAB; //AB曲线 CString strTitleBA; //BA曲线 //value CString OriCable; //起点光缆号 CString OriFiber; //起点光纤号 CString OriColor; //起点关纤颜色 CString EndCable; //终点光缆号 CString EndFiber; //终点光纤号 CString EndColor; //终点颜色 CString OriLocation;//起点位置 CString EndLocation; //终点位置 CString Wavelength; //测量波长 CString Index; //测量时用的折射率 CString Pulse; //脉宽 CString Range; //距离 CString Average; //平均的次数 CString Resolution; //解析度 CString BackScatter; //背向散射系数 CString LossThreshold; //衰减门限 CString RefThreshold; //反射门限 CString EndThreshold; //光纤末端门限 }; typedef struct PrintComment { CString strTitle; //注释标题文字 CString strComment; //注释 }; typedef struct PrintTrace { CString strTitle; //轨迹线标题 CString LocationA; //A标位置 CString LossA; //A标处损耗 CString LocationB; //B标位置 CString LossB; //B标处损耗 CString DistanceAB; //AB位置间隔 CString LossAB; //AB损耗差 CString SlopeAB; //AB段损耗斜率 }; struct WaveConfig { COLORREF ColorCurve1; //曲线1颜色 COLORREF ColorCurve2; //曲线2颜色 COLORREF ColorBack; //背景颜色 COLORREF ColorGrid; //栅格颜色 COLORREF ColorEvent; //事件颜色 COLORREF ColorCursor; //光标颜色 BOOL ShowGrid; //是否显示网格 BOOL ShowCursor; //是否显示光标 BOOL ShowDoubleCursor; //是否显示双光标 BOOL MultiMode; //是否为多曲线显示模式 //Unit Page int UnitDbFig; //Dt刻度单位精度5\4\3 int UnitDistFig; //距离刻度单位精度 CString DistUnit; //距离单位 }; typedef struct PrintEvent { CString strTitle; int EventColumn; //事件列表列数 int EventCount; //事件行数 }; //所有的打印信息 struct PrintDetail { CString strTitle; CString strLogo; PrintQuest stPrintQuest; PrintComment stComment; PrintConfig stPrintConfig; //配置信息 PrintTrace stPrintTrace; WaveConfig stWaveConfig; PrintEvent stPrintEvent; TestResultInfo stTestResultInfo[3]; INT curSelection;//文件列表当前选中哪个 INT totalCurveNumber; CString WaveList; }; class CPrintView : public CView { public: CPrintView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CPrintView) // Operations public: void OnMyPrint(); void OnMyPrintPreview(); virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo); virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrintPreview(CDC* pDC, CPrintInfo* pInfo, POINT point, CPreviewView* pView); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CPrintView) protected: virtual void OnDraw(CDC* pDC); // overridden to draw this view //}}AFX_VIRTUAL // Implementation public: virtual ~CPrintView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Attributes public: BOOL m_bPrint; BOOL m_bPrintCurve; CRect m_rectDraw;//绘制矩形区域大小 private: // Print BOOL m_bPrintData; BOOL m_bPrintImage; BOOL m_bPrintHead; UINT m_cxWidth; UINT m_cxOffset; UINT m_nLinesPerPage; UINT m_PageCount; UINT m_cyPrinter; CFont m_ListFont; CFont m_fontPrinter; CFont m_dataFont; CFont m_FontVR; CFont m_fontGroup; //组标题的字体 public: BOOL m_bPrintLogo; //是否打印光维版权信息 BOOL m_bPrintQuest; //是否打印任务 BOOL m_bPrintConfig; //是否打印配置 BOOL m_bPrintComment;//是否打印注释 BOOL m_bPrintTrace;//是否打印曲线 BOOL m_bPrintEvent;//是否打印事件 BOOL m_bShowGrid;//是否打印事件 //ghq 2016.4.21 INT m_nCurveNumber; CUtil m_util; PrintDetail m_stPrintDetail; CString strListHead[8]; CString strListHead2Way[8]; public: void DrawGridLine(CDC* pDC, CRect& rect);//绘制栅格 void DrawPrintContent(CDC* pDC, CRect rectDraw,INT nCurSel = 0, BOOL bSingle = TRUE); //绘制打印预览波形 void DrawScale(CDC *pDC, CRect &rect, FLOAT fYmax = 0, FLOAT fXmax = 0);//绘制刻度 void DrawCurve(CDC* pDC, CRect& rect, INT nCurveIndex); void DrawTrace(CDC *pDC, CRect rc, INT nCurSel, FLOAT fontRatio = 1.0); //绘制带坐标曲线 void DrawConfig(CDC* pDC, CRect rectDraw,INT &nBottom,INT nCurSel); void InnerDraw(CDC* pDC,INT m_nCurPage); //内部绘图只用 void DrawEventHead(CDC* pDC, INT nLeft, INT nTop, CRect rectDraw,INT nCurSel);//绘制事件列表表头 void DrawEventList(CDC* pDC, INT nLeft, INT nTop, INT nVspace, CRect rectDraw, INT nCurSel);//绘制事件列表 void DrawEventList2Way(CDC* pDC, INT nLeft, INT nTop , INT nVspace , CRect rectDraw, INT nCurSel);//绘制双向事件列表 void InitFont(CDC* pDC); //初始化字体 void InitPrintText(); void DrawCurve2Way(CDC* pDC, CRect& rect, INT nCurveIndex); void DrawEvent(CDC* pDC, CRect& rect, INT nCurveIndex); void DrawEvent2Way(CDC* pDC, CRect& rect, INT nCurveIndex); void GetEvent2Way(TestResultInfo *pInfo2Way, TestResultInfo *infoA2B, TestResultInfo *infoB2A); void DrawScale2Way(CDC *pDC, CRect &rect, FLOAT fXmin, FLOAT fXmax); void PrintPageHeader(CDC* pDC, UINT nPageNumber, CPrintInfo* pInfo); void DrawPrintContentPage2(CDC* pDC, CRect rectDraw, INT nCurSel, BOOL bSingle = TRUE); void DrawEventListPage2(CDC* pDC, INT nLeft, INT nTop, INT nVspace, CRect rectDraw, INT nCurSel);//绘制事件列表 void DrawEventList2WayPage2(CDC* pDC, INT nLeft, INT nTop , INT nVspace , CRect rectDraw, INT nCurSel);//绘制双向事件列表 public: void MemcpyResInfo(TestResultInfo *pResultInfo); // Generated message map functions public: //{{AFX_MSG(CPrintView) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_PRINTVIEW_H__2AF9CEDE_8D19_4688_94ED_3995497B2427__INCLUDED_)
71c82596967cdd4fab7506d2504444fb017d7107
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/statistics/cross_validation/boost/statistics/detail/cross_validation/extractor/identity.hpp
90639402e94af028a07ed580482c0c1e3dac1bf2
[ "BSL-1.0" ]
permissive
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
1,325
hpp
////////////////////////////////////////////////////////////////////////////// // cross_validation::extractor::identity.hpp // // // // (C) Copyright 2009 Erwann Rogard // // 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) // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_STATISTICS_DETAIL_CROSS_VALIDATION_EXTRACTOR_IDENTITY_HPP_ER_2009 #define BOOST_STATISTICS_DETAIL_CROSS_VALIDATION_EXTRACTOR_IDENTITY_HPP_ER_2009 namespace boost{ namespace statistics{ namespace detail{ namespace cross_validation{ namespace extractor{ struct identity{ identity(){} template<typename T> struct result{}; template<typename T> struct result<identity(const T&)>{ typedef const T& type; }; template<typename T> const T& operator()(const T& t)const{ return t; } }; }// iterator }// cross_validation }// detail }// statistics }// boost #endif
1fb97962d5dc3dfb01b19eb3c635eeacc85b1050
9104c971481ddadeb06e2af9a95305625e7c006f
/A_RTA/sol/ok.cpp
4e143a29998c68e36180cbbb5d7f04a19d7432ac
[]
no_license
Aizu-Competitive-Programming-Club/acpc2020
55d7a896ac3e874482813e769bef72359343c365
369e2175dbdbd0536543dcac54a2429843dcfc32
refs/heads/master
2022-12-14T22:23:26.207777
2020-09-20T05:40:21
2020-09-20T05:40:21
282,199,819
1
0
null
null
null
null
UTF-8
C++
false
false
125
cpp
#include<iostream> using namespace std; int main(){ int a, b; cin>>a>>b; cout<<a * 2 + b * 3<<endl; return 0; }
84f047638f2942d316f5a24ad8f10ecf71a69fd2
0dbc8983b64f588369d5de1a5e29347c41bdd899
/Project2/Person.h
99ffa7012b8fad0720df17420148aa165f15b254
[]
no_license
mrdiegoboy/Project2
733325677d0dcd90273b6c054d604b37af675032
ffbf34e1a57835fee9c8c2e66344a6d457af886a
refs/heads/master
2020-06-06T16:19:03.071916
2014-06-07T06:53:13
2014-06-07T06:53:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
548
h
/* * File: Person.h * Author: Diego * * Created on June 5, 2014, 8:21 PM */ #ifndef PERSON_H #define PERSON_H #include <iostream> using namespace std; class Person{ protected: string name; string address; string city; string state; int zip; public: string getName(); string getAddress(); string getCity(); string getState(); int getZip(); void setName(string); void setAddress(string); void setCity(string); void setState(string); void setZip(int); }; #endif /* PERSON_H */
b22f889bc973abcf790951ea05e2e92fb154e97a
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/libc/nt/thunk/paint.inc
5f9705a9f5bde287b61eb2bba17f82c70fab8b33
[ "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C++
false
false
211
inc
#define SetPixel(...) __imp_SetPixel(__VA_ARGS__) #define GetPixel(...) __imp_GetPixel(__VA_ARGS__) extern typeof(SetPixel) *const __imp_SetPixel __msabi; extern typeof(GetPixel) *const __imp_GetPixel __msabi;
91e6543b09fb7cff6c28ee7fe1ce809ba7ada34f
960c37661139294f79eca8a54e776f5377889425
/recursion/reverse a stack.cpp
a3c5e40bad19df8ce1df014880ef4b03defab9bd
[]
no_license
wizee-B/DS
a462777229e959535eefb47cfcb6804f033f8d03
b4f556b9a443b6ed5ba9767f9772fa821d924780
refs/heads/master
2022-11-13T19:31:17.282562
2020-07-04T07:56:16
2020-07-04T07:56:16
274,567,061
0
0
null
null
null
null
UTF-8
C++
false
false
735
cpp
#include<bits/stdc++.h> using namespace std; void print(stack<int> &s){ if(s.empty())return ; int x=s.top(); cout<<x<<" "; s.pop(); print(s); s.push(x); } void put_at_end(stack<int> &s, int x){ if(s.empty()){s.push(x);return ;} int y=s.top(); s.pop(); put_at_end(s,x); s.push(y); } void stack_reverse(stack<int> &s){ if(s.size()<=1)return; int x=s.top(); s.pop(); stack_reverse(s); put_at_end(s,x); } int main(){ stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); // s.push(6); // s.push(7); // s.push(8); // s.push(9); // s.push(10); print(s); stack_reverse(s); print(s); }
01575c60e7e0a6d12061c4649c1a5f7192601145
4d657ab78b904f3103ff9f8dc2bd5c137fb0973a
/cses/concert-tickets1.cpp
2eb77ad92e060a1dfaa5d26de6c892163849ee39
[]
no_license
durgeshak19/Cpp_DS_Algos
8b5eddcdea0d552f50f72fc4295bd632c4de6d61
42e5071b110e82a6cbda0ab08813daaf51119af2
refs/heads/main
2023-09-05T04:52:08.131393
2021-11-22T08:49:32
2021-11-22T08:49:32
367,378,037
0
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n,m,h,t; multiset<int> tickets; cin >> n >> m; for (int i=0;i<n;++i){ cin >> h; tickets.insert(h); } for (int i=0;i<m;++i){ cin >> t; auto it = tickets.upper_bound(t); if (it==tickets.begin()){ cout << -1 << "\n"; } else{ cout << *(--it) << "\n"; tickets.erase(it); } } }
f48ab9a2840b96c35bcd072acc3ff04546b8103d
0b9d9c4ba6f17ab2a43ce5a339010f7919d115e1
/src/main.cpp
98ff6dda842065e2583cf78f09150a8e0be04169
[]
no_license
paukert/fit-ctu-bi-pa2
95e3b342aa6a0c729f3e0f9480b7a6a607a3d19f
dda0d5c2bf531eef5a46a9fd4be6a4cac13809e9
refs/heads/master
2023-03-27T17:37:02.079674
2021-03-30T21:59:16
2021-03-30T21:59:16
352,959,443
0
0
null
null
null
null
UTF-8
C++
false
false
386
cpp
#include <iostream> #include <exception> #include "CApplication.h" using namespace std; int main() { try { CApplication().run(); } catch (const exception & e) { cerr << e.what() << endl; return EXIT_FAILURE; } catch (...) { cerr << "Something went wrong :(" << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
41a8bb48eb71fd79cca512cdc3cd84b033ef8348
5c18724055f2b86a5c9e6d04db24f86602d34bc1
/tests/data/SimpleParser.cpp
460c28b71bc937c08d12dca0105f4da7b57d49cb
[ "LLVM-exception", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
FergusonAJ/Empirical
35478e5b075bc0ad92eb8372fd0f1ab099787b4f
944968bac43274b601237392dfc82323942ffc20
refs/heads/master
2023-08-22T04:01:53.003213
2023-08-09T20:45:36
2023-08-09T20:45:36
192,601,261
0
0
null
2023-08-09T20:45:37
2019-06-18T19:34:11
C++
UTF-8
C++
false
false
11,051
cpp
/** * @note This file is part of Empirical, https://github.com/devosoft/Empirical * @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md * @date 2022 * * @file SimpleParser.cpp */ #define CATCH_CONFIG_MAIN #include "third-party/Catch/single_include/catch2/catch.hpp" #include <map> #include <unordered_map> #include "emp/data/SimpleParser.hpp" TEST_CASE("Test DataMap in SimpleParser", "[data]") { emp::DataMap dmA; dmA.AddVar<double>("val1", 1.5); dmA.AddVar<double>("val2", 2.0); dmA.AddVar<int>("val3", 3); dmA.AddVar<char>("char", 'A'); dmA.AddVar<double>("val4", 256.0); emp::DataMap dmB(dmA); dmB.Get<double>("val1") = 0.125; dmB.Get<double>("val2") = 64.25; dmB.Get<int>("val3") = 4; dmB.Get<char>("char") = '%'; dmB.Get<double>("val4") = 1024.0; // val1 val2 val3 val4 // dmA: 1.5 2 3 256 // dmB 0.125 64.25 4 1024 emp::SimpleParser parser; // Test a bunch of constant math. CHECK( parser.RunMathFunction(dmA, "(0 || 0)") == 0.0 ); CHECK( parser.RunMathFunction(dmA, "(0 || 1) + (1 || 0) + (1 || 1)") == 3.0 ); CHECK( parser.RunMathFunction(dmA, "(0 && 1) + (1 && 0) + (1 && 1)") == 1.0 ); CHECK( parser.RunMathFunction(dmA, "(0 == 0) + (1 == 1.000000001) + (1.1 == 1.2)") == 1.0 ); CHECK( parser.RunMathFunction(dmA, "(0 ~== 0) + (1 ~== 1.000000001) + (1.1 ~== 1.2)") == 2.0 ); CHECK( parser.RunMathFunction(dmA, "(0 != 0) + (1 != 1.000000001) + (1.1 != 1.2)") == 2.0 ); CHECK( parser.RunMathFunction(dmA, "(0 ~!= 0) + (1 ~!= 1.000000001) + (1.1 ~!= 1.2)") == 1.0 ); CHECK( parser.RunMathFunction(dmA, "(0 < 0) + (1 < 1.000000001) + (1.1 < 1.2)") == 2.0 ); CHECK( parser.RunMathFunction(dmA, "(0 ~< 0) + (1 ~< 1.000000001) + (1.1 ~< 1.2)") == 1.0 ); CHECK( parser.RunMathFunction(dmA, "(0 <= 0) + (1 <= 1.000000001) + (1.1 <= 1.2)") == 3.0 ); CHECK( parser.RunMathFunction(dmA, "(0 ~<= 0) + (1 ~<= 1.000000001) + (1.1 ~<= 1.2)") == 3.0 ); CHECK( parser.RunMathFunction(dmA, "(0 > 0) + (1 > 0.999999999) + (1.3 > 1.2)") == 2.0 ); CHECK( parser.RunMathFunction(dmA, "(0 ~> 0) + (1 ~> 0.999999999) + (1.3 ~> 1.2)") == 1.0 ); CHECK( parser.RunMathFunction(dmA, "(0 >= 0) + (1 >= 1.000000001) + (1.3 >= 1.2)") == 2.0 ); CHECK( parser.RunMathFunction(dmA, "(0 ~>= 0) + (1 ~>= 1.000000001) + (1.3 ~>= 1.2)") == 3.0 ); CHECK( parser.RunMathFunction(dmA, "5.5 + 4") == 9.5 ); CHECK( parser.RunMathFunction(dmA, "5.5 - 4") == 1.5 ); CHECK( parser.RunMathFunction(dmA, "5.5 * 4") == 22.0 ); CHECK( parser.RunMathFunction(dmA, "5.5 / 4") == 1.375 ); CHECK( parser.RunMathFunction(dmA, "5.5 % 4") == 1.5 ); CHECK( parser.RunMathFunction(dmA, "5.5 ** 4") == 915.0625 ); CHECK( parser.RunMathFunction(dmA, "30.25 ** 0.5") == 5.5 ); CHECK( parser.RunMathFunction(dmA, "64 %% 4") == 3.0 ); CHECK( parser.RunMathFunction(dmA, "1 + 2 * 2") == 5.0 ); CHECK( parser.RunMathFunction(dmA, "(1+2) * 2") == 6.0 ); CHECK( parser.RunMathFunction(dmA, "(3*3 + 4**2) ** 0.5") == 5.0 ); // Test with external variables. CHECK( parser.RunMathFunction(dmA, "$0 + $1 * $2", 1.4, 2, 7.1) == 15.6 ); // Now, try to use these with DataMap variables! std::function<emp::Datum(const emp::DataMap &)> fun = parser.BuildMathFunction(dmA, "val1 + val2 + 2*val3"); CHECK( fun(dmA) == 9.5 ); CHECK( fun(dmB) == 72.375 ); std::set<std::string> names_used = parser.GetNamesUsed(); CHECK( names_used.size() == 3 ); CHECK( emp::Has(names_used, "val1") ); CHECK( emp::Has(names_used, "val2") ); CHECK( emp::Has(names_used, "val3") ); CHECK( !emp::Has(names_used, "val4") ); fun = parser.BuildMathFunction(dmA, "1.5*val3"); CHECK( fun(dmA) == 4.5 ); CHECK( fun(dmB) == 6.0 ); names_used = parser.GetNamesUsed(); CHECK( names_used.size() == 1 ); CHECK( !emp::Has(names_used, "val1") ); CHECK( !emp::Has(names_used, "val2") ); CHECK( emp::Has(names_used, "val3") ); CHECK( !emp::Has(names_used, "val4") ); fun = parser.BuildMathFunction(dmA, "val1/0.5"); CHECK( fun(dmA) == 3.0 ); CHECK( fun(dmB) == 0.25 ); fun = parser.BuildMathFunction(dmA, "1.5*val3 - val1/0.5"); CHECK( fun(dmA) == 1.5 ); CHECK( fun(dmB) == 5.75 ); fun = parser.BuildMathFunction(dmA, "val2/64"); CHECK( fun(dmA) == 0.03125 ); CHECK( fun(dmB) == 1.00390625 ); fun = parser.BuildMathFunction(dmA, "1.5*val3 - val1/0.5 - val2/64"); CHECK( fun(dmA) == 1.46875 ); CHECK( fun(dmB) == 4.74609375 ); // Pairs of variables with each operation fun = parser.BuildMathFunction(dmA, "val1*val2"); CHECK( fun(dmA) == 3.0 ); CHECK( fun(dmB) == 8.03125 ); fun = parser.BuildMathFunction(dmA, "val3/val1"); CHECK( fun(dmA) == 2.0 ); CHECK( fun(dmB) == 32.0 ); fun = parser.BuildMathFunction(dmA, "val2%val1"); CHECK( fun(dmA) == 0.5 ); CHECK( fun(dmB) == 0.0 ); fun = parser.BuildMathFunction(dmA, "val1**val3"); CHECK( fun(dmA) == 3.375 ); CHECK( fun(dmB) == 0.000244140625 ); fun = parser.BuildMathFunction(dmA, "val4%%(val3*2-4)"); CHECK( fun(dmA) == 8.0 ); CHECK( fun(dmB) == 5.0 ); // ...and all together now... fun = parser.BuildMathFunction(dmA, "val1*val2 + val3/val1 + val2%val1 + val1**val3 - val4%%(val3*2-4)"); CHECK( fun(dmA) == 0.875 ); CHECK( fun(dmB) == 35.031494140625 ); names_used = parser.GetNamesUsed(); CHECK( names_used.size() == 4 ); CHECK( emp::Has(names_used, "val1") ); CHECK( emp::Has(names_used, "val2") ); CHECK( emp::Has(names_used, "val3") ); CHECK( emp::Has(names_used, "val4") ); // Using functions. fun = parser.BuildMathFunction(dmA, "EXP(val1,val3)"); CHECK( fun(dmA) == 3.375 ); CHECK( fun(dmB) == 0.000244140625 ); fun = parser.BuildMathFunction(dmA, "LOG(val4, val3*2-4)"); CHECK( fun(dmA) == 8.0 ); CHECK( fun(dmB) == 5.0 ); fun = parser.BuildMathFunction(dmA, "ABS(val3 - val2)"); CHECK( fun(dmA) == 1.0 ); CHECK( fun(dmB) == 60.25 ); fun = parser.BuildMathFunction(dmA, "CBRT(val1)"); CHECK( fun(dmA).AsDouble() == Approx(1.1447142426) ); CHECK( fun(dmB).AsDouble() == Approx(0.5) ); fun = parser.BuildMathFunction(dmA, "SQRT(val2)"); CHECK( fun(dmA).AsDouble() == Approx(1.4142135624) ); CHECK( fun(dmB).AsDouble() == Approx(8.0156097709) ); fun = parser.BuildMathFunction(dmA, "SQRT(val3)"); CHECK( fun(dmA).AsDouble() == Approx(1.7320508076) ); CHECK( fun(dmB) == 2.0 ); fun = parser.BuildMathFunction(dmA, "CBRT(val4)"); CHECK( fun(dmA).AsDouble() == Approx(6.3496042079) ); CHECK( fun(dmB).AsDouble() == Approx(10.0793683992) ); fun = parser.BuildMathFunction(dmA, "SQRT(val3) * SQRT(val2) + CBRT(val1) + CBRT(val4)"); CHECK( fun(dmA).AsDouble() == Approx(9.9438081932) ); CHECK( fun(dmB).AsDouble() == Approx(26.610587941) ); fun = parser.BuildMathFunction(dmA, "LOG(val1) + LOG(val2,9) + LOG2(val3) + LOG10(val4)"); CHECK( fun(dmA).AsDouble() == Approx(4.7141324511) ); CHECK( fun(dmB).AsDouble() == Approx(4.8254220245) ); names_used = parser.GetNamesUsed(); CHECK( names_used.size() == 4 ); CHECK( emp::Has(names_used, "val1") ); CHECK( emp::Has(names_used, "val2") ); CHECK( emp::Has(names_used, "val3") ); CHECK( emp::Has(names_used, "val4") ); CHECK( !emp::Has(names_used, "LOG") ); CHECK( !emp::Has(names_used, "LOG2") ); CHECK( !emp::Has(names_used, "LOG10") ); fun = parser.BuildMathFunction(dmA, "SIN(val1)"); CHECK( fun(dmA).AsDouble() == Approx(0.9974949866) ); CHECK( fun(dmB).AsDouble() == Approx(0.1246747334) ); fun = parser.BuildMathFunction(dmA, "COS(val2)"); CHECK( fun(dmA).AsDouble() == Approx(-0.4161468365) ); CHECK( fun(dmB).AsDouble() == Approx(0.1520572536) ); fun = parser.BuildMathFunction(dmA, "TAN(val4 - val3)"); CHECK( fun(dmA).AsDouble() == Approx(-9.7900600635) ); CHECK( fun(dmB).AsDouble() == Approx(-1.6194475388) ); fun = parser.BuildMathFunction(dmA, "SIN(val1) + COS(val2) + TAN(val4 - val3)"); CHECK( fun(dmA).AsDouble() == Approx(-9.2087119135) ); CHECK( fun(dmB).AsDouble() == Approx(-1.3427155518) ); fun = parser.BuildMathFunction(dmA, "CEIL(SIN(val1))"); CHECK( fun(dmA) == 1.0 ); CHECK( fun(dmB) == 1.0 ); names_used = parser.GetNamesUsed(); CHECK( names_used.size() == 1 ); CHECK( emp::Has(names_used, "val1") ); CHECK( !emp::Has(names_used, "val2") ); CHECK( !emp::Has(names_used, "val3") ); CHECK( !emp::Has(names_used, "val4") ); CHECK( !emp::Has(names_used, "CEIL") ); CHECK( !emp::Has(names_used, "SIN") ); fun = parser.BuildMathFunction(dmA, "FLOOR(COS(val2))"); CHECK( fun(dmA) == -1.0 ); CHECK( fun(dmB) == 0.0 ); fun = parser.BuildMathFunction(dmA, "ROUND(TAN(val4 - val3))"); CHECK( fun(dmA) == -10.0 ); CHECK( fun(dmB) == -2.0 ); fun = parser.BuildMathFunction(dmA, "HYPOT(2*val1, val3+1)"); CHECK( fun(dmA) == 5.0 ); CHECK( fun(dmB).AsDouble() == Approx(5.0062460986) ); fun = parser.BuildMathFunction(dmA, "MIN(val2, val3)"); CHECK( fun(dmA) == 2.0 ); CHECK( fun(dmB) == 4.0 ); fun = parser.BuildMathFunction(dmA, "MAX(val1*200, val4)"); CHECK( fun(dmA) == 300.0 ); CHECK( fun(dmB) == 1024.0 ); fun = parser.BuildMathFunction(dmA, "IF(val1 > 1, val3, val4)"); CHECK( fun(dmA) == 3.0 ); CHECK( fun(dmB) == 1024.0 ); fun = parser.BuildMathFunction(dmA, "CLAMP(val1, 0, 1)"); CHECK( fun(dmA) == 1.0 ); CHECK( fun(dmB) == 0.125 ); fun = parser.BuildMathFunction(dmA, "CLAMP(val4, 500, 600)"); CHECK( fun(dmA) == 500.0 ); CHECK( fun(dmB) == 600.0 ); fun = parser.BuildMathFunction(dmA, "TO_SCALE(val1, 1000, 2000)"); CHECK( fun(dmA) == 2500.0 ); CHECK( fun(dmB) == 1125.0 ); fun = parser.BuildMathFunction(dmA, "FROM_SCALE(val3, 1.5, 11.5)"); CHECK( fun(dmA) == 0.15 ); CHECK( fun(dmB) == 0.25 ); // Test with more extra values. double multiple = 2.0; std::string expression = "(val1 + val2 + 2*val3) * $0"; fun = parser.BuildMathFunction(dmA, expression, multiple); CHECK( fun(dmA) == 19 ); CHECK( fun(dmB) == 144.75 ); multiple = 1.0; fun = parser.BuildMathFunction(dmA, expression, multiple); CHECK( fun(dmA) == 9.5 ); CHECK( fun(dmB) == 72.375 ); // Test with string concatenation for '+' emp::DataMap dmC; dmC.AddVar<std::string>("val1", "abc"); dmC.AddVar<std::string>("val2", "def"); fun = parser.BuildMathFunction(dmC, "val1 + val2"); CHECK(fun(dmC).AsString() == "abcdef"); } TEST_CASE("Test std::map in SimpleParser", "[data]") { std::map<std::string, double> var_map; var_map["x"] = 5; var_map["y"] = 10; emp::SimpleParser parser; auto fun = parser.BuildMathFunction(var_map, "11*x + y*y"); CHECK(fun(var_map) == 155.0); var_map["x"] = 3.5; var_map["y"] = 5; CHECK(fun(var_map) == 63.5); } TEST_CASE("Test emp::ra_map in SimpleParser", "[data]") { emp::ra_map<std::string, double> var_map; var_map["x"] = 5; var_map["y"] = 10; emp::SimpleParser parser; auto fun = parser.BuildMathFunction(var_map, "11*x + y*y"); CHECK(fun(var_map) == 155.0); var_map["x"] = 3.5; var_map["y"] = 5; CHECK(fun(var_map) == 63.5); }
83f2698a3f436130e6c2d5efc1ecb244696be2b1
aa675a2c3658ce6d8d44de3985dd5b8090ddba9a
/cocos/2d/CCAutoPolygon.cpp
38a65c12a3275000b6989d2bd21c23695a10f713
[ "MIT" ]
permissive
mowenli/cocos2d-x-lite
7b08cb66ae9c99d33552b077babba8665ce2324e
a28324f91bbbf33158fb971688d57567b61f9916
refs/heads/master
2022-05-22T12:15:54.634012
2016-04-11T07:53:59
2016-04-11T07:53:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,321
cpp
/**************************************************************************** Copyright (c) 2015-2016 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCAutoPolygon.h" USING_NS_CC; static unsigned short quadIndices[]={0,1,2, 3,2,1}; PolygonInfo::PolygonInfo(const PolygonInfo& other): triangles(), isVertsOwner(true), rect() { filename = other.filename; isVertsOwner = true; rect = other.rect; triangles.verts = new (std::nothrow) V3F_C4B_T2F[other.triangles.vertCount]; triangles.indices = new (std::nothrow) unsigned short[other.triangles.indexCount]; triangles.vertCount = other.triangles.vertCount; triangles.indexCount = other.triangles.indexCount; memcpy(triangles.verts, other.triangles.verts, other.triangles.vertCount*sizeof(V3F_C4B_T2F)); memcpy(triangles.indices, other.triangles.indices, other.triangles.indexCount*sizeof(unsigned short)); }; PolygonInfo& PolygonInfo::operator= (const PolygonInfo& other) { if(this != &other) { releaseVertsAndIndices(); filename = other.filename; isVertsOwner = true; rect = other.rect; triangles.verts = new (std::nothrow) V3F_C4B_T2F[other.triangles.vertCount]; triangles.indices = new (std::nothrow) unsigned short[other.triangles.indexCount]; triangles.vertCount = other.triangles.vertCount; triangles.indexCount = other.triangles.indexCount; memcpy(triangles.verts, other.triangles.verts, other.triangles.vertCount*sizeof(V3F_C4B_T2F)); memcpy(triangles.indices, other.triangles.indices, other.triangles.indexCount*sizeof(unsigned short)); } return *this; } PolygonInfo::~PolygonInfo() { releaseVertsAndIndices(); } void PolygonInfo::setQuad(V3F_C4B_T2F_Quad *quad) { releaseVertsAndIndices(); isVertsOwner = false; triangles.indices = quadIndices; triangles.vertCount = 4; triangles.indexCount = 6; triangles.verts = (V3F_C4B_T2F*)quad; } void PolygonInfo::setTriangles(const TrianglesCommand::Triangles& other) { releaseVertsAndIndices(); isVertsOwner = false; triangles.vertCount = other.vertCount; triangles.indexCount = other.indexCount; triangles.verts = other.verts; triangles.indices = other.indices; } void PolygonInfo::releaseVertsAndIndices() { if(isVertsOwner) { if(nullptr != triangles.verts) { CC_SAFE_DELETE_ARRAY(triangles.verts); } if(nullptr != triangles.indices) { CC_SAFE_DELETE_ARRAY(triangles.indices); } } } unsigned int PolygonInfo::getVertCount() const { return (unsigned int)triangles.vertCount; } unsigned int PolygonInfo::getTrianglesCount() const { return (unsigned int)triangles.indexCount/3; } float PolygonInfo::getArea() const { float area = 0; V3F_C4B_T2F *verts = triangles.verts; unsigned short *indices = triangles.indices; for(int i = 0; i < triangles.indexCount; i+=3) { auto A = verts[indices[i]].vertices; auto B = verts[indices[i+1]].vertices; auto C = verts[indices[i+2]].vertices; area += (A.x*(B.y-C.y) + B.x*(C.y-A.y) + C.x*(A.y - B.y))/2; } return area; }
901190a5f7264a6f304b70accb818d33a368131a
1f68636232e489e19b7b937f75f04f01e833ce3f
/mfc_source/VS2015/Chapter08/Subclass/CMyEdit.h
4901e48ce19727c808e5ecb6e413df6e9cec7528
[]
no_license
SKARTEI/OOP_MFC_lecture
41de5922df2a607a688af8df5c79f7704cf7fb50
d18d2ed3cac8ebb7dff0c27be66cacfcc71dcc70
refs/heads/master
2023-04-11T19:37:19.817736
2021-05-07T03:30:54
2021-05-07T03:30:54
347,792,292
3
0
null
null
null
null
UTF-8
C++
false
false
234
h
#pragma once // CMyEdit class CMyEdit : public CWnd { DECLARE_DYNAMIC(CMyEdit) public: CMyEdit(); virtual ~CMyEdit(); protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); };
81ce2a7a9c32b4405006d88acef9af07f56b3da7
ba9322f7db02d797f6984298d892f74768193dcf
/live/src/model/DescribeLiveTopDomainsByFlowResult.cc
8630b08812142eb38fc0ed32d4f6b701da43eaa2
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
3,101
cc
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/live/model/DescribeLiveTopDomainsByFlowResult.h> #include <json/json.h> using namespace AlibabaCloud::Live; using namespace AlibabaCloud::Live::Model; DescribeLiveTopDomainsByFlowResult::DescribeLiveTopDomainsByFlowResult() : ServiceResult() {} DescribeLiveTopDomainsByFlowResult::DescribeLiveTopDomainsByFlowResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeLiveTopDomainsByFlowResult::~DescribeLiveTopDomainsByFlowResult() {} void DescribeLiveTopDomainsByFlowResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allTopDomains = value["TopDomains"]["TopDomain"]; for (auto value : allTopDomains) { TopDomain topDomainsObject; if(!value["DomainName"].isNull()) topDomainsObject.domainName = value["DomainName"].asString(); if(!value["Rank"].isNull()) topDomainsObject.rank = std::stol(value["Rank"].asString()); if(!value["TotalTraffic"].isNull()) topDomainsObject.totalTraffic = value["TotalTraffic"].asString(); if(!value["TrafficPercent"].isNull()) topDomainsObject.trafficPercent = value["TrafficPercent"].asString(); if(!value["MaxBps"].isNull()) topDomainsObject.maxBps = std::stol(value["MaxBps"].asString()); if(!value["MaxBpsTime"].isNull()) topDomainsObject.maxBpsTime = value["MaxBpsTime"].asString(); if(!value["TotalAccess"].isNull()) topDomainsObject.totalAccess = std::stol(value["TotalAccess"].asString()); topDomains_.push_back(topDomainsObject); } if(!value["StartTime"].isNull()) startTime_ = value["StartTime"].asString(); if(!value["EndTime"].isNull()) endTime_ = value["EndTime"].asString(); if(!value["DomainCount"].isNull()) domainCount_ = std::stol(value["DomainCount"].asString()); if(!value["DomainOnlineCount"].isNull()) domainOnlineCount_ = std::stol(value["DomainOnlineCount"].asString()); } std::vector<DescribeLiveTopDomainsByFlowResult::TopDomain> DescribeLiveTopDomainsByFlowResult::getTopDomains()const { return topDomains_; } std::string DescribeLiveTopDomainsByFlowResult::getEndTime()const { return endTime_; } long DescribeLiveTopDomainsByFlowResult::getDomainOnlineCount()const { return domainOnlineCount_; } std::string DescribeLiveTopDomainsByFlowResult::getStartTime()const { return startTime_; } long DescribeLiveTopDomainsByFlowResult::getDomainCount()const { return domainCount_; }
b0642cc51d13261c3013986080daab1b472abcc5
d6b4bdf418ae6ab89b721a79f198de812311c783
/teo/src/v20220106/model/CachePrefresh.cpp
43f7898ad8b506d0938006a11407e9a0dee351c0
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
2,959
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/teo/v20220106/model/CachePrefresh.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Teo::V20220106::Model; using namespace std; CachePrefresh::CachePrefresh() : m_switchHasBeenSet(false), m_percentHasBeenSet(false) { } CoreInternalOutcome CachePrefresh::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Switch") && !value["Switch"].IsNull()) { if (!value["Switch"].IsString()) { return CoreInternalOutcome(Core::Error("response `CachePrefresh.Switch` IsString=false incorrectly").SetRequestId(requestId)); } m_switch = string(value["Switch"].GetString()); m_switchHasBeenSet = true; } if (value.HasMember("Percent") && !value["Percent"].IsNull()) { if (!value["Percent"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `CachePrefresh.Percent` IsInt64=false incorrectly").SetRequestId(requestId)); } m_percent = value["Percent"].GetInt64(); m_percentHasBeenSet = true; } return CoreInternalOutcome(true); } void CachePrefresh::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_switchHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Switch"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_switch.c_str(), allocator).Move(), allocator); } if (m_percentHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Percent"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_percent, allocator); } } string CachePrefresh::GetSwitch() const { return m_switch; } void CachePrefresh::SetSwitch(const string& _switch) { m_switch = _switch; m_switchHasBeenSet = true; } bool CachePrefresh::SwitchHasBeenSet() const { return m_switchHasBeenSet; } int64_t CachePrefresh::GetPercent() const { return m_percent; } void CachePrefresh::SetPercent(const int64_t& _percent) { m_percent = _percent; m_percentHasBeenSet = true; } bool CachePrefresh::PercentHasBeenSet() const { return m_percentHasBeenSet; }
ae8b25592e7f522971ca52e4eedb875bae3e4c91
80efeac532826891989c039100cb4913083ae197
/Scripts/Tenny.cpp
581d10470e066e979d3df156212d10d6e6a12222
[]
no_license
lavelasco/Archon
582e5b1ddde7379eabc106cd68299c43fee0159d
287c8b25a0f347b24f069417ba174d76bb0cf449
refs/heads/master
2021-06-27T19:13:14.751151
2017-09-16T18:56:15
2017-09-16T18:56:15
82,961,292
0
0
null
null
null
null
UTF-8
C++
false
false
13,320
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Archon.h" #include "Tenny.h" #include "BossOwnedStates.h" #include "Kismet/KismetSystemLibrary.h" #include "DamagePlatform.h" #include "FireProjectile.h" // Sets default values ATenny::ATenny(const FObjectInitializer &ObjectInitializer) : Super(ObjectInitializer) { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; Health = 750.0f; //laugh vo Laugh = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Laugh VO")); Laugh->SetupAttachment(RootComponent); Laugh->bAutoActivate = false; //other dialogue TennyTaunt = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Tenny Taunt")); TennyTaunt->SetupAttachment(RootComponent); TennyTaunt->bAutoActivate = false; AntyTaunt = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Anty VO")); AntyTaunt->SetupAttachment(RootComponent); AntyTaunt->bAutoActivate = false; //TennyTaunt->OnAudioFinished.AddDynamic(this, &ATenny::AntyResponse); IsActive = false; IsDead = false; InPhase1 = true; InPhase2 = false; InPhase3 = false; //health marks that trigger state change Phase2Mark = 500.0f; Phase3Mark = 250.0f; //earthquake variables EQCastTime = 5.0f; EQParticle = ObjectInitializer.CreateDefaultSubobject<UParticleSystemComponent>(this, TEXT("Earthquake Particle")); EQParticle->SetupAttachment(RootComponent); EQParticle->bAutoActivate = false; EQVO = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Earthquake VO")); EQVO->SetupAttachment(RootComponent); EQVO->bAutoActivate = false; //ice nova variables IN_BaseDamage = 35.0f; IN_MinDamage = 10.0f; IN_InnerRadius = 100.0f; IN_OuterRadius = 500.0f; INCastTime = 3.0f; INParticle = ObjectInitializer.CreateDefaultSubobject<UParticleSystemComponent>(this, TEXT("Ice Nova Particle")); INParticle->SetupAttachment(RootComponent); INParticle->bAutoActivate = false; IceVO = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Ice Nova VO")); IceVO->SetupAttachment(RootComponent); IceVO->bAutoActivate = false; //help variables HelpVO = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Call for Help VO")); HelpVO->SetupAttachment(RootComponent); HelpVO->bAutoActivate = false; //death meteor variables canDM = true; MeteorReady = false; DM_Dmg = 90.0f; DMVO = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Death Meteor VO")); DMVO->SetupAttachment(RootComponent); DMVO->bAutoActivate = false; DMCooldownTime = 10.0f; //barrage variables NumFireBalls = 5; FireRate = 1.0f; BarrageVO = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Fire Barrage VO")); BarrageVO->SetupAttachment(RootComponent); BarrageVO->bAutoActivate = false; //initialize the sphere object on Tenny Shield = ObjectInitializer.CreateDefaultSubobject<USphereComponent>(this, TEXT("Shield")); Shield->SetupAttachment(RootComponent); ShieldActive = false; } // Called when the game starts or when spawned void ATenny::BeginPlay() { Super::BeginPlay(); //boss begins in 'Phase1' m_pCurrentState = Phase1::Instance(); //make sure the shield is disabled Shield->BodyInstance.SetResponseToAllChannels(ECR_Ignore); } // Called every frame void ATenny::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); if (m_pCurrentState) { m_pCurrentState->Execute(this); } } // Called to bind functionality to input void ATenny::SetupPlayerInputComponent(class UInputComponent* InputComponent) { Super::SetupPlayerInputComponent(InputComponent); } //************************************************************************************ //ABILITY ACTVATION //- activates the selected ability from an enum //************************************************************************************ void ATenny::ActivateAbility(EAbilitiesEnum ability) { switch (ability) { case EAbilitiesEnum::EARTHQUAKE: //play setup vo if (Laugh) Laugh->Play(); EQAssist(); UKismetSystemLibrary::K2_SetTimer(this, "Earthquake", EQCastTime, false); //Earthquake(); break; case EAbilitiesEnum::ICE_NOVA: //play setup vo if (IceVO) IceVO->Play(); IceAssist(); UKismetSystemLibrary::K2_SetTimer(this, "IceNova", INCastTime, false); //IceNova(); break; case EAbilitiesEnum::CALL_FOR_HELP: if (HelpVO) HelpVO->Play(); CallForHelp(); break; case EAbilitiesEnum::DEATH_METEOR: //activate only if Death Meteor isn't already active if (canDM) { if (Laugh) Laugh->Play(); DMAssist(); //UKismetSystemLibrary::K2_SetTimer(this, "DeathMeteor", 2.0f , false); DeathMeteor(); } //otherwise, use Fire Barrage else { if (BarrageVO) BarrageVO->Play(); UKismetSystemLibrary::K2_SetTimer(this, "FireBarrage", FBCastTime, false); } break; case EAbilitiesEnum::FIRE_BARRAGE: //play setup vo if (BarrageVO) BarrageVO->Play(); UKismetSystemLibrary::K2_SetTimer(this, "FireBarrage", FBCastTime, false); //FireBarrage(); break; } } #pragma region Phase 1 Abilities //************************************************************************************ //EARTHQUAKE ABILITY //************************************************************************************ void ATenny::Earthquake() { if (EQVO) EQVO->Play(); //if animation exists if (EarthquakeAnim != NULL) { //play animation GetMesh()->SetAnimation(EarthquakeAnim); GetMesh()->PlayAnimation(EarthquakeAnim, false); } //only called if a barricade is referenced if (Barricade != NULL) { //disable wall blocking separate platform Barricade->SetActorEnableCollision(false); Barricade->SetActorHiddenInGame(true); Barricade->SetActorTickEnabled(false); } //enable platform collision and events Platform->SetActorEnableCollision(true); Platform->SetActorTickEnabled(true); //enable platform to do damage Platform->SetDamageActive(true); //play particle EQParticle->Activate(); //deactivate earthquake after 5 seconds UKismetSystemLibrary::K2_SetTimer(this, "DeactivateEarthquake", 5.0f, false); } void ATenny::DeactivateEarthquake() { //turn off damage from platform Platform->SetDamageActive(false); } //************************************************************************************ //ICE NOVA ABILITY //-radial damage with falloff //************************************************************************************ void ATenny::IceNova() { //if (IceVO) IceVO->Play(); //if animation exists if (IceNovaAnim != NULL) { //play the animation GetMesh()->SetAnimation(IceNovaAnim); GetMesh()->PlayAnimation(IceNovaAnim, false); } //play particle effect INParticle->Activate(); //radial force that is blocked by line of sight or visual obstructions //and deals damage with falloff //UGameplayStatics::ApplyRadialDamageWithFalloff(GetWorld(), IN_BaseDamage, IN_MinDamage, GetActorLocation(), IN_InnerRadius, IN_OuterRadius, 1.0f, NULL, actorsToIgnore, NULL, NULL); UGameplayStatics::ApplyRadialDamage(GetWorld(), IN_BaseDamage, GetActorLocation(), IN_OuterRadius, NULL, actorsToIgnore, this, NULL, true); } #pragma endregion #pragma region Phase 2 Abilities //************************************************************************************ //CALL FOR HELP //-teleport Tenny to a second location //************************************************************************************ void ATenny::CallForHelp() { if (ShieldActive == false) { ShieldActive = true; //teleport Tenebris to second location Teleport(TeleportDestination); //activate shield //Shield->BodyInstance.SetResponseToChannel(ECC_Camera, ECR_Block); //Shield->BodyInstance.SetResponseToChannel(ECC_GameTraceChannel1, ECR_Block); ToggleShield(true); //spawn a set number of grunts (may not be needed due to level design changes) //deactivate shield when all grunts are destroyed } } void ATenny::ToggleShield(bool active) { if (active == true) { //have the shield block camera traces (like the arcane beam) Shield->BodyInstance.SetResponseToChannel(ECC_Camera, ECR_Block); //shield blocks projectiles Shield->BodyInstance.SetResponseToChannel(ECC_GameTraceChannel1, ECR_Block); //cannot be damaged bCanBeDamaged = false; } else { //do the reverse Shield->BodyInstance.SetResponseToChannel(ECC_Camera, ECR_Ignore); Shield->BodyInstance.SetResponseToChannel(ECC_GameTraceChannel1, ECR_Ignore); bCanBeDamaged = true; } } void ATenny::Teleport(AActor* destination) { SetActorLocation(destination->GetActorLocation(), false, nullptr, ETeleportType::None); } #pragma endregion #pragma region Phase 3 Abilities //************************************************************************************ //DEATH METEOR //************************************************************************************ void ATenny::DeathMeteor() { if (DMVO) DMVO->Play(); //if animation exists if (DeathMeteorAnim != NULL) { //play animation GetMesh()->SetAnimation(DeathMeteorAnim); GetMesh()->PlayAnimation(DeathMeteorAnim, false); } //activate shield ToggleShield(true); MeteorReady = true; //get references to 2 random obelisks and activate them ActivateObelisks(); //ActivateObelisks_Implementation(); //spawn meteor above boss platform //UKismetSystemLibrary::K2_SetTimer(this, "LaunchMeteor", DMCastTime, false); GetWorldTimerManager().SetTimer(UnusedHandle, this, &ATenny::LaunchMeteor, DMCastTime, false); } /* void ATenny::ActivateObelisks_Implementation() { //empty function call //triggers event for blueprint }*/ void ATenny::LaunchMeteor() { //debug GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Death")); if (MeteorReady) { //play explosion particle? //damage player for 90% of max health UGameplayStatics::ApplyDamage(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0), DM_Dmg, NULL, this, NULL); } ToggleShield(false); MeteorReady = false; canDM = false; ResetObelisks(); GetWorldTimerManager().SetTimer(UnusedHandle, this, &ATenny::EnableDM, DMCooldownTime, false); } void ATenny::EnableDM() { canDM = true; } //************************************************************************************ //FIRE BARRAGE //************************************************************************************ void ATenny::FireBarrage() { //spawn projectiles for a set duration for (int i = 0; i <= NumFireBalls; i++) { //UKismetSystemLibrary::K2_SetTimer(this, "SpawnFireball", FireRate, false); SpawnFireball(); } } void ATenny::SpawnFireball() { //if an animation exists if (BarrageAnim != NULL) { //play the animation GetMesh()->SetAnimation(BarrageAnim); GetMesh()->PlayAnimation(BarrageAnim, false); } //spawn params declaration //FActorSpawnParameters sp; //make sure the fireball always spawns //sp.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; //spawn a fireball //this->GetWorld()->SpawnActor<AFireProjectile>(FireballBlueprint, GetActorLocation(), GetActorRotation(), sp); this->FireSingle(); } #pragma endregion //************************************************************************************ //EVENT RECEIVE DAMAGE //- scripted version of the take damage event in blueprints //************************************************************************************ float ATenny::TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, class AActor* DamageCauser) { const float ActualDamage = Super::TakeDamage(Damage, DamageEvent, EventInstigator, DamageCauser); if ((ActualDamage > 0.f) && (DamageCauser == UGameplayStatics::GetPlayerCharacter(GetWorld(), 0))) { if(bCanBeDamaged == true) Health -= ActualDamage; if (Health <= 0.0f && IsDead == false) ChangeState(Death::Instance()); } return ActualDamage; } //************************************************************************************ //STATE MACHINE //************************************************************************************ void ATenny::ChangeState(BossState* pNewState) //takes an instance of a state as input { //call the exit function of state... m_pCurrentState->Exit(this); //change the current state to newly desire state m_pCurrentState = pNewState; //call the enter function of the new state m_pCurrentState->Enter(this); } //************************************************************************************ //OTHER DIALOGUE //************************************************************************************ void ATenny::Taunt() { TennyTaunt->Play(); UKismetSystemLibrary::K2_SetTimer(this, "AntyResponse", 4.0f, false); } void ATenny::AntyResponse() { AntyTaunt->Play(); }
426b2bcd02f93d1cbd170092c9fbc040db29ae17
bd2e6b8a7ce917d08e4ad1c835928d51afe1c43f
/util.cpp
047cfcf15ef979f2cda9c6b044acfa3508b85194
[]
no_license
offthebus/Keyshare
9491d8ad9994c2c3bc162440e27eff4aad8acc4c
fa0c4b8d3dd16d8e8acb3c7c58a12cce4450357e
refs/heads/master
2022-12-31T11:11:32.916276
2020-10-09T12:11:48
2020-10-09T12:11:48
299,288,794
0
0
null
null
null
null
UTF-8
C++
false
false
14,285
cpp
#include "stdafx.h" #include "util.h" namespace util { void printError() { // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; LPVOID lpDisplayBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); // Display the error message and exit the process lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + 40) * sizeof(TCHAR)); StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("SYSTEM ERROR: %d: %s"), dw, lpMsgBuf); printf("%s\n",(char*)lpDisplayBuf); LocalFree(lpMsgBuf); LocalFree(lpDisplayBuf); } struct LogBuffers { char fname[MAX_PATH]; char ext[_MAX_EXT]; ; char msg[1024]; char dbg[1024]; } g_buffers; //--------------------------------------------------------------------------- void Log::sysprint( const char* file, int line, DWORD err ) { char buf[128]; print(file,line,"SYSTEM ERROR: %s", strerror_s(buf,_countof(buf)) ); } //--------------------------------------------------------------------------- void Log::print( const char* file, int line, const char* fmt, ... ) { if ( !m_enabled ) return; _splitpath_s( file, NULL, 0, NULL, 0, g_buffers.fname, countof(g_buffers.fname), g_buffers.ext, countof(g_buffers.ext) ); va_list args; va_start( args, fmt ); vsprintf_s( g_buffers.msg, countof(g_buffers.msg), fmt, args ); if ( fpLog ) fprintf_s(fpLog, "%s%s(%d): %s\n", g_buffers.fname, g_buffers.ext, line, g_buffers.msg); // printf("%s%s(%d): %s\n", g_buffers.fname, g_buffers.ext, line, g_buffers.msg); if ( IsDebuggerPresent() ) { sprintf_s( g_buffers.dbg, countof(g_buffers.dbg), "\n**** %s%s(%d): %s\n", file, g_buffers.ext, line, g_buffers.msg ); OutputDebugString(g_buffers.dbg); } } //--------------------------------------------------------------------------- const char* strAllocCopy( const char* src, size_t* numCharsExclZero/*=0*/ ) { size_t len = strlen( src ); if ( numCharsExclZero ) *numCharsExclZero = len; char* ptr; ptr = new char[ len+1 ]; strcpy_s( ptr, len+1, src ); return (const char*)ptr; } //--------------------------------------------------------------------------- StringFile::StringFile( const char* filename ) : m_buf(0), m_len(0), m_filename(0) { char *full = _fullpath(NULL,filename,MAX_PATH+2); m_filename = strAllocCopy(filename); FILE* fp; fopen_s( &fp, full, "rb" ); if ( !fp ) { char buf[128]; strerror_s( buf, _countof(buf), errno ); LOG("ERROR: %s: %s", full, buf ); return; } fseek( fp, 0, SEEK_END ); size_t len = ftell( fp ); fseek( fp, 0, SEEK_SET ); if ( !len ) { LOG("ERROR: %s: zero length file", full ); fclose(fp); return; } m_buf = new char[ len + 1 ]; if ( len == fread( m_buf, 1, len, fp ) ) { m_len = len; m_buf[ len ] = 0; } else { char buf[128]; strerror_s( buf, _countof(buf), errno ); LOG("ERROR: %s: %s", full, buf ); delete[] m_buf; m_buf = 0; } fclose(fp); } typedef BOOL (WINAPI *LPFN_GLPI)( PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); // // Helper function to count set bits in the processor mask. DWORD CountSetBits(ULONG_PTR bitMask) { DWORD LSHIFT = sizeof(ULONG_PTR)*8-1; DWORD bitSetCount = 0; // ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT; // DWORD i; // // for (i = 0; i <= LSHIFT; ++i) // { // bitSetCount += ((bitMask & bitTest)?1:0); // bitTest/=2; // } // do { bitSetCount += bitMask&1; bitMask >>= 1; } while (LSHIFT--); return bitSetCount; } //--------------------------------------------------------------------------- void getProcessorInfo(DWORD& logical, DWORD& cores) { LPFN_GLPI glpi; BOOL done = FALSE; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL; DWORD returnLength = 0; DWORD logicalProcessorCount = 0; DWORD numaNodeCount = 0; DWORD processorCoreCount = 0; DWORD processorL1CacheCount = 0; DWORD processorL2CacheCount = 0; DWORD processorL3CacheCount = 0; DWORD processorPackageCount = 0; DWORD byteOffset = 0; PCACHE_DESCRIPTOR Cache; logical = cores = 0; glpi = (LPFN_GLPI) GetProcAddress( GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); if (NULL == glpi) { return; } while (!done) { DWORD rc = glpi(buffer, &returnLength); if (FALSE == rc) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if (buffer) free(buffer); buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc( returnLength); if (NULL == buffer) { return; } } else { return; } } else { done = TRUE; } } ptr = buffer; while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) { switch (ptr->Relationship) { case RelationNumaNode: // Non-NUMA systems report a single record of this type. numaNodeCount++; break; case RelationProcessorCore: processorCoreCount++; // A hyperthreaded core supplies more than one logical processor. logicalProcessorCount += CountSetBits(ptr->ProcessorMask); break; case RelationCache: // Cache data is in ptr->Cache, one CACHE_DESCRIPTOR structure for each cache. Cache = &ptr->Cache; if (Cache->Level == 1) { processorL1CacheCount++; } else if (Cache->Level == 2) { processorL2CacheCount++; } else if (Cache->Level == 3) { processorL3CacheCount++; } break; case RelationProcessorPackage: // Logical processors share a physical package. processorPackageCount++; break; default: break; } byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ptr++; } logical = logicalProcessorCount; cores = processorCoreCount; //_tprintf(TEXT("\nGetLogicalProcessorInformation results:\n")); //_tprintf(TEXT("Number of NUMA nodes: %d\n"), // numaNodeCount); //_tprintf(TEXT("Number of physical processor packages: %d\n"), // processorPackageCount); //_tprintf(TEXT("Number of processor cores: %d\n"), // processorCoreCount); //_tprintf(TEXT("Number of logical processors: %d\n"), // logicalProcessorCount); //_tprintf(TEXT("Number of processor L1/L2/L3 caches: %d/%d/%d\n"), // processorL1CacheCount, // processorL2CacheCount, // processorL3CacheCount); free(buffer); } //--------------------------------------------------------------------------- // ::VIRTUALKEYDICTIONARY //--------------------------------------------------------------------------- VirtualKeyDictionary::VirtualKeyDictionary() { m_dictionary.insert(DICTIONARY::value_type(VK_BACK,"Backspace")); m_dictionary.insert(DICTIONARY::value_type(VK_TAB,"Tab")); m_dictionary.insert(DICTIONARY::value_type(VK_CLEAR,"Clear")); m_dictionary.insert(DICTIONARY::value_type(VK_RETURN,"Return")); m_dictionary.insert(DICTIONARY::value_type(VK_SHIFT,"Shift")); m_dictionary.insert(DICTIONARY::value_type(VK_CONTROL,"Control")); m_dictionary.insert(DICTIONARY::value_type(VK_MENU,"Alt")); m_dictionary.insert(DICTIONARY::value_type(VK_PAUSE,"Pause")); m_dictionary.insert(DICTIONARY::value_type(VK_CAPITAL,"")); m_dictionary.insert(DICTIONARY::value_type(VK_ESCAPE,"Esc")); m_dictionary.insert(DICTIONARY::value_type(VK_SPACE,"Space")); m_dictionary.insert(DICTIONARY::value_type(VK_LEFT,"Left")); m_dictionary.insert(DICTIONARY::value_type(VK_UP,"Up")); m_dictionary.insert(DICTIONARY::value_type(VK_RIGHT,"Right")); m_dictionary.insert(DICTIONARY::value_type(VK_DOWN,"Down")); m_dictionary.insert(DICTIONARY::value_type(VK_PRINT,"Print")); m_dictionary.insert(DICTIONARY::value_type(VK_EXECUTE,"Execute")); m_dictionary.insert(DICTIONARY::value_type(VK_SNAPSHOT,"Snapshot")); m_dictionary.insert(DICTIONARY::value_type(VK_INSERT,"Insert")); m_dictionary.insert(DICTIONARY::value_type(VK_DELETE,"Delete")); m_dictionary.insert(DICTIONARY::value_type(VK_HELP,"Help")); m_dictionary.insert(DICTIONARY::value_type(VK_SELECT,"Select")); m_dictionary.insert(DICTIONARY::value_type(0x30,"0")); m_dictionary.insert(DICTIONARY::value_type(0x31,"1")); m_dictionary.insert(DICTIONARY::value_type(0x32,"2")); m_dictionary.insert(DICTIONARY::value_type(0x33,"3")); m_dictionary.insert(DICTIONARY::value_type(0x34,"4")); m_dictionary.insert(DICTIONARY::value_type(0x35,"5")); m_dictionary.insert(DICTIONARY::value_type(0x36,"6")); m_dictionary.insert(DICTIONARY::value_type(0x37,"7")); m_dictionary.insert(DICTIONARY::value_type(0x38,"8")); m_dictionary.insert(DICTIONARY::value_type(0x39,"9")); m_dictionary.insert(DICTIONARY::value_type(0x41,"A")); m_dictionary.insert(DICTIONARY::value_type(0x42,"B")); m_dictionary.insert(DICTIONARY::value_type(0x43,"C")); m_dictionary.insert(DICTIONARY::value_type(0x44,"D")); m_dictionary.insert(DICTIONARY::value_type(0x45,"E")); m_dictionary.insert(DICTIONARY::value_type(0x46,"F")); m_dictionary.insert(DICTIONARY::value_type(0x47,"G")); m_dictionary.insert(DICTIONARY::value_type(0x48,"H")); m_dictionary.insert(DICTIONARY::value_type(0x49,"I")); m_dictionary.insert(DICTIONARY::value_type(0x4A,"J")); m_dictionary.insert(DICTIONARY::value_type(0x4B,"K")); m_dictionary.insert(DICTIONARY::value_type(0x4C,"L")); m_dictionary.insert(DICTIONARY::value_type(0x4D,"M")); m_dictionary.insert(DICTIONARY::value_type(0x4E,"N")); m_dictionary.insert(DICTIONARY::value_type(0x4F,"O")); m_dictionary.insert(DICTIONARY::value_type(0x50,"P")); m_dictionary.insert(DICTIONARY::value_type(0x51,"Q")); m_dictionary.insert(DICTIONARY::value_type(0x52,"R")); m_dictionary.insert(DICTIONARY::value_type(0x53,"S")); m_dictionary.insert(DICTIONARY::value_type(0x54,"T")); m_dictionary.insert(DICTIONARY::value_type(0x55,"U")); m_dictionary.insert(DICTIONARY::value_type(0x56,"V")); m_dictionary.insert(DICTIONARY::value_type(0x57,"W")); m_dictionary.insert(DICTIONARY::value_type(0x58,"X")); m_dictionary.insert(DICTIONARY::value_type(0x59,"Y")); m_dictionary.insert(DICTIONARY::value_type(0x5A,"Z")); m_dictionary.insert(DICTIONARY::value_type(VK_LWIN,"Lwin")); m_dictionary.insert(DICTIONARY::value_type(VK_RWIN,"Rwin")); m_dictionary.insert(DICTIONARY::value_type(VK_APPS,"Apps")); m_dictionary.insert(DICTIONARY::value_type(VK_SLEEP,"Sleep")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD0,"Numpad0")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD1,"Numpad1")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD2,"Numpad2")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD3,"Numpad3")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD4,"Numpad4")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD5,"Numpad5")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD6,"Numpad6")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD7,"Numpad7")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD8,"Numpad8")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMPAD9,"Numpad9")); m_dictionary.insert(DICTIONARY::value_type(VK_MULTIPLY,"Multiply")); m_dictionary.insert(DICTIONARY::value_type(VK_ADD,"Add")); m_dictionary.insert(DICTIONARY::value_type(VK_SUBTRACT,"Subtract")); m_dictionary.insert(DICTIONARY::value_type(VK_DECIMAL,"Decimal")); m_dictionary.insert(DICTIONARY::value_type(VK_DIVIDE,"Divide")); m_dictionary.insert(DICTIONARY::value_type(VK_F1,"F1")); m_dictionary.insert(DICTIONARY::value_type(VK_F2,"F2")); m_dictionary.insert(DICTIONARY::value_type(VK_F3,"F3")); m_dictionary.insert(DICTIONARY::value_type(VK_F4,"F4")); m_dictionary.insert(DICTIONARY::value_type(VK_F5,"F5")); m_dictionary.insert(DICTIONARY::value_type(VK_F6,"F6")); m_dictionary.insert(DICTIONARY::value_type(VK_F7,"F7")); m_dictionary.insert(DICTIONARY::value_type(VK_F8,"F8")); m_dictionary.insert(DICTIONARY::value_type(VK_F9,"F9")); m_dictionary.insert(DICTIONARY::value_type(VK_F10,"F10")); m_dictionary.insert(DICTIONARY::value_type(VK_F11,"F11")); m_dictionary.insert(DICTIONARY::value_type(VK_F12,"F12")); m_dictionary.insert(DICTIONARY::value_type(VK_NUMLOCK,"Numlock")); m_dictionary.insert(DICTIONARY::value_type(VK_SCROLL,"Vscroll")); m_dictionary.insert(DICTIONARY::value_type(VK_LSHIFT,"Lshift")); m_dictionary.insert(DICTIONARY::value_type(VK_RSHIFT,"Rshift")); m_dictionary.insert(DICTIONARY::value_type(VK_LCONTROL,"Lcontrol")); m_dictionary.insert(DICTIONARY::value_type(VK_RCONTROL,"Rcontrol")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_1,"Oem_1")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_2,"Oem_2")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_3,"Oem_3")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_4,"Oem_4")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_5,"Oem_5")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_6,"Oem_6")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_7,"Oem_7")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_8,"Oem_8")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_102,"Oem_102")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_PLUS,"Oem_plus")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_COMMA,"Oem_comma")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_MINUS,"Oem_minus")); m_dictionary.insert(DICTIONARY::value_type(VK_OEM_PERIOD,"Oem_period")); } }; // namespace ut
056608ef6b5c02757e27f449bae04b3dd14bf070
cd726912664cea9c458ac8b609dd98bf33e3b9a0
/snippets/cpp/VS_Snippets_CLR_System/system.ConsoleKeyInfo.GetHashcode/cpp/hash.cpp
504f7fe19dfb74b0e2648f0f07c32fcf107d1556
[ "MIT", "CC-BY-4.0" ]
permissive
dotnet/dotnet-api-docs
b41fc7fa07aa4d54205df81284bae4f491286ec2
70e7abc4bcd692cb4fb6b4cbcb34bb517261dbaf
refs/heads/main
2023-09-04T07:16:44.908599
2023-09-01T21:46:11
2023-09-01T21:46:11
111,510,915
630
1,856
NOASSERTION
2023-09-14T21:45:33
2017-11-21T06:52:13
C#
UTF-8
C++
false
false
2,607
cpp
// ConsoleKeyInfo.GetHashCode.cpp : main project file. // <Snippet1> using namespace System; using namespace System::Text; String^ KeyCombination(ConsoleKeyInfo sourceCki); void main() { String^ k1 = "\nEnter a key ......... "; String^ key1 = ""; String^ hashCodeFmt = "The hash code for the {0} key is {1}."; String^ prompt = "Press the escape key (ESC) to quit, " + "or any other key to continue."; ConsoleKeyInfo cki1; int hashCode = 0; // The Console.TreatControlCAsInput property prevents this example from // ending if you press CTL+C, however all other operating system keys and // shortcuts, such as ALT+TAB or the Windows Logo key, are still in effect. // Console::TreatControlCAsInput = true; // Request that the user enter two key presses. A key press and any // combination shift, CTRL, and ALT modifier keys is permitted. do { Console::Write(k1); cki1 = Console::ReadKey(false); Console::WriteLine(); key1 = KeyCombination(cki1); hashCode = cki1.GetHashCode(); Console::WriteLine(hashCodeFmt, key1, hashCode); Console::WriteLine(prompt); cki1 = Console::ReadKey(true); } while (cki1.Key != ConsoleKey::Escape); // Note: This example requires the Escape (Esc) key. } // The KeyCombination() method creates a string that specifies what // key and what combination of shift, CTRL, and ALT modifier keys // were pressed simultaneously. static String^ KeyCombination(ConsoleKeyInfo sourceCki) { StringBuilder^ sb = gcnew StringBuilder(); sb->Length = 0; String^ keyCombo; if (sourceCki.Modifiers != (ConsoleModifiers) 0) { if ((sourceCki.Modifiers & ConsoleModifiers::Alt) != (ConsoleModifiers) 0) sb->Append("ALT+"); if ((sourceCki.Modifiers & ConsoleModifiers::Shift) != (ConsoleModifiers) 0) sb->Append("SHIFT+"); if ((sourceCki.Modifiers & ConsoleModifiers::Control) != (ConsoleModifiers) 0) sb->Append("CTL+"); } sb->Append(sourceCki.Key.ToString()); keyCombo = sb->ToString(); return keyCombo; } /* This example produces results similar to the following output: Enter a key ......... a The hash code for the A key is 97. Press the escape key (ESC) to quit, or any other key to continue. Enter a key ......... S The hash code for the SHIFT+S key is 83. Press the escape key (ESC) to quit, or any other key to continue. Enter a key ......... The hash code for the ALT+SHIFT+CTL+J key is 7. Press the escape key (ESC) to quit, or any other key to continue. */ // </Snippet1>
3f0122afd4440afb385aa2c3f152997f15afc8bc
4cfb925767003ede88b3314d744a1df9b329192b
/include/oglplus/enums/ext/compat_prim_type.ipp
0505d8a845cadb67b38c87792f5f3e7bb436d846
[ "BSL-1.0" ]
permissive
detunized/oglplus
4ddd7617fd38f47d7069834128bd49e16a79233c
184c9e2796d100f73800b924de1b9f8ba0b0fa62
refs/heads/master
2021-01-17T11:09:25.094741
2013-03-19T17:58:30
2013-03-19T17:58:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
752
ipp
/* * .file oglplus/enums/ext/compat_prim_type.ipp * * Automatically generated header file. DO NOT modify manually, * edit 'source/enums/ext/compat_prim_type.txt' instead. * * Copyright 2010-2013 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) */ #if OGLPLUS_DOCUMENTATION_ONLY /// POINTS Points, /// LINE_STRIP LineStrip, /// LINE_LOOP LineLoop, /// LINES Lines, /// TRIANGLE_STRIP TriangleStrip, /// TRIANGLE_FAN TriangleFan, /// TRIANGLES Triangles, /// QUADS Quads, /// QUAD_STRIP QuadStrip, /// POLYGON Polygon #else // !OGLPLUS_DOCUMENTATION_ONLY #include <oglplus/enums/ext/compat_prim_type_def.ipp> #endif
19e46114357156dd9f19323f0141fb76f22477ca
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5634947029139456_0/C++/rathi062/charging.cpp
e96c6940741e24b37a878ffd5b2f0fd47e3b05ef
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,814
cpp
#include<iostream> #include<list> #include<string> #include<cstring> #include<sstream> #include<cctype> #include<string.h> #include<algorithm> #include<cmath> #include<stack> #include<fstream> #include<cstdlib> #include<vector> #include<map> #include<set> #include<utility> #include<iomanip> #include<queue> using namespace std; #define INF (1<<29) #define SET(a) memset(a,-1,sizeof(a)) #define ALL(a) a.begin(),a.end() #define CLR(a) memset(a,0,sizeof(a)) #define FILL(a,v) memset(a,v,sizeof(a)) #define PB push_back #define FOR(i,n) for(int i = 0;i<n;i++) #define PI acos(-1.0) #define EPS 1e-9 #define MP(a,b) make_pair(a,b) #define min3(a,b,c) min(a,min(b,c)) #define max3(a,b,c) max(a,max(b,c)) #define READ freopen("input.txt", "r", stdin) #define WRITE freopen("output.txt", "w", stdout) #define LL long long #define MX 151 #define MOD 1000002013 #define p(x) printf("%d",x) #define inp(x) scanf("%d",&x) #define inpd(x) scanf("%lf",&x) #define inpll(x) scanf("%lld",&x) #define getcx getchar_unlocked /*inline void inp( int &n ) { n=0; int ch=getcx();int sign=1; while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getcx();} while( ch >= '0' && ch <= '9' ) n = (n<<3)+(n<<1) + ch-'0', ch=getcx(); n=n*sign; }*/ using namespace std; int cnt,n,l; string s[MX],rq[MX],ns[MX]; bool chng[50]; void flip(int j,int k) { cnt=0; for(int i=0;i<l;i++) { if(s[j][i]!=rq[k][i]) { cnt++; chng[i]=1; } } } char swp(char c) { if(c=='0') return '1'; else return '0'; } void assign(void) { for(int i=0;i<n;i++) { for(int j=0;j<l;j++) { if(chng[j]) ns[i][j]=swp(s[i][j]); else ns[i][j]=s[i][j]; } } } bool match() { for(int i=0;i<n;i++) { for(int j=0;j<l;j++) { if(ns[i][j]!=rq[i][j]) return 0; } } return 1; } int main() { int t=0; inp(t); for(int i =1;i<=t;i++) { cout<<"Case #"<<i<<": "; inp(n); inp(l); for(int j=0;j<n;j++) { cin>>s[j]; ns[j]=s[j]; } for(int j=0;j<n;j++) { cin>>rq[j]; } sort(rq,rq+n); int mini = 50; for(int j=0;j<n;j++) { for(int k=0;k<n;k++) { for(int p=0;p<l;p++) chng[p]=0; flip(j,k); if(cnt<mini) { assign(); sort(ns,ns+n); if(match()) mini = cnt; } } } if(mini!=50) cout<<mini<<endl; else cout<<"NOT POSSIBLE\n"; } return 0; }
1ef6c0f2b1c0095770d23e91f8f38210126b6c72
d9e969f958bfd04eaeaf1b3f51cd1bca939fcac5
/957.n-天后的牢房.cpp
7a155350f0476190d790ba07f79cca21f6883787
[]
no_license
SilverHL/Leetcode
7a1682f0157e7e84779be4a9c100be5d0a9602e3
deb89252a64e81341a53891058bc3ce58b17b50b
refs/heads/master
2022-05-11T15:42:56.560481
2022-05-02T07:16:05
2022-05-02T07:16:05
196,130,078
0
0
null
null
null
null
UTF-8
C++
false
false
562
cpp
#include <vector> using namespace std; /* * @lc app=leetcode.cn id=957 lang=cpp * * [957] N 天后的牢房 */ // @lc code=start class Solution { public: vector<int> prisonAfterNDays(vector<int>& cells, int N) { int k = N % 14; if (!k) k = 14; vector<int> tmp(8, 0); while (k--) { vector<int> tmp(cells); for (int j = 1; j < 7; ++j) { cells[j] = tmp[j-1] ^ !tmp[j+1]; } cells[0] = cells[7] = 0; } return cells; } }; // @lc code=end
1a61c001159649e0872ef5cbdf1be100b813488c
179d595010292190223b7aaf2ea3a39ab37ef52b
/DP/other_imp_problems/targetSum.cpp
334058f6b76357abbafdc7cdad9ff85131d79141
[]
no_license
dreamJarvis/Problem_Solving
d40359170ddfab456a62f9c4c2a55c31c6e2bdfb
4db08f76e26e9f61d9aa0c0382629d3499dc337f
refs/heads/master
2023-02-05T03:45:05.989338
2021-01-01T21:54:42
2021-01-01T21:54:42
174,203,367
0
1
null
2020-10-01T09:21:13
2019-03-06T19:01:05
C++
UTF-8
C++
false
false
2,110
cpp
// leetcode 494. Target Sum #include <bits/stdc++.h> using namespace std; // to find if by assinging '+', '-' we can get the required sum // recursive method // tc : ~ O(2^n) int targetSum(vector<int> &arr, int sum, int requiredSum, int index){ if(index == arr.size()){ if(sum == requiredSum){ return 1; } return 0; } int element = arr[index]; int left = targetSum(arr, sum+arr[index], requiredSum, index+1); int right = targetSum(arr, sum-arr[index], requiredSum, index+1); return (left + right); } int findTargetSumWays(vector<int>& nums, int S) { return targetSum(nums, 0, S, 0); } // ------------------- memoisation -------------------------- // int targetSumMemoUTIL(vector<int> &arr, int sum, int requiredSum, int index, unordered_map<string, int> &memo){ string key = to_string(index) + "_" + to_string(sum); // key if(index == arr.size()){ if(sum == requiredSum){ return 1; } return 0; } if(memo.count(key)) return memo[key]; int element = arr[index]; int left = targetSumMemoUTIL(arr, sum+arr[index], requiredSum, index+1, memo); int right = targetSumMemoUTIL(arr, sum-arr[index], requiredSum, index+1, memo); memo[key] = left+right; return (left + right); } int targetSumMemo(vector<int>&arr, int S){ unordered_map<string, int> memo; return targetSumMemoUTIL(arr, 0, S, 0, memo); } // to find the no. of ways to achieve the target sum // int count = 0; int findTargetSumWays(vector<int>& nums, int S, int k, int d, int index) { // base condition if(index > nums.size()) return 0; if(S - d == k) return 1; int sum=0, count = 0; for(int i = index; i < nums.size();i++){ sum += arr[i]; count = findTargetSumWays(nums, S, k, sum, i+1); } return count; } // Driver function int main(){ vector<int> arr({1, 1, 1, 1}); int k = 3; int sum = 0; for(auto item:arr) sum+=item; cout << findTargetSumWays(arr, sum, k, 0, 0) << endl; return 0; }
cdb8688ab54c4b8f7878b4f2b6f32db4be9baa7b
76e652e2ef2c5d57f8115eb4939e1fb460255549
/Source/NetworkAbility/Private/ActionCharacterBase.cpp
74a8219bcae181f6ba4625a1e5f88eb73bb9bdec
[]
no_license
alcachofalaruz/NetworkAbilityKit
00fc5a565cb9a73ec0b7a6e2a84ee11ce4663ada
7a90a74a1dc27f617bc50bb27e9c085b5df5f7c4
refs/heads/master
2023-06-08T09:22:44.172313
2021-06-30T18:06:07
2021-06-30T18:06:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,347
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ActionCharacterBase.h" #include "GameFramework/SpringArmComponent.h" #include "Camera/CameraComponent.h" #include "Components/ArrowComponent.h" #include "Gameframework/Controller.h" #include "NetworkAbilityKit/Public/AttributeComp.h" #include "NetworkAbilityKit/Public/AbilitySetComp.h" #include "NetworkAbilityKit/Public/AttrSet_Default.h" #include "ActionControllerBase.h" // Sets default values AActionCharacterBase::AActionCharacterBase() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm")); SpringArm->SetupAttachment(RootComponent); SpringArm->bUsePawnControlRotation = true; CamComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp")); CamComp->SetupAttachment(SpringArm, USpringArmComponent::SocketName); } void AActionCharacterBase::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); // This actually takes care of replicating the Variable DOREPLIFETIME(AActionCharacterBase, AbilityComp); DOREPLIFETIME(AActionCharacterBase, AttributeComp); } // Called when the game starts or when spawned void AActionCharacterBase::BeginPlay() { Super::BeginPlay(); } void AActionCharacterBase::PossessedBy(AController* NewController) { Super::PossessedBy(NewController); } // Called every frame void AActionCharacterBase::Tick(float DeltaTime) { Super::Tick(DeltaTime); } // Called to bind functionality to input void AActionCharacterBase::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } void AActionCharacterBase::InitializePlayer() { UE_LOG(LogTemp, Log, TEXT("----Player Initializing----")); if (HasAuthority()) { AttributeComp = FindComponentByClass<UAttributeComp>(); if (!AttributeComp) { UE_LOG(LogTemp, Log, TEXT("----Attribute Comp Not Found, ABORTING----")); return; } AttributeComp->SetActive(true); AttributeComp->InitializeAttributeComp(); AbilityComp = FindComponentByClass<UAbilitySetComp>(); if (!AbilityComp) { UE_LOG(LogTemp, Log, TEXT("----Ability Comp Not Found, ABORTING----")); return; } AbilityComp->SetActive(true); AbilityComp->InitializeAbilitySet(); //if (!StatsHUDWidget) //{ // UE_LOG(LogTemp, Log, TEXT("----Null StatsHUDWidget, ABORTING----")); // return; //} } } float AActionCharacterBase::TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) { if (HasAuthority()) { return 0.0f; } float ActualDamage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser); UAttributeComp* AttrComp = this->FindComponentByClass<UAttributeComp>(); if (!AttrComp) { UE_LOG(LogTemp, Log, TEXT("No AttrComp, ABOTRING")); return 0.0f; } AAttrSet_Default* DefaultAttribute = Cast<AAttrSet_Default>(AttrComp->AttributePreset); if (!DefaultAttribute) { UE_LOG(LogTemp, Log, TEXT("No Default Attr Set, ABORTING")); return 0.0f; } DefaultAttribute->Health -= ActualDamage; return ActualDamage; }
9493a4a381392c1b667e8d3d533d537421fc84a4
d38390276215ea79fe7a3c4b862d242dfabdd57b
/project3/echo_server.cpp
2ee66354f3554658a356be01ecb0477786047c05
[]
no_license
TommyWu-fdgkhdkgh/nctu_network_programming
f065662f118914c1e129aaa801298de5c8dc2454
122c0a33b4197b33947529cef49e04e933ba70a3
refs/heads/master
2022-07-13T13:33:25.338793
2019-04-06T08:29:04
2019-04-06T08:29:04
179,807,619
1
0
null
null
null
null
UTF-8
C++
false
false
13,578
cpp
#include <array> #include <boost/asio.hpp> #include <boost/process.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <cstdlib> #include <iostream> #include <memory> #include <utility> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> namespace bp = boost::process; using namespace std; using namespace boost::asio; extern char **environ; //https://stackoverflow.com/questions/717239/io-service-why-and-how-is-it-used //io_service:他先用select去檢查每個fd是不是readable or writable 。 檢查完fd後,開始遍尋所有fd。io_service會幫我們維護所有fd的意義(read ? write?),readable的fd就call read function,writable的fd就call write 所需要的function。 //當沒有新的call back出現的時候,這個io_service就會自己消失。 io_service global_io_service; //Q:這串程式碼是怎麼做到每個client的字串互不影響的? //A:每個session都有自己的buffer //argv要填,不然結果會出不來 //Q:該怎麼對付會延遲輸入的cgi?? //這樣勢必需要一個async的機制 //我發覺就算我發展了一個async的機制,可能還是沒辦法,因為會不停的等到'\0'的出現 struct OtherWork { using clock = std::chrono::high_resolution_clock; OtherWork(boost::asio::io_context& io) : timer(io) { } void start() { timer.expires_at(clock::time_point::max()); loop(); } void stop() { timer.expires_at(clock::time_point::min()); } private: void loop() { if (timer.expires_at() == clock::time_point::min()) { std::cout << "(done)" << std::endl; return; } timer.expires_from_now(std::chrono::milliseconds(2793)); timer.async_wait([=](boost::system::error_code ec) { if (!ec) { std::cout << "(other work in progress)" << std::endl; start(); } else { std::cout << "(" << ec.message() << ")" << std::endl; } }); } boost::asio::high_resolution_timer timer; }; class EchoSession : public enable_shared_from_this<EchoSession> { private: enum { max_length = 1000 }; //for socket connected with client ip::tcp::socket _socket; array<char, max_length> _data; boost::asio::signal_set signal_; int number; /* * index 0 : cgi_name * index 1~3 : parameters for first server * */ char parameters[16][50]; char temp_header[500]; /*char cgi_name[30]; char h0[30],p0[30],f0[30]; char h1[30],p1[30],f1[30]; char h2[30],p2[30],f2[30]; char h3[30],p3[30],f3[30]; char h4[30],p4[30],f4[30]; */ int header_flag; //1 send http status header(ex:200 OK) //0 don't send anything public: //EchoSession(ip::tcp::socket socket) : _socket(move(socket)){} EchoSession(ip::tcp::socket socket) : _socket(move(socket)), signal_(global_io_service,SIGCHLD){ wait_for_signal(); } //在這個echo server裡, void start() { int number=0; //紀錄是不是第一筆送出(第一筆送出需要多加一個header) header_flag=1; //第一個讀到的是client傳來的request,寫個程式來parse header do_read_with_head_from_client(); } private: void wait_for_signal() { signal_.async_wait( [this](boost::system::error_code /*ec*/, int /*signo*/) { // Only the parent process should check for this signal. We can // determine whether we are in the parent by checking if the acceptor // is still open. //if (acceptor_.is_open()) //{ // Reap completed child processes so that we don't end up with // zombies. int status = 0; while (waitpid(-1, &status, WNOHANG) > 0) {} wait_for_signal(); //} }); } void fork_and_exe_cgi(){ //turn _socket to fd //Q:socket fd 是不是該關掉? int socketfd = _socket.native_handle(); printf("parameters[0] %s\n",parameters[0]); char p1[50]; memcpy(p1,parameters[0],strlen(parameters[0])+1); printf("p1:%s\n",p1); global_io_service.notify_fork(boost::asio::io_context::fork_prepare); if (fork() == 0) { //child global_io_service.notify_fork(boost::asio::io_context::fork_child); auto self(shared_from_this()); //set env that cgi need set_env(); //send OK head array<char,20> okhead= {"HTTP/1.1 200 OK\r\n\0"}; int index=0; while(1){ _data[index]=okhead[index]; if(okhead[index]!='\0'){ index++; }else{ break; } } //_socket.async_send( _socket.async_write_some( buffer(_data, index), [this,self](boost::system::error_code ec, std::size_t length){ }); //dup stdout to socketfd dup2(socketfd,1); //dup2(socketfd,2); char *argvs[2]; char p1[50]; //執行檔名稱後面多一個空格就會炸開 //memcpy(p1,"./panel.cgi \x00",strlen("./panel.cgi \x00")); memcpy(p1,parameters[0],strlen(parameters[0])+1); argvs[0]=p1; argvs[1]=NULL; execve(argvs[0],argvs,environ); } else { //parent global_io_service.notify_fork(boost::asio::io_context::fork_parent); } } void set_env(){ /* *REQUEST_METHOD:GET *REQUEST_URI:/console.cgi?tid=222 *QUERY_STRING:tid=222&dd=111 *SERVER_PROTOCOL:HTTP/1.1 *HTTP_HOST:npbsd3.cs.nctu.edu.tw:55555 *SERVER_ADDR:140.113.235.223 *SERVER_PORT:55555 *REMOTE_ADDR:client端的host名稱 *REMOTE_PORT:client端的port */ int index=0; int tindex=0; int state; int flag=0; char tempstr[500]; //REQUEST_METHOD while(1){ if(_data[index]!=' '){ tempstr[index]=_data[index]; }else break; index++; } tempstr[index]='\x00'; setenv("REQUEST_METHOD",tempstr,1); printf("REQUEST_METHOD:%s\n",tempstr); //REQUEST_URI index=0; state=0; tindex=0; while(1){ if(state==0 && _data[index]=='/'){ state=1; } if(state==1 && _data[index]==' '){ break; } if(state==1){ tempstr[tindex++]=_data[index]; } index++; } tempstr[tindex]='\x00'; setenv("REQUEST_URI",tempstr,1); printf("REQUEST_URI:%s\n",tempstr); //QUERY_STRING index=0; state=0; tindex=0; flag=0; while(1){ if(state==0 && _data[index]=='?'){ state=1; index++; } if(state==0 && _data[index]=='\n'){ flag=1; break; } if(state==1 && _data[index]==' '){ break; } if(state==1){ tempstr[tindex++]=_data[index]; } index++; } tempstr[tindex]='\x00'; if(flag==1){ printf("no query_string!\n"); }else{ setenv("QUERY_STRING",tempstr,1); printf("QUERY_STRING:%s\n",tempstr); } //SERVER_PROTOCOL:HTTP/1.1 index=0; tindex=0; state=0; while(1){ if(state==0 && _data[index]==' '){ state++; index++; continue; } if(state==1 && _data[index]==' '){ state++; index++; continue; } if(state==2 && _data[index]==' '){ break; } if(state==2){ tempstr[tindex++]=_data[index]; } index++; } tempstr[tindex]='\x00'; setenv("SERVER_PROTOCOL",tempstr,1); printf("SERVER_PROTOCOL:%s\n",tempstr); //HTTP_HOST:npbsd3.cs.nctu.edu.tw:55555 index=0; tindex=0; state=0; while(1){ if(state==0 && _data[index]=='\n'){ state++; index++; } if(state==1 && _data[index]==' '){ state++; index++; } if(state==2 && _data[index]=='\n'){ break; } if(state==2){ tempstr[tindex++]=_data[index]; } index++; } tempstr[tindex]='\x00'; setenv("HTTP_HOST",tempstr,1); printf("HTTP_HOST:%s\n",tempstr); //SERVER_ADDR:140.113.235.223 //http://lang.idv.tw/doku.php/program/c/linux%E7%B7%A8%E7%A8%8B%E7%8D%B2%E5%8F%96%E6%9C%AC%E6%A9%9Fip%E5%9C%B0%E5%9D%80 //https://blog.csdn.net/huang_xw/article/details/8502895 ip::tcp::endpoint local_e = _socket.local_endpoint(); string temp = local_e.address().to_string(); int len = temp.length(); for(index=0;index<len;index++){ tempstr[index]=temp[index]; } tempstr[index]='\x00'; setenv("SERVER_ADDR",tempstr,1); printf("SERVER_ADDR:%s\n",tempstr); //SERVER_PORT:55555 index=0; tindex=0; state=0; while(1){ if(state==0 && _data[index]=='\n'){ state++; index++; } if(state==1 && _data[index]==' '){ state++; index++; } if(state==2 && _data[index]==':'){ state++; index++; } if(state==3 && _data[index]=='\n'){ break; } if(state==3){ tempstr[tindex++]=_data[index]; } index++; } tempstr[tindex]='\x00'; setenv("SERVER_PORT",tempstr,1); printf("SERVER_PORT:%s\n",tempstr); //REMOTE_ADDR:client端的host名稱 ip::tcp::endpoint remote_e = _socket.remote_endpoint(); temp = remote_e.address().to_string(); len = temp.length(); for(index=0;index<len;index++){ tempstr[index]=temp[index]; } tempstr[index]='\x00'; setenv("REMOTE_ADDR",tempstr,1); printf("REMOTE_ADDR:%s\n",tempstr); //REMOTE_PORT:client端的port short remote_port = remote_e.port(); sprintf(tempstr,"%hu",&remote_port); setenv("REMOTE_PORT",tempstr,1); printf("REMOTE_PORT:%s\n",tempstr); } void parse_header(){ //initialize parameters for(int i=0;i<16;i++){ for(int j=0;j<50;j++){ parameters[i][j]='\x00'; } } //parse header int index=0; while(1){ temp_header[index]=_data[index]; if(_data[index]=='\n'){ temp_header[index]='\x00'; break; } index++; } //cgi_name int state=0; int tindex=0; index=0; parameters[0][tindex++]='.'; while(1){ if(temp_header[index]=='/'){ state=1; }else if(state==1 && (temp_header[index]=='?' || temp_header[index]==' ')){ break; } if(state==1){ parameters[0][tindex++]=temp_header[index]; } index++; } parameters[0][tindex]='\x00'; if(temp_header[index-1]==' '){ //沒有任何參數,跳離function return; } ///console.cgi?h0=nplinux1.cs.nctu.edu.tw&p0=55555&f0=1.txt&h1=&p1=&f1=&h2=&p2=&f2=&h3=&p3=&f3=&h4=&p4=&f4= HTTP/1.1 //hn,pn,fn state=0; tindex=0; for(int i=0;i<15;i++){ printf("hi head \n"); state=0; tindex=0; while(1){ if(temp_header[index]=='='){ state=1; index++; } if(temp_header[index]=='&' || temp_header[index]==' '){ index++; break; } if(state==1){ parameters[i+1][tindex++] = temp_header[index]; } index++; } if(temp_header[index-1]==' '){ //no more parameters break; } parameters[i+1][tindex]='\x00'; } for(int i=0;i<16;i++){ printf("parameters[%d] %s\n",i,parameters[i]); } printf("\n\nnumber:%d\n",number++); printf("\n\n header now %s\n\n",temp_header); printf("\n\n cgi name %s \n\n",parameters[0]); } void do_read_with_head_from_client(){ //讀取來自客戶端的訊息 auto self(shared_from_this()); _socket.async_read_some( buffer(_data, max_length), [this, self](boost::system::error_code ec, std::size_t length) { //if (!ec) do_write(length); cout<<"_data:"<<endl; for(int i=0;;i++){ if(_data[i]!='\0'){ printf("%c",_data[i]); }else{ printf("%c",_data[i]); break; } } parse_header(); fork_and_exe_cgi(); }); } }; class EchoServer { private: ip::tcp::acceptor _acceptor; ip::tcp::socket _socket; public: EchoServer(short port) //這裡會把接受新連線用的socket fd丟到io_service裡面維護(io_service裡面的select) : _acceptor(global_io_service, ip::tcp::endpoint(ip::tcp::v4(), port)), _socket(global_io_service) //connection_manager() { //執行第一個異步的wait for accept do_accept(); } private: void do_accept() { //這裡會把接受新連線用的socket fd丟到io_service裡面維護(io_service裡面的selecti) //並且也把call back function也放到io_service裡 _acceptor.async_accept(_socket, [this](boost::system::error_code ec) { //拿到這個socket後,開始利用這個socket進行連線 //因為server這個object不會再用到socket,所以用move來完全的轉移對於socket這個物件的權限 //可以研究一下move的機制 if (!ec) make_shared<EchoSession>(move(_socket))->start(); do_accept(); }); } }; int main(int argc, char* const argv[]) { if (argc != 2) { std::cerr << "Usage:" << argv[0] << " [port]" << endl; return 1; } try { short port = atoi(argv[1]); EchoServer server(port); global_io_service.run(); //cgi_io_service.run(); } catch (exception& e) { cerr << "Exception: " << e.what() << "\n"; } return 0; }
57e53d37435bdb345ceab8ab5276c7f63a7f4ed0
67476073317c1ee6505e3193037596d99c29973d
/atCoder/begginer145/B/b.cpp
65a3cd56163130b6c001854b83c537d967f7fdba
[]
no_license
gabriellerosa/Codigos-Maratona
67d68ede4d2c85991323453b0f0166d86e01d27a
091225d258534b716fe3baa70e67d1fce68aa026
refs/heads/master
2023-01-19T10:39:56.153642
2020-11-24T21:24:28
2020-11-24T21:24:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
597
cpp
#include <iostream> using namespace std; int n; string s; int main(){ string s1, s2; cin >> n >> s; s1 = s.substr(0,n/2); s2 = s.substr(n/2,n); if(s1 == s2) cout << "Yes" << endl; else cout << "No" << endl; //cout << s1 << " " << s2; /*if(n % 2 != 0){ cout << "NO\n"; }else{ int k = n/2; for(int i = 0; i < (n/2); i++){ if(s[i] != s[k]){ cout << "NO\n"; break; } k++; } cout << "YES\n"; } */ return 0; }
5e17b88bfac6b51db8a2dc30efc3aaafc8f7fb8e
7428b919f4df7923b5eca00a6cb1e2064f5e4320
/pat1083. List Grades.cpp
544ab63cec47cc468d6185c07c58d86906c18e24
[]
no_license
mascure/PAT
44eca3ec8b99894d13a128b0199848e24fe39aa9
ed58818f66d696851d06cd3aaaa55b4bb2db76ab
refs/heads/master
2020-05-18T11:48:03.769927
2014-08-25T07:49:58
2014-08-25T07:49:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
850
cpp
#include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<iostream> #include<algorithm> #include<memory> #include<map> #include<unordered_map> #include<queue> #include <sstream> #include <set> using namespace std; const int MAX_N=105; typedef long long ll; typedef pair<ll,ll> P; struct Student{ string name,ID; int grade; }s[MAX_N]; int N; int g1,g2; bool cmp(Student a,Student b){ return a.grade>b.grade; } void solve(){ sort(s,s+N,cmp); int end=N-1,start=0; while(end>=0&&s[end].grade<g1)end--; while(start<N&&s[start].grade>g2)start++; if(start>end)cout<<"NONE"<<endl; else{ for(int i=start;i<=end;i++){ cout<<s[i].name<<" "<<s[i].ID<<endl; } } } int main(){ while(scanf("%d",&N)!=EOF){ for(int i=0;i<N;i++){ cin>>s[i].name>>s[i].ID>>s[i].grade; } cin>>g1>>g2; if(g1>g2)swap(g1,g2); solve(); } }
1e66d822b8fc81e7b3f4cdabcb9f2bc3eedadeac
c474c200021d5f06fc382f2f2e672bd45f2262fc
/non_windows/codeEssential/source/chapter1/chap1/ch1.h
06af637fe8f5f6191a0a1c358bfbf84dc060652a
[]
no_license
philipdongfei/EssentialCpp
5914ba4d1dfceb5f991014c406cac277162ec5e2
c1275e7b8e7b51cd1f56d83fb4133138a3c10a2f
refs/heads/master
2020-04-22T09:15:08.938108
2019-02-12T06:43:22
2019-02-12T06:43:22
170,265,680
3
0
null
null
null
null
UTF-8
C++
false
false
3,344
h
/************************************************** * Essential C++ -- Stanley Lippman * Addison-Wesley * ISBN 0-201-48518-4 * homepage: www.objectwrite.com * email: [email protected] *************************************************/ #ifndef CH1_H_ #define CH1_H_ #include <vector> #include <iostream> #include <string> using namespace std; // external type definitions typedef const vector<unsigned int>* (*pfunc)(int); typedef const vector<unsigned int>* pvec; enum num_sequence { ns_unk, ns_fib, ns_pell, ns_lucas, ns_tri, ns_sq, ns_pent, ns_cnt = 6, ns_wrong_msg = 4 }; struct user_profile { string name; int guesses; int correct; int level; num_sequence cur_seq; pvec cur_seq_vec; int pos; }; // external structures extern pfunc gen_elems[]; extern const char *name_seq[]; extern const char *wrong_msg[]; extern int level_size[]; extern bool greet_user( user_profile* ); extern void play_game( user_profile* ); extern void display_statistics( user_profile* ); extern pvec Fibonacci_gen_elems( int ); extern pvec Pell_gen_elems( int ); extern pvec Lucas_gen_elems( int ); extern pvec Triangular_gen_elems( int ); extern pvec Square_gen_elems( int ); extern pvec Pentagonal_gen_elems( int ); extern void set_seq( user_profile*, int ); extern const char* seq_id( user_profile* ); extern void init_user( user_profile *puser, const string& nm, int level ); extern bool correct_guess( user_profile *puser, int guess ); inline void set_seq_vec( user_profile *pu, pvec p ) { pu->cur_seq_vec = p; } inline pvec seq_vec( user_profile *pu ) { return pu->cur_seq_vec; } inline string user_name( user_profile *puser ) { return puser->name; } inline num_sequence seq( user_profile *puser ) { return puser->cur_seq; } inline void bump_guess( user_profile *puser ) { ++puser->guesses; } inline void bump_correct( user_profile *puser ) { bump_guess( puser ); ++puser->correct; } #include <cstdlib> inline num_sequence gen_seq_id( unsigned int ui ) { srand( ui++ ); return static_cast<num_sequence>( ( rand() % ns_cnt ) + 1 ); } inline void trace( const string& where, const string& msg, const string& data ) { cerr << where << " " << msg << " " << data << endl; } inline void trace( const string& where, const string& msg, int val ) { cerr << where << " " << msg << " " << val << endl; } inline void trace( const string& where, const string& msg, int val, int val2 ) { cerr << where << " " << msg << " " << val << ' ' << val2 << endl; } inline void trace( const string& where, int val1, int val2 ) { cerr << where << " " << val1 << " " << val2 << endl; } inline bool check_integrity( int pos ) { const int max_elems = 512; if ( pos <= 0 || pos > max_elems ) { cerr << "!! invalid position: " << pos << " Cannot honor request\n"; return false; } return true; } inline num_sequence check_sequence( int id ) { if ( id <= 0 || id > ns_cnt ) { cerr << "!! invalid sequence value: " << id << " Choosing one at random\n"; id = ( id % ns_cnt ) + 1; } return static_cast<num_sequence>( id ); } #endif
3ebba7ff9920d6c466ede78d449241bca25e403b
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/WebKit/Source/modules/webdatabase/QuotaTracker.cpp
326a22099cdd98d19369d6d87354414faa0e6db2
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,716
cpp
/* * Copyright (C) 2011 Google Inc. 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 Google Inc. 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 "modules/webdatabase/QuotaTracker.h" #include "platform/weborigin/SecurityOrigin.h" #include "public/platform/Platform.h" #include "public/platform/WebSecurityOrigin.h" #include "wtf/StdLibExtras.h" #include "wtf/Threading.h" namespace blink { QuotaTracker& QuotaTracker::instance() { DEFINE_THREAD_SAFE_STATIC_LOCAL(QuotaTracker, tracker, new QuotaTracker); return tracker; } void QuotaTracker::getDatabaseSizeAndSpaceAvailableToOrigin( SecurityOrigin* origin, const String& databaseName, unsigned long long* databaseSize, unsigned long long* spaceAvailable) { // Extra scope to unlock prior to potentially calling Platform. { MutexLocker lockData(m_dataGuard); ASSERT(m_databaseSizes.contains(origin->toRawString())); HashMap<String, SizeMap>::const_iterator it = m_databaseSizes.find(origin->toRawString()); ASSERT(it->value.contains(databaseName)); *databaseSize = it->value.get(databaseName); if (m_spaceAvailableToOrigins.contains(origin->toRawString())) { *spaceAvailable = m_spaceAvailableToOrigins.get(origin->toRawString()); return; } } // The embedder hasn't pushed this value to us, so we pull it as needed. *spaceAvailable = Platform::current()->databaseGetSpaceAvailableForOrigin( WebSecurityOrigin(origin)); } void QuotaTracker::updateDatabaseSize(SecurityOrigin* origin, const String& databaseName, unsigned long long databaseSize) { MutexLocker lockData(m_dataGuard); HashMap<String, SizeMap>::ValueType* it = m_databaseSizes.add(origin->toRawString(), SizeMap()).storedValue; it->value.set(databaseName, databaseSize); } void QuotaTracker::updateSpaceAvailableToOrigin( SecurityOrigin* origin, unsigned long long spaceAvailable) { MutexLocker lockData(m_dataGuard); m_spaceAvailableToOrigins.set(origin->toRawString(), spaceAvailable); } void QuotaTracker::resetSpaceAvailableToOrigin(SecurityOrigin* origin) { MutexLocker lockData(m_dataGuard); m_spaceAvailableToOrigins.remove(origin->toRawString()); } } // namespace blink
9c49cbfa24b14e47ec3686a3a058c89afba4d54d
3f1b0dc437c6f9b5009b3734fb46c16603eff7d7
/trash/newmain.cpp
448305b79293f1da7a63a44d1e00b6b57fcf27d5
[]
no_license
leoneed03/all
a09b2b9366d7e9c1cedd0ca4dbce04a8cef06d84
b1ee31cc71fe892b3757601c12764347beb042c7
refs/heads/master
2021-06-26T23:14:52.439810
2021-02-17T20:28:00
2021-02-17T20:28:00
218,765,141
0
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
#include "huffman.hpp" int main(int argc, char* argv[]) { std::vector<std::string> my_argv(argc); for (int i = 0; i < argc; ++i) { my_argv[i] = std::string(argv[i]); } if ((argc < 4) || ((argc == 5) && (my_argv[1] != "-v"))) { std::cout << "wrong args" << std::endl; return 0; } bool flag_v = (argc == 5) ? (my_argv[1] == "-v") : (false); bool flag_c_d = (argc == 5) ? (my_argv[2] == "-c") : (my_argv[1] == "-c"); run_coding_or_decoding(my_argv[argc - 2], my_argv[argc - 1], flag_v, flag_c_d); return 0; }
eeb10d84615b4c9084b7a5fb370d33a79e921f1c
ea4a165ee5ec50f3725cc6dba73328b596b1655b
/src/execution/arm64/simulator-arm64.cc
829638b871bcf793b0a66b569ff84a3a99dfda57
[ "BSD-3-Clause", "Apache-2.0", "SunPro" ]
permissive
cocos/v8
aee84292afaf7d640fd98855766552e229b529f9
93dcb090f1141bf80d1adaf4bb919b3b4c49ea89
refs/heads/main
2023-05-02T23:41:56.618739
2023-04-26T20:06:42
2023-04-26T23:01:28
633,206,875
0
1
null
2023-04-27T02:24:22
2023-04-27T02:24:21
null
UTF-8
C++
false
false
207,460
cc
// Copyright 2013 the V8 project 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 "src/execution/arm64/simulator-arm64.h" #include "src/execution/isolate.h" #if defined(USE_SIMULATOR) #include <stdlib.h> #include <cmath> #include <cstdarg> #include <type_traits> #include "src/base/overflowing-math.h" #include "src/base/platform/platform.h" #include "src/base/platform/wrappers.h" #include "src/codegen/arm64/decoder-arm64-inl.h" #include "src/codegen/assembler-inl.h" #include "src/codegen/macro-assembler.h" #include "src/diagnostics/disasm.h" #include "src/heap/combined-heap.h" #include "src/objects/objects-inl.h" #include "src/runtime/runtime-utils.h" #include "src/snapshot/embedded/embedded-data.h" #include "src/utils/ostreams.h" #if V8_OS_WIN #include <windows.h> #endif #if V8_ENABLE_WEBASSEMBLY #include "src/trap-handler/trap-handler-simulator.h" #endif // V8_ENABLE_WEBASSEMBLY namespace v8 { namespace internal { // This macro provides a platform independent use of sscanf. The reason for // SScanF not being implemented in a platform independent way through // ::v8::internal::OS in the same way as SNPrintF is that the // Windows C Run-Time Library does not provide vsscanf. #define SScanF sscanf // Helpers for colors. #define COLOUR(colour_code) "\033[0;" colour_code "m" #define COLOUR_BOLD(colour_code) "\033[1;" colour_code "m" #define NORMAL "" #define GREY "30" #define RED "31" #define GREEN "32" #define YELLOW "33" #define BLUE "34" #define MAGENTA "35" #define CYAN "36" #define WHITE "37" using TEXT_COLOUR = char const* const; TEXT_COLOUR clr_normal = v8_flags.log_colour ? COLOUR(NORMAL) : ""; TEXT_COLOUR clr_flag_name = v8_flags.log_colour ? COLOUR_BOLD(WHITE) : ""; TEXT_COLOUR clr_flag_value = v8_flags.log_colour ? COLOUR(NORMAL) : ""; TEXT_COLOUR clr_reg_name = v8_flags.log_colour ? COLOUR_BOLD(CYAN) : ""; TEXT_COLOUR clr_reg_value = v8_flags.log_colour ? COLOUR(CYAN) : ""; TEXT_COLOUR clr_vreg_name = v8_flags.log_colour ? COLOUR_BOLD(MAGENTA) : ""; TEXT_COLOUR clr_vreg_value = v8_flags.log_colour ? COLOUR(MAGENTA) : ""; TEXT_COLOUR clr_memory_address = v8_flags.log_colour ? COLOUR_BOLD(BLUE) : ""; TEXT_COLOUR clr_debug_number = v8_flags.log_colour ? COLOUR_BOLD(YELLOW) : ""; TEXT_COLOUR clr_debug_message = v8_flags.log_colour ? COLOUR(YELLOW) : ""; TEXT_COLOUR clr_printf = v8_flags.log_colour ? COLOUR(GREEN) : ""; DEFINE_LAZY_LEAKY_OBJECT_GETTER(Simulator::GlobalMonitor, Simulator::GlobalMonitor::Get) bool Simulator::ProbeMemory(uintptr_t address, uintptr_t access_size) { #if V8_ENABLE_WEBASSEMBLY && V8_TRAP_HANDLER_SUPPORTED uintptr_t last_accessed_byte = address + access_size - 1; uintptr_t current_pc = reinterpret_cast<uintptr_t>(pc_); uintptr_t landing_pad = trap_handler::ProbeMemory(last_accessed_byte, current_pc); if (!landing_pad) return true; set_pc(landing_pad); return false; #else return true; #endif } // This is basically the same as PrintF, with a guard for v8_flags.trace_sim. void Simulator::TraceSim(const char* format, ...) { if (v8_flags.trace_sim) { va_list arguments; va_start(arguments, format); base::OS::VFPrint(stream_, format, arguments); va_end(arguments); } } const Instruction* Simulator::kEndOfSimAddress = nullptr; void SimSystemRegister::SetBits(int msb, int lsb, uint32_t bits) { int width = msb - lsb + 1; DCHECK(is_uintn(bits, width) || is_intn(bits, width)); bits <<= lsb; uint32_t mask = ((1 << width) - 1) << lsb; DCHECK_EQ(mask & write_ignore_mask_, 0); value_ = (value_ & ~mask) | (bits & mask); } SimSystemRegister SimSystemRegister::DefaultValueFor(SystemRegister id) { switch (id) { case NZCV: return SimSystemRegister(0x00000000, NZCVWriteIgnoreMask); case FPCR: return SimSystemRegister(0x00000000, FPCRWriteIgnoreMask); default: UNREACHABLE(); } } // Get the active Simulator for the current thread. Simulator* Simulator::current(Isolate* isolate) { Isolate::PerIsolateThreadData* isolate_data = isolate->FindOrAllocatePerThreadDataForThisThread(); DCHECK_NOT_NULL(isolate_data); Simulator* sim = isolate_data->simulator(); if (sim == nullptr) { if (v8_flags.trace_sim || v8_flags.debug_sim) { sim = new Simulator(new Decoder<DispatchingDecoderVisitor>(), isolate); } else { sim = new Decoder<Simulator>(); sim->isolate_ = isolate; } isolate_data->set_simulator(sim); } return sim; } void Simulator::CallImpl(Address entry, CallArgument* args) { int index_x = 0; int index_d = 0; std::vector<int64_t> stack_args(0); for (int i = 0; !args[i].IsEnd(); i++) { CallArgument arg = args[i]; if (arg.IsX() && (index_x < 8)) { set_xreg(index_x++, arg.bits()); } else if (arg.IsD() && (index_d < 8)) { set_dreg_bits(index_d++, arg.bits()); } else { DCHECK(arg.IsD() || arg.IsX()); stack_args.push_back(arg.bits()); } } // Process stack arguments, and make sure the stack is suitably aligned. uintptr_t original_stack = sp(); uintptr_t entry_stack = original_stack - stack_args.size() * sizeof(stack_args[0]); if (base::OS::ActivationFrameAlignment() != 0) { entry_stack &= -base::OS::ActivationFrameAlignment(); } char* stack = reinterpret_cast<char*>(entry_stack); std::vector<int64_t>::const_iterator it; for (it = stack_args.begin(); it != stack_args.end(); it++) { memcpy(stack, &(*it), sizeof(*it)); stack += sizeof(*it); } DCHECK(reinterpret_cast<uintptr_t>(stack) <= original_stack); set_sp(entry_stack); // Call the generated code. set_pc(entry); set_lr(kEndOfSimAddress); CheckPCSComplianceAndRun(); set_sp(original_stack); } #ifdef DEBUG namespace { int PopLowestIndexAsCode(CPURegList* list) { if (list->IsEmpty()) { return -1; } uint64_t reg_list = list->bits(); int index = base::bits::CountTrailingZeros(reg_list); DCHECK((1LL << index) & reg_list); list->Remove(index); return index; } } // namespace #endif void Simulator::CheckPCSComplianceAndRun() { // Adjust JS-based stack limit to C-based stack limit. isolate_->stack_guard()->AdjustStackLimitForSimulator(); #ifdef DEBUG DCHECK_EQ(kNumberOfCalleeSavedRegisters, kCalleeSaved.Count()); DCHECK_EQ(kNumberOfCalleeSavedVRegisters, kCalleeSavedV.Count()); int64_t saved_registers[kNumberOfCalleeSavedRegisters]; uint64_t saved_fpregisters[kNumberOfCalleeSavedVRegisters]; CPURegList register_list = kCalleeSaved; CPURegList fpregister_list = kCalleeSavedV; for (int i = 0; i < kNumberOfCalleeSavedRegisters; i++) { // x31 is not a caller saved register, so no need to specify if we want // the stack or zero. saved_registers[i] = xreg(PopLowestIndexAsCode(&register_list)); } for (int i = 0; i < kNumberOfCalleeSavedVRegisters; i++) { saved_fpregisters[i] = dreg_bits(PopLowestIndexAsCode(&fpregister_list)); } int64_t original_stack = sp(); int64_t original_fp = fp(); #endif // Start the simulation! Run(); #ifdef DEBUG DCHECK_EQ(original_stack, sp()); DCHECK_EQ(original_fp, fp()); // Check that callee-saved registers have been preserved. register_list = kCalleeSaved; fpregister_list = kCalleeSavedV; for (int i = 0; i < kNumberOfCalleeSavedRegisters; i++) { DCHECK_EQ(saved_registers[i], xreg(PopLowestIndexAsCode(&register_list))); } for (int i = 0; i < kNumberOfCalleeSavedVRegisters; i++) { DCHECK(saved_fpregisters[i] == dreg_bits(PopLowestIndexAsCode(&fpregister_list))); } // Corrupt caller saved register minus the return regiters. // In theory x0 to x7 can be used for return values, but V8 only uses x0, x1 // for now . register_list = kCallerSaved; register_list.Remove(x0); register_list.Remove(x1); // In theory d0 to d7 can be used for return values, but V8 only uses d0 // for now . fpregister_list = kCallerSavedV; fpregister_list.Remove(d0); CorruptRegisters(&register_list, kCallerSavedRegisterCorruptionValue); CorruptRegisters(&fpregister_list, kCallerSavedVRegisterCorruptionValue); #endif } #ifdef DEBUG // The least significant byte of the curruption value holds the corresponding // register's code. void Simulator::CorruptRegisters(CPURegList* list, uint64_t value) { if (list->type() == CPURegister::kRegister) { while (!list->IsEmpty()) { unsigned code = PopLowestIndexAsCode(list); set_xreg(code, value | code); } } else { DCHECK_EQ(list->type(), CPURegister::kVRegister); while (!list->IsEmpty()) { unsigned code = PopLowestIndexAsCode(list); set_dreg_bits(code, value | code); } } } void Simulator::CorruptAllCallerSavedCPURegisters() { // Corrupt alters its parameter so copy them first. CPURegList register_list = kCallerSaved; CPURegList fpregister_list = kCallerSavedV; CorruptRegisters(&register_list, kCallerSavedRegisterCorruptionValue); CorruptRegisters(&fpregister_list, kCallerSavedVRegisterCorruptionValue); } #endif // Extending the stack by 2 * 64 bits is required for stack alignment purposes. uintptr_t Simulator::PushAddress(uintptr_t address) { DCHECK(sizeof(uintptr_t) < 2 * kXRegSize); intptr_t new_sp = sp() - 2 * kXRegSize; uintptr_t* alignment_slot = reinterpret_cast<uintptr_t*>(new_sp + kXRegSize); memcpy(alignment_slot, &kSlotsZapValue, kSystemPointerSize); uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp); memcpy(stack_slot, &address, kSystemPointerSize); set_sp(new_sp); return new_sp; } uintptr_t Simulator::PopAddress() { intptr_t current_sp = sp(); uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp); uintptr_t address = *stack_slot; DCHECK_LT(sizeof(uintptr_t), 2 * kXRegSize); set_sp(current_sp + 2 * kXRegSize); return address; } // Returns the limit of the stack area to enable checking for stack overflows. uintptr_t Simulator::StackLimit(uintptr_t c_limit) const { // The simulator uses a separate JS stack. If we have exhausted the C stack, // we also drop down the JS limit to reflect the exhaustion on the JS stack. if (base::Stack::GetCurrentStackPosition() < c_limit) { return get_sp(); } // Otherwise the limit is the JS stack. Leave a safety margin of 4 KiB // to prevent overrunning the stack when pushing values. return stack_limit_ + 4 * KB; } void Simulator::SetRedirectInstruction(Instruction* instruction) { instruction->SetInstructionBits( HLT | Assembler::ImmException(kImmExceptionIsRedirectedCall)); } Simulator::Simulator(Decoder<DispatchingDecoderVisitor>* decoder, Isolate* isolate, FILE* stream) : decoder_(decoder), guard_pages_(ENABLE_CONTROL_FLOW_INTEGRITY_BOOL), last_debugger_input_(nullptr), log_parameters_(NO_PARAM), icount_for_stop_sim_at_(0), isolate_(isolate) { // Setup the decoder. decoder_->AppendVisitor(this); Init(stream); if (v8_flags.trace_sim) { decoder_->InsertVisitorBefore(print_disasm_, this); log_parameters_ = LOG_ALL; } } Simulator::Simulator() : decoder_(nullptr), guard_pages_(ENABLE_CONTROL_FLOW_INTEGRITY_BOOL), last_debugger_input_(nullptr), log_parameters_(NO_PARAM), isolate_(nullptr) { Init(stdout); CHECK(!v8_flags.trace_sim); } void Simulator::Init(FILE* stream) { ResetState(); // Allocate and setup the simulator stack. stack_size_ = (v8_flags.sim_stack_size * KB) + (2 * stack_protection_size_); stack_ = reinterpret_cast<uintptr_t>(new byte[stack_size_]); stack_limit_ = stack_ + stack_protection_size_; uintptr_t tos = stack_ + stack_size_ - stack_protection_size_; // The stack pointer must be 16-byte aligned. set_sp(tos & ~0xFULL); stream_ = stream; print_disasm_ = new PrintDisassembler(stream_); // The debugger needs to disassemble code without the simulator executing an // instruction, so we create a dedicated decoder. disassembler_decoder_ = new Decoder<DispatchingDecoderVisitor>(); disassembler_decoder_->AppendVisitor(print_disasm_); } void Simulator::ResetState() { // Reset the system registers. nzcv_ = SimSystemRegister::DefaultValueFor(NZCV); fpcr_ = SimSystemRegister::DefaultValueFor(FPCR); // Reset registers to 0. pc_ = nullptr; for (unsigned i = 0; i < kNumberOfRegisters; i++) { set_xreg(i, 0xBADBEEF); } for (unsigned i = 0; i < kNumberOfVRegisters; i++) { // Set FP registers to a value that is NaN in both 32-bit and 64-bit FP. set_dreg_bits(i, 0x7FF000007F800001UL); } // Returning to address 0 exits the Simulator. set_lr(kEndOfSimAddress); // Reset debug helpers. breakpoints_.clear(); break_on_next_ = false; btype_ = DefaultBType; } Simulator::~Simulator() { GlobalMonitor::Get()->RemoveProcessor(&global_monitor_processor_); delete[] reinterpret_cast<byte*>(stack_); delete disassembler_decoder_; delete print_disasm_; delete decoder_; } void Simulator::Run() { // Flush any written registers before executing anything, so that // manually-set registers are logged _before_ the first instruction. LogAllWrittenRegisters(); pc_modified_ = false; if (v8_flags.stop_sim_at == 0) { // Fast version of the dispatch loop without checking whether the simulator // should be stopping at a particular executed instruction. while (pc_ != kEndOfSimAddress) { ExecuteInstruction(); } } else { // v8_flags.stop_sim_at is at the non-default value. Stop in the debugger // when we reach the particular instruction count. while (pc_ != kEndOfSimAddress) { icount_for_stop_sim_at_ = base::AddWithWraparound(icount_for_stop_sim_at_, 1); if (icount_for_stop_sim_at_ == v8_flags.stop_sim_at) { Debug(); } ExecuteInstruction(); } } } void Simulator::RunFrom(Instruction* start) { set_pc(start); Run(); } // Calls into the V8 runtime are based on this very simple interface. // Note: To be able to return two values from some calls the code in runtime.cc // uses the ObjectPair structure. // The simulator assumes all runtime calls return two 64-bits values. If they // don't, register x1 is clobbered. This is fine because x1 is caller-saved. #if defined(V8_OS_WIN) using SimulatorRuntimeCall_ReturnPtr = int64_t (*)( int64_t arg0, int64_t arg1, int64_t arg2, int64_t arg3, int64_t arg4, int64_t arg5, int64_t arg6, int64_t arg7, int64_t arg8, int64_t arg9, int64_t arg10, int64_t arg11, int64_t arg12, int64_t arg13, int64_t arg14, int64_t arg15, int64_t arg16, int64_t arg17, int64_t arg18, int64_t arg19); #endif using SimulatorRuntimeCall = ObjectPair (*)( int64_t arg0, int64_t arg1, int64_t arg2, int64_t arg3, int64_t arg4, int64_t arg5, int64_t arg6, int64_t arg7, int64_t arg8, int64_t arg9, int64_t arg10, int64_t arg11, int64_t arg12, int64_t arg13, int64_t arg14, int64_t arg15, int64_t arg16, int64_t arg17, int64_t arg18, int64_t arg19); using SimulatorRuntimeCompareCall = int64_t (*)(double arg1, double arg2); using SimulatorRuntimeFPFPCall = double (*)(double arg1, double arg2); using SimulatorRuntimeFPCall = double (*)(double arg1); using SimulatorRuntimeFPIntCall = double (*)(double arg1, int32_t arg2); // This signature supports direct call in to API function native callback // (refer to InvocationCallback in v8.h). using SimulatorRuntimeDirectApiCall = void (*)(int64_t arg0); using SimulatorRuntimeProfilingApiCall = void (*)(int64_t arg0, void* arg1); // This signature supports direct call to accessor getter callback. using SimulatorRuntimeDirectGetterCall = void (*)(int64_t arg0, int64_t arg1); using SimulatorRuntimeProfilingGetterCall = void (*)(int64_t arg0, int64_t arg1, void* arg2); // Separate for fine-grained UBSan blocklisting. Casting any given C++ // function to {SimulatorRuntimeCall} is undefined behavior; but since // the target function can indeed be any function that's exposed via // the "fast C call" mechanism, we can't reconstruct its signature here. ObjectPair UnsafeGenericFunctionCall( int64_t function, int64_t arg0, int64_t arg1, int64_t arg2, int64_t arg3, int64_t arg4, int64_t arg5, int64_t arg6, int64_t arg7, int64_t arg8, int64_t arg9, int64_t arg10, int64_t arg11, int64_t arg12, int64_t arg13, int64_t arg14, int64_t arg15, int64_t arg16, int64_t arg17, int64_t arg18, int64_t arg19) { SimulatorRuntimeCall target = reinterpret_cast<SimulatorRuntimeCall>(function); return target(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); } void UnsafeDirectApiCall(int64_t function, int64_t arg0) { SimulatorRuntimeDirectApiCall target = reinterpret_cast<SimulatorRuntimeDirectApiCall>(function); target(arg0); } void UnsafeProfilingApiCall(int64_t function, int64_t arg0, void* arg1) { SimulatorRuntimeProfilingApiCall target = reinterpret_cast<SimulatorRuntimeProfilingApiCall>(function); target(arg0, arg1); } void UnsafeDirectGetterCall(int64_t function, int64_t arg0, int64_t arg1) { SimulatorRuntimeDirectGetterCall target = reinterpret_cast<SimulatorRuntimeDirectGetterCall>(function); target(arg0, arg1); } using MixedRuntimeCall_0 = AnyCType (*)(); #define BRACKETS(ident, N) ident[N] #define REP_0(expr, FMT) #define REP_1(expr, FMT) FMT(expr, 0) #define REP_2(expr, FMT) REP_1(expr, FMT), FMT(expr, 1) #define REP_3(expr, FMT) REP_2(expr, FMT), FMT(expr, 2) #define REP_4(expr, FMT) REP_3(expr, FMT), FMT(expr, 3) #define REP_5(expr, FMT) REP_4(expr, FMT), FMT(expr, 4) #define REP_6(expr, FMT) REP_5(expr, FMT), FMT(expr, 5) #define REP_7(expr, FMT) REP_6(expr, FMT), FMT(expr, 6) #define REP_8(expr, FMT) REP_7(expr, FMT), FMT(expr, 7) #define REP_9(expr, FMT) REP_8(expr, FMT), FMT(expr, 8) #define REP_10(expr, FMT) REP_9(expr, FMT), FMT(expr, 9) #define REP_11(expr, FMT) REP_10(expr, FMT), FMT(expr, 10) #define REP_12(expr, FMT) REP_11(expr, FMT), FMT(expr, 11) #define REP_13(expr, FMT) REP_12(expr, FMT), FMT(expr, 12) #define REP_14(expr, FMT) REP_13(expr, FMT), FMT(expr, 13) #define REP_15(expr, FMT) REP_14(expr, FMT), FMT(expr, 14) #define REP_16(expr, FMT) REP_15(expr, FMT), FMT(expr, 15) #define REP_17(expr, FMT) REP_16(expr, FMT), FMT(expr, 16) #define REP_18(expr, FMT) REP_17(expr, FMT), FMT(expr, 17) #define REP_19(expr, FMT) REP_18(expr, FMT), FMT(expr, 18) #define REP_20(expr, FMT) REP_19(expr, FMT), FMT(expr, 19) #define GEN_MAX_PARAM_COUNT(V) \ V(0) \ V(1) \ V(2) \ V(3) \ V(4) \ V(5) \ V(6) \ V(7) \ V(8) \ V(9) \ V(10) \ V(11) \ V(12) \ V(13) \ V(14) \ V(15) \ V(16) \ V(17) \ V(18) \ V(19) \ V(20) #define MIXED_RUNTIME_CALL(N) \ using MixedRuntimeCall_##N = AnyCType (*)(REP_##N(AnyCType arg, CONCAT)); GEN_MAX_PARAM_COUNT(MIXED_RUNTIME_CALL) #undef MIXED_RUNTIME_CALL #define CALL_ARGS(N) REP_##N(args, BRACKETS) #define CALL_TARGET_VARARG(N) \ if (signature.ParameterCount() == N) { /* NOLINT */ \ MixedRuntimeCall_##N target = \ reinterpret_cast<MixedRuntimeCall_##N>(target_address); \ result = target(CALL_ARGS(N)); \ } else /* NOLINT */ void Simulator::CallAnyCTypeFunction(Address target_address, const EncodedCSignature& signature) { TraceSim("Type: mixed types BUILTIN_CALL\n"); const int64_t* stack_pointer = reinterpret_cast<int64_t*>(sp()); const double* double_stack_pointer = reinterpret_cast<double*>(sp()); int num_gp_params = 0, num_fp_params = 0, num_stack_params = 0; CHECK_LE(signature.ParameterCount(), kMaxCParameters); static_assert(sizeof(AnyCType) == 8, "AnyCType is assumed to be 64-bit."); AnyCType args[kMaxCParameters]; // The first 8 parameters of each type (GP or FP) are placed in corresponding // registers. The rest are expected to be on the stack, where each parameter // type counts on its own. For example a function like: // foo(int i1, ..., int i9, float f1, float f2) will use up all 8 GP // registers, place i9 on the stack, and place f1 and f2 in FP registers. // Source: https://developer.arm.com/documentation/ihi0055/d/, section // "Parameter Passing". for (int i = 0; i < signature.ParameterCount(); ++i) { if (signature.IsFloat(i)) { if (num_fp_params < 8) { args[i].double_value = dreg(num_fp_params++); } else { args[i].double_value = double_stack_pointer[num_stack_params++]; } } else { if (num_gp_params < 8) { args[i].int64_value = xreg(num_gp_params++); } else { args[i].int64_value = stack_pointer[num_stack_params++]; } } } AnyCType result; GEN_MAX_PARAM_COUNT(CALL_TARGET_VARARG) /* else */ { UNREACHABLE(); } static_assert(20 == kMaxCParameters, "If you've changed kMaxCParameters, please change the " "GEN_MAX_PARAM_COUNT macro."); #undef CALL_TARGET_VARARG #undef CALL_ARGS #undef GEN_MAX_PARAM_COUNT #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif if (signature.IsReturnFloat()) { set_dreg(0, result.double_value); } else { set_xreg(0, result.int64_value); } } void Simulator::DoRuntimeCall(Instruction* instr) { Redirection* redirection = Redirection::FromInstruction(instr); // The called C code might itself call simulated code, so any // caller-saved registers (including lr) could still be clobbered by a // redirected call. Instruction* return_address = lr(); int64_t external = reinterpret_cast<int64_t>(redirection->external_function()); TraceSim("Call to host function at %p\n", redirection->external_function()); // SP must be 16-byte-aligned at the call interface. bool stack_alignment_exception = ((sp() & 0xF) != 0); if (stack_alignment_exception) { TraceSim(" with unaligned stack 0x%016" PRIx64 ".\n", sp()); FATAL("ALIGNMENT EXCEPTION"); } Address func_addr = reinterpret_cast<Address>(redirection->external_function()); SimulatorData* simulator_data = isolate_->simulator_data(); DCHECK_NOT_NULL(simulator_data); const EncodedCSignature& signature = simulator_data->GetSignatureForTarget(func_addr); if (signature.IsValid()) { CHECK(redirection->type() == ExternalReference::FAST_C_CALL); CallAnyCTypeFunction(external, signature); set_lr(return_address); set_pc(return_address); return; } int64_t* stack_pointer = reinterpret_cast<int64_t*>(sp()); const int64_t arg0 = xreg(0); const int64_t arg1 = xreg(1); const int64_t arg2 = xreg(2); const int64_t arg3 = xreg(3); const int64_t arg4 = xreg(4); const int64_t arg5 = xreg(5); const int64_t arg6 = xreg(6); const int64_t arg7 = xreg(7); const int64_t arg8 = stack_pointer[0]; const int64_t arg9 = stack_pointer[1]; const int64_t arg10 = stack_pointer[2]; const int64_t arg11 = stack_pointer[3]; const int64_t arg12 = stack_pointer[4]; const int64_t arg13 = stack_pointer[5]; const int64_t arg14 = stack_pointer[6]; const int64_t arg15 = stack_pointer[7]; const int64_t arg16 = stack_pointer[8]; const int64_t arg17 = stack_pointer[9]; const int64_t arg18 = stack_pointer[10]; const int64_t arg19 = stack_pointer[11]; static_assert(kMaxCParameters == 20); switch (redirection->type()) { default: TraceSim("Type: Unknown.\n"); UNREACHABLE(); case ExternalReference::BUILTIN_CALL: #if defined(V8_OS_WIN) { // Object f(v8::internal::Arguments). TraceSim("Type: BUILTIN_CALL\n"); // When this simulator runs on Windows x64 host, function with ObjectPair // return type accepts an implicit pointer to caller allocated memory for // ObjectPair as return value. This diverges the calling convention from // function which returns primitive type, so function returns ObjectPair // and primitive type cannot share implementation. // We don't know how many arguments are being passed, but we can // pass 8 without touching the stack. They will be ignored by the // host function if they aren't used. TraceSim( "Arguments: " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); SimulatorRuntimeCall_ReturnPtr target = reinterpret_cast<SimulatorRuntimeCall_ReturnPtr>(external); int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); TraceSim("Returned: 0x%16\n", result); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif set_xreg(0, result); break; } #endif case ExternalReference::BUILTIN_CALL_PAIR: { // Object f(v8::internal::Arguments) or // ObjectPair f(v8::internal::Arguments). TraceSim("Type: BUILTIN_CALL\n"); // We don't know how many arguments are being passed, but we can // pass 8 without touching the stack. They will be ignored by the // host function if they aren't used. TraceSim( "Arguments: " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64 ", " "0x%016" PRIx64 ", 0x%016" PRIx64, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); ObjectPair result = UnsafeGenericFunctionCall( external, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); TraceSim("Returned: {%p, %p}\n", reinterpret_cast<void*>(result.x), reinterpret_cast<void*>(result.y)); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif set_xreg(0, static_cast<int64_t>(result.x)); set_xreg(1, static_cast<int64_t>(result.y)); break; } case ExternalReference::DIRECT_API_CALL: { // void f(v8::FunctionCallbackInfo&) TraceSim("Type: DIRECT_API_CALL\n"); TraceSim("Arguments: 0x%016" PRIx64 "\n", xreg(0)); UnsafeDirectApiCall(external, xreg(0)); TraceSim("No return value."); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif break; } case ExternalReference::BUILTIN_COMPARE_CALL: { // int f(double, double) TraceSim("Type: BUILTIN_COMPARE_CALL\n"); SimulatorRuntimeCompareCall target = reinterpret_cast<SimulatorRuntimeCompareCall>(external); TraceSim("Arguments: %f, %f\n", dreg(0), dreg(1)); int64_t result = target(dreg(0), dreg(1)); TraceSim("Returned: %" PRId64 "\n", result); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif set_xreg(0, result); break; } case ExternalReference::BUILTIN_FP_CALL: { // double f(double) TraceSim("Type: BUILTIN_FP_CALL\n"); SimulatorRuntimeFPCall target = reinterpret_cast<SimulatorRuntimeFPCall>(external); TraceSim("Argument: %f\n", dreg(0)); double result = target(dreg(0)); TraceSim("Returned: %f\n", result); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif set_dreg(0, result); break; } case ExternalReference::BUILTIN_FP_FP_CALL: { // double f(double, double) TraceSim("Type: BUILTIN_FP_FP_CALL\n"); SimulatorRuntimeFPFPCall target = reinterpret_cast<SimulatorRuntimeFPFPCall>(external); TraceSim("Arguments: %f, %f\n", dreg(0), dreg(1)); double result = target(dreg(0), dreg(1)); TraceSim("Returned: %f\n", result); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif set_dreg(0, result); break; } case ExternalReference::BUILTIN_FP_INT_CALL: { // double f(double, int) TraceSim("Type: BUILTIN_FP_INT_CALL\n"); SimulatorRuntimeFPIntCall target = reinterpret_cast<SimulatorRuntimeFPIntCall>(external); TraceSim("Arguments: %f, %d\n", dreg(0), wreg(0)); double result = target(dreg(0), wreg(0)); TraceSim("Returned: %f\n", result); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif set_dreg(0, result); break; } case ExternalReference::DIRECT_GETTER_CALL: { // void f(Local<String> property, PropertyCallbackInfo& info) TraceSim("Type: DIRECT_GETTER_CALL\n"); TraceSim("Arguments: 0x%016" PRIx64 ", 0x%016" PRIx64 "\n", xreg(0), xreg(1)); UnsafeDirectGetterCall(external, xreg(0), xreg(1)); TraceSim("No return value."); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif break; } case ExternalReference::PROFILING_API_CALL: { // void f(v8::FunctionCallbackInfo&, v8::FunctionCallback) TraceSim("Type: PROFILING_API_CALL\n"); void* arg1 = Redirection::UnwrapRedirection(xreg(1)); TraceSim("Arguments: 0x%016" PRIx64 ", %p\n", xreg(0), arg1); UnsafeProfilingApiCall(external, xreg(0), arg1); TraceSim("No return value."); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif break; } case ExternalReference::PROFILING_GETTER_CALL: { // void f(Local<String> property, PropertyCallbackInfo& info, // AccessorNameGetterCallback callback) TraceSim("Type: PROFILING_GETTER_CALL\n"); SimulatorRuntimeProfilingGetterCall target = reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external); void* arg2 = Redirection::UnwrapRedirection(xreg(2)); TraceSim("Arguments: 0x%016" PRIx64 ", 0x%016" PRIx64 ", %p\n", xreg(0), xreg(1), arg2); target(xreg(0), xreg(1), arg2); TraceSim("No return value."); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif break; } } set_lr(return_address); set_pc(return_address); } const char* Simulator::xreg_names[] = { "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "ip0", "ip1", "x18", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "cp", "x28", "fp", "lr", "xzr", "sp"}; const char* Simulator::wreg_names[] = { "w0", "w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "w9", "w10", "w11", "w12", "w13", "w14", "w15", "w16", "w17", "w18", "w19", "w20", "w21", "w22", "w23", "w24", "w25", "w26", "wcp", "w28", "wfp", "wlr", "wzr", "wsp"}; const char* Simulator::sreg_names[] = { "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31"}; const char* Simulator::dreg_names[] = { "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31"}; const char* Simulator::vreg_names[] = { "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"}; const char* Simulator::WRegNameForCode(unsigned code, Reg31Mode mode) { static_assert(arraysize(Simulator::wreg_names) == (kNumberOfRegisters + 1), "Array must be large enough to hold all register names."); DCHECK_LT(code, static_cast<unsigned>(kNumberOfRegisters)); // The modulo operator has no effect here, but it silences a broken GCC // warning about out-of-bounds array accesses. code %= kNumberOfRegisters; // If the code represents the stack pointer, index the name after zr. if ((code == kZeroRegCode) && (mode == Reg31IsStackPointer)) { code = kZeroRegCode + 1; } return wreg_names[code]; } const char* Simulator::XRegNameForCode(unsigned code, Reg31Mode mode) { static_assert(arraysize(Simulator::xreg_names) == (kNumberOfRegisters + 1), "Array must be large enough to hold all register names."); DCHECK_LT(code, static_cast<unsigned>(kNumberOfRegisters)); code %= kNumberOfRegisters; // If the code represents the stack pointer, index the name after zr. if ((code == kZeroRegCode) && (mode == Reg31IsStackPointer)) { code = kZeroRegCode + 1; } return xreg_names[code]; } const char* Simulator::SRegNameForCode(unsigned code) { static_assert(arraysize(Simulator::sreg_names) == kNumberOfVRegisters, "Array must be large enough to hold all register names."); DCHECK_LT(code, static_cast<unsigned>(kNumberOfVRegisters)); return sreg_names[code % kNumberOfVRegisters]; } const char* Simulator::DRegNameForCode(unsigned code) { static_assert(arraysize(Simulator::dreg_names) == kNumberOfVRegisters, "Array must be large enough to hold all register names."); DCHECK_LT(code, static_cast<unsigned>(kNumberOfVRegisters)); return dreg_names[code % kNumberOfVRegisters]; } const char* Simulator::VRegNameForCode(unsigned code) { static_assert(arraysize(Simulator::vreg_names) == kNumberOfVRegisters, "Array must be large enough to hold all register names."); DCHECK_LT(code, static_cast<unsigned>(kNumberOfVRegisters)); return vreg_names[code % kNumberOfVRegisters]; } void LogicVRegister::ReadUintFromMem(VectorFormat vform, int index, uint64_t addr) const { switch (LaneSizeInBitsFromFormat(vform)) { case 8: register_.Insert(index, SimMemory::Read<uint8_t>(addr)); break; case 16: register_.Insert(index, SimMemory::Read<uint16_t>(addr)); break; case 32: register_.Insert(index, SimMemory::Read<uint32_t>(addr)); break; case 64: register_.Insert(index, SimMemory::Read<uint64_t>(addr)); break; default: UNREACHABLE(); } } void LogicVRegister::WriteUintToMem(VectorFormat vform, int index, uint64_t addr) const { switch (LaneSizeInBitsFromFormat(vform)) { case 8: SimMemory::Write<uint8_t>(addr, static_cast<uint8_t>(Uint(vform, index))); break; case 16: SimMemory::Write<uint16_t>(addr, static_cast<uint16_t>(Uint(vform, index))); break; case 32: SimMemory::Write<uint32_t>(addr, static_cast<uint32_t>(Uint(vform, index))); break; case 64: SimMemory::Write<uint64_t>(addr, Uint(vform, index)); break; default: UNREACHABLE(); } } int Simulator::CodeFromName(const char* name) { for (unsigned i = 0; i < kNumberOfRegisters; i++) { if ((strcmp(xreg_names[i], name) == 0) || (strcmp(wreg_names[i], name) == 0)) { return i; } } for (unsigned i = 0; i < kNumberOfVRegisters; i++) { if ((strcmp(vreg_names[i], name) == 0) || (strcmp(dreg_names[i], name) == 0) || (strcmp(sreg_names[i], name) == 0)) { return i; } } if ((strcmp("sp", name) == 0) || (strcmp("wsp", name) == 0)) { return kSPRegInternalCode; } return -1; } // Helpers --------------------------------------------------------------------- template <typename T> T Simulator::AddWithCarry(bool set_flags, T left, T right, int carry_in) { // Use unsigned types to avoid implementation-defined overflow behaviour. static_assert(std::is_unsigned<T>::value, "operands must be unsigned"); static_assert((sizeof(T) == kWRegSize) || (sizeof(T) == kXRegSize), "Only W- or X-sized operands are tested"); DCHECK((carry_in == 0) || (carry_in == 1)); T result = left + right + carry_in; if (set_flags) { nzcv().SetN(CalcNFlag(result)); nzcv().SetZ(CalcZFlag(result)); // Compute the C flag by comparing the result to the max unsigned integer. T max_uint_2op = std::numeric_limits<T>::max() - carry_in; nzcv().SetC((left > max_uint_2op) || ((max_uint_2op - left) < right)); // Overflow iff the sign bit is the same for the two inputs and different // for the result. T sign_mask = T(1) << (sizeof(T) * 8 - 1); T left_sign = left & sign_mask; T right_sign = right & sign_mask; T result_sign = result & sign_mask; nzcv().SetV((left_sign == right_sign) && (left_sign != result_sign)); LogSystemRegister(NZCV); } return result; } template <typename T> void Simulator::AddSubWithCarry(Instruction* instr) { // Use unsigned types to avoid implementation-defined overflow behaviour. static_assert(std::is_unsigned<T>::value, "operands must be unsigned"); T op2 = reg<T>(instr->Rm()); T new_val; if ((instr->Mask(AddSubOpMask) == SUB) || instr->Mask(AddSubOpMask) == SUBS) { op2 = ~op2; } new_val = AddWithCarry<T>(instr->FlagsUpdate(), reg<T>(instr->Rn()), op2, nzcv().C()); set_reg<T>(instr->Rd(), new_val); } template <typename T> T Simulator::ShiftOperand(T value, Shift shift_type, unsigned amount) { using unsignedT = typename std::make_unsigned<T>::type; if (amount == 0) { return value; } // Larger shift {amount}s would be undefined behavior in C++. DCHECK(amount < sizeof(value) * kBitsPerByte); switch (shift_type) { case LSL: return static_cast<unsignedT>(value) << amount; case LSR: return static_cast<unsignedT>(value) >> amount; case ASR: return value >> amount; case ROR: { unsignedT mask = (static_cast<unsignedT>(1) << amount) - 1; return (static_cast<unsignedT>(value) >> amount) | ((value & mask) << (sizeof(mask) * 8 - amount)); } default: UNIMPLEMENTED(); return 0; } } template <typename T> T Simulator::ExtendValue(T value, Extend extend_type, unsigned left_shift) { const unsigned kSignExtendBShift = (sizeof(T) - 1) * 8; const unsigned kSignExtendHShift = (sizeof(T) - 2) * 8; const unsigned kSignExtendWShift = (sizeof(T) - 4) * 8; using unsignedT = typename std::make_unsigned<T>::type; switch (extend_type) { case UXTB: value &= kByteMask; break; case UXTH: value &= kHalfWordMask; break; case UXTW: value &= kWordMask; break; case SXTB: value = static_cast<T>(static_cast<unsignedT>(value) << kSignExtendBShift) >> kSignExtendBShift; break; case SXTH: value = static_cast<T>(static_cast<unsignedT>(value) << kSignExtendHShift) >> kSignExtendHShift; break; case SXTW: value = static_cast<T>(static_cast<unsignedT>(value) << kSignExtendWShift) >> kSignExtendWShift; break; case UXTX: case SXTX: break; default: UNREACHABLE(); } return static_cast<T>(static_cast<unsignedT>(value) << left_shift); } template <typename T> void Simulator::Extract(Instruction* instr) { unsigned lsb = instr->ImmS(); T op2 = reg<T>(instr->Rm()); T result = op2; if (lsb) { T op1 = reg<T>(instr->Rn()); result = op2 >> lsb | (op1 << ((sizeof(T) * 8) - lsb)); } set_reg<T>(instr->Rd(), result); } void Simulator::FPCompare(double val0, double val1) { AssertSupportedFPCR(); // TODO(jbramley): This assumes that the C++ implementation handles // comparisons in the way that we expect (as per AssertSupportedFPCR()). if ((std::isnan(val0) != 0) || (std::isnan(val1) != 0)) { nzcv().SetRawValue(FPUnorderedFlag); } else if (val0 < val1) { nzcv().SetRawValue(FPLessThanFlag); } else if (val0 > val1) { nzcv().SetRawValue(FPGreaterThanFlag); } else if (val0 == val1) { nzcv().SetRawValue(FPEqualFlag); } else { UNREACHABLE(); } LogSystemRegister(NZCV); } Simulator::PrintRegisterFormat Simulator::GetPrintRegisterFormatForSize( size_t reg_size, size_t lane_size) { DCHECK_GE(reg_size, lane_size); uint32_t format = 0; if (reg_size != lane_size) { switch (reg_size) { default: UNREACHABLE(); case kQRegSize: format = kPrintRegAsQVector; break; case kDRegSize: format = kPrintRegAsDVector; break; } } switch (lane_size) { default: UNREACHABLE(); case kQRegSize: format |= kPrintReg1Q; break; case kDRegSize: format |= kPrintReg1D; break; case kSRegSize: format |= kPrintReg1S; break; case kHRegSize: format |= kPrintReg1H; break; case kBRegSize: format |= kPrintReg1B; break; } // These sizes would be duplicate case labels. static_assert(kXRegSize == kDRegSize, "X and D registers must be same size."); static_assert(kWRegSize == kSRegSize, "W and S registers must be same size."); static_assert(kPrintXReg == kPrintReg1D, "X and D register printing code is shared."); static_assert(kPrintWReg == kPrintReg1S, "W and S register printing code is shared."); return static_cast<PrintRegisterFormat>(format); } Simulator::PrintRegisterFormat Simulator::GetPrintRegisterFormat( VectorFormat vform) { switch (vform) { default: UNREACHABLE(); case kFormat16B: return kPrintReg16B; case kFormat8B: return kPrintReg8B; case kFormat8H: return kPrintReg8H; case kFormat4H: return kPrintReg4H; case kFormat4S: return kPrintReg4S; case kFormat2S: return kPrintReg2S; case kFormat2D: return kPrintReg2D; case kFormat1D: return kPrintReg1D; case kFormatB: return kPrintReg1B; case kFormatH: return kPrintReg1H; case kFormatS: return kPrintReg1S; case kFormatD: return kPrintReg1D; } } Simulator::PrintRegisterFormat Simulator::GetPrintRegisterFormatFP( VectorFormat vform) { switch (vform) { default: UNREACHABLE(); case kFormat4S: return kPrintReg4SFP; case kFormat2S: return kPrintReg2SFP; case kFormat2D: return kPrintReg2DFP; case kFormat1D: return kPrintReg1DFP; case kFormatS: return kPrintReg1SFP; case kFormatD: return kPrintReg1DFP; } } void Simulator::SetBreakpoint(Instruction* location) { for (unsigned i = 0; i < breakpoints_.size(); i++) { if (breakpoints_.at(i).location == location) { PrintF(stream_, "Existing breakpoint at %p was %s\n", reinterpret_cast<void*>(location), breakpoints_.at(i).enabled ? "disabled" : "enabled"); breakpoints_.at(i).enabled = !breakpoints_.at(i).enabled; return; } } Breakpoint new_breakpoint = {location, true}; breakpoints_.push_back(new_breakpoint); PrintF(stream_, "Set a breakpoint at %p\n", reinterpret_cast<void*>(location)); } void Simulator::ListBreakpoints() { PrintF(stream_, "Breakpoints:\n"); for (unsigned i = 0; i < breakpoints_.size(); i++) { PrintF(stream_, "%p : %s\n", reinterpret_cast<void*>(breakpoints_.at(i).location), breakpoints_.at(i).enabled ? "enabled" : "disabled"); } } void Simulator::CheckBreakpoints() { bool hit_a_breakpoint = false; for (unsigned i = 0; i < breakpoints_.size(); i++) { if ((breakpoints_.at(i).location == pc_) && breakpoints_.at(i).enabled) { hit_a_breakpoint = true; // Disable this breakpoint. breakpoints_.at(i).enabled = false; } } if (hit_a_breakpoint) { PrintF(stream_, "Hit and disabled a breakpoint at %p.\n", reinterpret_cast<void*>(pc_)); Debug(); } } void Simulator::CheckBreakNext() { // If the current instruction is a BL, insert a breakpoint just after it. if (break_on_next_ && pc_->IsBranchAndLinkToRegister()) { SetBreakpoint(pc_->following()); break_on_next_ = false; } } void Simulator::PrintInstructionsAt(Instruction* start, uint64_t count) { Instruction* end = start->InstructionAtOffset(count * kInstrSize); for (Instruction* pc = start; pc < end; pc = pc->following()) { disassembler_decoder_->Decode(pc); } } void Simulator::PrintWrittenRegisters() { for (unsigned i = 0; i < kNumberOfRegisters; i++) { if (registers_[i].WrittenSinceLastLog()) PrintRegister(i); } } void Simulator::PrintWrittenVRegisters() { for (unsigned i = 0; i < kNumberOfVRegisters; i++) { // At this point there is no type information, so print as a raw 1Q. if (vregisters_[i].WrittenSinceLastLog()) PrintVRegister(i, kPrintReg1Q); } } void Simulator::PrintSystemRegisters() { PrintSystemRegister(NZCV); PrintSystemRegister(FPCR); } void Simulator::PrintRegisters() { for (unsigned i = 0; i < kNumberOfRegisters; i++) { PrintRegister(i); } } void Simulator::PrintVRegisters() { for (unsigned i = 0; i < kNumberOfVRegisters; i++) { // At this point there is no type information, so print as a raw 1Q. PrintVRegister(i, kPrintReg1Q); } } void Simulator::PrintRegister(unsigned code, Reg31Mode r31mode) { registers_[code].NotifyRegisterLogged(); // Don't print writes into xzr. if ((code == kZeroRegCode) && (r31mode == Reg31IsZeroRegister)) { return; } // The template for all x and w registers: // "# x{code}: 0x{value}" // "# w{code}: 0x{value}" PrintRegisterRawHelper(code, r31mode); fprintf(stream_, "\n"); } // Print a register's name and raw value. // // The `bytes` and `lsb` arguments can be used to limit the bytes that are // printed. These arguments are intended for use in cases where register hasn't // actually been updated (such as in PrintVWrite). // // No newline is printed. This allows the caller to print more details (such as // a floating-point interpretation or a memory access annotation). void Simulator::PrintVRegisterRawHelper(unsigned code, int bytes, int lsb) { // The template for vector types: // "# v{code}: 0xFFEEDDCCBBAA99887766554433221100". // An example with bytes=4 and lsb=8: // "# v{code}: 0xBBAA9988 ". fprintf(stream_, "# %s%5s: %s", clr_vreg_name, VRegNameForCode(code), clr_vreg_value); int msb = lsb + bytes - 1; int byte = kQRegSize - 1; // Print leading padding spaces. (Two spaces per byte.) while (byte > msb) { fprintf(stream_, " "); byte--; } // Print the specified part of the value, byte by byte. qreg_t rawbits = qreg(code); fprintf(stream_, "0x"); while (byte >= lsb) { fprintf(stream_, "%02x", rawbits.val[byte]); byte--; } // Print trailing padding spaces. while (byte >= 0) { fprintf(stream_, " "); byte--; } fprintf(stream_, "%s", clr_normal); } // Print each of the specified lanes of a register as a float or double value. // // The `lane_count` and `lslane` arguments can be used to limit the lanes that // are printed. These arguments are intended for use in cases where register // hasn't actually been updated (such as in PrintVWrite). // // No newline is printed. This allows the caller to print more details (such as // a memory access annotation). void Simulator::PrintVRegisterFPHelper(unsigned code, unsigned lane_size_in_bytes, int lane_count, int rightmost_lane) { DCHECK((lane_size_in_bytes == kSRegSize) || (lane_size_in_bytes == kDRegSize)); unsigned msb = (lane_count + rightmost_lane) * lane_size_in_bytes; DCHECK_LE(msb, static_cast<unsigned>(kQRegSize)); // For scalar types ((lane_count == 1) && (rightmost_lane == 0)), a register // name is used: // " (s{code}: {value})" // " (d{code}: {value})" // For vector types, "..." is used to represent one or more omitted lanes. // " (..., {value}, {value}, ...)" if ((lane_count == 1) && (rightmost_lane == 0)) { const char* name = (lane_size_in_bytes == kSRegSize) ? SRegNameForCode(code) : DRegNameForCode(code); fprintf(stream_, " (%s%s: ", clr_vreg_name, name); } else { if (msb < (kQRegSize - 1)) { fprintf(stream_, " (..., "); } else { fprintf(stream_, " ("); } } // Print the list of values. const char* separator = ""; int leftmost_lane = rightmost_lane + lane_count - 1; for (int lane = leftmost_lane; lane >= rightmost_lane; lane--) { double value = (lane_size_in_bytes == kSRegSize) ? vreg(code).Get<float>(lane) : vreg(code).Get<double>(lane); fprintf(stream_, "%s%s%#g%s", separator, clr_vreg_value, value, clr_normal); separator = ", "; } if (rightmost_lane > 0) { fprintf(stream_, ", ..."); } fprintf(stream_, ")"); } // Print a register's name and raw value. // // Only the least-significant `size_in_bytes` bytes of the register are printed, // but the value is aligned as if the whole register had been printed. // // For typical register updates, size_in_bytes should be set to kXRegSize // -- the default -- so that the whole register is printed. Other values of // size_in_bytes are intended for use when the register hasn't actually been // updated (such as in PrintWrite). // // No newline is printed. This allows the caller to print more details (such as // a memory access annotation). void Simulator::PrintRegisterRawHelper(unsigned code, Reg31Mode r31mode, int size_in_bytes) { // The template for all supported sizes. // "# x{code}: 0xFFEEDDCCBBAA9988" // "# w{code}: 0xBBAA9988" // "# w{code}<15:0>: 0x9988" // "# w{code}<7:0>: 0x88" unsigned padding_chars = (kXRegSize - size_in_bytes) * 2; const char* name = ""; const char* suffix = ""; switch (size_in_bytes) { case kXRegSize: name = XRegNameForCode(code, r31mode); break; case kWRegSize: name = WRegNameForCode(code, r31mode); break; case 2: name = WRegNameForCode(code, r31mode); suffix = "<15:0>"; padding_chars -= strlen(suffix); break; case 1: name = WRegNameForCode(code, r31mode); suffix = "<7:0>"; padding_chars -= strlen(suffix); break; default: UNREACHABLE(); } fprintf(stream_, "# %s%5s%s: ", clr_reg_name, name, suffix); // Print leading padding spaces. DCHECK_LT(padding_chars, kXRegSize * 2U); for (unsigned i = 0; i < padding_chars; i++) { putc(' ', stream_); } // Print the specified bits in hexadecimal format. uint64_t bits = reg<uint64_t>(code, r31mode); bits &= kXRegMask >> ((kXRegSize - size_in_bytes) * 8); static_assert(sizeof(bits) == kXRegSize, "X registers and uint64_t must be the same size."); int chars = size_in_bytes * 2; fprintf(stream_, "%s0x%0*" PRIx64 "%s", clr_reg_value, chars, bits, clr_normal); } void Simulator::PrintVRegister(unsigned code, PrintRegisterFormat format) { vregisters_[code].NotifyRegisterLogged(); int lane_size_log2 = format & kPrintRegLaneSizeMask; int reg_size_log2; if (format & kPrintRegAsQVector) { reg_size_log2 = kQRegSizeLog2; } else if (format & kPrintRegAsDVector) { reg_size_log2 = kDRegSizeLog2; } else { // Scalar types. reg_size_log2 = lane_size_log2; } int lane_count = 1 << (reg_size_log2 - lane_size_log2); int lane_size = 1 << lane_size_log2; // The template for vector types: // "# v{code}: 0x{rawbits} (..., {value}, ...)". // The template for scalar types: // "# v{code}: 0x{rawbits} ({reg}:{value})". // The values in parentheses after the bit representations are floating-point // interpretations. They are displayed only if the kPrintVRegAsFP bit is set. PrintVRegisterRawHelper(code); if (format & kPrintRegAsFP) { PrintVRegisterFPHelper(code, lane_size, lane_count); } fprintf(stream_, "\n"); } void Simulator::PrintSystemRegister(SystemRegister id) { switch (id) { case NZCV: fprintf(stream_, "# %sNZCV: %sN:%d Z:%d C:%d V:%d%s\n", clr_flag_name, clr_flag_value, nzcv().N(), nzcv().Z(), nzcv().C(), nzcv().V(), clr_normal); break; case FPCR: { static const char* rmode[] = { "0b00 (Round to Nearest)", "0b01 (Round towards Plus Infinity)", "0b10 (Round towards Minus Infinity)", "0b11 (Round towards Zero)"}; DCHECK(fpcr().RMode() < arraysize(rmode)); fprintf(stream_, "# %sFPCR: %sAHP:%d DN:%d FZ:%d RMode:%s%s\n", clr_flag_name, clr_flag_value, fpcr().AHP(), fpcr().DN(), fpcr().FZ(), rmode[fpcr().RMode()], clr_normal); break; } default: UNREACHABLE(); } } void Simulator::PrintRead(uintptr_t address, unsigned reg_code, PrintRegisterFormat format) { registers_[reg_code].NotifyRegisterLogged(); USE(format); // The template is "# {reg}: 0x{value} <- {address}". PrintRegisterRawHelper(reg_code, Reg31IsZeroRegister); fprintf(stream_, " <- %s0x%016" PRIxPTR "%s\n", clr_memory_address, address, clr_normal); } void Simulator::PrintVRead(uintptr_t address, unsigned reg_code, PrintRegisterFormat format, unsigned lane) { vregisters_[reg_code].NotifyRegisterLogged(); // The template is "# v{code}: 0x{rawbits} <- address". PrintVRegisterRawHelper(reg_code); if (format & kPrintRegAsFP) { PrintVRegisterFPHelper(reg_code, GetPrintRegLaneSizeInBytes(format), GetPrintRegLaneCount(format), lane); } fprintf(stream_, " <- %s0x%016" PRIxPTR "%s\n", clr_memory_address, address, clr_normal); } void Simulator::PrintWrite(uintptr_t address, unsigned reg_code, PrintRegisterFormat format) { DCHECK_EQ(GetPrintRegLaneCount(format), 1U); // The template is "# v{code}: 0x{value} -> {address}". To keep the trace tidy // and readable, the value is aligned with the values in the register trace. PrintRegisterRawHelper(reg_code, Reg31IsZeroRegister, GetPrintRegSizeInBytes(format)); fprintf(stream_, " -> %s0x%016" PRIxPTR "%s\n", clr_memory_address, address, clr_normal); } void Simulator::PrintVWrite(uintptr_t address, unsigned reg_code, PrintRegisterFormat format, unsigned lane) { // The templates: // "# v{code}: 0x{rawbits} -> {address}" // "# v{code}: 0x{rawbits} (..., {value}, ...) -> {address}". // "# v{code}: 0x{rawbits} ({reg}:{value}) -> {address}" // Because this trace doesn't represent a change to the source register's // value, only the relevant part of the value is printed. To keep the trace // tidy and readable, the raw value is aligned with the other values in the // register trace. int lane_count = GetPrintRegLaneCount(format); int lane_size = GetPrintRegLaneSizeInBytes(format); int reg_size = GetPrintRegSizeInBytes(format); PrintVRegisterRawHelper(reg_code, reg_size, lane_size * lane); if (format & kPrintRegAsFP) { PrintVRegisterFPHelper(reg_code, lane_size, lane_count, lane); } fprintf(stream_, " -> %s0x%016" PRIxPTR "%s\n", clr_memory_address, address, clr_normal); } // Visitors--------------------------------------------------------------------- void Simulator::VisitUnimplemented(Instruction* instr) { fprintf(stream_, "Unimplemented instruction at %p: 0x%08" PRIx32 "\n", reinterpret_cast<void*>(instr), instr->InstructionBits()); UNIMPLEMENTED(); } void Simulator::VisitUnallocated(Instruction* instr) { fprintf(stream_, "Unallocated instruction at %p: 0x%08" PRIx32 "\n", reinterpret_cast<void*>(instr), instr->InstructionBits()); UNIMPLEMENTED(); } void Simulator::VisitPCRelAddressing(Instruction* instr) { switch (instr->Mask(PCRelAddressingMask)) { case ADR: set_reg(instr->Rd(), instr->ImmPCOffsetTarget()); break; case ADRP: // Not implemented in the assembler. UNIMPLEMENTED(); default: UNREACHABLE(); } } void Simulator::VisitUnconditionalBranch(Instruction* instr) { switch (instr->Mask(UnconditionalBranchMask)) { case BL: set_lr(instr->following()); V8_FALLTHROUGH; case B: set_pc(instr->ImmPCOffsetTarget()); break; default: UNREACHABLE(); } } void Simulator::VisitConditionalBranch(Instruction* instr) { DCHECK(instr->Mask(ConditionalBranchMask) == B_cond); if (ConditionPassed(static_cast<Condition>(instr->ConditionBranch()))) { set_pc(instr->ImmPCOffsetTarget()); } } Simulator::BType Simulator::GetBTypeFromInstruction( const Instruction* instr) const { switch (instr->Mask(UnconditionalBranchToRegisterMask)) { case BLR: return BranchAndLink; case BR: if (!PcIsInGuardedPage() || (instr->Rn() == 16) || (instr->Rn() == 17)) { return BranchFromUnguardedOrToIP; } return BranchFromGuardedNotToIP; } return DefaultBType; } void Simulator::VisitUnconditionalBranchToRegister(Instruction* instr) { Instruction* target = reg<Instruction*>(instr->Rn()); switch (instr->Mask(UnconditionalBranchToRegisterMask)) { case BLR: { set_lr(instr->following()); if (instr->Rn() == 31) { // BLR XZR is used as a guard for the constant pool. We should never hit // this, but if we do trap to allow debugging. Debug(); } V8_FALLTHROUGH; } case BR: case RET: set_pc(target); break; default: UNIMPLEMENTED(); } set_btype(GetBTypeFromInstruction(instr)); } void Simulator::VisitTestBranch(Instruction* instr) { unsigned bit_pos = (instr->ImmTestBranchBit5() << 5) | instr->ImmTestBranchBit40(); bool take_branch = ((xreg(instr->Rt()) & (1ULL << bit_pos)) == 0); switch (instr->Mask(TestBranchMask)) { case TBZ: break; case TBNZ: take_branch = !take_branch; break; default: UNIMPLEMENTED(); } if (take_branch) { set_pc(instr->ImmPCOffsetTarget()); } } void Simulator::VisitCompareBranch(Instruction* instr) { unsigned rt = instr->Rt(); bool take_branch = false; switch (instr->Mask(CompareBranchMask)) { case CBZ_w: take_branch = (wreg(rt) == 0); break; case CBZ_x: take_branch = (xreg(rt) == 0); break; case CBNZ_w: take_branch = (wreg(rt) != 0); break; case CBNZ_x: take_branch = (xreg(rt) != 0); break; default: UNIMPLEMENTED(); } if (take_branch) { set_pc(instr->ImmPCOffsetTarget()); } } template <typename T> void Simulator::AddSubHelper(Instruction* instr, T op2) { // Use unsigned types to avoid implementation-defined overflow behaviour. static_assert(std::is_unsigned<T>::value, "operands must be unsigned"); bool set_flags = instr->FlagsUpdate(); T new_val = 0; Instr operation = instr->Mask(AddSubOpMask); switch (operation) { case ADD: case ADDS: { new_val = AddWithCarry<T>(set_flags, reg<T>(instr->Rn(), instr->RnMode()), op2); break; } case SUB: case SUBS: { new_val = AddWithCarry<T>(set_flags, reg<T>(instr->Rn(), instr->RnMode()), ~op2, 1); break; } default: UNREACHABLE(); } set_reg<T>(instr->Rd(), new_val, instr->RdMode()); } void Simulator::VisitAddSubShifted(Instruction* instr) { Shift shift_type = static_cast<Shift>(instr->ShiftDP()); unsigned shift_amount = instr->ImmDPShift(); if (instr->SixtyFourBits()) { uint64_t op2 = ShiftOperand(xreg(instr->Rm()), shift_type, shift_amount); AddSubHelper(instr, op2); } else { uint32_t op2 = ShiftOperand(wreg(instr->Rm()), shift_type, shift_amount); AddSubHelper(instr, op2); } } void Simulator::VisitAddSubImmediate(Instruction* instr) { int64_t op2 = instr->ImmAddSub() << ((instr->ShiftAddSub() == 1) ? 12 : 0); if (instr->SixtyFourBits()) { AddSubHelper(instr, static_cast<uint64_t>(op2)); } else { AddSubHelper(instr, static_cast<uint32_t>(op2)); } } void Simulator::VisitAddSubExtended(Instruction* instr) { Extend ext = static_cast<Extend>(instr->ExtendMode()); unsigned left_shift = instr->ImmExtendShift(); if (instr->SixtyFourBits()) { uint64_t op2 = ExtendValue(xreg(instr->Rm()), ext, left_shift); AddSubHelper(instr, op2); } else { uint32_t op2 = ExtendValue(wreg(instr->Rm()), ext, left_shift); AddSubHelper(instr, op2); } } void Simulator::VisitAddSubWithCarry(Instruction* instr) { if (instr->SixtyFourBits()) { AddSubWithCarry<uint64_t>(instr); } else { AddSubWithCarry<uint32_t>(instr); } } void Simulator::VisitLogicalShifted(Instruction* instr) { Shift shift_type = static_cast<Shift>(instr->ShiftDP()); unsigned shift_amount = instr->ImmDPShift(); if (instr->SixtyFourBits()) { uint64_t op2 = ShiftOperand(xreg(instr->Rm()), shift_type, shift_amount); op2 = (instr->Mask(NOT) == NOT) ? ~op2 : op2; LogicalHelper(instr, op2); } else { uint32_t op2 = ShiftOperand(wreg(instr->Rm()), shift_type, shift_amount); op2 = (instr->Mask(NOT) == NOT) ? ~op2 : op2; LogicalHelper(instr, op2); } } void Simulator::VisitLogicalImmediate(Instruction* instr) { if (instr->SixtyFourBits()) { LogicalHelper(instr, static_cast<uint64_t>(instr->ImmLogical())); } else { LogicalHelper(instr, static_cast<uint32_t>(instr->ImmLogical())); } } template <typename T> void Simulator::LogicalHelper(Instruction* instr, T op2) { T op1 = reg<T>(instr->Rn()); T result = 0; bool update_flags = false; // Switch on the logical operation, stripping out the NOT bit, as it has a // different meaning for logical immediate instructions. switch (instr->Mask(LogicalOpMask & ~NOT)) { case ANDS: update_flags = true; V8_FALLTHROUGH; case AND: result = op1 & op2; break; case ORR: result = op1 | op2; break; case EOR: result = op1 ^ op2; break; default: UNIMPLEMENTED(); } if (update_flags) { nzcv().SetN(CalcNFlag(result)); nzcv().SetZ(CalcZFlag(result)); nzcv().SetC(0); nzcv().SetV(0); LogSystemRegister(NZCV); } set_reg<T>(instr->Rd(), result, instr->RdMode()); } void Simulator::VisitConditionalCompareRegister(Instruction* instr) { if (instr->SixtyFourBits()) { ConditionalCompareHelper(instr, static_cast<uint64_t>(xreg(instr->Rm()))); } else { ConditionalCompareHelper(instr, static_cast<uint32_t>(wreg(instr->Rm()))); } } void Simulator::VisitConditionalCompareImmediate(Instruction* instr) { if (instr->SixtyFourBits()) { ConditionalCompareHelper(instr, static_cast<uint64_t>(instr->ImmCondCmp())); } else { ConditionalCompareHelper(instr, static_cast<uint32_t>(instr->ImmCondCmp())); } } template <typename T> void Simulator::ConditionalCompareHelper(Instruction* instr, T op2) { // Use unsigned types to avoid implementation-defined overflow behaviour. static_assert(std::is_unsigned<T>::value, "operands must be unsigned"); T op1 = reg<T>(instr->Rn()); if (ConditionPassed(static_cast<Condition>(instr->Condition()))) { // If the condition passes, set the status flags to the result of comparing // the operands. if (instr->Mask(ConditionalCompareMask) == CCMP) { AddWithCarry<T>(true, op1, ~op2, 1); } else { DCHECK(instr->Mask(ConditionalCompareMask) == CCMN); AddWithCarry<T>(true, op1, op2, 0); } } else { // If the condition fails, set the status flags to the nzcv immediate. nzcv().SetFlags(instr->Nzcv()); LogSystemRegister(NZCV); } } void Simulator::VisitLoadStoreUnsignedOffset(Instruction* instr) { int offset = instr->ImmLSUnsigned() << instr->SizeLS(); LoadStoreHelper(instr, offset, Offset); } void Simulator::VisitLoadStoreUnscaledOffset(Instruction* instr) { LoadStoreHelper(instr, instr->ImmLS(), Offset); } void Simulator::VisitLoadStorePreIndex(Instruction* instr) { LoadStoreHelper(instr, instr->ImmLS(), PreIndex); } void Simulator::VisitLoadStorePostIndex(Instruction* instr) { LoadStoreHelper(instr, instr->ImmLS(), PostIndex); } void Simulator::VisitLoadStoreRegisterOffset(Instruction* instr) { Extend ext = static_cast<Extend>(instr->ExtendMode()); DCHECK((ext == UXTW) || (ext == UXTX) || (ext == SXTW) || (ext == SXTX)); unsigned shift_amount = instr->ImmShiftLS() * instr->SizeLS(); int64_t offset = ExtendValue(xreg(instr->Rm()), ext, shift_amount); LoadStoreHelper(instr, offset, Offset); } void Simulator::LoadStoreHelper(Instruction* instr, int64_t offset, AddrMode addrmode) { unsigned srcdst = instr->Rt(); unsigned addr_reg = instr->Rn(); uintptr_t address = LoadStoreAddress(addr_reg, offset, addrmode); uintptr_t stack = 0; unsigned access_size = 1 << instr->SizeLS(); // First, check whether the memory is accessible (for wasm trap handling). if (!ProbeMemory(address, access_size)) return; { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); if (instr->IsLoad()) { local_monitor_.NotifyLoad(); } else { local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); } } // Handle the writeback for stores before the store. On a CPU the writeback // and the store are atomic, but when running on the simulator it is possible // to be interrupted in between. The simulator is not thread safe and V8 does // not require it to be to run JavaScript therefore the profiler may sample // the "simulated" CPU in the middle of load/store with writeback. The code // below ensures that push operations are safe even when interrupted: the // stack pointer will be decremented before adding an element to the stack. if (instr->IsStore()) { LoadStoreWriteBack(addr_reg, offset, addrmode); // For store the address post writeback is used to check access below the // stack. stack = sp(); } LoadStoreOp op = static_cast<LoadStoreOp>(instr->Mask(LoadStoreMask)); switch (op) { // Use _no_log variants to suppress the register trace (LOG_REGS, // LOG_VREGS). We will print a more detailed log. case LDRB_w: set_wreg_no_log(srcdst, MemoryRead<uint8_t>(address)); break; case LDRH_w: set_wreg_no_log(srcdst, MemoryRead<uint16_t>(address)); break; case LDR_w: set_wreg_no_log(srcdst, MemoryRead<uint32_t>(address)); break; case LDR_x: set_xreg_no_log(srcdst, MemoryRead<uint64_t>(address)); break; case LDRSB_w: set_wreg_no_log(srcdst, MemoryRead<int8_t>(address)); break; case LDRSH_w: set_wreg_no_log(srcdst, MemoryRead<int16_t>(address)); break; case LDRSB_x: set_xreg_no_log(srcdst, MemoryRead<int8_t>(address)); break; case LDRSH_x: set_xreg_no_log(srcdst, MemoryRead<int16_t>(address)); break; case LDRSW_x: set_xreg_no_log(srcdst, MemoryRead<int32_t>(address)); break; case LDR_b: set_breg_no_log(srcdst, MemoryRead<uint8_t>(address)); break; case LDR_h: set_hreg_no_log(srcdst, MemoryRead<uint16_t>(address)); break; case LDR_s: set_sreg_no_log(srcdst, MemoryRead<float>(address)); break; case LDR_d: set_dreg_no_log(srcdst, MemoryRead<double>(address)); break; case LDR_q: set_qreg_no_log(srcdst, MemoryRead<qreg_t>(address)); break; case STRB_w: MemoryWrite<uint8_t>(address, wreg(srcdst)); break; case STRH_w: MemoryWrite<uint16_t>(address, wreg(srcdst)); break; case STR_w: MemoryWrite<uint32_t>(address, wreg(srcdst)); break; case STR_x: MemoryWrite<uint64_t>(address, xreg(srcdst)); break; case STR_b: MemoryWrite<uint8_t>(address, breg(srcdst)); break; case STR_h: MemoryWrite<uint16_t>(address, hreg(srcdst)); break; case STR_s: MemoryWrite<float>(address, sreg(srcdst)); break; case STR_d: MemoryWrite<double>(address, dreg(srcdst)); break; case STR_q: MemoryWrite<qreg_t>(address, qreg(srcdst)); break; default: UNIMPLEMENTED(); } // Print a detailed trace (including the memory address) instead of the basic // register:value trace generated by set_*reg(). if (instr->IsLoad()) { if ((op == LDR_s) || (op == LDR_d)) { LogVRead(address, srcdst, GetPrintRegisterFormatForSizeFP(access_size)); } else if ((op == LDR_b) || (op == LDR_h) || (op == LDR_q)) { LogVRead(address, srcdst, GetPrintRegisterFormatForSize(access_size)); } else { LogRead(address, srcdst, GetPrintRegisterFormatForSize(access_size)); } } else { if ((op == STR_s) || (op == STR_d)) { LogVWrite(address, srcdst, GetPrintRegisterFormatForSizeFP(access_size)); } else if ((op == STR_b) || (op == STR_h) || (op == STR_q)) { LogVWrite(address, srcdst, GetPrintRegisterFormatForSize(access_size)); } else { LogWrite(address, srcdst, GetPrintRegisterFormatForSize(access_size)); } } // Handle the writeback for loads after the load to ensure safe pop // operation even when interrupted in the middle of it. The stack pointer // is only updated after the load so pop(fp) will never break the invariant // sp <= fp expected while walking the stack in the sampler. if (instr->IsLoad()) { // For loads the address pre writeback is used to check access below the // stack. stack = sp(); LoadStoreWriteBack(addr_reg, offset, addrmode); } // Accesses below the stack pointer (but above the platform stack limit) are // not allowed in the ABI. CheckMemoryAccess(address, stack); } void Simulator::VisitLoadStorePairOffset(Instruction* instr) { LoadStorePairHelper(instr, Offset); } void Simulator::VisitLoadStorePairPreIndex(Instruction* instr) { LoadStorePairHelper(instr, PreIndex); } void Simulator::VisitLoadStorePairPostIndex(Instruction* instr) { LoadStorePairHelper(instr, PostIndex); } void Simulator::LoadStorePairHelper(Instruction* instr, AddrMode addrmode) { unsigned rt = instr->Rt(); unsigned rt2 = instr->Rt2(); unsigned addr_reg = instr->Rn(); size_t access_size = 1ULL << instr->SizeLSPair(); int64_t offset = instr->ImmLSPair() * access_size; uintptr_t address = LoadStoreAddress(addr_reg, offset, addrmode); uintptr_t address2 = address + access_size; uintptr_t stack = 0; { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); if (instr->IsLoad()) { local_monitor_.NotifyLoad(); } else { local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); } } // Handle the writeback for stores before the store. On a CPU the writeback // and the store are atomic, but when running on the simulator it is possible // to be interrupted in between. The simulator is not thread safe and V8 does // not require it to be to run JavaScript therefore the profiler may sample // the "simulated" CPU in the middle of load/store with writeback. The code // below ensures that push operations are safe even when interrupted: the // stack pointer will be decremented before adding an element to the stack. if (instr->IsStore()) { LoadStoreWriteBack(addr_reg, offset, addrmode); // For store the address post writeback is used to check access below the // stack. stack = sp(); } LoadStorePairOp op = static_cast<LoadStorePairOp>(instr->Mask(LoadStorePairMask)); // 'rt' and 'rt2' can only be aliased for stores. DCHECK(((op & LoadStorePairLBit) == 0) || (rt != rt2)); switch (op) { // Use _no_log variants to suppress the register trace (LOG_REGS, // LOG_VREGS). We will print a more detailed log. case LDP_w: { DCHECK_EQ(access_size, static_cast<unsigned>(kWRegSize)); set_wreg_no_log(rt, MemoryRead<uint32_t>(address)); set_wreg_no_log(rt2, MemoryRead<uint32_t>(address2)); break; } case LDP_s: { DCHECK_EQ(access_size, static_cast<unsigned>(kSRegSize)); set_sreg_no_log(rt, MemoryRead<float>(address)); set_sreg_no_log(rt2, MemoryRead<float>(address2)); break; } case LDP_x: { DCHECK_EQ(access_size, static_cast<unsigned>(kXRegSize)); set_xreg_no_log(rt, MemoryRead<uint64_t>(address)); set_xreg_no_log(rt2, MemoryRead<uint64_t>(address2)); break; } case LDP_d: { DCHECK_EQ(access_size, static_cast<unsigned>(kDRegSize)); set_dreg_no_log(rt, MemoryRead<double>(address)); set_dreg_no_log(rt2, MemoryRead<double>(address2)); break; } case LDP_q: { DCHECK_EQ(access_size, static_cast<unsigned>(kQRegSize)); set_qreg(rt, MemoryRead<qreg_t>(address), NoRegLog); set_qreg(rt2, MemoryRead<qreg_t>(address2), NoRegLog); break; } case LDPSW_x: { DCHECK_EQ(access_size, static_cast<unsigned>(kWRegSize)); set_xreg_no_log(rt, MemoryRead<int32_t>(address)); set_xreg_no_log(rt2, MemoryRead<int32_t>(address2)); break; } case STP_w: { DCHECK_EQ(access_size, static_cast<unsigned>(kWRegSize)); MemoryWrite<uint32_t>(address, wreg(rt)); MemoryWrite<uint32_t>(address2, wreg(rt2)); break; } case STP_s: { DCHECK_EQ(access_size, static_cast<unsigned>(kSRegSize)); MemoryWrite<float>(address, sreg(rt)); MemoryWrite<float>(address2, sreg(rt2)); break; } case STP_x: { DCHECK_EQ(access_size, static_cast<unsigned>(kXRegSize)); MemoryWrite<uint64_t>(address, xreg(rt)); MemoryWrite<uint64_t>(address2, xreg(rt2)); break; } case STP_d: { DCHECK_EQ(access_size, static_cast<unsigned>(kDRegSize)); MemoryWrite<double>(address, dreg(rt)); MemoryWrite<double>(address2, dreg(rt2)); break; } case STP_q: { DCHECK_EQ(access_size, static_cast<unsigned>(kQRegSize)); MemoryWrite<qreg_t>(address, qreg(rt)); MemoryWrite<qreg_t>(address2, qreg(rt2)); break; } default: UNREACHABLE(); } // Print a detailed trace (including the memory address) instead of the basic // register:value trace generated by set_*reg(). if (instr->IsLoad()) { if ((op == LDP_s) || (op == LDP_d)) { LogVRead(address, rt, GetPrintRegisterFormatForSizeFP(access_size)); LogVRead(address2, rt2, GetPrintRegisterFormatForSizeFP(access_size)); } else if (op == LDP_q) { LogVRead(address, rt, GetPrintRegisterFormatForSize(access_size)); LogVRead(address2, rt2, GetPrintRegisterFormatForSize(access_size)); } else { LogRead(address, rt, GetPrintRegisterFormatForSize(access_size)); LogRead(address2, rt2, GetPrintRegisterFormatForSize(access_size)); } } else { if ((op == STP_s) || (op == STP_d)) { LogVWrite(address, rt, GetPrintRegisterFormatForSizeFP(access_size)); LogVWrite(address2, rt2, GetPrintRegisterFormatForSizeFP(access_size)); } else if (op == STP_q) { LogVWrite(address, rt, GetPrintRegisterFormatForSize(access_size)); LogVWrite(address2, rt2, GetPrintRegisterFormatForSize(access_size)); } else { LogWrite(address, rt, GetPrintRegisterFormatForSize(access_size)); LogWrite(address2, rt2, GetPrintRegisterFormatForSize(access_size)); } } // Handle the writeback for loads after the load to ensure safe pop // operation even when interrupted in the middle of it. The stack pointer // is only updated after the load so pop(fp) will never break the invariant // sp <= fp expected while walking the stack in the sampler. if (instr->IsLoad()) { // For loads the address pre writeback is used to check access below the // stack. stack = sp(); LoadStoreWriteBack(addr_reg, offset, addrmode); } // Accesses below the stack pointer (but above the platform stack limit) are // not allowed in the ABI. CheckMemoryAccess(address, stack); } void Simulator::VisitLoadLiteral(Instruction* instr) { uintptr_t address = instr->LiteralAddress(); unsigned rt = instr->Rt(); { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); local_monitor_.NotifyLoad(); } switch (instr->Mask(LoadLiteralMask)) { // Use _no_log variants to suppress the register trace (LOG_REGS, // LOG_VREGS), then print a more detailed log. case LDR_w_lit: set_wreg_no_log(rt, MemoryRead<uint32_t>(address)); LogRead(address, rt, kPrintWReg); break; case LDR_x_lit: set_xreg_no_log(rt, MemoryRead<uint64_t>(address)); LogRead(address, rt, kPrintXReg); break; case LDR_s_lit: set_sreg_no_log(rt, MemoryRead<float>(address)); LogVRead(address, rt, kPrintSReg); break; case LDR_d_lit: set_dreg_no_log(rt, MemoryRead<double>(address)); LogVRead(address, rt, kPrintDReg); break; default: UNREACHABLE(); } } uintptr_t Simulator::LoadStoreAddress(unsigned addr_reg, int64_t offset, AddrMode addrmode) { const unsigned kSPRegCode = kSPRegInternalCode & kRegCodeMask; uint64_t address = xreg(addr_reg, Reg31IsStackPointer); if ((addr_reg == kSPRegCode) && ((address % 16) != 0)) { // When the base register is SP the stack pointer is required to be // quadword aligned prior to the address calculation and write-backs. // Misalignment will cause a stack alignment fault. FATAL("ALIGNMENT EXCEPTION"); } if ((addrmode == Offset) || (addrmode == PreIndex)) { address += offset; } return address; } void Simulator::LoadStoreWriteBack(unsigned addr_reg, int64_t offset, AddrMode addrmode) { if ((addrmode == PreIndex) || (addrmode == PostIndex)) { DCHECK_NE(offset, 0); uint64_t address = xreg(addr_reg, Reg31IsStackPointer); set_reg(addr_reg, address + offset, Reg31IsStackPointer); } } Simulator::TransactionSize Simulator::get_transaction_size(unsigned size) { switch (size) { case 0: return TransactionSize::None; case 1: return TransactionSize::Byte; case 2: return TransactionSize::HalfWord; case 4: return TransactionSize::Word; case 8: return TransactionSize::DoubleWord; default: UNREACHABLE(); } } void Simulator::VisitLoadStoreAcquireRelease(Instruction* instr) { unsigned rt = instr->Rt(); unsigned rn = instr->Rn(); LoadStoreAcquireReleaseOp op = static_cast<LoadStoreAcquireReleaseOp>( instr->Mask(LoadStoreAcquireReleaseMask)); switch (op) { case CAS_w: case CASA_w: case CASL_w: case CASAL_w: CompareAndSwapHelper<uint32_t>(instr); return; case CAS_x: case CASA_x: case CASL_x: case CASAL_x: CompareAndSwapHelper<uint64_t>(instr); return; case CASB: case CASAB: case CASLB: case CASALB: CompareAndSwapHelper<uint8_t>(instr); return; case CASH: case CASAH: case CASLH: case CASALH: CompareAndSwapHelper<uint16_t>(instr); return; case CASP_w: case CASPA_w: case CASPL_w: case CASPAL_w: CompareAndSwapPairHelper<uint32_t>(instr); return; case CASP_x: case CASPA_x: case CASPL_x: case CASPAL_x: CompareAndSwapPairHelper<uint64_t>(instr); return; default: break; } int32_t is_acquire_release = instr->LoadStoreXAcquireRelease(); int32_t is_exclusive = (instr->LoadStoreXNotExclusive() == 0); int32_t is_load = instr->LoadStoreXLoad(); int32_t is_pair = instr->LoadStoreXPair(); USE(is_acquire_release); USE(is_pair); DCHECK_NE(is_acquire_release, 0); // Non-acquire/release unimplemented. DCHECK_EQ(is_pair, 0); // Pair unimplemented. unsigned access_size = 1 << instr->LoadStoreXSizeLog2(); uintptr_t address = LoadStoreAddress(rn, 0, AddrMode::Offset); DCHECK_EQ(address % access_size, 0); // First, check whether the memory is accessible (for wasm trap handling). if (!ProbeMemory(address, access_size)) return; base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); if (is_load != 0) { if (is_exclusive) { local_monitor_.NotifyLoadExcl(address, get_transaction_size(access_size)); GlobalMonitor::Get()->NotifyLoadExcl_Locked(address, &global_monitor_processor_); } else { local_monitor_.NotifyLoad(); } switch (op) { case LDAR_b: case LDAXR_b: set_wreg_no_log(rt, MemoryRead<uint8_t>(address)); break; case LDAR_h: case LDAXR_h: set_wreg_no_log(rt, MemoryRead<uint16_t>(address)); break; case LDAR_w: case LDAXR_w: set_wreg_no_log(rt, MemoryRead<uint32_t>(address)); break; case LDAR_x: case LDAXR_x: set_xreg_no_log(rt, MemoryRead<uint64_t>(address)); break; default: UNIMPLEMENTED(); } LogRead(address, rt, GetPrintRegisterFormatForSize(access_size)); } else { if (is_exclusive) { unsigned rs = instr->Rs(); DCHECK_NE(rs, rt); DCHECK_NE(rs, rn); if (local_monitor_.NotifyStoreExcl(address, get_transaction_size(access_size)) && GlobalMonitor::Get()->NotifyStoreExcl_Locked( address, &global_monitor_processor_)) { switch (op) { case STLXR_b: MemoryWrite<uint8_t>(address, wreg(rt)); break; case STLXR_h: MemoryWrite<uint16_t>(address, wreg(rt)); break; case STLXR_w: MemoryWrite<uint32_t>(address, wreg(rt)); break; case STLXR_x: MemoryWrite<uint64_t>(address, xreg(rt)); break; default: UNIMPLEMENTED(); } LogWrite(address, rt, GetPrintRegisterFormatForSize(access_size)); set_wreg(rs, 0); } else { set_wreg(rs, 1); } } else { local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); switch (op) { case STLR_b: MemoryWrite<uint8_t>(address, wreg(rt)); break; case STLR_h: MemoryWrite<uint16_t>(address, wreg(rt)); break; case STLR_w: MemoryWrite<uint32_t>(address, wreg(rt)); break; case STLR_x: MemoryWrite<uint64_t>(address, xreg(rt)); break; default: UNIMPLEMENTED(); } } } } template <typename T> void Simulator::CompareAndSwapHelper(const Instruction* instr) { unsigned rs = instr->Rs(); unsigned rt = instr->Rt(); unsigned rn = instr->Rn(); unsigned element_size = sizeof(T); uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer); // First, check whether the memory is accessible (for wasm trap handling). if (!ProbeMemory(address, element_size)) return; bool is_acquire = instr->Bit(22) == 1; bool is_release = instr->Bit(15) == 1; T comparevalue = reg<T>(rs); T newvalue = reg<T>(rt); // The architecture permits that the data read clears any exclusive monitors // associated with that location, even if the compare subsequently fails. local_monitor_.NotifyLoad(); T data = MemoryRead<T>(address); if (is_acquire) { // Approximate load-acquire by issuing a full barrier after the load. std::atomic_thread_fence(std::memory_order_seq_cst); } if (data == comparevalue) { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); if (is_release) { local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); // Approximate store-release by issuing a full barrier before the store. std::atomic_thread_fence(std::memory_order_seq_cst); } MemoryWrite<T>(address, newvalue); LogWrite(address, rt, GetPrintRegisterFormatForSize(element_size)); } set_reg<T>(rs, data); LogRead(address, rs, GetPrintRegisterFormatForSize(element_size)); } template <typename T> void Simulator::CompareAndSwapPairHelper(const Instruction* instr) { DCHECK((sizeof(T) == 4) || (sizeof(T) == 8)); unsigned rs = instr->Rs(); unsigned rt = instr->Rt(); unsigned rn = instr->Rn(); DCHECK((rs % 2 == 0) && (rt % 2 == 0)); unsigned element_size = sizeof(T); uint64_t address = reg<uint64_t>(rn, Reg31IsStackPointer); uint64_t address2 = address + element_size; // First, check whether the memory is accessible (for wasm trap handling). if (!ProbeMemory(address, element_size)) return; if (!ProbeMemory(address2, element_size)) return; bool is_acquire = instr->Bit(22) == 1; bool is_release = instr->Bit(15) == 1; T comparevalue_high = reg<T>(rs + 1); T comparevalue_low = reg<T>(rs); T newvalue_high = reg<T>(rt + 1); T newvalue_low = reg<T>(rt); // The architecture permits that the data read clears any exclusive monitors // associated with that location, even if the compare subsequently fails. local_monitor_.NotifyLoad(); T data_low = MemoryRead<T>(address); T data_high = MemoryRead<T>(address2); if (is_acquire) { // Approximate load-acquire by issuing a full barrier after the load. std::atomic_thread_fence(std::memory_order_seq_cst); } bool same = (data_high == comparevalue_high) && (data_low == comparevalue_low); if (same) { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); if (is_release) { local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); // Approximate store-release by issuing a full barrier before the store. std::atomic_thread_fence(std::memory_order_seq_cst); } MemoryWrite<T>(address, newvalue_low); MemoryWrite<T>(address2, newvalue_high); } set_reg<T>(rs + 1, data_high); set_reg<T>(rs, data_low); PrintRegisterFormat format = GetPrintRegisterFormatForSize(element_size); LogRead(address, rs, format); LogRead(address2, rs + 1, format); if (same) { LogWrite(address, rt, format); LogWrite(address2, rt + 1, format); } } template <typename T> void Simulator::AtomicMemorySimpleHelper(const Instruction* instr) { unsigned rs = instr->Rs(); unsigned rt = instr->Rt(); unsigned rn = instr->Rn(); bool is_acquire = (instr->Bit(23) == 1) && (rt != kZeroRegCode); bool is_release = instr->Bit(22) == 1; unsigned element_size = sizeof(T); uint64_t address = xreg(rn, Reg31IsStackPointer); DCHECK_EQ(address % element_size, 0); // First, check whether the memory is accessible (for wasm trap handling). if (!ProbeMemory(address, element_size)) return; local_monitor_.NotifyLoad(); T value = reg<T>(rs); T data = MemoryRead<T>(address); if (is_acquire) { // Approximate load-acquire by issuing a full barrier after the load. std::atomic_thread_fence(std::memory_order_seq_cst); } T result = 0; switch (instr->Mask(AtomicMemorySimpleOpMask)) { case LDADDOp: result = data + value; break; case LDCLROp: DCHECK(!std::numeric_limits<T>::is_signed); result = data & ~value; break; case LDEOROp: DCHECK(!std::numeric_limits<T>::is_signed); result = data ^ value; break; case LDSETOp: DCHECK(!std::numeric_limits<T>::is_signed); result = data | value; break; // Signed/Unsigned difference is done via the templated type T. case LDSMAXOp: case LDUMAXOp: result = (data > value) ? data : value; break; case LDSMINOp: case LDUMINOp: result = (data > value) ? value : data; break; } if (is_release) { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); // Approximate store-release by issuing a full barrier before the store. std::atomic_thread_fence(std::memory_order_seq_cst); } MemoryWrite<T>(address, result); set_reg<T>(rt, data); PrintRegisterFormat format = GetPrintRegisterFormatForSize(element_size); LogRead(address, rt, format); LogWrite(address, rs, format); } template <typename T> void Simulator::AtomicMemorySwapHelper(const Instruction* instr) { unsigned rs = instr->Rs(); unsigned rt = instr->Rt(); unsigned rn = instr->Rn(); bool is_acquire = (instr->Bit(23) == 1) && (rt != kZeroRegCode); bool is_release = instr->Bit(22) == 1; unsigned element_size = sizeof(T); uint64_t address = xreg(rn, Reg31IsStackPointer); // First, check whether the memory is accessible (for wasm trap handling). if (!ProbeMemory(address, element_size)) return; local_monitor_.NotifyLoad(); T data = MemoryRead<T>(address); if (is_acquire) { // Approximate load-acquire by issuing a full barrier after the load. std::atomic_thread_fence(std::memory_order_seq_cst); } if (is_release) { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); // Approximate store-release by issuing a full barrier before the store. std::atomic_thread_fence(std::memory_order_seq_cst); } MemoryWrite<T>(address, reg<T>(rs)); set_reg<T>(rt, data); PrintRegisterFormat format = GetPrintRegisterFormatForSize(element_size); LogRead(address, rt, format); LogWrite(address, rs, format); } #define ATOMIC_MEMORY_SIMPLE_UINT_LIST(V) \ V(LDADD) \ V(LDCLR) \ V(LDEOR) \ V(LDSET) \ V(LDUMAX) \ V(LDUMIN) #define ATOMIC_MEMORY_SIMPLE_INT_LIST(V) \ V(LDSMAX) \ V(LDSMIN) void Simulator::VisitAtomicMemory(Instruction* instr) { switch (instr->Mask(AtomicMemoryMask)) { // clang-format off #define SIM_FUNC_B(A) \ case A##B: \ case A##AB: \ case A##LB: \ case A##ALB: #define SIM_FUNC_H(A) \ case A##H: \ case A##AH: \ case A##LH: \ case A##ALH: #define SIM_FUNC_w(A) \ case A##_w: \ case A##A_w: \ case A##L_w: \ case A##AL_w: #define SIM_FUNC_x(A) \ case A##_x: \ case A##A_x: \ case A##L_x: \ case A##AL_x: ATOMIC_MEMORY_SIMPLE_UINT_LIST(SIM_FUNC_B) AtomicMemorySimpleHelper<uint8_t>(instr); break; ATOMIC_MEMORY_SIMPLE_INT_LIST(SIM_FUNC_B) AtomicMemorySimpleHelper<int8_t>(instr); break; ATOMIC_MEMORY_SIMPLE_UINT_LIST(SIM_FUNC_H) AtomicMemorySimpleHelper<uint16_t>(instr); break; ATOMIC_MEMORY_SIMPLE_INT_LIST(SIM_FUNC_H) AtomicMemorySimpleHelper<int16_t>(instr); break; ATOMIC_MEMORY_SIMPLE_UINT_LIST(SIM_FUNC_w) AtomicMemorySimpleHelper<uint32_t>(instr); break; ATOMIC_MEMORY_SIMPLE_INT_LIST(SIM_FUNC_w) AtomicMemorySimpleHelper<int32_t>(instr); break; ATOMIC_MEMORY_SIMPLE_UINT_LIST(SIM_FUNC_x) AtomicMemorySimpleHelper<uint64_t>(instr); break; ATOMIC_MEMORY_SIMPLE_INT_LIST(SIM_FUNC_x) AtomicMemorySimpleHelper<int64_t>(instr); break; // clang-format on case SWPB: case SWPAB: case SWPLB: case SWPALB: AtomicMemorySwapHelper<uint8_t>(instr); break; case SWPH: case SWPAH: case SWPLH: case SWPALH: AtomicMemorySwapHelper<uint16_t>(instr); break; case SWP_w: case SWPA_w: case SWPL_w: case SWPAL_w: AtomicMemorySwapHelper<uint32_t>(instr); break; case SWP_x: case SWPA_x: case SWPL_x: case SWPAL_x: AtomicMemorySwapHelper<uint64_t>(instr); break; } } void Simulator::CheckMemoryAccess(uintptr_t address, uintptr_t stack) { if ((address >= stack_limit_) && (address < stack)) { fprintf(stream_, "ACCESS BELOW STACK POINTER:\n"); fprintf(stream_, " sp is here: 0x%016" PRIx64 "\n", static_cast<uint64_t>(stack)); fprintf(stream_, " access was here: 0x%016" PRIx64 "\n", static_cast<uint64_t>(address)); fprintf(stream_, " stack limit is here: 0x%016" PRIx64 "\n", static_cast<uint64_t>(stack_limit_)); fprintf(stream_, "\n"); FATAL("ACCESS BELOW STACK POINTER"); } } void Simulator::VisitMoveWideImmediate(Instruction* instr) { MoveWideImmediateOp mov_op = static_cast<MoveWideImmediateOp>(instr->Mask(MoveWideImmediateMask)); int64_t new_xn_val = 0; bool is_64_bits = instr->SixtyFourBits() == 1; // Shift is limited for W operations. DCHECK(is_64_bits || (instr->ShiftMoveWide() < 2)); // Get the shifted immediate. int64_t shift = instr->ShiftMoveWide() * 16; int64_t shifted_imm16 = static_cast<int64_t>(instr->ImmMoveWide()) << shift; // Compute the new value. switch (mov_op) { case MOVN_w: case MOVN_x: { new_xn_val = ~shifted_imm16; if (!is_64_bits) new_xn_val &= kWRegMask; break; } case MOVK_w: case MOVK_x: { unsigned reg_code = instr->Rd(); int64_t prev_xn_val = is_64_bits ? xreg(reg_code) : wreg(reg_code); new_xn_val = (prev_xn_val & ~(INT64_C(0xFFFF) << shift)) | shifted_imm16; break; } case MOVZ_w: case MOVZ_x: { new_xn_val = shifted_imm16; break; } default: UNREACHABLE(); } // Update the destination register. set_xreg(instr->Rd(), new_xn_val); } void Simulator::VisitConditionalSelect(Instruction* instr) { uint64_t new_val = xreg(instr->Rn()); if (ConditionFailed(static_cast<Condition>(instr->Condition()))) { new_val = xreg(instr->Rm()); switch (instr->Mask(ConditionalSelectMask)) { case CSEL_w: case CSEL_x: break; case CSINC_w: case CSINC_x: new_val++; break; case CSINV_w: case CSINV_x: new_val = ~new_val; break; case CSNEG_w: case CSNEG_x: // Simulate two's complement (instead of casting to signed and negating) // to avoid undefined behavior on signed overflow. new_val = (~new_val) + 1; break; default: UNIMPLEMENTED(); } } if (instr->SixtyFourBits()) { set_xreg(instr->Rd(), new_val); } else { set_wreg(instr->Rd(), static_cast<uint32_t>(new_val)); } } void Simulator::VisitDataProcessing1Source(Instruction* instr) { unsigned dst = instr->Rd(); unsigned src = instr->Rn(); switch (instr->Mask(DataProcessing1SourceMask)) { case RBIT_w: set_wreg(dst, base::bits::ReverseBits(wreg(src))); break; case RBIT_x: set_xreg(dst, base::bits::ReverseBits(xreg(src))); break; case REV16_w: set_wreg(dst, ReverseBytes(wreg(src), 1)); break; case REV16_x: set_xreg(dst, ReverseBytes(xreg(src), 1)); break; case REV_w: set_wreg(dst, ReverseBytes(wreg(src), 2)); break; case REV32_x: set_xreg(dst, ReverseBytes(xreg(src), 2)); break; case REV_x: set_xreg(dst, ReverseBytes(xreg(src), 3)); break; case CLZ_w: set_wreg(dst, CountLeadingZeros(wreg(src), kWRegSizeInBits)); break; case CLZ_x: set_xreg(dst, CountLeadingZeros(xreg(src), kXRegSizeInBits)); break; case CLS_w: { set_wreg(dst, CountLeadingSignBits(wreg(src), kWRegSizeInBits)); break; } case CLS_x: { set_xreg(dst, CountLeadingSignBits(xreg(src), kXRegSizeInBits)); break; } default: UNIMPLEMENTED(); } } template <typename T> void Simulator::DataProcessing2Source(Instruction* instr) { Shift shift_op = NO_SHIFT; T result = 0; switch (instr->Mask(DataProcessing2SourceMask)) { case SDIV_w: case SDIV_x: { T rn = reg<T>(instr->Rn()); T rm = reg<T>(instr->Rm()); if ((rn == std::numeric_limits<T>::min()) && (rm == -1)) { result = std::numeric_limits<T>::min(); } else if (rm == 0) { // Division by zero can be trapped, but not on A-class processors. result = 0; } else { result = rn / rm; } break; } case UDIV_w: case UDIV_x: { using unsignedT = typename std::make_unsigned<T>::type; unsignedT rn = static_cast<unsignedT>(reg<T>(instr->Rn())); unsignedT rm = static_cast<unsignedT>(reg<T>(instr->Rm())); if (rm == 0) { // Division by zero can be trapped, but not on A-class processors. result = 0; } else { result = rn / rm; } break; } case LSLV_w: case LSLV_x: shift_op = LSL; break; case LSRV_w: case LSRV_x: shift_op = LSR; break; case ASRV_w: case ASRV_x: shift_op = ASR; break; case RORV_w: case RORV_x: shift_op = ROR; break; default: UNIMPLEMENTED(); } if (shift_op != NO_SHIFT) { // Shift distance encoded in the least-significant five/six bits of the // register. unsigned shift = wreg(instr->Rm()); if (sizeof(T) == kWRegSize) { shift &= kShiftAmountWRegMask; } else { shift &= kShiftAmountXRegMask; } result = ShiftOperand(reg<T>(instr->Rn()), shift_op, shift); } set_reg<T>(instr->Rd(), result); } void Simulator::VisitDataProcessing2Source(Instruction* instr) { if (instr->SixtyFourBits()) { DataProcessing2Source<int64_t>(instr); } else { DataProcessing2Source<int32_t>(instr); } } void Simulator::VisitDataProcessing3Source(Instruction* instr) { int64_t result = 0; // Extract and sign- or zero-extend 32-bit arguments for widening operations. uint64_t rn_u32 = reg<uint32_t>(instr->Rn()); uint64_t rm_u32 = reg<uint32_t>(instr->Rm()); int64_t rn_s32 = reg<int32_t>(instr->Rn()); int64_t rm_s32 = reg<int32_t>(instr->Rm()); switch (instr->Mask(DataProcessing3SourceMask)) { case MADD_w: case MADD_x: result = base::AddWithWraparound( xreg(instr->Ra()), base::MulWithWraparound(xreg(instr->Rn()), xreg(instr->Rm()))); break; case MSUB_w: case MSUB_x: result = base::SubWithWraparound( xreg(instr->Ra()), base::MulWithWraparound(xreg(instr->Rn()), xreg(instr->Rm()))); break; case SMADDL_x: result = base::AddWithWraparound(xreg(instr->Ra()), (rn_s32 * rm_s32)); break; case SMSUBL_x: result = base::SubWithWraparound(xreg(instr->Ra()), (rn_s32 * rm_s32)); break; case UMADDL_x: result = static_cast<uint64_t>(xreg(instr->Ra())) + (rn_u32 * rm_u32); break; case UMSUBL_x: result = static_cast<uint64_t>(xreg(instr->Ra())) - (rn_u32 * rm_u32); break; case SMULH_x: DCHECK_EQ(instr->Ra(), kZeroRegCode); result = base::bits::SignedMulHigh64(xreg(instr->Rn()), xreg(instr->Rm())); break; case UMULH_x: DCHECK_EQ(instr->Ra(), kZeroRegCode); result = base::bits::UnsignedMulHigh64(xreg(instr->Rn()), xreg(instr->Rm())); break; default: UNIMPLEMENTED(); } if (instr->SixtyFourBits()) { set_xreg(instr->Rd(), result); } else { set_wreg(instr->Rd(), static_cast<int32_t>(result)); } } template <typename T> void Simulator::BitfieldHelper(Instruction* instr) { using unsignedT = typename std::make_unsigned<T>::type; T reg_size = sizeof(T) * 8; T R = instr->ImmR(); T S = instr->ImmS(); T diff = S - R; T mask; if (diff >= 0) { mask = diff < reg_size - 1 ? (static_cast<unsignedT>(1) << (diff + 1)) - 1 : static_cast<T>(-1); } else { uint64_t umask = ((1ULL << (S + 1)) - 1); umask = (umask >> R) | (umask << (reg_size - R)); mask = static_cast<T>(umask); diff += reg_size; } // inzero indicates if the extracted bitfield is inserted into the // destination register value or in zero. // If extend is true, extend the sign of the extracted bitfield. bool inzero = false; bool extend = false; switch (instr->Mask(BitfieldMask)) { case BFM_x: case BFM_w: break; case SBFM_x: case SBFM_w: inzero = true; extend = true; break; case UBFM_x: case UBFM_w: inzero = true; break; default: UNIMPLEMENTED(); } T dst = inzero ? 0 : reg<T>(instr->Rd()); T src = reg<T>(instr->Rn()); // Rotate source bitfield into place. T result = R == 0 ? src : (static_cast<unsignedT>(src) >> R) | (static_cast<unsignedT>(src) << (reg_size - R)); // Determine the sign extension. T topbits_preshift = (static_cast<unsignedT>(1) << (reg_size - diff - 1)) - 1; T signbits = diff >= reg_size - 1 ? 0 : ((extend && ((src >> S) & 1) ? topbits_preshift : 0) << (diff + 1)); // Merge sign extension, dest/zero and bitfield. result = signbits | (result & mask) | (dst & ~mask); set_reg<T>(instr->Rd(), result); } void Simulator::VisitBitfield(Instruction* instr) { if (instr->SixtyFourBits()) { BitfieldHelper<int64_t>(instr); } else { BitfieldHelper<int32_t>(instr); } } void Simulator::VisitExtract(Instruction* instr) { if (instr->SixtyFourBits()) { Extract<uint64_t>(instr); } else { Extract<uint32_t>(instr); } } void Simulator::VisitFPImmediate(Instruction* instr) { AssertSupportedFPCR(); unsigned dest = instr->Rd(); switch (instr->Mask(FPImmediateMask)) { case FMOV_s_imm: set_sreg(dest, instr->ImmFP32()); break; case FMOV_d_imm: set_dreg(dest, instr->ImmFP64()); break; default: UNREACHABLE(); } } void Simulator::VisitFPIntegerConvert(Instruction* instr) { AssertSupportedFPCR(); unsigned dst = instr->Rd(); unsigned src = instr->Rn(); FPRounding round = fpcr().RMode(); switch (instr->Mask(FPIntegerConvertMask)) { case FCVTAS_ws: set_wreg(dst, FPToInt32(sreg(src), FPTieAway)); break; case FCVTAS_xs: set_xreg(dst, FPToInt64(sreg(src), FPTieAway)); break; case FCVTAS_wd: set_wreg(dst, FPToInt32(dreg(src), FPTieAway)); break; case FCVTAS_xd: set_xreg(dst, FPToInt64(dreg(src), FPTieAway)); break; case FCVTAU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPTieAway)); break; case FCVTAU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPTieAway)); break; case FCVTAU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPTieAway)); break; case FCVTAU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPTieAway)); break; case FCVTMS_ws: set_wreg(dst, FPToInt32(sreg(src), FPNegativeInfinity)); break; case FCVTMS_xs: set_xreg(dst, FPToInt64(sreg(src), FPNegativeInfinity)); break; case FCVTMS_wd: set_wreg(dst, FPToInt32(dreg(src), FPNegativeInfinity)); break; case FCVTMS_xd: set_xreg(dst, FPToInt64(dreg(src), FPNegativeInfinity)); break; case FCVTMU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPNegativeInfinity)); break; case FCVTMU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPNegativeInfinity)); break; case FCVTMU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPNegativeInfinity)); break; case FCVTMU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPNegativeInfinity)); break; case FCVTNS_ws: set_wreg(dst, FPToInt32(sreg(src), FPTieEven)); break; case FCVTNS_xs: set_xreg(dst, FPToInt64(sreg(src), FPTieEven)); break; case FCVTNS_wd: set_wreg(dst, FPToInt32(dreg(src), FPTieEven)); break; case FCVTNS_xd: set_xreg(dst, FPToInt64(dreg(src), FPTieEven)); break; case FCVTNU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPTieEven)); break; case FCVTNU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPTieEven)); break; case FCVTNU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPTieEven)); break; case FCVTNU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPTieEven)); break; case FCVTZS_ws: set_wreg(dst, FPToInt32(sreg(src), FPZero)); break; case FCVTZS_xs: set_xreg(dst, FPToInt64(sreg(src), FPZero)); break; case FCVTZS_wd: set_wreg(dst, FPToInt32(dreg(src), FPZero)); break; case FCVTZS_xd: set_xreg(dst, FPToInt64(dreg(src), FPZero)); break; case FCVTZU_ws: set_wreg(dst, FPToUInt32(sreg(src), FPZero)); break; case FCVTZU_xs: set_xreg(dst, FPToUInt64(sreg(src), FPZero)); break; case FCVTZU_wd: set_wreg(dst, FPToUInt32(dreg(src), FPZero)); break; case FCVTZU_xd: set_xreg(dst, FPToUInt64(dreg(src), FPZero)); break; case FJCVTZS: set_wreg(dst, FPToFixedJS(dreg(src))); break; case FMOV_ws: set_wreg(dst, sreg_bits(src)); break; case FMOV_xd: set_xreg(dst, dreg_bits(src)); break; case FMOV_sw: set_sreg_bits(dst, wreg(src)); break; case FMOV_dx: set_dreg_bits(dst, xreg(src)); break; // A 32-bit input can be handled in the same way as a 64-bit input, since // the sign- or zero-extension will not affect the conversion. case SCVTF_dx: set_dreg(dst, FixedToDouble(xreg(src), 0, round)); break; case SCVTF_dw: set_dreg(dst, FixedToDouble(wreg(src), 0, round)); break; case UCVTF_dx: set_dreg(dst, UFixedToDouble(xreg(src), 0, round)); break; case UCVTF_dw: { set_dreg(dst, UFixedToDouble(reg<uint32_t>(src), 0, round)); break; } case SCVTF_sx: set_sreg(dst, FixedToFloat(xreg(src), 0, round)); break; case SCVTF_sw: set_sreg(dst, FixedToFloat(wreg(src), 0, round)); break; case UCVTF_sx: set_sreg(dst, UFixedToFloat(xreg(src), 0, round)); break; case UCVTF_sw: { set_sreg(dst, UFixedToFloat(reg<uint32_t>(src), 0, round)); break; } default: UNREACHABLE(); } } void Simulator::VisitFPFixedPointConvert(Instruction* instr) { AssertSupportedFPCR(); unsigned dst = instr->Rd(); unsigned src = instr->Rn(); int fbits = 64 - instr->FPScale(); FPRounding round = fpcr().RMode(); switch (instr->Mask(FPFixedPointConvertMask)) { // A 32-bit input can be handled in the same way as a 64-bit input, since // the sign- or zero-extension will not affect the conversion. case SCVTF_dx_fixed: set_dreg(dst, FixedToDouble(xreg(src), fbits, round)); break; case SCVTF_dw_fixed: set_dreg(dst, FixedToDouble(wreg(src), fbits, round)); break; case UCVTF_dx_fixed: set_dreg(dst, UFixedToDouble(xreg(src), fbits, round)); break; case UCVTF_dw_fixed: { set_dreg(dst, UFixedToDouble(reg<uint32_t>(src), fbits, round)); break; } case SCVTF_sx_fixed: set_sreg(dst, FixedToFloat(xreg(src), fbits, round)); break; case SCVTF_sw_fixed: set_sreg(dst, FixedToFloat(wreg(src), fbits, round)); break; case UCVTF_sx_fixed: set_sreg(dst, UFixedToFloat(xreg(src), fbits, round)); break; case UCVTF_sw_fixed: { set_sreg(dst, UFixedToFloat(reg<uint32_t>(src), fbits, round)); break; } default: UNREACHABLE(); } } void Simulator::VisitFPCompare(Instruction* instr) { AssertSupportedFPCR(); switch (instr->Mask(FPCompareMask)) { case FCMP_s: FPCompare(sreg(instr->Rn()), sreg(instr->Rm())); break; case FCMP_d: FPCompare(dreg(instr->Rn()), dreg(instr->Rm())); break; case FCMP_s_zero: FPCompare(sreg(instr->Rn()), 0.0f); break; case FCMP_d_zero: FPCompare(dreg(instr->Rn()), 0.0); break; default: UNIMPLEMENTED(); } } void Simulator::VisitFPConditionalCompare(Instruction* instr) { AssertSupportedFPCR(); switch (instr->Mask(FPConditionalCompareMask)) { case FCCMP_s: if (ConditionPassed(static_cast<Condition>(instr->Condition()))) { FPCompare(sreg(instr->Rn()), sreg(instr->Rm())); } else { nzcv().SetFlags(instr->Nzcv()); LogSystemRegister(NZCV); } break; case FCCMP_d: { if (ConditionPassed(static_cast<Condition>(instr->Condition()))) { FPCompare(dreg(instr->Rn()), dreg(instr->Rm())); } else { // If the condition fails, set the status flags to the nzcv immediate. nzcv().SetFlags(instr->Nzcv()); LogSystemRegister(NZCV); } break; } default: UNIMPLEMENTED(); } } void Simulator::VisitFPConditionalSelect(Instruction* instr) { AssertSupportedFPCR(); Instr selected; if (ConditionPassed(static_cast<Condition>(instr->Condition()))) { selected = instr->Rn(); } else { selected = instr->Rm(); } switch (instr->Mask(FPConditionalSelectMask)) { case FCSEL_s: set_sreg(instr->Rd(), sreg(selected)); break; case FCSEL_d: set_dreg(instr->Rd(), dreg(selected)); break; default: UNIMPLEMENTED(); } } void Simulator::VisitFPDataProcessing1Source(Instruction* instr) { AssertSupportedFPCR(); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); VectorFormat vform = (instr->Mask(FP64) == FP64) ? kFormatD : kFormatS; SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); bool inexact_exception = false; unsigned fd = instr->Rd(); unsigned fn = instr->Rn(); switch (instr->Mask(FPDataProcessing1SourceMask)) { case FMOV_s: set_sreg(fd, sreg(fn)); return; case FMOV_d: set_dreg(fd, dreg(fn)); return; case FABS_s: case FABS_d: fabs_(vform, vreg(fd), vreg(fn)); // Explicitly log the register update whilst we have type information. LogVRegister(fd, GetPrintRegisterFormatFP(vform)); return; case FNEG_s: case FNEG_d: fneg(vform, vreg(fd), vreg(fn)); // Explicitly log the register update whilst we have type information. LogVRegister(fd, GetPrintRegisterFormatFP(vform)); return; case FCVT_ds: set_dreg(fd, FPToDouble(sreg(fn))); return; case FCVT_sd: set_sreg(fd, FPToFloat(dreg(fn), FPTieEven)); return; case FCVT_hs: set_hreg(fd, FPToFloat16(sreg(fn), FPTieEven)); return; case FCVT_sh: set_sreg(fd, FPToFloat(hreg(fn))); return; case FCVT_dh: set_dreg(fd, FPToDouble(FPToFloat(hreg(fn)))); return; case FCVT_hd: set_hreg(fd, FPToFloat16(dreg(fn), FPTieEven)); return; case FSQRT_s: case FSQRT_d: fsqrt(vform, rd, rn); // Explicitly log the register update whilst we have type information. LogVRegister(fd, GetPrintRegisterFormatFP(vform)); return; case FRINTI_s: case FRINTI_d: break; // Use FPCR rounding mode. case FRINTX_s: case FRINTX_d: inexact_exception = true; break; case FRINTA_s: case FRINTA_d: fpcr_rounding = FPTieAway; break; case FRINTM_s: case FRINTM_d: fpcr_rounding = FPNegativeInfinity; break; case FRINTN_s: case FRINTN_d: fpcr_rounding = FPTieEven; break; case FRINTP_s: case FRINTP_d: fpcr_rounding = FPPositiveInfinity; break; case FRINTZ_s: case FRINTZ_d: fpcr_rounding = FPZero; break; default: UNIMPLEMENTED(); } // Only FRINT* instructions fall through the switch above. frint(vform, rd, rn, fpcr_rounding, inexact_exception); // Explicitly log the register update whilst we have type information LogVRegister(fd, GetPrintRegisterFormatFP(vform)); } void Simulator::VisitFPDataProcessing2Source(Instruction* instr) { AssertSupportedFPCR(); VectorFormat vform = (instr->Mask(FP64) == FP64) ? kFormatD : kFormatS; SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(FPDataProcessing2SourceMask)) { case FADD_s: case FADD_d: fadd(vform, rd, rn, rm); break; case FSUB_s: case FSUB_d: fsub(vform, rd, rn, rm); break; case FMUL_s: case FMUL_d: fmul(vform, rd, rn, rm); break; case FNMUL_s: case FNMUL_d: fnmul(vform, rd, rn, rm); break; case FDIV_s: case FDIV_d: fdiv(vform, rd, rn, rm); break; case FMAX_s: case FMAX_d: fmax(vform, rd, rn, rm); break; case FMIN_s: case FMIN_d: fmin(vform, rd, rn, rm); break; case FMAXNM_s: case FMAXNM_d: fmaxnm(vform, rd, rn, rm); break; case FMINNM_s: case FMINNM_d: fminnm(vform, rd, rn, rm); break; default: UNREACHABLE(); } // Explicitly log the register update whilst we have type information. LogVRegister(instr->Rd(), GetPrintRegisterFormatFP(vform)); } void Simulator::VisitFPDataProcessing3Source(Instruction* instr) { AssertSupportedFPCR(); unsigned fd = instr->Rd(); unsigned fn = instr->Rn(); unsigned fm = instr->Rm(); unsigned fa = instr->Ra(); switch (instr->Mask(FPDataProcessing3SourceMask)) { // fd = fa +/- (fn * fm) case FMADD_s: set_sreg(fd, FPMulAdd(sreg(fa), sreg(fn), sreg(fm))); break; case FMSUB_s: set_sreg(fd, FPMulAdd(sreg(fa), -sreg(fn), sreg(fm))); break; case FMADD_d: set_dreg(fd, FPMulAdd(dreg(fa), dreg(fn), dreg(fm))); break; case FMSUB_d: set_dreg(fd, FPMulAdd(dreg(fa), -dreg(fn), dreg(fm))); break; // Negated variants of the above. case FNMADD_s: set_sreg(fd, FPMulAdd(-sreg(fa), -sreg(fn), sreg(fm))); break; case FNMSUB_s: set_sreg(fd, FPMulAdd(-sreg(fa), sreg(fn), sreg(fm))); break; case FNMADD_d: set_dreg(fd, FPMulAdd(-dreg(fa), -dreg(fn), dreg(fm))); break; case FNMSUB_d: set_dreg(fd, FPMulAdd(-dreg(fa), dreg(fn), dreg(fm))); break; default: UNIMPLEMENTED(); } } bool Simulator::FPProcessNaNs(Instruction* instr) { unsigned fd = instr->Rd(); unsigned fn = instr->Rn(); unsigned fm = instr->Rm(); bool done = false; if (instr->Mask(FP64) == FP64) { double result = FPProcessNaNs(dreg(fn), dreg(fm)); if (std::isnan(result)) { set_dreg(fd, result); done = true; } } else { float result = FPProcessNaNs(sreg(fn), sreg(fm)); if (std::isnan(result)) { set_sreg(fd, result); done = true; } } return done; } // clang-format off #define PAUTH_SYSTEM_MODES(V) \ V(B1716, 17, xreg(16), kPACKeyIB) \ V(BSP, 30, xreg(31, Reg31IsStackPointer), kPACKeyIB) // clang-format on void Simulator::VisitSystem(Instruction* instr) { // Some system instructions hijack their Op and Cp fields to represent a // range of immediates instead of indicating a different instruction. This // makes the decoding tricky. if (instr->Mask(SystemPAuthFMask) == SystemPAuthFixed) { // The BType check for PACIBSP happens in CheckBType(). switch (instr->Mask(SystemPAuthMask)) { #define DEFINE_PAUTH_FUNCS(SUFFIX, DST, MOD, KEY) \ case PACI##SUFFIX: \ set_xreg(DST, AddPAC(xreg(DST), MOD, KEY, kInstructionPointer)); \ break; \ case AUTI##SUFFIX: \ set_xreg(DST, AuthPAC(xreg(DST), MOD, KEY, kInstructionPointer)); \ break; PAUTH_SYSTEM_MODES(DEFINE_PAUTH_FUNCS) #undef DEFINE_PAUTH_FUNCS #undef PAUTH_SYSTEM_MODES } } else if (instr->Mask(SystemSysRegFMask) == SystemSysRegFixed) { switch (instr->Mask(SystemSysRegMask)) { case MRS: { switch (instr->ImmSystemRegister()) { case NZCV: set_xreg(instr->Rt(), nzcv().RawValue()); break; case FPCR: set_xreg(instr->Rt(), fpcr().RawValue()); break; default: UNIMPLEMENTED(); } break; } case MSR: { switch (instr->ImmSystemRegister()) { case NZCV: nzcv().SetRawValue(wreg(instr->Rt())); LogSystemRegister(NZCV); break; case FPCR: fpcr().SetRawValue(wreg(instr->Rt())); LogSystemRegister(FPCR); break; default: UNIMPLEMENTED(); } break; } } } else if (instr->Mask(SystemHintFMask) == SystemHintFixed) { DCHECK(instr->Mask(SystemHintMask) == HINT); switch (instr->ImmHint()) { case NOP: case CSDB: case BTI_jc: case BTI: case BTI_c: case BTI_j: // The BType checks happen in CheckBType(). break; default: UNIMPLEMENTED(); } } else if (instr->Mask(MemBarrierFMask) == MemBarrierFixed) { std::atomic_thread_fence(std::memory_order_seq_cst); } else { UNIMPLEMENTED(); } } bool Simulator::GetValue(const char* desc, int64_t* value) { int regnum = CodeFromName(desc); if (regnum >= 0) { unsigned code = regnum; if (code == kZeroRegCode) { // Catch the zero register and return 0. *value = 0; return true; } else if (code == kSPRegInternalCode) { // Translate the stack pointer code to 31, for Reg31IsStackPointer. code = 31; } if (desc[0] == 'w') { *value = wreg(code, Reg31IsStackPointer); } else { *value = xreg(code, Reg31IsStackPointer); } return true; } else if (strncmp(desc, "0x", 2) == 0) { return SScanF(desc + 2, "%" SCNx64, reinterpret_cast<uint64_t*>(value)) == 1; } else { return SScanF(desc, "%" SCNu64, reinterpret_cast<uint64_t*>(value)) == 1; } } bool Simulator::PrintValue(const char* desc) { if (strcmp(desc, "sp") == 0) { DCHECK(CodeFromName(desc) == static_cast<int>(kSPRegInternalCode)); PrintF(stream_, "%s sp:%s 0x%016" PRIx64 "%s\n", clr_reg_name, clr_reg_value, xreg(31, Reg31IsStackPointer), clr_normal); return true; } else if (strcmp(desc, "wsp") == 0) { DCHECK(CodeFromName(desc) == static_cast<int>(kSPRegInternalCode)); PrintF(stream_, "%s wsp:%s 0x%08" PRIx32 "%s\n", clr_reg_name, clr_reg_value, wreg(31, Reg31IsStackPointer), clr_normal); return true; } int i = CodeFromName(desc); static_assert(kNumberOfRegisters == kNumberOfVRegisters, "Must be same number of Registers as VRegisters."); if (i < 0 || static_cast<unsigned>(i) >= kNumberOfVRegisters) return false; if (desc[0] == 'v') { PrintF(stream_, "%s %s:%s 0x%016" PRIx64 "%s (%s%s:%s %g%s %s:%s %g%s)\n", clr_vreg_name, VRegNameForCode(i), clr_vreg_value, base::bit_cast<uint64_t>(dreg(i)), clr_normal, clr_vreg_name, DRegNameForCode(i), clr_vreg_value, dreg(i), clr_vreg_name, SRegNameForCode(i), clr_vreg_value, sreg(i), clr_normal); return true; } else if (desc[0] == 'd') { PrintF(stream_, "%s %s:%s %g%s\n", clr_vreg_name, DRegNameForCode(i), clr_vreg_value, dreg(i), clr_normal); return true; } else if (desc[0] == 's') { PrintF(stream_, "%s %s:%s %g%s\n", clr_vreg_name, SRegNameForCode(i), clr_vreg_value, sreg(i), clr_normal); return true; } else if (desc[0] == 'w') { PrintF(stream_, "%s %s:%s 0x%08" PRIx32 "%s\n", clr_reg_name, WRegNameForCode(i), clr_reg_value, wreg(i), clr_normal); return true; } else { // X register names have a wide variety of starting characters, but anything // else will be an X register. PrintF(stream_, "%s %s:%s 0x%016" PRIx64 "%s\n", clr_reg_name, XRegNameForCode(i), clr_reg_value, xreg(i), clr_normal); return true; } } void Simulator::Debug() { if (v8_flags.correctness_fuzzer_suppressions) { PrintF("Debugger disabled for differential fuzzing.\n"); return; } bool done = false; while (!done) { // Disassemble the next instruction to execute before doing anything else. PrintInstructionsAt(pc_, 1); // Read the command line. ArrayUniquePtr<char> line(ReadLine("sim> ")); done = ExecDebugCommand(std::move(line)); } } bool Simulator::ExecDebugCommand(ArrayUniquePtr<char> line_ptr) { #define COMMAND_SIZE 63 #define ARG_SIZE 255 #define STR(a) #a #define XSTR(a) STR(a) char cmd[COMMAND_SIZE + 1]; char arg1[ARG_SIZE + 1]; char arg2[ARG_SIZE + 1]; char* argv[3] = {cmd, arg1, arg2}; // Make sure to have a proper terminating character if reaching the limit. cmd[COMMAND_SIZE] = 0; arg1[ARG_SIZE] = 0; arg2[ARG_SIZE] = 0; bool cleared_log_disasm_bit = false; if (line_ptr == nullptr) return false; // Repeat last command by default. const char* line = line_ptr.get(); const char* last_input = last_debugger_input(); if (strcmp(line, "\n") == 0 && (last_input != nullptr)) { line_ptr.reset(); line = last_input; } else { // Update the latest command ran set_last_debugger_input(std::move(line_ptr)); } // Use sscanf to parse the individual parts of the command line. At the // moment no command expects more than two parameters. int argc = SScanF(line, "%" XSTR(COMMAND_SIZE) "s " "%" XSTR(ARG_SIZE) "s " "%" XSTR(ARG_SIZE) "s", cmd, arg1, arg2); // stepi / si ------------------------------------------------------------ if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) { // We are about to execute instructions, after which by default we // should increment the pc_. If it was set when reaching this debug // instruction, it has not been cleared because this instruction has not // completed yet. So clear it manually. pc_modified_ = false; if (argc == 1) { ExecuteInstruction(); } else { int64_t number_of_instructions_to_execute = 1; GetValue(arg1, &number_of_instructions_to_execute); set_log_parameters(log_parameters() | LOG_DISASM); while (number_of_instructions_to_execute-- > 0) { ExecuteInstruction(); } set_log_parameters(log_parameters() & ~LOG_DISASM); PrintF("\n"); } // If it was necessary, the pc has already been updated or incremented // when executing the instruction. So we do not want it to be updated // again. It will be cleared when exiting. pc_modified_ = true; // next / n // -------------------------------------------------------------- } else if ((strcmp(cmd, "next") == 0) || (strcmp(cmd, "n") == 0)) { // Tell the simulator to break after the next executed BL. break_on_next_ = true; // Continue. return true; // continue / cont / c // --------------------------------------------------- } else if ((strcmp(cmd, "continue") == 0) || (strcmp(cmd, "cont") == 0) || (strcmp(cmd, "c") == 0)) { // Leave the debugger shell. return true; // disassemble / disasm / di // --------------------------------------------- } else if (strcmp(cmd, "disassemble") == 0 || strcmp(cmd, "disasm") == 0 || strcmp(cmd, "di") == 0) { int64_t n_of_instrs_to_disasm = 10; // default value. int64_t address = reinterpret_cast<int64_t>(pc_); // default value. if (argc >= 2) { // disasm <n of instrs> GetValue(arg1, &n_of_instrs_to_disasm); } if (argc >= 3) { // disasm <n of instrs> <address> GetValue(arg2, &address); } // Disassemble. PrintInstructionsAt(reinterpret_cast<Instruction*>(address), n_of_instrs_to_disasm); PrintF("\n"); // print / p // ------------------------------------------------------------- } else if ((strcmp(cmd, "print") == 0) || (strcmp(cmd, "p") == 0)) { if (argc == 2) { if (strcmp(arg1, "all") == 0) { PrintRegisters(); PrintVRegisters(); } else { if (!PrintValue(arg1)) { PrintF("%s unrecognized\n", arg1); } } } else { PrintF( "print <register>\n" " Print the content of a register. (alias 'p')\n" " 'print all' will print all registers.\n" " Use 'printobject' to get more details about the value.\n"); } // printobject / po // ------------------------------------------------------ } else if ((strcmp(cmd, "printobject") == 0) || (strcmp(cmd, "po") == 0)) { if (argc == 2) { int64_t value; StdoutStream os; if (GetValue(arg1, &value)) { Object obj(value); os << arg1 << ": \n"; #ifdef DEBUG obj.Print(os); os << "\n"; #else os << Brief(obj) << "\n"; #endif } else { os << arg1 << " unrecognized\n"; } } else { PrintF( "printobject <value>\n" "printobject <register>\n" " Print details about the value. (alias 'po')\n"); } // stack / mem // ---------------------------------------------------------- } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0 || strcmp(cmd, "dump") == 0) { int64_t* cur = nullptr; int64_t* end = nullptr; int next_arg = 1; if (strcmp(cmd, "stack") == 0) { cur = reinterpret_cast<int64_t*>(sp()); } else { // "mem" int64_t value; if (!GetValue(arg1, &value)) { PrintF("%s unrecognized\n", arg1); return false; } cur = reinterpret_cast<int64_t*>(value); next_arg++; } int64_t words = 0; if (argc == next_arg) { words = 10; } else if (argc == next_arg + 1) { if (!GetValue(argv[next_arg], &words)) { PrintF("%s unrecognized\n", argv[next_arg]); PrintF("Printing 10 double words by default"); words = 10; } } else { UNREACHABLE(); } end = cur + words; bool skip_obj_print = (strcmp(cmd, "dump") == 0); while (cur < end) { PrintF(" 0x%016" PRIx64 ": 0x%016" PRIx64 " %10" PRId64, reinterpret_cast<uint64_t>(cur), *cur, *cur); if (!skip_obj_print) { Object obj(*cur); Heap* current_heap = isolate_->heap(); if (obj.IsSmi() || IsValidHeapObject(current_heap, HeapObject::cast(obj))) { PrintF(" ("); if (obj.IsSmi()) { PrintF("smi %" PRId32, Smi::ToInt(obj)); } else { obj.ShortPrint(); } PrintF(")"); } } PrintF("\n"); cur++; } // trace / t // ------------------------------------------------------------- } else if (strcmp(cmd, "trace") == 0 || strcmp(cmd, "t") == 0) { if ((log_parameters() & LOG_ALL) != LOG_ALL) { PrintF("Enabling disassembly, registers and memory write tracing\n"); set_log_parameters(log_parameters() | LOG_ALL); } else { PrintF("Disabling disassembly, registers and memory write tracing\n"); set_log_parameters(log_parameters() & ~LOG_ALL); } // break / b // ------------------------------------------------------------- } else if (strcmp(cmd, "break") == 0 || strcmp(cmd, "b") == 0) { if (argc == 2) { int64_t value; if (GetValue(arg1, &value)) { SetBreakpoint(reinterpret_cast<Instruction*>(value)); } else { PrintF("%s unrecognized\n", arg1); } } else { ListBreakpoints(); PrintF("Use `break <address>` to set or disable a breakpoint\n"); } // backtrace / bt // --------------------------------------------------------------- } else if (strcmp(cmd, "backtrace") == 0 || strcmp(cmd, "bt") == 0) { Address pc = reinterpret_cast<Address>(pc_); Address lr = reinterpret_cast<Address>(this->lr()); Address sp = static_cast<Address>(this->sp()); Address fp = static_cast<Address>(this->fp()); int i = 0; while (true) { PrintF("#%d: " V8PRIxPTR_FMT " (sp=" V8PRIxPTR_FMT ", fp=" V8PRIxPTR_FMT ")\n", i, pc, sp, fp); pc = lr; sp = fp; if (pc == reinterpret_cast<Address>(kEndOfSimAddress)) { break; } lr = *(reinterpret_cast<Address*>(fp) + 1); fp = *reinterpret_cast<Address*>(fp); i++; if (i > 100) { PrintF("Too many frames\n"); break; } } // gdb // ------------------------------------------------------------------- } else if (strcmp(cmd, "gdb") == 0) { PrintF("Relinquishing control to gdb.\n"); base::OS::DebugBreak(); PrintF("Regaining control from gdb.\n"); // sysregs // --------------------------------------------------------------- } else if (strcmp(cmd, "sysregs") == 0) { PrintSystemRegisters(); // help / h // -------------------------------------------------------------- } else if (strcmp(cmd, "help") == 0 || strcmp(cmd, "h") == 0) { PrintF( "stepi / si\n" " stepi <n>\n" " Step <n> instructions.\n" "next / n\n" " Continue execution until a BL instruction is reached.\n" " At this point a breakpoint is set just after this BL.\n" " Then execution is resumed. It will probably later hit the\n" " breakpoint just set.\n" "continue / cont / c\n" " Continue execution from here.\n" "disassemble / disasm / di\n" " disassemble <n> <address>\n" " Disassemble <n> instructions from current <address>.\n" " By default <n> is 20 and <address> is the current pc.\n" "print / p\n" " print <register>\n" " Print the content of a register.\n" " 'print all' will print all registers.\n" " Use 'printobject' to get more details about the value.\n" "printobject / po\n" " printobject <value>\n" " printobject <register>\n" " Print details about the value.\n" "stack\n" " stack [<words>]\n" " Dump stack content, default dump 10 words\n" "mem\n" " mem <address> [<words>]\n" " Dump memory content, default dump 10 words\n" "dump\n" " dump <address> [<words>]\n" " Dump memory content without pretty printing JS objects, " "default dump 10 words\n" "trace / t\n" " Toggle disassembly and register tracing\n" "break / b\n" " break : list all breakpoints\n" " break <address> : set / enable / disable a breakpoint.\n" "backtrace / bt\n" " Walk the frame pointers, dumping the pc/sp/fp for each frame.\n" "gdb\n" " Enter gdb.\n" "sysregs\n" " Print all system registers (including NZCV).\n"); } else { PrintF("Unknown command: %s\n", cmd); PrintF("Use 'help' for more information.\n"); } if (cleared_log_disasm_bit == true) { set_log_parameters(log_parameters_ | LOG_DISASM); } return false; } void Simulator::VisitException(Instruction* instr) { switch (instr->Mask(ExceptionMask)) { case HLT: { if (instr->ImmException() == kImmExceptionIsDebug) { // Read the arguments encoded inline in the instruction stream. uint32_t code; uint32_t parameters; memcpy(&code, pc_->InstructionAtOffset(kDebugCodeOffset), sizeof(code)); memcpy(&parameters, pc_->InstructionAtOffset(kDebugParamsOffset), sizeof(parameters)); char const* message = reinterpret_cast<char const*>( pc_->InstructionAtOffset(kDebugMessageOffset)); // Always print something when we hit a debug point that breaks. // We are going to break, so printing something is not an issue in // terms of speed. if (v8_flags.trace_sim_messages || v8_flags.trace_sim || (parameters & BREAK)) { if (message != nullptr) { PrintF(stream_, "# %sDebugger hit %d: %s%s%s\n", clr_debug_number, code, clr_debug_message, message, clr_normal); } else { PrintF(stream_, "# %sDebugger hit %d.%s\n", clr_debug_number, code, clr_normal); } Builtin maybe_builtin = OffHeapInstructionStream::TryLookupCode( Isolate::Current(), reinterpret_cast<Address>(pc_)); if (Builtins::IsBuiltinId(maybe_builtin)) { char const* name = Builtins::name(maybe_builtin); PrintF(stream_, "# %s %sLOCATION: %s%s\n", clr_debug_number, clr_debug_message, name, clr_normal); } } // Other options. switch (parameters & kDebuggerTracingDirectivesMask) { case TRACE_ENABLE: set_log_parameters(log_parameters() | parameters); if (parameters & LOG_SYS_REGS) { PrintSystemRegisters(); } if (parameters & LOG_REGS) { PrintRegisters(); } if (parameters & LOG_VREGS) { PrintVRegisters(); } break; case TRACE_DISABLE: set_log_parameters(log_parameters() & ~parameters); break; case TRACE_OVERRIDE: set_log_parameters(parameters); break; default: // We don't support a one-shot LOG_DISASM. DCHECK_EQ(parameters & LOG_DISASM, 0); // Don't print information that is already being traced. parameters &= ~log_parameters(); // Print the requested information. if (parameters & LOG_SYS_REGS) PrintSystemRegisters(); if (parameters & LOG_REGS) PrintRegisters(); if (parameters & LOG_VREGS) PrintVRegisters(); } // The stop parameters are inlined in the code. Skip them: // - Skip to the end of the message string. size_t size = kDebugMessageOffset + strlen(message) + 1; pc_ = pc_->InstructionAtOffset(RoundUp(size, kInstrSize)); // - Verify that the unreachable marker is present. DCHECK(pc_->Mask(ExceptionMask) == HLT); DCHECK_EQ(pc_->ImmException(), kImmExceptionIsUnreachable); // - Skip past the unreachable marker. set_pc(pc_->following()); // Check if the debugger should break. if (parameters & BREAK) Debug(); } else if (instr->ImmException() == kImmExceptionIsRedirectedCall) { DoRuntimeCall(instr); } else if (instr->ImmException() == kImmExceptionIsPrintf) { DoPrintf(instr); } else if (instr->ImmException() == kImmExceptionIsUnreachable) { fprintf(stream_, "Hit UNREACHABLE marker at PC=%p.\n", reinterpret_cast<void*>(pc_)); abort(); } else { base::OS::DebugBreak(); } break; } case BRK: base::OS::DebugBreak(); break; default: UNIMPLEMENTED(); } } void Simulator::VisitNEON2RegMisc(Instruction* instr) { NEONFormatDecoder nfd(instr); VectorFormat vf = nfd.GetVectorFormat(); // Format mapping for "long pair" instructions, [su]addlp, [su]adalp. static const NEONFormatMap map_lp = { {23, 22, 30}, {NF_4H, NF_8H, NF_2S, NF_4S, NF_1D, NF_2D}}; VectorFormat vf_lp = nfd.GetVectorFormat(&map_lp); static const NEONFormatMap map_fcvtl = {{22}, {NF_4S, NF_2D}}; VectorFormat vf_fcvtl = nfd.GetVectorFormat(&map_fcvtl); static const NEONFormatMap map_fcvtn = {{22, 30}, {NF_4H, NF_8H, NF_2S, NF_4S}}; VectorFormat vf_fcvtn = nfd.GetVectorFormat(&map_fcvtn); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); if (instr->Mask(NEON2RegMiscOpcode) <= NEON_NEG_opcode) { // These instructions all use a two bit size field, except NOT and RBIT, // which use the field to encode the operation. switch (instr->Mask(NEON2RegMiscMask)) { case NEON_REV64: rev64(vf, rd, rn); break; case NEON_REV32: rev32(vf, rd, rn); break; case NEON_REV16: rev16(vf, rd, rn); break; case NEON_SUQADD: suqadd(vf, rd, rn); break; case NEON_USQADD: usqadd(vf, rd, rn); break; case NEON_CLS: cls(vf, rd, rn); break; case NEON_CLZ: clz(vf, rd, rn); break; case NEON_CNT: cnt(vf, rd, rn); break; case NEON_SQABS: abs(vf, rd, rn).SignedSaturate(vf); break; case NEON_SQNEG: neg(vf, rd, rn).SignedSaturate(vf); break; case NEON_CMGT_zero: cmp(vf, rd, rn, 0, gt); break; case NEON_CMGE_zero: cmp(vf, rd, rn, 0, ge); break; case NEON_CMEQ_zero: cmp(vf, rd, rn, 0, eq); break; case NEON_CMLE_zero: cmp(vf, rd, rn, 0, le); break; case NEON_CMLT_zero: cmp(vf, rd, rn, 0, lt); break; case NEON_ABS: abs(vf, rd, rn); break; case NEON_NEG: neg(vf, rd, rn); break; case NEON_SADDLP: saddlp(vf_lp, rd, rn); break; case NEON_UADDLP: uaddlp(vf_lp, rd, rn); break; case NEON_SADALP: sadalp(vf_lp, rd, rn); break; case NEON_UADALP: uadalp(vf_lp, rd, rn); break; case NEON_RBIT_NOT: vf = nfd.GetVectorFormat(nfd.LogicalFormatMap()); switch (instr->FPType()) { case 0: not_(vf, rd, rn); break; case 1: rbit(vf, rd, rn); break; default: UNIMPLEMENTED(); } break; } } else { VectorFormat fpf = nfd.GetVectorFormat(nfd.FPFormatMap()); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); bool inexact_exception = false; // These instructions all use a one bit size field, except XTN, SQXTUN, // SHLL, SQXTN and UQXTN, which use a two bit size field. switch (instr->Mask(NEON2RegMiscFPMask)) { case NEON_FABS: fabs_(fpf, rd, rn); return; case NEON_FNEG: fneg(fpf, rd, rn); return; case NEON_FSQRT: fsqrt(fpf, rd, rn); return; case NEON_FCVTL: if (instr->Mask(NEON_Q)) { fcvtl2(vf_fcvtl, rd, rn); } else { fcvtl(vf_fcvtl, rd, rn); } return; case NEON_FCVTN: if (instr->Mask(NEON_Q)) { fcvtn2(vf_fcvtn, rd, rn); } else { fcvtn(vf_fcvtn, rd, rn); } return; case NEON_FCVTXN: if (instr->Mask(NEON_Q)) { fcvtxn2(vf_fcvtn, rd, rn); } else { fcvtxn(vf_fcvtn, rd, rn); } return; // The following instructions break from the switch statement, rather // than return. case NEON_FRINTI: break; // Use FPCR rounding mode. case NEON_FRINTX: inexact_exception = true; break; case NEON_FRINTA: fpcr_rounding = FPTieAway; break; case NEON_FRINTM: fpcr_rounding = FPNegativeInfinity; break; case NEON_FRINTN: fpcr_rounding = FPTieEven; break; case NEON_FRINTP: fpcr_rounding = FPPositiveInfinity; break; case NEON_FRINTZ: fpcr_rounding = FPZero; break; // The remaining cases return to the caller. case NEON_FCVTNS: fcvts(fpf, rd, rn, FPTieEven); return; case NEON_FCVTNU: fcvtu(fpf, rd, rn, FPTieEven); return; case NEON_FCVTPS: fcvts(fpf, rd, rn, FPPositiveInfinity); return; case NEON_FCVTPU: fcvtu(fpf, rd, rn, FPPositiveInfinity); return; case NEON_FCVTMS: fcvts(fpf, rd, rn, FPNegativeInfinity); return; case NEON_FCVTMU: fcvtu(fpf, rd, rn, FPNegativeInfinity); return; case NEON_FCVTZS: fcvts(fpf, rd, rn, FPZero); return; case NEON_FCVTZU: fcvtu(fpf, rd, rn, FPZero); return; case NEON_FCVTAS: fcvts(fpf, rd, rn, FPTieAway); return; case NEON_FCVTAU: fcvtu(fpf, rd, rn, FPTieAway); return; case NEON_SCVTF: scvtf(fpf, rd, rn, 0, fpcr_rounding); return; case NEON_UCVTF: ucvtf(fpf, rd, rn, 0, fpcr_rounding); return; case NEON_URSQRTE: ursqrte(fpf, rd, rn); return; case NEON_URECPE: urecpe(fpf, rd, rn); return; case NEON_FRSQRTE: frsqrte(fpf, rd, rn); return; case NEON_FRECPE: frecpe(fpf, rd, rn, fpcr_rounding); return; case NEON_FCMGT_zero: fcmp_zero(fpf, rd, rn, gt); return; case NEON_FCMGE_zero: fcmp_zero(fpf, rd, rn, ge); return; case NEON_FCMEQ_zero: fcmp_zero(fpf, rd, rn, eq); return; case NEON_FCMLE_zero: fcmp_zero(fpf, rd, rn, le); return; case NEON_FCMLT_zero: fcmp_zero(fpf, rd, rn, lt); return; default: if ((NEON_XTN_opcode <= instr->Mask(NEON2RegMiscOpcode)) && (instr->Mask(NEON2RegMiscOpcode) <= NEON_UQXTN_opcode)) { switch (instr->Mask(NEON2RegMiscMask)) { case NEON_XTN: xtn(vf, rd, rn); return; case NEON_SQXTN: sqxtn(vf, rd, rn); return; case NEON_UQXTN: uqxtn(vf, rd, rn); return; case NEON_SQXTUN: sqxtun(vf, rd, rn); return; case NEON_SHLL: vf = nfd.GetVectorFormat(nfd.LongIntegerFormatMap()); if (instr->Mask(NEON_Q)) { shll2(vf, rd, rn); } else { shll(vf, rd, rn); } return; default: UNIMPLEMENTED(); } } else { UNIMPLEMENTED(); } } // Only FRINT* instructions fall through the switch above. frint(fpf, rd, rn, fpcr_rounding, inexact_exception); } } void Simulator::VisitNEON3Same(Instruction* instr) { NEONFormatDecoder nfd(instr); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); if (instr->Mask(NEON3SameLogicalFMask) == NEON3SameLogicalFixed) { VectorFormat vf = nfd.GetVectorFormat(nfd.LogicalFormatMap()); switch (instr->Mask(NEON3SameLogicalMask)) { case NEON_AND: and_(vf, rd, rn, rm); break; case NEON_ORR: orr(vf, rd, rn, rm); break; case NEON_ORN: orn(vf, rd, rn, rm); break; case NEON_EOR: eor(vf, rd, rn, rm); break; case NEON_BIC: bic(vf, rd, rn, rm); break; case NEON_BIF: bif(vf, rd, rn, rm); break; case NEON_BIT: bit(vf, rd, rn, rm); break; case NEON_BSL: bsl(vf, rd, rn, rm); break; default: UNIMPLEMENTED(); } } else if (instr->Mask(NEON3SameFPFMask) == NEON3SameFPFixed) { VectorFormat vf = nfd.GetVectorFormat(nfd.FPFormatMap()); switch (instr->Mask(NEON3SameFPMask)) { case NEON_FADD: fadd(vf, rd, rn, rm); break; case NEON_FSUB: fsub(vf, rd, rn, rm); break; case NEON_FMUL: fmul(vf, rd, rn, rm); break; case NEON_FDIV: fdiv(vf, rd, rn, rm); break; case NEON_FMAX: fmax(vf, rd, rn, rm); break; case NEON_FMIN: fmin(vf, rd, rn, rm); break; case NEON_FMAXNM: fmaxnm(vf, rd, rn, rm); break; case NEON_FMINNM: fminnm(vf, rd, rn, rm); break; case NEON_FMLA: fmla(vf, rd, rn, rm); break; case NEON_FMLS: fmls(vf, rd, rn, rm); break; case NEON_FMULX: fmulx(vf, rd, rn, rm); break; case NEON_FACGE: fabscmp(vf, rd, rn, rm, ge); break; case NEON_FACGT: fabscmp(vf, rd, rn, rm, gt); break; case NEON_FCMEQ: fcmp(vf, rd, rn, rm, eq); break; case NEON_FCMGE: fcmp(vf, rd, rn, rm, ge); break; case NEON_FCMGT: fcmp(vf, rd, rn, rm, gt); break; case NEON_FRECPS: frecps(vf, rd, rn, rm); break; case NEON_FRSQRTS: frsqrts(vf, rd, rn, rm); break; case NEON_FABD: fabd(vf, rd, rn, rm); break; case NEON_FADDP: faddp(vf, rd, rn, rm); break; case NEON_FMAXP: fmaxp(vf, rd, rn, rm); break; case NEON_FMAXNMP: fmaxnmp(vf, rd, rn, rm); break; case NEON_FMINP: fminp(vf, rd, rn, rm); break; case NEON_FMINNMP: fminnmp(vf, rd, rn, rm); break; default: UNIMPLEMENTED(); } } else { VectorFormat vf = nfd.GetVectorFormat(); switch (instr->Mask(NEON3SameMask)) { case NEON_ADD: add(vf, rd, rn, rm); break; case NEON_ADDP: addp(vf, rd, rn, rm); break; case NEON_CMEQ: cmp(vf, rd, rn, rm, eq); break; case NEON_CMGE: cmp(vf, rd, rn, rm, ge); break; case NEON_CMGT: cmp(vf, rd, rn, rm, gt); break; case NEON_CMHI: cmp(vf, rd, rn, rm, hi); break; case NEON_CMHS: cmp(vf, rd, rn, rm, hs); break; case NEON_CMTST: cmptst(vf, rd, rn, rm); break; case NEON_MLS: mls(vf, rd, rn, rm); break; case NEON_MLA: mla(vf, rd, rn, rm); break; case NEON_MUL: mul(vf, rd, rn, rm); break; case NEON_PMUL: pmul(vf, rd, rn, rm); break; case NEON_SMAX: smax(vf, rd, rn, rm); break; case NEON_SMAXP: smaxp(vf, rd, rn, rm); break; case NEON_SMIN: smin(vf, rd, rn, rm); break; case NEON_SMINP: sminp(vf, rd, rn, rm); break; case NEON_SUB: sub(vf, rd, rn, rm); break; case NEON_UMAX: umax(vf, rd, rn, rm); break; case NEON_UMAXP: umaxp(vf, rd, rn, rm); break; case NEON_UMIN: umin(vf, rd, rn, rm); break; case NEON_UMINP: uminp(vf, rd, rn, rm); break; case NEON_SSHL: sshl(vf, rd, rn, rm); break; case NEON_USHL: ushl(vf, rd, rn, rm); break; case NEON_SABD: AbsDiff(vf, rd, rn, rm, true); break; case NEON_UABD: AbsDiff(vf, rd, rn, rm, false); break; case NEON_SABA: saba(vf, rd, rn, rm); break; case NEON_UABA: uaba(vf, rd, rn, rm); break; case NEON_UQADD: add(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQADD: add(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_UQSUB: sub(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQSUB: sub(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_SQDMULH: sqdmulh(vf, rd, rn, rm); break; case NEON_SQRDMULH: sqrdmulh(vf, rd, rn, rm); break; case NEON_UQSHL: ushl(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQSHL: sshl(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_URSHL: ushl(vf, rd, rn, rm).Round(vf); break; case NEON_SRSHL: sshl(vf, rd, rn, rm).Round(vf); break; case NEON_UQRSHL: ushl(vf, rd, rn, rm).Round(vf).UnsignedSaturate(vf); break; case NEON_SQRSHL: sshl(vf, rd, rn, rm).Round(vf).SignedSaturate(vf); break; case NEON_UHADD: add(vf, rd, rn, rm).Uhalve(vf); break; case NEON_URHADD: add(vf, rd, rn, rm).Uhalve(vf).Round(vf); break; case NEON_SHADD: add(vf, rd, rn, rm).Halve(vf); break; case NEON_SRHADD: add(vf, rd, rn, rm).Halve(vf).Round(vf); break; case NEON_UHSUB: sub(vf, rd, rn, rm).Uhalve(vf); break; case NEON_SHSUB: sub(vf, rd, rn, rm).Halve(vf); break; default: UNIMPLEMENTED(); } } } void Simulator::VisitNEON3Different(Instruction* instr) { NEONFormatDecoder nfd(instr); VectorFormat vf = nfd.GetVectorFormat(); VectorFormat vf_l = nfd.GetVectorFormat(nfd.LongIntegerFormatMap()); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(NEON3DifferentMask)) { case NEON_PMULL: pmull(vf_l, rd, rn, rm); break; case NEON_PMULL2: pmull2(vf_l, rd, rn, rm); break; case NEON_UADDL: uaddl(vf_l, rd, rn, rm); break; case NEON_UADDL2: uaddl2(vf_l, rd, rn, rm); break; case NEON_SADDL: saddl(vf_l, rd, rn, rm); break; case NEON_SADDL2: saddl2(vf_l, rd, rn, rm); break; case NEON_USUBL: usubl(vf_l, rd, rn, rm); break; case NEON_USUBL2: usubl2(vf_l, rd, rn, rm); break; case NEON_SSUBL: ssubl(vf_l, rd, rn, rm); break; case NEON_SSUBL2: ssubl2(vf_l, rd, rn, rm); break; case NEON_SABAL: sabal(vf_l, rd, rn, rm); break; case NEON_SABAL2: sabal2(vf_l, rd, rn, rm); break; case NEON_UABAL: uabal(vf_l, rd, rn, rm); break; case NEON_UABAL2: uabal2(vf_l, rd, rn, rm); break; case NEON_SABDL: sabdl(vf_l, rd, rn, rm); break; case NEON_SABDL2: sabdl2(vf_l, rd, rn, rm); break; case NEON_UABDL: uabdl(vf_l, rd, rn, rm); break; case NEON_UABDL2: uabdl2(vf_l, rd, rn, rm); break; case NEON_SMLAL: smlal(vf_l, rd, rn, rm); break; case NEON_SMLAL2: smlal2(vf_l, rd, rn, rm); break; case NEON_UMLAL: umlal(vf_l, rd, rn, rm); break; case NEON_UMLAL2: umlal2(vf_l, rd, rn, rm); break; case NEON_SMLSL: smlsl(vf_l, rd, rn, rm); break; case NEON_SMLSL2: smlsl2(vf_l, rd, rn, rm); break; case NEON_UMLSL: umlsl(vf_l, rd, rn, rm); break; case NEON_UMLSL2: umlsl2(vf_l, rd, rn, rm); break; case NEON_SMULL: smull(vf_l, rd, rn, rm); break; case NEON_SMULL2: smull2(vf_l, rd, rn, rm); break; case NEON_UMULL: umull(vf_l, rd, rn, rm); break; case NEON_UMULL2: umull2(vf_l, rd, rn, rm); break; case NEON_SQDMLAL: sqdmlal(vf_l, rd, rn, rm); break; case NEON_SQDMLAL2: sqdmlal2(vf_l, rd, rn, rm); break; case NEON_SQDMLSL: sqdmlsl(vf_l, rd, rn, rm); break; case NEON_SQDMLSL2: sqdmlsl2(vf_l, rd, rn, rm); break; case NEON_SQDMULL: sqdmull(vf_l, rd, rn, rm); break; case NEON_SQDMULL2: sqdmull2(vf_l, rd, rn, rm); break; case NEON_UADDW: uaddw(vf_l, rd, rn, rm); break; case NEON_UADDW2: uaddw2(vf_l, rd, rn, rm); break; case NEON_SADDW: saddw(vf_l, rd, rn, rm); break; case NEON_SADDW2: saddw2(vf_l, rd, rn, rm); break; case NEON_USUBW: usubw(vf_l, rd, rn, rm); break; case NEON_USUBW2: usubw2(vf_l, rd, rn, rm); break; case NEON_SSUBW: ssubw(vf_l, rd, rn, rm); break; case NEON_SSUBW2: ssubw2(vf_l, rd, rn, rm); break; case NEON_ADDHN: addhn(vf, rd, rn, rm); break; case NEON_ADDHN2: addhn2(vf, rd, rn, rm); break; case NEON_RADDHN: raddhn(vf, rd, rn, rm); break; case NEON_RADDHN2: raddhn2(vf, rd, rn, rm); break; case NEON_SUBHN: subhn(vf, rd, rn, rm); break; case NEON_SUBHN2: subhn2(vf, rd, rn, rm); break; case NEON_RSUBHN: rsubhn(vf, rd, rn, rm); break; case NEON_RSUBHN2: rsubhn2(vf, rd, rn, rm); break; default: UNIMPLEMENTED(); } } void Simulator::VisitNEONAcrossLanes(Instruction* instr) { NEONFormatDecoder nfd(instr); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); // The input operand's VectorFormat is passed for these instructions. if (instr->Mask(NEONAcrossLanesFPFMask) == NEONAcrossLanesFPFixed) { VectorFormat vf = nfd.GetVectorFormat(nfd.FPFormatMap()); switch (instr->Mask(NEONAcrossLanesFPMask)) { case NEON_FMAXV: fmaxv(vf, rd, rn); break; case NEON_FMINV: fminv(vf, rd, rn); break; case NEON_FMAXNMV: fmaxnmv(vf, rd, rn); break; case NEON_FMINNMV: fminnmv(vf, rd, rn); break; default: UNIMPLEMENTED(); } } else { VectorFormat vf = nfd.GetVectorFormat(); switch (instr->Mask(NEONAcrossLanesMask)) { case NEON_ADDV: addv(vf, rd, rn); break; case NEON_SMAXV: smaxv(vf, rd, rn); break; case NEON_SMINV: sminv(vf, rd, rn); break; case NEON_UMAXV: umaxv(vf, rd, rn); break; case NEON_UMINV: uminv(vf, rd, rn); break; case NEON_SADDLV: saddlv(vf, rd, rn); break; case NEON_UADDLV: uaddlv(vf, rd, rn); break; default: UNIMPLEMENTED(); } } } void Simulator::VisitNEONByIndexedElement(Instruction* instr) { NEONFormatDecoder nfd(instr); VectorFormat vf_r = nfd.GetVectorFormat(); VectorFormat vf = nfd.GetVectorFormat(nfd.LongIntegerFormatMap()); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); ByElementOp Op = nullptr; int rm_reg = instr->Rm(); int index = (instr->NEONH() << 1) | instr->NEONL(); if (instr->NEONSize() == 1) { rm_reg &= 0xF; index = (index << 1) | instr->NEONM(); } switch (instr->Mask(NEONByIndexedElementMask)) { case NEON_MUL_byelement: Op = &Simulator::mul; vf = vf_r; break; case NEON_MLA_byelement: Op = &Simulator::mla; vf = vf_r; break; case NEON_MLS_byelement: Op = &Simulator::mls; vf = vf_r; break; case NEON_SQDMULH_byelement: Op = &Simulator::sqdmulh; vf = vf_r; break; case NEON_SQRDMULH_byelement: Op = &Simulator::sqrdmulh; vf = vf_r; break; case NEON_SMULL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::smull2; } else { Op = &Simulator::smull; } break; case NEON_UMULL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::umull2; } else { Op = &Simulator::umull; } break; case NEON_SMLAL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::smlal2; } else { Op = &Simulator::smlal; } break; case NEON_UMLAL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::umlal2; } else { Op = &Simulator::umlal; } break; case NEON_SMLSL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::smlsl2; } else { Op = &Simulator::smlsl; } break; case NEON_UMLSL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::umlsl2; } else { Op = &Simulator::umlsl; } break; case NEON_SQDMULL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::sqdmull2; } else { Op = &Simulator::sqdmull; } break; case NEON_SQDMLAL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::sqdmlal2; } else { Op = &Simulator::sqdmlal; } break; case NEON_SQDMLSL_byelement: if (instr->Mask(NEON_Q)) { Op = &Simulator::sqdmlsl2; } else { Op = &Simulator::sqdmlsl; } break; default: index = instr->NEONH(); if ((instr->FPType() & 1) == 0) { index = (index << 1) | instr->NEONL(); } vf = nfd.GetVectorFormat(nfd.FPFormatMap()); switch (instr->Mask(NEONByIndexedElementFPMask)) { case NEON_FMUL_byelement: Op = &Simulator::fmul; break; case NEON_FMLA_byelement: Op = &Simulator::fmla; break; case NEON_FMLS_byelement: Op = &Simulator::fmls; break; case NEON_FMULX_byelement: Op = &Simulator::fmulx; break; default: UNIMPLEMENTED(); } } (this->*Op)(vf, rd, rn, vreg(rm_reg), index); } void Simulator::VisitNEONCopy(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::TriangularFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); int imm5 = instr->ImmNEON5(); int lsb = LowestSetBitPosition(imm5); int reg_index = imm5 >> lsb; if (instr->Mask(NEONCopyInsElementMask) == NEON_INS_ELEMENT) { int imm4 = instr->ImmNEON4(); DCHECK_GE(lsb, 1); int rn_index = imm4 >> (lsb - 1); ins_element(vf, rd, reg_index, rn, rn_index); } else if (instr->Mask(NEONCopyInsGeneralMask) == NEON_INS_GENERAL) { ins_immediate(vf, rd, reg_index, xreg(instr->Rn())); } else if (instr->Mask(NEONCopyUmovMask) == NEON_UMOV) { uint64_t value = LogicVRegister(rn).Uint(vf, reg_index); value &= MaxUintFromFormat(vf); set_xreg(instr->Rd(), value); } else if (instr->Mask(NEONCopyUmovMask) == NEON_SMOV) { int64_t value = LogicVRegister(rn).Int(vf, reg_index); if (instr->NEONQ()) { set_xreg(instr->Rd(), value); } else { DCHECK(is_int32(value)); set_wreg(instr->Rd(), static_cast<int32_t>(value)); } } else if (instr->Mask(NEONCopyDupElementMask) == NEON_DUP_ELEMENT) { dup_element(vf, rd, rn, reg_index); } else if (instr->Mask(NEONCopyDupGeneralMask) == NEON_DUP_GENERAL) { dup_immediate(vf, rd, xreg(instr->Rn())); } else { UNIMPLEMENTED(); } } void Simulator::VisitNEONExtract(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LogicalFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); if (instr->Mask(NEONExtractMask) == NEON_EXT) { int index = instr->ImmNEONExt(); ext(vf, rd, rn, rm, index); } else { UNIMPLEMENTED(); } } void Simulator::NEONLoadStoreMultiStructHelper(const Instruction* instr, AddrMode addr_mode) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LoadStoreFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); uint64_t addr_base = xreg(instr->Rn(), Reg31IsStackPointer); int reg_size = RegisterSizeInBytesFromFormat(vf); int reg[4]; uint64_t addr[4]; for (int i = 0; i < 4; i++) { reg[i] = (instr->Rt() + i) % kNumberOfVRegisters; addr[i] = addr_base + (i * reg_size); } int count = 1; bool log_read = true; // Bit 23 determines whether this is an offset or post-index addressing mode. // In offset mode, bits 20 to 16 should be zero; these bits encode the // register of immediate in post-index mode. if ((instr->Bit(23) == 0) && (instr->Bits(20, 16) != 0)) { UNREACHABLE(); } // We use the PostIndex mask here, as it works in this case for both Offset // and PostIndex addressing. switch (instr->Mask(NEONLoadStoreMultiStructPostIndexMask)) { case NEON_LD1_4v: case NEON_LD1_4v_post: ld1(vf, vreg(reg[3]), addr[3]); count++; V8_FALLTHROUGH; case NEON_LD1_3v: case NEON_LD1_3v_post: ld1(vf, vreg(reg[2]), addr[2]); count++; V8_FALLTHROUGH; case NEON_LD1_2v: case NEON_LD1_2v_post: ld1(vf, vreg(reg[1]), addr[1]); count++; V8_FALLTHROUGH; case NEON_LD1_1v: case NEON_LD1_1v_post: ld1(vf, vreg(reg[0]), addr[0]); break; case NEON_ST1_4v: case NEON_ST1_4v_post: st1(vf, vreg(reg[3]), addr[3]); count++; V8_FALLTHROUGH; case NEON_ST1_3v: case NEON_ST1_3v_post: st1(vf, vreg(reg[2]), addr[2]); count++; V8_FALLTHROUGH; case NEON_ST1_2v: case NEON_ST1_2v_post: st1(vf, vreg(reg[1]), addr[1]); count++; V8_FALLTHROUGH; case NEON_ST1_1v: case NEON_ST1_1v_post: st1(vf, vreg(reg[0]), addr[0]); log_read = false; break; case NEON_LD2_post: case NEON_LD2: ld2(vf, vreg(reg[0]), vreg(reg[1]), addr[0]); count = 2; break; case NEON_ST2: case NEON_ST2_post: st2(vf, vreg(reg[0]), vreg(reg[1]), addr[0]); count = 2; log_read = false; break; case NEON_LD3_post: case NEON_LD3: ld3(vf, vreg(reg[0]), vreg(reg[1]), vreg(reg[2]), addr[0]); count = 3; break; case NEON_ST3: case NEON_ST3_post: st3(vf, vreg(reg[0]), vreg(reg[1]), vreg(reg[2]), addr[0]); count = 3; log_read = false; break; case NEON_LD4_post: case NEON_LD4: ld4(vf, vreg(reg[0]), vreg(reg[1]), vreg(reg[2]), vreg(reg[3]), addr[0]); count = 4; break; case NEON_ST4: case NEON_ST4_post: st4(vf, vreg(reg[0]), vreg(reg[1]), vreg(reg[2]), vreg(reg[3]), addr[0]); count = 4; log_read = false; break; default: UNIMPLEMENTED(); } { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); if (log_read) { local_monitor_.NotifyLoad(); } else { local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); } } // Explicitly log the register update whilst we have type information. for (int i = 0; i < count; i++) { // For de-interleaving loads, only print the base address. int lane_size = LaneSizeInBytesFromFormat(vf); PrintRegisterFormat format = GetPrintRegisterFormatTryFP( GetPrintRegisterFormatForSize(reg_size, lane_size)); if (log_read) { LogVRead(addr_base, reg[i], format); } else { LogVWrite(addr_base, reg[i], format); } } if (addr_mode == PostIndex) { int rm = instr->Rm(); // The immediate post index addressing mode is indicated by rm = 31. // The immediate is implied by the number of vector registers used. addr_base += (rm == 31) ? RegisterSizeInBytesFromFormat(vf) * count : xreg(rm); set_xreg(instr->Rn(), addr_base); } else { DCHECK_EQ(addr_mode, Offset); } } void Simulator::VisitNEONLoadStoreMultiStruct(Instruction* instr) { NEONLoadStoreMultiStructHelper(instr, Offset); } void Simulator::VisitNEONLoadStoreMultiStructPostIndex(Instruction* instr) { NEONLoadStoreMultiStructHelper(instr, PostIndex); } void Simulator::NEONLoadStoreSingleStructHelper(const Instruction* instr, AddrMode addr_mode) { uint64_t addr = xreg(instr->Rn(), Reg31IsStackPointer); int rt = instr->Rt(); // Bit 23 determines whether this is an offset or post-index addressing mode. // In offset mode, bits 20 to 16 should be zero; these bits encode the // register of immediate in post-index mode. DCHECK_IMPLIES(instr->Bit(23) == 0, instr->Bits(20, 16) == 0); bool do_load = false; NEONFormatDecoder nfd(instr, NEONFormatDecoder::LoadStoreFormatMap()); VectorFormat vf_t = nfd.GetVectorFormat(); VectorFormat vf = kFormat16B; // We use the PostIndex mask here, as it works in this case for both Offset // and PostIndex addressing. switch (instr->Mask(NEONLoadStoreSingleStructPostIndexMask)) { case NEON_LD1_b: case NEON_LD1_b_post: case NEON_LD2_b: case NEON_LD2_b_post: case NEON_LD3_b: case NEON_LD3_b_post: case NEON_LD4_b: case NEON_LD4_b_post: do_load = true; V8_FALLTHROUGH; case NEON_ST1_b: case NEON_ST1_b_post: case NEON_ST2_b: case NEON_ST2_b_post: case NEON_ST3_b: case NEON_ST3_b_post: case NEON_ST4_b: case NEON_ST4_b_post: break; case NEON_LD1_h: case NEON_LD1_h_post: case NEON_LD2_h: case NEON_LD2_h_post: case NEON_LD3_h: case NEON_LD3_h_post: case NEON_LD4_h: case NEON_LD4_h_post: do_load = true; V8_FALLTHROUGH; case NEON_ST1_h: case NEON_ST1_h_post: case NEON_ST2_h: case NEON_ST2_h_post: case NEON_ST3_h: case NEON_ST3_h_post: case NEON_ST4_h: case NEON_ST4_h_post: vf = kFormat8H; break; case NEON_LD1_s: case NEON_LD1_s_post: case NEON_LD2_s: case NEON_LD2_s_post: case NEON_LD3_s: case NEON_LD3_s_post: case NEON_LD4_s: case NEON_LD4_s_post: do_load = true; V8_FALLTHROUGH; case NEON_ST1_s: case NEON_ST1_s_post: case NEON_ST2_s: case NEON_ST2_s_post: case NEON_ST3_s: case NEON_ST3_s_post: case NEON_ST4_s: case NEON_ST4_s_post: { static_assert((NEON_LD1_s | (1 << NEONLSSize_offset)) == NEON_LD1_d, "LSB of size distinguishes S and D registers."); static_assert( (NEON_LD1_s_post | (1 << NEONLSSize_offset)) == NEON_LD1_d_post, "LSB of size distinguishes S and D registers."); static_assert((NEON_ST1_s | (1 << NEONLSSize_offset)) == NEON_ST1_d, "LSB of size distinguishes S and D registers."); static_assert( (NEON_ST1_s_post | (1 << NEONLSSize_offset)) == NEON_ST1_d_post, "LSB of size distinguishes S and D registers."); vf = ((instr->NEONLSSize() & 1) == 0) ? kFormat4S : kFormat2D; break; } case NEON_LD1R: case NEON_LD1R_post: { vf = vf_t; if (!ProbeMemory(addr, LaneSizeInBytesFromFormat(vf))) return; ld1r(vf, vreg(rt), addr); do_load = true; break; } case NEON_LD2R: case NEON_LD2R_post: { vf = vf_t; if (!ProbeMemory(addr, 2 * LaneSizeInBytesFromFormat(vf))) return; int rt2 = (rt + 1) % kNumberOfVRegisters; ld2r(vf, vreg(rt), vreg(rt2), addr); do_load = true; break; } case NEON_LD3R: case NEON_LD3R_post: { vf = vf_t; if (!ProbeMemory(addr, 3 * LaneSizeInBytesFromFormat(vf))) return; int rt2 = (rt + 1) % kNumberOfVRegisters; int rt3 = (rt2 + 1) % kNumberOfVRegisters; ld3r(vf, vreg(rt), vreg(rt2), vreg(rt3), addr); do_load = true; break; } case NEON_LD4R: case NEON_LD4R_post: { vf = vf_t; if (!ProbeMemory(addr, 4 * LaneSizeInBytesFromFormat(vf))) return; int rt2 = (rt + 1) % kNumberOfVRegisters; int rt3 = (rt2 + 1) % kNumberOfVRegisters; int rt4 = (rt3 + 1) % kNumberOfVRegisters; ld4r(vf, vreg(rt), vreg(rt2), vreg(rt3), vreg(rt4), addr); do_load = true; break; } default: UNIMPLEMENTED(); } PrintRegisterFormat print_format = GetPrintRegisterFormatTryFP(GetPrintRegisterFormat(vf)); // Make sure that the print_format only includes a single lane. print_format = static_cast<PrintRegisterFormat>(print_format & ~kPrintRegAsVectorMask); int esize = LaneSizeInBytesFromFormat(vf); int index_shift = LaneSizeInBytesLog2FromFormat(vf); int lane = instr->NEONLSIndex(index_shift); int scale = 0; int rt2 = (rt + 1) % kNumberOfVRegisters; int rt3 = (rt2 + 1) % kNumberOfVRegisters; int rt4 = (rt3 + 1) % kNumberOfVRegisters; switch (instr->Mask(NEONLoadStoreSingleLenMask)) { case NEONLoadStoreSingle1: scale = 1; if (!ProbeMemory(addr, scale * esize)) return; if (do_load) { ld1(vf, vreg(rt), lane, addr); LogVRead(addr, rt, print_format, lane); } else { st1(vf, vreg(rt), lane, addr); LogVWrite(addr, rt, print_format, lane); } break; case NEONLoadStoreSingle2: scale = 2; if (!ProbeMemory(addr, scale * esize)) return; if (do_load) { ld2(vf, vreg(rt), vreg(rt2), lane, addr); LogVRead(addr, rt, print_format, lane); LogVRead(addr + esize, rt2, print_format, lane); } else { st2(vf, vreg(rt), vreg(rt2), lane, addr); LogVWrite(addr, rt, print_format, lane); LogVWrite(addr + esize, rt2, print_format, lane); } break; case NEONLoadStoreSingle3: scale = 3; if (!ProbeMemory(addr, scale * esize)) return; if (do_load) { ld3(vf, vreg(rt), vreg(rt2), vreg(rt3), lane, addr); LogVRead(addr, rt, print_format, lane); LogVRead(addr + esize, rt2, print_format, lane); LogVRead(addr + (2 * esize), rt3, print_format, lane); } else { st3(vf, vreg(rt), vreg(rt2), vreg(rt3), lane, addr); LogVWrite(addr, rt, print_format, lane); LogVWrite(addr + esize, rt2, print_format, lane); LogVWrite(addr + (2 * esize), rt3, print_format, lane); } break; case NEONLoadStoreSingle4: scale = 4; if (!ProbeMemory(addr, scale * esize)) return; if (do_load) { ld4(vf, vreg(rt), vreg(rt2), vreg(rt3), vreg(rt4), lane, addr); LogVRead(addr, rt, print_format, lane); LogVRead(addr + esize, rt2, print_format, lane); LogVRead(addr + (2 * esize), rt3, print_format, lane); LogVRead(addr + (3 * esize), rt4, print_format, lane); } else { st4(vf, vreg(rt), vreg(rt2), vreg(rt3), vreg(rt4), lane, addr); LogVWrite(addr, rt, print_format, lane); LogVWrite(addr + esize, rt2, print_format, lane); LogVWrite(addr + (2 * esize), rt3, print_format, lane); LogVWrite(addr + (3 * esize), rt4, print_format, lane); } break; default: UNIMPLEMENTED(); } { base::MutexGuard lock_guard(&GlobalMonitor::Get()->mutex); if (do_load) { local_monitor_.NotifyLoad(); } else { local_monitor_.NotifyStore(); GlobalMonitor::Get()->NotifyStore_Locked(&global_monitor_processor_); } } if (addr_mode == PostIndex) { int rm = instr->Rm(); int lane_size = LaneSizeInBytesFromFormat(vf); set_xreg(instr->Rn(), addr + ((rm == 31) ? (scale * lane_size) : xreg(rm))); } } void Simulator::VisitNEONLoadStoreSingleStruct(Instruction* instr) { NEONLoadStoreSingleStructHelper(instr, Offset); } void Simulator::VisitNEONLoadStoreSingleStructPostIndex(Instruction* instr) { NEONLoadStoreSingleStructHelper(instr, PostIndex); } void Simulator::VisitNEONModifiedImmediate(Instruction* instr) { SimVRegister& rd = vreg(instr->Rd()); int cmode = instr->NEONCmode(); int cmode_3_1 = (cmode >> 1) & 7; int cmode_3 = (cmode >> 3) & 1; int cmode_2 = (cmode >> 2) & 1; int cmode_1 = (cmode >> 1) & 1; int cmode_0 = cmode & 1; int q = instr->NEONQ(); int op_bit = instr->NEONModImmOp(); uint64_t imm8 = instr->ImmNEONabcdefgh(); // Find the format and immediate value uint64_t imm = 0; VectorFormat vform = kFormatUndefined; switch (cmode_3_1) { case 0x0: case 0x1: case 0x2: case 0x3: vform = (q == 1) ? kFormat4S : kFormat2S; imm = imm8 << (8 * cmode_3_1); break; case 0x4: case 0x5: vform = (q == 1) ? kFormat8H : kFormat4H; imm = imm8 << (8 * cmode_1); break; case 0x6: vform = (q == 1) ? kFormat4S : kFormat2S; if (cmode_0 == 0) { imm = imm8 << 8 | 0x000000FF; } else { imm = imm8 << 16 | 0x0000FFFF; } break; case 0x7: if (cmode_0 == 0 && op_bit == 0) { vform = q ? kFormat16B : kFormat8B; imm = imm8; } else if (cmode_0 == 0 && op_bit == 1) { vform = q ? kFormat2D : kFormat1D; imm = 0; for (int i = 0; i < 8; ++i) { if (imm8 & (1ULL << i)) { imm |= (UINT64_C(0xFF) << (8 * i)); } } } else { // cmode_0 == 1, cmode == 0xF. if (op_bit == 0) { vform = q ? kFormat4S : kFormat2S; imm = base::bit_cast<uint32_t>(instr->ImmNEONFP32()); } else if (q == 1) { vform = kFormat2D; imm = base::bit_cast<uint64_t>(instr->ImmNEONFP64()); } else { DCHECK((q == 0) && (op_bit == 1) && (cmode == 0xF)); VisitUnallocated(instr); } } break; default: UNREACHABLE(); } // Find the operation. NEONModifiedImmediateOp op; if (cmode_3 == 0) { if (cmode_0 == 0) { op = op_bit ? NEONModifiedImmediate_MVNI : NEONModifiedImmediate_MOVI; } else { // cmode<0> == '1' op = op_bit ? NEONModifiedImmediate_BIC : NEONModifiedImmediate_ORR; } } else { // cmode<3> == '1' if (cmode_2 == 0) { if (cmode_0 == 0) { op = op_bit ? NEONModifiedImmediate_MVNI : NEONModifiedImmediate_MOVI; } else { // cmode<0> == '1' op = op_bit ? NEONModifiedImmediate_BIC : NEONModifiedImmediate_ORR; } } else { // cmode<2> == '1' if (cmode_1 == 0) { op = op_bit ? NEONModifiedImmediate_MVNI : NEONModifiedImmediate_MOVI; } else { // cmode<1> == '1' if (cmode_0 == 0) { op = NEONModifiedImmediate_MOVI; } else { // cmode<0> == '1' op = NEONModifiedImmediate_MOVI; } } } } // Call the logic function. switch (op) { case NEONModifiedImmediate_ORR: orr(vform, rd, rd, imm); break; case NEONModifiedImmediate_BIC: bic(vform, rd, rd, imm); break; case NEONModifiedImmediate_MOVI: movi(vform, rd, imm); break; case NEONModifiedImmediate_MVNI: mvni(vform, rd, imm); break; default: VisitUnimplemented(instr); } } void Simulator::VisitNEONScalar2RegMisc(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::ScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); if (instr->Mask(NEON2RegMiscOpcode) <= NEON_NEG_scalar_opcode) { // These instructions all use a two bit size field, except NOT and RBIT, // which use the field to encode the operation. switch (instr->Mask(NEONScalar2RegMiscMask)) { case NEON_CMEQ_zero_scalar: cmp(vf, rd, rn, 0, eq); break; case NEON_CMGE_zero_scalar: cmp(vf, rd, rn, 0, ge); break; case NEON_CMGT_zero_scalar: cmp(vf, rd, rn, 0, gt); break; case NEON_CMLT_zero_scalar: cmp(vf, rd, rn, 0, lt); break; case NEON_CMLE_zero_scalar: cmp(vf, rd, rn, 0, le); break; case NEON_ABS_scalar: abs(vf, rd, rn); break; case NEON_SQABS_scalar: abs(vf, rd, rn).SignedSaturate(vf); break; case NEON_NEG_scalar: neg(vf, rd, rn); break; case NEON_SQNEG_scalar: neg(vf, rd, rn).SignedSaturate(vf); break; case NEON_SUQADD_scalar: suqadd(vf, rd, rn); break; case NEON_USQADD_scalar: usqadd(vf, rd, rn); break; default: UNIMPLEMENTED(); } } else { VectorFormat fpf = nfd.GetVectorFormat(nfd.FPScalarFormatMap()); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); // These instructions all use a one bit size field, except SQXTUN, SQXTN // and UQXTN, which use a two bit size field. switch (instr->Mask(NEONScalar2RegMiscFPMask)) { case NEON_FRECPE_scalar: frecpe(fpf, rd, rn, fpcr_rounding); break; case NEON_FRECPX_scalar: frecpx(fpf, rd, rn); break; case NEON_FRSQRTE_scalar: frsqrte(fpf, rd, rn); break; case NEON_FCMGT_zero_scalar: fcmp_zero(fpf, rd, rn, gt); break; case NEON_FCMGE_zero_scalar: fcmp_zero(fpf, rd, rn, ge); break; case NEON_FCMEQ_zero_scalar: fcmp_zero(fpf, rd, rn, eq); break; case NEON_FCMLE_zero_scalar: fcmp_zero(fpf, rd, rn, le); break; case NEON_FCMLT_zero_scalar: fcmp_zero(fpf, rd, rn, lt); break; case NEON_SCVTF_scalar: scvtf(fpf, rd, rn, 0, fpcr_rounding); break; case NEON_UCVTF_scalar: ucvtf(fpf, rd, rn, 0, fpcr_rounding); break; case NEON_FCVTNS_scalar: fcvts(fpf, rd, rn, FPTieEven); break; case NEON_FCVTNU_scalar: fcvtu(fpf, rd, rn, FPTieEven); break; case NEON_FCVTPS_scalar: fcvts(fpf, rd, rn, FPPositiveInfinity); break; case NEON_FCVTPU_scalar: fcvtu(fpf, rd, rn, FPPositiveInfinity); break; case NEON_FCVTMS_scalar: fcvts(fpf, rd, rn, FPNegativeInfinity); break; case NEON_FCVTMU_scalar: fcvtu(fpf, rd, rn, FPNegativeInfinity); break; case NEON_FCVTZS_scalar: fcvts(fpf, rd, rn, FPZero); break; case NEON_FCVTZU_scalar: fcvtu(fpf, rd, rn, FPZero); break; case NEON_FCVTAS_scalar: fcvts(fpf, rd, rn, FPTieAway); break; case NEON_FCVTAU_scalar: fcvtu(fpf, rd, rn, FPTieAway); break; case NEON_FCVTXN_scalar: // Unlike all of the other FP instructions above, fcvtxn encodes dest // size S as size<0>=1. There's only one case, so we ignore the form. DCHECK_EQ(instr->Bit(22), 1); fcvtxn(kFormatS, rd, rn); break; default: switch (instr->Mask(NEONScalar2RegMiscMask)) { case NEON_SQXTN_scalar: sqxtn(vf, rd, rn); break; case NEON_UQXTN_scalar: uqxtn(vf, rd, rn); break; case NEON_SQXTUN_scalar: sqxtun(vf, rd, rn); break; default: UNIMPLEMENTED(); } } } } void Simulator::VisitNEONScalar3Diff(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LongScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(NEONScalar3DiffMask)) { case NEON_SQDMLAL_scalar: sqdmlal(vf, rd, rn, rm); break; case NEON_SQDMLSL_scalar: sqdmlsl(vf, rd, rn, rm); break; case NEON_SQDMULL_scalar: sqdmull(vf, rd, rn, rm); break; default: UNIMPLEMENTED(); } } void Simulator::VisitNEONScalar3Same(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::ScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); if (instr->Mask(NEONScalar3SameFPFMask) == NEONScalar3SameFPFixed) { vf = nfd.GetVectorFormat(nfd.FPScalarFormatMap()); switch (instr->Mask(NEONScalar3SameFPMask)) { case NEON_FMULX_scalar: fmulx(vf, rd, rn, rm); break; case NEON_FACGE_scalar: fabscmp(vf, rd, rn, rm, ge); break; case NEON_FACGT_scalar: fabscmp(vf, rd, rn, rm, gt); break; case NEON_FCMEQ_scalar: fcmp(vf, rd, rn, rm, eq); break; case NEON_FCMGE_scalar: fcmp(vf, rd, rn, rm, ge); break; case NEON_FCMGT_scalar: fcmp(vf, rd, rn, rm, gt); break; case NEON_FRECPS_scalar: frecps(vf, rd, rn, rm); break; case NEON_FRSQRTS_scalar: frsqrts(vf, rd, rn, rm); break; case NEON_FABD_scalar: fabd(vf, rd, rn, rm); break; default: UNIMPLEMENTED(); } } else { switch (instr->Mask(NEONScalar3SameMask)) { case NEON_ADD_scalar: add(vf, rd, rn, rm); break; case NEON_SUB_scalar: sub(vf, rd, rn, rm); break; case NEON_CMEQ_scalar: cmp(vf, rd, rn, rm, eq); break; case NEON_CMGE_scalar: cmp(vf, rd, rn, rm, ge); break; case NEON_CMGT_scalar: cmp(vf, rd, rn, rm, gt); break; case NEON_CMHI_scalar: cmp(vf, rd, rn, rm, hi); break; case NEON_CMHS_scalar: cmp(vf, rd, rn, rm, hs); break; case NEON_CMTST_scalar: cmptst(vf, rd, rn, rm); break; case NEON_USHL_scalar: ushl(vf, rd, rn, rm); break; case NEON_SSHL_scalar: sshl(vf, rd, rn, rm); break; case NEON_SQDMULH_scalar: sqdmulh(vf, rd, rn, rm); break; case NEON_SQRDMULH_scalar: sqrdmulh(vf, rd, rn, rm); break; case NEON_UQADD_scalar: add(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQADD_scalar: add(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_UQSUB_scalar: sub(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQSUB_scalar: sub(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_UQSHL_scalar: ushl(vf, rd, rn, rm).UnsignedSaturate(vf); break; case NEON_SQSHL_scalar: sshl(vf, rd, rn, rm).SignedSaturate(vf); break; case NEON_URSHL_scalar: ushl(vf, rd, rn, rm).Round(vf); break; case NEON_SRSHL_scalar: sshl(vf, rd, rn, rm).Round(vf); break; case NEON_UQRSHL_scalar: ushl(vf, rd, rn, rm).Round(vf).UnsignedSaturate(vf); break; case NEON_SQRSHL_scalar: sshl(vf, rd, rn, rm).Round(vf).SignedSaturate(vf); break; default: UNIMPLEMENTED(); } } } void Simulator::VisitNEONScalarByIndexedElement(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LongScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); VectorFormat vf_r = nfd.GetVectorFormat(nfd.ScalarFormatMap()); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); ByElementOp Op = nullptr; int rm_reg = instr->Rm(); int index = (instr->NEONH() << 1) | instr->NEONL(); if (instr->NEONSize() == 1) { rm_reg &= 0xF; index = (index << 1) | instr->NEONM(); } switch (instr->Mask(NEONScalarByIndexedElementMask)) { case NEON_SQDMULL_byelement_scalar: Op = &Simulator::sqdmull; break; case NEON_SQDMLAL_byelement_scalar: Op = &Simulator::sqdmlal; break; case NEON_SQDMLSL_byelement_scalar: Op = &Simulator::sqdmlsl; break; case NEON_SQDMULH_byelement_scalar: Op = &Simulator::sqdmulh; vf = vf_r; break; case NEON_SQRDMULH_byelement_scalar: Op = &Simulator::sqrdmulh; vf = vf_r; break; default: vf = nfd.GetVectorFormat(nfd.FPScalarFormatMap()); index = instr->NEONH(); if ((instr->FPType() & 1) == 0) { index = (index << 1) | instr->NEONL(); } switch (instr->Mask(NEONScalarByIndexedElementFPMask)) { case NEON_FMUL_byelement_scalar: Op = &Simulator::fmul; break; case NEON_FMLA_byelement_scalar: Op = &Simulator::fmla; break; case NEON_FMLS_byelement_scalar: Op = &Simulator::fmls; break; case NEON_FMULX_byelement_scalar: Op = &Simulator::fmulx; break; default: UNIMPLEMENTED(); } } (this->*Op)(vf, rd, rn, vreg(rm_reg), index); } void Simulator::VisitNEONScalarCopy(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::TriangularScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); if (instr->Mask(NEONScalarCopyMask) == NEON_DUP_ELEMENT_scalar) { int imm5 = instr->ImmNEON5(); int lsb = LowestSetBitPosition(imm5); int rn_index = imm5 >> lsb; dup_element(vf, rd, rn, rn_index); } else { UNIMPLEMENTED(); } } void Simulator::VisitNEONScalarPairwise(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::FPScalarFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); switch (instr->Mask(NEONScalarPairwiseMask)) { case NEON_ADDP_scalar: addp(vf, rd, rn); break; case NEON_FADDP_scalar: faddp(vf, rd, rn); break; case NEON_FMAXP_scalar: fmaxp(vf, rd, rn); break; case NEON_FMAXNMP_scalar: fmaxnmp(vf, rd, rn); break; case NEON_FMINP_scalar: fminp(vf, rd, rn); break; case NEON_FMINNMP_scalar: fminnmp(vf, rd, rn); break; default: UNIMPLEMENTED(); } } void Simulator::VisitNEONScalarShiftImmediate(Instruction* instr) { SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); static const NEONFormatMap map = { {22, 21, 20, 19}, {NF_UNDEF, NF_B, NF_H, NF_H, NF_S, NF_S, NF_S, NF_S, NF_D, NF_D, NF_D, NF_D, NF_D, NF_D, NF_D, NF_D}}; NEONFormatDecoder nfd(instr, &map); VectorFormat vf = nfd.GetVectorFormat(); int highestSetBit = HighestSetBitPosition(instr->ImmNEONImmh()); int immhimmb = instr->ImmNEONImmhImmb(); int right_shift = (16 << highestSetBit) - immhimmb; int left_shift = immhimmb - (8 << highestSetBit); switch (instr->Mask(NEONScalarShiftImmediateMask)) { case NEON_SHL_scalar: shl(vf, rd, rn, left_shift); break; case NEON_SLI_scalar: sli(vf, rd, rn, left_shift); break; case NEON_SQSHL_imm_scalar: sqshl(vf, rd, rn, left_shift); break; case NEON_UQSHL_imm_scalar: uqshl(vf, rd, rn, left_shift); break; case NEON_SQSHLU_scalar: sqshlu(vf, rd, rn, left_shift); break; case NEON_SRI_scalar: sri(vf, rd, rn, right_shift); break; case NEON_SSHR_scalar: sshr(vf, rd, rn, right_shift); break; case NEON_USHR_scalar: ushr(vf, rd, rn, right_shift); break; case NEON_SRSHR_scalar: sshr(vf, rd, rn, right_shift).Round(vf); break; case NEON_URSHR_scalar: ushr(vf, rd, rn, right_shift).Round(vf); break; case NEON_SSRA_scalar: ssra(vf, rd, rn, right_shift); break; case NEON_USRA_scalar: usra(vf, rd, rn, right_shift); break; case NEON_SRSRA_scalar: srsra(vf, rd, rn, right_shift); break; case NEON_URSRA_scalar: ursra(vf, rd, rn, right_shift); break; case NEON_UQSHRN_scalar: uqshrn(vf, rd, rn, right_shift); break; case NEON_UQRSHRN_scalar: uqrshrn(vf, rd, rn, right_shift); break; case NEON_SQSHRN_scalar: sqshrn(vf, rd, rn, right_shift); break; case NEON_SQRSHRN_scalar: sqrshrn(vf, rd, rn, right_shift); break; case NEON_SQSHRUN_scalar: sqshrun(vf, rd, rn, right_shift); break; case NEON_SQRSHRUN_scalar: sqrshrun(vf, rd, rn, right_shift); break; case NEON_FCVTZS_imm_scalar: fcvts(vf, rd, rn, FPZero, right_shift); break; case NEON_FCVTZU_imm_scalar: fcvtu(vf, rd, rn, FPZero, right_shift); break; case NEON_SCVTF_imm_scalar: scvtf(vf, rd, rn, right_shift, fpcr_rounding); break; case NEON_UCVTF_imm_scalar: ucvtf(vf, rd, rn, right_shift, fpcr_rounding); break; default: UNIMPLEMENTED(); } } void Simulator::VisitNEONShiftImmediate(Instruction* instr) { SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); FPRounding fpcr_rounding = static_cast<FPRounding>(fpcr().RMode()); // 00010->8B, 00011->16B, 001x0->4H, 001x1->8H, // 01xx0->2S, 01xx1->4S, 1xxx1->2D, all others undefined. static const NEONFormatMap map = { {22, 21, 20, 19, 30}, {NF_UNDEF, NF_UNDEF, NF_8B, NF_16B, NF_4H, NF_8H, NF_4H, NF_8H, NF_2S, NF_4S, NF_2S, NF_4S, NF_2S, NF_4S, NF_2S, NF_4S, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D, NF_UNDEF, NF_2D}}; NEONFormatDecoder nfd(instr, &map); VectorFormat vf = nfd.GetVectorFormat(); // 0001->8H, 001x->4S, 01xx->2D, all others undefined. static const NEONFormatMap map_l = { {22, 21, 20, 19}, {NF_UNDEF, NF_8H, NF_4S, NF_4S, NF_2D, NF_2D, NF_2D, NF_2D}}; VectorFormat vf_l = nfd.GetVectorFormat(&map_l); int highestSetBit = HighestSetBitPosition(instr->ImmNEONImmh()); int immhimmb = instr->ImmNEONImmhImmb(); int right_shift = (16 << highestSetBit) - immhimmb; int left_shift = immhimmb - (8 << highestSetBit); switch (instr->Mask(NEONShiftImmediateMask)) { case NEON_SHL: shl(vf, rd, rn, left_shift); break; case NEON_SLI: sli(vf, rd, rn, left_shift); break; case NEON_SQSHLU: sqshlu(vf, rd, rn, left_shift); break; case NEON_SRI: sri(vf, rd, rn, right_shift); break; case NEON_SSHR: sshr(vf, rd, rn, right_shift); break; case NEON_USHR: ushr(vf, rd, rn, right_shift); break; case NEON_SRSHR: sshr(vf, rd, rn, right_shift).Round(vf); break; case NEON_URSHR: ushr(vf, rd, rn, right_shift).Round(vf); break; case NEON_SSRA: ssra(vf, rd, rn, right_shift); break; case NEON_USRA: usra(vf, rd, rn, right_shift); break; case NEON_SRSRA: srsra(vf, rd, rn, right_shift); break; case NEON_URSRA: ursra(vf, rd, rn, right_shift); break; case NEON_SQSHL_imm: sqshl(vf, rd, rn, left_shift); break; case NEON_UQSHL_imm: uqshl(vf, rd, rn, left_shift); break; case NEON_SCVTF_imm: scvtf(vf, rd, rn, right_shift, fpcr_rounding); break; case NEON_UCVTF_imm: ucvtf(vf, rd, rn, right_shift, fpcr_rounding); break; case NEON_FCVTZS_imm: fcvts(vf, rd, rn, FPZero, right_shift); break; case NEON_FCVTZU_imm: fcvtu(vf, rd, rn, FPZero, right_shift); break; case NEON_SSHLL: vf = vf_l; if (instr->Mask(NEON_Q)) { sshll2(vf, rd, rn, left_shift); } else { sshll(vf, rd, rn, left_shift); } break; case NEON_USHLL: vf = vf_l; if (instr->Mask(NEON_Q)) { ushll2(vf, rd, rn, left_shift); } else { ushll(vf, rd, rn, left_shift); } break; case NEON_SHRN: if (instr->Mask(NEON_Q)) { shrn2(vf, rd, rn, right_shift); } else { shrn(vf, rd, rn, right_shift); } break; case NEON_RSHRN: if (instr->Mask(NEON_Q)) { rshrn2(vf, rd, rn, right_shift); } else { rshrn(vf, rd, rn, right_shift); } break; case NEON_UQSHRN: if (instr->Mask(NEON_Q)) { uqshrn2(vf, rd, rn, right_shift); } else { uqshrn(vf, rd, rn, right_shift); } break; case NEON_UQRSHRN: if (instr->Mask(NEON_Q)) { uqrshrn2(vf, rd, rn, right_shift); } else { uqrshrn(vf, rd, rn, right_shift); } break; case NEON_SQSHRN: if (instr->Mask(NEON_Q)) { sqshrn2(vf, rd, rn, right_shift); } else { sqshrn(vf, rd, rn, right_shift); } break; case NEON_SQRSHRN: if (instr->Mask(NEON_Q)) { sqrshrn2(vf, rd, rn, right_shift); } else { sqrshrn(vf, rd, rn, right_shift); } break; case NEON_SQSHRUN: if (instr->Mask(NEON_Q)) { sqshrun2(vf, rd, rn, right_shift); } else { sqshrun(vf, rd, rn, right_shift); } break; case NEON_SQRSHRUN: if (instr->Mask(NEON_Q)) { sqrshrun2(vf, rd, rn, right_shift); } else { sqrshrun(vf, rd, rn, right_shift); } break; default: UNIMPLEMENTED(); } } void Simulator::VisitNEONTable(Instruction* instr) { NEONFormatDecoder nfd(instr, NEONFormatDecoder::LogicalFormatMap()); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rn2 = vreg((instr->Rn() + 1) % kNumberOfVRegisters); SimVRegister& rn3 = vreg((instr->Rn() + 2) % kNumberOfVRegisters); SimVRegister& rn4 = vreg((instr->Rn() + 3) % kNumberOfVRegisters); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(NEONTableMask)) { case NEON_TBL_1v: tbl(vf, rd, rn, rm); break; case NEON_TBL_2v: tbl(vf, rd, rn, rn2, rm); break; case NEON_TBL_3v: tbl(vf, rd, rn, rn2, rn3, rm); break; case NEON_TBL_4v: tbl(vf, rd, rn, rn2, rn3, rn4, rm); break; case NEON_TBX_1v: tbx(vf, rd, rn, rm); break; case NEON_TBX_2v: tbx(vf, rd, rn, rn2, rm); break; case NEON_TBX_3v: tbx(vf, rd, rn, rn2, rn3, rm); break; case NEON_TBX_4v: tbx(vf, rd, rn, rn2, rn3, rn4, rm); break; default: UNIMPLEMENTED(); } } void Simulator::VisitNEONPerm(Instruction* instr) { NEONFormatDecoder nfd(instr); VectorFormat vf = nfd.GetVectorFormat(); SimVRegister& rd = vreg(instr->Rd()); SimVRegister& rn = vreg(instr->Rn()); SimVRegister& rm = vreg(instr->Rm()); switch (instr->Mask(NEONPermMask)) { case NEON_TRN1: trn1(vf, rd, rn, rm); break; case NEON_TRN2: trn2(vf, rd, rn, rm); break; case NEON_UZP1: uzp1(vf, rd, rn, rm); break; case NEON_UZP2: uzp2(vf, rd, rn, rm); break; case NEON_ZIP1: zip1(vf, rd, rn, rm); break; case NEON_ZIP2: zip2(vf, rd, rn, rm); break; default: UNIMPLEMENTED(); } } void Simulator::DoPrintf(Instruction* instr) { DCHECK((instr->Mask(ExceptionMask) == HLT) && (instr->ImmException() == kImmExceptionIsPrintf)); // Read the arguments encoded inline in the instruction stream. uint32_t arg_count; uint32_t arg_pattern_list; static_assert(sizeof(*instr) == 1); memcpy(&arg_count, instr + kPrintfArgCountOffset, sizeof(arg_count)); memcpy(&arg_pattern_list, instr + kPrintfArgPatternListOffset, sizeof(arg_pattern_list)); DCHECK_LE(arg_count, kPrintfMaxArgCount); DCHECK_EQ(arg_pattern_list >> (kPrintfArgPatternBits * arg_count), 0); // We need to call the host printf function with a set of arguments defined by // arg_pattern_list. Because we don't know the types and sizes of the // arguments, this is very difficult to do in a robust and portable way. To // work around the problem, we pick apart the format string, and print one // format placeholder at a time. // Allocate space for the format string. We take a copy, so we can modify it. // Leave enough space for one extra character per expected argument (plus the // '\0' termination). const char* format_base = reg<const char*>(0); DCHECK_NOT_NULL(format_base); size_t length = strlen(format_base) + 1; char* const format = new char[length + arg_count]; // A list of chunks, each with exactly one format placeholder. const char* chunks[kPrintfMaxArgCount]; // Copy the format string and search for format placeholders. uint32_t placeholder_count = 0; char* format_scratch = format; for (size_t i = 0; i < length; i++) { if (format_base[i] != '%') { *format_scratch++ = format_base[i]; } else { if (format_base[i + 1] == '%') { // Ignore explicit "%%" sequences. *format_scratch++ = format_base[i]; if (placeholder_count == 0) { // The first chunk is passed to printf using "%s", so we need to // unescape "%%" sequences in this chunk. (Just skip the next '%'.) i++; } else { // Otherwise, pass through "%%" unchanged. *format_scratch++ = format_base[++i]; } } else { CHECK(placeholder_count < arg_count); // Insert '\0' before placeholders, and store their locations. *format_scratch++ = '\0'; chunks[placeholder_count++] = format_scratch; *format_scratch++ = format_base[i]; } } } DCHECK(format_scratch <= (format + length + arg_count)); CHECK(placeholder_count == arg_count); // Finally, call printf with each chunk, passing the appropriate register // argument. Normally, printf returns the number of bytes transmitted, so we // can emulate a single printf call by adding the result from each chunk. If // any call returns a negative (error) value, though, just return that value. fprintf(stream_, "%s", clr_printf); // Because '\0' is inserted before each placeholder, the first string in // 'format' contains no format placeholders and should be printed literally. int result = fprintf(stream_, "%s", format); int pcs_r = 1; // Start at x1. x0 holds the format string. int pcs_f = 0; // Start at d0. if (result >= 0) { for (uint32_t i = 0; i < placeholder_count; i++) { int part_result = -1; uint32_t arg_pattern = arg_pattern_list >> (i * kPrintfArgPatternBits); arg_pattern &= (1 << kPrintfArgPatternBits) - 1; switch (arg_pattern) { case kPrintfArgW: part_result = fprintf(stream_, chunks[i], wreg(pcs_r++)); break; case kPrintfArgX: part_result = fprintf(stream_, chunks[i], xreg(pcs_r++)); break; case kPrintfArgD: part_result = fprintf(stream_, chunks[i], dreg(pcs_f++)); break; default: UNREACHABLE(); } if (part_result < 0) { // Handle error values. result = part_result; break; } result += part_result; } } fprintf(stream_, "%s", clr_normal); #ifdef DEBUG CorruptAllCallerSavedCPURegisters(); #endif // Printf returns its result in x0 (just like the C library's printf). set_xreg(0, result); // The printf parameters are inlined in the code, so skip them. set_pc(instr->InstructionAtOffset(kPrintfLength)); // Set LR as if we'd just called a native printf function. set_lr(pc()); delete[] format; } Simulator::LocalMonitor::LocalMonitor() : access_state_(MonitorAccess::Open), tagged_addr_(0), size_(TransactionSize::None) {} void Simulator::LocalMonitor::Clear() { access_state_ = MonitorAccess::Open; tagged_addr_ = 0; size_ = TransactionSize::None; } void Simulator::LocalMonitor::NotifyLoad() { if (access_state_ == MonitorAccess::Exclusive) { // A non exclusive load could clear the local monitor. As a result, it's // most strict to unconditionally clear the local monitor on load. Clear(); } } void Simulator::LocalMonitor::NotifyLoadExcl(uintptr_t addr, TransactionSize size) { access_state_ = MonitorAccess::Exclusive; tagged_addr_ = addr; size_ = size; } void Simulator::LocalMonitor::NotifyStore() { if (access_state_ == MonitorAccess::Exclusive) { // A non exclusive store could clear the local monitor. As a result, it's // most strict to unconditionally clear the local monitor on store. Clear(); } } bool Simulator::LocalMonitor::NotifyStoreExcl(uintptr_t addr, TransactionSize size) { if (access_state_ == MonitorAccess::Exclusive) { // It is allowed for a processor to require that the address matches // exactly (B2.10.1), so this comparison does not mask addr. if (addr == tagged_addr_ && size_ == size) { Clear(); return true; } else { // It is implementation-defined whether an exclusive store to a // non-tagged address will update memory. As a result, it's most strict // to unconditionally clear the local monitor. Clear(); return false; } } else { DCHECK(access_state_ == MonitorAccess::Open); return false; } } Simulator::GlobalMonitor::Processor::Processor() : access_state_(MonitorAccess::Open), tagged_addr_(0), next_(nullptr), prev_(nullptr), failure_counter_(0) {} void Simulator::GlobalMonitor::Processor::Clear_Locked() { access_state_ = MonitorAccess::Open; tagged_addr_ = 0; } void Simulator::GlobalMonitor::Processor::NotifyLoadExcl_Locked( uintptr_t addr) { access_state_ = MonitorAccess::Exclusive; tagged_addr_ = addr; } void Simulator::GlobalMonitor::Processor::NotifyStore_Locked( bool is_requesting_processor) { if (access_state_ == MonitorAccess::Exclusive) { // A non exclusive store could clear the global monitor. As a result, it's // most strict to unconditionally clear global monitors on store. Clear_Locked(); } } bool Simulator::GlobalMonitor::Processor::NotifyStoreExcl_Locked( uintptr_t addr, bool is_requesting_processor) { if (access_state_ == MonitorAccess::Exclusive) { if (is_requesting_processor) { // It is allowed for a processor to require that the address matches // exactly (B2.10.2), so this comparison does not mask addr. if (addr == tagged_addr_) { Clear_Locked(); // Introduce occasional stxr failures. This is to simulate the // behavior of hardware, which can randomly fail due to background // cache evictions. if (failure_counter_++ >= kMaxFailureCounter) { failure_counter_ = 0; return false; } else { return true; } } } else if ((addr & kExclusiveTaggedAddrMask) == (tagged_addr_ & kExclusiveTaggedAddrMask)) { // Check the masked addresses when responding to a successful lock by // another processor so the implementation is more conservative (i.e. the // granularity of locking is as large as possible.) Clear_Locked(); return false; } } return false; } void Simulator::GlobalMonitor::NotifyLoadExcl_Locked(uintptr_t addr, Processor* processor) { processor->NotifyLoadExcl_Locked(addr); PrependProcessor_Locked(processor); } void Simulator::GlobalMonitor::NotifyStore_Locked(Processor* processor) { // Notify each processor of the store operation. for (Processor* iter = head_; iter; iter = iter->next_) { bool is_requesting_processor = iter == processor; iter->NotifyStore_Locked(is_requesting_processor); } } bool Simulator::GlobalMonitor::NotifyStoreExcl_Locked(uintptr_t addr, Processor* processor) { DCHECK(IsProcessorInLinkedList_Locked(processor)); if (processor->NotifyStoreExcl_Locked(addr, true)) { // Notify the other processors that this StoreExcl succeeded. for (Processor* iter = head_; iter; iter = iter->next_) { if (iter != processor) { iter->NotifyStoreExcl_Locked(addr, false); } } return true; } else { return false; } } bool Simulator::GlobalMonitor::IsProcessorInLinkedList_Locked( Processor* processor) const { return head_ == processor || processor->next_ || processor->prev_; } void Simulator::GlobalMonitor::PrependProcessor_Locked(Processor* processor) { if (IsProcessorInLinkedList_Locked(processor)) { return; } if (head_) { head_->prev_ = processor; } processor->prev_ = nullptr; processor->next_ = head_; head_ = processor; } void Simulator::GlobalMonitor::RemoveProcessor(Processor* processor) { base::MutexGuard lock_guard(&mutex); if (!IsProcessorInLinkedList_Locked(processor)) { return; } if (processor->prev_) { processor->prev_->next_ = processor->next_; } else { head_ = processor->next_; } if (processor->next_) { processor->next_->prev_ = processor->prev_; } processor->prev_ = nullptr; processor->next_ = nullptr; } #undef SScanF #undef COLOUR #undef COLOUR_BOLD #undef NORMAL #undef GREY #undef RED #undef GREEN #undef YELLOW #undef BLUE #undef MAGENTA #undef CYAN #undef WHITE #undef COMMAND_SIZE #undef ARG_SIZE #undef STR #undef XSTR } // namespace internal } // namespace v8 // // The following functions are used by our gdb macros. // V8_EXPORT_PRIVATE extern bool _v8_internal_Simulator_ExecDebugCommand( const char* command) { i::Isolate* isolate = i::Isolate::Current(); if (!isolate) { fprintf(stderr, "No V8 Isolate found\n"); return false; } i::Simulator* simulator = i::Simulator::current(isolate); if (!simulator) { fprintf(stderr, "No Arm64 simulator found\n"); return false; } // Copy the command so that the simulator can take ownership of it. size_t len = strlen(command); i::ArrayUniquePtr<char> command_copy(i::NewArray<char>(len + 1)); i::MemCopy(command_copy.get(), command, len + 1); return simulator->ExecDebugCommand(std::move(command_copy)); } #undef BRACKETS #endif // USE_SIMULATOR
36cdb7f032b90975af80601b9da0d73fada3276b
dd331b88628ec852a1dbc07ce425084150e4e992
/hphp/runtime/vm/jit/vasm-jumps.cpp
78c6439ec2c8a4be279c47ed586334416e12790a
[ "PHP-3.01", "Zend-2.0", "BSD-3-Clause" ]
permissive
shjgiser/hhvm
eff6efeeb30f8d9be87243d3e635e0b5504111ac
90ec368835344f8267cefb57ad56d7226ef7a0b5
refs/heads/master
2021-01-18T05:46:04.299598
2014-08-21T07:04:06
2014-08-21T07:30:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,481
cpp
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/jit/vasm-x64.h" #include <boost/dynamic_bitset.hpp> #include <algorithm> TRACE_SET_MOD(hhir); namespace HPHP { namespace JIT { using namespace X64; namespace X64 { PredVector computePreds(Vunit& unit) { PredVector preds(unit.blocks.size()); PostorderWalker walker(unit); walker.dfs([&](Vlabel b) { for (auto s: succs(unit.blocks[b])) { preds[s].push_back(b); } }); return preds; } } void optimizeJmps(Vunit& unit) { auto isEmpty = [&](Vlabel b, Vinstr::Opcode op) { auto& code = unit.blocks[b].code; switch (code.size()) { case 1: return code[0].op == op; case 2: return code[0].op == Vinstr::point && code[1].op == op; default: return false; } }; bool changed = false; bool ever_changed = false; smart::vector<int> npreds(unit.blocks.size(), 0); do { if (changed) { fill(npreds.begin(), npreds.end(), 0); } changed = false; PostorderWalker{unit}.dfs([&](Vlabel b) { for (auto s : succs(unit.blocks[b])) { npreds[s]++; } }); // give roots an extra predecessor to prevent cloning them. for (auto b : unit.roots) { npreds[b]++; } PostorderWalker{unit}.dfs([&](Vlabel b) { auto& block = unit.blocks[b]; auto& code = block.code; assert(!code.empty()); if (code.back().op == Vinstr::jcc) { auto ss = succs(block); if (ss[0] == ss[1]) { // both edges have same target, change to jmp code.back() = jmp{ss[0]}; changed = true; } } if (code.back().op == Vinstr::jmp) { auto& s = code.back().jmp_.target; if (isEmpty(s, Vinstr::jmp)) { // skip over s s = unit.blocks[s].code.back().jmp_.target; changed = true; } else if (npreds[s] == 1 || isEmpty(s, Vinstr::jcc)) { // overwrite jmp with copy of s auto& code2 = unit.blocks[s].code; code.pop_back(); code.insert(code.end(), code2.begin(), code2.end()); changed = true; } } else { for (auto& s : succs(block)) { if (isEmpty(s, Vinstr::jmp)) { // skip over s s = unit.blocks[s].code.back().jmp_.target; changed = true; } } } }); ever_changed |= changed; } while (changed); if (ever_changed) { printUnit("after vasm-jumps", unit); } } }}
1ee609338b4bf5d3ff16c84980edacfa42ed43b6
6589ef00c11b547e1b5af939968007eaaf17c12b
/common/Display/Adafruit_GFX.h
036acff36a1133a7034c4a8c2e0b60e042adf9f7
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
Nan0416/AVR-atmega328p
e2f2ce8fc16eaa495f54fc843a521c2605f381d2
3e9733f4e13e1a78e7ac4e80c78ddb4c5fbd8051
refs/heads/master
2021-09-05T17:04:37.935477
2018-01-29T21:24:11
2018-01-29T21:24:11
85,274,211
3
1
null
null
null
null
UTF-8
C++
false
false
7,498
h
#ifndef _ADAFRUIT_GFX_H #define _ADAFRUIT_GFX_H #include "Arduino.h" #include "Print.h" #include "gfxfont.h" class Adafruit_GFX : public Print { public: Adafruit_GFX(int16_t w, int16_t h); // Constructor // This MUST be defined by the subclass: virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0; // TRANSACTION API / CORE DRAW API // These MAY be overridden by the subclass to provide device-specific // optimized code. Otherwise 'generic' versions are used. virtual void startWrite(void); virtual void writePixel(int16_t x, int16_t y, uint16_t color); virtual void writeFillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color); virtual void writeFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color); virtual void writeFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color); virtual void writeLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color); virtual void endWrite(void); // CONTROL API // These MAY be overridden by the subclass to provide device-specific // optimized code. Otherwise 'generic' versions are used. virtual void setRotation(uint8_t r); virtual void invertDisplay(boolean i); // BASIC DRAW API // These MAY be overridden by the subclass to provide device-specific // optimized code. Otherwise 'generic' versions are used. virtual void // It's good to implement those, even if using transaction API drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), fillScreen(uint16_t color), // Optional and probably not necessary to change drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color), drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color); // These exist only with Adafruit_GFX (no subclass overrides) void drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), drawCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint16_t color), fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, int16_t delta, uint16_t color), drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color), fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color), drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, int16_t radius, uint16_t color), fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, int16_t radius, uint16_t color), drawBitmap(int16_t x, int16_t y, const uint8_t bitmap[], int16_t w, int16_t h, uint16_t color), drawBitmap(int16_t x, int16_t y, const uint8_t bitmap[], int16_t w, int16_t h, uint16_t color, uint16_t bg), drawBitmap(int16_t x, int16_t y, uint8_t *bitmap, int16_t w, int16_t h, uint16_t color), drawBitmap(int16_t x, int16_t y, uint8_t *bitmap, int16_t w, int16_t h, uint16_t color, uint16_t bg), drawXBitmap(int16_t x, int16_t y, const uint8_t bitmap[], int16_t w, int16_t h, uint16_t color), drawGrayscaleBitmap(int16_t x, int16_t y, const uint8_t bitmap[], int16_t w, int16_t h), drawGrayscaleBitmap(int16_t x, int16_t y, uint8_t *bitmap, int16_t w, int16_t h), drawGrayscaleBitmap(int16_t x, int16_t y, const uint8_t bitmap[], const uint8_t mask[], int16_t w, int16_t h), drawGrayscaleBitmap(int16_t x, int16_t y, uint8_t *bitmap, uint8_t *mask, int16_t w, int16_t h), drawRGBBitmap(int16_t x, int16_t y, const uint16_t bitmap[], int16_t w, int16_t h), drawRGBBitmap(int16_t x, int16_t y, uint16_t *bitmap, int16_t w, int16_t h), drawRGBBitmap(int16_t x, int16_t y, const uint16_t bitmap[], const uint8_t mask[], int16_t w, int16_t h), drawRGBBitmap(int16_t x, int16_t y, uint16_t *bitmap, uint8_t *mask, int16_t w, int16_t h), drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color, uint16_t bg, uint8_t size), setCursor(int16_t x, int16_t y), setTextColor(uint16_t c), setTextColor(uint16_t c, uint16_t bg), setTextSize(uint8_t s), setTextWrap(boolean w), cp437(boolean x=true), setFont(const GFXfont *f = NULL), getTextBounds(char *string, int16_t x, int16_t y, int16_t *x1, int16_t *y1, uint16_t *w, uint16_t *h), getTextBounds(const __FlashStringHelper *s, int16_t x, int16_t y, int16_t *x1, int16_t *y1, uint16_t *w, uint16_t *h); #if ARDUINO >= 100 virtual size_t write(uint8_t); #else virtual void write(uint8_t); #endif int16_t height(void) const; int16_t width(void) const; uint8_t getRotation(void) const; // get current cursor position (get rotation safe maximum values, using: width() for x, height() for y) int16_t getCursorX(void) const; int16_t getCursorY(void) const; protected: void charBounds(char c, int16_t *x, int16_t *y, int16_t *minx, int16_t *miny, int16_t *maxx, int16_t *maxy); const int16_t WIDTH, HEIGHT; // This is the 'raw' display w/h - never changes int16_t _width, _height, // Display w/h as modified by current rotation cursor_x, cursor_y; uint16_t textcolor, textbgcolor; uint8_t textsize, rotation; boolean wrap, // If set, 'wrap' text at right edge of display _cp437; // If set, use correct CP437 charset (default is off) GFXfont *gfxFont; }; class Adafruit_GFX_Button { public: Adafruit_GFX_Button(void); // "Classic" initButton() uses center & size void initButton(Adafruit_GFX *gfx, int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t outline, uint16_t fill, uint16_t textcolor, char *label, uint8_t textsize); // New/alt initButton() uses upper-left corner & size void initButtonUL(Adafruit_GFX *gfx, int16_t x1, int16_t y1, uint16_t w, uint16_t h, uint16_t outline, uint16_t fill, uint16_t textcolor, char *label, uint8_t textsize); void drawButton(boolean inverted = false); boolean contains(int16_t x, int16_t y); void press(boolean p); boolean isPressed(); boolean justPressed(); boolean justReleased(); private: Adafruit_GFX *_gfx; int16_t _x1, _y1; // Coordinates of top-left corner uint16_t _w, _h; uint8_t _textsize; uint16_t _outlinecolor, _fillcolor, _textcolor; char _label[10]; boolean currstate, laststate; }; class GFXcanvas1 : public Adafruit_GFX { public: GFXcanvas1(uint16_t w, uint16_t h); ~GFXcanvas1(void); void drawPixel(int16_t x, int16_t y, uint16_t color), fillScreen(uint16_t color); uint8_t *getBuffer(void); private: uint8_t *buffer; }; class GFXcanvas8 : public Adafruit_GFX { public: GFXcanvas8(uint16_t w, uint16_t h); ~GFXcanvas8(void); void drawPixel(int16_t x, int16_t y, uint16_t color), fillScreen(uint16_t color), writeFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color); uint8_t *getBuffer(void); private: uint8_t *buffer; }; class GFXcanvas16 : public Adafruit_GFX { public: GFXcanvas16(uint16_t w, uint16_t h); ~GFXcanvas16(void); void drawPixel(int16_t x, int16_t y, uint16_t color), fillScreen(uint16_t color); uint16_t *getBuffer(void); private: uint16_t *buffer; }; #endif // _ADAFRUIT_GFX_H
21c5bb9c6e9b5b79bf140901dd04bb0f82eb20a8
424d9d65e27cd204cc22e39da3a13710b163f4e7
/components/autofill_assistant/browser/web/web_controller_browsertest.cc
855ad835158ffb3e4d6b06bfd5286a73e52192e3
[ "BSD-3-Clause" ]
permissive
bigben0123/chromium
7c5f4624ef2dacfaf010203b60f307d4b8e8e76d
83d9cd5e98b65686d06368f18b4835adbab76d89
refs/heads/master
2023-01-10T11:02:26.202776
2020-10-30T09:47:16
2020-10-30T09:47:16
275,543,782
0
0
BSD-3-Clause
2020-10-30T09:47:18
2020-06-28T08:45:11
null
UTF-8
C++
false
false
84,621
cc
// Copyright 2018 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 "components/autofill_assistant/browser/web/web_controller.h" #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/strings/strcat.h" #include "components/autofill_assistant/browser/client_settings.h" #include "components/autofill_assistant/browser/service.pb.h" #include "components/autofill_assistant/browser/string_conversions_util.h" #include "components/autofill_assistant/browser/top_padding.h" #include "components/autofill_assistant/browser/web/element_finder.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gmock/include/gmock/gmock.h" namespace autofill_assistant { using ::testing::AnyOf; using ::testing::IsEmpty; // Flag to enable site per process to enforce OOPIFs. const char* kSitePerProcess = "site-per-process"; const char* kTargetWebsitePath = "/autofill_assistant_target_website.html"; class WebControllerBrowserTest : public content::ContentBrowserTest, public content::WebContentsObserver { public: WebControllerBrowserTest() {} ~WebControllerBrowserTest() override {} void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(kSitePerProcess); } void SetUpOnMainThread() override { ContentBrowserTest::SetUpOnMainThread(); // Start a mock server for hosting an OOPIF. http_server_iframe_ = std::make_unique<net::EmbeddedTestServer>( net::EmbeddedTestServer::TYPE_HTTP); http_server_iframe_->ServeFilesFromSourceDirectory( "components/test/data/autofill_assistant/html_iframe"); ASSERT_TRUE(http_server_iframe_->Start(8081)); // Start the main server hosting the test page. http_server_ = std::make_unique<net::EmbeddedTestServer>( net::EmbeddedTestServer::TYPE_HTTP); http_server_->ServeFilesFromSourceDirectory( "components/test/data/autofill_assistant/html"); ASSERT_TRUE(http_server_->Start(8080)); ASSERT_TRUE( NavigateToURL(shell(), http_server_->GetURL(kTargetWebsitePath))); web_controller_ = WebController::CreateForWebContents( shell()->web_contents(), &settings_); Observe(shell()->web_contents()); } void WaitTillPageIsIdle(base::TimeDelta continuous_paint_timeout) { base::TimeTicks finished_load_time = base::TimeTicks::Now(); while (true) { content::RenderFrameSubmissionObserver frame_submission_observer( web_contents()); // Runs a loop for 3 seconds to see if the renderer is idle. { base::RunLoop heart_beat; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, heart_beat.QuitClosure(), base::TimeDelta::FromSeconds(3)); heart_beat.Run(); } bool page_is_loading = web_contents()->IsWaitingForResponse() || web_contents()->IsLoading(); if (page_is_loading) { finished_load_time = base::TimeTicks::Now(); } else if ((base::TimeTicks::Now() - finished_load_time) > continuous_paint_timeout) { // |continuous_paint_timeout| has expired since Chrome loaded the page. // During this period of time, Chrome has been continuously painting // the page. In this case, the page is probably idle, but a bug, a // blinking caret or a persistent animation is making Chrome paint at // regular intervals. Exit. break; } else if (frame_submission_observer.render_frame_count() == 0) { // If the renderer has stopped submitting frames for 3 seconds then // we're done. break; } } } void RunStrictElementCheck(const Selector& selector, bool result) { RunElementCheck(/* strict= */ true, selector, result); } void RunLaxElementCheck(const Selector& selector, bool result) { RunElementCheck(/* strict= */ false, selector, result); } void RunElementCheck(bool strict, const Selector& selector, bool result) { std::vector<Selector> selectors{selector}; std::vector<bool> results{result}; RunElementChecks(strict, selectors, results); } void RunElementChecks(bool strict, const std::vector<Selector>& selectors, const std::vector<bool> results) { base::RunLoop run_loop; ASSERT_EQ(selectors.size(), results.size()); size_t pending_number_of_checks = selectors.size(); for (size_t i = 0; i < selectors.size(); i++) { web_controller_->FindElement( selectors[i], strict, base::BindOnce(&WebControllerBrowserTest::ElementCheckCallback, base::Unretained(this), run_loop.QuitClosure(), selectors[i], &pending_number_of_checks, results[i])); } run_loop.Run(); } void ElementCheckCallback( base::OnceClosure done_callback, const Selector& selector, size_t* pending_number_of_checks_output, bool expected_result, const ClientStatus& result, std::unique_ptr<ElementFinder::Result> ignored_element) { EXPECT_EQ(expected_result, result.ok()) << "selector: " << selector << " status: " << result; *pending_number_of_checks_output -= 1; if (*pending_number_of_checks_output == 0) { std::move(done_callback).Run(); } } void ElementRetainingCallback(std::unique_ptr<ElementFinder::Result> element, base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& status) { EXPECT_TRUE(element != nullptr); *result_output = status; std::move(done_callback).Run(); } void ElementRetainingStringCallback( std::unique_ptr<ElementFinder::Result> element, base::OnceClosure done_callback, ClientStatus* result_output, std::string* result, const ClientStatus& status, const std::string& value) { EXPECT_TRUE(element != nullptr); *result_output = status; result->assign(value); std::move(done_callback).Run(); } void ClickOrTapElement(const Selector& selector, ClickType click_type) { base::RunLoop run_loop; ClientStatus result_output; web_controller_->FindElement( selector, /* strict_mode= */ true, base::BindOnce(&WebControllerBrowserTest::FindClickOrTapElementCallback, base::Unretained(this), click_type, run_loop.QuitClosure(), &result_output)); run_loop.Run(); EXPECT_EQ(ACTION_APPLIED, result_output.proto_status()); } void FindClickOrTapElementCallback( ClickType click_type, base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& status, std::unique_ptr<ElementFinder::Result> element_result) { EXPECT_EQ(ACTION_APPLIED, status.proto_status()); ASSERT_TRUE(element_result != nullptr); PerformClickOrTap( click_type, *element_result, base::BindOnce(&WebControllerBrowserTest::ElementRetainingCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output)); } void PerformClickOrTap( ClickType click_type, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) { web_controller_->ScrollIntoView( element, base::BindOnce(&WebControllerBrowserTest::OnScrollIntoViewForClickOrTap, base::Unretained(this), click_type, element, std::move(callback))); } void OnScrollIntoViewForClickOrTap( ClickType click_type, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback, const ClientStatus& scroll_status) { if (!scroll_status.ok()) { std::move(callback).Run(scroll_status); return; } web_controller_->ClickOrTapElement(element, click_type, std::move(callback)); } void WaitForElementRemove(const Selector& selector) { base::RunLoop run_loop; web_controller_->FindElement( selector, /* strict= */ false, base::BindOnce(&WebControllerBrowserTest::OnWaitForElementRemove, base::Unretained(this), run_loop.QuitClosure(), selector)); run_loop.Run(); } void OnWaitForElementRemove( base::OnceClosure done_callback, const Selector& selector, const ClientStatus& result, std::unique_ptr<ElementFinder::Result> ignored_element) { std::move(done_callback).Run(); if (result.ok()) { WaitForElementRemove(selector); } } void ScrollToElementPosition(const Selector& selector, const TopPadding& top_padding) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict_mode= */ true, base::BindOnce( &WebControllerBrowserTest::FindScrollToElementPositionCallback, base::Unretained(this), top_padding, run_loop.QuitClosure(), &result)); run_loop.Run(); EXPECT_EQ(ACTION_APPLIED, result.proto_status()); } void FindScrollToElementPositionCallback( const TopPadding& top_padding, base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& status, std::unique_ptr<ElementFinder::Result> element_result) { if (!status.ok()) { *result_output = status; std::move(done_callback).Run(); return; } ASSERT_TRUE(element_result != nullptr); web_controller_->ScrollToElementPosition( *element_result, top_padding, base::BindOnce(&WebControllerBrowserTest::ElementRetainingCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output)); } ClientStatus SelectOption(const Selector& selector, const std::string& value, DropdownSelectStrategy select_strategy) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict_mode= */ true, base::BindOnce( &WebControllerBrowserTest::FindSelectOptionElementCallback, base::Unretained(this), value, select_strategy, run_loop.QuitClosure(), &result)); run_loop.Run(); return result; } void FindSelectOptionElementCallback( const std::string& value, DropdownSelectStrategy select_strategy, base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& status, std::unique_ptr<ElementFinder::Result> element_result) { if (!status.ok()) { *result_output = status; std::move(done_callback).Run(); return; } ASSERT_TRUE(element_result != nullptr); web_controller_->SelectOption( *element_result, value, select_strategy, base::BindOnce(&WebControllerBrowserTest::ElementRetainingCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output)); } void OnClientStatus(base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& status) { *result_output = status; std::move(done_callback).Run(); } void OnClientStatusAndReadyState(base::OnceClosure done_callback, ClientStatus* result_output, DocumentReadyState* ready_state_out, const ClientStatus& status, DocumentReadyState ready_state) { *result_output = status; *ready_state_out = ready_state; std::move(done_callback).Run(); } ClientStatus HighlightElement(const Selector& selector) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict_mode= */ true, base::BindOnce(&WebControllerBrowserTest::FindHighlightElementCallback, base::Unretained(this), run_loop.QuitClosure(), &result)); run_loop.Run(); return result; } void FindHighlightElementCallback( base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& status, std::unique_ptr<ElementFinder::Result> element_result) { if (!status.ok()) { *result_output = status; std::move(done_callback).Run(); return; } ASSERT_TRUE(element_result != nullptr); web_controller_->HighlightElement( *element_result, base::BindOnce(&WebControllerBrowserTest::ElementRetainingCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output)); } ClientStatus GetOuterHtml(const Selector& selector, std::string* html_output) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict= */ true, base::BindOnce( &WebControllerBrowserTest::FindGetOuterHtmlElementCallback, base::Unretained(this), run_loop.QuitClosure(), &result, html_output)); run_loop.Run(); EXPECT_EQ(ACTION_APPLIED, result.proto_status()); return result; } void FindGetOuterHtmlElementCallback( base::OnceClosure done_callback, ClientStatus* result_output, std::string* html_output, const ClientStatus& element_status, std::unique_ptr<ElementFinder::Result> element_result) { EXPECT_EQ(ACTION_APPLIED, element_status.proto_status()); ASSERT_TRUE(element_result != nullptr); web_controller_->GetOuterHtml( *element_result, base::BindOnce( &WebControllerBrowserTest::ElementRetainingStringCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output, html_output)); } ClientStatus GetElementTag(const Selector& selector, std::string* element_tag_output) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict= */ true, base::BindOnce( &WebControllerBrowserTest::FindGetElementTagElementCallback, base::Unretained(this), run_loop.QuitClosure(), &result, element_tag_output)); run_loop.Run(); EXPECT_EQ(ACTION_APPLIED, result.proto_status()); return result; } void FindGetElementTagElementCallback( base::OnceClosure done_callback, ClientStatus* result_output, std::string* element_tag_output, const ClientStatus& element_status, std::unique_ptr<ElementFinder::Result> element_result) { EXPECT_EQ(ACTION_APPLIED, element_status.proto_status()); ASSERT_TRUE(element_result != nullptr); web_controller_->GetElementTag( *element_result, base::BindOnce( &WebControllerBrowserTest::ElementRetainingStringCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output, element_tag_output)); } void FindElement(const Selector& selector, ClientStatus* status_out, ElementFinder::Result* result_out) { base::RunLoop run_loop; web_controller_->FindElement( selector, /* strict_mode= */ true, base::BindOnce(&WebControllerBrowserTest::OnFindElement, base::Unretained(this), run_loop.QuitClosure(), base::Unretained(status_out), base::Unretained(result_out))); run_loop.Run(); } void OnFindElement(base::OnceClosure done_callback, ClientStatus* status_out, ElementFinder::Result* result_out, const ClientStatus& status, std::unique_ptr<ElementFinder::Result> result) { ASSERT_TRUE(result); std::move(done_callback).Run(); if (status_out) *status_out = status; if (result_out) *result_out = *result; } void FindElementAndCheck(const Selector& selector, bool is_main_frame) { SCOPED_TRACE(::testing::Message() << selector << " strict"); ClientStatus status; ElementFinder::Result result; FindElement(selector, &status, &result); EXPECT_EQ(ACTION_APPLIED, status.proto_status()); CheckFindElementResult(result, is_main_frame); } void FindElementExpectEmptyResult(const Selector& selector) { SCOPED_TRACE(::testing::Message() << selector << " strict"); ClientStatus status; ElementFinder::Result result; FindElement(selector, &status, &result); EXPECT_EQ(ELEMENT_RESOLUTION_FAILED, status.proto_status()); EXPECT_THAT(result.object_id, IsEmpty()); } void CheckFindElementResult(const ElementFinder::Result& result, bool is_main_frame) { if (is_main_frame) { EXPECT_EQ(shell()->web_contents()->GetMainFrame(), result.container_frame_host); EXPECT_EQ(result.frame_stack.size(), 0u); } else { EXPECT_NE(shell()->web_contents()->GetMainFrame(), result.container_frame_host); EXPECT_GE(result.frame_stack.size(), 1u); } EXPECT_FALSE(result.object_id.empty()); } ClientStatus GetStringAttribute(const Selector& selector, const std::vector<std::string>& attributes, std::string* value) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict= */ true, base::BindOnce( &WebControllerBrowserTest::FindGetStringAttributeElementCallback, base::Unretained(this), attributes, run_loop.QuitClosure(), &result, value)); run_loop.Run(); return result; } void FindGetStringAttributeElementCallback( const std::vector<std::string>& attributes, base::OnceClosure done_callback, ClientStatus* result_output, std::string* value, const ClientStatus& element_status, std::unique_ptr<ElementFinder::Result> element_result) { EXPECT_EQ(ACTION_APPLIED, element_status.proto_status()); ASSERT_TRUE(element_result != nullptr); web_controller_->GetStringAttribute( *element_result, attributes, base::BindOnce( &WebControllerBrowserTest::ElementRetainingStringCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output, value)); } void GetFieldsValue(const std::vector<Selector>& selectors, const std::vector<std::string>& expected_values) { base::RunLoop run_loop; ASSERT_EQ(selectors.size(), expected_values.size()); size_t pending_number_of_checks = selectors.size(); for (size_t i = 0; i < selectors.size(); i++) { web_controller_->FindElement( selectors[i], /* strict= */ true, base::BindOnce( &WebControllerBrowserTest::GetFieldValueElementCallback, base::Unretained(this), run_loop.QuitClosure(), &pending_number_of_checks, expected_values[i])); } run_loop.Run(); } void GetFieldValueElementCallback( base::OnceClosure done_callback, size_t* pending_number_of_checks_output, const std::string& expected_value, const ClientStatus& element_status, std::unique_ptr<ElementFinder::Result> element_result) { if (!element_status.ok()) { OnGetFieldValue(nullptr, std::move(done_callback), pending_number_of_checks_output, expected_value, element_status, std::string()); return; } web_controller_->GetFieldValue( *element_result, base::BindOnce(&WebControllerBrowserTest::OnGetFieldValue, base::Unretained(this), std::move(element_result), std::move(done_callback), pending_number_of_checks_output, expected_value)); } void OnGetFieldValue(std::unique_ptr<ElementFinder::Result> element, base::OnceClosure done_callback, size_t* pending_number_of_checks_output, const std::string& expected_value, const ClientStatus& status, const std::string& value) { // Don't use ASSERT: If the check fails, this would result in an endless // loop without meaningful test results. EXPECT_EQ(expected_value, value); *pending_number_of_checks_output -= 1; if (*pending_number_of_checks_output == 0) { std::move(done_callback).Run(); } } ClientStatus SetFieldValue(const Selector& selector, const std::string& value, KeyboardValueFillStrategy fill_strategy) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict_mode= */ true, base::BindOnce( &WebControllerBrowserTest::FindSetFieldValueElementCallback, base::Unretained(this), value, fill_strategy, run_loop.QuitClosure(), &result)); run_loop.Run(); return result; } void FindSetFieldValueElementCallback( const std::string& value, KeyboardValueFillStrategy fill_strategy, base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& element_status, std::unique_ptr<ElementFinder::Result> element_result) { if (!element_status.ok()) { *result_output = element_status; std::move(done_callback).Run(); return; } EXPECT_EQ(ACTION_APPLIED, element_status.proto_status()); ASSERT_TRUE(element_result != nullptr); PerformSetFieldValue( value, fill_strategy, *element_result, base::BindOnce(&WebControllerBrowserTest::ElementRetainingCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output)); } void PerformSetFieldValue( const std::string& value, KeyboardValueFillStrategy fill_strategy, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) { if (value.empty()) { web_controller_->SetValueAttribute(element, value, std::move(callback)); return; } switch (fill_strategy) { case SET_VALUE: web_controller_->SetValueAttribute(element, value, std::move(callback)); return; case SIMULATE_KEY_PRESSES: web_controller_->SetValueAttribute( element, /* value= */ std::string(), base::BindOnce( &WebControllerBrowserTest::OnSetValueAttributeForSetFieldValue, base::Unretained(this), value, false, element, std::move(callback))); return; case SIMULATE_KEY_PRESSES_SELECT_VALUE: web_controller_->SelectFieldValue( element, base::BindOnce( &WebControllerBrowserTest::OnSelectFieldValueForSetFieldValue, base::Unretained(this), value, element, std::move(callback))); return; case SIMULATE_KEY_PRESSES_FOCUS: web_controller_->SetValueAttribute( element, /* value= */ std::string(), base::BindOnce( &WebControllerBrowserTest::OnSetValueAttributeForSetFieldValue, base::Unretained(this), value, true, element, std::move(callback))); return; case UNSPECIFIED_KEYBAORD_STRATEGY: std::move(callback).Run(ClientStatus(INVALID_ACTION)); } } void OnSetValueAttributeForSetFieldValue( const std::string& value, bool use_js_focus, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback, const ClientStatus& status) { if (!status.ok()) { std::move(callback).Run(status); return; } PerformSendKeyboardInput(UTF8ToUnicode(value), /* delay_in_milli= */ 0, use_js_focus, element, std::move(callback)); } void OnSelectFieldValueForSetFieldValue( const std::string& value, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback, const ClientStatus& status) { if (!status.ok()) { std::move(callback).Run(status); return; } web_controller_->SendKeyboardInput(element, UTF8ToUnicode(value), /* delay_in_milli= */ 0, std::move(callback)); } ClientStatus SendKeyboardInput(const Selector& selector, const std::vector<UChar32>& codepoints, int delay_in_milli, bool use_js_focus) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict_mode= */ true, base::BindOnce( &WebControllerBrowserTest::FindSendKeyboardInputElementCallback, base::Unretained(this), codepoints, delay_in_milli, use_js_focus, run_loop.QuitClosure(), &result)); run_loop.Run(); return result; } ClientStatus SendKeyboardInput(const Selector& selector, const std::vector<UChar32>& codepoints) { return SendKeyboardInput(selector, codepoints, -1, false); } void FindSendKeyboardInputElementCallback( const std::vector<UChar32>& codepoints, int delay_in_milli, bool use_js_focus, base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& element_status, std::unique_ptr<ElementFinder::Result> element_result) { EXPECT_EQ(ACTION_APPLIED, element_status.proto_status()); ASSERT_TRUE(element_result != nullptr); PerformSendKeyboardInput( codepoints, delay_in_milli, use_js_focus, *element_result, base::BindOnce(&WebControllerBrowserTest::ElementRetainingCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output)); } void PerformSendKeyboardInput( const std::vector<UChar32>& codepoints, int delay_in_milli, bool use_js_focus, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback) { if (use_js_focus) { web_controller_->FocusField( element, base::BindOnce( &WebControllerBrowserTest::OnFieldFocussedForSendKeyboardInput, base::Unretained(this), codepoints, delay_in_milli, element, std::move(callback))); return; } PerformClickOrTap( ClickType::CLICK, element, base::BindOnce( &WebControllerBrowserTest::OnFieldFocussedForSendKeyboardInput, base::Unretained(this), codepoints, delay_in_milli, element, std::move(callback))); } void OnFieldFocussedForSendKeyboardInput( const std::vector<UChar32>& codepoints, int delay_in_milli, const ElementFinder::Result& element, base::OnceCallback<void(const ClientStatus&)> callback, const ClientStatus& click_status) { if (!click_status.ok()) { std::move(callback).Run(click_status); return; } web_controller_->SendKeyboardInput(element, codepoints, delay_in_milli, std::move(callback)); } ClientStatus SetAttribute(const Selector& selector, const std::vector<std::string>& attributes, const std::string& value) { base::RunLoop run_loop; ClientStatus result; web_controller_->FindElement( selector, /* strict_mode= */ true, base::BindOnce( &WebControllerBrowserTest::FindSetAttributeElementCallback, base::Unretained(this), attributes, value, run_loop.QuitClosure(), &result)); run_loop.Run(); return result; } void FindSetAttributeElementCallback( const std::vector<std::string>& attributes, const std::string& value, base::OnceClosure done_callback, ClientStatus* result_output, const ClientStatus& status, std::unique_ptr<ElementFinder::Result> element_result) { if (!status.ok()) { *result_output = status; std::move(done_callback).Run(); return; } ASSERT_TRUE(element_result != nullptr); web_controller_->SetAttribute( *element_result, attributes, value, base::BindOnce(&WebControllerBrowserTest::ElementRetainingCallback, base::Unretained(this), std::move(element_result), std::move(done_callback), result_output)); } ClientStatus GetElementRect(const Selector& selector, RectF* rect_output) { base::RunLoop run_loop; ClientStatus result; web_controller_->GetElementRect( selector, base::BindOnce(&WebControllerBrowserTest::OnGetElementRect, base::Unretained(this), run_loop.QuitClosure(), &result, rect_output)); run_loop.Run(); return result; } void OnGetElementRect(base::OnceClosure done_callback, ClientStatus* result_output, RectF* rect_output, const ClientStatus& rect_status, const RectF& rect) { if (rect_status.ok()) { *rect_output = rect; } *result_output = rect_status; std::move(done_callback).Run(); } // Make sure scrolling is necessary for #scroll_container , no matter the // screen height void SetupScrollContainerHeights() { EXPECT_TRUE(content::ExecJs(shell(), R"( let before = document.querySelector("#before_scroll_container"); before.style.height = window.innerHeight + "px"; let after = document.querySelector("#after_scroll_container"); after.style.height = window.innerHeight + "px";)")); } // Scrolls #scroll_container to the given y position. void ScrollContainerTo(int y) { EXPECT_TRUE(content::ExecJs(shell(), base::StringPrintf( R"( let container = document.querySelector("#scroll_container"); container.scrollTo(0, %d);)", y))); } // Scrolls the window to the given y position. void ScrollWindowTo(int y) { EXPECT_TRUE(content::ExecJs( shell(), base::StringPrintf("window.scrollTo(0, %d);", y))); } // Scroll an element into view that's within a container element. This // requires scrolling the container, then the window, to get the element to // the desired y position. void TestScrollIntoView(int initial_window_scroll_y, int initial_container_scroll_y) { Selector selector({"#scroll_item_5"}); SetupScrollContainerHeights(); ScrollWindowTo(initial_window_scroll_y); ScrollContainerTo(initial_window_scroll_y); TopPadding top_padding{0.25, TopPadding::Unit::RATIO}; ScrollToElementPosition(selector, top_padding); base::ListValue eval_result = content::EvalJs(shell(), R"( let item = document.querySelector("#scroll_item_5"); let itemRect = item.getBoundingClientRect(); let container = document.querySelector("#scroll_container"); let containerRect = container.getBoundingClientRect(); [itemRect.top, itemRect.bottom, window.innerHeight, containerRect.top, containerRect.bottom])") .ExtractList(); double top = eval_result.GetList()[0].GetDouble(); double bottom = eval_result.GetList()[1].GetDouble(); double window_height = eval_result.GetList()[2].GetDouble(); double container_top = eval_result.GetList()[3].GetDouble(); double container_bottom = eval_result.GetList()[4].GetDouble(); // Element is at the desired position. (top is relative to the viewport) EXPECT_NEAR(top, window_height * 0.25, 0.5); // Element is within the visible portion of its container. EXPECT_GT(bottom, container_top); EXPECT_LT(top, container_bottom); } // Send a Runtime.Evaluate protocol message. Useful for evaluating JS in the // page as there is no ordering guarantee between protocol messages and e.g. // ExecJs(). void RuntimeEvaluate(const std::string& code) { web_controller_->devtools_client_->GetRuntime()->Evaluate( code, /* node_frame_id= */ std::string()); } protected: std::unique_ptr<WebController> web_controller_; ClientSettings settings_; private: std::unique_ptr<net::EmbeddedTestServer> http_server_; std::unique_ptr<net::EmbeddedTestServer> http_server_iframe_; DISALLOW_COPY_AND_ASSIGN(WebControllerBrowserTest); }; IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ElementExistenceCheck) { // A visible element RunLaxElementCheck(Selector({"#button"}), true); // A hidden element. RunLaxElementCheck(Selector({"#hidden"}), true); // A nonexistent element. RunLaxElementCheck(Selector({"#doesnotexist"}), false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, PseudoElementChecks) { // A pseudo-element RunLaxElementCheck(Selector({"#terms-and-conditions"}).SetPseudoType(BEFORE), true); // An invisible pseudo-element // // TODO(b/129461999): This is wrong; it should exist. Fix it. RunLaxElementCheck(Selector({"#button"}).SetPseudoType(BEFORE), false); // A non-existent pseudo-element RunLaxElementCheck(Selector({"#button"}).SetPseudoType(AFTER), false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ElementInFrameChecks) { // An iFrame. RunLaxElementCheck(Selector({"#iframe"}), true); // An element in a same-origin iFrame. RunLaxElementCheck(Selector({"#iframe", "#button"}), true); // An element in a same-origin iFrame. RunLaxElementCheck(Selector({"#iframe", "#doesnotexist"}), false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ElementInExternalFrameChecks) { // An OOPIF. RunLaxElementCheck(Selector({"#iframeExternal"}), true); // An element in an OOPIF. RunLaxElementCheck(Selector({"#iframeExternal", "#button"}), true); // An element in an OOPIF. RunLaxElementCheck(Selector({"#iframeExternal", "#doesnotexist"}), false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, VisibilityRequirementCheck) { // A visible element RunLaxElementCheck(Selector({"#button"}).MustBeVisible(), true); // A hidden element. RunLaxElementCheck(Selector({"#hidden"}).MustBeVisible(), false); // A non-existent element RunLaxElementCheck(Selector({"#doesnotexist"}).MustBeVisible(), false); // A pseudo-element RunLaxElementCheck( Selector({"#terms-and-conditions"}).MustBeVisible().SetPseudoType(BEFORE), true); // An invisible pseudo-element RunLaxElementCheck( Selector({"#button"}).MustBeVisible().SetPseudoType(BEFORE), false); // A non-existent pseudo-element RunLaxElementCheck(Selector({"#button"}).MustBeVisible().SetPseudoType(AFTER), false); // An iFrame. RunLaxElementCheck(Selector({"#iframe"}).MustBeVisible(), true); // An element in a same-origin iFrame. RunLaxElementCheck(Selector({"#iframe", "#button"}).MustBeVisible(), true); // An OOPIF. RunLaxElementCheck(Selector({"#iframeExternal"}).MustBeVisible(), true); // An element in an OOPIF. RunLaxElementCheck(Selector({"#iframeExternal", "#button"}).MustBeVisible(), true); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, MultipleVisibleElementCheck) { // both visible RunLaxElementCheck(Selector({"#button,#select"}).MustBeVisible(), true); RunStrictElementCheck(Selector({"#button,#select"}).MustBeVisible(), false); // one visible (first non-visible) RunLaxElementCheck(Selector({"#hidden,#select"}).MustBeVisible(), true); RunStrictElementCheck(Selector({"#hidden,#select"}).MustBeVisible(), true); // one visible (first visible) RunLaxElementCheck(Selector({"#button,#hidden"}).MustBeVisible(), true); RunStrictElementCheck(Selector({"#hidden,#select"}).MustBeVisible(), true); // one invisible, one non-existent RunLaxElementCheck(Selector({"#doesnotexist,#hidden"}).MustBeVisible(), false); RunStrictElementCheck(Selector({"#doesnotexist,#hidden"}).MustBeVisible(), false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, SearchMultipleIframes) { // There are two "iframe" elements in the document so the selector would need // to search in both iframes, which isn't supported. SelectorProto proto; proto.add_filters()->set_css_selector("iframe"); proto.add_filters()->mutable_enter_frame(); proto.add_filters()->set_css_selector("#element_in_iframe_two"); ClientStatus status; FindElement(Selector(proto), &status, nullptr); EXPECT_EQ(TOO_MANY_ELEMENTS, status.proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, InnerTextCondition) { const Selector base_selector({"#with_inner_text span"}); Selector selector = base_selector; selector.MustBeVisible(); RunLaxElementCheck(selector, true); RunStrictElementCheck(selector.MustBeVisible(), false); // No matches selector = base_selector; selector.MatchingInnerText("no match"); RunLaxElementCheck(selector, false); selector.MustBeVisible(); RunLaxElementCheck(selector, false); // Matches exactly one visible element. selector = base_selector; selector.MatchingInnerText("hello, world"); RunLaxElementCheck(selector, true); RunStrictElementCheck(selector, true); selector.MustBeVisible(); RunLaxElementCheck(selector, true); RunStrictElementCheck(selector, true); // Matches case (in)sensitive. selector = base_selector; selector.MatchingInnerText("HELLO, WORLD", /* case_sensitive=*/false); RunLaxElementCheck(selector, true); RunStrictElementCheck(selector, true); selector = base_selector; selector.MatchingInnerText("HELLO, WORLD", /* case_sensitive=*/true); RunLaxElementCheck(selector, false); RunStrictElementCheck(selector, false); // Matches two visible elements selector = base_selector; selector.MatchingInnerText("^hello"); RunLaxElementCheck(selector, true); RunStrictElementCheck(selector, false); selector.MustBeVisible(); RunLaxElementCheck(selector, true); RunStrictElementCheck(selector, false); // Matches one visible, one invisible element selector = base_selector; selector.MatchingInnerText("world$"); RunLaxElementCheck(selector, true); selector.MustBeVisible(); RunLaxElementCheck(selector, true); RunStrictElementCheck(selector, true); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, PseudoTypeAndInnerText) { // Inner text conditions then pseudo type vs pseudo type then inner text // condition. Selector selector({"#with_inner_text span"}); selector.MatchingInnerText("world"); selector.SetPseudoType(PseudoType::BEFORE); RunLaxElementCheck(selector, true); // "before" is the content of the :before, checking the text of pseudo-types // doesn't work. selector = Selector({"#with_inner_text span"}); selector.SetPseudoType(PseudoType::BEFORE); selector.MatchingInnerText("before"); RunLaxElementCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, MultipleBefore) { Selector selector({"span"}); selector.SetPseudoType(PseudoType::BEFORE); // There's more than one "span" with a before, so only a lax check can // succeed. RunLaxElementCheck(selector, true); RunStrictElementCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, PseudoTypeThenBoundingBox) { Selector selector({"span"}); selector.SetPseudoType(PseudoType::BEFORE); selector.proto.add_filters()->mutable_bounding_box(); RunLaxElementCheck(selector, true); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, PseudoTypeThenPickOne) { Selector selector({"span"}); selector.SetPseudoType(PseudoType::BEFORE); selector.proto.add_filters()->mutable_pick_one(); RunStrictElementCheck(selector, true); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, PseudoTypeThenCss) { Selector selector({"span"}); selector.SetPseudoType(PseudoType::BEFORE); selector.proto.add_filters()->set_css_selector("div"); // This makes no sense, but shouldn't return an unexpected error. ClientStatus status; ElementFinder::Result result; FindElement(selector, &status, &result); EXPECT_EQ(ELEMENT_RESOLUTION_FAILED, status.proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, PseudoTypeThenInnerText) { Selector selector({"span"}); selector.SetPseudoType(PseudoType::BEFORE); selector.proto.add_filters()->mutable_inner_text()->set_re2("before"); // This isn't supported yet. RunLaxElementCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, PseudoTypeContent) { Selector selector({"#with_inner_text span"}); auto* content = selector.proto.add_filters()->mutable_pseudo_element_content(); content->set_pseudo_type(PseudoType::BEFORE); content->mutable_content()->set_re2("before"); RunLaxElementCheck(selector, true); content->mutable_content()->set_re2("nomatch"); RunLaxElementCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, PseudoElementContentWithCssStyle) { Selector selector({"#with_inner_text span"}); auto* style = selector.proto.add_filters()->mutable_css_style(); style->set_property("content"); style->set_pseudo_element("before"); style->mutable_value()->set_re2("\"before\""); RunLaxElementCheck(selector, true); style->mutable_value()->set_re2("\"nomatch\""); RunLaxElementCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, CssVisibility) { Selector selector({"#button"}); auto* style = selector.proto.add_filters()->mutable_css_style(); style->set_property("visibility"); style->mutable_value()->set_re2("visible"); EXPECT_TRUE(content::ExecJs(shell(), R"( document.getElementById("button").style.visibility = 'hidden'; )")); RunLaxElementCheck(selector, false); style->set_should_match(false); RunLaxElementCheck(selector, true); EXPECT_TRUE(content::ExecJs(shell(), R"( document.getElementById("button").style.visibility = 'visible'; )")); style->set_should_match(true); RunLaxElementCheck(selector, true); style->set_should_match(false); RunLaxElementCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, InnerTextThenCss) { // There are two divs containing "Section with text", but only one has a // button, which removes #button. SelectorProto proto; proto.add_filters()->set_css_selector("div"); proto.add_filters()->mutable_inner_text()->set_re2("Section with text"); proto.add_filters()->set_css_selector("button"); ClickOrTapElement(Selector(proto), ClickType::CLICK); WaitForElementRemove(Selector({"#button"})); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, FindFormInputByLabel) { // #option1_label refers to the labelled control by id. Selector option1; option1.proto.add_filters()->set_css_selector("#option1_label"); option1.proto.add_filters()->mutable_labelled(); const std::string option1_checked = R"( document.querySelector("#option1").checked; )"; EXPECT_FALSE(content::EvalJs(shell(), option1_checked).ExtractBool()); ClickOrTapElement(option1, ClickType::CLICK); EXPECT_TRUE(content::EvalJs(shell(), option1_checked).ExtractBool()); // #option2 contains the labelled control. Selector option2; option2.proto.add_filters()->set_css_selector("#option2_label"); option2.proto.add_filters()->mutable_labelled(); const std::string option2_checked = R"( document.querySelector("#option2").checked; )"; EXPECT_FALSE(content::EvalJs(shell(), option2_checked).ExtractBool()); ClickOrTapElement(option2, ClickType::CLICK); EXPECT_TRUE(content::EvalJs(shell(), option2_checked).ExtractBool()); // #button is not a label. Selector not_a_label; not_a_label.proto.add_filters()->set_css_selector("#button"); not_a_label.proto.add_filters()->mutable_labelled(); // #bad_label1 and #bad_label2 are labels that don't reference a valid // element. They must not cause JavaScript errors. Selector bad_label1; bad_label1.proto.add_filters()->set_css_selector("#bad_label1"); bad_label1.proto.add_filters()->mutable_labelled(); ClientStatus status; FindElement(bad_label1, &status, nullptr); EXPECT_EQ(ELEMENT_RESOLUTION_FAILED, status.proto_status()); Selector bad_label2; bad_label2.proto.add_filters()->set_css_selector("#bad_label2"); bad_label2.proto.add_filters()->mutable_labelled(); FindElement(bad_label2, &status, nullptr); EXPECT_EQ(ELEMENT_RESOLUTION_FAILED, status.proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, MatchCssSelectorFilter) { Selector selector({"label"}); selector.MatchingInnerText("terms and conditions"); selector.proto.add_filters()->mutable_labelled(); RunStrictElementCheck(selector, true); auto* last_filter = selector.proto.add_filters(); last_filter->set_match_css_selector("input[type='checkbox']"); RunStrictElementCheck(selector, true); last_filter->set_match_css_selector("input[type='text']"); RunStrictElementCheck(selector, false); last_filter->set_match_css_selector(":checked"); RunStrictElementCheck(selector, false); last_filter->set_match_css_selector(":not(:checked)"); RunStrictElementCheck(selector, true); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ValueCondition) { // One match RunLaxElementCheck(Selector({"#input1"}).MatchingValue("helloworld1"), true); RunStrictElementCheck(Selector({"#input1"}).MatchingValue("helloworld1"), true); // Case (in)sensitive match RunLaxElementCheck(Selector({"#input1"}).MatchingValue("HELLOWORLD1", false), true); RunLaxElementCheck(Selector({"#input1"}).MatchingValue("HELLOWORLD1", true), false); RunStrictElementCheck( Selector({"#input1"}).MatchingValue("HELLOWORLD1", false), true); RunStrictElementCheck( Selector({"#input1"}).MatchingValue("HELLOWORLD1", true), false); // No matches RunLaxElementCheck(Selector({"#input2"}).MatchingValue("doesnotmatch"), false); RunStrictElementCheck(Selector({"#input2"}).MatchingValue("doesnotmatch"), false); // Multiple matches RunLaxElementCheck(Selector({"#input1,#input2"}).MatchingValue("^hello"), true); RunStrictElementCheck(Selector({"#input1,#input2"}).MatchingValue("^hello"), false); // Multiple selector matches, one value match RunLaxElementCheck(Selector({"#input1,#input2"}).MatchingValue("helloworld1"), true); RunStrictElementCheck( Selector({"#input1,#input2"}).MatchingValue("helloworld1"), true); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ConcurrentElementsVisibilityCheck) { std::vector<Selector> selectors; std::vector<bool> results; Selector visible_button({"#button"}); visible_button.MustBeVisible(); selectors.emplace_back(visible_button); results.emplace_back(true); Selector visible_with_iframe({"#button", "#watever"}); visible_with_iframe.MustBeVisible(); selectors.emplace_back(visible_with_iframe); results.emplace_back(false); // IFrame. selectors.emplace_back(Selector({"#iframe", "#button"})); results.emplace_back(true); selectors.emplace_back(Selector({"#iframe", "#button", "#whatever"})); results.emplace_back(false); selectors.emplace_back(Selector({"#iframe", "[name=name]"})); results.emplace_back(true); // OOPIF. selectors.emplace_back(Selector({"#iframeExternal", "#button"})); results.emplace_back(true); // Shadow DOM. selectors.emplace_back( Selector({"#iframe", "#shadowsection", "#shadowbutton"})); results.emplace_back(true); selectors.emplace_back( Selector({"#iframe", "#shadowsection", "#shadowbutton", "#whatever"})); results.emplace_back(false); // IFrame inside IFrame. selectors.emplace_back(Selector({"#iframe", "#iframe", "#button"})); results.emplace_back(true); selectors.emplace_back( Selector({"#iframe", "#iframe", "#button", "#whatever"})); results.emplace_back(false); // Hidden element. selectors.emplace_back(Selector({"#hidden"}).MustBeVisible()); results.emplace_back(false); RunElementChecks(/* strict= */ false, selectors, results); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ClickElement) { Selector selector({"#button"}); ClickOrTapElement(selector, ClickType::CLICK); WaitForElementRemove(selector); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ClickElementInIFrame) { ClickOrTapElement(Selector({"#iframe", "#shadowsection", "#shadowbutton"}), ClickType::CLICK); WaitForElementRemove(Selector({"#iframe", "#button"})); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ClickElementInOOPIF) { ClickOrTapElement(Selector({"#iframeExternal", "#button"}), ClickType::CLICK); WaitForElementRemove(Selector({"#iframeExternal", "#div"})); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ClickElementInScrollContainer) { // Make sure #scroll_item_3 is not visible, no matter the screen height. It // also makes sure that there's enough room on the visual viewport to scroll // everything to the center. SetupScrollContainerHeights(); ScrollWindowTo(0); ScrollContainerTo(0); EXPECT_TRUE(content::ExecJs(shell(), R"(var scrollItem3WasClicked = false; let item = document.querySelector("#scroll_item_3"); item.addEventListener("click", function() { scrollItem3WasClicked = true; });)")); Selector selector({"#scroll_item_3"}); ClickOrTapElement(selector, ClickType::CLICK); EXPECT_TRUE(content::EvalJs(shell(), "scrollItem3WasClicked").ExtractBool()); // TODO(b/135909926): Find a reliable way of verifying that the button was // mover roughly to the center. } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, TapElement) { Selector area_two({"#touch_area_two"}); ClickOrTapElement(area_two, ClickType::TAP); WaitForElementRemove(area_two); Selector area_one({"#touch_area_one"}); ClickOrTapElement(area_one, ClickType::TAP); WaitForElementRemove(area_one); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, DISABLED_TapElementMovingOutOfView) { Selector selector({"#touch_area_three"}); ClickOrTapElement(selector, ClickType::TAP); WaitForElementRemove(selector); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, DISABLED_TapElementAfterPageIsIdle) { // Set a very long timeout to make sure either the page is idle or the test // timeout. WaitTillPageIsIdle(base::TimeDelta::FromHours(1)); Selector selector({"#touch_area_one"}); ClickOrTapElement(selector, ClickType::TAP); WaitForElementRemove(selector); } // TODO(crbug.com/920948) Disabled for strong flakiness. IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, DISABLED_TapElementInIFrame) { Selector selector({"#iframe", "#touch_area"}); ClickOrTapElement(selector, ClickType::TAP); WaitForElementRemove(selector); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, DISABLED_TapRandomMovingElementRepeatedly) { Selector button_selector({"#random_moving_button"}); int num_clicks = 100; for (int i = 0; i < num_clicks; ++i) { ClickOrTapElement(button_selector, ClickType::JAVASCRIPT); } std::vector<Selector> click_counter_selectors; std::vector<std::string> expected_values; expected_values.emplace_back(base::NumberToString(num_clicks)); Selector click_counter_selector({"#random_moving_click_counter"}); click_counter_selectors.emplace_back(click_counter_selector); GetFieldsValue(click_counter_selectors, expected_values); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, TapMovingElementRepeatedly) { Selector button_selector({"#moving_button"}); int num_clicks = 100; for (int i = 0; i < num_clicks; ++i) { ClickOrTapElement(button_selector, ClickType::JAVASCRIPT); } std::vector<Selector> click_counter_selectors; std::vector<std::string> expected_values; expected_values.emplace_back(base::NumberToString(num_clicks)); Selector click_counter_selector({"#moving_click_counter"}); click_counter_selectors.emplace_back(click_counter_selector); GetFieldsValue(click_counter_selectors, expected_values); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, TapStaticElementRepeatedly) { Selector button_selector({"#static_button"}); int num_clicks = 100; for (int i = 0; i < num_clicks; ++i) { ClickOrTapElement(button_selector, ClickType::JAVASCRIPT); } std::vector<Selector> click_counter_selectors; std::vector<std::string> expected_values; expected_values.emplace_back(base::NumberToString(num_clicks)); Selector click_counter_selector({"#static_click_counter"}); click_counter_selectors.emplace_back(click_counter_selector); GetFieldsValue(click_counter_selectors, expected_values); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ClickPseudoElement) { const std::string javascript = R"( document.querySelector("#terms-and-conditions").checked; )"; EXPECT_FALSE(content::EvalJs(shell(), javascript).ExtractBool()); Selector selector({R"(label[for="terms-and-conditions"])"}); selector.SetPseudoType(PseudoType::BEFORE); ClickOrTapElement(selector, ClickType::CLICK); EXPECT_TRUE(content::EvalJs(shell(), javascript).ExtractBool()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, FindElement) { Selector selector({"#button"}); FindElementAndCheck(selector, true); selector.MustBeVisible(); FindElementAndCheck(selector, true); // IFrame. selector = Selector({"#iframe", "#button"}); FindElementAndCheck(selector, false); selector.MustBeVisible(); FindElementAndCheck(selector, false); selector = Selector({"#iframe", "[name=name]"}); FindElementAndCheck(selector, false); selector.MustBeVisible(); FindElementAndCheck(selector, false); // IFrame inside IFrame. selector = Selector({"#iframe", "#iframe", "#button"}); FindElementAndCheck(selector, false); selector.MustBeVisible(); FindElementAndCheck(selector, false); // OutOfProcessIFrame. selector = Selector({"#iframeExternal", "#button"}); FindElementAndCheck(selector, false); selector.MustBeVisible(); FindElementAndCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, FindElementNotFound) { FindElementExpectEmptyResult(Selector({"#notfound"})); FindElementExpectEmptyResult(Selector({"#hidden"}).MustBeVisible()); FindElementExpectEmptyResult(Selector({"#iframe", "#iframe", "#notfound"})); FindElementExpectEmptyResult( Selector({"#iframe", "#iframe", "#hidden"}).MustBeVisible()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, FindElementErrorStatus) { ClientStatus status; FindElement(Selector(SelectorProto::default_instance()), &status, nullptr); EXPECT_EQ(INVALID_SELECTOR, status.proto_status()); FindElement(Selector({"#doesnotexist"}), &status, nullptr); EXPECT_EQ(ELEMENT_RESOLUTION_FAILED, status.proto_status()); FindElement(Selector({"div"}), &status, nullptr); EXPECT_EQ(TOO_MANY_ELEMENTS, status.proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ScrollToElementPosition) { Selector selector({"#iframe", "#focus"}); const std::string checkVisibleScript = R"( let iframe = document.querySelector("#iframe"); let div = iframe.contentDocument.querySelector("#focus"); let iframeRect = iframe.getBoundingClientRect(); let divRect = div.getBoundingClientRect(); iframeRect.y + divRect.y < window.innerHeight; )"; EXPECT_EQ(false, content::EvalJs(shell(), checkVisibleScript)); TopPadding top_padding; ScrollToElementPosition(selector, top_padding); EXPECT_EQ(true, content::EvalJs(shell(), checkVisibleScript)); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ScrollToElementPosition_WithScrollIntoViewNeeded) { TestScrollIntoView(/* initial_window_scroll_y= */ 0, /* initial_container_scroll_y=*/0); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ScrollToElementPosition_WithScrollIntoViewNotNeeded) { TestScrollIntoView(/* initial_window_scroll_y= */ 0, /* initial_container_scroll_y=*/200); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ScrollToElementPosition_WithPaddingInPixels) { Selector selector({"#scroll-me"}); const std::string checkScrollDifferentThanTargetScript = R"( window.scrollTo(0, 0); let scrollTarget = document.querySelector("#scroll-me"); let scrollTargetRect = scrollTarget.getBoundingClientRect(); scrollTargetRect.y > 360; )"; EXPECT_EQ(true, content::EvalJs(shell(), checkScrollDifferentThanTargetScript)); // Scroll 360px from the top. TopPadding top_padding{/* value= */ 360, TopPadding::Unit::PIXELS}; ScrollToElementPosition(selector, top_padding); double eval_result = content::EvalJs(shell(), R"( let scrollTarget = document.querySelector("#scroll-me"); let scrollTargetRect = scrollTarget.getBoundingClientRect(); scrollTargetRect.top; )") .ExtractDouble(); EXPECT_NEAR(360, eval_result, 1); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ScrollToElementPosition_WithPaddingInRatio) { Selector selector({"#scroll-me"}); const std::string checkScrollDifferentThanTargetScript = R"( window.scrollTo(0, 0); let scrollTarget = document.querySelector("#scroll-me"); let scrollTargetRect = scrollTarget.getBoundingClientRect(); let targetScrollY = window.innerHeight * 0.7; scrollTargetRect.y > targetScrollY; )"; EXPECT_EQ(true, content::EvalJs(shell(), checkScrollDifferentThanTargetScript)); // Scroll 70% from the top. TopPadding top_padding{/* value= */ 0.7, TopPadding::Unit::RATIO}; ScrollToElementPosition(selector, top_padding); base::ListValue eval_result = content::EvalJs(shell(), R"( let scrollTarget = document.querySelector("#scroll-me"); let scrollTargetRect = scrollTarget.getBoundingClientRect(); [scrollTargetRect.top, window.innerHeight] )") .ExtractList(); double top = eval_result.GetList()[0].GetDouble(); double window_inner_height = eval_result.GetList()[1].GetDouble(); EXPECT_NEAR(top, window_inner_height * 0.7, 1); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, SelectOption) { Selector selector({"#select"}); const std::string javascript = R"( let select = document.querySelector("#select"); select.options[select.selectedIndex].label; )"; // Select value not matching anything. EXPECT_EQ(OPTION_VALUE_NOT_FOUND, SelectOption(selector, "incorrect label", LABEL_STARTS_WITH) .proto_status()); // Selects nothing if no strategy is set. EXPECT_EQ(OPTION_VALUE_NOT_FOUND, SelectOption(selector, "one", UNSPECIFIED_SELECT_STRATEGY) .proto_status()); // Select value matching the option's label. EXPECT_EQ(ACTION_APPLIED, SelectOption(selector, "ZÜRICH", LABEL_STARTS_WITH).proto_status()); EXPECT_EQ("Zürich Hauptbahnhof", content::EvalJs(shell(), javascript)); // Select value matching the option's value. EXPECT_EQ(ACTION_APPLIED, SelectOption(selector, "Aü万𠜎", VALUE_MATCH).proto_status()); EXPECT_EQ("Character Test Entry", content::EvalJs(shell(), javascript)); EXPECT_EQ(ELEMENT_RESOLUTION_FAILED, SelectOption(Selector({"#incorrect_selector"}), "not important", LABEL_STARTS_WITH) .proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, SelectOptionInIFrame) { // IFrame. Selector select_selector({"#iframe", "select[name=state]"}); EXPECT_EQ( ACTION_APPLIED, SelectOption(select_selector, "NY", LABEL_STARTS_WITH).proto_status()); const std::string javascript = R"( let iframe = document.querySelector("iframe").contentDocument; let select = iframe.querySelector("select[name=state]"); select.options[select.selectedIndex].label; )"; EXPECT_EQ("NY", content::EvalJs(shell(), javascript)); // OOPIF. // Checking elements through EvalJs in OOPIF is blocked by cross-site. select_selector = Selector({"#iframeExternal", "select[name=pet]"}); EXPECT_EQ( ACTION_APPLIED, SelectOption(select_selector, "Cat", LABEL_STARTS_WITH).proto_status()); Selector result_selector({"#iframeExternal", "#myPet"}); GetFieldsValue({result_selector}, {"Cat"}); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetOuterHtml) { std::string html; // Div. Selector div_selector({"#testOuterHtml"}); ASSERT_EQ(ACTION_APPLIED, GetOuterHtml(div_selector, &html).proto_status()); EXPECT_EQ( R"(<div id="testOuterHtml"><span>Span</span><p>Paragraph</p></div>)", html); // IFrame. Selector iframe_selector({"#iframe", "#input"}); ASSERT_EQ(ACTION_APPLIED, GetOuterHtml(iframe_selector, &html).proto_status()); EXPECT_EQ(R"(<input id="input" type="text">)", html); // OOPIF. Selector oopif_selector({"#iframeExternal", "#divToRemove"}); ASSERT_EQ(ACTION_APPLIED, GetOuterHtml(oopif_selector, &html).proto_status()); EXPECT_EQ(R"(<div id="divToRemove">Text</div>)", html); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetElementTag) { std::string element_tag; // Div. ASSERT_EQ( ACTION_APPLIED, GetElementTag(Selector({"#testOuterHtml"}), &element_tag).proto_status()); EXPECT_EQ("DIV", element_tag); // Select. ASSERT_EQ(ACTION_APPLIED, GetElementTag(Selector({"#select"}), &element_tag).proto_status()); EXPECT_EQ("SELECT", element_tag); // Input. ASSERT_EQ(ACTION_APPLIED, GetElementTag(Selector({"#input1"}), &element_tag).proto_status()); EXPECT_EQ("INPUT", element_tag); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetAndSetFieldValue) { std::vector<Selector> selectors; std::vector<std::string> expected_values; Selector a_selector({"body"}); // Body has 'undefined' value selectors.emplace_back(a_selector); expected_values.emplace_back(""); GetFieldsValue(selectors, expected_values); selectors.clear(); a_selector = Selector({"#input1"}); selectors.emplace_back(a_selector); expected_values.clear(); expected_values.emplace_back("helloworld1"); GetFieldsValue(selectors, expected_values); EXPECT_EQ(ACTION_APPLIED, SetFieldValue(a_selector, "foo", SET_VALUE).proto_status()); expected_values.clear(); expected_values.emplace_back("foo"); GetFieldsValue(selectors, expected_values); selectors.clear(); a_selector = Selector({"#uppercase_input"}); selectors.emplace_back(a_selector); EXPECT_EQ(ACTION_APPLIED, SetFieldValue(a_selector, /* Zürich */ "Z\xc3\xbcrich", SIMULATE_KEY_PRESSES) .proto_status()); expected_values.clear(); expected_values.emplace_back(/* ZÜRICH */ "Z\xc3\x9cRICH"); GetFieldsValue(selectors, expected_values); selectors.clear(); a_selector = Selector({"#input2"}); selectors.emplace_back(a_selector); expected_values.clear(); expected_values.emplace_back("helloworld2"); GetFieldsValue(selectors, expected_values); EXPECT_EQ( ACTION_APPLIED, SetFieldValue(a_selector, /* value= */ "", SET_VALUE).proto_status()); expected_values.clear(); expected_values.emplace_back(""); GetFieldsValue(selectors, expected_values); selectors.clear(); a_selector = Selector({"#input3"}); selectors.emplace_back(a_selector); expected_values.clear(); expected_values.emplace_back("helloworld3"); GetFieldsValue(selectors, expected_values); EXPECT_EQ(ACTION_APPLIED, SetFieldValue(a_selector, "new value", SIMULATE_KEY_PRESSES) .proto_status()); expected_values.clear(); expected_values.emplace_back("new value"); GetFieldsValue(selectors, expected_values); selectors.clear(); a_selector = Selector({"#input4"}); selectors.emplace_back(a_selector); expected_values.clear(); expected_values.emplace_back("helloworld4"); GetFieldsValue(selectors, expected_values); EXPECT_EQ(ACTION_APPLIED, SetFieldValue(a_selector, "new value", SIMULATE_KEY_PRESSES_SELECT_VALUE) .proto_status()); expected_values.clear(); expected_values.emplace_back("new value"); GetFieldsValue(selectors, expected_values); selectors.clear(); a_selector = Selector({"#input5"}); selectors.emplace_back(a_selector); expected_values.clear(); expected_values.emplace_back("helloworld5"); GetFieldsValue(selectors, expected_values); EXPECT_EQ(ACTION_APPLIED, SetFieldValue(a_selector, "new value", SIMULATE_KEY_PRESSES_FOCUS) .proto_status()); expected_values.clear(); expected_values.emplace_back("new value"); GetFieldsValue(selectors, expected_values); selectors.clear(); a_selector = Selector({"#invalid_selector"}); selectors.emplace_back(a_selector); expected_values.clear(); expected_values.emplace_back(""); GetFieldsValue(selectors, expected_values); EXPECT_EQ(ELEMENT_RESOLUTION_FAILED, SetFieldValue(a_selector, "foobar", SET_VALUE).proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetAndSetFieldValueInIFrame) { // IFrame. Selector a_selector({"#iframe", "#input"}); EXPECT_EQ(ACTION_APPLIED, SetFieldValue(a_selector, "text", SET_VALUE).proto_status()); GetFieldsValue({a_selector}, {"text"}); // OOPIF. a_selector = Selector({"#iframeExternal", "#input"}); EXPECT_EQ(ACTION_APPLIED, SetFieldValue(a_selector, "text", SET_VALUE).proto_status()); GetFieldsValue({a_selector}, {"text"}); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, SendKeyboardInput) { auto input = UTF8ToUnicode("Zürich"); std::string expected_output = "Zürich"; std::vector<Selector> selectors; Selector a_selector({"#input6"}); selectors.emplace_back(a_selector); EXPECT_EQ(ACTION_APPLIED, SendKeyboardInput(a_selector, input).proto_status()); Selector b_selector({"#input7"}); selectors.emplace_back(b_selector); EXPECT_EQ(ACTION_APPLIED, SendKeyboardInput(b_selector, input, /* delay_in_milli= */ -1, /* use_js_focus= */ true) .proto_status()); GetFieldsValue(selectors, {expected_output, expected_output}); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, SendKeyboardInputSetsKeyProperty) { auto input = UTF8ToUnicode("Zürich\r"); std::string expected_output = "ZürichEnter"; std::vector<Selector> selectors; Selector a_selector({"#input_js_event_listener"}); selectors.emplace_back(a_selector); EXPECT_EQ(ACTION_APPLIED, SendKeyboardInput(a_selector, input).proto_status()); GetFieldsValue(selectors, {expected_output}); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, SendKeyboardInputSetsKeyPropertyWithTimeout) { // Sends input keys to a field where JS will intercept KeyDown and // at index 3 it will set a timeout whick inserts an space after the // timeout. If key press delay is enabled, it should handle this // correctly. auto input = UTF8ToUnicode("012345"); std::string expected_output = "012 345"; std::vector<Selector> selectors; Selector a_selector({"#input_js_event_with_timeout"}); selectors.emplace_back(a_selector); EXPECT_EQ(ACTION_APPLIED, SendKeyboardInput(a_selector, input, /* delay_in_milli= */ 100, /* use_js_focus= */ false) .proto_status()); GetFieldsValue(selectors, {expected_output}); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, SetAttribute) { std::vector<std::string> attribute; Selector selector({"#full_height_section"}); attribute.emplace_back("style"); attribute.emplace_back("backgroundColor"); std::string value = "red"; EXPECT_EQ(ACTION_APPLIED, SetAttribute(selector, attribute, value).proto_status()); const std::string javascript = R"( document.querySelector("#full_height_section").style.backgroundColor; )"; EXPECT_EQ(value, content::EvalJs(shell(), javascript)); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ConcurrentGetFieldsValue) { std::vector<Selector> selectors; std::vector<std::string> expected_values; Selector a_selector({"#input1"}); selectors.emplace_back(a_selector); expected_values.emplace_back("helloworld1"); a_selector = Selector({"#input2"}); selectors.emplace_back(a_selector); expected_values.emplace_back("helloworld2"); a_selector = Selector({"#input3"}); selectors.emplace_back(a_selector); expected_values.emplace_back("helloworld3"); a_selector = Selector({"#input4"}); selectors.emplace_back(a_selector); expected_values.emplace_back("helloworld4"); a_selector = Selector({"#input5"}); selectors.emplace_back(a_selector); expected_values.emplace_back("helloworld5"); GetFieldsValue(selectors, expected_values); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, NavigateToUrl) { EXPECT_EQ(kTargetWebsitePath, shell()->web_contents()->GetLastCommittedURL().path()); web_controller_->LoadURL(GURL(url::kAboutBlankURL)); EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); EXPECT_EQ(url::kAboutBlankURL, shell()->web_contents()->GetLastCommittedURL().spec()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, HighlightElement) { Selector selector({"#select"}); const std::string javascript = R"( let select = document.querySelector("#select"); select.style.boxShadow; )"; EXPECT_EQ("", content::EvalJs(shell(), javascript)); EXPECT_EQ(ACTION_APPLIED, HighlightElement(selector).proto_status()); // We only make sure that the element has a non-empty boxShadow style without // requiring an exact string match. EXPECT_NE("", content::EvalJs(shell(), javascript)); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, WaitForHeightChange) { base::RunLoop run_loop; ClientStatus result; web_controller_->WaitForWindowHeightChange( base::BindOnce(&WebControllerBrowserTest::OnClientStatus, base::Unretained(this), run_loop.QuitClosure(), &result)); RuntimeEvaluate("window.dispatchEvent(new Event('resize'))"); run_loop.Run(); EXPECT_EQ(ACTION_APPLIED, result.proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, WaitMainDocumentReadyStateInteractive) { ClientStatus status; DocumentReadyState end_state; base::RunLoop run_loop; web_controller_->WaitForDocumentReadyState( Selector(), DOCUMENT_INTERACTIVE, base::BindOnce(&WebControllerBrowserTest::OnClientStatusAndReadyState, base::Unretained(this), run_loop.QuitClosure(), &status, &end_state)); run_loop.Run(); EXPECT_EQ(ACTION_APPLIED, status.proto_status()) << "Status: " << status; EXPECT_THAT(end_state, AnyOf(DOCUMENT_INTERACTIVE, DOCUMENT_COMPLETE)); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, WaitMainDocumentReadyStateComplete) { ClientStatus status; DocumentReadyState end_state; base::RunLoop run_loop; web_controller_->WaitForDocumentReadyState( Selector(), DOCUMENT_COMPLETE, base::BindOnce(&WebControllerBrowserTest::OnClientStatusAndReadyState, base::Unretained(this), run_loop.QuitClosure(), &status, &end_state)); run_loop.Run(); EXPECT_EQ(ACTION_APPLIED, status.proto_status()) << "Status: " << status; EXPECT_EQ(DOCUMENT_COMPLETE, end_state); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, WaitFrameDocumentReadyStateLoaded) { ClientStatus status; DocumentReadyState end_state; base::RunLoop run_loop; web_controller_->WaitForDocumentReadyState( Selector({"#iframe"}), DOCUMENT_LOADED, base::BindOnce(&WebControllerBrowserTest::OnClientStatusAndReadyState, base::Unretained(this), run_loop.QuitClosure(), &status, &end_state)); run_loop.Run(); EXPECT_EQ(ACTION_APPLIED, status.proto_status()) << "Status: " << status; EXPECT_THAT(end_state, AnyOf(DOCUMENT_LOADED, DOCUMENT_INTERACTIVE, DOCUMENT_COMPLETE)); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetElementRect) { RectF document_element_rect; Selector document_element({"#full_height_section"}); EXPECT_EQ( ACTION_APPLIED, GetElementRect(document_element, &document_element_rect).proto_status()); // The iFrame must be after the #full_height_section element to check that // the resulting rect is global. RectF iframe_element_rect; Selector iframe_element({"#iframe", "#touch_area_1"}); EXPECT_EQ( ACTION_APPLIED, GetElementRect(iframe_element, &iframe_element_rect).proto_status()); EXPECT_GT(iframe_element_rect.top, document_element_rect.bottom); // Make sure the element is within the iframe. RectF iframe_rect; Selector iframe({"#iframe"}); EXPECT_EQ(ACTION_APPLIED, GetElementRect(iframe, &iframe_rect).proto_status()); EXPECT_GT(iframe_element_rect.left, iframe_rect.left); EXPECT_LT(iframe_element_rect.right, iframe_rect.right); EXPECT_GT(iframe_element_rect.top, iframe_rect.top); EXPECT_LT(iframe_element_rect.bottom, iframe_rect.bottom); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetElementByProximity) { Selector input1_selector({"input"}); auto* input1_closest = input1_selector.proto.add_filters()->mutable_closest(); input1_closest->add_target()->set_css_selector("label"); input1_closest->add_target()->mutable_inner_text()->set_re2("Input1"); GetFieldsValue({input1_selector}, {"helloworld1"}); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetElementByProximityWithTooManyCandidates) { Selector selector({"input.pairs"}); auto* closest = selector.proto.add_filters()->mutable_closest(); closest->add_target()->set_css_selector("label.pairs"); closest->set_max_pairs(24); ClientStatus status; ElementFinder::Result result; FindElement(selector, &status, &result); EXPECT_EQ(TOO_MANY_CANDIDATES, status.proto_status()); closest->set_max_pairs(25); FindElement(selector, &status, &result); EXPECT_EQ(ACTION_APPLIED, status.proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ProximityRelative_Position) { Selector selector({"#at_center"}); auto* closest = selector.proto.add_filters()->mutable_closest(); closest->add_target()->set_css_selector("table.proximity td"); auto* inner_text = closest->add_target()->mutable_inner_text(); // The cells of the table look like the following: // // One Two Three // Four Center Five // Six Seven Eight // // The element is "Center", the target is "One" to "Eight". The // relative_position specify that the element should be below|above|... the // target. closest->set_relative_position(SelectorProto::ProximityFilter::BELOW); inner_text->set_re2("One"); RunStrictElementCheck(selector, true); inner_text->set_re2("Two"); RunStrictElementCheck(selector, true); inner_text->set_re2("Three"); RunStrictElementCheck(selector, true); inner_text->set_re2("Four"); RunStrictElementCheck(selector, false); inner_text->set_re2("Five"); RunStrictElementCheck(selector, false); inner_text->set_re2("Six"); RunStrictElementCheck(selector, false); inner_text->set_re2("Seven"); RunStrictElementCheck(selector, false); inner_text->set_re2("Eight"); RunStrictElementCheck(selector, false); inner_text->set_re2("Center"); RunStrictElementCheck(selector, false); closest->set_relative_position(SelectorProto::ProximityFilter::ABOVE); inner_text->set_re2("One"); RunStrictElementCheck(selector, false); inner_text->set_re2("Two"); RunStrictElementCheck(selector, false); inner_text->set_re2("Three"); RunStrictElementCheck(selector, false); inner_text->set_re2("Four"); RunStrictElementCheck(selector, false); inner_text->set_re2("Five"); RunStrictElementCheck(selector, false); inner_text->set_re2("Six"); RunStrictElementCheck(selector, true); inner_text->set_re2("Seven"); RunStrictElementCheck(selector, true); inner_text->set_re2("Eight"); RunStrictElementCheck(selector, true); inner_text->set_re2("Center"); RunStrictElementCheck(selector, false); closest->set_relative_position(SelectorProto::ProximityFilter::LEFT); inner_text->set_re2("One"); RunStrictElementCheck(selector, false); inner_text->set_re2("Two"); RunStrictElementCheck(selector, false); inner_text->set_re2("Three"); RunStrictElementCheck(selector, true); inner_text->set_re2("Four"); RunStrictElementCheck(selector, false); inner_text->set_re2("Five"); RunStrictElementCheck(selector, true); inner_text->set_re2("Six"); RunStrictElementCheck(selector, false); inner_text->set_re2("Seven"); RunStrictElementCheck(selector, false); inner_text->set_re2("Eight"); RunStrictElementCheck(selector, true); inner_text->set_re2("Center"); RunStrictElementCheck(selector, false); closest->set_relative_position(SelectorProto::ProximityFilter::RIGHT); inner_text->set_re2("One"); RunStrictElementCheck(selector, true); inner_text->set_re2("Two"); RunStrictElementCheck(selector, false); inner_text->set_re2("Three"); RunStrictElementCheck(selector, false); inner_text->set_re2("Four"); RunStrictElementCheck(selector, true); inner_text->set_re2("Five"); RunStrictElementCheck(selector, false); inner_text->set_re2("Six"); RunStrictElementCheck(selector, true); inner_text->set_re2("Seven"); RunStrictElementCheck(selector, false); inner_text->set_re2("Eight"); RunStrictElementCheck(selector, false); inner_text->set_re2("Center"); RunStrictElementCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ProximityAlignment) { Selector selector({"#at_center"}); auto* closest = selector.proto.add_filters()->mutable_closest(); closest->add_target()->set_css_selector("table.proximity td"); auto* inner_text = closest->add_target()->mutable_inner_text(); closest->set_in_alignment(true); inner_text->set_re2("One"); RunStrictElementCheck(selector, false); inner_text->set_re2("Two"); RunStrictElementCheck(selector, true); inner_text->set_re2("Three"); RunStrictElementCheck(selector, false); inner_text->set_re2("Four"); RunStrictElementCheck(selector, true); inner_text->set_re2("Five"); RunStrictElementCheck(selector, true); inner_text->set_re2("Six"); RunStrictElementCheck(selector, false); inner_text->set_re2("Seven"); RunStrictElementCheck(selector, true); inner_text->set_re2("Eight"); RunStrictElementCheck(selector, false); inner_text->set_re2("Center"); RunStrictElementCheck(selector, true); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, ProximityAlignmentWithPosition) { Selector selector({"#at_center"}); auto* closest = selector.proto.add_filters()->mutable_closest(); closest->add_target()->set_css_selector("table.proximity td"); auto* inner_text = closest->add_target()->mutable_inner_text(); closest->set_in_alignment(true); closest->set_relative_position(SelectorProto::ProximityFilter::LEFT); inner_text->set_re2("One"); RunStrictElementCheck(selector, false); inner_text->set_re2("Two"); RunStrictElementCheck(selector, false); inner_text->set_re2("Three"); RunStrictElementCheck(selector, false); inner_text->set_re2("Four"); RunStrictElementCheck(selector, false); inner_text->set_re2("Five"); RunStrictElementCheck(selector, true); inner_text->set_re2("Six"); RunStrictElementCheck(selector, false); inner_text->set_re2("Seven"); RunStrictElementCheck(selector, false); inner_text->set_re2("Eight"); RunStrictElementCheck(selector, false); inner_text->set_re2("Center"); RunStrictElementCheck(selector, false); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, FindPseudoElementToClickByProximity) { const std::string javascript = R"( document.querySelector("#terms-and-conditions").checked; )"; EXPECT_FALSE(content::EvalJs(shell(), javascript).ExtractBool()); // This test clicks on the before pseudo-element that's closest to // #terms-and-conditions - this has the same effect as clicking on // #terms-and-conditions. This checks that pseudo-elements have positions and // that we can go through an array of pseudo-elements and choose the closest // one. Selector selector({"label, span"}); selector.SetPseudoType(PseudoType::BEFORE); auto* closest = selector.proto.add_filters()->mutable_closest(); closest->add_target()->set_css_selector("#terms-and-conditions"); ClickOrTapElement(selector, ClickType::CLICK); EXPECT_TRUE(content::EvalJs(shell(), javascript).ExtractBool()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetElementByProximityDifferentFrames) { Selector selector({"input"}); auto* closest = selector.proto.add_filters()->mutable_closest(); closest->add_target()->set_css_selector("#iframe"); closest->add_target()->mutable_pick_one(); closest->add_target()->mutable_enter_frame(); closest->add_target()->set_css_selector("div"); // Cannot compare position of elements on different frames. ClientStatus status; FindElement(Selector(SelectorProto::default_instance()), &status, nullptr); EXPECT_EQ(INVALID_SELECTOR, status.proto_status()); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetElementByProximitySameFrame) { Selector selector({"#iframe", "input[name='email']"}); // The target is searched within #iframe. auto* closest = selector.proto.add_filters()->mutable_closest(); closest->add_target()->set_css_selector("span"); closest->add_target()->mutable_inner_text()->set_re2("Email"); RunLaxElementCheck(selector, true); GetFieldsValue({selector}, {"[email protected]"}); } IN_PROC_BROWSER_TEST_F(WebControllerBrowserTest, GetStringAttribute) { std::string value; std::vector<std::string> inner_text_attribute = {"innerText"}; ASSERT_EQ(ACTION_APPLIED, GetStringAttribute(Selector({"#testOuterHtml p"}), inner_text_attribute, &value) .proto_status()); EXPECT_EQ("Paragraph", value); std::vector<std::string> option_label_attribute = {"options", "2", "label"}; ASSERT_EQ(ACTION_APPLIED, GetStringAttribute(Selector({"#select"}), option_label_attribute, &value) .proto_status()); EXPECT_EQ("Three", value); std::vector<std::string> bad_access = {"none", "none"}; ASSERT_EQ(UNEXPECTED_JS_ERROR, GetStringAttribute(Selector({"#button"}), bad_access, &value) .proto_status()); } } // namespace autofill_assistant
4c38a96d0ac05def1da7ed205212fa9a31550a44
478506575299db25829f19efb565821ab2ff1bf3
/include/netuit/arrange/CompleteTopologyFactory.hpp
e2f223ee530a739727acba8213da56d84e6f342f
[ "MIT" ]
permissive
perryk12/conduit
bf75d7b79f50f2ca123baa0a66cbc4080fd35328
3ea055312598353afd465536c8e04cdec1111c8c
refs/heads/master
2023-01-01T21:56:19.210550
2020-10-22T14:55:44
2020-10-22T14:55:44
300,478,004
0
0
MIT
2020-10-22T15:39:56
2020-10-02T02:13:46
C++
UTF-8
C++
false
false
1,343
hpp
#pragma once #ifndef NETUIT_ARRANGE_COMPLETETOPOLOGYFACTORY_HPP_INCLUDE #define NETUIT_ARRANGE_COMPLETETOPOLOGYFACTORY_HPP_INCLUDE #include "../../../third-party/Empirical/source/base/vector.h" #include "../topology/TopoEdge.hpp" #include "../topology/Topology.hpp" #include "../topology/TopoNode.hpp" namespace netuit { netuit::Topology make_complete_topology(const size_t cardinality) { emp::vector<netuit::TopoNode> res( cardinality ); size_t edge_counter{}; for (size_t i{}; i < cardinality; ++i) { for (size_t j{}; j < cardinality; ++j) { if ( i != j ) { // exclude self-loops netuit::TopoEdge edge{edge_counter++}; res[i].AddInput( edge.GetOutlet() ); res[j].AddOutput( edge.GetInlet() ); } } } return netuit::Topology{ res }; } struct CompleteTopologyFactory { netuit::Topology operator()(const size_t cardinality) const { return make_complete_topology(cardinality); } netuit::Topology operator()(const emp::vector<size_t> cardinality) const { emp_assert(cardinality.size() == 1); return make_complete_topology(cardinality.front()); } static std::string GetName() { return "Complete Topology"; } static std::string GetSlug() { return "complete"; } }; } // namespace netuit #endif // #ifndef NETUIT_ARRANGE_COMPLETETOPOLOGYFACTORY_HPP_INCLUDE
738736edb2a1ac7ddda423501d20bd59bad3379e
9e47fa2c44e8af9a2e2416563178ea1392b2990c
/rs232driver.h
0b45cdf9f8761dd3baadc73826870573f697568b
[]
no_license
koboldwiz/grue-usb-avr
39bfed8106efd1d269caae2a0e0f6fb92e56408f
f64151dd0017f9b545c4925706d4938ac76c14c1
refs/heads/main
2023-01-21T10:03:39.237482
2020-11-25T06:29:54
2020-11-25T06:29:54
315,848,855
0
0
null
null
null
null
UTF-8
C++
false
false
196
h
//Copyright (C) goon 2020. See the LICENSE file for details class RS232Driver { public: RS232Driver(); virtual ~RS232Driver(); protected: private: public: private: int fileno; };
d3024fd884d2bc0913fc9da0c6d176091c3630b0
9afb4e19078c013d2ab04ff765d16cefb1c54075
/BrowsePanel.h
6b69e5aff455901a9a09f10ec98aac123d85478b
[]
no_license
Dofensmirtsz/TiEnEdit
bbdacbad8cecb107162f50cb1de10d0a307eef85
18115709339edfb88af0bf9e82af58eb1e98f74f
refs/heads/master
2021-01-21T18:21:09.520277
2017-06-01T10:01:50
2017-06-01T10:01:50
92,034,232
0
0
null
2017-05-22T09:10:31
2017-05-22T09:10:31
null
UTF-8
C++
false
false
1,086
h
#pragma once #include "wm/Panel.h" #include "wm/Image.h" class TienEdit; namespace vrlib { class Texture; } class DraggableImage : public Image { TienEdit* editor; DragProperties* dragProperties = nullptr; public: DraggableImage(TienEdit* editor, vrlib::Texture* texture, const glm::ivec2& position, const glm::ivec2 &size, const glm::ivec2 &tl = glm::ivec2(0, 0), const glm::ivec2 &br = glm::ivec2(-1, -1), DragProperties* dragProperties = nullptr); virtual bool mouseDrag(bool leftButton, const glm::ivec2 &startPos, const glm::ivec2 &mousePos, const glm::ivec2 &lastMousePos) override; virtual bool mouseFinishDrag(bool leftButton, const glm::ivec2 &startPos, const glm::ivec2 &mousePos) override; }; class BrowsePanel : public Panel { TienEdit* editor; public: std::string directory; enum class FileType { Other, Image, Model, Video, Prefab }; BrowsePanel(TienEdit* editor); ~BrowsePanel(); virtual void onReposition(Component* parent) override; virtual void rebuild(const std::string & directory); FileType fileType(const std::string &file); };
2db61685286fce5494bf9c405229cd41fecb3c57
b6e8a1fa1085a52d7ba6ed6b6f11dbd82905f3ba
/source/lowlevel/brcriticalsection.cpp
043593f2ba9794fb28581ea97378a03c2b6d3d4d
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-warranty-disclaimer", "Zlib" ]
permissive
etsangsplk/burgerlib
ed4039b175ec96fe28c0ccd52d19f5715fbeccc9
bec821be1ba1d7fbe08e3b128b086158d3bb1b21
refs/heads/master
2022-04-03T20:56:46.598519
2020-02-24T09:25:15
2020-02-24T09:25:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,361
cpp
/*************************************** Root base class Copyright (c) 1995-2017 by Rebecca Ann Heineman <[email protected]> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brcriticalsection.h" /*! ************************************ \class Burger::CriticalSection \brief Class for creating a Mutex for a critical section of data In a multiprocessor system, it's necessary to have multiple threads access the same data at the same time. To prevent data collisions, this class is locked just before the data is used/modified and unlocked after the data access/modification is complete so all CPUs/threads do not have to worry about data collisions. \sa Burger::CriticalSectionStatic and Burger::CriticalSectionLock ***************************************/ /*! ************************************ \brief Initialize the data in the class. Sets up operating system defaults to the data ***************************************/ #if !(defined(BURGER_WINDOWS) || defined(BURGER_XBOX360) || defined(BURGER_PS3) || \ defined(BURGER_PS4) || defined(BURGER_SHIELD) || defined(BURGER_VITA) || \ defined(BURGER_MACOSX) || defined(BURGER_IOS) || defined(BURGER_MAC)) || defined(DOXYGEN) Burger::CriticalSection::CriticalSection() { } /*! ************************************ \brief Shutdown the data in the class. Releases the operating system resources allocated by the constructor. ***************************************/ Burger::CriticalSection::~CriticalSection() { } /*! ************************************ \brief Locks the mutex If the mutex is locked, a lock is obtained and execution continues. If the mutex was already locked, the thread halts until the alternate thread that has this mutex locked releases the lock. There is no timeout. \sa Burger::CriticalSection::Unlock() ***************************************/ void Burger::CriticalSection::Lock() { } /*! ************************************ \brief Attempt to lock the mutex If the mutex is locked, the function fails and returns \ref FALSE. Otherwise, the mutex is locked and the function returns \ref TRUE. \sa Lock() and Unlock() ***************************************/ Word Burger::CriticalSection::TryLock(void) { return FALSE; } /*! ************************************ \brief Unlocks the mutex Releases a lock on a mutex and if any other threads are waiting on this lock, they will obtain the lock and the other thread will continue execution. The caller will never block. \note This call MUST be preceded by a matching Lock() call. Calling Unlock() without a preceding Lock() call will result in undefined behavior and in some cases can result in threadlock or a crash. \sa Burger::CriticalSection::Lock() ***************************************/ void Burger::CriticalSection::Unlock() { } #endif /*! ************************************ \class Burger::CriticalSectionStatic \brief Class for creating a Mutex for a statically allocated critical section of data When an object is created in static memory, the order of startup and shutdown is undeterminate in a cross platform way. To avoid an accidental call to this class before it's constructed or after it's destructed, this class will test a flag to determine if it's out of sequence and if so, the Lock() and Unlock() functions will perform no action. Since C++'s startup and shutdown sequence is performed on a single thread, this is a safe method to ensure that unknown startup/shutdown sequences won't accidentally thread lock. \sa Burger::CriticalSection ***************************************/ /*! ************************************ \brief Set the flag that a critical section is initialized ***************************************/ Burger::CriticalSectionStatic::CriticalSectionStatic() : m_bValid(TRUE) { } /*! ************************************ \brief Clears the flag that a critical section is initialized ***************************************/ Burger::CriticalSectionStatic::~CriticalSectionStatic() { m_bValid = FALSE; } /*! ************************************ \fn Burger::CriticalSectionStatic::Lock(void) \brief Locks a mutex if initialized \sa Burger::CriticalSection::Lock() and Burger::CriticalSectionStatic::Unlock() ***************************************/ /*! ************************************ \fn Burger::CriticalSectionStatic::TryLock(void) \brief Tries to lock a mutex if initialized \sa Burger::CriticalSection::TryLock() and Burger::CriticalSectionStatic::Lock() ***************************************/ /*! ************************************ \fn Burger::CriticalSectionStatic::Unlock(void) \brief Unlocks a mutex if initialized \sa Burger::CriticalSection::Unlock() and Burger::CriticalSectionStatic::Lock() ***************************************/ /*! ************************************ \class Burger::CriticalSectionLock \brief Class for locking and releasing a mutex in a function To ease the obtaining and releasing a lock on a Burger::CriticalSection this class is passed a pointer to a mutex and obtains a lock immediately. When the function that has this class locally stored exits, the lock is released. \note This class is not to be used as a global variable or a member of another class. It will not release a lock until the class is destructed \code // Statically created mutex static Burger::CriticalSectionStatic g_Lock; void foo(void) { // Obtain a lock on mutex Burger::CriticalSectionLock(&g_Lock); printf("Do stuff"); // Lock is released on function exit } \endcode \sa Burger::CriticalSectionStatic and Burger::CriticalSection ***************************************/ /*! ************************************ \fn Burger::CriticalSectionLock::CriticalSectionLock(CriticalSection *pCriticalSection) \brief Obtain a lock on a mutex Locks the critical section upon construction. Will release it when the class is destructed. \note \ref NULL pointers are NOT allowed!! \param pCriticalSection Pointer to a valid CriticalSectionLock \sa Burger::CriticalSectionLock and ~CriticalSectionLock() ***************************************/ /*! ************************************ \fn Burger::CriticalSectionLock::~CriticalSectionLock() \brief Release a locked mutex Unlocks the critical section upon destruction. \sa Burger::CriticalSectionLock and CriticalSectionLock::CriticalSectionLock() ***************************************/ /*! ************************************ \class Burger::Semaphore \brief Class for creating a semaphore In a multiprocessor system, it's necessary to have multiple resources available to multiple threads at the same time. To prevent resource starvation, this class is decremented until the number of available resources is exhausted and then it will halt future threads from executing until resources are made available. Further reading http://en.wikipedia.org/wiki/Semaphore_(programming) \note On operating systems that don't have native semaphore support, such as MSDOS, this class will always return error codes for all calls. \sa Burger::CriticalSection and Burger::Thread ***************************************/ #if !(defined(BURGER_WINDOWS) || defined(BURGER_XBOX360) || defined(BURGER_ANDROID) || defined(BURGER_VITA) || \ defined(BURGER_MACOSX) || defined(BURGER_IOS)) || defined(DOXYGEN) /*! ************************************ \brief Initialize a semaphore Query the operating system for a semaphore and initialize it to the initial value. \param uCount Initial number of resources available (0 means a binary semaphore) \sa ~Semaphore() ***************************************/ Burger::Semaphore::Semaphore(Word32 uCount) : m_uCount(uCount) { } /*! ************************************ \brief Shut down a semaphore Release any operating system resources allocated in the creation of the semaphore. \note Care should be exercised in ensuring that all threads are are waiting on semaphores have been shutdown down already. \sa Semaphore(Word32) ***************************************/ Burger::Semaphore::~Semaphore() { } /*! ************************************ \fn Word Burger::Semaphore::Acquire(void) \brief Acquire a lock on a semaphore resource If the semaphore's resource count has not gone to zero or less, decrement the count and immediately return. Otherwise, block until another thread releases the semaphore. \return Zero on success, nonzero in the case of a semaphore failure \sa TryAcquire(Word) or Release(void) ***************************************/ /*! ************************************ \brief Acquire a lock on a semaphore resource with a timeout If the semaphore's resource count has not gone to zero or less, decrement the count and immediately return. Otherwise, block until another thread releases the semaphore or the time in milliseconds has elapsed. If the timeout is zero, return immediately with a non-zero error code. \param uMilliseconds Number of milliseconds to wait for the resource, 0 means no wait, \ref BURGER_MAXUINT means infinite \return Zero on success, One on a timeout, and non Zero or One in the case of a semaphore failure \sa Acquire(void) or Release(void) ***************************************/ Word BURGER_API Burger::Semaphore::TryAcquire(Word /* uMilliseconds */) { return 10; } /*! ************************************ \brief Release a lock on a semaphore resource After a thread has acquired a resource via a semaphore, release it with this call once the resource is no longer needed. \return Zero on success, nonzero in the case of a semaphore failure \sa Acquire(void) or TryAcquire(Word) ***************************************/ Word BURGER_API Burger::Semaphore::Release(void) { return 10; } /*! ************************************ \fn Word32 Burger::Semaphore::GetValue(void) const \brief Get the current number of available resources. \return The number of available resources. \sa Semaphore(Word32) ***************************************/ #endif /*! ************************************ \class Burger::ConditionVariable \brief Class for creating a condition variable In a multiprocessor system, it's sometimes necessary to have a thread wait until an external condition has been satisfied. Once this class is created, the consumer thread will call Wait() with a locked CriticalSection and a timeout and it will halt until time has expired or another thread sends a signal to this class to alert the waiting thread that the stars are finally right and great Cthulhu can rise again. Further reading http://en.wikipedia.org/wiki/Condition_variable#Condition_variables \sa Burger::CriticalSection, Burger::Semaphore and Burger::Thread ***************************************/ /*! ************************************ \brief Initialize a condition signaler \sa ~ConditionVariable() ***************************************/ #if !(defined(BURGER_SHIELD) || defined(BURGER_VITA) || defined(BURGER_MACOSX) || defined(BURGER_IOS)) || defined(DOXYGEN) Burger::ConditionVariable::ConditionVariable() : m_CriticalSection(), m_WaitSemaphore(0), m_SignalsSemaphore(0), m_uWaiting(0), m_uSignals(0) { } /*! ************************************ \brief Release the condition signaler's resources \sa ConditionVariable() ***************************************/ Burger::ConditionVariable::~ConditionVariable() { // Invoke the auto destructors } /*! ************************************ \brief Signal a waiting thread If a thread is waiting for a signal, send a signal to the thread so it may continue execution. If no thread is waiting, do nothing. \return Zero on success, non-zero on error. \sa Broadcast() or Wait(CriticalSection *,Word) ***************************************/ Word BURGER_API Burger::ConditionVariable::Signal(void) { m_CriticalSection.Lock(); // Is there anyone waiting for a signal? if (m_uWaiting > m_uSignals) { // Add to the signal count (Wait() will decrement) ++m_uSignals; // Release a waiting thread m_WaitSemaphore.Release(); // Unlock the data to allow Wait() to continue m_CriticalSection.Unlock(); // Increase the signals semaphore to match m_SignalsSemaphore.Acquire(); } else { // No one was waiting, discard m_CriticalSection.Unlock(); } return 0; } /*! ************************************ \brief Signal all waiting threads If any threads are waiting for a signal, send a signal to all of them so they all may continue execution. If no thread is waiting, do nothing. \return Zero on success, non-zero on error. \sa Signal() or Wait(CriticalSection *,Word) ***************************************/ Word BURGER_API Burger::ConditionVariable::Broadcast(void) { // Lock internal data m_CriticalSection.Lock(); // Anyone waiting? if (m_uWaiting > m_uSignals) { // For all the ones that haven't already gotten a signal // let them execute Word32 uCount = m_uWaiting-m_uSignals; // Always positive // Set the new count m_uSignals = m_uWaiting; // Reduce the number of waiting threads Word32 uCount2 = uCount; do { m_WaitSemaphore.Release(); } while (--uCount2); // The act of unlocking will fire all the released threads m_CriticalSection.Unlock(); // Reacquire the thread count to restore the wait count to // match m_uWaiting (Note that other threads could be modifying this // value, however, Wait() is updating this value, so // from our point of view, it must be restored) do { m_WaitSemaphore.Acquire(); } while (--uCount); } else { // Get out, nothing to see here m_CriticalSection.Unlock(); } return 0; } /*! ************************************ \brief Wait for a signal (With timeout) Halt the thread until a signal is received or if a timeout has elapsed. If any threads are waiting for a signal, send a signal to all of them so they all may continue execution. If no thread is waiting, do nothing. \return Zero on success, non-zero on error. \sa Signal() or Wait(CriticalSection *,Word) ***************************************/ Word BURGER_API Burger::ConditionVariable::Wait(CriticalSection *pCriticalSection,Word uMilliseconds) { // A thread is waiting m_CriticalSection.Lock(); ++m_uWaiting; m_CriticalSection.Unlock(); // Unlock the thread's lock pCriticalSection->Unlock(); // Wait for a signal (With timeout) Word uResult = m_WaitSemaphore.TryAcquire(uMilliseconds); // It returned! m_CriticalSection.Lock(); // Was there a signal from Signal() or Broadcast()? if (m_uSignals) { // Was there a timeout? if (uResult==1) { // Force an obtaining of a resource m_WaitSemaphore.Acquire(); } // Mark this signal as processed m_SignalsSemaphore.Release(); --m_uSignals; } // No longer waiting --m_uWaiting; m_CriticalSection.Unlock(); // Relock the thread's lock pCriticalSection->Lock(); return uResult; } #endif /*! ************************************ \class Burger::Thread \brief Class for creating a thread In a multiprocessor system, it's sometimes necessary to have another CPU run a concurrent thread. This class will handle the dispatching a thread. Further reading http://en.wikipedia.org/wiki/Thread_(computing) \sa Burger::CriticalSection, Burger::Semaphore and Burger::ConditionVariable ***************************************/ /*! ************************************ \brief Initialize a thread to power up defaults \sa Start(), Thread(FunctionPtr,void *) or ~Thread() ***************************************/ #if !(defined(BURGER_WINDOWS) || defined(BURGER_XBOX360) || defined(BURGER_VITA) || defined(BURGER_MACOSX) || defined(BURGER_IOS)) || defined(DOXYGEN) Burger::Thread::Thread() : m_pFunction(NULL), m_pData(NULL), m_pSemaphore(NULL), m_uResult(0) { } /*! ************************************ \brief Initialize a thread and begin execution This constructor will immediately start the thread. If deferred startup is desired, use the default constructor and then call Start() when it's time to launch the thread. \param pFunction Pointer to the entry point to the thread \param pData Pointer to data to pass to the thread \sa Thread() or ~Thread() ***************************************/ Burger::Thread::Thread(FunctionPtr pFunction,void *pData) : m_pFunction(pFunction), m_pData(pData), m_pSemaphore(NULL), m_uResult(0) { // Runt the code Run(this); } /*! ************************************ \brief Kill any running threads \sa Kill(), Thread(FunctionPtr,void *) or Thread() ***************************************/ Burger::Thread::~Thread() { Kill(); } /*! ************************************ \brief Startup a thread If a thread isn't already running, launch this thread of execution. If a thread is already running, return an error \param pFunction Pointer to the entry point to the thread \param pData Pointer to data to pass to the thread \return Zero if no error, non-zero if there was an error \sa Kill() or Wait() ***************************************/ Word BURGER_API Burger::Thread::Start(FunctionPtr pFunction,void *pData) { m_pFunction = pFunction; m_pData = pData; Run(this); return 10; } /*! ************************************ \brief Wait for a thread to exit If a thread isn't already running, return immediately. If a thread is already running, sleep until the thread has completed execution. \return Zero if no error, non-zero if there was an error \sa Kill() or Start() ***************************************/ Word BURGER_API Burger::Thread::Wait(void) { m_pFunction = NULL; m_pData = NULL; return 10; } /*! ************************************ \brief Force shutdown of a thread If a thread isn't already running, return immediately. If a thread is already running, alert the operating system that this thread should be aborted and shut down. \note This is a function of last resort. Some operating systems can leak resources if a thread is shut down in this manner. The proper way to shut down a thread is to sent the thread a signal to alert it to exit it's loop and call Wait(). \return Zero if no error, non-zero if there was an error \sa Wait() or Start() ***************************************/ Word BURGER_API Burger::Thread::Kill(void) { m_pFunction = NULL; m_pData = NULL; return 10; } /*! ************************************ \brief Synchronize and then execute the thread and save the result if any This internal routine is used to synchronize with the main thread to ensure that the class variables are stable before execution begins. It will also capture the result code before exiting back to the operating system. \note This function should not be called by applications. \param pThis Pointer to an instance of Thread \sa Start() ***************************************/ void BURGER_API Burger::Thread::Run(void *pThis) { Thread *pThread = static_cast<Thread *>(pThis); pThread->m_uResult = pThread->m_pFunction(pThread->m_pData); } /*! ************************************ \fn WordPtr Burger::Thread::GetResult(void) const \brief Return the exit code of the user supplied thread. When a thread launched by this class executes, it can return a result code which is captured by the dispatcher. The code can retrieved by this call. \note The code is only valid once the thread exits cleanly. Ending a thread with a call to Kill() will set the error code to a non-zero number. \return Result code from the user code \sa Start() or IsInitialized() ***************************************/ /*! ************************************ \fn Word Burger::Thread::IsInitialized(void) const \brief Return \ref TRUE if a thread is running. Once a thread is started, this function will return \ref TRUE. Once either Wait() or Kill() is called, this function will return \ref FALSE. \return \ref TRUE if a thread was started, or \ref FALSE if not. \sa Start() or GetResult() ***************************************/ #endif
f1406dd40076bd44ba8c5f73835b7628b5600850
f08a55d13af6ab107a868db6419e0b0cb0e1828a
/10972.cpp
914947432170e5a0305e7255f6e4ee9b7af25bb0
[]
no_license
mylvoh0714/BOJ
3bf369c0e03d5fa2aff45075c8db753c709050f7
f9456055bab897cce2041d2a3ad5468090a72a43
refs/heads/master
2018-11-29T09:02:55.134174
2018-11-16T18:06:58
2018-11-16T18:06:58
121,135,047
0
0
null
null
null
null
UTF-8
C++
false
false
580
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> arr; int main() { ios_base::sync_with_stdio(false); int n; cin >> n; arr.resize(n); for ( int i = 0; i < n; i++ ) cin >> arr[i]; int i = n - 1; while ( i > 0 && arr[i - 1] >= arr[i] ) i--; if ( i <= 0 ) { printf("%d\n", -1); return 0; } int j = n - 1; while ( arr[j] <= arr[i - 1] ) j--; int temp = arr[j]; arr[j] = arr[i - 1]; arr[i - 1] = temp; sort(arr.begin() + i, arr.end()); for ( auto i = arr.begin(); i != arr.end(); i++ ) { cout << *i << " "; } }
bca31fbf819a042d28449269bb5dcd6a2ec5c749
b16e2f8cc94df8320f9caf8c8592fa21b1f7c413
/Kattis/prefixfreecode/combinatorics_trie.cpp
e488721a5cb179d824748d149c05df24011d4f6b
[ "MIT" ]
permissive
codgician/Competitive-Programming
000dfafea0575b773b0a10502f5128d2088f3398
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
refs/heads/master
2022-06-13T04:59:52.322037
2020-04-29T06:38:59
2020-04-29T06:38:59
104,017,512
3
0
null
null
null
null
UTF-8
C++
false
false
3,259
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <string> #include <cstring> #include <iomanip> #include <climits> #include <stack> #include <queue> #include <vector> #include <set> #include <map> #include <functional> #include <iterator> using namespace std; #define SIZE 1000010 #define CHAR_SIZE 26 const int mod = 1e9 + 7; typedef struct _TrieNode { int wordId; int nextArr[CHAR_SIZE]; } TrieNode; TrieNode trieArr[SIZE]; int triePt, wordPt; long long int factorialArr[SIZE], invFactorialArr[SIZE]; int bitArr[SIZE]; string strArr[SIZE], s; int arr[SIZE], arrPt; int newTrieNode() { trieArr[triePt].wordId = -1; for (int i = 0; i < CHAR_SIZE; i++) trieArr[triePt].nextArr[i] = -1; return triePt++; } void insertName(string & str) { int cntPt = 0; for (int i = 0; i < (int)str.size(); i++) { int cnt = str[i] - 'a'; if (trieArr[cntPt].nextArr[cnt] == -1) trieArr[cntPt].nextArr[cnt] = newTrieNode(); cntPt = trieArr[cntPt].nextArr[cnt]; } trieArr[cntPt].wordId = wordPt++; } void findStr(string & str) { int len = str.size(), cntPt = 0; arrPt = 0; for (int i = 0; i < len; i++) { int cnt = str[i] - 'a'; cntPt = trieArr[cntPt].nextArr[cnt]; if (trieArr[cntPt].wordId != -1) { arr[arrPt++] = trieArr[cntPt].wordId; cntPt = 0; } } } int getLowbit(int n) { return n & (-n); } void add(int pos, int val) { for (int i = pos; i < SIZE; i += getLowbit(i)) { bitArr[i] += val; } } int getPrefixSum(int pos) { int ans = 0; for (int i = pos; i > 0; i -= getLowbit(i)) { ans += bitArr[i]; } return ans; } long long int fastPow(long long int a, long long int n) { long long int ans = 1; a %= mod; while (n > 0) { if (n & 1) ans = ans * a % mod; a = a * a % mod; n >>= 1; } return ans; } void initFactorial() { factorialArr[0] = 1; for (int i = 1; i < SIZE; i++) factorialArr[i] = factorialArr[i - 1] * i % mod; } void initInvFactorial() { invFactorialArr[SIZE - 1] = fastPow(factorialArr[SIZE - 1], mod - 2); for (int i = SIZE - 2; i >= 0; i--) invFactorialArr[i] = invFactorialArr[i + 1] * (i + 1) % mod; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); initFactorial(); initInvFactorial(); int num, k; while (cin >> num >> k) { memset(bitArr, 0, sizeof(bitArr)); triePt = 0; wordPt = 0; newTrieNode(); for (int i = 0; i < num; i++) cin >> strArr[i]; sort(strArr + 0, strArr + num); for (int i = 0; i < num; i++) { add(i + 1, 1); insertName(strArr[i]); } cin >> s; findStr(s); long long int ans = 1; for (int i = 0; i < arrPt; i++) { int unusedNum = getPrefixSum(arr[i]); add(arr[i] + 1, -1); ans += unusedNum * factorialArr[num - i - 1] % mod * invFactorialArr[num - k] % mod; ans %= mod; } cout << ans << endl; } return 0; }
fa553f17f77a8e31d79e9321592e8c80d424ba59
d7e41f16df202fe917d0d6398cb7a0185db0bbac
/include/wise.kernel/server/server_packets_factory.hpp
463ba3dea7966bd312243d9f2b3b7ed98e3eb28f
[ "MIT" ]
permissive
npangunion/wise.kernel
77a60d4e7fcecd69721d9bd106d41f0e5370282a
a44f852f5e7ade2c5f95f5d615daaf154bc69468
refs/heads/master
2020-12-28T16:17:29.077050
2020-05-18T15:42:30
2020-05-18T15:42:30
238,401,519
1
0
null
null
null
null
UTF-8
C++
false
false
40
hpp
#pragma once void add_server_packets();
edf733116747146ee87ed1cabe69f71c4500b116
4759c53c009224317299082d075d67ca50835ad4
/irondust/sg/isgelement.hpp
21a39b1067e7cee7b1e888be92c6709e9d7a7538
[]
no_license
HymiR/IronDust
bd980d807bf7e3a9eb3921f38bb2e51a5083ed5d
0764c667c1f375aef00e41580516cb7f2e5d7525
refs/heads/master
2021-05-23T23:58:37.611125
2020-10-18T10:56:43
2020-10-18T10:56:43
35,041,701
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
hpp
/** ** This file is part of the irondust project. ** Copyright 2019 CyberViking Softwareschmiede GbR <[email protected]>. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as ** published by the Free Software Foundation, either version 3 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 Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #ifndef ISGELEMENT_HPP #define ISGELEMENT_HPP namespace irondust { namespace sg { class SGContext; class ISGElement { public: virtual ~ISGElement() = default; virtual void render(SGContext& context) = 0; }; } } #endif // ISGELEMENT_HPP
e9456d6bbae376ad70a65702a5eec38b5d6c16fd
38dd1218e921096135f4e9b1001a8020cfc2d2fb
/jni/Sound/OSLSound.cpp
74c7ddc05f54a98e1ae7dd4d5254d55c29147035
[]
no_license
cibergod/Pac-man-for-android-NDK
fb79431de7f786c211f492e39660f251ebac2de2
b85828f17a6916589db2f515c3c7956d0efbd142
refs/heads/master
2021-01-18T08:34:15.413242
2014-01-21T08:10:26
2014-01-21T08:10:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,185
cpp
#include "Sound/OSLSound.h" #include "unistd.h" OSLSound::~OSLSound(){ } OSLSound::OSLSound( OSLContext * context){ this->context = context; this->mgr = context->mgr; player = NULL; volume = 1; } OSLSound::OSLSound( OSLContext * context, char * path){ this->context = context; this->mgr = context->mgr; } void OSLSound::setVolumePlayer(){ if(player != NULL) if(player->sound != NULL && player->sound == this) player->setVolume(volume); } void OSLSound::setVolume(float volume){ this->volume = volume; if(player != NULL) setVolumePlayer(); } float OSLSound::getVolume(){ return this->volume; } void OSLSound::pause(){ if(player == NULL) return; player->pauseAssert(); } void OSLSound::play(bool isLoop){ if( player != NULL && player->isPaused()){ setVolumePlayer(); player->playAssert(); return; } player = context->getFreePlayer(this); if( player == NULL){ return; } player->setSoundAssert(this->context->mgr, this, isLoop); setVolumePlayer(); if( player != NULL) player->playAssert(); } void OSLSound::stop(){ if(player == NULL) return; player->stopAssert(); player = 0; } SLuint32 OSLSound::state(){ if(player == NULL) return SL_PLAYSTATE_STOPPED; return player->state(); } bool OSLSound::isActive(){ int newState = state(); return !(newState == SL_PLAYSTATE_STOPPED); } bool OSLSound::isPlaying(){ return state() == SL_PLAYSTATE_PLAYING; } bool OSLSound::isPaused(){ return state() == SL_PLAYSTATE_PAUSED; } bool OSLSound::isStopped(){ return state() == SL_PLAYSTATE_STOPPED; } AAsset* OSLSound::openFile(char * path){ char fname[80]; strcpy(fname, ""); strcat(fname, path); if(mgr == NULL) LOGE("AAssetManager null"); AAsset* asset = AAssetManager_open(mgr, fname, AASSET_MODE_UNKNOWN); if (mgr == NULL) { LOGE("AAssetManager NULL"); return NULL; } if (NULL == asset) { LOGE("_ASSET_NOT_FOUND_ %s", fname); return NULL; } return asset; } char* OSLSound::readWAVFull(AAssetManager *mgr, BasicWAVEHeader* header){ char* buffer = 0; AAsset * file = openFile(filename); if (!file) { LOGE("no file %s in readWAV",filename); return 0; } char extra[2]; int res = AAsset_read (file,header,sizeof(BasicWAVEHeader)); if(!strstr(header->data, "data")){ AAsset_read (file,extra,2); header->dataSize = AAsset_getLength(file) - sizeof(BasicWAVEHeader)-2; } if(res){ buffer = (char*)malloc(header->dataSize); if (buffer){ res = AAsset_read (file,buffer,header->dataSize); if(res){ AAsset_close(file); return buffer; } free(buffer); } } AAsset_close(file); return 0; } void OSLSound::LogHeaders(){ LOGI("dataSize = %i ",header.dataSize); LOGI("bitsPerSample = %i ",header.bitsPerSample); LOGI("bytesPerSec = %i ",header.bytesPerSec); LOGI("samplesPerSec = %i ",header.samplesPerSec); LOGI("fmtSize = %i ",header.fmtSize); LOGI("riffSize = %i ", header.riffSize); LOGI("channels = %i ", header.channels); } void OSLSound::load(char* filename) { strcpy(this->filename, filename); buf = readWAVFull(mgr, &header); dataSize = header.dataSize; } char * OSLSound::getBuffer(){ return buf; } long OSLSound::getSize(){ return dataSize; }
305b5535d932a7f9d28701fe427d83ca0c512a2b
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
/update_notifier/thirdparty/wxWidgets/tests/strings/strings.cpp
8bbe9d69adabd70e29ffb040d7c9cd306d4d2a30
[ "BSD-3-Clause" ]
permissive
ric2b/Vivaldi-browser
388a328b4cb838a4c3822357a5529642f86316a5
87244f4ee50062e59667bf8b9ca4d5291b6818d7
refs/heads/master
2022-12-21T04:44:13.804535
2022-12-17T16:30:35
2022-12-17T16:30:35
86,637,416
166
41
BSD-3-Clause
2021-03-31T18:49:30
2017-03-29T23:09:05
null
UTF-8
C++
false
false
41,962
cpp
/////////////////////////////////////////////////////////////////////////////// // Name: tests/strings/strings.cpp // Purpose: wxString unit test // Author: Vadim Zeitlin, Wlodzimierz ABX Skiba // Created: 2004-04-19 // Copyright: (c) 2004 Vadim Zeitlin, Wlodzimierz Skiba /////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #include "testprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif // WX_PRECOMP // ---------------------------------------------------------------------------- // test class // ---------------------------------------------------------------------------- class StringTestCase : public CppUnit::TestCase { public: StringTestCase(); private: CPPUNIT_TEST_SUITE( StringTestCase ); CPPUNIT_TEST( String ); CPPUNIT_TEST( PChar ); CPPUNIT_TEST( Format ); CPPUNIT_TEST( FormatUnicode ); CPPUNIT_TEST( Constructors ); CPPUNIT_TEST( StaticConstructors ); CPPUNIT_TEST( Extraction ); CPPUNIT_TEST( Trim ); CPPUNIT_TEST( Find ); CPPUNIT_TEST( Replace ); CPPUNIT_TEST( Match ); CPPUNIT_TEST( CaseChanges ); CPPUNIT_TEST( Compare ); CPPUNIT_TEST( CompareNoCase ); CPPUNIT_TEST( Contains ); CPPUNIT_TEST( ToLong ); CPPUNIT_TEST( ToULong ); #ifdef wxLongLong_t CPPUNIT_TEST( ToLongLong ); CPPUNIT_TEST( ToULongLong ); #endif // wxLongLong_t CPPUNIT_TEST( ToDouble ); CPPUNIT_TEST( FromDouble ); CPPUNIT_TEST( StringBuf ); CPPUNIT_TEST( UTF8Buf ); CPPUNIT_TEST( CStrDataTernaryOperator ); CPPUNIT_TEST( CStrDataOperators ); CPPUNIT_TEST( CStrDataImplicitConversion ); CPPUNIT_TEST( ExplicitConversion ); CPPUNIT_TEST( IndexedAccess ); CPPUNIT_TEST( BeforeAndAfter ); CPPUNIT_TEST( ScopedBuffers ); CPPUNIT_TEST( SupplementaryUniChar ); CPPUNIT_TEST_SUITE_END(); void String(); void PChar(); void Format(); void FormatUnicode(); void Constructors(); void StaticConstructors(); void Extraction(); void Trim(); void Find(); void Replace(); void Match(); void CaseChanges(); void Compare(); void CompareNoCase(); void Contains(); void ToLong(); void ToULong(); #ifdef wxLongLong_t void ToLongLong(); void ToULongLong(); #endif // wxLongLong_t void ToDouble(); void FromDouble(); void StringBuf(); void UTF8Buf(); void CStrDataTernaryOperator(); void DoCStrDataTernaryOperator(bool cond); void CStrDataOperators(); void CStrDataImplicitConversion(); void ExplicitConversion(); void IndexedAccess(); void BeforeAndAfter(); void ScopedBuffers(); void SupplementaryUniChar(); wxDECLARE_NO_COPY_CLASS(StringTestCase); }; // register in the unnamed registry so that these tests are run by default CPPUNIT_TEST_SUITE_REGISTRATION( StringTestCase ); // also include in its own registry so that these tests can be run alone CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( StringTestCase, "StringTestCase" ); StringTestCase::StringTestCase() { } void StringTestCase::String() { wxString a, b, c; a.reserve (128); b.reserve (128); c.reserve (128); for (int i = 0; i < 2; ++i) { a = wxT("Hello"); b = wxT(" world"); c = wxT("! How'ya doin'?"); a += b; a += c; c = wxT("Hello world! What's up?"); CPPUNIT_ASSERT( c != a ); } } void StringTestCase::PChar() { wxChar a [128]; wxChar b [128]; wxChar c [128]; for (int i = 0; i < 2; ++i) { wxStrcpy (a, wxT("Hello")); wxStrcpy (b, wxT(" world")); wxStrcpy (c, wxT("! How'ya doin'?")); wxStrcat (a, b); wxStrcat (a, c); wxStrcpy (c, wxT("Hello world! What's up?")); CPPUNIT_ASSERT( wxStrcmp (c, a) != 0 ); } } void StringTestCase::Format() { wxString s1,s2; s1.Printf(wxT("%03d"), 18); CPPUNIT_ASSERT( s1 == wxString::Format(wxT("%03d"), 18) ); s2.Printf(wxT("Number 18: %s\n"), s1.c_str()); CPPUNIT_ASSERT( s2 == wxString::Format(wxT("Number 18: %s\n"), s1.c_str()) ); static const size_t lengths[] = { 1, 512, 1024, 1025, 2048, 4096, 4097 }; for ( size_t n = 0; n < WXSIZEOF(lengths); n++ ) { const size_t len = lengths[n]; wxString s(wxT('Z'), len); CPPUNIT_ASSERT_EQUAL( len, wxString::Format(wxT("%s"), s.c_str()).length()); } // Positional parameters tests: CPPUNIT_ASSERT_EQUAL ( "two one", wxString::Format(wxT("%2$s %1$s"), wxT("one"), wxT("two")) ); CPPUNIT_ASSERT_EQUAL ( "hello hello", wxString::Format("%1$s %1$s", "hello") ); CPPUNIT_ASSERT_EQUAL ( "4 world hello world 3", wxString::Format("%4$d %2$s %1$s %2$s %3$d", "hello", "world", 3, 4) ); CHECK( wxString::Format("%1$o %1$d %1$x", 20) == "24 20 14" ); } void StringTestCase::FormatUnicode() { #if wxUSE_UNICODE const char *UNICODE_STR = "Iestat\xC4\xAB %i%i"; //const char *UNICODE_STR = "Iestat\xCC\x84 %i%i"; wxString fmt = wxString::FromUTF8(UNICODE_STR); wxString s = wxString::Format(fmt, 1, 1); wxString expected(fmt); expected.Replace("%i", "1"); CPPUNIT_ASSERT_EQUAL( expected, s ); #endif // wxUSE_UNICODE } void StringTestCase::Constructors() { CPPUNIT_ASSERT_EQUAL( "", wxString('Z', 0) ); CPPUNIT_ASSERT_EQUAL( "Z", wxString('Z') ); CPPUNIT_ASSERT_EQUAL( "ZZZZ", wxString('Z', 4) ); CPPUNIT_ASSERT_EQUAL( "Hell", wxString("Hello", 4) ); CPPUNIT_ASSERT_EQUAL( "Hello", wxString("Hello", 5) ); #if wxUSE_UNICODE CPPUNIT_ASSERT_EQUAL( L"", wxString(L'Z', 0) ); CPPUNIT_ASSERT_EQUAL( L"Z", wxString(L'Z') ); CPPUNIT_ASSERT_EQUAL( L"ZZZZ", wxString(L'Z', 4) ); CPPUNIT_ASSERT_EQUAL( L"Hell", wxString(L"Hello", 4) ); CPPUNIT_ASSERT_EQUAL( L"Hello", wxString(L"Hello", 5) ); #endif // wxUSE_UNICODE CPPUNIT_ASSERT_EQUAL( 0, wxString(wxString(), 17).length() ); #if wxUSE_UNICODE_UTF8 // This string has 3 characters (<h>, <e'> and <l>), not 4 when using UTF-8 // locale! if ( wxConvLibc.IsUTF8() ) { wxString s3("h\xc3\xa9llo", 4); CPPUNIT_ASSERT_EQUAL( 3, s3.length() ); CPPUNIT_ASSERT_EQUAL( 'l', (char)s3[2] ); } #endif // wxUSE_UNICODE_UTF8 static const char *s = "?really!"; const char *start = wxStrchr(s, 'r'); const char *end = wxStrchr(s, '!'); CPPUNIT_ASSERT_EQUAL( "really", wxString(start, end) ); // test if creating string from NULL C pointer works: CPPUNIT_ASSERT_EQUAL( "", wxString((const char *)NULL) ); } void StringTestCase::StaticConstructors() { CPPUNIT_ASSERT_EQUAL( "", wxString::FromAscii("") ); CPPUNIT_ASSERT_EQUAL( "", wxString::FromAscii("Hello", 0) ); CPPUNIT_ASSERT_EQUAL( "Hell", wxString::FromAscii("Hello", 4) ); CPPUNIT_ASSERT_EQUAL( "Hello", wxString::FromAscii("Hello", 5) ); CPPUNIT_ASSERT_EQUAL( "Hello", wxString::FromAscii("Hello") ); // FIXME: this doesn't work currently but should! //CPPUNIT_ASSERT_EQUAL( 1, wxString::FromAscii("", 1).length() ); CPPUNIT_ASSERT_EQUAL( "", wxString::FromUTF8("") ); CPPUNIT_ASSERT_EQUAL( "", wxString::FromUTF8("Hello", 0) ); CPPUNIT_ASSERT_EQUAL( "Hell", wxString::FromUTF8("Hello", 4) ); CPPUNIT_ASSERT_EQUAL( "Hello", wxString::FromUTF8("Hello", 5) ); CPPUNIT_ASSERT_EQUAL( "Hello", wxString::FromUTF8("Hello") ); #if wxUSE_UNICODE CPPUNIT_ASSERT_EQUAL( 2, wxString::FromUTF8("h\xc3\xa9llo", 3).length() ); #endif // wxUSE_UNICODE //CPPUNIT_ASSERT_EQUAL( 1, wxString::FromUTF8("", 1).length() ); } void StringTestCase::Extraction() { wxString s(wxT("Hello, world!")); CPPUNIT_ASSERT( wxStrcmp( s.c_str() , wxT("Hello, world!") ) == 0 ); CPPUNIT_ASSERT( wxStrcmp( s.Left(5).c_str() , wxT("Hello") ) == 0 ); CPPUNIT_ASSERT( wxStrcmp( s.Right(6).c_str() , wxT("world!") ) == 0 ); CPPUNIT_ASSERT( wxStrcmp( s(3, 5).c_str() , wxT("lo, w") ) == 0 ); CPPUNIT_ASSERT( wxStrcmp( s.Mid(3).c_str() , wxT("lo, world!") ) == 0 ); CPPUNIT_ASSERT( wxStrcmp( s.substr(3, 5).c_str() , wxT("lo, w") ) == 0 ); CPPUNIT_ASSERT( wxStrcmp( s.substr(3).c_str() , wxT("lo, world!") ) == 0 ); #if wxUSE_UNICODE static const char *germanUTF8 = "Oberfl\303\244che"; wxString strUnicode(wxString::FromUTF8(germanUTF8)); CPPUNIT_ASSERT( strUnicode.Mid(0, 10) == strUnicode ); CPPUNIT_ASSERT( strUnicode.Mid(7, 2) == "ch" ); #endif // wxUSE_UNICODE wxString rest; #define TEST_STARTS_WITH(prefix, correct_rest, result) \ CPPUNIT_ASSERT_EQUAL(result, s.StartsWith(prefix, &rest)); \ if ( result ) \ CPPUNIT_ASSERT_EQUAL(correct_rest, rest) TEST_STARTS_WITH( wxT("Hello"), wxT(", world!"), true ); TEST_STARTS_WITH( wxT("Hello, "), wxT("world!"), true ); TEST_STARTS_WITH( wxT("Hello, world!"), wxT(""), true ); TEST_STARTS_WITH( wxT("Hello, world!!!"), wxT(""), false ); TEST_STARTS_WITH( wxT(""), wxT("Hello, world!"), true ); TEST_STARTS_WITH( wxT("Goodbye"), wxT(""), false ); TEST_STARTS_WITH( wxT("Hi"), wxT(""), false ); #undef TEST_STARTS_WITH rest = "Hello world"; CPPUNIT_ASSERT( rest.StartsWith("Hello ", &rest) ); CPPUNIT_ASSERT_EQUAL("world", rest); #define TEST_ENDS_WITH(suffix, correct_rest, result) \ CPPUNIT_ASSERT_EQUAL(result, s.EndsWith(suffix, &rest)); \ if ( result ) \ CPPUNIT_ASSERT_EQUAL(correct_rest, rest) TEST_ENDS_WITH( wxT(""), wxT("Hello, world!"), true ); TEST_ENDS_WITH( wxT("!"), wxT("Hello, world"), true ); TEST_ENDS_WITH( wxT(", world!"), wxT("Hello"), true ); TEST_ENDS_WITH( wxT("ello, world!"), wxT("H"), true ); TEST_ENDS_WITH( wxT("Hello, world!"), wxT(""), true ); TEST_ENDS_WITH( wxT("very long string"), wxT(""), false ); TEST_ENDS_WITH( wxT("?"), wxT(""), false ); TEST_ENDS_WITH( wxT("Hello, world"), wxT(""), false ); TEST_ENDS_WITH( wxT("Gello, world!"), wxT(""), false ); #undef TEST_ENDS_WITH } void StringTestCase::Trim() { #define TEST_TRIM( str , dir , result ) \ CPPUNIT_ASSERT( wxString(str).Trim(dir) == result ) TEST_TRIM( wxT(" Test "), true, wxT(" Test") ); TEST_TRIM( wxT(" "), true, wxT("") ); TEST_TRIM( wxT(" "), true, wxT("") ); TEST_TRIM( wxT(""), true, wxT("") ); TEST_TRIM( wxT(" Test "), false, wxT("Test ") ); TEST_TRIM( wxT(" "), false, wxT("") ); TEST_TRIM( wxT(" "), false, wxT("") ); TEST_TRIM( wxT(""), false, wxT("") ); #undef TEST_TRIM } void StringTestCase::Find() { #define TEST_FIND( str , start , result ) \ CPPUNIT_ASSERT( wxString(str).find(wxT("ell"), start) == result ); TEST_FIND( wxT("Well, hello world"), 0, 1 ); TEST_FIND( wxT("Well, hello world"), 6, 7 ); TEST_FIND( wxT("Well, hello world"), 9, wxString::npos ); #undef TEST_FIND } void StringTestCase::Replace() { #define TEST_REPLACE( original , pos , len , replacement , result ) \ { \ wxString s = original; \ s.replace( pos , len , replacement ); \ CPPUNIT_ASSERT_EQUAL( result, s ); \ } TEST_REPLACE( wxT("012-AWORD-XYZ"), 4, 5, wxT("BWORD"), wxT("012-BWORD-XYZ") ); TEST_REPLACE( wxT("increase"), 0, 2, wxT("de"), wxT("decrease") ); TEST_REPLACE( wxT("wxWindow"), 8, 0, wxT("s"), wxT("wxWindows") ); TEST_REPLACE( wxT("foobar"), 3, 0, wxT("-"), wxT("foo-bar") ); TEST_REPLACE( wxT("barfoo"), 0, 6, wxT("foobar"), wxT("foobar") ); #define TEST_NULLCHARREPLACE( o , olen, pos , len , replacement , r, rlen ) \ { \ wxString s(o,olen); \ s.replace( pos , len , replacement ); \ CPPUNIT_ASSERT_EQUAL( wxString(r,rlen), s ); \ } TEST_NULLCHARREPLACE( wxT("null\0char"), 9, 5, 1, wxT("d"), wxT("null\0dhar"), 9 ); #define TEST_WXREPLACE( o , olen, olds, news, all, r, rlen ) \ { \ wxString s(o,olen); \ s.Replace( olds, news, all ); \ CPPUNIT_ASSERT_EQUAL( wxString(r,rlen), s ); \ } TEST_WXREPLACE( wxT("null\0char"), 9, wxT("c"), wxT("de"), true, wxT("null\0dehar"), 10 ); TEST_WXREPLACE( wxT("null\0dehar"), 10, wxT("de"), wxT("c"), true, wxT("null\0char"), 9 ); TEST_WXREPLACE( "life", 4, "f", "", false, "lie", 3 ); TEST_WXREPLACE( "life", 4, "f", "", true, "lie", 3 ); TEST_WXREPLACE( "life", 4, "fe", "ve", true, "live", 4 ); TEST_WXREPLACE( "xx", 2, "x", "yy", true, "yyyy", 4 ); TEST_WXREPLACE( "xxx", 3, "xx", "z", true, "zx", 2 ); #undef TEST_WXREPLACE #undef TEST_NULLCHARREPLACE #undef TEST_REPLACE } void StringTestCase::Match() { #define TEST_MATCH( s1 , s2 , result ) \ CPPUNIT_ASSERT( wxString(s1).Matches(s2) == result ) TEST_MATCH( "foobar", "foo*", true ); TEST_MATCH( "foobar", "*oo*", true ); TEST_MATCH( "foobar", "*bar", true ); TEST_MATCH( "foobar", "??????", true ); TEST_MATCH( "foobar", "f??b*", true ); TEST_MATCH( "foobar", "f?b*", false ); TEST_MATCH( "foobar", "*goo*", false ); TEST_MATCH( "foobar", "*foo", false ); TEST_MATCH( "foobarfoo", "*foo", true ); TEST_MATCH( "", "*", true ); TEST_MATCH( "", "?", false ); #undef TEST_MATCH } void StringTestCase::CaseChanges() { wxString s1(wxT("Hello!")); wxString s1u(s1); wxString s1l(s1); s1u.MakeUpper(); s1l.MakeLower(); CPPUNIT_ASSERT_EQUAL( wxT("HELLO!"), s1u ); CPPUNIT_ASSERT_EQUAL( wxT("hello!"), s1l ); wxString s2u, s2l; s2u.MakeUpper(); s2l.MakeLower(); CPPUNIT_ASSERT_EQUAL( "", s2u ); CPPUNIT_ASSERT_EQUAL( "", s2l ); wxString s3("good bye"); CPPUNIT_ASSERT_EQUAL( "Good bye", s3.Capitalize() ); s3.MakeCapitalized(); CPPUNIT_ASSERT_EQUAL( "Good bye", s3 ); CPPUNIT_ASSERT_EQUAL( "Abc", wxString("ABC").Capitalize() ); CPPUNIT_ASSERT_EQUAL( "", wxString().Capitalize() ); } void StringTestCase::Compare() { wxString s1 = wxT("AHH"); wxString eq = wxT("AHH"); wxString neq1 = wxT("HAH"); wxString neq2 = wxT("AH"); wxString neq3 = wxT("AHHH"); wxString neq4 = wxT("AhH"); CPPUNIT_ASSERT( s1 == eq ); CPPUNIT_ASSERT( s1 != neq1 ); CPPUNIT_ASSERT( s1 != neq2 ); CPPUNIT_ASSERT( s1 != neq3 ); CPPUNIT_ASSERT( s1 != neq4 ); CPPUNIT_ASSERT( s1 == wxT("AHH") ); CPPUNIT_ASSERT( s1 != wxT("no") ); CPPUNIT_ASSERT( s1 < wxT("AZ") ); CPPUNIT_ASSERT( s1 <= wxT("AZ") ); CPPUNIT_ASSERT( s1 <= wxT("AHH") ); CPPUNIT_ASSERT( s1 > wxT("AA") ); CPPUNIT_ASSERT( s1 >= wxT("AA") ); CPPUNIT_ASSERT( s1 >= wxT("AHH") ); // test comparison with C strings in Unicode build (must work in ANSI as // well, of course): CPPUNIT_ASSERT( s1 == "AHH" ); CPPUNIT_ASSERT( s1 != "no" ); CPPUNIT_ASSERT( s1 < "AZ" ); CPPUNIT_ASSERT( s1 <= "AZ" ); CPPUNIT_ASSERT( s1 <= "AHH" ); CPPUNIT_ASSERT( s1 > "AA" ); CPPUNIT_ASSERT( s1 >= "AA" ); CPPUNIT_ASSERT( s1 >= "AHH" ); // wxString _s1 = wxT("A\0HH"); // wxString _eq = wxT("A\0HH"); // wxString _neq1 = wxT("H\0AH"); // wxString _neq2 = wxT("A\0H"); // wxString _neq3 = wxT("A\0HHH"); // wxString _neq4 = wxT("A\0hH"); s1.insert(1,1,'\0'); eq.insert(1,1,'\0'); neq1.insert(1,1,'\0'); neq2.insert(1,1,'\0'); neq3.insert(1,1,'\0'); neq4.insert(1,1,'\0'); CPPUNIT_ASSERT( s1 == eq ); CPPUNIT_ASSERT( s1 != neq1 ); CPPUNIT_ASSERT( s1 != neq2 ); CPPUNIT_ASSERT( s1 != neq3 ); CPPUNIT_ASSERT( s1 != neq4 ); CPPUNIT_ASSERT( wxString("\n").Cmp(" ") < 0 ); CPPUNIT_ASSERT( wxString("'").Cmp("!") > 0 ); CPPUNIT_ASSERT( wxString("!").Cmp("z") < 0 ); } void StringTestCase::CompareNoCase() { wxString s1 = wxT("AHH"); wxString eq = wxT("AHH"); wxString eq2 = wxT("AhH"); wxString eq3 = wxT("ahh"); wxString neq = wxT("HAH"); wxString neq2 = wxT("AH"); wxString neq3 = wxT("AHHH"); #define CPPUNIT_CNCEQ_ASSERT(s1, s2) CPPUNIT_ASSERT( s1.CmpNoCase(s2) == 0) #define CPPUNIT_CNCNEQ_ASSERT(s1, s2) CPPUNIT_ASSERT( s1.CmpNoCase(s2) != 0) CPPUNIT_CNCEQ_ASSERT( s1, eq ); CPPUNIT_CNCEQ_ASSERT( s1, eq2 ); CPPUNIT_CNCEQ_ASSERT( s1, eq3 ); CPPUNIT_CNCNEQ_ASSERT( s1, neq ); CPPUNIT_CNCNEQ_ASSERT( s1, neq2 ); CPPUNIT_CNCNEQ_ASSERT( s1, neq3 ); // wxString _s1 = wxT("A\0HH"); // wxString _eq = wxT("A\0HH"); // wxString _eq2 = wxT("A\0hH"); // wxString _eq3 = wxT("a\0hh"); // wxString _neq = wxT("H\0AH"); // wxString _neq2 = wxT("A\0H"); // wxString _neq3 = wxT("A\0HHH"); s1.insert(1,1,'\0'); eq.insert(1,1,'\0'); eq2.insert(1,1,'\0'); eq3.insert(1,1,'\0'); neq.insert(1,1,'\0'); neq2.insert(1,1,'\0'); neq3.insert(1,1,'\0'); CPPUNIT_CNCEQ_ASSERT( s1, eq ); CPPUNIT_CNCEQ_ASSERT( s1, eq2 ); CPPUNIT_CNCEQ_ASSERT( s1, eq3 ); CPPUNIT_CNCNEQ_ASSERT( s1, neq ); CPPUNIT_CNCNEQ_ASSERT( s1, neq2 ); CPPUNIT_CNCNEQ_ASSERT( s1, neq3 ); CPPUNIT_ASSERT( wxString("\n").CmpNoCase(" ") < 0 ); CPPUNIT_ASSERT( wxString("'").CmpNoCase("!") > 0); CPPUNIT_ASSERT( wxString("!").Cmp("Z") < 0 ); } void StringTestCase::Contains() { static const struct ContainsData { const wxChar *hay; const wxChar *needle; bool contains; } containsData[] = { { wxT(""), wxT(""), true }, { wxT(""), wxT("foo"), false }, { wxT("foo"), wxT(""), true }, { wxT("foo"), wxT("f"), true }, { wxT("foo"), wxT("o"), true }, { wxT("foo"), wxT("oo"), true }, { wxT("foo"), wxT("ooo"), false }, { wxT("foo"), wxT("oooo"), false }, { wxT("foo"), wxT("fooo"), false }, }; for ( size_t n = 0; n < WXSIZEOF(containsData); n++ ) { const ContainsData& cd = containsData[n]; CPPUNIT_ASSERT_EQUAL( cd.contains, wxString(cd.hay).Contains(cd.needle) ); } } // flags used in ToLongData.flags enum { Number_Ok = 0, Number_Invalid = 1, Number_Unsigned = 2, // if not specified, works for signed conversion Number_Signed = 4, // if not specified, works for unsigned Number_LongLong = 8, // only for long long tests Number_Long = 16 // only for long tests }; #ifdef wxLongLong_t typedef wxLongLong_t TestValue_t; #else typedef long TestValue_t; #endif wxGCC_WARNING_SUPPRESS(missing-field-initializers) static const struct ToLongData { const wxChar *str; TestValue_t value; int flags; int base; long LValue() const { return value; } unsigned long ULValue() const { return value; } #ifdef wxLongLong_t wxLongLong_t LLValue() const { return value; } wxULongLong_t ULLValue() const { return (wxULongLong_t)value; } #endif // wxLongLong_t bool IsOk() const { return !(flags & Number_Invalid); } } longData[] = { { wxT("1"), 1, Number_Ok }, { wxT("0"), 0, Number_Ok }, { wxT("a"), 0, Number_Invalid }, { wxT("12345"), 12345, Number_Ok }, { wxT("--1"), 0, Number_Invalid }, { wxT("-1"), -1, Number_Signed | Number_Long }, // this is surprising but consistent with strtoul() behaviour { wxT("-1"), (TestValue_t)ULONG_MAX, Number_Unsigned | Number_Long }, // this must overflow, even with 64 bit long { wxT("922337203685477580711"), 0, Number_Invalid }, #ifdef wxLongLong_t { wxT("2147483648"), wxLL(2147483648), Number_LongLong }, { wxT("-2147483648"), wxLL(-2147483648), Number_LongLong | Number_Signed }, { wxT("9223372036854775808"), TestValue_t(wxULL(9223372036854775808)), Number_LongLong | Number_Unsigned }, #endif // wxLongLong_t // Base tests. { wxT("010"), 10, Number_Ok, 10 }, { wxT("010"), 8, Number_Ok, 0 }, { wxT("010"), 8, Number_Ok, 8 }, { wxT("010"), 16, Number_Ok, 16 }, { wxT("0010"), 10, Number_Ok, 10 }, { wxT("0010"), 8, Number_Ok, 0 }, { wxT("0010"), 8, Number_Ok, 8 }, { wxT("0010"), 16, Number_Ok, 16 }, { wxT("0x11"), 0, Number_Invalid, 10 }, { wxT("0x11"), 17, Number_Ok, 0 }, { wxT("0x11"), 0, Number_Invalid, 8 }, { wxT("0x11"), 17, Number_Ok, 16 }, }; wxGCC_WARNING_RESTORE(missing-field-initializers) void StringTestCase::ToLong() { long l; for ( size_t n = 0; n < WXSIZEOF(longData); n++ ) { const ToLongData& ld = longData[n]; if ( ld.flags & (Number_LongLong | Number_Unsigned) ) continue; // NOTE: unless you're using some exotic locale, ToCLong and ToLong // should behave the same for our test data set: CPPUNIT_ASSERT_EQUAL( ld.IsOk(), wxString(ld.str).ToCLong(&l, ld.base) ); if ( ld.IsOk() ) CPPUNIT_ASSERT_EQUAL( ld.LValue(), l ); CPPUNIT_ASSERT_EQUAL( ld.IsOk(), wxString(ld.str).ToLong(&l, ld.base) ); if ( ld.IsOk() ) CPPUNIT_ASSERT_EQUAL( ld.LValue(), l ); } // special case: check that the output is not modified if the parsing // failed completely l = 17; CPPUNIT_ASSERT( !wxString("foo").ToLong(&l) ); CPPUNIT_ASSERT_EQUAL( 17, l ); // also check that it is modified if we did parse something successfully in // the beginning of the string CPPUNIT_ASSERT( !wxString("9 cats").ToLong(&l) ); CPPUNIT_ASSERT_EQUAL( 9, l ); } void StringTestCase::ToULong() { unsigned long ul; for ( size_t n = 0; n < WXSIZEOF(longData); n++ ) { const ToLongData& ld = longData[n]; if ( ld.flags & (Number_LongLong | Number_Signed) ) continue; // NOTE: unless you're using some exotic locale, ToCLong and ToLong // should behave the same for our test data set: CPPUNIT_ASSERT_EQUAL( ld.IsOk(), wxString(ld.str).ToCULong(&ul, ld.base) ); if ( ld.IsOk() ) CPPUNIT_ASSERT_EQUAL( ld.ULValue(), ul ); CPPUNIT_ASSERT_EQUAL( ld.IsOk(), wxString(ld.str).ToULong(&ul, ld.base) ); if ( ld.IsOk() ) CPPUNIT_ASSERT_EQUAL( ld.ULValue(), ul ); } } #ifdef wxLongLong_t void StringTestCase::ToLongLong() { wxLongLong_t l; for ( size_t n = 0; n < WXSIZEOF(longData); n++ ) { const ToLongData& ld = longData[n]; if ( ld.flags & (Number_Long | Number_Unsigned) ) continue; CPPUNIT_ASSERT_EQUAL( ld.IsOk(), wxString(ld.str).ToLongLong(&l, ld.base) ); if ( ld.IsOk() ) CPPUNIT_ASSERT_EQUAL( ld.LLValue(), l ); } } void StringTestCase::ToULongLong() { wxULongLong_t ul; for ( size_t n = 0; n < WXSIZEOF(longData); n++ ) { const ToLongData& ld = longData[n]; if ( ld.flags & (Number_Long | Number_Signed) ) continue; CPPUNIT_ASSERT_EQUAL( ld.IsOk(), wxString(ld.str).ToULongLong(&ul, ld.base) ); if ( ld.IsOk() ) CPPUNIT_ASSERT_EQUAL( ld.ULLValue(), ul ); } } #endif // wxLongLong_t void StringTestCase::ToDouble() { double d; static const struct ToDoubleData { const wxChar *str; double value; bool ok; } doubleData[] = { { wxT("1"), 1, true }, { wxT("1.23"), 1.23, true }, { wxT(".1"), .1, true }, { wxT("1."), 1, true }, { wxT("1.."), 0, false }, { wxT("0"), 0, true }, { wxT("a"), 0, false }, { wxT("12345"), 12345, true }, { wxT("-1"), -1, true }, { wxT("--1"), 0, false }, { wxT("-3E-5"), -3E-5, true }, { wxT("-3E-abcde5"), 0, false }, }; // test ToCDouble() first: size_t n; for ( n = 0; n < WXSIZEOF(doubleData); n++ ) { const ToDoubleData& ld = doubleData[n]; CPPUNIT_ASSERT_EQUAL( ld.ok, wxString(ld.str).ToCDouble(&d) ); if ( ld.ok ) CPPUNIT_ASSERT_EQUAL( ld.value, d ); } // test ToDouble() now: // NOTE: for the test to be reliable, we need to set the locale explicitly // so that we know the decimal point character to use if (!wxLocale::IsAvailable(wxLANGUAGE_FRENCH)) return; // you should have french support installed to continue this test! wxLocale locale; // don't load default catalog, it may be unavailable: CPPUNIT_ASSERT( locale.Init(wxLANGUAGE_FRENCH, wxLOCALE_DONT_LOAD_DEFAULT) ); static const struct ToDoubleData doubleData2[] = { { wxT("1"), 1, true }, { wxT("1,23"), 1.23, true }, { wxT(",1"), .1, true }, { wxT("1,"), 1, true }, { wxT("1,,"), 0, false }, { wxT("0"), 0, true }, { wxT("a"), 0, false }, { wxT("12345"), 12345, true }, { wxT("-1"), -1, true }, { wxT("--1"), 0, false }, { wxT("-3E-5"), -3E-5, true }, { wxT("-3E-abcde5"), 0, false }, }; for ( n = 0; n < WXSIZEOF(doubleData2); n++ ) { const ToDoubleData& ld = doubleData2[n]; CPPUNIT_ASSERT_EQUAL( ld.ok, wxString(ld.str).ToDouble(&d) ); if ( ld.ok ) CPPUNIT_ASSERT_EQUAL( ld.value, d ); } } void StringTestCase::FromDouble() { static const struct FromDoubleTestData { double value; int prec; const char *str; } testData[] = { { 1.23, -1, "1.23" }, #if defined(wxDEFAULT_MANTISSA_SIZE_3) { -3e-10, -1, "-3e-010" }, #else { -3e-10, -1, "-3e-10" }, #endif { -0.45678, -1, "-0.45678" }, { 1.2345678, 0, "1" }, { 1.2345678, 1, "1.2" }, { 1.2345678, 2, "1.23" }, { 1.2345678, 3, "1.235" }, }; for ( unsigned n = 0; n < WXSIZEOF(testData); n++ ) { const FromDoubleTestData& td = testData[n]; CPPUNIT_ASSERT_EQUAL( td.str, wxString::FromCDouble(td.value, td.prec) ); } if ( !wxLocale::IsAvailable(wxLANGUAGE_FRENCH) ) return; wxLocale locale; CPPUNIT_ASSERT( locale.Init(wxLANGUAGE_FRENCH, wxLOCALE_DONT_LOAD_DEFAULT) ); for ( unsigned m = 0; m < WXSIZEOF(testData); m++ ) { const FromDoubleTestData& td = testData[m]; wxString str(td.str); str.Replace(".", ","); CPPUNIT_ASSERT_EQUAL( str, wxString::FromDouble(td.value, td.prec) ); } } void StringTestCase::StringBuf() { // check that buffer can be used to write into the string wxString s; wxStrcpy(wxStringBuffer(s, 10), wxT("foo")); CPPUNIT_ASSERT_EQUAL(3, s.length()); CPPUNIT_ASSERT(wxT('f') == s[0u]); CPPUNIT_ASSERT(wxT('o') == s[1]); CPPUNIT_ASSERT(wxT('o') == s[2]); { // also check that the buffer initially contains the original string // contents wxStringBuffer buf(s, 10); CPPUNIT_ASSERT_EQUAL( wxT('f'), buf[0] ); CPPUNIT_ASSERT_EQUAL( wxT('o'), buf[1] ); CPPUNIT_ASSERT_EQUAL( wxT('o'), buf[2] ); CPPUNIT_ASSERT_EQUAL( wxT('\0'), buf[3] ); } { wxStringBufferLength buf(s, 10); CPPUNIT_ASSERT_EQUAL( wxT('f'), buf[0] ); CPPUNIT_ASSERT_EQUAL( wxT('o'), buf[1] ); CPPUNIT_ASSERT_EQUAL( wxT('o'), buf[2] ); CPPUNIT_ASSERT_EQUAL( wxT('\0'), buf[3] ); // and check that it can be used to write only the specified number of // characters to the string wxStrcpy(buf, wxT("barrbaz")); buf.SetLength(4); } CPPUNIT_ASSERT_EQUAL(4, s.length()); CPPUNIT_ASSERT(wxT('b') == s[0u]); CPPUNIT_ASSERT(wxT('a') == s[1]); CPPUNIT_ASSERT(wxT('r') == s[2]); CPPUNIT_ASSERT(wxT('r') == s[3]); // check that creating buffer of length smaller than string works, i.e. at // least doesn't crash (it would if we naively copied the entire original // string contents in the buffer) *wxStringBuffer(s, 1) = '!'; } void StringTestCase::UTF8Buf() { #if wxUSE_UNICODE // "czech" in Czech ("cestina"): static const char *textUTF8 = "\304\215e\305\241tina"; static const wchar_t textUTF16[] = {0x10D, 0x65, 0x161, 0x74, 0x69, 0x6E, 0x61, 0}; wxString s; wxStrcpy(wxUTF8StringBuffer(s, 9), textUTF8); CPPUNIT_ASSERT(s == textUTF16); { wxUTF8StringBufferLength buf(s, 20); wxStrcpy(buf, textUTF8); buf.SetLength(5); } CPPUNIT_ASSERT(s == wxString(textUTF16, 0, 3)); #endif // wxUSE_UNICODE } void StringTestCase::CStrDataTernaryOperator() { DoCStrDataTernaryOperator(true); DoCStrDataTernaryOperator(false); } template<typename T> bool CheckStr(const wxString& expected, T s) { return expected == wxString(s); } void StringTestCase::DoCStrDataTernaryOperator(bool cond) { // test compilation of wxCStrData when used with operator?: (the asserts // are not very important, we're testing if the code compiles at all): wxString s("foo"); // Using literal strings in ternary operator below results in these // warnings, but they're unavoidable if we want such code to continue to // compile at all, as it used to in pre-3.0 versions, so just suppress them. wxGCC_WARNING_SUPPRESS(write-strings) wxCLANG_WARNING_SUPPRESS(c++11-compat-deprecated-writable-strings) const wchar_t *wcStr = L"foo"; CPPUNIT_ASSERT( CheckStr(s, (cond ? s.c_str() : wcStr)) ); CPPUNIT_ASSERT( CheckStr(s, (cond ? s.c_str() : L"foo")) ); CPPUNIT_ASSERT( CheckStr(s, (cond ? wcStr : s.c_str())) ); CPPUNIT_ASSERT( CheckStr(s, (cond ? L"foo" : s.c_str())) ); const char *mbStr = "foo"; CPPUNIT_ASSERT( CheckStr(s, (cond ? s.c_str() : mbStr)) ); CPPUNIT_ASSERT( CheckStr(s, (cond ? s.c_str() : "foo")) ); CPPUNIT_ASSERT( CheckStr(s, (cond ? mbStr : s.c_str())) ); CPPUNIT_ASSERT( CheckStr(s, (cond ? "foo" : s.c_str())) ); wxGCC_WARNING_RESTORE(write-strings) wxCLANG_WARNING_RESTORE(c++11-compat-deprecated-writable-strings) wxString empty(""); CPPUNIT_ASSERT( CheckStr(empty, (cond ? empty.c_str() : wxEmptyString)) ); CPPUNIT_ASSERT( CheckStr(empty, (cond ? wxEmptyString : empty.c_str())) ); } void StringTestCase::CStrDataOperators() { wxString s("hello"); CPPUNIT_ASSERT( s.c_str()[0] == 'h' ); CPPUNIT_ASSERT( s.c_str()[1] == 'e' ); // IMPORTANT: at least with the CRT coming with MSVC++ 2008 trying to access // the final character results in an assert failure (with debug CRT) //CPPUNIT_ASSERT( s.c_str()[5] == '\0' ); CPPUNIT_ASSERT( *s.c_str() == 'h' ); CPPUNIT_ASSERT( *(s.c_str() + 2) == 'l' ); //CPPUNIT_ASSERT( *(s.c_str() + 5) == '\0' ); } bool CheckStrChar(const wxString& expected, char *s) { return CheckStr(expected, s); } bool CheckStrWChar(const wxString& expected, wchar_t *s) { return CheckStr(expected, s); } bool CheckStrConstChar(const wxString& expected, const char *s) { return CheckStr(expected, s); } bool CheckStrConstWChar(const wxString& expected, const wchar_t *s) { return CheckStr(expected, s); } void StringTestCase::CStrDataImplicitConversion() { wxString s("foo"); CPPUNIT_ASSERT( CheckStrConstWChar(s, s.c_str()) ); CPPUNIT_ASSERT( CheckStrConstChar(s, s.c_str()) ); // implicit conversion of wxString is not available in STL build #if !wxUSE_STL CPPUNIT_ASSERT( CheckStrConstWChar(s, s) ); #if wxUSE_UNSAFE_WXSTRING_CONV CPPUNIT_ASSERT( CheckStrConstChar(s, s) ); #endif #endif } void StringTestCase::ExplicitConversion() { wxString s("foo"); CPPUNIT_ASSERT( CheckStr(s, s.mb_str()) ); CPPUNIT_ASSERT( CheckStrConstChar(s, s.mb_str()) ); CPPUNIT_ASSERT( CheckStrChar(s, s.char_str()) ); CPPUNIT_ASSERT( CheckStr(s, s.wc_str()) ); CPPUNIT_ASSERT( CheckStrConstWChar(s, s.wc_str()) ); CPPUNIT_ASSERT( CheckStrWChar(s, s.wchar_str()) ); } void StringTestCase::IndexedAccess() { wxString s("bar"); CPPUNIT_ASSERT_EQUAL( 'r', (char)s[2] ); // this tests for a possible bug in UTF-8 based wxString implementation: // the 3rd character of the underlying byte string is going to change, but // the 3rd character of wxString should remain the same s[0] = L'\xe9'; CPPUNIT_ASSERT_EQUAL( 'r', (char)s[2] ); } void StringTestCase::BeforeAndAfter() { // Construct a string with 2 equal signs in it by concatenating its three // parts: before the first "=", in between the two "="s and after the last // one. This allows to avoid duplicating the string contents (which has to // be different for Unicode and ANSI builds) in the tests below. #if wxUSE_UNICODE #define FIRST_PART L"letter" #define MIDDLE_PART L"\xe9;\xe7a" #define LAST_PART L"l\xe0" #else // !wxUSE_UNICODE #define FIRST_PART "letter" #define MIDDLE_PART "e;ca" #define LAST_PART "la" #endif // wxUSE_UNICODE/!wxUSE_UNICODE const wxString s(FIRST_PART wxT("=") MIDDLE_PART wxT("=") LAST_PART); wxString r; CPPUNIT_ASSERT_EQUAL( FIRST_PART, s.BeforeFirst('=', &r) ); CPPUNIT_ASSERT_EQUAL( MIDDLE_PART wxT("=") LAST_PART, r ); CPPUNIT_ASSERT_EQUAL( s, s.BeforeFirst('!', &r) ); CPPUNIT_ASSERT_EQUAL( "", r ); CPPUNIT_ASSERT_EQUAL( FIRST_PART wxT("=") MIDDLE_PART, s.BeforeLast('=', &r) ); CPPUNIT_ASSERT_EQUAL( LAST_PART, r ); CPPUNIT_ASSERT_EQUAL( "", s.BeforeLast('!', &r) ); CPPUNIT_ASSERT_EQUAL( s, r ); CPPUNIT_ASSERT_EQUAL( MIDDLE_PART wxT("=") LAST_PART, s.AfterFirst('=') ); CPPUNIT_ASSERT_EQUAL( "", s.AfterFirst('!') ); CPPUNIT_ASSERT_EQUAL( LAST_PART, s.AfterLast('=') ); CPPUNIT_ASSERT_EQUAL( s, s.AfterLast('!') ); #undef LAST_PART #undef MIDDLE_PART #undef FIRST_PART } void StringTestCase::ScopedBuffers() { // wxString relies on efficient buffers, verify they work as they should const char *literal = "Hello World!"; // non-owned buffer points to the string passed to it wxScopedCharBuffer sbuf = wxScopedCharBuffer::CreateNonOwned(literal); CPPUNIT_ASSERT( sbuf.data() == literal ); // a copy of scoped non-owned buffer still points to the same string wxScopedCharBuffer sbuf2(sbuf); CPPUNIT_ASSERT( sbuf.data() == sbuf2.data() ); // but assigning it to wxCharBuffer makes a full copy wxCharBuffer buf(sbuf); CPPUNIT_ASSERT( buf.data() != literal ); CPPUNIT_ASSERT_EQUAL( std::string(literal), buf.data() ); wxCharBuffer buf2 = sbuf; CPPUNIT_ASSERT( buf2.data() != literal ); CPPUNIT_ASSERT_EQUAL( std::string(literal), buf.data() ); // Check that extending the buffer keeps it NUL-terminated. size_t len = 10; wxCharBuffer buf3(len); CPPUNIT_ASSERT_EQUAL('\0', buf3.data()[len]); wxCharBuffer buf4; buf4.extend(len); CPPUNIT_ASSERT_EQUAL('\0', buf4.data()[len]); wxCharBuffer buf5(5); buf5.extend(len); CPPUNIT_ASSERT_EQUAL('\0', buf5.data()[len]); } void StringTestCase::SupplementaryUniChar() { #if wxUSE_UNICODE // Test wxString(wxUniChar ch, size_t nRepeat = 1), // which is implemented upon assign(size_t n, wxUniChar ch). { wxString s(wxUniChar(0x12345)); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(2, s.length()); CPPUNIT_ASSERT_EQUAL(0xD808, s[0].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDF45, s[1].GetValue()); #else CPPUNIT_ASSERT_EQUAL(1, s.length()); CPPUNIT_ASSERT_EQUAL(0x12345, s[0].GetValue()); #endif } // Test operator=(wxUniChar ch). { wxString s; s = wxUniChar(0x23456); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(2, s.length()); CPPUNIT_ASSERT_EQUAL(0xD84D, s[0].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDC56, s[1].GetValue()); #else CPPUNIT_ASSERT_EQUAL(1, s.length()); CPPUNIT_ASSERT_EQUAL(0x23456, s[0].GetValue()); #endif } // Test operator+=(wxUniChar ch). { wxString s = "A"; s += wxUniChar(0x34567); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(3, s.length()); CPPUNIT_ASSERT_EQUAL(0xD891, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDD67, s[2].GetValue()); #else CPPUNIT_ASSERT_EQUAL(2, s.length()); CPPUNIT_ASSERT_EQUAL(0x34567, s[1].GetValue()); #endif } // Test operator<<(wxUniChar ch), // which is implemented upon append(size_t n, wxUniChar ch). { wxString s = "A"; s << wxUniChar(0x45678); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(3, s.length()); CPPUNIT_ASSERT_EQUAL(0xD8D5, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDE78, s[2].GetValue()); #else CPPUNIT_ASSERT_EQUAL(2, s.length()); CPPUNIT_ASSERT_EQUAL(0x45678, s[1].GetValue()); #endif } // Test insert(size_t nPos, size_t n, wxUniChar ch). { wxString s = L"\x3042\x208\x3059"; s.insert(1, 2, wxUniChar(0x12345)); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(7, s.length()); CPPUNIT_ASSERT_EQUAL(0xD808, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDF45, s[2].GetValue()); CPPUNIT_ASSERT_EQUAL(0xD808, s[3].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDF45, s[4].GetValue()); #else CPPUNIT_ASSERT_EQUAL(5, s.length()); CPPUNIT_ASSERT_EQUAL(0x12345, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0x12345, s[2].GetValue()); #endif } // Test insert(iterator it, wxUniChar ch). { wxString s = L"\x3042\x208\x3059"; s.insert(s.begin() + 1, wxUniChar(0x23456)); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(5, s.length()); CPPUNIT_ASSERT_EQUAL(0xD84D, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDC56, s[2].GetValue()); #else CPPUNIT_ASSERT_EQUAL(4, s.length()); CPPUNIT_ASSERT_EQUAL(0x23456, s[1].GetValue()); #endif } // Test insert(iterator it, size_type n, wxUniChar ch). { wxString s = L"\x3042\x208\x3059"; s.insert(s.begin() + 1, 2, wxUniChar(0x34567)); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(7, s.length()); CPPUNIT_ASSERT_EQUAL(0xD891, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDD67, s[2].GetValue()); #else CPPUNIT_ASSERT_EQUAL(5, s.length()); CPPUNIT_ASSERT_EQUAL(0x34567, s[1].GetValue()); #endif } // Test replace(size_t nStart, size_t nLen, size_t nCount, wxUniChar ch). { wxString s = L"\x3042\x208\x3059"; s.replace(1, 2, 2, wxUniChar(0x45678)); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(5, s.length()); CPPUNIT_ASSERT_EQUAL(0xD8D5, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDE78, s[2].GetValue()); CPPUNIT_ASSERT_EQUAL(0xD8D5, s[3].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDE78, s[4].GetValue()); #else CPPUNIT_ASSERT_EQUAL(3, s.length()); CPPUNIT_ASSERT_EQUAL(0x45678, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0x45678, s[2].GetValue()); #endif } // Test replace(iterator first, iterator last, size_type n, wxUniChar ch). { wxString s = L"\x3042\x208\x3059"; s.replace(s.begin() + 1, s.end(), 2, wxUniChar(0x34567)); #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(5, s.length()); CPPUNIT_ASSERT_EQUAL(0xD891, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDD67, s[2].GetValue()); CPPUNIT_ASSERT_EQUAL(0xD891, s[3].GetValue()); CPPUNIT_ASSERT_EQUAL(0xDD67, s[4].GetValue()); #else CPPUNIT_ASSERT_EQUAL(3, s.length()); CPPUNIT_ASSERT_EQUAL(0x34567, s[1].GetValue()); CPPUNIT_ASSERT_EQUAL(0x34567, s[2].GetValue()); #endif } // Test find(wxUniChar ch, size_t nStart = 0) // and rfind(wxUniChar ch, size_t nStart = npos). { wxString s = L"\x308\x2063"; s << wxUniChar(0x12345); s << "x"; s += wxUniChar(0x12345); s += "y"; #if wxUSE_UNICODE_UTF16 CPPUNIT_ASSERT_EQUAL(8, s.length()); CPPUNIT_ASSERT_EQUAL(2, s.find(wxUniChar(0x12345))); CPPUNIT_ASSERT_EQUAL(5, s.find(wxUniChar(0x12345), 3)); CPPUNIT_ASSERT_EQUAL(5, s.rfind(wxUniChar(0x12345))); CPPUNIT_ASSERT_EQUAL(2, s.rfind(wxUniChar(0x12345), 4)); #else CPPUNIT_ASSERT_EQUAL(6, s.length()); CPPUNIT_ASSERT_EQUAL(2, s.find(wxUniChar(0x12345))); CPPUNIT_ASSERT_EQUAL(4, s.find(wxUniChar(0x12345), 3)); CPPUNIT_ASSERT_EQUAL(4, s.rfind(wxUniChar(0x12345))); CPPUNIT_ASSERT_EQUAL(2, s.rfind(wxUniChar(0x12345), 3)); #endif } /* Not tested here: find_first_of, find_last_of, find_first_not_of, find_last_not_of */ #endif }
36eea9c0d76ac87ea937f2ed65671c1120a3bc3e
700dc3170fddbdf6eb53ff39a0b29749e7645a39
/debug/moc_digitaldiary.cpp
11ce64f6f2266474150bfb2088285430acbd3937
[]
no_license
pseudoPixels/digitalDiary
6e2e40c86e1d58eb153889c2470c4466718116b6
dad14aa70f819370111ee5747c1a734c15180f65
refs/heads/master
2020-04-05T06:22:39.567534
2018-11-08T02:06:26
2018-11-08T02:06:26
156,635,831
0
0
null
null
null
null
UTF-8
C++
false
false
2,691
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'digitaldiary.h' ** ** Created: Mon Apr 16 04:25:31 2012 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../digitaldiary.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'digitaldiary.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_digitaldiary[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 14, 13, 13, 13, 0x08, 40, 13, 13, 13, 0x08, 66, 13, 13, 13, 0x08, 0 // eod }; static const char qt_meta_stringdata_digitaldiary[] = { "digitaldiary\0\0on_pushButton_3_clicked()\0" "on_pushButton_2_clicked()\0" "on_pushButton_clicked()\0" }; const QMetaObject digitaldiary::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_digitaldiary, qt_meta_data_digitaldiary, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &digitaldiary::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *digitaldiary::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *digitaldiary::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_digitaldiary)) return static_cast<void*>(const_cast< digitaldiary*>(this)); return QDialog::qt_metacast(_clname); } int digitaldiary::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: on_pushButton_3_clicked(); break; case 1: on_pushButton_2_clicked(); break; case 2: on_pushButton_clicked(); break; default: ; } _id -= 3; } return _id; } QT_END_MOC_NAMESPACE
9fc11d5c968dcf3aae8b2d1d374363350a495617
573445251e0b6ce115eaac7b7f8a593635cc7210
/native-osx/src/DeviceListener.cpp
40c7160a4156a44d3dda4201c453f7b744347dcb
[ "MIT" ]
permissive
CodeDistillery/myodaemon
d2592d1f9ea8ce7e9f359f120f992fdb930827a8
0db901ec9ca39fcf84eb88836c6f4477c8767f25
refs/heads/master
2020-02-26T13:48:38.881508
2014-11-21T16:45:41
2014-11-21T16:45:41
27,585,687
0
0
null
null
null
null
UTF-8
C++
false
false
10,025
cpp
#include <stdio.h> #include "DeviceListener.hpp" #include "Constants.h" void DeviceListener::toggleEulerHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) { NSDictionary *userInfoDictionary = (__bridge NSDictionary*)userInfo; int toggleEulerValue = (int)[[userInfoDictionary objectForKey:@"toggleEuler"] integerValue]; (static_cast<DeviceListener *>(observer))->toggleEuler(toggleEulerValue); } DeviceListener::DeviceListener() { removeDataAfterSend = FALSE; isCalculatingEuler = TRUE; wrapper = [[NSMutableDictionary alloc] init]; frame = [[NSMutableDictionary alloc] init]; lastTime = clock(); // Listen for notifications from Settings CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), this, DeviceListener::toggleEulerHandler, (CFStringRef)kToggleEuler, NULL, CFNotificationSuspensionBehaviorDeliverImmediately); // Start a thread to run the processing loop processMessagesThread = thread((bind(&DataHandler::process_messages,&server))); // Run the asio loop in a separate thread dataHandlerThread = thread((bind(&DataHandler::run,&server))); } DeviceListener::~DeviceListener(){ CFNotificationCenterRemoveEveryObserver(CFNotificationCenterGetLocalCenter(), this); } /// Called when a Myo has been paired. void DeviceListener::onPair(myo::Myo *myo, uint64_t timestamp) { NSLog(@"onPair"); NSDictionary *eventDictionary = [[NSMutableDictionary alloc] init]; [eventDictionary setValue:@"onPair" forKey:@"type"]; [frame setValue:eventDictionary forKey:@"event"]; sendData(); } /// Called when a Myo has been un-paired. void DeviceListener::onUnpair(myo::Myo *myo, uint64_t timestamp) { NSLog(@"onUnpair"); NSDictionary *eventDictionary = [[NSMutableDictionary alloc] init]; [eventDictionary setValue:@"onUnpair" forKey:@"type"]; [frame setValue:eventDictionary forKey:@"event"]; sendData(); } /// Called when a paired Myo has been connected. void DeviceListener::onConnect(myo::Myo *myo, uint64_t timestamp) { NSLog(@"onConnect"); NSDictionary *eventDictionary = [[NSMutableDictionary alloc] init]; [eventDictionary setValue:@"onConnect" forKey:@"type"]; [frame setValue:eventDictionary forKey:@"event"]; sendData(); } /// Called when a paired Myo has been disconnected. void DeviceListener::onDisconnect(myo::Myo *myo, uint64_t timestamp) { NSLog(@"onDisconnect"); NSDictionary *eventDictionary = [[NSMutableDictionary alloc] init]; [eventDictionary setValue:@"onDisconnect" forKey:@"type"]; [frame setValue:eventDictionary forKey:@"event"]; sendData(); } /// Called when a paired Myo recognizes that it is on an arm. void DeviceListener::onArmRecognized(myo::Myo* myo, uint64_t timestamp, myo::Arm arm, myo::XDirection xDirection) { NSLog(@"onArmRecognized"); NSString* whichArm; switch (arm) { case myo::armLeft: whichArm = [NSString stringWithFormat:@"armLeft"]; break; case myo::armRight: whichArm = [NSString stringWithFormat:@"armRight"]; break; case myo::armUnknown: whichArm = [NSString stringWithFormat:@"armUnknown"]; break; default: break; } NSString* whichDirection; switch (xDirection) { case myo::xDirectionTowardWrist: whichDirection = [NSString stringWithFormat:@"xDirectionTowardWrist"]; break; case myo::xDirectionTowardElbow: whichDirection = [NSString stringWithFormat:@"xDirectionTowardElbow"]; break; case myo::xDirectionUnknown: whichDirection = [NSString stringWithFormat:@"xDirectionUnknown"]; break; default: break; } NSDictionary *eventDictionary = [[NSMutableDictionary alloc] init]; [eventDictionary setValue:@"onArmRecognized" forKey:@"type"]; [eventDictionary setValue:whichArm forKey:@"arm"]; [eventDictionary setValue:whichDirection forKey:@"xDirection"]; [frame setValue:eventDictionary forKey:@"event"]; sendData(); } /// Called when a paired Myo is moved or removed from the arm. void DeviceListener::onArmLost(myo::Myo* myo, uint64_t timestamp) { NSLog(@"onArmLost"); NSDictionary *eventDictionary = [[NSMutableDictionary alloc] init]; [eventDictionary setValue:@"onArmLost" forKey:@"type"]; [frame setValue:eventDictionary forKey:@"event"]; sendData(); } /// Called when a paired Myo has provided a new pose. void DeviceListener::onPose(myo::Myo *myo, uint64_t timestamp, myo::Pose pose) { NSDictionary *poseDictionary = [[NSMutableDictionary alloc] init]; NSNumber *poseType = @(pose.type()); [poseDictionary setValue:poseType forKey:@"type"]; [frame setValue:poseDictionary forKey:@"pose"]; sendData(); } /// Called when a paired Myo has provided new orientation data. void DeviceListener::onOrientationData(myo::Myo *myo, uint64_t timestamp, const myo::Quaternion<float>& rotation) { NSArray *rotationArray = [[NSArray alloc] initWithObjects:@(rotation.x()), @(rotation.y()), @(rotation.z()), @(rotation.w()), nil]; [frame setValue:rotationArray forKey:@"rotation"]; if (isCalculatingEuler) { using std::atan2; using std::asin; using std::sqrt; // Calculate Euler angles (roll, pitch, and yaw) from the unit quaternion. float roll = atan2(2.0f * (rotation.w() * rotation.x() + rotation.y() * rotation.z()), 1.0f - 2.0f * (rotation.x() * rotation.x() + rotation.y() * rotation.y())); float pitch = asin(2.0f * (rotation.w() * rotation.y() - rotation.z() * rotation.x())); float yaw = atan2(2.0f * (rotation.w() * rotation.z() + rotation.x() * rotation.y()), 1.0f - 2.0f * (rotation.y() * rotation.y() + rotation.z() * rotation.z())); NSMutableDictionary *eulerDictionary = [[NSMutableDictionary alloc] init]; [eulerDictionary setValue:@(roll) forKey:@"roll"]; [eulerDictionary setValue:@(pitch) forKey:@"pitch"]; [eulerDictionary setValue:@(yaw) forKey:@"yaw"]; [frame setValue:eulerDictionary forKey:@"euler"]; } [frame setValue:@(timestamp) forKey:@"timestamp"]; sendData(FALSE); } /// Called when a paired Myo has provided new accelerometer data in units of g. void DeviceListener::onAccelerometerData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3<float>& accel) { NSArray *accelArray = [[NSArray alloc] initWithObjects:@(accel.x()), @(accel.y()), @(accel.z()), nil]; [frame setValue:accelArray forKey:@"accel"]; } /// Called when a paired Myo has provided new gyroscope data in units of deg/s. void DeviceListener::onGyroscopeData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3<float>& gyro) { NSArray *gyroArray = [[NSArray alloc] initWithObjects:@(gyro.x()), @(gyro.y()), @(gyro.z()), nil]; [frame setValue:gyroArray forKey:@"gyro"]; } /// Called when a paired Myo has provided a new RSSI value. void DeviceListener::onRssi(myo::Myo *myo, uint64_t timestamp, int8_t rssi) { NSNumber *rssiValue = @(rssi); [frame setValue:rssiValue forKey:@"rssi"]; CFStringRef rssiString = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), rssi); CFDictionaryKeyCallBacks keyCallbacks = {0, NULL, NULL, CFCopyDescription, CFEqual, NULL}; CFDictionaryValueCallBacks valueCallbacks = {0, NULL, NULL, CFCopyDescription, CFEqual}; CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &keyCallbacks, &valueCallbacks); CFDictionaryAddValue(dictionary, CFSTR("rssi"), rssiString); CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(), (CFStringRef)kMyoRSSI, NULL, dictionary, TRUE); CFRelease(rssiString); CFRelease(dictionary); sendData(); } void DeviceListener::sendData(bool removeData) { // Calculate framerate if (frameId % 50 == 0) { float delta = (clock() - lastTime) / (float) CLOCKS_PER_SEC; lastTime = clock(); float frameRate = 50 / delta; CFStringRef frameRateString = CFStringCreateWithFormat(NULL, NULL, CFSTR("%.2f"), frameRate); CFDictionaryKeyCallBacks keyCallbacks = {0, NULL, NULL, CFCopyDescription, CFEqual, NULL}; CFDictionaryValueCallBacks valueCallbacks = {0, NULL, NULL, CFCopyDescription, CFEqual}; CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &keyCallbacks, &valueCallbacks); CFDictionaryAddValue(dictionary, CFSTR("fps"), frameRateString); CFNotificationCenterPostNotification(CFNotificationCenterGetLocalCenter(), (CFStringRef)kMyoFPS, NULL, dictionary, TRUE); CFRelease(frameRateString); CFRelease(dictionary); } NSNumber *frameIDNumber = @(frameId); [frame setValue:frameIDNumber forKey:@"id"]; [wrapper setValue:frame forKey:@"frame"]; // Encode JSON NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:wrapper options:NSJSONWritingPrettyPrinted error:&error]; if (!jsonData) { NSLog(@"Error in JSON: %@", error); } else { NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; server.send_message(std::string([jsonString UTF8String])); } if(removeData || removeDataAfterSend) { removeDataAfterSend = FALSE; [frame removeAllObjects]; } frameId++; } void DeviceListener::toggleEuler(int toggleEulerValue) { std::cout << "MyoWebsocket::toggleEuler: " << toggleEulerValue << std::endl; switch (toggleEulerValue) { case 0: isCalculatingEuler = FALSE; break; case 1: isCalculatingEuler = TRUE; break; default: break; } }
2ae9bc8bf1094c6851e7f6a7d36d80d8a3d48a14
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-qt5/generated/client/OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties.h
7a8dcf48b73ee466d1724c3ad5d999d0d0367f7d
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
1,831
h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties.h * * */ #ifndef OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties_H_ #define OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties_H_ #include <QJsonObject> #include "OAIOAIConfigNodePropertyInteger.h" #include "OAIObject.h" namespace OpenAPI { class OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties: public OAIObject { public: OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties(); OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties(QString json); ~OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties(); void init(); void cleanup(); QString asJson () override; QJsonObject asJsonObject() override; void fromJsonObject(QJsonObject json) override; OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties* fromJson(QString jsonString) override; OAIConfigNodePropertyInteger* getReportFetchDelay(); void setReportFetchDelay(OAIConfigNodePropertyInteger* report_fetch_delay); virtual bool isSet() override; private: OAIConfigNodePropertyInteger* report_fetch_delay; bool m_report_fetch_delay_isSet; }; } #endif /* OAIComAdobeCqSocialReportingAnalyticsServicesImplAnalyticsReportMProperties_H_ */
a352c36a0c7a2311a7b5c52482502e7d60a22baa
6aef4e0826561f5b4c69e8233de301db7fb12b02
/protobuf_prototype/cpp/src/Commands.cpp
a5fe240d250008e8bfb91fe4ebec011f7c3d05d6
[]
no_license
PivotalSarge/experiments
daa40249b5e989510ed5af1e39e20198c5260a97
f0d3af05bb3768a2de58b43bbb99ebf7a5d3f1c5
refs/heads/master
2020-06-14T21:05:52.236753
2017-12-12T21:01:00
2017-12-12T21:01:00
75,339,248
0
0
null
null
null
null
UTF-8
C++
false
false
3,411
cpp
#include "Commands.hpp" #include <sstream> #include "Delay.hpp" namespace { const bool debugLogging = (::getenv("DEBUG_LOGGING") && 0 == ::strcmp(::getenv("DEBUG_LOGGING"), "true")); } // namespace Commands::Commands() { // NOP } Commands::~Commands() { // NOP } const std::string &Commands::operator*() const { if (!_commands.empty()) { return _commands.front(); } static const std::string none; return none; } Commands &Commands::operator++() { if (!_commands.empty()) { _commands.pop_front(); } return *this; } void Commands::runCommandLoop(Client &client) { Delay delay; while (*this) { if (delay) { if (debugLogging) { std::cout << "Sleeping " << delay.seconds() << " seconds..." << std::endl; } delay(); } delay.reset(); const std::string &command(*(*this)); if (command == "quit") { return; } else if (command == "sleep") { delay.parse(*(++(*this))); } else if (command == "put") { const std::string region(*(++(*this))); const std::string key(*(++(*this))); const std::string value(*(++(*this))); if (!region.empty() && !key.empty()) { std::cout << std::endl; std::cout << key << "=" << value << std::endl; client.put(region, key, value); delay.randomize(); } } else if (command == "get") { const std::string region(*(++(*this))); const std::string key(*(++(*this))); if (!region.empty() && !key.empty()) { const std::string value(client.get(region, key)); delay.randomize(); std::cout << std::endl; std::cout << key << "=" << value << std::endl; } } else if (command == "invalidate") { const std::string region(*(++(*this))); const std::string key(*(++(*this))); if (!region.empty() && !key.empty()) { client.invalidate(region, key); delay.randomize(); } } else if (command == "destroy") { const std::string region(*(++(*this))); const std::string key(*(++(*this))); if (!region.empty() && !key.empty()) { client.destroy(region, key); delay.randomize(); } } else { if (command != "help") { std::cerr << "Unknown command: " << command << std::endl; } std::cout << "Valid commands:" << std::endl; std::cout << "\thelp -- print this help message" << std::endl; std::cout << "\tquit -- exit" << std::endl; std::cout << "\tsleep <duration> -- wait for the duration" << std::endl; std::cout << "\tget <region> <key> -- get the value for a key" << std::endl; std::cout << "\tput <region> <key> <value> -- put the value for a key" << std::endl; std::cout << "\tinvalidate <region> <key> -- invalidate the key" << std::endl; std::cout << "\tdestroy <region> <key> -- destroy the key" << std::endl; } ++(*this); } } void Commands::parseLine(std::istream &is) { std::string line; if (std::getline(is, line)) { std::istringstream iss(line); while (iss) { std::string command; iss >> command; if (!command.empty()) { _commands.push_back(command); } } } }
38dd47a62c3ef66dba52cc0f17bb8fb61c4696dd
03565927bae4b336625dfefeb714898fcfccda79
/test/Main.cpp
c8f18ccbbd97f10743442ebf67fd210555e427a0
[ "MIT" ]
permissive
stjordanis/spool
8a0a2328f2b221003958cec44813489752845215
5ff994ce1f626ef52e4bd2422ca76e2424d32bca
refs/heads/master
2020-05-30T09:06:36.799880
2019-05-30T06:09:28
2019-05-30T08:26:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
893
cpp
#include <spool.h> #include "Test.hpp" #include <cstdio> static size_t test_count = 0; static size_t test_passes = 0; void test(bool condition, const char* cond_str, const char* file, int line) { ++test_count; if (condition) { ++test_passes; } else { printf("[%s:%d] Test failed: %s\n", file, line, cond_str); } } extern const char* tu1_foo; extern const char* tu1_bar; extern const char* tu1_zoo; extern const char* lib1_x; extern const char* lib2_x; int main(int argc, char** argv) { const char* foo = SP("super"); const char* bar = SP("super"); const char* zoo = SP("duper"); TEST(foo == bar); TEST(foo != zoo); TEST(bar == tu1_foo); TEST(zoo == tu1_zoo); TEST(tu1_bar == foo); TEST(lib1_x == SP("x")); TEST(lib1_x == lib2_x); printf("%d out of %d tests passed.\n", test_passes, test_count); }
17f46a20b910e5325d3654c88fc3b4efbcc7dae2
50a8a3fe0fdffb4141b12b0ee73363f218efc222
/src/nas/ies/EPS_NAS_Security_Algorithms.cpp
0de17a62c028a741d1a635481d06f862a587d042
[]
no_license
dukl/fake_gnb
f89972ad50c6a50e620fe8590cece7200d2560da
b6f772e8fb82c61a9949a4f4c317637d97c36fb6
refs/heads/master
2022-12-07T21:55:26.285263
2020-08-27T07:11:37
2020-08-27T07:11:37
290,703,480
1
0
null
null
null
null
UTF-8
C++
false
false
1,923
cpp
#include "EPS_NAS_Security_Algorithms.hpp" #include "logger.hpp" #include <iostream> using namespace nas; using namespace std; EPS_NAS_Security_Algorithms::EPS_NAS_Security_Algorithms() {} EPS_NAS_Security_Algorithms::~EPS_NAS_Security_Algorithms() {} EPS_NAS_Security_Algorithms::EPS_NAS_Security_Algorithms(uint8_t iei, uint8_t ciphering, uint8_t integrity_protection) { _iei = iei; CIPHERING = ciphering; INTEGRITY_PROTECTION = integrity_protection; } void EPS_NAS_Security_Algorithms::setCIPHERING(uint8_t value) { CIPHERING = value; } void EPS_NAS_Security_Algorithms::setINTEGRITY_PROTECTION(uint8_t value) { INTEGRITY_PROTECTION = value; } uint8_t EPS_NAS_Security_Algorithms::getCIPHERING() { return CIPHERING; } uint8_t EPS_NAS_Security_Algorithms::getINTEGRITY_PROTECTION() { return INTEGRITY_PROTECTION; } int EPS_NAS_Security_Algorithms::encode2buffer(uint8_t *buf, int len) { Logger::nas_mm().debug("encoding EPS_NAS_Security_Algorithms iei(0x%x)", _iei); int encoded_size = 0; if (len < 2) { Logger::nas_mm().error("len is less than 2"); return -1; } else { *(buf + encoded_size) = _iei; encoded_size++; *(buf + encoded_size) = ((CIPHERING&0x07)<<4)|(INTEGRITY_PROTECTION&0x07); encoded_size++; Logger::nas_mm().debug("encoded EPS_NAS_Security_Algorithms IE 0x%x", *buf); } return encoded_size; } int EPS_NAS_Security_Algorithms::decodefrombuffer(uint8_t *buf, int len, bool is_option) { Logger::nas_mm().debug("decoding EPS_NAS_Security_Algorithms IE"); if (len < 2) { Logger::nas_mm().error("len is less than 2"); return 0; } else { int decoded_size = 0; decoded_size++; CIPHERING = (*(buf+decoded_size)&0x70)>>4; INTEGRITY_PROTECTION = *(buf+decoded_size) & 0x07; decoded_size++; Logger::nas_mm().debug("decoded NAS_Security_Algorithms len 1 octet,CIPHERING=0x%x,INTEGRITY_PROTECTION=0x%x", CIPHERING, INTEGRITY_PROTECTION); return decoded_size; } }
3a6e5f1df99ea0cdaf6b9279fd156c66fa057419
28eb24d30828981a0034fbf6c3f9e54a466e1da6
/ros_navigation/move_base/include/move_base/move_base.h
6d51d4440a853f20f7936202a546d348955caf2b
[]
no_license
jianming1481/Navigation
f871f93a37dd05bed11e139eed7c6308fe0e31e8
277b3864eb41e38cac136c4a563d3406ce00fdfa
refs/heads/master
2021-01-20T10:23:54.638649
2017-05-05T07:45:53
2017-05-05T07:45:53
90,350,685
0
0
null
null
null
null
UTF-8
C++
false
false
8,575
h
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * 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 Willow Garage 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. * * Author: Eitan Marder-Eppstein *********************************************************************/ #ifndef NAV_MOVE_BASE_ACTION_H_ #define NAV_MOVE_BASE_ACTION_H_ #include <vector> #include <string> #include <ros/ros.h> #include <actionlib/server/simple_action_server.h> #include <move_base_msgs/MoveBaseAction.h> #include <nav_core/base_local_planner.h> #include <nav_core/base_global_planner.h> #include <nav_core/recovery_behavior.h> #include <geometry_msgs/PoseStamped.h> #include <costmap_2d/costmap_2d_ros.h> #include <costmap_2d/costmap_2d.h> #include <nav_msgs/GetPlan.h> #include <pluginlib/class_loader.h> #include <std_srvs/Empty.h> #include <dynamic_reconfigure/server.h> #include "move_base/MoveBaseConfig.h" #include <stdio.h> namespace move_base { //typedefs to help us out with the action server so that we don't hace to type so much typedef actionlib::SimpleActionServer<move_base_msgs::MoveBaseAction> MoveBaseActionServer; enum MoveBaseState { PLANNING, CONTROLLING, CLEARING }; enum RecoveryTrigger { PLANNING_R, CONTROLLING_R, OSCILLATION_R }; /** * @class MoveBase * @brief A class that uses the actionlib::ActionServer interface that moves the robot base to a goal location. */ class MoveBase { public: /** * @brief Constructor for the actions * @param name The name of the action * @param tf A reference to a TransformListener */ MoveBase(tf::TransformListener& tf); /** * @brief Destructor - Cleans up */ virtual ~MoveBase(); /** * @brief Performs a control cycle * @param goal A reference to the goal to pursue * @param global_plan A reference to the global plan being used * @return True if processing of the goal is done, false otherwise */ bool executeCycle(geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& global_plan); private: /** * @brief A service call that clears the costmaps of obstacles * @param req The service request * @param resp The service response * @return True if the service call succeeds, false otherwise */ bool clearCostmapsService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp); /** * @brief A service call that can be made when the action is inactive that will return a plan * @param req The goal request * @param resp The plan request * @return True if planning succeeded, false otherwise */ bool planService(nav_msgs::GetPlan::Request &req, nav_msgs::GetPlan::Response &resp); /** * @brief Make a new global plan * @param goal The goal to plan to * @param plan Will be filled in with the plan made by the planner * @return True if planning succeeds, false otherwise */ bool makePlan(const geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& plan); /** * @brief Load the recovery behaviors for the navigation stack from the parameter server * @param node The ros::NodeHandle to be used for loading parameters * @return True if the recovery behaviors were loaded successfully, false otherwise */ bool loadRecoveryBehaviors(ros::NodeHandle node); /** * @brief Loads the default recovery behaviors for the navigation stack */ void loadDefaultRecoveryBehaviors(); /** * @brief Clears obstacles within a window around the robot * @param size_x The x size of the window * @param size_y The y size of the window */ void clearCostmapWindows(double size_x, double size_y); /** * @brief Publishes a velocity command of zero to the base */ void publishZeroVelocity(); /** * @brief Reset the state of the move_base action and send a zero velocity command to the base */ void resetState(); void goalCB(const geometry_msgs::PoseStamped::ConstPtr& goal); void planThread(); void executeCb(const move_base_msgs::MoveBaseGoalConstPtr& move_base_goal); bool isQuaternionValid(const geometry_msgs::Quaternion& q); double distance(const geometry_msgs::PoseStamped& p1, const geometry_msgs::PoseStamped& p2); geometry_msgs::PoseStamped goalToGlobalFrame(const geometry_msgs::PoseStamped& goal_pose_msg); /** * @brief This is used to wake the planner at periodic intervals. */ void wakePlanner(const ros::TimerEvent& event); tf::TransformListener& tf_; MoveBaseActionServer* as_; boost::shared_ptr<nav_core::BaseLocalPlanner> tc_; costmap_2d::Costmap2DROS* planner_costmap_ros_, *controller_costmap_ros_; boost::shared_ptr<nav_core::BaseGlobalPlanner> planner_; std::string robot_base_frame_, global_frame_; std::vector<boost::shared_ptr<nav_core::RecoveryBehavior> > recovery_behaviors_; unsigned int recovery_index_; tf::Stamped<tf::Pose> global_pose_; double planner_frequency_, controller_frequency_, inscribed_radius_, circumscribed_radius_; double planner_patience_, controller_patience_; double conservative_reset_dist_, clearing_radius_; ros::Publisher current_goal_pub_, vel_pub_, action_goal_pub_; ros::Subscriber goal_sub_; ros::ServiceServer make_plan_srv_, clear_costmaps_srv_; bool shutdown_costmaps_, clearing_rotation_allowed_, recovery_behavior_enabled_; double oscillation_timeout_, oscillation_distance_; MoveBaseState state_; RecoveryTrigger recovery_trigger_; ros::Time last_valid_plan_, last_valid_control_, last_oscillation_reset_; geometry_msgs::PoseStamped oscillation_pose_; pluginlib::ClassLoader<nav_core::BaseGlobalPlanner> bgp_loader_; pluginlib::ClassLoader<nav_core::BaseLocalPlanner> blp_loader_; pluginlib::ClassLoader<nav_core::RecoveryBehavior> recovery_loader_; //set up plan triple buffer std::vector<geometry_msgs::PoseStamped>* planner_plan_; std::vector<geometry_msgs::PoseStamped>* latest_plan_; std::vector<geometry_msgs::PoseStamped>* controller_plan_; //set up the planner's thread bool runPlanner_; boost::mutex planner_mutex_; boost::condition_variable planner_cond_; geometry_msgs::PoseStamped planner_goal_; boost::thread* planner_thread_; boost::recursive_mutex configuration_mutex_; dynamic_reconfigure::Server<move_base::MoveBaseConfig> *dsrv_; void reconfigureCB(move_base::MoveBaseConfig &config, uint32_t level); move_base::MoveBaseConfig last_config_; move_base::MoveBaseConfig default_config_; bool setup_, p_freq_change_, c_freq_change_; bool new_global_plan_; }; }; #endif
44ae2074bbb261d4e6f6cc7feac5cfbb07b58486
255e355f120b528b20eb7ecf115df749a82b0fab
/src_code/RobotModel.cpp
2fc7a72469dc15e89a9d8bd5c225bb918f559eb3
[]
no_license
KhoiNguyen1304/RobotShopGUI
06f0d5d67858db48743b1101d5bc4260b0562fc1
0cabf8b732530322aa53257020daae24b00c98c2
refs/heads/master
2020-07-05T20:15:37.482757
2016-11-22T05:49:27
2016-11-22T05:49:27
73,982,604
0
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
#include "RobotPart.h" #include "RobotModel.h" #include <string> #include <sstream> using namespace std; RobotModel::RobotModel(std::string kname, int kmodelNumber, double kprice) : name(kname), modelNumber(kmodelNumber), price(kprice) {} std::string RobotModel::GetName() { return name; } int RobotModel::GetModelNumber() { return modelNumber; } double RobotModel::GetPrice() { return price; } std::string RobotModel::print() { ostringstream of; of << "Model's name: " << GetName() << endl << "Model's number: " << GetModelNumber() << endl << "Model's price: " << GetPrice() << endl; return of.str(); }
8fb422fa0a7b682fc47e41b04a29b712211388ae
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_new_hunk_571.cpp
7f356e3563c5030bb309210ba0f84e4c9a28791b
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
891
cpp
/* build request prefix and append it to a given MemBuf; * return the length of the prefix */ mb_size_t HttpStateData::buildRequestPrefix(MemBuf * mb) { const int offset = mb->size; /* Uses a local httpver variable to print the HTTP/1.1 label * since the HttpRequest may have an older version label. * XXX: This could create protocol bugs as the headers sent and * flow control should all be based on the HttpRequest version * not the one we are sending. Needs checking. */ Http::ProtocolVersion httpver(1,1); const char * url; if (_peer && !_peer->options.originserver) url = urlCanonical(request); else url = request->urlpath.termedBuf(); mb->Printf("%s %s %s/%d.%d\r\n", RequestMethodStr(request->method), url && *url ? url : "/", AnyP::ProtocolType_str[httpver.protocol],
c9f841b3799eafe54d78a0054e45478d142530de
8cea1e902a1df07136b68199eb9b6fb16ffb38fa
/passenger.h
50f5ac63d062e27c59a37d9bb99e90c31d0ababa
[ "MIT" ]
permissive
robot-alien/airplane
0819ddccf604a84a5d90d20ebc1f0b7b435ac938
1fb5f192c8942a14696c239b40fdbbbef8280a62
refs/heads/main
2022-12-24T11:33:54.374433
2020-10-12T00:50:03
2020-10-12T00:50:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
373
h
//Passenger.h #include<string> #ifndef PASSENGER_H #define PASSENGER_H class Passenger{ private: std::string name,booking; public: Passenger(); Passenger(std::string name); Passenger(std::string name,std::string booking); std::string getName(); std::string getBooking(); void setName(std::string name); void setBooking(std::string booking); void printPassenger(); }; #endif
4bffa8b44487bdede48a0dd9dc7a5502f2b8d952
53abaa2c6535e6088a375d0e63f0fc1f174912bf
/Hackerrank/ssas.cpp
a86504d9a835db5562f4cb851b762546075fbcb7
[]
no_license
Cinereouss/OLP-ICPC
015130d074fbcf26b9227a68ca8c95149e4a97a6
87de30974838ca3328bc39b4478a12ade7c02092
refs/heads/master
2023-01-23T02:46:20.724053
2020-12-16T03:37:09
2020-12-16T03:37:09
319,627,957
1
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
#include <bits/stdc++.h> using namespace std; int n; bool ktra(int kt, int a[], int b[]){ for (int i = 0; i < kt; ++i){ if(a[kt-i]>=b[n-1-i]) return false; } return true; } main(){ freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int tmp; cin >> n; int a[n]; int b[n]; for(int i = 0; i < n; ++i){ cin >> a[i]; } sort(a, a+n); for(int i = 0; i < n; ++i){ cin >> b[i]; } sort(b, b+n); int left = 0; int right = n-1; int mid; while(left != right){ mid = (left+right)/2; if(ktra(mid, a, b)) left = mid+1; else right = mid-1; } cout << left; }
967498e5992d8988ba4f284d27bc5aafec735958
7734798606ff9c2a7810b445039e3f17a5da01e9
/armv6k/include/arm11_mpcore.h
a490e56196b79a650f6d4533773b8c69c0e3b8b3
[]
no_license
ufoderek/mvp
149a9cc58bd81895a82115830e8047e111fbf457
92f4d76dcf4ee02ba20a7794faa4f1b49030c3a9
refs/heads/master
2021-01-10T02:03:26.788801
2015-10-13T16:37:49
2015-10-13T16:38:03
43,765,523
3
1
null
null
null
null
UTF-8
C++
false
false
947
h
#ifndef _ARM11_MPCORE_H_ #define _ARM11_MPCORE_H_ #include <memory.h> #include <stdint.h> #include <systemc.h> #include <boost/shared_ptr.hpp> #include <armv6k.h> #include <gic2_dist.h> #include <gic2_cpu_if.h> class ARM11_MPCORE: public sc_module { public: sc_in_clk clk; sc_in_clk clk_slow; sc_in<bool> gic_irq_n[64]; sc_signal<bool> irq_n[4]; sc_signal<bool> virq_n[4]; SC_HAS_PROCESS(ARM11_MPCORE); ARM11_MPCORE(sc_module_name name, uint32_t addr, uint32_t second_addr, bool using_gdb, unsigned int gdb_port, unsigned int n_cores); ~ARM11_MPCORE(); boost::shared_ptr<mp_scu> scu; boost::shared_ptr<gic2_dist> gic_dist; boost::shared_ptr<gic2_cpu_if> gic_cpu_if; auto_ptr<ARMV6K> core0; auto_ptr<ARMV6K> core1; auto_ptr<ARMV6K> core2; auto_ptr<ARMV6K> core3; private: unsigned int n_cores; }; #endif
5782bbde09f68a22313e033023a5ed6596cd67c1
2e222de5e03b948e5692f0011b6e38aa6067551b
/av/media/libvoicecall/libwebrtc_neteq/src/system_wrappers/source/tick_util.cc
f5a608f307b335a04e2e14f14f6a3f0837cd8b1e
[]
no_license
cnping/Framework_V3
2df169e82aad2a898f4128f186ff88cc48249a4a
558bbd2175a46cb83c1a65af7146e8f5918f4bac
refs/heads/master
2021-01-12T20:48:36.792426
2015-11-13T01:22:52
2015-11-13T01:22:52
48,948,388
3
3
null
2016-01-03T14:23:08
2016-01-03T14:23:07
null
UTF-8
C++
false
false
3,361
cc
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "system_wrappers/interface/tick_util.h" #include <assert.h> namespace webrtc { bool TickTime::use_fake_clock_ = false; int64_t TickTime::fake_ticks_ = 0; void TickTime::UseFakeClock(int64_t start_millisecond) { use_fake_clock_ = true; fake_ticks_ = MillisecondsToTicks(start_millisecond); } void TickTime::AdvanceFakeClock(int64_t milliseconds) { assert(use_fake_clock_); fake_ticks_ += MillisecondsToTicks(milliseconds); } int64_t TickTime::QueryOsForTicks() { TickTime result; #if _WIN32 // TODO(wu): Remove QueryPerformanceCounter implementation. #ifdef USE_QUERY_PERFORMANCE_COUNTER // QueryPerformanceCounter returns the value from the TSC which is // incremented at the CPU frequency. The algorithm used requires // the CPU frequency to be constant. Technology like speed stepping // which has variable CPU frequency will therefore yield unpredictable, // incorrect time estimations. LARGE_INTEGER qpcnt; QueryPerformanceCounter(&qpcnt); result.ticks_ = qpcnt.QuadPart; #else static volatile LONG last_time_get_time = 0; static volatile int64_t num_wrap_time_get_time = 0; volatile LONG* last_time_get_time_ptr = &last_time_get_time; DWORD now = timeGetTime(); // Atomically update the last gotten time DWORD old = InterlockedExchange(last_time_get_time_ptr, now); if (now < old) { // If now is earlier than old, there may have been a race between // threads. // 0x0fffffff ~3.1 days, the code will not take that long to execute // so it must have been a wrap around. if (old > 0xf0000000 && now < 0x0fffffff) { num_wrap_time_get_time++; } } result.ticks_ = now + (num_wrap_time_get_time << 32); #endif #elif defined(WEBRTC_LINUX) || defined(WEBRTC_BSD) struct timespec ts; // TODO(wu): Remove CLOCK_REALTIME implementation. #ifdef WEBRTC_CLOCK_TYPE_REALTIME clock_gettime(CLOCK_REALTIME, &ts); #else clock_gettime(CLOCK_MONOTONIC, &ts); #endif result.ticks_ = 1000000000LL * static_cast<int64_t>(ts.tv_sec) + static_cast<int64_t>(ts.tv_nsec); #elif defined(WEBRTC_MAC) static mach_timebase_info_data_t timebase; if (timebase.denom == 0) { // Get the timebase if this is the first time we run. // Recommended by Apple's QA1398. kern_return_t retval = mach_timebase_info(&timebase); if (retval != KERN_SUCCESS) { // TODO(wu): Implement CHECK similar to chrome for all the platforms. // Then replace this with a CHECK(retval == KERN_SUCCESS); #ifndef WEBRTC_IOS asm("int3"); #else __builtin_trap(); #endif // WEBRTC_IOS } } // Use timebase to convert absolute time tick units into nanoseconds. result.ticks_ = mach_absolute_time() * timebase.numer / timebase.denom; #else struct timeval tv; gettimeofday(&tv, NULL); result.ticks_ = 1000000LL * static_cast<int64_t>(tv.tv_sec) + static_cast<int64_t>(tv.tv_usec); #endif return result.ticks_; } } // namespace webrtc
3c74b808e9a5ba4443180d0170448b867e8e47a8
fa4cb41ef68d83a52d72da75492b0475327e8670
/Debug/Generated Files/winrt/impl/Windows.UI.Notifications.1.h
1ac24052b3718adb2be376bbf02a7fc315a14b7e
[ "MIT" ]
permissive
zedpoirier/JupiterEngine
4ec595e886802dbc4c57b4d4503f91f9c48f8765
26afe2fede8e9fce0a48de3a768ef58839ae1565
refs/heads/master
2023-02-09T04:40:12.797148
2021-01-04T19:35:08
2021-01-04T19:35:08
298,377,326
1
0
null
null
null
null
UTF-8
C++
false
false
25,879
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.200921.6 #ifndef WINRT_Windows_UI_Notifications_1_H #define WINRT_Windows_UI_Notifications_1_H #include "winrt/impl/Windows.UI.Notifications.0.h" WINRT_EXPORT namespace winrt::Windows::UI::Notifications { struct __declspec(empty_bases) IAdaptiveNotificationContent : Windows::Foundation::IInspectable, impl::consume_t<IAdaptiveNotificationContent> { IAdaptiveNotificationContent(std::nullptr_t = nullptr) noexcept {} IAdaptiveNotificationContent(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IAdaptiveNotificationText : Windows::Foundation::IInspectable, impl::consume_t<IAdaptiveNotificationText> { IAdaptiveNotificationText(std::nullptr_t = nullptr) noexcept {} IAdaptiveNotificationText(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IBadgeNotification : Windows::Foundation::IInspectable, impl::consume_t<IBadgeNotification> { IBadgeNotification(std::nullptr_t = nullptr) noexcept {} IBadgeNotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IBadgeNotificationFactory : Windows::Foundation::IInspectable, impl::consume_t<IBadgeNotificationFactory> { IBadgeNotificationFactory(std::nullptr_t = nullptr) noexcept {} IBadgeNotificationFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IBadgeUpdateManagerForUser : Windows::Foundation::IInspectable, impl::consume_t<IBadgeUpdateManagerForUser> { IBadgeUpdateManagerForUser(std::nullptr_t = nullptr) noexcept {} IBadgeUpdateManagerForUser(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IBadgeUpdateManagerStatics : Windows::Foundation::IInspectable, impl::consume_t<IBadgeUpdateManagerStatics> { IBadgeUpdateManagerStatics(std::nullptr_t = nullptr) noexcept {} IBadgeUpdateManagerStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IBadgeUpdateManagerStatics2 : Windows::Foundation::IInspectable, impl::consume_t<IBadgeUpdateManagerStatics2> { IBadgeUpdateManagerStatics2(std::nullptr_t = nullptr) noexcept {} IBadgeUpdateManagerStatics2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IBadgeUpdater : Windows::Foundation::IInspectable, impl::consume_t<IBadgeUpdater> { IBadgeUpdater(std::nullptr_t = nullptr) noexcept {} IBadgeUpdater(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IKnownAdaptiveNotificationHintsStatics : Windows::Foundation::IInspectable, impl::consume_t<IKnownAdaptiveNotificationHintsStatics> { IKnownAdaptiveNotificationHintsStatics(std::nullptr_t = nullptr) noexcept {} IKnownAdaptiveNotificationHintsStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IKnownAdaptiveNotificationTextStylesStatics : Windows::Foundation::IInspectable, impl::consume_t<IKnownAdaptiveNotificationTextStylesStatics> { IKnownAdaptiveNotificationTextStylesStatics(std::nullptr_t = nullptr) noexcept {} IKnownAdaptiveNotificationTextStylesStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IKnownNotificationBindingsStatics : Windows::Foundation::IInspectable, impl::consume_t<IKnownNotificationBindingsStatics> { IKnownNotificationBindingsStatics(std::nullptr_t = nullptr) noexcept {} IKnownNotificationBindingsStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) INotification : Windows::Foundation::IInspectable, impl::consume_t<INotification> { INotification(std::nullptr_t = nullptr) noexcept {} INotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) INotificationBinding : Windows::Foundation::IInspectable, impl::consume_t<INotificationBinding> { INotificationBinding(std::nullptr_t = nullptr) noexcept {} INotificationBinding(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) INotificationData : Windows::Foundation::IInspectable, impl::consume_t<INotificationData> { INotificationData(std::nullptr_t = nullptr) noexcept {} INotificationData(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) INotificationDataFactory : Windows::Foundation::IInspectable, impl::consume_t<INotificationDataFactory> { INotificationDataFactory(std::nullptr_t = nullptr) noexcept {} INotificationDataFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) INotificationVisual : Windows::Foundation::IInspectable, impl::consume_t<INotificationVisual> { INotificationVisual(std::nullptr_t = nullptr) noexcept {} INotificationVisual(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IScheduledTileNotification : Windows::Foundation::IInspectable, impl::consume_t<IScheduledTileNotification> { IScheduledTileNotification(std::nullptr_t = nullptr) noexcept {} IScheduledTileNotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IScheduledTileNotificationFactory : Windows::Foundation::IInspectable, impl::consume_t<IScheduledTileNotificationFactory> { IScheduledTileNotificationFactory(std::nullptr_t = nullptr) noexcept {} IScheduledTileNotificationFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IScheduledToastNotification : Windows::Foundation::IInspectable, impl::consume_t<IScheduledToastNotification> { IScheduledToastNotification(std::nullptr_t = nullptr) noexcept {} IScheduledToastNotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IScheduledToastNotification2 : Windows::Foundation::IInspectable, impl::consume_t<IScheduledToastNotification2> { IScheduledToastNotification2(std::nullptr_t = nullptr) noexcept {} IScheduledToastNotification2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IScheduledToastNotification3 : Windows::Foundation::IInspectable, impl::consume_t<IScheduledToastNotification3> { IScheduledToastNotification3(std::nullptr_t = nullptr) noexcept {} IScheduledToastNotification3(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IScheduledToastNotification4 : Windows::Foundation::IInspectable, impl::consume_t<IScheduledToastNotification4> { IScheduledToastNotification4(std::nullptr_t = nullptr) noexcept {} IScheduledToastNotification4(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IScheduledToastNotificationFactory : Windows::Foundation::IInspectable, impl::consume_t<IScheduledToastNotificationFactory> { IScheduledToastNotificationFactory(std::nullptr_t = nullptr) noexcept {} IScheduledToastNotificationFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IScheduledToastNotificationShowingEventArgs : Windows::Foundation::IInspectable, impl::consume_t<IScheduledToastNotificationShowingEventArgs> { IScheduledToastNotificationShowingEventArgs(std::nullptr_t = nullptr) noexcept {} IScheduledToastNotificationShowingEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IShownTileNotification : Windows::Foundation::IInspectable, impl::consume_t<IShownTileNotification> { IShownTileNotification(std::nullptr_t = nullptr) noexcept {} IShownTileNotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileFlyoutNotification : Windows::Foundation::IInspectable, impl::consume_t<ITileFlyoutNotification> { ITileFlyoutNotification(std::nullptr_t = nullptr) noexcept {} ITileFlyoutNotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileFlyoutNotificationFactory : Windows::Foundation::IInspectable, impl::consume_t<ITileFlyoutNotificationFactory> { ITileFlyoutNotificationFactory(std::nullptr_t = nullptr) noexcept {} ITileFlyoutNotificationFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileFlyoutUpdateManagerStatics : Windows::Foundation::IInspectable, impl::consume_t<ITileFlyoutUpdateManagerStatics> { ITileFlyoutUpdateManagerStatics(std::nullptr_t = nullptr) noexcept {} ITileFlyoutUpdateManagerStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileFlyoutUpdater : Windows::Foundation::IInspectable, impl::consume_t<ITileFlyoutUpdater> { ITileFlyoutUpdater(std::nullptr_t = nullptr) noexcept {} ITileFlyoutUpdater(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileNotification : Windows::Foundation::IInspectable, impl::consume_t<ITileNotification> { ITileNotification(std::nullptr_t = nullptr) noexcept {} ITileNotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileNotificationFactory : Windows::Foundation::IInspectable, impl::consume_t<ITileNotificationFactory> { ITileNotificationFactory(std::nullptr_t = nullptr) noexcept {} ITileNotificationFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileUpdateManagerForUser : Windows::Foundation::IInspectable, impl::consume_t<ITileUpdateManagerForUser> { ITileUpdateManagerForUser(std::nullptr_t = nullptr) noexcept {} ITileUpdateManagerForUser(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileUpdateManagerStatics : Windows::Foundation::IInspectable, impl::consume_t<ITileUpdateManagerStatics> { ITileUpdateManagerStatics(std::nullptr_t = nullptr) noexcept {} ITileUpdateManagerStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileUpdateManagerStatics2 : Windows::Foundation::IInspectable, impl::consume_t<ITileUpdateManagerStatics2> { ITileUpdateManagerStatics2(std::nullptr_t = nullptr) noexcept {} ITileUpdateManagerStatics2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileUpdater : Windows::Foundation::IInspectable, impl::consume_t<ITileUpdater> { ITileUpdater(std::nullptr_t = nullptr) noexcept {} ITileUpdater(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITileUpdater2 : Windows::Foundation::IInspectable, impl::consume_t<ITileUpdater2> { ITileUpdater2(std::nullptr_t = nullptr) noexcept {} ITileUpdater2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastActivatedEventArgs : Windows::Foundation::IInspectable, impl::consume_t<IToastActivatedEventArgs> { IToastActivatedEventArgs(std::nullptr_t = nullptr) noexcept {} IToastActivatedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastActivatedEventArgs2 : Windows::Foundation::IInspectable, impl::consume_t<IToastActivatedEventArgs2> { IToastActivatedEventArgs2(std::nullptr_t = nullptr) noexcept {} IToastActivatedEventArgs2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastCollection : Windows::Foundation::IInspectable, impl::consume_t<IToastCollection> { IToastCollection(std::nullptr_t = nullptr) noexcept {} IToastCollection(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastCollectionFactory : Windows::Foundation::IInspectable, impl::consume_t<IToastCollectionFactory> { IToastCollectionFactory(std::nullptr_t = nullptr) noexcept {} IToastCollectionFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastCollectionManager : Windows::Foundation::IInspectable, impl::consume_t<IToastCollectionManager> { IToastCollectionManager(std::nullptr_t = nullptr) noexcept {} IToastCollectionManager(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastDismissedEventArgs : Windows::Foundation::IInspectable, impl::consume_t<IToastDismissedEventArgs> { IToastDismissedEventArgs(std::nullptr_t = nullptr) noexcept {} IToastDismissedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastFailedEventArgs : Windows::Foundation::IInspectable, impl::consume_t<IToastFailedEventArgs> { IToastFailedEventArgs(std::nullptr_t = nullptr) noexcept {} IToastFailedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotification : Windows::Foundation::IInspectable, impl::consume_t<IToastNotification> { IToastNotification(std::nullptr_t = nullptr) noexcept {} IToastNotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotification2 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotification2> { IToastNotification2(std::nullptr_t = nullptr) noexcept {} IToastNotification2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotification3 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotification3> { IToastNotification3(std::nullptr_t = nullptr) noexcept {} IToastNotification3(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotification4 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotification4> { IToastNotification4(std::nullptr_t = nullptr) noexcept {} IToastNotification4(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotification6 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotification6> { IToastNotification6(std::nullptr_t = nullptr) noexcept {} IToastNotification6(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationActionTriggerDetail : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationActionTriggerDetail> { IToastNotificationActionTriggerDetail(std::nullptr_t = nullptr) noexcept {} IToastNotificationActionTriggerDetail(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationFactory : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationFactory> { IToastNotificationFactory(std::nullptr_t = nullptr) noexcept {} IToastNotificationFactory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationHistory : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationHistory> { IToastNotificationHistory(std::nullptr_t = nullptr) noexcept {} IToastNotificationHistory(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationHistory2 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationHistory2> { IToastNotificationHistory2(std::nullptr_t = nullptr) noexcept {} IToastNotificationHistory2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationHistoryChangedTriggerDetail : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationHistoryChangedTriggerDetail> { IToastNotificationHistoryChangedTriggerDetail(std::nullptr_t = nullptr) noexcept {} IToastNotificationHistoryChangedTriggerDetail(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationHistoryChangedTriggerDetail2 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationHistoryChangedTriggerDetail2> { IToastNotificationHistoryChangedTriggerDetail2(std::nullptr_t = nullptr) noexcept {} IToastNotificationHistoryChangedTriggerDetail2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationManagerForUser : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationManagerForUser> { IToastNotificationManagerForUser(std::nullptr_t = nullptr) noexcept {} IToastNotificationManagerForUser(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationManagerForUser2 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationManagerForUser2> { IToastNotificationManagerForUser2(std::nullptr_t = nullptr) noexcept {} IToastNotificationManagerForUser2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationManagerStatics : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationManagerStatics> { IToastNotificationManagerStatics(std::nullptr_t = nullptr) noexcept {} IToastNotificationManagerStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationManagerStatics2 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationManagerStatics2> { IToastNotificationManagerStatics2(std::nullptr_t = nullptr) noexcept {} IToastNotificationManagerStatics2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationManagerStatics4 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationManagerStatics4> { IToastNotificationManagerStatics4(std::nullptr_t = nullptr) noexcept {} IToastNotificationManagerStatics4(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotificationManagerStatics5 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotificationManagerStatics5> { IToastNotificationManagerStatics5(std::nullptr_t = nullptr) noexcept {} IToastNotificationManagerStatics5(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotifier : Windows::Foundation::IInspectable, impl::consume_t<IToastNotifier> { IToastNotifier(std::nullptr_t = nullptr) noexcept {} IToastNotifier(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotifier2 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotifier2> { IToastNotifier2(std::nullptr_t = nullptr) noexcept {} IToastNotifier2(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IToastNotifier3 : Windows::Foundation::IInspectable, impl::consume_t<IToastNotifier3> { IToastNotifier3(std::nullptr_t = nullptr) noexcept {} IToastNotifier3(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IUserNotification : Windows::Foundation::IInspectable, impl::consume_t<IUserNotification> { IUserNotification(std::nullptr_t = nullptr) noexcept {} IUserNotification(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) IUserNotificationChangedEventArgs : Windows::Foundation::IInspectable, impl::consume_t<IUserNotificationChangedEventArgs> { IUserNotificationChangedEventArgs(std::nullptr_t = nullptr) noexcept {} IUserNotificationChangedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; } #endif
07e57983c4a796e1ff8e58ecb322c1e9a547eacf
b1842ae9b5fc773ca3d0b8b3f31862ef48464fc0
/src/test/key_tests.cpp
74f0829d6a4b0e01b5badb94d9ff31f98ba777da
[ "MIT" ]
permissive
ipocoin-dev/ipocoinCore
fb815a5b0a84e95631247f75158ee150debca815
b5f6b612d4f0a67bb5150ab1f980476e2eb68550
refs/heads/master
2020-12-30T17:10:53.756105
2017-05-12T07:56:25
2017-05-12T07:56:25
91,060,777
0
1
null
2017-09-03T08:30:02
2017-05-12T06:53:05
C++
UTF-8
C++
false
false
7,958
cpp
// Copyright (c) 2012-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 "key.h" #include "base58.h" #include "script/script.h" #include "uint256.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_ipo.h" #include <string> #include <vector> #include <boost/test/unit_test.hpp> using namespace std; static const string strSecret1 ("7qh6LYnLN2w2ntz2wwUhRUEgkQ2j8XB16FGw77ZRDZmC29bn7cD"); static const string strSecret2 ("7rve4MxeWFQHGbSYH6J2yaaZd3MBUqoDEwN6ZAZ6ZHmhTT4r3hW"); static const string strSecret1C ("XBuxZHH6TqXUuaSjbVTFR1DQSYecxCB9QA1Koyx5tTc3ddhqEnhm"); static const string strSecret2C ("XHMkZqWcY6Zkoq1j42NBijD8z5N5FtNy2Wx7WyAfXX2HZgxry8cr"); static const CBitcoinAddress addr1 ("Xywgfc872nn5CKtpATCoAjZCc4v96pJczy"); static const CBitcoinAddress addr2 ("XpmouUj9KKJ99ZuU331ZS1KqsboeFnLGgK"); static const CBitcoinAddress addr1C("XxV9h4Xmv6Pup8tVAQmH97K6grzvDwMG9F"); static const CBitcoinAddress addr2C("Xn7ZrYdExuk79Dm7CJCw7sfUWi2qWJSbRy"); static const string strAddressBad("Xta1praZQjyELweyMByXyiREw1ZRsjXzVP"); #ifdef KEY_TESTS_DUMPINFO void dumpKeyInfo(uint256 privkey) { CKey key; key.resize(32); memcpy(&secret[0], &privkey, 32); vector<unsigned char> sec; sec.resize(32); memcpy(&sec[0], &secret[0], 32); printf(" * secret (hex): %s\n", HexStr(sec).c_str()); for (int nCompressed=0; nCompressed<2; nCompressed++) { bool fCompressed = nCompressed == 1; printf(" * %s:\n", fCompressed ? "compressed" : "uncompressed"); CBitcoinSecret bsecret; bsecret.SetSecret(secret, fCompressed); printf(" * secret (base58): %s\n", bsecret.ToString().c_str()); CKey key; key.SetSecret(secret, fCompressed); vector<unsigned char> vchPubKey = key.GetPubKey(); printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str()); printf(" * address (base58): %s\n", CBitcoinAddress(vchPubKey).ToString().c_str()); } } #endif BOOST_FIXTURE_TEST_SUITE(key_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(key_test1) { CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; BOOST_CHECK( bsecret1.SetString (strSecret1)); BOOST_CHECK( bsecret2.SetString (strSecret2)); BOOST_CHECK( bsecret1C.SetString(strSecret1C)); BOOST_CHECK( bsecret2C.SetString(strSecret2C)); BOOST_CHECK(!baddress1.SetString(strAddressBad)); CKey key1 = bsecret1.GetKey(); BOOST_CHECK(key1.IsCompressed() == false); CKey key2 = bsecret2.GetKey(); BOOST_CHECK(key2.IsCompressed() == false); CKey key1C = bsecret1C.GetKey(); BOOST_CHECK(key1C.IsCompressed() == true); CKey key2C = bsecret2C.GetKey(); BOOST_CHECK(key2C.IsCompressed() == true); CPubKey pubkey1 = key1. GetPubKey(); CPubKey pubkey2 = key2. GetPubKey(); CPubKey pubkey1C = key1C.GetPubKey(); CPubKey pubkey2C = key2C.GetPubKey(); BOOST_CHECK(key1.VerifyPubKey(pubkey1)); BOOST_CHECK(!key1.VerifyPubKey(pubkey1C)); BOOST_CHECK(!key1.VerifyPubKey(pubkey2)); BOOST_CHECK(!key1.VerifyPubKey(pubkey2C)); BOOST_CHECK(!key1C.VerifyPubKey(pubkey1)); BOOST_CHECK(key1C.VerifyPubKey(pubkey1C)); BOOST_CHECK(!key1C.VerifyPubKey(pubkey2)); BOOST_CHECK(!key1C.VerifyPubKey(pubkey2C)); BOOST_CHECK(!key2.VerifyPubKey(pubkey1)); BOOST_CHECK(!key2.VerifyPubKey(pubkey1C)); BOOST_CHECK(key2.VerifyPubKey(pubkey2)); BOOST_CHECK(!key2.VerifyPubKey(pubkey2C)); BOOST_CHECK(!key2C.VerifyPubKey(pubkey1)); BOOST_CHECK(!key2C.VerifyPubKey(pubkey1C)); BOOST_CHECK(!key2C.VerifyPubKey(pubkey2)); BOOST_CHECK(key2C.VerifyPubKey(pubkey2C)); BOOST_CHECK(addr1.Get() == CTxDestination(pubkey1.GetID())); BOOST_CHECK(addr2.Get() == CTxDestination(pubkey2.GetID())); BOOST_CHECK(addr1C.Get() == CTxDestination(pubkey1C.GetID())); BOOST_CHECK(addr2C.Get() == CTxDestination(pubkey2C.GetID())); for (int n=0; n<16; n++) { string strMsg = strprintf("Very secret message %i: 11", n); uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); // normal signatures vector<unsigned char> sign1, sign2, sign1C, sign2C; BOOST_CHECK(key1.Sign (hashMsg, sign1)); BOOST_CHECK(key2.Sign (hashMsg, sign2)); BOOST_CHECK(key1C.Sign(hashMsg, sign1C)); BOOST_CHECK(key2C.Sign(hashMsg, sign2C)); BOOST_CHECK( pubkey1.Verify(hashMsg, sign1)); BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2)); BOOST_CHECK( pubkey1.Verify(hashMsg, sign1C)); BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2C)); BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1)); BOOST_CHECK( pubkey2.Verify(hashMsg, sign2)); BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1C)); BOOST_CHECK( pubkey2.Verify(hashMsg, sign2C)); BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1)); BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2)); BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1C)); BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2C)); BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1)); BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2)); BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1C)); BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2C)); // compact signatures (with key recovery) vector<unsigned char> csign1, csign2, csign1C, csign2C; BOOST_CHECK(key1.SignCompact (hashMsg, csign1)); BOOST_CHECK(key2.SignCompact (hashMsg, csign2)); BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C)); BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C)); CPubKey rkey1, rkey2, rkey1C, rkey2C; BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1)); BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2)); BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C)); BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C)); BOOST_CHECK(rkey1 == pubkey1); BOOST_CHECK(rkey2 == pubkey2); BOOST_CHECK(rkey1C == pubkey1C); BOOST_CHECK(rkey2C == pubkey2C); } // test deterministic signing std::vector<unsigned char> detsig, detsigc; string strMsg = "Very deterministic message"; uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); BOOST_CHECK(key1.Sign(hashMsg, detsig)); BOOST_CHECK(key1C.Sign(hashMsg, detsigc)); BOOST_CHECK(detsig == detsigc); BOOST_CHECK(detsig == ParseHex("304402205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d022014ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6")); BOOST_CHECK(key2.Sign(hashMsg, detsig)); BOOST_CHECK(key2C.Sign(hashMsg, detsigc)); BOOST_CHECK(detsig == detsigc); BOOST_CHECK(detsig == ParseHex("3044022052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd5022061d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d")); BOOST_CHECK(key1.SignCompact(hashMsg, detsig)); BOOST_CHECK(key1C.SignCompact(hashMsg, detsigc)); BOOST_CHECK(detsig == ParseHex("1c5dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6")); BOOST_CHECK(detsigc == ParseHex("205dbbddda71772d95ce91cd2d14b592cfbc1dd0aabd6a394b6c2d377bbe59d31d14ddda21494a4e221f0824f0b8b924c43fa43c0ad57dccdaa11f81a6bd4582f6")); BOOST_CHECK(key2.SignCompact(hashMsg, detsig)); BOOST_CHECK(key2C.SignCompact(hashMsg, detsigc)); BOOST_CHECK(detsig == ParseHex("1c52d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d")); BOOST_CHECK(detsigc == ParseHex("2052d8a32079c11e79db95af63bb9600c5b04f21a9ca33dc129c2bfa8ac9dc1cd561d8ae5e0f6c1a16bde3719c64c2fd70e404b6428ab9a69566962e8771b5944d")); } BOOST_AUTO_TEST_SUITE_END()
57ca6b0bea97cc1a472120a576b7a56cf78ef097
0743ab744d46e044900baa74984513c3e723357c
/ErrorReport.cpp
9cef1a9858436d3889bb730905cdc87bfbe821c4
[]
no_license
Watergun/DuckLife
5b94046188c131abbfaa20981788d9eb279662cc
f040c4ccea977becc3b55d50cf14b1955cf1f678
refs/heads/master
2022-10-16T17:52:55.636017
2014-05-13T22:31:01
2014-05-13T22:31:42
19,423,893
0
0
null
null
null
null
UTF-8
C++
false
false
935
cpp
#include "ErrorReport.h" int ERROR_REPORT::ErrorCount = 0; ERROR_REPORT::ERROR_REPORT() { ErrorCount = 0; } void ERROR_REPORT::ReportError(const char* ErrorMessage) { std::cout << "[ERROR] " << ErrorMessage << std::endl; ErrorCount++; } void ERROR_REPORT::ReportError(const char* FileName, const char* ClassName, const char* FunctionName, const char* Topic, const char* Additional) { std::cout << "[ERROR] REPORTED:" << std::endl; std::cout << "\tFile:\t\t" << FileName << std::endl; std::cout << "\tClass:\t\t" << ClassName << std::endl; std::cout << "\tFunction:\t" << FunctionName << std::endl; std::cout << "\tTopic:\t\t" << Topic << std::endl; if(Additional != NULL) std::cout << "\t*** " << Additional << " ***" << std::endl; std::cout << std::endl; ErrorCount++; } void ERROR_REPORT::ReportError(int ErrorCode) { std::cout << "[ERROR] Errorcode: " << ErrorCode << std::endl; ErrorCount++; }
acd22dbd7e8bb48e4558b4044106436570c1e50e
ec5c36c490ef35e2e2e81e0e1a9640baae34de97
/main.cpp
559b3b370c2e7bd2a7f25f53f887a98d9b4d0c46
[]
no_license
EC-TSJ/q2c
8c78a28e9d0c86d0114c615a0d6a94f412117d60
e1c43ac4c034ed37bfa0ba7dc909c9069788ea46
refs/heads/master
2020-12-23T14:11:08.814347
2020-01-30T09:16:50
2020-01-30T09:16:50
237,176,735
2
0
null
null
null
null
UTF-8
C++
false
false
7,547
cpp
/*********************************************************/ /* (%T% %S%), %J% <$A$> <$2.125$> */ /* (%W% 02/12/2019 ) Escrito */ /* (%X% 28/12/2019 ) Extendido extra en parámetros */ /* (%X% 29/12/2019 ) Impresión con qInfo */ /* (%M% 28/12/2019 ) */ /* <$Válido$> */ /*********************************************************/ #include "_defs.h" #include "main.h" #include "generic.h" #include <QCoreApplication> #include <iostream> #include <QDir> #include "Config.h" #include "project.h" #include "logs.h" #include "CommandParser.h" #if V__MFUNC__ # if V__PRINT__ # include <QtDebug> # else # ifdef Q_OS_WIN # include <stdio.h> # endif # endif #endif QT_BEGIN_NAMESPACE /** * @brief DetectInput. Scan for input file and return true if it finds some * @return true ó false */ bool DetectInput() { QDir d(QDir::currentPath()); QStringList files = d.entryList(); int x = 0; bool found = false; while (x < files.count()) { QString filename = files.at(x); filename.toLower(); if (filename.endsWith(".pro")) { if (found) { // more pro files exist, let's print error and quit Logs::errorLog("Hay varios fichero .pro en este directorio, necesitas proporcionar uno explícitamente "); Logs::errorLog("el proyecto que quieres convertir. mira --help para más."); return false; } found = true; Generic::Config::inputFile = files.at(x); } x++; } return found; } /** * @brief _parserInput. */ APX_SETTINGS(_parserInput, parser, params) { Q_UNUSED(parser) Generic::Config::inputFile = params.at(0); return 0; } /** * @brief _parserOutput */ APX_SETTINGS(_parserOutput, parser, params) { Q_UNUSED(parser) Generic::Config::outputFile = params.at(0); return 0; } /** * @brief _parserQt5 */ APX_SETTINGS(_parserQt5, parser, params) { Q_UNUSED(params) Q_UNUSED(parser) Generic::Config::only_qt5 = true; return 0; } /** * @brief _parserVerbosity */ APX_SETTINGS(_parserVerbosity, parser, params) { Q_UNUSED(params) Q_UNUSED(parser) Generic::Config::verbosity++; return 0; } /** * @brief _parserName */ APX_SETTINGS(_parserName, parser, params) { Q_UNUSED(params) Q_UNUSED(parser) Generic::Config::name = params.at(0); Generic::Config::mustName = true; return 0; } #if V__MFUNC__ APX_SETTINGS(_parserClown, parser, params) { Q_UNUSED(params) Q_UNUSED(parser) } void myFunction(bool f, QString sz, TP_Callback cb) { #if !V__PRINT__ fprintf(stdout, "%b | %s | %p\n",f, sz.toStdString().c_str(), cb); #else qInfo().noquote() << f << " | " << sz.toStdString().c_str() << " | " << cb << endl; #endif } #endif /** * @brief runQ2c. Ejecuta el programa * @param argc Nº de argumentos * @param argv. Argumentos * @return 0 */ int runQ2c(int argc, char *argv[]) { QCoreApplication::setApplicationName("q2c"); CommandParser *tp = new CommandParser(); tp->addOption('v', "verbose", "Incrementa verbosidad", "(Default off, 1er lugar)", 0, (TP_Callback)_parserVerbosity,VN); tp->addOption('o', "out", "Especifica fichero de salida", QString(), 1, (TP_Callback)_parserOutput, VN); tp->addOption('i', "in", "Especifica fichero de entrada", QString(), 1, (TP_Callback)_parserInput, VN); #if V__MFUNC__ tp->addOption('5', "qt5", "Soporta sólo Qt5", QString(), 0, (TP_Callback)_parserQt5, (TP_Callback)_parserClown); #else tp->addOption('5', "qt5", "Soporta sólo Qt5", QString(), 0, (TP_Callback)_parserQt5, VN); #endif tp->addOption('n', "name", "Nombre del proyecto", "(Default name)", 1, (TP_Callback)_parserName,VN); #if V__MFUNC__ tp->addPositional("Gilipollas", "lo que haga", QString(), VN, VN); tp->addPositional("Oculto", "lo que haga", QString(), VN, VN); tp->addPositional("eleven", "lo que haga", "(15, 20, 25. Default 20)", VN, VN); #endif if (!tp->parse(argc, argv)) { // Parameter require to exit (--help) etc delete tp; return 0; } #if V__MFUNC__ QStringList qsl; qsl.append(""); tp->runOption('5', qsl); tp->runOptionEx('5', qsl); tp->run(myFunction); bool f = tp->exist('v'); f = tp->exist("Gilipollas"); f = tp->exist("out"); #endif delete tp; // a) if ( (Generic::Config::mustName) && (Generic::Config::name == QSTRING()) ) { Logs::debugLog("Debe ser puesto nombre en la opción ' --name NAME '"); return 7; } // c) if (Generic::Config::inputFile == QSTRING()) { // user didn't provide any input file if (!DetectInput()) { return 2; } Logs::debugLog("Resuelto nombre de entrada a " + Generic::Config::inputFile); } // d) if (Generic::Config::outputFile == QSTRING()) { // user didn't provide output file name // we can simply reuse the original name if (!Generic::Config::inputFile.contains(".")) { Logs::errorLog("El fichero de entrada no pede ser convertido a fichero de salida, por favor proporciona fichero de salida"); return 3; } Generic::Config::outputFile = Generic::Config::inputFile.mid(0, Generic::Config::inputFile.indexOf(".")); if (Generic::Config::q2c) { Generic::Config::outputFile = "CMakeLists.txt"; } else { Generic::Config::outputFile += ".pro"; } Logs::debugLog("Resuelto nombre de salida a " + Generic::Config::outputFile); } // e) Load the project file QFile *file = new QFile(Generic::Config::inputFile); if (!file->open(QIODevice::ReadOnly)) { Logs::errorLog("Incapaz de leer: " + Generic::Config::inputFile); delete file; return 4; } // f) lee todo QString source = QString(file->readAll()); delete file; // g) Parsea el QMake Project *input = new Project(); if (!input->parseQMake( source )) { Logs::errorLog("Incapaz de parsear: " + Generic::Config::inputFile); return 5; } // h) file = new QFile(Generic::Config::outputFile); if (!file->open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { Logs::errorLog("Incapaz de abrir para escritura: " + Generic::Config::outputFile); delete file; return 6; } // i) escribe el CMake if (Generic::Config::q2c) { file->write(input->toCMake().toUtf8()); } delete file; delete input; return 0; } QT_END_NAMESPACE #if V__MHANDLER__ static const QtMessageHandler QT_DEFAULT_MESSAGE_HANDLER = qInstallMessageHandler(0); void myCustomMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { // Handle the messages! QString txt; switch (type) { case QtDebugMsg: txt = QString("Debug: %1").arg(msg); break; case QtWarningMsg: txt = QString("Warning: %1").arg(msg); break; case QtCriticalMsg: txt = QString("Critical: %1").arg(msg); break; case QtFatalMsg: txt = QString("Fatal: %1").arg(msg); break; case QtInfoMsg: for(QChar x: msg) if(x == "\"") continue; else txt = txt + x; } //msg = txt; // Call the default handler. (*QT_DEFAULT_MESSAGE_HANDLER)(type, context, txt); } #endif /** * @brief main.Programa * @param argc. Nº de argumentos * @param argv. Argumentos * @return 0 ó 1 */ int main(int argc, char *argv[]) { #if V__MHANDLER__ qInstallMessageHandler(myCustomMessageHandler); #endif return QT_PREPEND_NAMESPACE(runQ2c)(argc, argv); }
ff2b52bcfb169bb866b66d8c1211b7ae85f6c39b
95228129a4b71bca47c5970e38f7a7e4bb802eb8
/fft.hpp
686e4270b25c0e3da7ce1a7865b1cc13110b7a44
[]
no_license
AntoinePlumerault/Pitch_Detection_Cpp
cddb95cdd26aa636b4b7557a92a3c73375549063
493052247533a8e9e062acaa032d8e304b700d75
refs/heads/master
2021-08-23T02:45:39.799083
2017-12-02T17:07:08
2017-12-02T17:07:08
108,756,323
0
0
null
null
null
null
UTF-8
C++
false
false
266
hpp
#ifndef FFT_HPP #define FFT_HPP #include <complex> #include <math.h> #include <vector> #include <iostream> #define PI 3.14159265359 typedef std::complex<double> Complex; void separate(Complex *X, const size_t N); void fft(Complex *X, const size_t N); #endif
9c505c101c4880e12e41bf6a370abc17953b6982
d9eba5307a0da1c82413f5ecb5e5aa7482a3b975
/Emoogle Balance 12279/main.cpp
5f347fbb11bc200d292a5c2891f1104fa5fa6509
[]
no_license
eugenioLeal/MyNetBeansProjects
3d1ad72362dff01aa162d1138ab9d5b00348666a
e58e9955a90207e853cae17077d73f63f39a475f
refs/heads/master
2021-01-23T08:22:01.145355
2018-09-13T03:00:48
2018-09-13T03:00:48
80,540,601
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
/* * File: main.cpp * Author: eugenioLeal * * Created on 24 de febrero de 2017, 21:32 */ #include <bits/stdc++.h> using namespace std; int main(int argc, char** argv) { int n, e, count = 1, res; cin >> n; while(n != 0) { res = 0; while (n--) { cin >> e; if (e > 0) res += 1; else res -= 1; } cout << "Case " << count << ": "; cout << res << endl; count++; cin >> n; } return 0; }
9f4958c3fb369036075b2294beab52b186c8bc40
781b483f6449aa8987aeac9563e635525f7bea50
/tests/ListContainer_test.hpp
65f53f6b23359df48fb25be3b4609aa294769f25
[]
no_license
NishPatel101/DesignPatterns_Math
515f932aa64064a43a62891498f7ec4b30696046
09930c01c503b81a117295e239e43a255a065996
refs/heads/master
2023-05-10T08:38:55.078128
2020-05-28T16:45:13
2020-05-28T16:45:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,692
hpp
#ifndef __LISTCONTAINER_TEST_HPP__ #define __LISTCONTAINER_TEST_HPP__ #include "gtest/gtest.h" #include "../headers/op.hpp" #include "../headers/sub.hpp" #include "../headers/add.hpp" #include "../headers/mult.hpp" #include "../headers/ListContainer.hpp" TEST(ListContainerTestSet, SwapElementTest) { //Setup the elements under test Op* seven = new Op(7); Op* one = new Op(1); Op* four = new Op(4); ListContainer* test_container = new ListContainer(); // Exercise some functionality of hte test elements test_container->add_element(seven); test_container->add_element(one); test_container->add_element(four); // Assert that the container has at least a single element ASSERT_EQ(test_container->size(), 3); test_container->swap(0,1); EXPECT_EQ(test_container->at(0)->evaluate(), 1); } TEST(ListContainerTestSet, AddElementTest) { //Setup the elements under test Op* seven = new Op(7); Op* one = new Op(1); Op* four = new Op(4); ListContainer* test_container = new ListContainer(); // Exercise some functionality of hte test elements test_container->add_element(seven); test_container->add_element(one); test_container->add_element(four); // Assert that the container has at least a single element ASSERT_EQ(test_container->size(), 3); EXPECT_EQ(test_container->at(0)->evaluate(), 7); EXPECT_EQ(test_container->at(1)->evaluate(), 1); EXPECT_EQ(test_container->at(2)->evaluate(), 4); } /*TEST(ListContainerTestSet, PrintList){ Op* seven = new Op(7); Op* four = new Op(4); Op* three = new Op(3); ListContainer* test_container = new ListContainer(); test_container->add_element(seven); test_container->add_element(four); test_container->add_element(three); test_container->print(); ASSERT_EQ(test_container->size(), 3); EXPECT_EQ(test_container->at(0)->evaluate(), 7); EXPECT_EQ(test_container->at(1)->evaluate(), 4); EXPECT_EQ(test_container->at(2)->evaluate(), 3); } TEST(ListContainerTestSet, PrintTrees){ Op* seven = new Op(7); Op* four = new Op(4); Mult* TreeA = new Mult(seven, four); Op* three = new Op(3); Op* two = new Op(2); Add* TreeB = new Add(three, two); Op* ten = new Op(10); Op* six = new Op(6); Sub* TreeC = new Sub(ten, six); ListContainer* test_container = new ListContainer(); test_container->add_element(TreeA); test_container->add_element(TreeB); test_container->add_element(TreeC); test_container->print(); ASSERT_EQ(test_container->size(), 3); EXPECT_EQ(test_container->at(0)->evaluate(), 28); EXPECT_EQ(test_container->at(1)->evaluate(), 5); EXPECT_EQ(test_container->at(2)->evaluate(), 4); }*/ #endif
83554b97df06e7aceb960f52bc234656b4abcf2c
63a6b9087dfa9a4de551dc5e8209176e695302e3
/T2/Code/w2/incrementpointervalue.cpp
edbcff4376051cc8d52e7dcbcf376bea6237948a
[]
no_license
Ernir/kennsluefni
e953352c2c54d744cb52686f4c931f730d97a7a2
56d05c2e349595ee7feee3cf144e6e2ee6c2d6a4
refs/heads/master
2021-01-17T01:12:49.857568
2018-08-06T21:11:35
2018-08-06T21:11:45
49,427,245
1
11
null
null
null
null
UTF-8
C++
false
false
592
cpp
#include <iostream> using namespace std; void increment_pointed(int* p) { /* Increments the value pointed to by p. */ (*p)++; } void increment_value(int i) { /* Increments the value i. Then discards it. */ i++; } int main() { int* j = new int; *j = 7; cout << "Fyrst er *j=" << *j << endl; increment_value(*j); cout << "Eftir að kallað er á increment_value er *j=" << *j << " (óbreytt)" << endl; increment_pointed(j); cout << "Eftir að kallað er á increment_pointed er *j=" << *j << endl; delete j; return 0; }
d1ab8b855ec2687e160bcad93468d5c498e6b167
93eb75a580dbe06063f8a74b8d3c0ad35e6beb9a
/Classes/BattleScene.cpp
07f9a328e63e1e754af98967534605daaaa4c0ad
[]
no_license
rainbowlee/Pocket-Warriors
2d3b5f677af4e790c1577a16eed411ae7d361ec2
322651e83550203182f2bae78e940408707e8146
refs/heads/master
2021-01-17T21:17:03.943016
2014-08-20T03:18:09
2014-08-20T03:18:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,474
cpp
// // BattleScene.cpp // TestGame // // Created by lh on 13-9-18. // www.9miao.com // #include "BattleScene.h" #include "Voiceover.h" #include "message.h" CCScene * BattleScene::scene(){ CCScene * scene= CCScene :: create(); CCLayer * layer= BattleScene::create(); scene->addChild(layer); return scene; } bool BattleScene::init(){ if (!CCLayer::init()) { return false; } line= BattleLayer::create(); this->addChild(line); socket=GameData::shareGameData()->socket; sendEnterBattle(); return true; } bool HeadLayer::init(){ if(!CCLayer::init()){ return false; } return true; } void BattleScene::sendEnterBattle(){ CSJson::FastWriter writer; CSJson::Value root; root["pid"]=GameData::shareGameData()->chaId; std::string str=writer.write(root); Message * msg= (Message *)socket->constructMessage(str, CMID_GETPERMITENTERBATTLE); socket->sendMessage_(msg, false); this->schedule(schedule_selector(BattleScene::receiveEnterBattle)); } void BattleScene::receiveEnterBattle(){ Message * msg= (Message *)GameData::shareGameData()->msg_dic->objectForKey(CMID_GETPERMITENTERBATTLE); if (msg) { this->unschedule(schedule_selector(BattleScene::receiveEnterBattle)); GameData::shareGameData()->msg_dic->removeObjectForKey(CMID_GETPERMITENTERBATTLE); } } void BattleScene::onExit(){ CCLayer::onExit(); }
7ea18ac7d2997f3953123c5f7ed6220a9cfdcdcd
206144923f04acfa22b9127755917df1c82ff18e
/src/MyChrome/SkinWnd/SkinWnd.h
c1d4db959b789ca2036c966aea945f712e59156e
[]
no_license
drivestudy/MyChrome
5a98b36353bd4c518d9c1f796ec260590a3e495c
c34f1cafa6f417b533a0cfe9439154c9b90ecc68
refs/heads/master
2020-07-08T18:12:31.158318
2019-08-05T02:14:09
2019-08-05T02:14:09
203,741,250
3
0
null
2019-08-22T07:44:00
2019-08-22T07:43:59
null
WINDOWS-1252
C++
false
false
672
h
#pragma once #include "UIColorSkin.h" class CSkinWnd : public WindowImplBase , public CSelectColorCallback { public: CSkinWnd(void); ~CSkinWnd(void); virtual LPCTSTR GetWindowClassName()const { return _T("»»·ô"); } virtual CDuiString GetSkinFolder() { return _T("Skin"); } virtual CDuiString GetSkinFile() { return _T("SkinWnd.xml"); } virtual void InitWindow(); virtual void OnFinalMessage( HWND hWnd ); virtual void OnClick(TNotifyUI& msg); virtual CControlUI* CreateControl(LPCTSTR pstrClass); protected: virtual void ColorTest(DWORD color); private: CButtonUI* m_pBtnOk; CColorSkinUI* m_pColorSkin; CHorizontalLayoutUI* m_pTitleBar; };
77c0141f7788952638581f660819309c70e9db96
ad71ab3c39785830a112951075afe97c9948f5bc
/ZF/ZFCore/zfsrc/ZFCore/ZFObjectDef/ZFSerializableDataSerializableConverter.cpp
241e9747ce50134303df5c4147a1d5bf64610f73
[ "Vim", "MIT" ]
permissive
ZFFrameworkDist/ZFFramework
0f8027126ef41e59c762cd68d878cac28fae1ea4
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
refs/heads/master
2021-08-04T04:40:41.207724
2021-05-25T08:36:10
2021-05-25T08:36:10
120,870,315
0
0
null
null
null
null
UTF-8
C++
false
false
22,097
cpp
#include "ZFSerializableDataSerializableConverter.h" #include "ZFObjectImpl.h" #include "ZFSerializableUtil.h" ZF_NAMESPACE_GLOBAL_BEGIN // ============================================================ /* * // '-' for empty ClassName * * <ClassNameEncoded AttrKey1="AttrValue1" AttrKey2="AttrValue2" [ * <ChildElement0> * <ChildElement1 AttrKey3=""> * <ChildElement2 []> * ]> */ #define _ZFP_ZFSD_NullClass '-' #define _ZFP_ZFSD_IsSpace(c) (zfcharIsSpace(c) || zfcharIsEndl(c)) #define _ZFP_ZFSD_Space ' ' #define _ZFP_ZFSD_ObjBegin '<' #define _ZFP_ZFSD_ObjEnd '>' #define _ZFP_ZFSD_AttrAssign '=' #define _ZFP_ZFSD_AttrValuePair '"' #define _ZFP_ZFSD_AttrValuePairEscape '\\' #define _ZFP_ZFSD_ChildBegin '[' #define _ZFP_ZFSD_ChildEnd ']' // ============================================================ // escape char map for serializable data's class name and attribute key name // everything would be escaped except: // 0~9 // a-z // A-Z // @#$_ static const zfchar _ZFP_ZFSerializableEscapeCharMap[256] = { // 0x00 ~ 0x0F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10 ~ 0x1F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x20 ~ 0x2F 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x30 ~ 0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 0x40 ~ 0x4F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 ~ 0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 0x60 ~ 0x6F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 ~ 0x7F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, // 0x80 ~ 0x8F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90 ~ 0x9F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xA0 ~ 0xAF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xB0 ~ 0xBF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xC0 ~ 0xCF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xD0 ~ 0xDF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xE0 ~ 0xEF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xF0 ~ 0xFF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // }; // ============================================================ zfbool ZFSerializableDataFromZfsd(ZF_OUT ZFSerializableData &serializableData, ZF_IN const ZFInput &input, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */) { if(!input.callbackIsValid()) { ZFSerializableUtil::errorOccurred(outErrorHint, "invalid input callback"); return zffalse; } ZFBuffer buf = ZFInputReadToBuffer(input); if(buf.buffer() == zfnull) { ZFSerializableUtil::errorOccurred(outErrorHint, "unable to load data from input"); return zffalse; } zfbool ret = ZFSerializableDataFromZfsd(serializableData, buf.bufferAsString(), buf.bufferAsStringLength(), outErrorHint); if(ret) { serializableData.pathInfo(input.pathInfo()); } return ret; } ZFSerializableData ZFSerializableDataFromZfsd(ZF_IN const ZFInput &input, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */) { ZFSerializableData ret; if(ZFSerializableDataFromZfsd(ret, input, outErrorHint)) { return ret; } else { return ZFSerializableData(); } } zfbool ZFSerializableDataToZfsd(ZF_IN_OUT const ZFOutput &output, ZF_IN const ZFSerializableData &serializableData, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */, ZF_IN_OPT zfbool prettyPrint /* = zftrue */) { if(!output.callbackIsValid()) { ZFSerializableUtil::errorOccurred(outErrorHint, "invalid output callback"); return zffalse; } zfstring tmp; if(!ZFSerializableDataToZfsd(tmp, serializableData, outErrorHint, prettyPrint)) { return zffalse; } tmp += "\n"; output.execute(tmp.cString(), tmp.length()); return zftrue; } // ============================================================ static zfbool _ZFP_ZFSD_AttrValueDecode(ZF_IN_OUT zfstring &ret, ZF_IN_OUT const zfchar *&encodedData, ZF_IN const zfchar *srcEnd) { if(*encodedData != _ZFP_ZFSD_AttrValuePair) { return zffalse; } ++encodedData; const zfchar *pLeft = encodedData; while(encodedData < srcEnd && *encodedData != _ZFP_ZFSD_AttrValuePair) { if(*encodedData == _ZFP_ZFSD_AttrValuePairEscape && encodedData + 1 < srcEnd) { ++encodedData; if(*encodedData == _ZFP_ZFSD_AttrValuePair) { ret.append(pLeft, encodedData - 1 - pLeft); ret += _ZFP_ZFSD_AttrValuePair; ++encodedData; pLeft = encodedData; } else if(*encodedData == _ZFP_ZFSD_AttrValuePairEscape) { ret.append(pLeft, encodedData - 1 - pLeft); ret += _ZFP_ZFSD_AttrValuePairEscape; ++encodedData; pLeft = encodedData; } else if(*encodedData == 'r') { ret.append(pLeft, encodedData - 1 - pLeft); ret += '\r'; ++encodedData; pLeft = encodedData; } else if(*encodedData == 'n') { ret.append(pLeft, encodedData - 1 - pLeft); ret += '\n'; ++encodedData; pLeft = encodedData; } else if(*encodedData == 't') { ret.append(pLeft, encodedData - 1 - pLeft); ret += '\t'; ++encodedData; pLeft = encodedData; } } else { zfcharMoveNext(encodedData); } } ret.append(pLeft, encodedData - pLeft); if(*encodedData == _ZFP_ZFSD_AttrValuePair) { ++encodedData; return zftrue; } else { return zffalse; } } static void _ZFP_ZFSD_AttrValueEncode(ZF_IN_OUT zfstring &ret, ZF_IN const zfchar *value) { ret += _ZFP_ZFSD_AttrValuePair; const zfchar *pL = value; while(*value != '\0') { if(*value == _ZFP_ZFSD_AttrValuePair) { ret.append(pL, value - pL); ++value; pL = value; ret += _ZFP_ZFSD_AttrValuePairEscape; ret += _ZFP_ZFSD_AttrValuePair; } else if(*value == _ZFP_ZFSD_AttrValuePairEscape) { ret.append(pL, value - pL); ++value; pL = value; ret += _ZFP_ZFSD_AttrValuePairEscape; ret += _ZFP_ZFSD_AttrValuePairEscape; } else if(*value == '\r') { ret.append(pL, value - pL); ++value; pL = value; ret += _ZFP_ZFSD_AttrValuePairEscape; ret += 'r'; } else if(*value == '\n') { ret.append(pL, value - pL); ++value; pL = value; ret += _ZFP_ZFSD_AttrValuePairEscape; ret += 'n'; } else if(*value == '\t') { ret.append(pL, value - pL); ++value; pL = value; ret += _ZFP_ZFSD_AttrValuePairEscape; ret += 't'; } else { zfcharMoveNext(value); } } ret.append(pL, value - pL); ret += _ZFP_ZFSD_AttrValuePair; } zfbool _ZFP_ZFSerializableDataFromZfsd(ZF_OUT ZFSerializableData &serializableData, ZF_IN_OUT const zfchar *&encodedData, ZF_IN zfindex encodedDataLen, ZF_OUT zfstring *outErrorHint, ZF_IN_OPT zfbool validateTail = zffalse) { if(encodedData == zfnull) { ZFSerializableUtil::errorOccurred(outErrorHint, "invalid param"); return zffalse; } const zfchar *srcEnd = (encodedData + ((encodedDataLen == zfindexMax()) ? zfslen(encodedData) : encodedDataLen)); zfbool ret = zffalse; do { const zfchar *pLeft = zfnull; const zfchar *pRight = zfnull; zfstring decodedTmp; // begin zfcharSkipSpaceAndEndl(encodedData, srcEnd); if(encodedData >= srcEnd || *encodedData != _ZFP_ZFSD_ObjBegin) {break;} ++encodedData; // class name zfcharSkipSpaceAndEndl(encodedData, srcEnd); pLeft = encodedData; while(encodedData < srcEnd && !_ZFP_ZFSD_IsSpace(*encodedData) && *encodedData != _ZFP_ZFSD_ChildBegin && *encodedData != _ZFP_ZFSD_ObjEnd ) { zfcharMoveNext(encodedData); } pRight = encodedData; zfcharSkipSpaceAndEndl(encodedData, srcEnd); if(encodedData >= srcEnd) {break;} if(pRight == pLeft + 1 && *pLeft == _ZFP_ZFSD_NullClass) { serializableData.itemClass(zfnull); } else { zfCoreDataDecode(decodedTmp, pLeft, pRight - pLeft); serializableData.itemClass(decodedTmp.cString()); decodedTmp.removeAll(); } // attributes if(*encodedData != _ZFP_ZFSD_ChildBegin && *encodedData != _ZFP_ZFSD_ObjEnd) { while(encodedData < srcEnd) { if(*encodedData == _ZFP_ZFSD_ChildBegin || *encodedData == _ZFP_ZFSD_ObjEnd) { ret = zftrue; break; } // name pLeft = encodedData; while(encodedData < srcEnd && !_ZFP_ZFSD_IsSpace(*encodedData) && *encodedData != _ZFP_ZFSD_AttrAssign ) { zfcharMoveNext(encodedData); } if(encodedData >= srcEnd) {break;} pRight = encodedData; if(*encodedData != _ZFP_ZFSD_AttrAssign) { zfcharSkipSpaceAndEndl(encodedData, srcEnd); } if(*encodedData != _ZFP_ZFSD_AttrAssign) {break;} ++encodedData; zfcharSkipSpaceAndEndl(encodedData, srcEnd); zfstring attributeName; zfCoreDataDecode(attributeName, pLeft, pRight - pLeft); // value if(!_ZFP_ZFSD_AttrValueDecode(decodedTmp, encodedData, srcEnd)) {break;} // save if(!attributeName.isEmpty() && !decodedTmp.isEmpty()) { serializableData.attributeForName(attributeName.cString(), decodedTmp.cString()); } decodedTmp.removeAll(); zfcharSkipSpaceAndEndl(encodedData, srcEnd); } if(!ret) {break;} ret = zffalse; } // if(*encodedData == _ZFP_ZFSD_AttrBegin) // elements if(*encodedData == _ZFP_ZFSD_ChildBegin) { ++encodedData; while(encodedData < srcEnd) { zfcharSkipSpaceAndEndl(encodedData, srcEnd); if(*encodedData == _ZFP_ZFSD_ChildEnd) { ++encodedData; zfcharSkipSpaceAndEndl(encodedData, srcEnd); ret = zftrue; break; } ZFSerializableData element; if(!_ZFP_ZFSerializableDataFromZfsd(element, encodedData, srcEnd - encodedData, outErrorHint)) { return zffalse; } serializableData.elementAdd(element); } if(!ret) {break;} ret = zffalse; } // tail if(encodedData >= srcEnd || *encodedData != _ZFP_ZFSD_ObjEnd) {break;} ++encodedData; if(validateTail) { zfcharSkipSpaceAndEndl(encodedData, srcEnd); if(encodedData < srcEnd) {break;} } ret = zftrue; } while(zffalse); if(!ret) { ZFSerializableUtil::errorOccurred(outErrorHint, "wrong serializable string format at position: \"%s\"", zfstring(encodedData, srcEnd - encodedData).cString()); } return ret; } // ============================================================ zfbool ZFSerializableDataFromZfsd(ZF_OUT ZFSerializableData &serializableData, ZF_IN const zfchar *encodedData, ZF_IN_OPT zfindex encodedDataLen /* = zfindexMax() */, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */) { return _ZFP_ZFSerializableDataFromZfsd(serializableData, encodedData, encodedDataLen, outErrorHint, zfHint("validateTail")zftrue); } ZFSerializableData ZFSerializableDataFromZfsd(ZF_IN const zfchar *encodedData, ZF_IN zfindex encodedDataLen, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */) { ZFSerializableData ret; if(ZFSerializableDataFromZfsd(ret, encodedData, encodedDataLen, outErrorHint)) { return ret; } else { return ZFSerializableData(); } } static zfbool _ZFP_ZFSerializableDataToZfsdPretty(ZF_OUT zfstring &result, ZF_IN const ZFSerializableData &serializableData, ZF_OUT zfstring *outErrorHint, ZF_IN zfindex indentLevel); zfbool ZFSerializableDataToZfsd(ZF_OUT zfstring &result, ZF_IN const ZFSerializableData &serializableData, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */, ZF_IN_OPT zfbool prettyPrint /* = zftrue */) { if(prettyPrint) { return _ZFP_ZFSerializableDataToZfsdPretty(result, serializableData, outErrorHint, 0); } result += _ZFP_ZFSD_ObjBegin; // serializable class if(serializableData.itemClass() == zfnull) { result += _ZFP_ZFSD_NullClass; } else { zfCoreDataEncode(result, serializableData.itemClass(), zfindexMax(), _ZFP_ZFSerializableEscapeCharMap); } // attributes if(serializableData.attributeCount() > 0) { for(zfiterator it = serializableData.attributeIterator(); serializableData.attributeIteratorIsValid(it); serializableData.attributeIteratorNextValue(it)) { result += _ZFP_ZFSD_Space; zfCoreDataEncode(result, serializableData.attributeIteratorKey(it), zfindexMax(), _ZFP_ZFSerializableEscapeCharMap); result += _ZFP_ZFSD_AttrAssign; _ZFP_ZFSD_AttrValueEncode(result, serializableData.attributeIteratorValue(it)); } } // elements if(serializableData.elementCount() > 0) { result += _ZFP_ZFSD_ChildBegin; for(zfindex i = 0; i < serializableData.elementCount(); ++i) { if(!ZFSerializableDataToZfsd(result, serializableData.elementAtIndex(i), outErrorHint, prettyPrint)) { return zffalse; } } result += _ZFP_ZFSD_ChildEnd; } result += _ZFP_ZFSD_ObjEnd; return zftrue; } zfstring ZFSerializableDataToZfsd(ZF_IN const ZFSerializableData &serializableData, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */, ZF_IN_OPT zfbool prettyPrint /* = zftrue */) { zfstring tmp; ZFSerializableDataToZfsd(tmp, serializableData, outErrorHint); return tmp; } // ============================================================ static void _ZFP_ZFSerializableDataToZfsdPrettyIndent(ZF_OUT zfstring &result, ZF_IN zfindex indentLevel) { for(zfindex i = 0; i < indentLevel; ++i) { result += " "; } } static zfbool _ZFP_ZFSerializableDataToZfsdPretty(ZF_OUT zfstring &result, ZF_IN const ZFSerializableData &serializableData, ZF_OUT zfstring *outErrorHint, ZF_IN zfindex indentLevel) { _ZFP_ZFSerializableDataToZfsdPrettyIndent(result, indentLevel); result += _ZFP_ZFSD_ObjBegin; // serializable class if(serializableData.itemClass() == zfnull) { result += _ZFP_ZFSD_NullClass; } else { zfCoreDataEncode(result, serializableData.itemClass(), zfindexMax(), _ZFP_ZFSerializableEscapeCharMap); } zfbool needBreak = (serializableData.attributeCount() > 3); // attributes if(serializableData.attributeCount() > 0) { for(zfiterator it = serializableData.attributeIterator(); serializableData.attributeIteratorIsValid(it); serializableData.attributeIteratorNextValue(it)) { if(needBreak) { result += '\n'; _ZFP_ZFSerializableDataToZfsdPrettyIndent(result, indentLevel + 1); } result += _ZFP_ZFSD_Space; zfCoreDataEncode(result, serializableData.attributeIteratorKey(it), zfindexMax(), _ZFP_ZFSerializableEscapeCharMap); result += _ZFP_ZFSD_AttrAssign; _ZFP_ZFSD_AttrValueEncode(result, serializableData.attributeIteratorValue(it)); } } // elements if(serializableData.elementCount() > 0) { if(needBreak) { result += '\n'; _ZFP_ZFSerializableDataToZfsdPrettyIndent(result, indentLevel + 1); } else { result += ' '; } result += _ZFP_ZFSD_ChildBegin; result += '\n'; for(zfindex i = 0; i < serializableData.elementCount(); ++i) { if(!_ZFP_ZFSerializableDataToZfsdPretty(result, serializableData.elementAtIndex(i), outErrorHint, indentLevel + 1)) { return zffalse; } result += '\n'; } _ZFP_ZFSerializableDataToZfsdPrettyIndent(result, indentLevel); result += _ZFP_ZFSD_ChildEnd; } if(needBreak) { result += ' '; } result += _ZFP_ZFSD_ObjEnd; return zftrue; } zfbool ZFObjectFromZfsd(ZF_OUT zfautoObject &ret, ZF_IN const ZFInput &input, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */) { ZFSerializableData data; if(ZFSerializableDataFromZfsd(data, input, outErrorHint)) { return ZFObjectFromData(ret, data, outErrorHint); } else { return zffalse; } } zfautoObject ZFObjectFromZfsd(ZF_IN const ZFInput &input, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */) { zfautoObject ret; ZFObjectFromZfsd(ret, input, outErrorHint); return ret; } zfbool ZFObjectToZfsd(ZF_IN_OUT const ZFOutput &output, ZF_IN ZFObject *obj, ZF_OUT_OPT zfstring *outErrorHint /* = zfnull */, ZF_IN_OPT zfbool prettyPrint /* = zftrue */) { ZFSerializableData serializableData; if(!ZFObjectToData(serializableData, obj, outErrorHint)) { return zffalse; } else { return ZFSerializableDataToZfsd(output, serializableData, outErrorHint, prettyPrint); } } ZF_NAMESPACE_GLOBAL_END #if _ZFP_ZFOBJECT_METHOD_REG #include "../ZFObject.h" ZF_NAMESPACE_GLOBAL_BEGIN ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_3(zfbool, ZFSerializableDataFromZfsd, ZFMP_OUT(ZFSerializableData &, serializableData), ZFMP_IN(const ZFInput &, input), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_2(ZFSerializableData, ZFSerializableDataFromZfsd, ZFMP_IN(const ZFInput &, input), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_3(zfbool, ZFSerializableDataToZfsd, ZFMP_IN_OUT(const ZFOutput &, output), ZFMP_IN(const ZFSerializableData &, serializableData), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_4(zfbool, ZFSerializableDataFromZfsd, ZFMP_OUT(ZFSerializableData &, serializableData), ZFMP_IN(const zfchar *, encodedData), ZFMP_IN_OPT(zfindex, encodedDataLen, zfindexMax()), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_3(ZFSerializableData, ZFSerializableDataFromZfsd, ZFMP_IN(const zfchar *, encodedData), ZFMP_IN_OPT(zfindex, encodedDataLen, zfindexMax()), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_3(zfbool, ZFSerializableDataToZfsd, ZFMP_OUT(zfstring &, result), ZFMP_IN(const ZFSerializableData &, serializableData), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_2(zfstring, ZFSerializableDataToZfsd, ZFMP_IN(const ZFSerializableData &, serializableData), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_3(zfbool, ZFObjectFromZfsd, ZFMP_OUT(zfautoObject &, ret), ZFMP_IN(const ZFInput &, input), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_2(zfautoObject, ZFObjectFromZfsd, ZFMP_IN(const ZFInput &, input), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull)) ZFMETHOD_FUNC_USER_REGISTER_FOR_FUNC_4(zfbool, ZFObjectToZfsd, ZFMP_IN_OUT(const ZFOutput &, output), ZFMP_IN(ZFObject *, obj), ZFMP_OUT_OPT(zfstring *, outErrorHint, zfnull), ZFMP_IN_OPT(zfbool, prettyPrint, zftrue)) ZF_NAMESPACE_GLOBAL_END #endif