hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
3d932aa33720f1c7a77a75b9994337d062f2494a
2,000
cpp
C++
libs/icl/test/fix_tickets_/fix_tickets.cpp
olegshnitko/libboost
548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8
[ "BSL-1.0" ]
1
2019-10-31T00:40:22.000Z
2019-10-31T00:40:22.000Z
libs/icl/test/fix_tickets_/fix_tickets.cpp
olegshnitko/libboost
548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8
[ "BSL-1.0" ]
1
2018-01-17T10:11:43.000Z
2018-01-17T10:11:43.000Z
libs/icl/test/fix_tickets_/fix_tickets.cpp
olegshnitko/libboost
548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8
[ "BSL-1.0" ]
null
null
null
/*-----------------------------------------------------------------------------+ Copyright (c) 2011-2011: Joachim Faulhaber +------------------------------------------------------------------------------+ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENCE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +-----------------------------------------------------------------------------*/ #define BOOST_TEST_MODULE icl::fix_icl_after_thread unit test #include <libs/icl/test/disable_test_warnings.hpp> #include "../unit_test_unwarned.hpp" //#define BOOST_ICL_USE_STATIC_BOUNDED_INTERVALS #include <boost/icl/interval_map.hpp> #include <boost/icl/split_interval_map.hpp> #include <boost/icl/separate_interval_set.hpp> #include <boost/icl/split_interval_set.hpp> using namespace std; using namespace boost; using namespace unit_test; using namespace boost::icl; BOOST_AUTO_TEST_CASE(ticket_5482) { typedef interval_map<int,int,partial_absorber,std::less> m1_t; typedef interval_map<int,int,partial_absorber,std::greater> m2_t; m1_t m1; m2_t m2; m1.insert(make_pair(m1_t::interval_type(1), 20)); m1.insert(make_pair(m1_t::interval_type(2), 20)); m1.insert(make_pair(m1_t::interval_type(3), 20)); m2.insert(make_pair(m2_t::interval_type(1), 20)); m2.insert(make_pair(m2_t::interval_type(2), 20)); m2.insert(make_pair(m2_t::interval_type(3), 20)); BOOST_CHECK_EQUAL(m1.iterative_size(), m2.iterative_size()); BOOST_CHECK_EQUAL(m1.iterative_size(), 1); BOOST_CHECK_EQUAL(m2.iterative_size(), 1); } #include <boost/cstdint.hpp> BOOST_AUTO_TEST_CASE(ticket_5559_Denis) { //Submitted by Denis typedef boost::icl::interval_set<boost::uint32_t, std::greater> Set; const uint32_t ui32_max = (std::numeric_limits<uint32_t>::max)(); Set q1( Set::interval_type::closed(ui32_max, 0) ); Set q5( Set::interval_type::closed(0, 0) ); BOOST_CHECK_EQUAL(q1, q1+q5); }
35.087719
84
0.646
olegshnitko
3d93346dff30ce2e5a4205407046d262a11ac7f0
1,347
cpp
C++
3D/Model.cpp
Floppy/alienation
d2fca9344f88f70f1547573bea2244f77bd23379
[ "BSD-3-Clause" ]
null
null
null
3D/Model.cpp
Floppy/alienation
d2fca9344f88f70f1547573bea2244f77bd23379
[ "BSD-3-Clause" ]
null
null
null
3D/Model.cpp
Floppy/alienation
d2fca9344f88f70f1547573bea2244f77bd23379
[ "BSD-3-Clause" ]
null
null
null
#include "3D/Model.h" #include <SDL_opengl.h> #include <iostream> using namespace std; CModel::CModel() { } CModel::~CModel() { // Delete meshes for (vector<C3DObject*>::iterator it(m_oObjects.begin()); it!=m_oObjects.end(); ++it) { delete *it; } } void CModel::init() { vector<C3DObject*>::iterator it; // Init meshes for (it = m_oObjects.begin(); it!=m_oObjects.end(); ++it) { (*it)->init(); } // Calculate bounding sphere for (it = m_oObjects.begin(); it!=m_oObjects.end(); ++it) { float fLength = (*it)->getTranslation().length() + (*it)->boundingSphere().m_fRadius; if (fLength > m_oSphere.m_fRadius) m_oSphere.m_fRadius = fLength; } C3DObject::init(); } void CModel::render() const { NSDMath::CMatrix mat; if (!m_bInitialised) { //cerr << "WARNING: Model not initialised!" << endl; return; } // Push glPushMatrix(); // Translate glTranslatef(m_vecTranslation.X(),m_vecTranslation.Y(),m_vecTranslation.Z()); mat = CMatrix(GL_MODELVIEW_MATRIX); mat.invert(); // Draw meshes for (vector<C3DObject*>::const_iterator it(m_oObjects.begin()); it!=m_oObjects.end(); ++it) { (*it)->setRotation(mat); (*it)->render(); } // Pop glPopMatrix(); } void CModel::addObject(C3DObject* pObject) { m_oObjects.push_back(pObject); }
21.725806
96
0.623608
Floppy
3d938a72a0fbca54f2579dfd96f53f6b7fe1aa32
139
cc
C++
u-math.cc
lvv/lvvlib
b610a089103853e7cf970efde2ce4bed9f505090
[ "MIT" ]
13
2015-02-05T12:26:16.000Z
2020-09-14T23:13:14.000Z
u-math.cc
lvv/lvvlib
b610a089103853e7cf970efde2ce4bed9f505090
[ "MIT" ]
null
null
null
u-math.cc
lvv/lvvlib
b610a089103853e7cf970efde2ce4bed9f505090
[ "MIT" ]
null
null
null
#include <lvv/check.h> #include <lvv/math.h> //using namespace std; using namespace lvv; int main() { CHECK_EXIT; }
10.692308
23
0.589928
lvv
3d93f1cb10ea3bee5d995ee83b7a16e26d503a20
1,385
hpp
C++
src/NumericalAlgorithms/LinearOperators/Tags.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
2
2021-04-11T04:07:42.000Z
2021-04-11T05:07:54.000Z
src/NumericalAlgorithms/LinearOperators/Tags.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
4
2018-06-04T20:26:40.000Z
2018-07-27T14:54:55.000Z
src/NumericalAlgorithms/LinearOperators/Tags.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
1
2019-01-03T21:47:04.000Z
2019-01-03T21:47:04.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <string> #include "DataStructures/DataBox/Tag.hpp" #include "Options/Options.hpp" namespace OptionTags { /*! * \ingroup OptionGroupsGroup * \brief Groups the filtering configurations in the input file. */ struct FilteringGroup { static std::string name() noexcept { return "Filtering"; } static constexpr Options::String help = "Options for filtering"; }; /*! * \ingroup OptionTagsGroup * \brief The option tag that retrieves the parameters for the filter * from the input file */ template <typename FilterType> struct Filter { static std::string name() noexcept { return Options::name<FilterType>(); } static constexpr Options::String help = "Options for the filter"; using type = FilterType; using group = FilteringGroup; }; } // namespace OptionTags namespace Filters { namespace Tags { /*! * \brief The global cache tag for the filter */ template <typename FilterType> struct Filter : db::SimpleTag { static std::string name() noexcept { return "Filter"; } using type = FilterType; using option_tags = tmpl::list<::OptionTags::Filter<FilterType>>; static constexpr bool pass_metavariables = false; static FilterType create_from_options(const FilterType& filter) noexcept { return filter; } }; } // namespace Tags } // namespace Filters
25.181818
76
0.725632
macedo22
3d9769206990b5a564033e499fd191ca703103ee
1,377
cpp
C++
backends/magma/kernels/hip/magma_devptr.hip.cpp
AdelekeBankole/libCEED
aae8ce39fa1e28b745979a9cbffc67a790eb3f5e
[ "BSD-2-Clause" ]
123
2018-01-29T02:04:05.000Z
2022-03-21T18:13:48.000Z
backends/magma/kernels/hip/magma_devptr.hip.cpp
AdelekeBankole/libCEED
aae8ce39fa1e28b745979a9cbffc67a790eb3f5e
[ "BSD-2-Clause" ]
781
2017-12-22T17:20:35.000Z
2022-03-29T21:34:34.000Z
backends/magma/kernels/hip/magma_devptr.hip.cpp
AdelekeBankole/libCEED
aae8ce39fa1e28b745979a9cbffc67a790eb3f5e
[ "BSD-2-Clause" ]
41
2017-12-27T22:35:13.000Z
2022-03-01T13:02:07.000Z
#include <ceed/ceed.h> #include <magma_v2.h> #include <hip/hip_runtime.h> /***************************************************************************//** Determines whether a pointer points to CPU or GPU memory. This is very similar to magma_is_devptr, except that it does not check for unified addressing support. @param[in] A pointer to test @return 1: if A is a device pointer (definitely), @return 0: if A is a host pointer (definitely or inferred from error), @return -1: if unknown. @ingroup magma_util *******************************************************************************/ extern "C" magma_int_t magma_isdevptr( const void* A ) { hipError_t err; hipPointerAttribute_t attr; int dev; // must be int err = hipGetDevice( &dev ); if ( ! err ) { err = hipPointerGetAttributes( &attr, A); if ( ! err ) { // definitely know type return (attr.memoryType == hipMemoryTypeDevice); } else if ( err == hipErrorInvalidValue ) { // clear error; see http://icl.cs.utk.edu/magma/forum/viewtopic.php?f=2&t=529 hipGetLastError(); // infer as host pointer return 0; } } // clear error hipGetLastError(); // unknown, e.g., device doesn't support unified addressing return -1; }
32.023256
89
0.538853
AdelekeBankole
3d987da0967cf411958390863a9b9253926c4607
4,115
cpp
C++
libredex/WorkQueue.cpp
sjndhkl/redex
f6da510e67da284b0093bf01e2e9357d8b963cfd
[ "BSD-3-Clause" ]
null
null
null
libredex/WorkQueue.cpp
sjndhkl/redex
f6da510e67da284b0093bf01e2e9357d8b963cfd
[ "BSD-3-Clause" ]
null
null
null
libredex/WorkQueue.cpp
sjndhkl/redex
f6da510e67da284b0093bf01e2e9357d8b963cfd
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "WorkQueue.h" #include <stdio.h> #include "Trace.h" /* * Question: What happens when you alot yourself 30 minutes * to design and write a work-queue? * Answer: You're looking at it. * * This is a BatchWork (TM) type of work queue. The work is * dispatched blocking the submitter of the work. Lame, I know, * but good enough for now. * */ constexpr int WORKER_THREADS = 4; per_thread* WorkQueue::s_per_thread = nullptr; std::condition_variable WorkQueue::s_completion; std::condition_variable WorkQueue::s_work_ready; std::mutex WorkQueue::s_lock; std::mutex WorkQueue::s_work_running; int WorkQueue::s_threads_complete; inline int get_next_thread_num(int threadno) { threadno++; if (threadno == WORKER_THREADS) return 0; return threadno; } bool WorkQueue::steal_work(per_thread* self) { int threadno = get_next_thread_num(self->thread_num); while (self->thread_num != threadno) { per_thread* target = &s_per_thread[threadno]; std::unique_lock<std::mutex> target_unique_lock(target->lock); int stealcount = (target->next - target->last) / 2; if (stealcount > 0) { // Found work! work_item* wi = target->wi; int next = target->next; int last = target->last - stealcount; target->next = last; target_unique_lock.unlock(); std::lock_guard<std::mutex> guard(self->lock); self->wi = wi; self->next = next; self->last = last; return true; } target_unique_lock.unlock(); threadno = get_next_thread_num(threadno); } return false; } void* WorkQueue::worker_thread(void* priv) { per_thread* self = (per_thread*)priv; while (1) { std::unique_lock<std::mutex> self_unique_lock(self->lock); if (self->next < self->last) { work_item* todo = &self->wi[self->next++]; self_unique_lock.unlock(); todo->function(todo->arg); continue; } self_unique_lock.unlock(); if (steal_work(self)) continue; /* Nothing to do..., wait for it. */ std::unique_lock<std::mutex> s_unique_lock(s_lock); s_threads_complete++; if (s_threads_complete == WORKER_THREADS) { s_completion.notify_one(); } s_work_ready.wait(s_unique_lock); } return nullptr; } WorkQueue::WorkQueue() { std::lock_guard<std::mutex> guard(s_lock); if (s_per_thread == nullptr) { s_per_thread = new per_thread[WORKER_THREADS]; for (int i = 0; i < WORKER_THREADS; i++) { s_per_thread[i].wi = nullptr; s_per_thread[i].next = 0; s_per_thread[i].last = 0; s_per_thread[i].thread_num = i; } /* Steal work can peek at other threads work queues, * so we have to init all the work queues before * launching any threads. */ for (int i = 0; i < WORKER_THREADS; i++) { pthread_create( &s_per_thread[i].thread, nullptr, &worker_thread, &s_per_thread[i]); } } } /* Caller owns memory for witems. WorkQueue does not free it. */ void WorkQueue::run_work_items(work_item* witems, int count) { std::lock_guard<std::mutex> guard(s_work_running); std::unique_lock<std::mutex> s_unique_lock(s_lock); while (s_threads_complete < WORKER_THREADS) { s_completion.wait(s_unique_lock); } if (witems != nullptr) { int per_thread_count = count / WORKER_THREADS; int sindex = 0; int i; for (i = 0; i < (WORKER_THREADS - 1); i++) { s_per_thread[i].wi = witems; s_per_thread[i].next = sindex; s_per_thread[i].last = sindex + per_thread_count; sindex += per_thread_count; } s_per_thread[i].wi = witems; s_per_thread[i].next = sindex; s_per_thread[i].last = count; s_threads_complete = 0; s_work_ready.notify_all(); do { s_completion.wait(s_unique_lock); } while (s_threads_complete < WORKER_THREADS); } }
30.036496
78
0.665857
sjndhkl
3d9cb981888e33978b323b09898b09907ce75425
14,311
cpp
C++
src/mame/audio/cinemat.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/audio/cinemat.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/audio/cinemat.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Aaron Giles /*************************************************************************** Cinematronics vector hardware Special thanks to Neil Bradley, Zonn Moore, and Jeff Mitchell of the Retrocade Alliance Update: 6/27/99 Jim Hernandez -- 1st Attempt at Fixing Drone Star Castle sound and pitch adjustments. 6/30/99 MLR added Rip Off, Solar Quest, Armor Attack (no samples yet) 11/04/08 Jim Hernandez -- Fixed Drone Star Castle sound again. It was broken for a long time due to some changes. Bugs: Sometimes the death explosion (small explosion) does not trigger. ***************************************************************************/ #include "emu.h" #include "includes/cinemat.h" #include "audio/nl_armora.h" #include "audio/nl_barrier.h" #include "audio/nl_boxingb.h" #include "audio/nl_ripoff.h" #include "audio/nl_solarq.h" #include "audio/nl_spacewar.h" #include "audio/nl_speedfrk.h" #include "audio/nl_starcas.h" #include "audio/nl_starhawk.h" #include "audio/nl_sundance.h" #include "audio/nl_tailg.h" #include "audio/nl_warrior.h" #include "cpu/z80/z80.h" #include "machine/z80daisy.h" #include "machine/z80ctc.h" #include "speaker.h" /************************************* * * Base class * *************************************/ cinemat_audio_device_base::cinemat_audio_device_base(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock, u8 inputs_mask, void (*netlist)(netlist::nlparse_t &), double output_scale) : device_t(mconfig, type, tag, owner, clock), device_mixer_interface(mconfig, *this), m_out_input(*this, "sound_nl:out_%u", 0), m_inputs_mask(inputs_mask), m_netlist(netlist), m_output_scale(output_scale) { } cinemat_audio_device_base &cinemat_audio_device_base::configure_latch_inputs(ls259_device &latch, u8 mask) { if (mask == 0) mask = m_inputs_mask; if (BIT(mask, 0)) latch.q_out_cb<0>().set(write_line_delegate(*this, FUNC(cinemat_audio_device_base::sound_w<0>))); if (BIT(mask, 1)) latch.q_out_cb<1>().set(write_line_delegate(*this, FUNC(cinemat_audio_device_base::sound_w<1>))); if (BIT(mask, 2)) latch.q_out_cb<2>().set(write_line_delegate(*this, FUNC(cinemat_audio_device_base::sound_w<2>))); if (BIT(mask, 3)) latch.q_out_cb<3>().set(write_line_delegate(*this, FUNC(cinemat_audio_device_base::sound_w<3>))); if (BIT(mask, 4)) latch.q_out_cb<4>().set(write_line_delegate(*this, FUNC(cinemat_audio_device_base::sound_w<4>))); if (BIT(mask, 7)) latch.q_out_cb<7>().set(write_line_delegate(*this, FUNC(cinemat_audio_device_base::sound_w<7>))); return *this; } void cinemat_audio_device_base::device_add_mconfig(machine_config &config) { NETLIST_SOUND(config, "sound_nl", 48000) .set_source(m_netlist) .add_route(ALL_OUTPUTS, *this, 1.0); if ((m_inputs_mask & 0x01) != 0) NETLIST_LOGIC_INPUT(config, m_out_input[0], "I_OUT_0.IN", 0); if ((m_inputs_mask & 0x02) != 0) NETLIST_LOGIC_INPUT(config, m_out_input[1], "I_OUT_1.IN", 0); if ((m_inputs_mask & 0x04) != 0) NETLIST_LOGIC_INPUT(config, m_out_input[2], "I_OUT_2.IN", 0); if ((m_inputs_mask & 0x08) != 0) NETLIST_LOGIC_INPUT(config, m_out_input[3], "I_OUT_3.IN", 0); if ((m_inputs_mask & 0x10) != 0) NETLIST_LOGIC_INPUT(config, m_out_input[4], "I_OUT_4.IN", 0); if ((m_inputs_mask & 0x80) != 0) NETLIST_LOGIC_INPUT(config, m_out_input[7], "I_OUT_7.IN", 0); NETLIST_STREAM_OUTPUT(config, "sound_nl:cout0", 0, "OUTPUT").set_mult_offset(m_output_scale, 0.0); } void cinemat_audio_device_base::device_start() { save_item(NAME(m_inputs)); } void cinemat_audio_device_base::input_set(int bit, int state) { u8 oldvals = m_inputs; m_inputs = (m_inputs & ~(1 << bit)) | ((state & 1) << bit); if (oldvals != m_inputs) for (int index = 0; index < 8; index++) if (m_out_input[index] != nullptr) m_out_input[index]->write_line(BIT(m_inputs, index)); } /************************************* * * Space Wars * *************************************/ DEFINE_DEVICE_TYPE(SPACE_WARS_AUDIO, spacewar_audio_device, "spacewar_audio", "Space Wars Sound Board") spacewar_audio_device::spacewar_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, SPACE_WARS_AUDIO, tag, owner, clock, 0x1f, NETLIST_NAME(spacewar), 4.5) { } /************************************* * * Barrier * *************************************/ DEFINE_DEVICE_TYPE(BARRIER_AUDIO, barrier_audio_device, "barrier_audio", "Barrier Sound Board") barrier_audio_device::barrier_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, BARRIER_AUDIO, tag, owner, clock, 0x07, NETLIST_NAME(barrier), 6.1) { } /************************************* * * Speed Freak * *************************************/ DEFINE_DEVICE_TYPE(SPEED_FREAK_AUDIO, speedfrk_audio_device, "speedfrk_audio", "Speed Freak Sound Board") speedfrk_audio_device::speedfrk_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, SPEED_FREAK_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(speedfrk), 0.35) { } /************************************* * * Star Hawk * *************************************/ DEFINE_DEVICE_TYPE(STAR_HAWK_AUDIO, starhawk_audio_device, "starhawk_audio", "Star Hawk Sound Board") starhawk_audio_device::starhawk_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, STAR_HAWK_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(starhawk), 1.5) { } /************************************* * * Sundance * *************************************/ DEFINE_DEVICE_TYPE(SUNDANCE_AUDIO, sundance_audio_device, "sundance_audio", "Sundance Sound Board") sundance_audio_device::sundance_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, SUNDANCE_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(sundance), 1.0) { } /************************************* * * Tail Gunner * *************************************/ DEFINE_DEVICE_TYPE(TAIL_GUNNER_AUDIO, tailg_audio_device, "tailg_audio", "Tail Gunner Sound Board") tailg_audio_device::tailg_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, TAIL_GUNNER_AUDIO, tag, owner, clock, 0x1f, NETLIST_NAME(tailg), 2.2) { } /************************************* * * Warrior * *************************************/ DEFINE_DEVICE_TYPE(WARRIOR_AUDIO, warrior_audio_device, "warrior_audio", "Warrior Sound Board") warrior_audio_device::warrior_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, WARRIOR_AUDIO, tag, owner, clock, 0x1f, NETLIST_NAME(warrior), 1.5) { } /************************************* * * Armor Attack * *************************************/ DEFINE_DEVICE_TYPE(ARMOR_ATTACK_AUDIO, armora_audio_device, "armora_audio", "Armor Atrack Sound Board") armora_audio_device::armora_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, ARMOR_ATTACK_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(armora), 0.15) { } /************************************* * * Ripoff * *************************************/ DEFINE_DEVICE_TYPE(RIPOFF_AUDIO, ripoff_audio_device, "ripoff_audio", "Rip Off Sound Board") ripoff_audio_device::ripoff_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, RIPOFF_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(ripoff), 0.61) { } /************************************* * * Star Castle * *************************************/ DEFINE_DEVICE_TYPE(STAR_CASTLE_AUDIO, starcas_audio_device, "starcas_audio", "Star Castle Sound Board") starcas_audio_device::starcas_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, STAR_CASTLE_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(starcas), 0.15) { } /************************************* * * Solar Quest * *************************************/ DEFINE_DEVICE_TYPE(SOLAR_QUEST_AUDIO, solarq_audio_device, "solarq_audio", "Solar Quest Sound Board") solarq_audio_device::solarq_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, SOLAR_QUEST_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(solarq), 0.15) { } /************************************* * * Boxing Bugs * *************************************/ DEFINE_DEVICE_TYPE(BOXING_BUGS_AUDIO, boxingb_audio_device, "boxingb_audio", "Boxing Bugs Sound Board") boxingb_audio_device::boxingb_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, BOXING_BUGS_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(boxingb), 0.15) { } /************************************* * * War of the Worlds * *************************************/ DEFINE_DEVICE_TYPE(WAR_OF_THE_WORLDS_AUDIO, wotw_audio_device, "wotw_audio", "War of the Worlds Sound Board") wotw_audio_device::wotw_audio_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock) : cinemat_audio_device_base(mconfig, WAR_OF_THE_WORLDS_AUDIO, tag, owner, clock, 0x9f, NETLIST_NAME(wotw), 0.15) { } /************************************* * * Demon * *************************************/ TIMER_CALLBACK_MEMBER( demon_state::synced_sound_w ) { m_sound_fifo[m_sound_fifo_in] = param; m_sound_fifo_in = (m_sound_fifo_in + 1) % 16; } WRITE_LINE_MEMBER(demon_state::demon_sound4_w) { /* watch for a 0->1 edge on bit 4 ("shift in") to clock in the new data */ if (state) machine().scheduler().synchronize(timer_expired_delegate(FUNC(demon_state::synced_sound_w), this), ~m_outlatch->output_state() & 0x0f); } u8 demon_state::sound_porta_r() { /* bits 0-3 are the sound data; bit 4 is the data ready */ return m_sound_fifo[m_sound_fifo_out] | ((m_sound_fifo_in != m_sound_fifo_out) << 4); } u8 demon_state::sound_portb_r() { return m_last_portb_write; } void demon_state::sound_portb_w(u8 data) { /* watch for a 0->1 edge on bit 0 ("shift out") to advance the data pointer */ if ((data & 1) != (m_last_portb_write & 1) && (data & 1) != 0) m_sound_fifo_out = (m_sound_fifo_out + 1) % 16; /* watch for a 0->1 edge of bit 1 ("hard reset") to reset the FIFO */ if ((data & 2) != (m_last_portb_write & 2) && (data & 2) != 0) m_sound_fifo_in = m_sound_fifo_out = 0; /* bit 2 controls the global mute */ if ((data & 4) != (m_last_portb_write & 4)) machine().sound().system_mute(data & 4); /* remember the last value written */ m_last_portb_write = data; } void demon_state::sound_output_w(u8 data) { logerror("sound_output = %02X\n", data); } void demon_state::sound_start() { cinemat_state::sound_start(); /* register for save states */ save_item(NAME(m_sound_fifo)); save_item(NAME(m_sound_fifo_in)); save_item(NAME(m_sound_fifo_out)); save_item(NAME(m_last_portb_write)); } void demon_state::sound_reset() { /* generic init */ cinemat_state::sound_reset(); /* reset the FIFO */ m_sound_fifo_in = m_sound_fifo_out = 0; m_last_portb_write = 0xff; /* turn off channel A on AY8910 #0 because it is used as a low-pass filter */ m_ay1->set_volume(0, 0); } void demon_state::demon_sound_map(address_map &map) { map(0x0000, 0x1fff).rom(); map(0x3000, 0x33ff).ram(); map(0x4000, 0x4001).r(m_ay1, FUNC(ay8910_device::data_r)); map(0x4002, 0x4003).w(m_ay1, FUNC(ay8910_device::data_address_w)); map(0x5000, 0x5001).r("ay2", FUNC(ay8910_device::data_r)); map(0x5002, 0x5003).w("ay2", FUNC(ay8910_device::data_address_w)); map(0x6000, 0x6001).r("ay3", FUNC(ay8910_device::data_r)); map(0x6002, 0x6003).w("ay3", FUNC(ay8910_device::data_address_w)); map(0x7000, 0x7000).nopw(); /* watchdog? */ } void demon_state::demon_sound_ports(address_map &map) { map.global_mask(0xff); map(0x00, 0x03).w("ctc", FUNC(z80ctc_device::write)); map(0x1c, 0x1f).w("ctc", FUNC(z80ctc_device::write)); } static const z80_daisy_config daisy_chain[] = { { "ctc" }, { nullptr } }; void demon_state::demon_sound(machine_config &config) { /* basic machine hardware */ z80_device& audiocpu(Z80(config, "audiocpu", 3579545)); audiocpu.set_daisy_config(daisy_chain); audiocpu.set_addrmap(AS_PROGRAM, &demon_state::demon_sound_map); audiocpu.set_addrmap(AS_IO, &demon_state::demon_sound_ports); z80ctc_device& ctc(Z80CTC(config, "ctc", 3579545 /* same as "audiocpu" */)); ctc.intr_callback().set_inputline("audiocpu", INPUT_LINE_IRQ0); m_outlatch->q_out_cb<4>().set(FUNC(demon_state::demon_sound4_w)); /* sound hardware */ SPEAKER(config, "mono").front_center(); AY8910(config, m_ay1, 3579545); m_ay1->port_a_read_callback().set(FUNC(demon_state::sound_porta_r)); m_ay1->port_b_read_callback().set(FUNC(demon_state::sound_portb_r)); m_ay1->port_b_write_callback().set(FUNC(demon_state::sound_portb_w)); m_ay1->add_route(ALL_OUTPUTS, "mono", 0.25); AY8910(config, "ay2", 3579545).add_route(ALL_OUTPUTS, "mono", 0.25); ay8910_device &ay3(AY8910(config, "ay3", 3579545)); ay3.port_b_write_callback().set(FUNC(demon_state::sound_output_w)); ay3.add_route(ALL_OUTPUTS, "mono", 0.25); } /************************************* * * QB3 * *************************************/ void qb3_state::qb3_sound_fifo_w(u8 data) { u16 rega = m_maincpu->state_int(ccpu_cpu_device::CCPU_A); machine().scheduler().synchronize(timer_expired_delegate(FUNC(qb3_state::synced_sound_w), this), rega & 0x0f); } void qb3_state::sound_reset() { demon_state::sound_reset(); /* this patch prevents the sound ROM from eating itself when command $0A is sent */ /* on a cube rotate */ memregion("audiocpu")->base()[0x11dc] = 0x09; } void qb3_state::qb3_sound(machine_config &config) { demon_sound(config); m_outlatch->q_out_cb<4>().set_nop(); // not mapped through LS259 }
29.6294
224
0.665013
Robbbert
3da038efc520f05d7de39e486984c907e32def8d
27,204
cpp
C++
device/pal/palcounters.cpp
devurandom/ROCclr
96724e055997473b36c74a0516d1e5ad9e1ca959
[ "MIT" ]
null
null
null
device/pal/palcounters.cpp
devurandom/ROCclr
96724e055997473b36c74a0516d1e5ad9e1ca959
[ "MIT" ]
null
null
null
device/pal/palcounters.cpp
devurandom/ROCclr
96724e055997473b36c74a0516d1e5ad9e1ca959
[ "MIT" ]
null
null
null
/* Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. 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 "device/pal/palcounters.hpp" #include "device/pal/palvirtual.hpp" #include <array> namespace pal { PalCounterReference* PalCounterReference::Create(VirtualGPU& gpu) { Pal::Result result; // Create performance experiment Pal::PerfExperimentCreateInfo createInfo = {}; createInfo.optionFlags.sampleInternalOperations = 1; createInfo.optionFlags.cacheFlushOnCounterCollection = 1; createInfo.optionFlags.sqShaderMask = 1; createInfo.optionValues.sampleInternalOperations = true; createInfo.optionValues.cacheFlushOnCounterCollection = true; createInfo.optionValues.sqShaderMask = Pal::PerfShaderMaskCs; size_t palExperSize = gpu.dev().iDev()->GetPerfExperimentSize(createInfo, &result); if (result != Pal::Result::Success) { return nullptr; } PalCounterReference* memRef = new (palExperSize) PalCounterReference(gpu); if (memRef != nullptr) { result = gpu.dev().iDev()->CreatePerfExperiment(createInfo, &memRef[1], &memRef->perfExp_); if (result != Pal::Result::Success) { memRef->release(); return nullptr; } } return memRef; } PalCounterReference::~PalCounterReference() { // The counter object is always associated with a particular queue, // so we have to lock just this queue amd::ScopedLock lock(gpu_.execution()); if (layout_ != nullptr) { delete layout_; } if (memory_ != nullptr) { delete memory_; } if (nullptr != iPerf()) { iPerf()->Destroy(); } } uint64_t PalCounterReference::result(const std::vector<int>& index) { if (index.size() == 0) { // These are counters that have no corresponding PalSample created return 0; } if (layout_ == nullptr) { return 0; } uint64_t result = 0; for (auto const& i : index) { assert(i <= static_cast<int>(layout_->sampleCount) && "index not in range"); const Pal::GlobalSampleLayout& sample = layout_->samples[i]; if (sample.dataType == Pal::PerfCounterDataType::Uint32) { uint32_t beginVal = *reinterpret_cast<uint32_t*>(reinterpret_cast<char*>(cpuAddr_) + sample.beginValueOffset); uint32_t endVal = *reinterpret_cast<uint32_t*>(reinterpret_cast<char*>(cpuAddr_) + sample.endValueOffset); result += (endVal - beginVal); } else if (sample.dataType == Pal::PerfCounterDataType::Uint64) { uint64_t beginVal = *reinterpret_cast<uint64_t*>(reinterpret_cast<char*>(cpuAddr_) + sample.beginValueOffset); uint64_t endVal = *reinterpret_cast<uint64_t*>(reinterpret_cast<char*>(cpuAddr_) + sample.endValueOffset); result += (endVal - beginVal); } else { assert(0 && "dataType should be either Uint32 or Uint64"); return 0; } } return result; } bool PalCounterReference::finalize() { Pal::Result result; iPerf()->Finalize(); // Acquire GPU memory for the query from the pool and bind it. Pal::GpuMemoryRequirements gpuMemReqs = {}; iPerf()->GetGpuMemoryRequirements(&gpuMemReqs); memory_ = new Memory(gpu().dev(), amd::alignUp(gpuMemReqs.size, gpuMemReqs.alignment)); if (nullptr == memory_) { return false; } if (!memory_->create(Resource::Remote)) { return false; } cpuAddr_ = memory_->cpuMap(gpu_); if (nullptr == cpuAddr_) { return false; } gpu_.queue(gpu_.engineID_).addMemRef(memory_->iMem()); result = iPerf()->BindGpuMemory(memory_->iMem(), 0); if (result == Pal::Result::Success) { Pal::GlobalCounterLayout layout = {}; iPerf()->GetGlobalCounterLayout(&layout); assert(layout.sampleCount == numExpCounters_); size_t size = sizeof(Pal::GlobalCounterLayout) + (sizeof(Pal::GlobalSampleLayout) * (layout.sampleCount - 1)); layout_ = reinterpret_cast<Pal::GlobalCounterLayout*>(new char[size]); if (layout_ != nullptr) { layout_->sampleCount = layout.sampleCount; iPerf()->GetGlobalCounterLayout(layout_); } return true; } else { return false; } } static constexpr std::array<PCIndexSelect, 49> blockIdToIndexSelect = {{ PCIndexSelect::None, // CPF PCIndexSelect::ShaderEngine, // IA PCIndexSelect::ShaderEngine, // VGT PCIndexSelect::ShaderArray, // PA PCIndexSelect::ShaderArray, // SC PCIndexSelect::ShaderEngine, // SPI PCIndexSelect::ShaderEngine, // SQ PCIndexSelect::ShaderArray, // SX PCIndexSelect::ComputeUnit, // TA PCIndexSelect::ComputeUnit, // TD PCIndexSelect::ComputeUnit, // TCP PCIndexSelect::Instance, // TCC PCIndexSelect::Instance, // TCA PCIndexSelect::ShaderArray, // DB PCIndexSelect::ShaderArray, // CB PCIndexSelect::None, // GDS PCIndexSelect::None, // SRBM PCIndexSelect::None, // GRBM PCIndexSelect::ShaderEngine, // GRBMSE PCIndexSelect::None, // RLC PCIndexSelect::Instance, // DMA PCIndexSelect::None, // MC PCIndexSelect::None, // CPG PCIndexSelect::None, // CPC PCIndexSelect::None, // WD PCIndexSelect::None, // TCS PCIndexSelect::None, // ATC PCIndexSelect::None, // ATCL2 PCIndexSelect::None, // MCVML2 PCIndexSelect::Instance, // EA PCIndexSelect::None, // RPB PCIndexSelect::ShaderArray, // RMI PCIndexSelect::Instance, // UMCCH PCIndexSelect::Instance, // GE PCIndexSelect::ShaderArray, // GL1A PCIndexSelect::ShaderArray, // GL1C PCIndexSelect::ShaderArray, // GL1CG PCIndexSelect::Instance, // GL2A PCIndexSelect::Instance, // GL2C PCIndexSelect::None, // CHA PCIndexSelect::Instance, // CHC PCIndexSelect::None, // CHCG PCIndexSelect::None, // GUS PCIndexSelect::None, // GCR PCIndexSelect::None, // PH PCIndexSelect::ShaderArray, // UTCL1 PCIndexSelect::None, // GeDist PCIndexSelect::ShaderEngine, // GeSe PCIndexSelect::None, // Df }}; static_assert(blockIdToIndexSelect.size() == static_cast<size_t>(Pal::GpuBlock::Count), "size of blockIdToIndexSelect does not match GpuBlock::Count"); // Converting from ORCA cmndefs.h to PAL palPerfExperiment.h static constexpr std::array<std::pair<int, int>, 83> ciBlockIdOrcaToPal = {{ {0x0E, 0}, // CB0 {0x0E, 1}, // CB1 {0x0E, 2}, // CB2 {0x0E, 3}, // CB3 {0x00, 0}, // CPF {0x0D, 0}, // DB0 {0x0D, 1}, // DB1 {0x0D, 2}, // DB2 {0x0D, 3}, // DB3 {0x11, 0}, // GRBM {0x12, 0}, // GRBMSE {0x03, 0}, // PA_SU {0x04, 0}, // PA_SC {0x05, 0}, // SPI {0x06, 0}, // SQ {0x06, 0}, // SQ_ES {0x06, 0}, // SQ_GS {0x06, 0}, // SQ_VS {0x06, 0}, // SQ_PS {0x06, 0}, // SQ_LS {0x06, 0}, // SQ_HS {0x06, 0}, // SQ_CS {0x07, 0}, // SX {0x08, 0}, // TA0 {0x08, 1}, // TA1 {0x08, 2}, // TA2 {0x08, 3}, // TA3 {0x08, 4}, // TA4 {0x08, 5}, // TA5 {0x08, 6}, // TA6 {0x08, 7}, // TA7 {0x08, 8}, // TA8 {0x08, 9}, // TA9 {0x08, 0x0a}, // TA10 {0x0C, 0}, // TCA0 {0x0C, 1}, // TCA1 {0x0B, 0}, // TCC0 {0x0B, 1}, // TCC1 {0x0B, 2}, // TCC2 {0x0B, 3}, // TCC3 {0x0B, 4}, // TCC4 {0x0B, 5}, // TCC5 {0x0B, 6}, // TCC6 {0x0B, 7}, // TCC7 {0x0B, 8}, // TCC8 {0x0B, 9}, // TCC9 {0x0B, 0x0a}, // TCC10 {0x0B, 0x0b}, // TCC11 {0x0B, 0x0c}, // TCC12 {0x0B, 0x0d}, // TCC13 {0x0B, 0x0e}, // TCC14 {0x0B, 0x0f}, // TCC15 {0x09, 0}, // TD0 {0x09, 1}, // TD1 {0x09, 2}, // TD2 {0x09, 3}, // TD3 {0x09, 4}, // TD4 {0x09, 5}, // TD5 {0x09, 6}, // TD6 {0x09, 7}, // TD7 {0x09, 8}, // TD8 {0x09, 9}, // TD9 {0x09, 0x0a}, // TD10 {0x0A, 0}, // TCP0 {0x0A, 1}, // TCP1 {0x0A, 2}, // TCP2 {0x0A, 3}, // TCP3 {0x0A, 4}, // TCP4 {0x0A, 5}, // TCP5 {0x0A, 6}, // TCP6 {0x0A, 7}, // TCP7 {0x0A, 8}, // TCP8 {0x0A, 9}, // TCP9 {0x0A, 0x0a}, // TCP10 {0x0F, 0}, // GDS {0x02, 0}, // VGT {0x01, 0}, // IA {0x15, 0}, // MC {0x10, 0}, // SRBM {0x19, 0}, // TCS {0x18, 0}, // WD {0x16, 0}, // CPG {0x17, 0}, // CPC }}; static constexpr std::array<std::pair<int, int>, 97> viBlockIdOrcaToPal = {{ {0x0E, 0}, // CB0 {0x0E, 1}, // CB1 {0x0E, 2}, // CB2 {0x0E, 3}, // CB3 {0x00, 0}, // CPF {0x0D, 0}, // DB0 {0x0D, 1}, // DB1 {0x0D, 2}, // DB2 {0x0D, 3}, // DB3 {0x11, 0}, // GRBM {0x12, 0}, // GRBMSE {0x03, 0}, // PA_SU {0x04, 0}, // PA_SC {0x05, 0}, // SPI {0x06, 0}, // SQ {0x06, 0}, // SQ_ES {0x06, 0}, // SQ_GS {0x06, 0}, // SQ_VS {0x06, 0}, // SQ_PS {0x06, 0}, // SQ_LS {0x06, 0}, // SQ_HS {0x06, 0}, // SQ_CS {0x07, 0}, // SX {0x08, 0}, // TA0 {0x08, 1}, // TA1 {0x08, 2}, // TA2 {0x08, 3}, // TA3 {0x08, 4}, // TA4 {0x08, 5}, // TA5 {0x08, 6}, // TA6 {0x08, 7}, // TA7 {0x08, 8}, // TA8 {0x08, 9}, // TA9 {0x08, 0x0a}, // TA10 {0x08, 0x0b}, // TA11 {0x08, 0x0c}, // TA12 {0x08, 0x0d}, // TA13 {0x08, 0x0e}, // TA14 {0x08, 0x0f}, // TA15 {0x0C, 0}, // TCA0 {0x0C, 1}, // TCA1 {0x0B, 0}, // TCC0 {0x0B, 1}, // TCC1 {0x0B, 2}, // TCC2 {0x0B, 3}, // TCC3 {0x0B, 4}, // TCC4 {0x0B, 5}, // TCC5 {0x0B, 6}, // TCC6 {0x0B, 7}, // TCC7 {0x0B, 8}, // TCC8 {0x0B, 9}, // TCC9 {0x0B, 0x0a}, // TCC10 {0x0B, 0x0b}, // TCC11 {0x0B, 0x0c}, // TCC12 {0x0B, 0x0d}, // TCC13 {0x0B, 0x0e}, // TCC14 {0x0B, 0x0f}, // TCC15 {0x09, 0}, // TD0 {0x09, 1}, // TD1 {0x09, 2}, // TD2 {0x09, 3}, // TD3 {0x09, 4}, // TD4 {0x09, 5}, // TD5 {0x09, 6}, // TD6 {0x09, 7}, // TD7 {0x09, 8}, // TD8 {0x09, 9}, // TD9 {0x09, 0x0a}, // TD10 {0x09, 0x0b}, // TD11 {0x09, 0x0c}, // TD12 {0x09, 0x0d}, // TD13 {0x09, 0x0e}, // TD14 {0x09, 0x0f}, // TD15 {0x0A, 0}, // TCP0 {0x0A, 1}, // TCP1 {0x0A, 2}, // TCP2 {0x0A, 3}, // TCP3 {0x0A, 4}, // TCP4 {0x0A, 5}, // TCP5 {0x0A, 6}, // TCP6 {0x0A, 7}, // TCP7 {0x0A, 8}, // TCP8 {0x0A, 9}, // TCP9 {0x0A, 0x0a}, // TCP10 {0x0A, 0x0b}, // TCP11 {0x0A, 0x0c}, // TCP12 {0x0A, 0x0d}, // TCP13 {0x0A, 0x0e}, // TCP14 {0x0A, 0x0f}, // TCP15 {0x0F, 0}, // GDS {0x02, 0}, // VGT {0x01, 0}, // IA {0x15, 0}, // MC {0x10, 0}, // SRBM {0x18, 0}, // WD {0x16, 0}, // CPG {0x17, 0}, // CPC }}; // The number of counters per block has been increased for gfx9 but this table may not reflect all // of them // as compute may not use all of them. static constexpr std::array<std::pair<int, int>, 123> gfx9BlockIdPal = {{ {0x0E, 0}, // CB0 - 0 {0x0E, 1}, // CB1 - 1 {0x0E, 2}, // CB2 - 2 {0x0E, 3}, // CB3 - 3 {0x00, 0}, // CPF - 4 {0x0D, 0}, // DB0 - 5 {0x0D, 1}, // DB1 - 6 {0x0D, 2}, // DB2 - 7 {0x0D, 3}, // DB3 - 8 {0x11, 0}, // GRBM - 9 {0x12, 0}, // GRBMSE - 10 {0x03, 0}, // PA_SU - 11 {0x04, 0}, // PA_SC - 12 {0x05, 0}, // SPI - 13 {0x06, 0}, // SQ - 14 {0x06, 0}, // SQ_ES - 15 {0x06, 0}, // SQ_GS - 16 {0x06, 0}, // SQ_VS - 17 {0x06, 0}, // SQ_PS - 18 {0x06, 0}, // SQ_LS - 19 {0x06, 0}, // SQ_HS - 20 {0x06, 0}, // SQ_CS - 21 {0x07, 0}, // SX - 22 {0x08, 0}, // TA0 - 23 {0x08, 1}, // TA1 - 24 {0x08, 2}, // TA2 - 25 {0x08, 3}, // TA3 - 26 {0x08, 4}, // TA4 - 27 {0x08, 5}, // TA5 - 28 {0x08, 6}, // TA6 - 29 {0x08, 7}, // TA7 - 30 {0x08, 8}, // TA8 - 31 {0x08, 9}, // TA9 - 32 {0x08, 0x0a}, // TA10 - 33 {0x08, 0x0b}, // TA11 - 34 {0x08, 0x0c}, // TA12 - 35 {0x08, 0x0d}, // TA13 - 36 {0x08, 0x0e}, // TA14 - 37 {0x08, 0x0f}, // TA15 - 38 {0x0C, 0}, // TCA0 - 39 {0x0C, 1}, // TCA1 - 40 {0x0B, 0}, // TCC0 - 41 {0x0B, 1}, // TCC1 - 42 {0x0B, 2}, // TCC2 - 43 {0x0B, 3}, // TCC3 - 44 {0x0B, 4}, // TCC4 - 45 {0x0B, 5}, // TCC5 - 46 {0x0B, 6}, // TCC6 - 47 {0x0B, 7}, // TCC7 - 48 {0x0B, 8}, // TCC8 - 49 {0x0B, 9}, // TCC9 - 50 {0x0B, 0x0a}, // TCC10 - 51 {0x0B, 0x0b}, // TCC11 - 52 {0x0B, 0x0c}, // TCC12 - 53 {0x0B, 0x0d}, // TCC13 - 54 {0x0B, 0x0e}, // TCC14 - 55 {0x0B, 0x0f}, // TCC15 - 56 {0x09, 0}, // TD0 - 57 {0x09, 1}, // TD1 - 58 {0x09, 2}, // TD2 - 59 {0x09, 3}, // TD3 - 60 {0x09, 4}, // TD4 - 61 {0x09, 5}, // TD5 - 62 {0x09, 6}, // TD6 - 63 {0x09, 7}, // TD7 - 64 {0x09, 8}, // TD8 - 65 {0x09, 9}, // TD9 - 66 {0x09, 0x0a}, // TD10 - 67 {0x09, 0x0b}, // TD11 - 68 {0x09, 0x0c}, // TD12 - 69 {0x09, 0x0d}, // TD13 - 70 {0x09, 0x0e}, // TD14 - 71 {0x09, 0x0f}, // TD15 - 72 {0x0A, 0}, // TCP0 - 73 {0x0A, 1}, // TCP1 - 74 {0x0A, 2}, // TCP2 - 75 {0x0A, 3}, // TCP3 - 76 {0x0A, 4}, // TCP4 - 77 {0x0A, 5}, // TCP5 - 78 {0x0A, 6}, // TCP6 - 79 {0x0A, 7}, // TCP7 - 80 {0x0A, 8}, // TCP8 - 81 {0x0A, 9}, // TCP9 - 82 {0x0A, 0x0a}, // TCP10 - 83 {0x0A, 0x0b}, // TCP11 - 84 {0x0A, 0x0c}, // TCP12 - 85 {0x0A, 0x0d}, // TCP13 - 86 {0x0A, 0x0e}, // TCP14 - 87 {0x0A, 0x0f}, // TCP15 - 88 {0x0F, 0}, // GDS - 89 {0x02, 0}, // VGT - 90 {0x01, 0}, // IA - 91 {0x18, 0}, // WD - 92 {0x16, 0}, // CPG - 93 {0x17, 0}, // CPC - 94 {0x1A, 0}, // ATC - 95 {0x1B, 0}, // ATCL2 - 96 {0x1C, 0}, // MCVML2 - 97 {0x1D, 0}, // EA0 - 98 {0x1D, 1}, // EA1 - 99 {0x1D, 2}, // EA2 - 100 {0x1D, 3}, // EA3 - 101 {0x1D, 4}, // EA4 - 102 {0x1D, 5}, // EA5 - 103 {0x1D, 6}, // EA6 - 104 {0x1D, 7}, // EA7 - 105 {0x1D, 8}, // EA8 - 106 {0x1D, 9}, // EA9 - 107 {0x1D, 0x0a}, // EA10 - 108 {0x1D, 0x0b}, // EA11 - 109 {0x1D, 0x0c}, // EA12 - 110 {0x1D, 0x0d}, // EA13 - 111 {0x1D, 0x0e}, // EA14 - 112 {0x1D, 0x0f}, // EA15 - 113 {0x1E, 0}, // RPB - 114 {0x1F, 0}, // RMI0 - 115 {0x1F, 1}, // RMI1 - 116 {0x1F, 2}, // RMI2 - 117 {0x1F, 3}, // RMI3 - 118 {0x1F, 4}, // RMI4 - 119 {0x1F, 5}, // RMI5 - 120 {0x1F, 6}, // RMI6 - 121 {0x1F, 7}, // RMI7 - 122 }}; static constexpr std::array<std::pair<int, int>, 139> gfx10BlockIdPal = {{ {0x0E, 0}, // CB0 - 0 {0x0E, 1}, // CB1 - 1 {0x0E, 2}, // CB2 - 2 {0x0E, 3}, // CB3 - 3 {0x00, 0}, // CPF - 4 {0x0D, 0}, // DB0 - 5 {0x0D, 1}, // DB1 - 6 {0x0D, 2}, // DB2 - 7 {0x0D, 3}, // DB3 - 8 {0x11, 0}, // GRBM - 9 {0x12, 0}, // GRBMSE - 10 {0x03, 0}, // PA_SU - 11 {0x04, 0}, // PA_SC0 - 12 {0x04, 1}, // PA_SC1 - 13 {0x05, 0}, // SPI - 14 {0x06, 0}, // SQ - 15 {0x06, 0}, // SQ_ES - 16 {0x06, 0}, // SQ_GS - 17 {0x06, 0}, // SQ_VS - 18 {0x06, 0}, // SQ_PS - 19 {0x06, 0}, // SQ_LS - 20 {0x06, 0}, // SQ_HS - 21 {0x06, 0}, // SQ_CS - 22 {0x07, 0}, // SX - 23 {0x08, 0}, // TA0 - 24 {0x08, 1}, // TA1 - 25 {0x08, 2}, // TA2 - 26 {0x08, 3}, // TA3 - 27 {0x08, 4}, // TA4 - 28 {0x08, 5}, // TA5 - 29 {0x08, 6}, // TA6 - 30 {0x08, 7}, // TA7 - 31 {0x08, 8}, // TA8 - 32 {0x08, 9}, // TA9 - 33 {0x08, 0x0a}, // TA10 - 34 {0x08, 0x0b}, // TA11 - 35 {0x08, 0x0c}, // TA12 - 36 {0x08, 0x0d}, // TA13 - 37 {0x08, 0x0e}, // TA14 - 38 {0x08, 0x0f}, // TA15 - 39 {0x09, 0}, // TD0 - 40 {0x09, 1}, // TD1 - 41 {0x09, 2}, // TD2 - 42 {0x09, 3}, // TD3 - 43 {0x09, 4}, // TD4 - 44 {0x09, 5}, // TD5 - 45 {0x09, 6}, // TD6 - 46 {0x09, 7}, // TD7 - 47 {0x09, 8}, // TD8 - 48 {0x09, 9}, // TD9 - 49 {0x09, 0x0a}, // TD10 - 50 {0x09, 0x0b}, // TD11 - 51 {0x09, 0x0c}, // TD12 - 52 {0x09, 0x0d}, // TD13 - 53 {0x09, 0x0e}, // TD14 - 54 {0x09, 0x0f}, // TD15 - 55 {0x0A, 0}, // TCP0 - 56 {0x0A, 1}, // TCP1 - 57 {0x0A, 2}, // TCP2 - 58 {0x0A, 3}, // TCP3 - 59 {0x0A, 4}, // TCP4 - 60 {0x0A, 5}, // TCP5 - 61 {0x0A, 6}, // TCP6 - 62 {0x0A, 7}, // TCP7 - 63 {0x0A, 8}, // TCP8 - 64 {0x0A, 9}, // TCP9 - 65 {0x0A, 0x0a}, // TCP10 - 66 {0x0A, 0x0b}, // TCP11 - 67 {0x0A, 0x0c}, // TCP12 - 68 {0x0A, 0x0d}, // TCP13 - 69 {0x0A, 0x0e}, // TCP14 - 70 {0x0A, 0x0f}, // TCP15 - 71 {0x0F, 0}, // GDS - 72 {0x16, 0}, // CPG - 73 {0x17, 0}, // CPC - 74 {0x1A, 0}, // ATC - 75 {0x1B, 0}, // ATCL2 - 76 {0x1C, 0}, // MCVML2 - 77 {0x1D, 0}, // EA0 - 78 {0x1D, 1}, // EA1 - 79 {0x1D, 2}, // EA2 - 80 {0x1D, 3}, // EA3 - 81 {0x1D, 4}, // EA4 - 82 {0x1D, 5}, // EA5 - 83 {0x1D, 6}, // EA6 - 84 {0x1D, 7}, // EA7 - 85 {0x1D, 8}, // EA8 - 86 {0x1D, 9}, // EA9 - 87 {0x1D, 0x0a}, // EA10 - 88 {0x1D, 0x0b}, // EA11 - 89 {0x1D, 0x0c}, // EA12 - 90 {0x1D, 0x0d}, // EA13 - 91 {0x1D, 0x0e}, // EA14 - 92 {0x1D, 0x0f}, // EA15 - 93 {0x1E, 0}, // RPB - 94 {0x1F, 0}, // RMI0 - 95 {0x1F, 1}, // RMI1 - 96 {0x21, 0}, // GE - 97 {0x22, 0}, // GL1A - 98 {0x23, 0}, // GL1C - 99 {0x24, 0}, // GL1CG0 - 100 {0x24, 1}, // GL1CG1 - 101 {0x24, 2}, // GL1CG2 - 102 {0x24, 3}, // GL1CG3 - 103 {0x25, 0}, // GL2A0 - 104 {0x25, 1}, // GL2A1 - 105 {0x25, 2}, // GL2A2 - 106 {0x25, 3}, // GL2A3 - 107 {0x26, 0}, // GL2C0 - 108 {0x26, 1}, // GL2C1 - 109 {0x26, 2}, // GL2C2 - 110 {0x26, 3}, // GL2C3 - 111 {0x26, 4}, // GL2C4 - 112 {0x26, 5}, // GL2C5 - 113 {0x26, 6}, // GL2C6 - 114 {0x26, 7}, // GL2C7 - 115 {0x26, 8}, // GL2C8 - 116 {0x26, 9}, // GL2C9 - 117 {0x26, 0x0a}, // GL2C10 - 118 {0x26, 0x0b}, // GL2C11 - 119 {0x26, 0x0c}, // GL2C12 - 120 {0x26, 0x0d}, // GL2C13 - 121 {0x26, 0x0e}, // GL2C14 - 122 {0x26, 0x0f}, // GL2C15 - 123 {0x26, 0x10}, // GL2C16 - 124 {0x26, 0x11}, // GL2C17 - 125 {0x26, 0x12}, // GL2C18 - 126 {0x26, 0x13}, // GL2C19 - 127 {0x26, 0x14}, // GL2C20 - 128 {0x26, 0x15}, // GL2C21 - 129 {0x26, 0x16}, // GL2C22 - 130 {0x26, 0x17}, // GL2C23 - 131 {0x27, 0}, // CHA - 132 {0x28, 0}, // CHC - 133 {0x29, 0}, // CHCG - 134 {0x2A, 0}, // GUS - 135 {0x2B, 0}, // GCR - 136 {0x2C, 0}, // PH - 137 {0x2C, 0}, // UTCL1 - 138 }}; void PerfCounter::convertInfo() { switch (dev().ipLevel()) { case Pal::GfxIpLevel::GfxIp7: if (info_.blockIndex_ < ciBlockIdOrcaToPal.size()) { auto p = ciBlockIdOrcaToPal[info_.blockIndex_]; info_.blockIndex_ = std::get<0>(p); info_.counterIndex_ = std::get<1>(p); } break; case Pal::GfxIpLevel::GfxIp8: if (info_.blockIndex_ < viBlockIdOrcaToPal.size()) { auto p = viBlockIdOrcaToPal[info_.blockIndex_]; info_.blockIndex_ = std::get<0>(p); info_.counterIndex_ = std::get<1>(p); } break; case Pal::GfxIpLevel::GfxIp9: if (info_.blockIndex_ < gfx9BlockIdPal.size()) { auto p = gfx9BlockIdPal[info_.blockIndex_]; info_.blockIndex_ = std::get<0>(p); info_.counterIndex_ = std::get<1>(p); } break; case Pal::GfxIpLevel::GfxIp10_1: case Pal::GfxIpLevel::GfxIp10_3: if (info_.blockIndex_ < gfx10BlockIdPal.size()) { auto p = gfx10BlockIdPal[info_.blockIndex_]; info_.blockIndex_ = std::get<0>(p); info_.counterIndex_ = std::get<1>(p); } break; default: Unimplemented(); break; } assert(info_.blockIndex_ < blockIdToIndexSelect.size()); info_.indexSelect_ = blockIdToIndexSelect.at(info_.blockIndex_); } PerfCounter::~PerfCounter() { if (palRef_ == nullptr) { return; } // Release the counter reference object palRef_->release(); } bool PerfCounter::create() { palRef_->retain(); // Initialize the counter Pal::PerfCounterInfo counterInfo = {}; counterInfo.counterType = Pal::PerfCounterType::Global; counterInfo.block = static_cast<Pal::GpuBlock>(info_.blockIndex_); counterInfo.eventId = info_.eventIndex_; Pal::PerfExperimentProperties perfExpProps; Pal::Result result; result = dev().iDev()->GetPerfExperimentProperties(&perfExpProps); if (result != Pal::Result::Success) { return false; } const auto& blockProps = perfExpProps.blocks[static_cast<uint32_t>(counterInfo.block)]; uint32_t counter_start, counter_step; switch (info_.indexSelect_) { case PCIndexSelect::ShaderEngine: case PCIndexSelect::None: counter_start = 0; counter_step = 1; break; case PCIndexSelect::ShaderArray: if (info_.counterIndex_ >= (dev().properties().gfxipProperties.shaderCore.numShaderArrays * dev().properties().gfxipProperties.shaderCore.numShaderEngines)) { return true; } counter_start = info_.counterIndex_; counter_step = dev().properties().gfxipProperties.shaderCore.numShaderArrays * dev().properties().gfxipProperties.shaderCore.numShaderEngines; break; case PCIndexSelect::ComputeUnit: if (info_.counterIndex_ >= dev().properties().gfxipProperties.shaderCore.maxCusPerShaderArray) { return true; } counter_start = info_.counterIndex_; counter_step = dev().properties().gfxipProperties.shaderCore.maxCusPerShaderArray; break; case PCIndexSelect::Instance: counter_start = info_.counterIndex_; counter_step = blockProps.instanceCount; break; default: assert(0 && "Unknown indexSelect_"); return true; } for (uint32_t i = counter_start; i < blockProps.instanceCount; i += counter_step) { counterInfo.instance = i; result = iPerf()->AddCounter(counterInfo); if (result == Pal::Result::Success) { index_.push_back(palRef_->getPalCounterIndex()); } else { // Get here when there's no HW PerfCounter matching the counterInfo assert(0 && "AddCounter() failed"); } } return true; } uint64_t PerfCounter::getInfo(uint64_t infoType) const { switch (infoType) { case CL_PERFCOUNTER_GPU_BLOCK_INDEX: { // Return the GPU block index return info()->blockIndex_; } case CL_PERFCOUNTER_GPU_COUNTER_INDEX: { // Return the GPU counter index return info()->counterIndex_; } case CL_PERFCOUNTER_GPU_EVENT_INDEX: { // Return the GPU event index return info()->eventIndex_; } case CL_PERFCOUNTER_DATA: { return palRef_->result(index_); } default: LogError("Wrong PerfCounter::getInfo parameter"); } return 0; } } // namespace pal
33.6267
152
0.474489
devurandom
3da14a42571d935284d2b3c5246050a0b6bfe644
16,167
cc
C++
lib/fromfile.cc
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
null
null
null
lib/fromfile.cc
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
null
null
null
lib/fromfile.cc
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
null
null
null
// -*- related-file-name: "../include/click/fromfile.hh"; c-basic-offset: 4 -*- /* * fromfile.{cc,hh} -- provides convenient, fast access to files * Eddie Kohler * * Copyright (c) 1999-2000 Massachusetts Institute of Technology * Copyright (c) 2001-2003 International Computer Science Institute * Copyright (c) 2004-2007 The Regents of the University of California * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/fromfile.hh> #include <click/args.hh> #include <click/error.hh> #include <click/element.hh> #include <click/straccum.hh> #include <click/userutils.hh> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifdef ALLOW_MMAP # include <sys/mman.h> #endif CLICK_DECLS FromFile::FromFile() : _fd(-1), #if !CLICK_PACKET_USE_DPDK _buffer(0), _data_packet(0), #endif #ifdef ALLOW_MMAP _mmap(true), #endif _filename(), _pipe(0), _landmark_pattern("%f"), _lineno(0) { } int FromFile::configure_keywords(Vector<String> &conf, Element *e, ErrorHandler *errh) { #ifdef ALLOW_MMAP bool mmap = _mmap; #else bool mmap = false; #endif if (Args(e, errh).bind(conf) .read("MMAP", mmap) .consume() < 0) return -1; #ifdef ALLOW_MMAP _mmap = mmap; #else if (mmap) errh->warning("%<MMAP true%> is not supported on this platform"); #endif return 0; } String FromFile::print_filename() const { if (!_filename || _filename == "-") return String::make_stable("<stdin>", 7); else return _filename; } String FromFile::landmark(const String &landmark_pattern) const { StringAccum sa; const char *e = landmark_pattern.end(); for (const char *s = landmark_pattern.begin(); s < e; s++) if (s < e - 1 && s[0] == '%' && s[1] == 'f') { sa << print_filename(); s++; } else if (s < e - 1 && s[0] == '%' && s[1] == 'l') { sa << _lineno; s++; } else if (s < e - 1 && s[0] == '%' && s[1] == '%') { sa << '%'; s++; } else sa << *s; return sa.take_string(); } int FromFile::error(ErrorHandler *errh, const char *format, ...) const { if (!errh) errh = ErrorHandler::default_handler(); va_list val; va_start(val, format); int r = errh->xmessage(landmark(), ErrorHandler::e_error, format, val); va_end(val); return r; } int FromFile::warning(ErrorHandler *errh, const char *format, ...) const { if (!errh) errh = ErrorHandler::default_handler(); va_list val; va_start(val, format); int r = errh->xmessage(landmark(), ErrorHandler::e_warning_annotated, format, val); va_end(val); return r; } #ifdef ALLOW_MMAP static void munmap_destructor(unsigned char *data, size_t amount, void*) { if (munmap((caddr_t)data, amount) < 0) click_chatter("FromFile: munmap: %s", strerror(errno)); } int FromFile::read_buffer_mmap(ErrorHandler *errh) { if (_mmap_unit == 0) { size_t page_size = getpagesize(); _mmap_unit = (WANT_MMAP_UNIT / page_size) * page_size; _mmap_off = 0; // don't report most errors on the first time through errh = ErrorHandler::silent_handler(); } // get length of file struct stat statbuf; if (fstat(_fd, &statbuf) < 0) return error(errh, "stat: %s", strerror(errno)); // check for end of file // But return -1 if we have not mmaped before: it might be a pipe, not // true EOF. if (_mmap_off >= statbuf.st_size) return (_mmap_off == 0 ? -1 : 0); // actually mmap _len = _mmap_unit; if ((off_t)(_mmap_off + _len) > statbuf.st_size) _len = statbuf.st_size - _mmap_off; void *mmap_data = mmap(0, _len, PROT_READ, MAP_SHARED, _fd, _mmap_off); if (mmap_data == MAP_FAILED) return error(errh, "mmap: %s", strerror(errno)); _data_packet = Packet::make((unsigned char *)mmap_data, _len, munmap_destructor, 0); _buffer = _data_packet->data(); _file_offset = _mmap_off; _mmap_off += _len; # ifdef HAVE_MADVISE // don't care about errors (void) madvise((caddr_t)mmap_data, _len, MADV_SEQUENTIAL); # endif return 1; } #endif int FromFile::read_buffer(ErrorHandler *errh) { #if !CLICK_PACKET_USE_DPDK if (_data_packet) { _data_packet->kill(); } _data_packet = 0; #endif _file_offset += _len; _pos -= _len; // adjust _pos by _len: it might validly point // beyond _len _len = 0; if (_fd < 0) { return _fd == -1 ? -EBADF : _len; } #ifdef ALLOW_MMAP if (_mmap) { int result = read_buffer_mmap(errh); if (result >= 0) return result; // else, try a regular read _mmap = false; (void) lseek(_fd, _mmap_off, SEEK_SET); _len = 0; } #endif #if !CLICK_PACKET_USE_DPDK _data_packet = Packet::make(0, 0, BUFFER_SIZE, 0); if (!_data_packet) return error(errh, strerror(ENOMEM)); _buffer = _data_packet->data(); unsigned char *data = _data_packet->data(); #else unsigned char *data = _buffer; #endif // assert(_data_packet->headroom() == 0); while (_len < BUFFER_SIZE) { ssize_t got = ::read(_fd, data + _len, BUFFER_SIZE - _len); if (got > 0) _len += got; else if (got == 0) // premature end of file return _len; else if (got < 0 && errno != EINTR && errno != EAGAIN) return error(errh, strerror(errno)); } return _len; } int FromFile::read(void *vdata, uint32_t dlen, ErrorHandler *errh) { unsigned char *data = reinterpret_cast<unsigned char *>(vdata); uint32_t dpos = 0; while (dpos < dlen) { if (_pos < _len) { uint32_t howmuch = dlen - dpos; if (howmuch > _len - _pos) howmuch = _len - _pos; memcpy(data + dpos, _buffer + _pos, howmuch); dpos += howmuch; _pos += howmuch; } if (dpos < dlen && read_buffer(errh) <= 0) return dpos; } return dlen; } int FromFile::read_line(String &result, ErrorHandler *errh, bool temporary) { // first, try to read a line from the current buffer const unsigned char *s = _buffer + _pos; const unsigned char *e = _buffer + _len; while (s < e && *s != '\n' && *s != '\r') { s++; } if (s < e && (*s == '\n' || s + 1 < e)) { s += (*s == '\r' && s[1] == '\n' ? 2 : 1); int new_pos = s - _buffer; if (temporary) result = String::make_stable((const char *) (_buffer + _pos), new_pos - _pos); else result = String((const char *) (_buffer + _pos), new_pos - _pos); _pos = new_pos; _lineno++; return 1; } // otherwise, build up a line StringAccum sa; sa.append(_buffer + _pos, _len - _pos); while (1) { int errcode = read_buffer(errh); if (errcode < 0 || (errcode == 0 && !sa)) return errcode; // check doneness bool done; if (sa && sa.back() == '\r') { if (_len > 0 && _buffer[0] == '\n') sa << '\n', _pos++; done = true; } else if (errcode == 0) { _pos = _len; done = true; } else { s = _buffer, e = _buffer + _len; while (s < e && *s != '\n' && *s != '\r') s++; if (s < e && (*s == '\n' || s + 1 < e)) { s += (*s == '\r' && s[1] == '\n' ? 2 : 1); sa.append(_buffer, s - _buffer); _pos = s - _buffer; done = true; } else { sa.append(_buffer, _len); done = false; } } if (done) { result = sa.take_string(); _lineno++; return 1; } } } int FromFile::peek_line(String &result, ErrorHandler *errh, bool temporary) { int before_pos = _pos; int retval = read_line(result, errh, temporary); if (retval > 0) { _pos = before_pos; _lineno--; } return retval; } int FromFile::reset(off_t want, ErrorHandler* errh) { #ifdef ALLOW_MMAP _mmap_unit = 0; _mmap_off = 0; #else lseek(_fd, 0, SEEK_SET); #endif _file_offset = 0; _pos = _len = 0; int result = read_buffer(errh); _pos = want; return result; } int FromFile::seek(off_t want, ErrorHandler* errh) { if (want >= _file_offset && want < (off_t) (_file_offset + _len)) { _pos = want; return 0; } #ifdef ALLOW_MMAP if (_mmap) { _mmap_off = (want / _mmap_unit) * _mmap_unit; _pos = _len + want - _mmap_off; _file_offset = 0; // Is that correct? // TODO: fix lineno return 0; } #endif if (_fd < 0) return _fd == -1 ? -EBADF : 0; // check length of file struct stat statbuf; if (fstat(_fd, &statbuf) < 0) return error(errh, "stat: %s", strerror(errno)); if (S_ISREG(statbuf.st_mode) && statbuf.st_size && want > statbuf.st_size) return errh->error("FILEPOS out of range"); // try to seek if (lseek(_fd, want, SEEK_SET) != (off_t) -1) { _pos = _len; _file_offset = want - _len; return 0; } // otherwise, read data while ((off_t) (_file_offset + _len) < want && _len) if (read_buffer(errh) < 0) return -1; _pos = want - _file_offset; return 0; } int FromFile::set_data(const String& data, ErrorHandler* errh) { #if CLICK_PACKET_USE_DPDK assert(false); #else assert(_fd == -1 && !_data_packet); _data_packet = Packet::make(0, data.data(), data.length(), 0); if (!_data_packet) return error(errh, strerror(ENOMEM)); _buffer = _data_packet->data(); _file_offset = 0; _pos = 0; _len = data.length(); _filename = "<data>"; _fd = -2; #endif return 0; } int FromFile::initialize(ErrorHandler *errh, bool allow_nonexistent) { // if set_data, initialize is noop if (_fd == -2) return 0; // must set for allow_nonexistent case _pos = _len = 0; // open file if (!_filename || _filename == "-") _fd = STDIN_FILENO; else _fd = open(_filename.c_str(), O_RDONLY); if (_fd < 0) { int e = -errno; if (e != -ENOENT || !allow_nonexistent) errh->error("%s: %s", print_filename().c_str(), strerror(-e)); return e; } retry_file: #ifdef ALLOW_MMAP _mmap_unit = 0; #endif _file_offset = 0; _pos = _len = 0; int result = read_buffer(errh); if (result < 0) return -1; else if (result == 0) { if (!allow_nonexistent) error(errh, "empty file"); return -ENOENT; } // check for a gziped or bzip2d dump if (_fd == STDIN_FILENO || _pipe) /* cannot handle gzip or bzip2 */; else if (compressed_data(_buffer, _len)) { close(_fd); _fd = -1; if (!(_pipe = open_uncompress_pipe(_filename, _buffer, _len, errh))) return -1; _fd = fileno(_pipe); goto retry_file; } return 0; } void FromFile::take_state(FromFile &o, ErrorHandler *errh) { #if CLICK_PACKET_USE_DPDK assert(false); #else _fd = o._fd; o._fd = -1; _pipe = o._pipe; o._pipe = 0; _buffer = o._buffer; _pos = o._pos; _len = o._len; _data_packet = o._data_packet; o._data_packet = 0; #ifdef ALLOW_MMAP if (_mmap != o._mmap) errh->warning("different MMAP states"); _mmap = o._mmap; _mmap_unit = o._mmap_unit; _mmap_off = o._mmap_off; #else (void) errh; #endif _file_offset = o._file_offset; #endif } void FromFile::cleanup() { if (_pipe) pclose(_pipe); else if (_fd >= 0 && _fd != STDIN_FILENO) close(_fd); _pipe = 0; _fd = -1; #if CLICK_PACKET_USE_DPDK #else if (_data_packet) _data_packet->kill(); _data_packet = 0; #endif } const uint8_t * FromFile::get_aligned(size_t size, void *buffer, ErrorHandler *errh) { // we may need to read bits of the file if (_pos + size <= _len) { const uint8_t *chunk = _buffer + _pos; _pos += size; #if HAVE_INDIFFERENT_ALIGNMENT return reinterpret_cast<const uint8_t *>(chunk); #else // make a copy if required for alignment if (((uintptr_t)(chunk) & 3) == 0) return reinterpret_cast<const uint8_t *>(chunk); else { memcpy(buffer, chunk, size); return reinterpret_cast<uint8_t *>(buffer); } #endif } else if (read(buffer, size, errh) == (int)size) return reinterpret_cast<uint8_t *>(buffer); else return 0; } const uint8_t * FromFile::get_unaligned(size_t size, void *buffer, ErrorHandler *errh) { // we may need to read bits of the file if (_pos + size <= _len) { const uint8_t *chunk = _buffer + _pos; _pos += size; return reinterpret_cast<const uint8_t *>(chunk); } else if (read(buffer, size, errh) == (int)size) return reinterpret_cast<uint8_t *>(buffer); else return 0; } String FromFile::get_string(size_t size, ErrorHandler *errh) { // we may need to read bits of the file if (_pos + size <= _len) { const uint8_t *chunk = _buffer + _pos; _pos += size; return String::make_stable((const char *) chunk, size); } else { String s = String::make_uninitialized(size); if (read(s.mutable_data(), size, errh) == (int) size) return s; else return String(); } } Packet * FromFile::get_packet(size_t size, uint32_t sec, uint32_t subsec, ErrorHandler *errh) { #if CLICK_PACKET_USE_DPDK #else if (_pos + size <= _len) { if (Packet *p = _data_packet->clone()) { p->shrink_data(_buffer + _pos, size); p->timestamp_anno().assign(sec, subsec); _pos += size; return p; } } else #endif { if (WritablePacket *p = Packet::make(0, 0, size, 0)) { if (read(p->data(), size, errh) < (int)size) { p->kill(); return 0; } else { p->timestamp_anno().assign(sec, subsec); return p; } } } error(errh, strerror(ENOMEM)); return 0; } Packet * FromFile::get_packet_from_data(const void *data_void, size_t data_size, size_t size, uint32_t sec, uint32_t subsec, ErrorHandler *errh) { const uint8_t *data = reinterpret_cast<const uint8_t *>(data_void); #if !CLICK_PACKET_USE_DPDK if (data >= _buffer && data + size <= _buffer + _len) { if (Packet *p = _data_packet->clone()) { p->shrink_data(data, size); p->timestamp_anno().assign(sec, subsec); return p; } } else #endif { if (WritablePacket *p = Packet::make(0, 0, size, 0)) { memcpy(p->data(), data, data_size); if (data_size < size && read(p->data() + data_size, size - data_size, errh) != (int)(size - data_size)) { p->kill(); return 0; } p->timestamp_anno().assign(sec, subsec); return p; } } error(errh, strerror(ENOMEM)); return 0; } String FromFile::filename_handler(Element *e, void *thunk) { FromFile *fd = reinterpret_cast<FromFile *>((uint8_t *)e + (intptr_t)thunk); return fd->print_filename(); } String FromFile::filesize_handler(Element *e, void *thunk) { FromFile *fd = reinterpret_cast<FromFile *>((uint8_t *)e + (intptr_t)thunk); struct stat s; if (fd->_fd >= 0 && fstat(fd->_fd, &s) >= 0 && S_ISREG(s.st_mode)) return String(s.st_size); else return "-"; } String FromFile::filepos_handler(Element* e, void* thunk) { FromFile* fd = reinterpret_cast<FromFile*>((uint8_t*)e + (intptr_t)thunk); return String(fd->_file_offset + fd->_pos); } int FromFile::filepos_write_handler(const String& str, Element* e, void* thunk, ErrorHandler* errh) { off_t offset; if (!cp_file_offset(cp_uncomment(str), &offset)) return errh->error("argument must be file offset"); FromFile* fd = reinterpret_cast<FromFile*>((uint8_t*)e + (intptr_t)thunk); return fd->seek(offset, errh); } void FromFile::add_handlers(Element* e, bool filepos_writable) const { intptr_t offset = (const uint8_t *)this - (const uint8_t *)e; e->add_read_handler("filename", filename_handler, (void *)offset); e->add_read_handler("filesize", filesize_handler, (void *)offset); e->add_read_handler("filepos", filepos_handler, (void *)offset); if (filepos_writable) e->add_write_handler("filepos", filepos_write_handler, (void *)offset); } CLICK_ENDDECLS
24.022288
135
0.623616
BorisPis
3da5cdd56c3e5b293637dbd764dbed8d1a4f6ebc
1,737
cpp
C++
PlatformIO/Peak-ESP32-fw/src/App/Pages/SystemInfos/SystemInfosModel.cpp
Xinyuan-LilyGO/T-Watch-2019-reissue-peak
9bc2b065e652ce78ef1bcff50a250d6bbea866e1
[ "MIT" ]
null
null
null
PlatformIO/Peak-ESP32-fw/src/App/Pages/SystemInfos/SystemInfosModel.cpp
Xinyuan-LilyGO/T-Watch-2019-reissue-peak
9bc2b065e652ce78ef1bcff50a250d6bbea866e1
[ "MIT" ]
null
null
null
PlatformIO/Peak-ESP32-fw/src/App/Pages/SystemInfos/SystemInfosModel.cpp
Xinyuan-LilyGO/T-Watch-2019-reissue-peak
9bc2b065e652ce78ef1bcff50a250d6bbea866e1
[ "MIT" ]
1
2021-12-22T08:32:14.000Z
2021-12-22T08:32:14.000Z
#include "SystemInfosModel.h" #include <stdio.h> using namespace Page; void SystemInfosModel::Init() { account = new Account("SystemInfosModel", AccountSystem::Broker(), 0, this); account->Subscribe("IMU"); account->Subscribe("Power"); account->Subscribe("Storage"); } void SystemInfosModel::Deinit() { if (account) { delete account; account = nullptr; } } void SystemInfosModel::GetIMUInfo( char* info, uint32_t len ) { HAL::IMU_Info_t imu; account->Pull("IMU", &imu, sizeof(imu)); snprintf( info, len, "%.3f\n%.3f\n%.3f\n%.3f\n%.3f\n%.3f\n%.3f\n%.3f\n%.3f", imu.ax, imu.ay, imu.az, imu.gx, imu.gy, imu.gz, imu.mx, imu.my, imu.mz ); } void SystemInfosModel::GetBatteryInfo( int* usage, float* voltage, char* state, uint32_t len ) { HAL::Power_Info_t power; account->Pull("Power", &power, sizeof(power)); *usage = power.usage; *voltage = power.voltage / 1000.0f; strncpy(state, power.isCharging ? "CHARGE" : "DISCHARGE", len); } void SystemInfosModel::GetStorageInfo( bool* detect, char* usage, uint32_t len ) { AccountSystem::Storage_Basic_Info_t info; account->Pull("Storage", &info, sizeof(info)); *detect = info.isDetect; snprintf( usage, len, "%0.1f GB", info.totalSizeMB / 1024.0f ); } void Page::SystemInfosModel::GetJointsInfo(char* data, uint32_t len) { snprintf( data, len, "0\n0\n90\n0\n0\n0\n" ); } void Page::SystemInfosModel::GetPose6DInfo(char* data, uint32_t len) { snprintf( data, len, "222\n0\n307\n0\n90\n0\n" ); }
19.087912
80
0.583765
Xinyuan-LilyGO
3da5df954d2062ca7f6b835e0ba3ad92ea638dff
3,898
cc
C++
src/native_client_sdk/src/examples/pong/pong_instance.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
src/native_client_sdk/src/examples/pong/pong_instance.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
native_client_sdk/src/examples/pong/pong_instance.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdio.h> #include <string.h> #include <cmath> #include <string> #include "ppapi/cpp/completion_callback.h" #include "ppapi/cpp/input_event.h" #include "ppapi/cpp/rect.h" #include "ppapi/cpp/var.h" #include "pong_instance.h" #include "pong_view.h" namespace { const uint32_t kUpArrow = 0x26; const uint32_t kDownArrow = 0x28; const int32_t kMaxPointsAllowed = 256; const int32_t kUpdateInterval = 17; // milliseconds const char kResetScoreMethodId[] = "resetScore"; } // namespace PongInstance::PongInstance(PP_Instance instance) : pp::Instance(instance), factory_(this), model_(NULL), view_(NULL), is_initial_view_change_(true) { // Request to receive input events. RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE | PP_INPUTEVENT_CLASS_KEYBOARD); } PongInstance::~PongInstance() { delete right_paddle_input_; delete left_paddle_input_; delete view_; delete model_; } bool PongInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { model_ = new PongModel(this); view_ = new PongView(model_); left_paddle_input_ = new PongInputKeyboard(this); right_paddle_input_ = new PongInputAI(); UpdateScoreDisplay(); return true; } void PongInstance::DidChangeView(const pp::View& view) { if (!view_->DidChangeView(this, view, is_initial_view_change_)) { PostMessage(pp::Var( "ERROR DidChangeView failed. Could not bind graphics?")); return; } model_->SetCourtSize(view_->GetSize()); model_->ResetPositions(); if (is_initial_view_change_) { ScheduleUpdate(); is_initial_view_change_ = false; } } bool PongInstance::HandleInputEvent(const pp::InputEvent& event) { if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP || event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN) { // By notifying the browser mouse clicks are handled, the application window // is able to get focus and receive key events. return true; } else if (event.GetType() == PP_INPUTEVENT_TYPE_KEYUP) { pp::KeyboardInputEvent key = pp::KeyboardInputEvent(event); key_map_[key.GetKeyCode()] = false; return true; } else if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) { pp::KeyboardInputEvent key = pp::KeyboardInputEvent(event); key_map_[key.GetKeyCode()] = true; return true; } return false; } void PongInstance::HandleMessage(const pp::Var& var_message) { if (!var_message.is_string()) return; std::string message = var_message.AsString(); if (message == kResetScoreMethodId) { ResetScore(); } } void PongInstance::OnScoreChanged() { if (model_->left_score() > kMaxPointsAllowed || model_->right_score() > kMaxPointsAllowed) { ResetScore(); return; } UpdateScoreDisplay(); } void PongInstance::OnPlayerScored() { model_->ResetPositions(); } bool PongInstance::IsKeyDown(int key_code) { return key_map_[key_code]; } void PongInstance::ScheduleUpdate() { pp::Module::Get()->core()->CallOnMainThread( kUpdateInterval, factory_.NewCallback(&PongInstance::UpdateCallback)); } void PongInstance::UpdateCallback(int32_t result) { // This is the game loop; UpdateCallback schedules another call to itself to // occur kUpdateInterval milliseconds later. ScheduleUpdate(); MoveDirection left_move = left_paddle_input_->GetMove(*model_, true); MoveDirection right_move = right_paddle_input_->GetMove(*model_, false); model_->Update(left_move, right_move); } void PongInstance::ResetScore() { model_->SetScore(0, 0); } void PongInstance::UpdateScoreDisplay() { char buffer[100]; snprintf(&buffer[0], sizeof(buffer), "You %d: Computer %d", model_->left_score(), model_->right_score()); PostMessage(pp::Var(buffer)); }
27.258741
80
0.718061
jxjnjjn
3da62616228d30be6861f14794bbb41450fd7aec
5,152
hpp
C++
enduser/netmeeting/ui/wb/bmpobj.hpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
enduser/netmeeting/ui/wb/bmpobj.hpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
enduser/netmeeting/ui/wb/bmpobj.hpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// // BITMAPOBJ.HPP // Bitmap objects: // // Copyright Microsoft 1998- // #ifndef __BITMAPOBJ_HPP_ #define __BITMAPOBJ_HPP_ typedef struct COLOREDICON { HICON hIcon; COLORREF color; } COLORED_ICON; #define MAX_BITMAP_DATA 8192 UINT GetBitmapDestinationAddress(BitmapDestinationAddress *destinationAddress, PUINT workspaceHandle, PUINT planeID); #define NonStandard24BitBitmapID "Bitmap24\0" typedef struct tagBITMAP_DATA { // // Data Buffer // BOOL m_bdataCheckpoint; UINT m_padBits; UINT m_length; } BITMAPDATA, *PBITMAPDATA; class BitmapObj : public T126Obj { public: BitmapObj (BitmapCreatePDU * pbitmapCreatePDU); void Continue (BitmapCreateContinuePDU * pbitmapCreateContinuePDU); BitmapObj (UINT); ~BitmapObj( void ); void Draw(HDC hDC = NULL, BOOL bForcedDraw = FALSE, BOOL bPrinting = FALSE); BOOL CheckReallyHit(LPCRECT pRectHit){return RectangleHit(FALSE, pRectHit);} void FromScreenArea(LPCRECT lprcScreen); BOOL HasFillColor(void){return FALSE;} void SetFillColor(COLORREF cr, BOOL isPresent){} BOOL GetFillColor(COLORREF * pcr){return FALSE;} BOOL GetFillColor(RGBTRIPLE* prgb){return FALSE;} void SetPenColor(COLORREF cr, BOOL isPresent){} BOOL GetPenColor(COLORREF * pcr) {return FALSE;} BOOL GetPenColor(RGBTRIPLE* prgb){return FALSE;} void SetViewHandle(UINT viewHandle){}; void DeleteSavedBitmap(void); void BitmapEditObj ( BitmapEditPDU * pbitmapEditPDU ); void GetBitmapAttrib(PBitmapCreatePDU_attributes pAttribPDU); void SetBitmapAttrib(PBitmapCreatePDU_attributes *pattributes); void AllocateAttrib(PBitmapCreatePDU_attributes *pAttributes); // // PDU stuff // void CreateBitmapCreatePDU(CWBOBLIST * pCreatePDUList); void CreateBitmapEditPDU(BitmapEditPDU *pEditPDU); void CreateBitmapDeletePDU(BitmapDeletePDU *pDeletePDU); void CreateNonStandard24BitBitmap(BitmapCreatePDU * pBitmapCreatePDU); LPBITMAPINFOHEADER m_lpbiImage; // local copy of the DIB LPBITMAPINFOHEADER m_lpBitMask; // Bitmask for transparent bitmaps. LPBYTE m_lpTransparencyMask; UINT m_SizeOfTransparencyMask; BOOL m_fMoreToFollow; // // Masks 0x000000007 (BitmapAttribute_viewState_chosen = 1... BitmapAttribute_transparencyMask_chosen = 3) // void ChangedViewState(void){m_dwChangedAttrib |= (1 << (BitmapAttribute_viewState_chosen-1)) | BitmapEditPDU_attributeEdits_present;}; void ChangedZOrder(void){m_dwChangedAttrib |= (1 << (BitmapAttribute_zOrder_chosen-1)) | BitmapEditPDU_attributeEdits_present;}; void ChangedTransparencyMask(void){m_dwChangedAttrib |= (1 << (BitmapAttribute_transparencyMask_chosen-1)) | BitmapEditPDU_attributeEdits_present;}; BOOL HasViewStateChanged(void){return (m_dwChangedAttrib & ( 1 << (BitmapAttribute_viewState_chosen-1)));}; BOOL HasZOrderChanged(void){return (m_dwChangedAttrib & ( 1 << (BitmapAttribute_zOrder_chosen-1)));}; BOOL HasTransparencyMaskChanged(void){return (m_dwChangedAttrib & ( 1 << (BitmapAttribute_transparencyMask_chosen-1)));}; // // Masks 0x000000070 (BitmapEditPDU_scalingEdit_present = 0x10... BitmapEditPDU_anchorPointEdit_present = 0x40) // void ChangedAnchorPoint(void){ m_dwChangedAttrib |= BitmapEditPDU_anchorPointEdit_present;} void ChangedRegionOfInterest(void){ m_dwChangedAttrib |= bitmapRegionOfInterestEdit_present;} void ChangedScaling(void){ m_dwChangedAttrib |= BitmapEditPDU_scalingEdit_present;} BOOL HasAnchorPointChanged(void){ return (m_dwChangedAttrib & BitmapEditPDU_anchorPointEdit_present);} BOOL HasRegionOfInterestChanged(void){ return (m_dwChangedAttrib & bitmapRegionOfInterestEdit_present);} BOOL HasScalingChanged(void){ return (m_dwChangedAttrib & BitmapEditPDU_scalingEdit_present);} void ResetAttrib(void){m_dwChangedAttrib = 0;} void SetAllAttribs(void){m_dwChangedAttrib = 0x07;} DWORD GetPresentAttribs(void){return ((m_dwChangedAttrib & 0x0F0));} void ChangedPenThickness(void){}; void OnObjectEdit(void); void OnObjectDelete(void); void SendNewObjectToT126Apps(void); void GetEncodedCreatePDU(ASN1_BUF *pBuf); //Remote pointer stuff // // Device context used for drawing and undrawing the pointer // HDC m_hMemDC; // // Pointer to the bitmap used to save the data under the pointer // HBITMAP m_hSaveBitmap; // // Handle of bitmap originally supplied with memDC // HBITMAP m_hOldBitmap; // // Handle of icon to be used for drawing // HICON m_hIcon; HICON CreateColoredIcon(COLORREF color, LPBITMAPINFOHEADER lpbInfo = NULL, LPBYTE pMaskBits = NULL); void CreateSaveBitmap(); void UnDraw(void); BOOL UndrawScreen(); void SetBitmapSize(LONG x, LONG y){m_bitmapSize.x = x; m_bitmapSize.y = y;} protected: DWORD m_dwChangedAttrib; POINT m_bitmapSize; // Width, Height RECT m_bitmapRegionOfInterest; UINT m_pixelAspectRatio; POINT m_scaling; UINT m_checkPoints; BITMAPDATA m_bitmapData; }; #endif // __BITMAPOBJ_HPP_
31.802469
123
0.742236
npocmaka
3da63cb408e8386af37d557baa797fe3a21753c3
1,452
cpp
C++
Source/Core/TornadoEngine/Features/Graphic/TitleUpdaterSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
27
2015-01-08T08:26:29.000Z
2019-02-10T03:18:05.000Z
Source/Core/TornadoEngine/Features/Graphic/TitleUpdaterSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
1
2017-04-05T02:02:14.000Z
2017-04-05T02:02:14.000Z
Source/Core/TornadoEngine/Features/Graphic/TitleUpdaterSystem.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
17
2015-01-18T02:50:01.000Z
2019-02-08T21:00:53.000Z
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [ramil2085@mail.ru, ramil2085@gmail.com] See for more information LICENSE.md. */ #include "TitleUpdaterSystem.h" #include "ButtonComponent.h" #include "DialogComponent.h" #include "InputTextComponent.h" #include "MenuNodeComponent.h" #include "WindowComponent.h" #include "TreeNodeComponent.h" using namespace nsGraphicWrapper; using namespace nsGuiWrapper; using namespace std::placeholders; void TTitleUpdaterSystem::Init() { Add(std::bind(&TTitleUpdaterSystem::SetTitle<TButtonComponent>, this, _1, _2)); Add(std::bind(&TTitleUpdaterSystem::SetTitle<TDialogComponent>, this, _1, _2)); Add(std::bind(&TTitleUpdaterSystem::SetTitle<TInputTextComponent>, this, _1, _2)); Add(std::bind(&TTitleUpdaterSystem::SetTitle<TMenuNodeComponent>, this, _1, _2)); Add(std::bind(&TTitleUpdaterSystem::SetTitle<TWindowComponent>, this, _1, _2)); Add(std::bind(&TTitleUpdaterSystem::SetTitle<TTreeNodeComponent>, this, _1, _2)); } //-------------------------------------------------------------------------------------------------------------------------- void TTitleUpdaterSystem::Reactive(nsECSFramework::TEntityID eid, const nsGuiWrapper::TTitleComponent* pC) { HandleByPool(eid, pC); } //--------------------------------------------------------------------------------------------------------------------------
40.333333
125
0.614325
RamilGauss
3da766cd537615bd574d3c16da1c8070c15eb107
3,368
hpp
C++
src/renderer/Overlay.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
7
2015-06-21T14:35:16.000Z
2021-08-30T12:00:52.000Z
src/renderer/Overlay.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
1
2017-02-28T14:09:43.000Z
2017-03-02T06:55:19.000Z
src/renderer/Overlay.hpp
Youka/SSBRenderer_rework
a42aa7f90819f8dddd2073d5c971f74b36c97380
[ "Zlib" ]
1
2015-12-09T18:22:09.000Z
2015-12-09T18:22:09.000Z
/* Project: SSBRenderer File: Overlay.hpp Copyright (c) 2015, Christoph "Youka" Spanknebel This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include "../graphics/gutils.hpp" #include "../parser/SSBData.hpp" namespace SSB{ // Image with overlay instruction struct Overlay{ GUtils::Image2D<> image; // Always RGBA int x, y; Blend::Mode op; Time fade_in, fade_out; }; // Colorspace type enum class Colorspace{BGR, BGRX, BGRA}; // Fades overlay and blends on target static inline void blend_overlay(Time start_ms, Time end_ms, Time cur_ms, Overlay& overlay, unsigned char* data, unsigned width, unsigned height, unsigned stride, Colorspace format){ // Calculate fade factor Time inner_ms = cur_ms - start_ms, inv_inner_ms = end_ms - cur_ms; double alpha = inner_ms < overlay.fade_in ? static_cast<double>(inner_ms) / overlay.fade_in : (inv_inner_ms < overlay.fade_out ? static_cast<double>(inv_inner_ms) / overlay.fade_out : 1.0); // Fade image if(alpha != 1.0){ unsigned char* pdata = overlay.image.get_data(); const unsigned char* const data_end = pdata + overlay.image.get_size(); while(pdata != data_end) *pdata++ *= alpha; } // Convert target from BGRX to BGRA for blending requirements if(format == Colorspace::BGRX){ unsigned char* pdata = overlay.image.get_data(); const unsigned char* const data_end = pdata + overlay.image.get_size(); const unsigned row_length = overlay.image.get_width() << 2, offset = overlay.image.get_stride() - row_length; const unsigned char* pdata_row_end; while(pdata != data_end){ for(pdata_row_end = pdata + row_length; pdata != pdata_row_end; pdata += 4) pdata[3] = 255; pdata += offset; } } // Cast SSB blend mode to GUtils blend operation GUtils::BlendOp op; switch(overlay.op){ case Blend::Mode::OVER: op = GUtils::BlendOp::OVER; break; case Blend::Mode::ADDITION: op = GUtils::BlendOp::ADD; break; case Blend::Mode::SUBTRACT: op = GUtils::BlendOp::SUB; break; case Blend::Mode::MULTIPLY: op = GUtils::BlendOp::MUL; break; case Blend::Mode::SCREEN: op = GUtils::BlendOp::SCR; break; case Blend::Mode::DIFFERENCES: op = GUtils::BlendOp::DIFF; break; default: op = GUtils::BlendOp::OVER; break; // Compiler nonsense, all possibles cases were already handled } // Blend overlay on target GUtils::blend( overlay.image.get_data(), overlay.image.get_width(), overlay.image.get_height(), overlay.image.get_stride(), true, data, width, height, stride, format != Colorspace::BGR, overlay.x, overlay.y, op ); } }
42.632911
247
0.720903
Youka
3da8afccbc59291be92554ce4f12bffabb27b63d
17,308
cc
C++
modules/util/load/load_dump_options.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
null
null
null
modules/util/load/load_dump_options.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
1
2021-09-12T22:07:06.000Z
2021-09-12T22:07:06.000Z
modules/util/load/load_dump_options.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020, 2021, Oracle and/or its affiliates. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, as * designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "modules/util/load/load_dump_options.h" #include <algorithm> #include <mysqld_error.h> #include "modules/mod_utils.h" #include "modules/util/dump/dump_manifest.h" #include "mysqlshdk/include/scripting/type_info/custom.h" #include "mysqlshdk/include/scripting/type_info/generic.h" #include "mysqlshdk/libs/storage/backend/oci_object_storage.h" #include "mysqlshdk/libs/utils/debug.h" #include "mysqlshdk/libs/utils/utils_string.h" namespace mysqlsh { namespace { const char *k_excluded_users[] = {"mysql.infoschema", "mysql.session", "mysql.sys"}; const char *k_oci_excluded_users[] = {"administrator", "ociadmin", "ocimonitor", "ocirpl"}; bool is_mds(const mysqlshdk::utils::Version &version) { return shcore::str_endswith(version.get_extra(), "cloud"); } void parse_tables(const std::vector<std::string> &opt_tables, std::unordered_set<std::string> *out_filter, bool add_schema_entry) { for (const auto &table_def : opt_tables) { std::string schema, table; try { shcore::split_schema_and_table(table_def, &schema, &table); } catch (const std::exception &e) { throw std::invalid_argument( "Can't parse table filter '" + table_def + "'. The table must be in the following form: " "schema.table, with optional backtick quotes."); } if (schema.empty()) { throw std::invalid_argument( "Can't parse table filter '" + table_def + "'. The table must be in the following form: " "schema.table, with optional backtick quotes."); } if (schema[0] == '`') schema = shcore::unquote_identifier(schema); if (table[0] == '`') table = shcore::unquote_identifier(table_def); out_filter->insert(schema_table_key(schema, table)); if (add_schema_entry) { // insert schema."", so that we can check whether we want to include // one or more tables for a given schema, but not the whole schema out_filter->insert(schema_table_key(schema, "")); } } } } // namespace using mysqlsh::dump::Dump_manifest; using mysqlsh::dump::Manifest_mode; Load_dump_options::Load_dump_options() : Load_dump_options("") {} Load_dump_options::Load_dump_options(const std::string &url) : m_url(url) {} const shcore::Option_pack_def<Load_dump_options> &Load_dump_options::options() { static const auto opts = shcore::Option_pack_def<Load_dump_options>() .optional("threads", &Load_dump_options::m_threads_count) .optional("showProgress", &Load_dump_options::m_show_progress) .optional("waitDumpTimeout", &Load_dump_options::set_wait_timeout) .optional("loadData", &Load_dump_options::m_load_data) .optional("loadDdl", &Load_dump_options::m_load_ddl) .optional("loadUsers", &Load_dump_options::m_load_users) .optional("dryRun", &Load_dump_options::m_dry_run) .optional("resetProgress", &Load_dump_options::m_reset_progress) .optional("progressFile", &Load_dump_options::m_progress_file) .optional("includeSchemas", &Load_dump_options::set_str_vector_option) .optional("includeTables", &Load_dump_options::set_str_vector_option) .optional("excludeSchemas", &Load_dump_options::set_str_vector_option) .optional("excludeTables", &Load_dump_options::set_str_vector_option) .optional("characterSet", &Load_dump_options::m_character_set) .optional("skipBinlog", &Load_dump_options::m_skip_binlog) .optional("ignoreExistingObjects", &Load_dump_options::m_ignore_existing_objects) .optional("ignoreVersion", &Load_dump_options::m_ignore_version) .optional("analyzeTables", &Load_dump_options::m_analyze_tables, {{"histogram", Analyze_table_mode::HISTOGRAM}, {"on", Analyze_table_mode::ON}, {"off", Analyze_table_mode::OFF}}) .optional("deferTableIndexes", &Load_dump_options::m_defer_table_indexes, {{"off", Defer_index_mode::OFF}, {"all", Defer_index_mode::ALL}, {"fulltext", Defer_index_mode::FULLTEXT}}) .optional("loadIndexes", &Load_dump_options::m_load_indexes) .optional("schema", &Load_dump_options::m_target_schema) .optional("excludeUsers", &Load_dump_options::set_str_unordered_set_option) .optional("includeUsers", &Load_dump_options::set_str_unordered_set_option) .optional("updateGtidSet", &Load_dump_options::m_update_gtid_set, {{"append", Update_gtid_set::APPEND}, {"replace", Update_gtid_set::REPLACE}, {"off", Update_gtid_set::OFF}}) .optional("showMetadata", &Load_dump_options::m_show_metadata) .optional("createInvisiblePKs", &Load_dump_options::m_create_invisible_pks) .include(&Load_dump_options::m_oci_option_pack) .on_done(&Load_dump_options::on_unpacked_options); return opts; } void Load_dump_options::set_wait_timeout(const double &timeout_seconds) { m_wait_dump_timeout_ms = timeout_seconds * 1000; } void Load_dump_options::set_str_vector_option( const std::string &option, const std::vector<std::string> &data) { if (option == "includeSchemas") { for (const auto &schema : data) { if (!schema.empty() && schema[0] != '`') m_include_schemas.insert(shcore::quote_identifier(schema)); else m_include_schemas.insert(schema); } } else if (option == "includeTables") { parse_tables(data, &m_include_tables, true); } else if (option == "excludeSchemas") { for (const auto &schema : data) { if (!schema.empty() && schema[0] != '`') m_exclude_schemas.insert(shcore::quote_identifier(schema)); else m_exclude_schemas.insert(schema); } } else if (option == "excludeTables") { parse_tables(data, &m_exclude_tables, false); } else { // This function should only be called with the options above. assert(false); } } void Load_dump_options::set_str_unordered_set_option( const std::string &option, const std::unordered_set<std::string> &data) { if (option == "excludeUsers") { if (!m_load_users) { if (!data.empty()) { throw std::invalid_argument( "The 'excludeUsers' option cannot be used if the " "'loadUsers' option is set to false."); } } else { try { // some users are always excluded auto excluded_users = data; excluded_users.insert(std::begin(k_excluded_users), std::end(k_excluded_users)); if (is_mds()) { excluded_users.insert(std::begin(k_oci_excluded_users), std::end(k_oci_excluded_users)); } m_excluded_users = shcore::to_accounts(excluded_users); } catch (const std::runtime_error &e) { throw std::invalid_argument(e.what()); } } } else if (option == "includeUsers") { if (!m_load_users) { if (!data.empty()) { throw std::invalid_argument( "The 'includeUsers' option cannot be used if the " "'loadUsers' option is set to false."); } } else { try { m_included_users = shcore::to_accounts(data); } catch (const std::runtime_error &e) { throw std::invalid_argument(e.what()); } } } else { // This function should only be called with the options above. assert(false); } } void Load_dump_options::set_session( const std::shared_ptr<mysqlshdk::db::ISession> &session, const std::string &current_schema) { m_base_session = session; m_current_schema = current_schema; m_target = get_classic_connection_options(m_base_session); if (m_target.has(mysqlshdk::db::kLocalInfile)) { m_target.remove(mysqlshdk::db::kLocalInfile); } m_target.set(mysqlshdk::db::kLocalInfile, "true"); // Set long timeouts by default std::string timeout = "86400000"; // 1 day in milliseconds if (!m_target.has(mysqlshdk::db::kNetReadTimeout)) { m_target.set(mysqlshdk::db::kNetReadTimeout, timeout); } if (!m_target.has(mysqlshdk::db::kNetWriteTimeout)) { m_target.set(mysqlshdk::db::kNetWriteTimeout, timeout); } // set size of max packet (~size of 1 row) we can send to server if (!m_target.has(mysqlshdk::db::kMaxAllowedPacket)) { const auto k_one_gb = "1073741824"; m_target.set(mysqlshdk::db::kMaxAllowedPacket, k_one_gb); } m_target_server_version = mysqlshdk::utils::Version( m_base_session->query("SELECT @@version")->fetch_one()->get_string(0)); m_is_mds = ::mysqlsh::is_mds(m_target_server_version); DBUG_EXECUTE_IF("dump_loader_force_mds", { m_is_mds = true; }); try { m_base_session->query( "SELECT @@SESSION.sql_generate_invisible_primary_key;"); m_auto_create_pks_supported = true; } catch (const mysqlshdk::db::Error &e) { if (e.code() == ER_UNKNOWN_SYSTEM_VARIABLE) { m_auto_create_pks_supported = false; } else { throw; } } } void Load_dump_options::validate() { using mysqlshdk::storage::backend::oci::Par_structure; using mysqlshdk::storage::backend::oci::parse_full_object_par; Par_structure url_par_data; m_use_par = parse_full_object_par(m_url, &url_par_data); if (m_use_par) { if (m_progress_file.is_null()) { throw shcore::Exception::argument_error( "When using a PAR to a dump manifest, the progressFile option must " "be defined."); } else { Par_structure progress_par_data; m_use_par_progress = parse_full_object_par(*m_progress_file, &progress_par_data); } m_oci_options.set_par(m_url); m_prefix = url_par_data.object_prefix; } m_oci_options.check_option_values(); { auto result = m_base_session->query("SHOW GLOBAL VARIABLES LIKE 'local_infile'"); auto row = result->fetch_one(); auto local_infile_value = row->get_string(1); if (shcore::str_caseeq(local_infile_value, "off")) { mysqlsh::current_console()->print_error( "The 'local_infile' global system variable must be set to ON in " "the target server, after the server is verified to be trusted."); throw shcore::Exception::runtime_error("local_infile disabled in server"); } } if (m_progress_file.is_null()) { std::string uuid = m_base_session->query("SELECT @@server_uuid") ->fetch_one_or_throw() ->get_string(0); m_default_progress_file = "load-progress." + uuid + ".json"; } m_excluded_users.emplace_back( shcore::split_account(m_base_session->query("SELECT current_user()") ->fetch_one() ->get_string(0))); } std::string Load_dump_options::target_import_info() const { std::string action; std::vector<std::string> what_to_load; if (load_ddl()) what_to_load.push_back("DDL"); if (load_data()) what_to_load.push_back("Data"); if (load_users()) what_to_load.push_back("Users"); std::string where; if (m_oci_options) { if (m_use_par) { where = "OCI PAR=" + m_url + ", prefix='" + m_prefix + "'"; } else { where = "OCI ObjectStorage bucket=" + *m_oci_options.os_bucket_name + ", prefix='" + m_url + "'"; } } else { where = "'" + m_url + "'"; } // this is validated earlier on assert(!what_to_load.empty() || m_analyze_tables != Analyze_table_mode::OFF || m_update_gtid_set != Update_gtid_set::OFF); if (what_to_load.size() == 3) { action = shcore::str_format( "Loading %s, %s and %s from %s", what_to_load[0].c_str(), what_to_load[1].c_str(), what_to_load[2].c_str(), where.c_str()); } else if (what_to_load.size() == 2) { action = shcore::str_format("Loading %s and %s from %s", what_to_load[0].c_str(), what_to_load[1].c_str(), where.c_str()); } else if (!what_to_load.empty()) { action = shcore::str_format("Loading %s only from %s", what_to_load[0].c_str(), where.c_str()); } else { if (m_analyze_tables == Analyze_table_mode::HISTOGRAM) action = "Updating table histograms"; else if (m_analyze_tables == Analyze_table_mode::ON) action = "Updating table histograms and key distribution statistics"; if (m_update_gtid_set != Update_gtid_set::OFF) { if (!action.empty()) action += ", and updating GTID_PURGED"; else action = "Updating GTID_PURGED"; } } std::string detail; if (threads_count() == 1) detail = " using 1 thread."; else detail = shcore::str_format(" using %s threads.", std::to_string(threads_count()).c_str()); return action + detail; } void Load_dump_options::on_unpacked_options() { m_oci_options = m_oci_option_pack; if (!m_load_data && !m_load_ddl && !m_load_users && m_analyze_tables == Analyze_table_mode::OFF && m_update_gtid_set == Update_gtid_set::OFF) throw shcore::Exception::argument_error( "At least one of loadData, loadDdl or loadUsers options must be " "enabled"); if (!m_load_indexes && m_defer_table_indexes == Defer_index_mode::OFF) throw std::invalid_argument( "'deferTableIndexes' option needs to be enabled when " "'loadIndexes' option is disabled"); } std::unique_ptr<mysqlshdk::storage::IDirectory> Load_dump_options::create_dump_handle() const { if (m_use_par) { return std::make_unique<Dump_manifest>(Manifest_mode::READ, m_oci_options, nullptr, m_url); } else if (!m_oci_options.os_bucket_name.get_safe().empty()) { return mysqlshdk::storage::make_directory(m_url, m_oci_options); } else { return mysqlshdk::storage::make_directory(m_url); } } std::unique_ptr<mysqlshdk::storage::IFile> Load_dump_options::create_progress_file_handle() const { if (m_progress_file.get_safe().empty()) return create_dump_handle()->file(m_default_progress_file); else return mysqlshdk::storage::make_file(*m_progress_file); } // Filtering works as: // (includeSchemas + includeTables || *) - excludeSchemas - excludeTables bool Load_dump_options::include_schema(const std::string &schema) const { std::string qschema = shcore::quote_identifier(schema); if (m_exclude_schemas.count(qschema) > 0) return false; // If includeSchemas neither includeTables are given, then all schemas // are included by default if ((m_include_schemas.empty() && m_include_tables.empty()) || m_include_schemas.count(qschema) > 0) return true; return false; } bool Load_dump_options::include_table(const std::string &schema, const std::string &table) const { std::string key = schema_table_key(schema, table); if (m_exclude_tables.count(key) > 0 || m_exclude_schemas.count(shcore::quote_identifier(schema)) > 0) return false; if ((include_schema(schema) && m_include_tables.empty()) || m_include_tables.count(key) > 0) return true; return false; } bool Load_dump_options::include_user(const shcore::Account &account) const { const auto predicate = [&account](const shcore::Account &a) { return a.user == account.user && (a.host.empty() ? true : a.host == account.host); }; if (m_excluded_users.end() != std::find_if(m_excluded_users.begin(), m_excluded_users.end(), predicate)) { return false; } if (m_included_users.empty()) { return true; } return m_included_users.end() != std::find_if(m_included_users.begin(), m_included_users.end(), predicate); } } // namespace mysqlsh
37.382289
80
0.651144
mueller
3dac8bc324e9532eb6200a2d9208019c5702462d
524
cpp
C++
src/crypto/test/src/UUIDTest.cpp
karz0n/algorithms
b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8
[ "MIT" ]
1
2020-04-18T14:34:16.000Z
2020-04-18T14:34:16.000Z
src/crypto/test/src/UUIDTest.cpp
karz0n/algorithms
b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8
[ "MIT" ]
null
null
null
src/crypto/test/src/UUIDTest.cpp
karz0n/algorithms
b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "UUID.hpp" using namespace testing; using namespace algorithms; TEST(UUIDTest, ByTime) { const auto uuid = UUID::createByTime().toString(); EXPECT_THAT(uuid, Not(IsEmpty())); } TEST(UUIDTest, ByRandom) { const auto uuid = UUID::createByRandom().toString(); EXPECT_THAT(uuid, Not(IsEmpty())); } TEST(UUIDTest, ByName) { const auto uuid = UUID::createByName(UUID::dns(), "www.example.com").toString(); EXPECT_THAT(uuid, Not(IsEmpty())); }
20.96
84
0.685115
karz0n
3dacbd05c705863a5af6703ad7ea29bc2383bec8
7,740
cpp
C++
lib/fuzzer/FuzzerUtilFuchsia.cpp
MaskRay/compiler-rt
3756e8110e6f7d8e1e8a47a048afe02fb3a09999
[ "MIT" ]
null
null
null
lib/fuzzer/FuzzerUtilFuchsia.cpp
MaskRay/compiler-rt
3756e8110e6f7d8e1e8a47a048afe02fb3a09999
[ "MIT" ]
null
null
null
lib/fuzzer/FuzzerUtilFuchsia.cpp
MaskRay/compiler-rt
3756e8110e6f7d8e1e8a47a048afe02fb3a09999
[ "MIT" ]
null
null
null
//===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Misc utils implementation using Fuchsia/Zircon APIs. //===----------------------------------------------------------------------===// #include "FuzzerDefs.h" #if LIBFUZZER_FUCHSIA #include "FuzzerInternal.h" #include "FuzzerUtil.h" #include <cerrno> #include <cinttypes> #include <cstdint> #include <fcntl.h> #include <lib/fdio/spawn.h> #include <string> #include <sys/select.h> #include <thread> #include <unistd.h> #include <zircon/errors.h> #include <zircon/process.h> #include <zircon/status.h> #include <zircon/syscalls.h> #include <zircon/syscalls/port.h> #include <zircon/types.h> namespace fuzzer { namespace { // A magic value for the Zircon exception port, chosen to spell 'FUZZING' // when interpreted as a byte sequence on little-endian platforms. const uint64_t kFuzzingCrash = 0x474e495a5a5546; void AlarmHandler(int Seconds) { while (true) { SleepSeconds(Seconds); Fuzzer::StaticAlarmCallback(); } } void InterruptHandler() { fd_set readfds; // Ctrl-C sends ETX in Zircon. do { FD_ZERO(&readfds); FD_SET(STDIN_FILENO, &readfds); select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr); } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03); Fuzzer::StaticInterruptCallback(); } void CrashHandler(zx_handle_t *Port) { std::unique_ptr<zx_handle_t> ExceptionPort(Port); zx_port_packet_t Packet; _zx_port_wait(*ExceptionPort, ZX_TIME_INFINITE, &Packet); // Unbind as soon as possible so we don't receive exceptions from this thread. if (_zx_task_bind_exception_port(ZX_HANDLE_INVALID, ZX_HANDLE_INVALID, kFuzzingCrash, 0) != ZX_OK) { // Shouldn't happen; if it does the safest option is to just exit. Printf("libFuzzer: unable to unbind exception port; aborting!\n"); exit(1); } if (Packet.key != kFuzzingCrash) { Printf("libFuzzer: invalid crash key: %" PRIx64 "; aborting!\n", Packet.key); exit(1); } // CrashCallback should not return from this call Fuzzer::StaticCrashSignalCallback(); } } // namespace // Platform specific functions. void SetSignalHandler(const FuzzingOptions &Options) { zx_status_t rc; // Set up alarm handler if needed. if (Options.UnitTimeoutSec > 0) { std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1); T.detach(); } // Set up interrupt handler if needed. if (Options.HandleInt || Options.HandleTerm) { std::thread T(InterruptHandler); T.detach(); } // Early exit if no crash handler needed. if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll && !Options.HandleFpe && !Options.HandleAbrt) return; // Create an exception port zx_handle_t *ExceptionPort = new zx_handle_t; if ((rc = _zx_port_create(0, ExceptionPort)) != ZX_OK) { Printf("libFuzzer: zx_port_create failed: %s\n", _zx_status_get_string(rc)); exit(1); } // Bind the port to receive exceptions from our process if ((rc = _zx_task_bind_exception_port(_zx_process_self(), *ExceptionPort, kFuzzingCrash, 0)) != ZX_OK) { Printf("libFuzzer: unable to bind exception port: %s\n", _zx_status_get_string(rc)); exit(1); } // Set up the crash handler. std::thread T(CrashHandler, ExceptionPort); T.detach(); } void SleepSeconds(int Seconds) { _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds))); } unsigned long GetPid() { zx_status_t rc; zx_info_handle_basic_t Info; if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info, sizeof(Info), NULL, NULL)) != ZX_OK) { Printf("libFuzzer: unable to get info about self: %s\n", _zx_status_get_string(rc)); exit(1); } return Info.koid; } size_t GetPeakRSSMb() { zx_status_t rc; zx_info_task_stats_t Info; if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info, sizeof(Info), NULL, NULL)) != ZX_OK) { Printf("libFuzzer: unable to get info about self: %s\n", _zx_status_get_string(rc)); exit(1); } return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20; } template <typename Fn> class RunOnDestruction { public: explicit RunOnDestruction(Fn fn) : fn_(fn) {} ~RunOnDestruction() { fn_(); } private: Fn fn_; }; template <typename Fn> RunOnDestruction<Fn> at_scope_exit(Fn fn) { return RunOnDestruction<Fn>(fn); } int ExecuteCommand(const Command &Cmd) { zx_status_t rc; // Convert arguments to C array auto Args = Cmd.getArguments(); size_t Argc = Args.size(); assert(Argc != 0); std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]); for (size_t i = 0; i < Argc; ++i) Argv[i] = Args[i].c_str(); Argv[Argc] = nullptr; // Determine stdout int FdOut = STDOUT_FILENO; if (Cmd.hasOutputFile()) { auto Filename = Cmd.getOutputFile(); FdOut = open(Filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0); if (FdOut == -1) { Printf("libFuzzer: failed to open %s: %s\n", Filename.c_str(), strerror(errno)); return ZX_ERR_IO; } } auto CloseFdOut = at_scope_exit([&]() { close(FdOut); } ); // Determine stderr int FdErr = STDERR_FILENO; if (Cmd.isOutAndErrCombined()) FdErr = FdOut; // Clone the file descriptors into the new process fdio_spawn_action_t SpawnAction[] = { { .action = FDIO_SPAWN_ACTION_CLONE_FD, .fd = { .local_fd = STDIN_FILENO, .target_fd = STDIN_FILENO, }, }, { .action = FDIO_SPAWN_ACTION_CLONE_FD, .fd = { .local_fd = FdOut, .target_fd = STDOUT_FILENO, }, }, { .action = FDIO_SPAWN_ACTION_CLONE_FD, .fd = { .local_fd = FdErr, .target_fd = STDERR_FILENO, }, }, }; // Start the process. char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH]; zx_handle_t ProcessHandle = ZX_HANDLE_INVALID; rc = fdio_spawn_etc( ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0], Argv.get(), nullptr, 3, SpawnAction, &ProcessHandle, ErrorMsg); if (rc != ZX_OK) { Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg, _zx_status_get_string(rc)); return rc; } auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); }); // Now join the process and return the exit status. if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED, ZX_TIME_INFINITE, nullptr)) != ZX_OK) { Printf("libFuzzer: failed to join '%s': %s\n", Argv[0], _zx_status_get_string(rc)); return rc; } zx_info_process_t Info; if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info, sizeof(Info), nullptr, nullptr)) != ZX_OK) { Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0], _zx_status_get_string(rc)); return rc; } return Info.return_code; } const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt, size_t PattLen) { return memmem(Data, DataLen, Patt, PattLen); } } // namespace fuzzer #endif // LIBFUZZER_FUCHSIA
29.318182
80
0.624935
MaskRay
3db20bdee63c01240ac7f0ccf9a04ab3184e8b28
3,547
cpp
C++
src/Pegasus/Repository/tests/AssocTable/AssocTable.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Repository/tests/AssocTable/AssocTable.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Repository/tests/AssocTable/AssocTable.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
1
2022-03-07T22:54:02.000Z
2022-03-07T22:54:02.000Z
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // 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. // //============================================================================== // // Author: Mike Brasher (mbrasher@bmc.com) // // Modified By: Jenny Yu (jenny_yu@hp.com) // Carol Ann Krug Graves, Hewlett-Packard Company // (carolann_graves@hp.com) // //%///////////////////////////////////////////////////////////////////////////// #include <Pegasus/Repository/AssocClassTable.h> #include <Pegasus/Repository/AssocInstTable.h> PEGASUS_USING_PEGASUS; PEGASUS_USING_STD; static char * verbose; int main(int argc, char** argv) { verbose = getenv("PEGASUS_TEST_VERBOSE"); String assocTablePath; const char* tmpDir = getenv ("PEGASUS_TMP"); if (tmpDir == NULL) { assocTablePath = "."; } else { assocTablePath = tmpDir; } assocTablePath.append("/associations.tbl"); // // create class association // AssocClassTable::append( assocTablePath, CIMName ("Lineage"), CIMName ("Person"), CIMName ("parent"), CIMName ("Person"), CIMName ("child")); // // delete class association // AssocClassTable::deleteAssociation( assocTablePath, CIMName ("Lineage")); // // create instance association // AssocInstTable::append( assocTablePath, "A.left=\"x.key=\\\"one\\\"\",right=\"y.key=\\\"two\\\"\"", CIMName ("A"), "X.key=\"one\"", CIMName ("X"), CIMName ("left"), "Y.key=\"two\"", CIMName ("Y"), CIMName ("right")); // // delete instance association // AssocInstTable::deleteAssociation( assocTablePath, CIMObjectPath ("A.left=\"x.key=\\\"one\\\"\",right=\"y.key=\\\"two\\\"\"")); cout << argv[0] << " +++++ passed all tests" << endl; return 0; }
34.105769
80
0.614886
ncultra
3db3ab5e00833a62af26549b7e990fa5e7f08309
885
cpp
C++
cpp/emcpp/impls/trim.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
2
2021-04-26T16:37:38.000Z
2022-03-15T01:26:19.000Z
cpp/emcpp/impls/trim.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
null
null
null
cpp/emcpp/impls/trim.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
1
2022-03-15T01:26:23.000Z
2022-03-15T01:26:23.000Z
#include <vector> #include <string> #include <iostream> int main() { /** * 针对可复制的形参,在移动成本低且一定会被复制的情况下,考虑将其按值传递 */ { // 1 仅对于可复制的形参,才考虑按值传递; // 2 按值传递仅仅在形参成本低廉的情况下; // 3 在不需要重新分配内存的情况下,按值传递会导致多得多的成本; // 4 在调用链上传递累加会导致难以忍受的成本; // 5 按值传递可能遇到切片问题; } /** * 考虑置入而非插入 */ { { std::vector<std::string> vs{}; vs.push_back("xyzzy"); // 可能会遭遇一次构造,右值构造,析构 vs.emplace_back("xyzzy"); // 只经历一次构造 for(const auto& s:vs) { std::cout<<s<<std::endl; } } // 需要考虑的典型情况是: // 1 欲添加的值是以构造而非赋值的方式加入容器 // 2 传递的实参类型与持有物的类型不同 // 3 容器不太可能由于重复情况而拒绝添加新的值,如set、map等 // 4 不是使用new Widget形式的,在这种情况下,push由于析构比较安全,emplace由于构造,比较危险 // 5 置入函数可能会执行在插入函数中拒绝的类型转换,这种情况下即使使用explicit也会因为直接初始化没有被阻止而成功编译 } }
25.285714
72
0.540113
lonelyhentai
3db3f42f1fc67fbe8b23f279b65efa163b3c7a3b
1,142
cpp
C++
shortest_path_in_DAG.cpp
WizArdZ3658/Data-Structures-and-Algorithms
4098c0680c13127473d7ce6a41ead519559ff962
[ "MIT" ]
3
2020-09-14T04:50:13.000Z
2021-04-17T06:42:43.000Z
shortest_path_in_DAG.cpp
WizArdZ3658/Data-Structures-and-Algorithms
4098c0680c13127473d7ce6a41ead519559ff962
[ "MIT" ]
null
null
null
shortest_path_in_DAG.cpp
WizArdZ3658/Data-Structures-and-Algorithms
4098c0680c13127473d7ce6a41ead519559ff962
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int shortest_path(vector<vector<int>> &adj) { int n = adj.size(); int indegree[n] = {0}; int s_path[n] = {0}; for (int i = 0; i < n; ++i) { for (int j = 0; j < adj[i].size(); ++j) { indegree[adj[i][j]]++; } } queue<int> q; for (int i = 0; i < n; ++i) { if (indegree[i]==0) { q.push(i); } } while(!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < adj[u].size(); ++i) { indegree[adj[u][i]]--; s_path[adj[u][i]] = min(s_path[adj[u][i]],s_path[u]+1); if (indegree[adj[u][i]] == 0) { q.push(adj[u][i]); } } } int answer = INT_MAX; for (int i = 0; i < n; ++i) { answer = min(answer, s_path[i]); } return answer; } int main() { /* the code will be similar to topological sort */ cout << "Enter number of vertices\n"; int n; cin >> n; vector<vector<int>> adj(n); cout << "Enter number of edges\n"; int e, u, v; cin >> e; cout << "Enter the u-v pairs where edge goes from u to v\n"; while(e--) { cin >> u >> v; adj[u-1].push_back(v-1); } cout << "Answer : " << shortest_path(adj) + 1 << '\n'; return 0; }
17.569231
61
0.517513
WizArdZ3658
3db4280fa80299604b5bdf55c8bfaf45565e880f
2,767
cpp
C++
lib/loaders/BoxLoader.cpp
nghiattran/KittiViz
fa3ac5edb1f5efbfef7a9ef2926042f32045b7c0
[ "MIT" ]
19
2017-12-29T14:34:58.000Z
2021-12-22T07:46:32.000Z
lib/loaders/BoxLoader.cpp
dj-boy/KittiViz
fa3ac5edb1f5efbfef7a9ef2926042f32045b7c0
[ "MIT" ]
1
2017-12-29T14:34:53.000Z
2018-08-05T20:09:56.000Z
lib/loaders/BoxLoader.cpp
dj-boy/KittiViz
fa3ac5edb1f5efbfef7a9ef2926042f32045b7c0
[ "MIT" ]
3
2018-01-25T00:17:24.000Z
2021-07-03T15:36:58.000Z
#include "BoxLoader.h" BoxLoader* BoxLoader::mInstance = NULL; BoxLoader::BoxLoader() { // This creates our identifier and puts it in vbo glGenVertexArrays(1, &vboptr); glGenBuffers(1, &eboptr); glGenBuffers(1, &bufptr); for (uint i = 0; i < NUM_PTS; i++) { if (points[i*4] < -0.45) { colors[i * 3] = 1; colors[i * 3 + 1] = 0; colors[i * 3 + 2] = 0; } else { colors[i * 3] = 1; colors[i * 3 + 1] = 1; colors[i * 3 + 2] = 1; } } LoadDataToGraphicsCard(); } BoxLoader::~BoxLoader() { glBindVertexArray(vboptr); glDeleteBuffers(1, &bufptr); glDeleteBuffers(1, &eboptr); } /** \brief Singleton constructor. Create a singleton object of DataLoader. */ BoxLoader* BoxLoader::instance() { if (!mInstance) { mInstance = new BoxLoader(); } return mInstance; } void BoxLoader::LoadDataToGraphicsCard() { GLuint vPosition = 0; GLuint vColor = 1; glGenVertexArrays(1, &vboptr); glBindVertexArray(vboptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eboptr); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, bufptr); glBufferData(GL_ARRAY_BUFFER, sizeof(points) + sizeof(colors), NULL, GL_DYNAMIC_DRAW);\ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(points), points); glBufferSubData(GL_ARRAY_BUFFER, sizeof(points), sizeof(colors), colors); glVertexAttribPointer(vColor, 3, GL_FLOAT, GL_TRUE, 0, BUFFER_OFFSET(sizeof(points))); glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); glEnableVertexAttribArray(vPosition); glEnableVertexAttribArray(vColor); } void BoxLoader::draw(GLuint PVMLoc, glm::mat4 projection, glm::mat4 view) { if (!isShow) return; glLineWidth(3); for (int i = 0; i < boxes.size(); i++) { glm::mat4 boxModel = boxes[i].getModelMatrix(); glUniformMatrix4fv(PVMLoc, 1, GL_FALSE, glm::value_ptr(projection*view*boxModel)); // Draw box glBindVertexArray(vboptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eboptr); glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0); glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, (GLvoid*)(4*sizeof(GLushort))); glDrawElements(GL_LINES, 8, GL_UNSIGNED_SHORT, (GLvoid*)(8*sizeof(GLushort))); glDrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, (GLvoid*)(20*sizeof(GLushort))); glDrawElements(GL_LINES, 8, GL_UNSIGNED_SHORT, (GLvoid*)(24*sizeof(GLushort))); } } void BoxLoader::update(BoxList v) { boxes = v.getData(); } void BoxLoader::toggleDisplay() { isShow = !isShow; }
25.859813
91
0.643296
nghiattran
3db4e7a54e1559f8dc1fbc088e21f83d2a7d7be7
2,461
cc
C++
chrome/browser/ui/views/crostini/crostini_force_close_view_browsertest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/ui/views/crostini/crostini_force_close_view_browsertest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/ui/views/crostini/crostini_force_close_view_browsertest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/crostini/crostini_force_close_view.h" #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "chrome/browser/ui/views/crostini/crostini_dialogue_browser_test_util.h" #include "content/public/test/browser_test.h" #include "ui/views/controls/button/label_button.h" namespace crostini { namespace { class CrostiniForceCloseViewTest : public DialogBrowserTest { public: CrostiniForceCloseViewTest() : weak_ptr_factory_(this) {} void ShowUi(const std::string& name) override { dialog_widget_ = CrostiniForceCloseView::Show( "Test App", nullptr, nullptr, base::BindOnce(&CrostiniForceCloseViewTest::ForceCloseCounter, weak_ptr_factory_.GetWeakPtr())); } protected: // This method is used as the force close callback, allowing us to observe // calls to it. void ForceCloseCounter() { force_close_invocations_++; } views::Widget* dialog_widget_ = nullptr; int force_close_invocations_ = 0; base::WeakPtrFactory<CrostiniForceCloseViewTest> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(CrostiniForceCloseViewTest); }; IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, FocusesForceQuit) { ShowUi(""); EXPECT_EQ( dialog_widget_->widget_delegate()->AsDialogDelegate()->GetOkButton(), dialog_widget_->GetFocusManager()->GetFocusedView()); } IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, OkInvokesCallback) { ShowUi(""); EXPECT_EQ(force_close_invocations_, 0); dialog_widget_->widget_delegate()->AsDialogDelegate()->AcceptDialog(); EXPECT_EQ(force_close_invocations_, 1); } IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, CancelDoesNotInvokeCallback) { ShowUi(""); EXPECT_EQ(force_close_invocations_, 0); dialog_widget_->widget_delegate()->AsDialogDelegate()->CancelDialog(); EXPECT_EQ(force_close_invocations_, 0); } IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, CloseDoesNotInvokeCallback) { ShowUi(""); EXPECT_EQ(force_close_invocations_, 0); dialog_widget_->Close(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(force_close_invocations_, 0); } IN_PROC_BROWSER_TEST_F(CrostiniForceCloseViewTest, InvokeUi_default) { ShowAndVerifyUi(); } } // namespace } // namespace crostini
31.551282
81
0.762292
Ron423c
3db6382bf802d86f342da1d68b881dfdcadfa86a
2,308
cpp
C++
Untitled-1.cpp
amitRan109/Cpp-Ex2
e52ee35d5a1857a423c2a78f96e44830bbf275a7
[ "MIT" ]
null
null
null
Untitled-1.cpp
amitRan109/Cpp-Ex2
e52ee35d5a1857a423c2a78f96e44830bbf275a7
[ "MIT" ]
null
null
null
Untitled-1.cpp
amitRan109/Cpp-Ex2
e52ee35d5a1857a423c2a78f96e44830bbf275a7
[ "MIT" ]
1
2021-02-05T11:09:02.000Z
2021-02-05T11:09:02.000Z
// string Tree:: relation(string relate) { // Node root = getRoot(); // if (root == NULL) return "unrelated"; // if (relate == "me") { // return root.getData(); // } // if (relate == "father"){ // if (root.getFather() == NULL) return "unrelated"; // return root.getFather().getData(); // } // if (relate == "mother"){ // if (root.getMother() == NULL) return "unrelated"; // return root.getMother().getData(); // } // if (relate == "grandFather"){ // if (root.getFather() == NULL) { // if (root.getMother() == NULL) return "unrelated"; // else if (root.getMother().getFather() == NULL) return "unrelated"; // else return root.getMother().getFather().getData(); // } // else if (root.getFather().getFather() == NULL) return "unrelated"; // else return root.getFather().getFather().getData(); // } // if (relate == "grandMother"){ // if (root.getFather() == NULL) { // if (root.getMother() == NULL) return "unrelated"; // else if (root.getMother().getMother() == NULL) return "unrelated"; // else return root.getMother().getMother().getData(); // } // else if (root.getFather().getMother() == NULL) return "unrelated"; // else return root.getFather().getMother().getData(); // } // int sum = sum (relate); // int gender = 0; //?? // if (sum == 0) return "unrelated"; // else return great (relate, root, sum+3,gender); // } // int Tree:: sum (string relate) { return 3;} //?? // string great (string relate, Node temp, int sum, int gender){ // if (temp == NULL) return ""; // // if (sum == 1 ) return temp; // if (sum == 2 ) { // if (gender == 0 && temp.getFather() !=NULL) return temp.getFather().getData(); // else if (gender == 1 && temp.getMother() !=NULL) return temp.getMother().getData(); // else return ""; // } // else { // string f= great(relate, temp.getFather(),sum-1,gender); // string m= great(relate, temp.getMother(),sum-1,gender); // if (f !="") return f; // else return m; // } // } // string Tree:: find (string name) { // } // void Tree:: remove (string rm){}
37.225806
94
0.519064
amitRan109
3db7feb4d96c5071323b56e854906ac011e8682f
5,192
cpp
C++
src/test/WorldPacketHandlerTestCase.cpp
Lidocian/ZeroBots
297072e07f85fc661e1b0e9a34c09580e3bfef14
[ "PostgreSQL", "Zlib", "OpenSSL" ]
1
2018-05-06T12:13:04.000Z
2018-05-06T12:13:04.000Z
src/test/WorldPacketHandlerTestCase.cpp
Lidocian/ZeroBots
297072e07f85fc661e1b0e9a34c09580e3bfef14
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
src/test/WorldPacketHandlerTestCase.cpp
Lidocian/ZeroBots
297072e07f85fc661e1b0e9a34c09580e3bfef14
[ "PostgreSQL", "Zlib", "OpenSSL" ]
null
null
null
#include "pch.h" #include "aitest.h" #include "MockAiObjectContext.h" #include "MockedAiObjectContextTestCase.h" #include "../../modules/Bots/playerbot/strategy/generic/ChatCommandHandlerStrategy.h" using namespace ai; class WorldPacketHandlerTestCase : public MockedAiObjectContextTestCase { CPPUNIT_TEST_SUITE( WorldPacketHandlerTestCase ); CPPUNIT_TEST( groupInvite ); CPPUNIT_TEST( groupSetLeader ); CPPUNIT_TEST( notEnoughMoney ); CPPUNIT_TEST( notEnoughReputation ); CPPUNIT_TEST( gossip_hello ); CPPUNIT_TEST( useGameObject ); CPPUNIT_TEST( roll ); CPPUNIT_TEST( revive ); CPPUNIT_TEST( resurrect_request ); CPPUNIT_TEST( area_trigger ); CPPUNIT_TEST( mount ); CPPUNIT_TEST( taxi ); CPPUNIT_TEST( cannot_equip ); CPPUNIT_TEST( trade_status ); CPPUNIT_TEST( loot ); CPPUNIT_TEST( item_push_result ); CPPUNIT_TEST( quest_objective_completed ); CPPUNIT_TEST( party_command ); CPPUNIT_TEST( taxi_done ); CPPUNIT_TEST( ready_check ); CPPUNIT_TEST( uninvite ); CPPUNIT_TEST( security_check ); CPPUNIT_TEST( guild_accept ); CPPUNIT_TEST( random_bot_update ); CPPUNIT_TEST( delay ); CPPUNIT_TEST_SUITE_END(); public: void setUp() { EngineTestBase::setUp(); setupEngine(context = new MockAiObjectContext(ai, new AiObjectContext(ai), &ai->buffer), "default", NULL); } protected: void groupInvite() { trigger("group invite"); tick(); assertActions(">S:accept invitation"); } void groupSetLeader() { trigger("group set leader"); tick(); assertActions(">S:leader"); } void notEnoughMoney() { trigger("not enough money"); tick(); assertActions(">S:tell not enough money"); } void notEnoughReputation() { trigger("not enough reputation"); tick(); assertActions(">S:tell not enough reputation"); } void useGameObject() { trigger("use game object"); tick(); tick(); assertActions(">S:add loot>S:use meeting stone"); } void gossip_hello() { trigger("gossip hello"); tick(); assertActions(">S:trainer"); } void roll() { trigger("loot roll"); tick(); assertActions(">S:loot roll"); } void revive() { engine->addStrategy("dead"); trigger("dead"); tick(); assertActions(">S:revive from corpse"); } void resurrect_request() { engine->addStrategy("dead"); trigger("resurrect request"); tick(); assertActions(">S:accept resurrect"); } void area_trigger() { trigger("area trigger"); tick(); trigger("within area trigger"); tick(); assertActions(">S:reach area trigger>S:area trigger"); } void mount() { trigger("check mount state"); tick(); assertActions(">S:check mount state"); } void taxi() { trigger("activate taxi"); tick(); tick(); assertActions(">S:remember taxi>S:taxi"); } void cannot_equip() { trigger("cannot equip"); tick(); assertActions(">S:tell cannot equip"); } void trade_status() { trigger("trade status"); tick(); assertActions(">S:accept trade"); } void loot() { trigger("loot response"); tick(); assertActions(">S:store loot"); } void quest_objective_completed() { trigger("quest objective completed"); tick(); assertActions(">S:quest objective completed"); } void item_push_result() { trigger("item push result"); tick(); assertActions(">S:query item usage"); } void party_command() { trigger("party command"); tick(); assertActions(">S:party command"); } void taxi_done() { trigger("taxi done"); tick(); assertActions(">S:taxi"); } void ready_check() { trigger("ready check"); tick(); assertActions(">S:ready check"); } void ready_check_finished() { trigger("ready check finished"); tick(); assertActions(">S:finish ready check"); } void uninvite() { trigger("uninvite"); tick(); assertActions(">S:uninvite"); } void security_check() { trigger("often"); tick(); tick(); assertActions(">S:security check>S:check mail"); } void guild_accept() { trigger("guild invite"); tick(); assertActions(">S:guild accept"); } void random_bot_update() { trigger("random bot update"); tick(); assertActions(">S:random bot update"); } void delay() { trigger("no non bot players around"); tick(); assertActions(">S:delay"); } }; CPPUNIT_TEST_SUITE_REGISTRATION( WorldPacketHandlerTestCase );
19.969231
108
0.561633
Lidocian
3dbfb7ec317b20d1d50b712a6ecc29a3c718378d
18,526
hpp
C++
libs/fnd/span/include/bksge/fnd/span/span.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/span/include/bksge/fnd/span/span.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/span/include/bksge/fnd/span/span.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file span.hpp * * @brief span の定義 * * @author myoukaku */ #ifndef BKSGE_FND_SPAN_SPAN_HPP #define BKSGE_FND_SPAN_SPAN_HPP #include <bksge/fnd/span/config.hpp> #if defined(BKSGE_USE_STD_SPAN) namespace bksge { using std::span; } // namespace bksge #else #include <bksge/fnd/span/fwd/span_fwd.hpp> #include <bksge/fnd/span/dynamic_extent.hpp> #include <bksge/fnd/span/detail/is_array_convertible.hpp> #include <bksge/fnd/span/detail/span_compatible_iterator.hpp> #include <bksge/fnd/span/detail/span_compatible_range.hpp> #include <bksge/fnd/concepts/detail/require.hpp> #include <bksge/fnd/ranges/range_reference_t.hpp> #include <bksge/fnd/ranges/data.hpp> #include <bksge/fnd/ranges/size.hpp> #include <bksge/fnd/type_traits/bool_constant.hpp> #include <bksge/fnd/type_traits/conjunction.hpp> #include <bksge/fnd/type_traits/enable_if.hpp> #include <bksge/fnd/type_traits/is_convertible.hpp> #include <bksge/fnd/type_traits/negation.hpp> #include <bksge/fnd/type_traits/remove_reference.hpp> #include <bksge/fnd/type_traits/remove_cv.hpp> #include <bksge/fnd/type_traits/type_identity.hpp> #include <bksge/fnd/iterator/iter_reference_t.hpp> #include <bksge/fnd/iterator/reverse_iterator.hpp> #include <bksge/fnd/iterator/concepts/contiguous_iterator.hpp> #include <bksge/fnd/iterator/concepts/sized_sentinel_for.hpp> #include <bksge/fnd/memory/to_address.hpp> #include <bksge/fnd/assert.hpp> #include <bksge/fnd/array.hpp> #include <cstddef> namespace bksge { template <typename T, std::size_t Extent> class span { private: template <typename U, std::size_t N> using is_compatible_array = bksge::conjunction< bksge::bool_constant<N == Extent>, detail::is_array_convertible<T, U> >; public: // member types using element_type = T; using value_type = bksge::remove_cv_t<T>; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T*; using const_pointer = T const*; using reference = T&; using const_reference = T const&; using iterator = pointer;//__gnu_cxx::__normal_iterator<pointer, span>; using reverse_iterator = bksge::reverse_iterator<iterator>; // member constants BKSGE_STATIC_CONSTEXPR std::size_t extent = Extent; // constructors, copy and assignment #if !defined(BKSGE_HAS_CXX20_CONCEPTS) template < std::size_t E = Extent, typename = bksge::enable_if_t<E == 0u> > #endif BKSGE_CONSTEXPR span() BKSGE_NOEXCEPT BKSGE_REQUIRES(Extent == 0u) : m_ptr(nullptr) {} template <BKSGE_REQUIRES_PARAM(detail::span_compatible_iterator, T, It)> BKSGE_CXX14_CONSTEXPR explicit span(It first, size_type count) BKSGE_NOEXCEPT : m_ptr(bksge::to_address(first)) { BKSGE_ASSERT(count == Extent); } #if defined(BKSGE_HAS_CXX20_CONCEPTS) template <detail::span_compatible_iterator<T> It, bksge::sized_sentinel_for<It> End> requires (!bksge::is_convertible<End, size_type>::value) #else template < typename It, typename End, typename = bksge::enable_if_t<bksge::conjunction< detail::span_compatible_iterator<It, T>, bksge::sized_sentinel_for<End, It>, bksge::negation<bksge::is_convertible<End, size_type>> >::value> > #endif BKSGE_CXX14_CONSTEXPR explicit span(It first, End last) BKSGE_NOEXCEPT_IF_EXPR(last - first) : m_ptr(bksge::to_address(first)) { BKSGE_ASSERT(static_cast<size_type>(last - first) == Extent); } template <std::size_t N #if !defined(BKSGE_HAS_CXX20_CONCEPTS) , typename = bksge::enable_if_t<N == Extent> #endif > BKSGE_REQUIRES(N == Extent) BKSGE_CXX14_CONSTEXPR span(bksge::type_identity_t<element_type> (&arr)[N]) BKSGE_NOEXCEPT : span(static_cast<pointer>(arr), N) {} template <typename U, std::size_t N #if !defined(BKSGE_HAS_CXX20_CONCEPTS) , typename = bksge::enable_if_t< is_compatible_array<U, N>::value > #endif > BKSGE_REQUIRES(is_compatible_array<U, N>::value) BKSGE_CXX14_CONSTEXPR span(bksge::array<U, N>& arr) BKSGE_NOEXCEPT : span(static_cast<pointer>(arr.data()), N) {} template <typename U, std::size_t N #if !defined(BKSGE_HAS_CXX20_CONCEPTS) , typename = bksge::enable_if_t< is_compatible_array<U const, N>::value > #endif > BKSGE_REQUIRES(is_compatible_array<U const, N>::value) BKSGE_CXX14_CONSTEXPR span(bksge::array<U, N> const& arr) BKSGE_NOEXCEPT : span(static_cast<pointer>(arr.data()), N) {} template <BKSGE_REQUIRES_PARAM(detail::span_compatible_range, T, Range)> BKSGE_CXX14_CONSTEXPR explicit span(Range&& r) BKSGE_NOEXCEPT_IF( BKSGE_NOEXCEPT_EXPR(ranges::data(r)) && BKSGE_NOEXCEPT_EXPR(ranges::size(r))) : span(ranges::data(r), ranges::size(r)) { BKSGE_ASSERT(ranges::size(r) == Extent); } BKSGE_CONSTEXPR span(span const&) BKSGE_NOEXCEPT = default; template < typename U, std::size_t N #if !defined(BKSGE_HAS_CXX20_CONCEPTS) , typename = bksge::enable_if_t< N == bksge::dynamic_extent && detail::is_array_convertible<T, U>::value > #endif > BKSGE_REQUIRES( N == bksge::dynamic_extent && detail::is_array_convertible<T, U>::value) BKSGE_CXX14_CONSTEXPR explicit span(span<U, N> const& s) BKSGE_NOEXCEPT : m_ptr(s.data()) { BKSGE_ASSERT(s.size() == Extent); } template < typename U, std::size_t N #if !defined(BKSGE_HAS_CXX20_CONCEPTS) , bksge::enable_if_t< N == Extent && detail::is_array_convertible<T, U>::value >* = nullptr #endif > BKSGE_REQUIRES( N == Extent && detail::is_array_convertible<T, U>::value) BKSGE_CXX14_CONSTEXPR span(span<U, N> const& s) BKSGE_NOEXCEPT : m_ptr(s.data()) { BKSGE_ASSERT(s.size() == Extent); } ~span() BKSGE_NOEXCEPT = default; BKSGE_CXX14_CONSTEXPR span& operator=(span const&) BKSGE_NOEXCEPT = default; // observers BKSGE_CONSTEXPR size_type size() const BKSGE_NOEXCEPT { return Extent; } BKSGE_CONSTEXPR size_type size_bytes() const BKSGE_NOEXCEPT { return Extent * sizeof(element_type); } BKSGE_NODISCARD BKSGE_CONSTEXPR bool empty() const BKSGE_NOEXCEPT { return size() == 0; } // element access BKSGE_CONSTEXPR reference front() const BKSGE_NOEXCEPT { static_assert(Extent != 0, ""); return BKSGE_ASSERT(!empty()), *this->m_ptr; } BKSGE_CONSTEXPR reference back() const BKSGE_NOEXCEPT { static_assert(Extent != 0, ""); return BKSGE_ASSERT(!empty()), *(this->m_ptr + (size() - 1)); } BKSGE_CONSTEXPR reference operator[](size_type idx) const BKSGE_NOEXCEPT { static_assert(Extent != 0, ""); return BKSGE_ASSERT(idx < size()), *(this->m_ptr + idx); } BKSGE_CONSTEXPR pointer data() const BKSGE_NOEXCEPT { return this->m_ptr; } // iterator support BKSGE_CONSTEXPR iterator begin() const BKSGE_NOEXCEPT { return iterator(this->m_ptr); } BKSGE_CONSTEXPR iterator end() const BKSGE_NOEXCEPT { return iterator(this->m_ptr + this->size()); } BKSGE_CONSTEXPR reverse_iterator rbegin() const BKSGE_NOEXCEPT { return reverse_iterator(this->end()); } BKSGE_CONSTEXPR reverse_iterator rend() const BKSGE_NOEXCEPT { return reverse_iterator(this->begin()); } // subviews template <std::size_t Count> BKSGE_CONSTEXPR span<element_type, Count> first() const BKSGE_NOEXCEPT { static_assert(Count <= Extent, ""); using Sp = span<element_type, Count>; return Sp{this->data(), Count}; } BKSGE_CONSTEXPR span<element_type, bksge::dynamic_extent> first(size_type count) const BKSGE_NOEXCEPT { using Sp = span<element_type, bksge::dynamic_extent>; return BKSGE_ASSERT(count <= size()), Sp{this->data(), count}; } template <std::size_t Count> BKSGE_CONSTEXPR span<element_type, Count> last() const BKSGE_NOEXCEPT { static_assert(Count <= Extent, ""); using Sp = span<element_type, Count>; return Sp{this->data() + (this->size() - Count), Count}; } BKSGE_CONSTEXPR span<element_type, bksge::dynamic_extent> last(size_type count) const BKSGE_NOEXCEPT { using Sp = span<element_type, bksge::dynamic_extent>; return BKSGE_ASSERT(count <= size()), Sp{this->data() + (this->size() - count), count}; } private: template <std::size_t Offset, std::size_t Count> struct subspan_impl { using type = span<element_type, Count>; static BKSGE_CONSTEXPR type get(pointer data) { static_assert(Count <= Extent, ""); static_assert(Count <= (Extent - Offset), ""); return type{data + Offset, Count}; } }; template <std::size_t Offset> struct subspan_impl<Offset, bksge::dynamic_extent> { using type = span<element_type, Extent - Offset>; static BKSGE_CONSTEXPR type get(pointer data) { return type{data + Offset, Extent - Offset}; } }; public: template <std::size_t Offset, std::size_t Count = bksge::dynamic_extent> BKSGE_CONSTEXPR auto subspan() const BKSGE_NOEXCEPT -> typename subspan_impl<Offset, Count>::type { static_assert(Offset <= Extent, ""); return subspan_impl<Offset, Count>::get(this->data()); } BKSGE_CONSTEXPR span<element_type, bksge::dynamic_extent> subspan(size_type offset, size_type count = bksge::dynamic_extent) const BKSGE_NOEXCEPT { using Sp = span<element_type, bksge::dynamic_extent>; return BKSGE_ASSERT(offset <= size()), (count == bksge::dynamic_extent) ? Sp{this->data() + offset, this->size() - offset} : (BKSGE_ASSERT(count <= size()), BKSGE_ASSERT(offset + count <= size()), Sp{this->data() + offset, count}); } private: pointer m_ptr; }; template <typename T> class span<T, bksge::dynamic_extent> { private: template <typename U, std::size_t N> using is_compatible_array = detail::is_array_convertible<T, U>; public: // member types using element_type = T; using value_type = bksge::remove_cv_t<T>; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T*; using const_pointer = T const*; using reference = T&; using const_reference = T const&; using iterator = pointer;//__gnu_cxx::__normal_iterator<pointer, span>; using reverse_iterator = bksge::reverse_iterator<iterator>; // member constants BKSGE_STATIC_CONSTEXPR std::size_t extent = bksge::dynamic_extent; // constructors, copy and assignment BKSGE_CONSTEXPR span() BKSGE_NOEXCEPT : m_extent(0) , m_ptr(nullptr) {} template <BKSGE_REQUIRES_PARAM(detail::span_compatible_iterator, T, It)> BKSGE_CONSTEXPR span(It first, size_type count) BKSGE_NOEXCEPT : m_extent(count) , m_ptr(bksge::to_address(first)) {} #if defined(BKSGE_HAS_CXX20_CONCEPTS) template <detail::span_compatible_iterator<T> It, bksge::sized_sentinel_for<It> End> requires (!bksge::is_convertible<End, size_type>::value) #else template < typename It, typename End, typename = bksge::enable_if_t<bksge::conjunction< detail::span_compatible_iterator<It, T>, bksge::sized_sentinel_for<End, It>, bksge::negation<bksge::is_convertible<End, size_type>> >::value> > #endif BKSGE_CONSTEXPR span(It first, End last) BKSGE_NOEXCEPT_IF_EXPR(last - first) : m_extent(static_cast<size_type>(last - first)) , m_ptr(bksge::to_address(first)) {} template <std::size_t N> BKSGE_CONSTEXPR span(bksge::type_identity_t<element_type> (&arr)[N]) BKSGE_NOEXCEPT : span(static_cast<pointer>(arr), N) {} template <typename U, std::size_t N #if !defined(BKSGE_HAS_CXX20_CONCEPTS) , typename = bksge::enable_if_t< is_compatible_array<U, N>::value > #endif > BKSGE_REQUIRES(is_compatible_array<U, N>::value) BKSGE_CONSTEXPR span(bksge::array<U, N>& arr) BKSGE_NOEXCEPT : span(static_cast<pointer>(arr.data()), N) {} template <typename U, std::size_t N #if !defined(BKSGE_HAS_CXX20_CONCEPTS) , typename = bksge::enable_if_t< is_compatible_array<U const, N>::value > #endif > BKSGE_REQUIRES(is_compatible_array<U const, N>::value) BKSGE_CONSTEXPR span(bksge::array<U, N> const& arr) BKSGE_NOEXCEPT : span(static_cast<pointer>(arr.data()), N) {} template <BKSGE_REQUIRES_PARAM(detail::span_compatible_range, T, Range)> BKSGE_CONSTEXPR span(Range&& r) BKSGE_NOEXCEPT_IF( BKSGE_NOEXCEPT_EXPR(ranges::data(r)) && BKSGE_NOEXCEPT_EXPR(ranges::size(r))) : span(ranges::data(r), ranges::size(r)) {} BKSGE_CONSTEXPR span(span const&) BKSGE_NOEXCEPT = default; template < typename U, std::size_t N #if !defined(BKSGE_HAS_CXX20_CONCEPTS) , typename = bksge::enable_if_t< detail::is_array_convertible<T, U>::value > #endif > BKSGE_REQUIRES(detail::is_array_convertible<T, U>::value) BKSGE_CONSTEXPR span(span<U, N> const& s) BKSGE_NOEXCEPT : m_extent(s.size()) , m_ptr(s.data()) {} ~span() BKSGE_NOEXCEPT = default; BKSGE_CXX14_CONSTEXPR span& operator=(span const&) BKSGE_NOEXCEPT = default; // observers BKSGE_CONSTEXPR size_type size() const BKSGE_NOEXCEPT { return this->m_extent; } BKSGE_CONSTEXPR size_type size_bytes() const BKSGE_NOEXCEPT { return this->m_extent * sizeof(element_type); } BKSGE_NODISCARD BKSGE_CONSTEXPR bool empty() const BKSGE_NOEXCEPT { return size() == 0; } // element access BKSGE_CONSTEXPR reference front() const BKSGE_NOEXCEPT { return BKSGE_ASSERT(!empty()), *this->m_ptr; } BKSGE_CONSTEXPR reference back() const BKSGE_NOEXCEPT { return BKSGE_ASSERT(!empty()), *(this->m_ptr + (size() - 1)); } BKSGE_CONSTEXPR reference operator[](size_type idx) const BKSGE_NOEXCEPT { return BKSGE_ASSERT(idx < size()), *(this->m_ptr + idx); } BKSGE_CONSTEXPR pointer data() const BKSGE_NOEXCEPT { return this->m_ptr; } // iterator support BKSGE_CONSTEXPR iterator begin() const BKSGE_NOEXCEPT { return iterator(this->m_ptr); } BKSGE_CONSTEXPR iterator end() const BKSGE_NOEXCEPT { return iterator(this->m_ptr + this->size()); } BKSGE_CONSTEXPR reverse_iterator rbegin() const BKSGE_NOEXCEPT { return reverse_iterator(this->end()); } BKSGE_CONSTEXPR reverse_iterator rend() const BKSGE_NOEXCEPT { return reverse_iterator(this->begin()); } // subviews template <std::size_t Count> BKSGE_CONSTEXPR span<element_type, Count> first() const BKSGE_NOEXCEPT { using Sp = span<element_type, Count>; return BKSGE_ASSERT(Count <= size()), Sp{this->data(), Count}; } BKSGE_CONSTEXPR span<element_type, bksge::dynamic_extent> first(size_type count) const BKSGE_NOEXCEPT { using Sp = span<element_type, bksge::dynamic_extent>; return BKSGE_ASSERT(count <= size()), Sp{this->data(), count}; } template <std::size_t Count> BKSGE_CONSTEXPR span<element_type, Count> last() const BKSGE_NOEXCEPT { using Sp = span<element_type, Count>; return BKSGE_ASSERT(Count <= size()), Sp{this->data() + (this->size() - Count), Count}; } BKSGE_CONSTEXPR span<element_type, bksge::dynamic_extent> last(size_type count) const BKSGE_NOEXCEPT { using Sp = span<element_type, bksge::dynamic_extent>; return BKSGE_ASSERT(count <= size()), Sp{this->data() + (this->size() - count), count}; } private: template <std::size_t Offset, std::size_t Count> struct subspan_impl { using type = span<element_type, Count>; static BKSGE_CONSTEXPR type get(pointer data, std::size_t size) { return BKSGE_ASSERT(Count <= size), BKSGE_ASSERT(Count <= (size - Offset)), type{data + Offset, Count}; } }; template <std::size_t Offset> struct subspan_impl<Offset, bksge::dynamic_extent> { using type = span<element_type, bksge::dynamic_extent>; static BKSGE_CONSTEXPR type get(pointer data, std::size_t size) { return type{data + Offset, size - Offset}; } }; public: template <std::size_t Offset, std::size_t Count = bksge::dynamic_extent> BKSGE_CONSTEXPR auto subspan() const BKSGE_NOEXCEPT -> typename subspan_impl<Offset, Count>::type { return BKSGE_ASSERT(Offset <= size()), subspan_impl<Offset, Count>::get(this->data(), this->size()); } BKSGE_CONSTEXPR span<element_type, bksge::dynamic_extent> subspan(size_type offset, size_type count = bksge::dynamic_extent) const BKSGE_NOEXCEPT { using Sp = span<element_type, bksge::dynamic_extent>; return BKSGE_ASSERT(offset <= size()), (count == bksge::dynamic_extent) ? Sp{this->data() + offset, this->size() - offset} : (BKSGE_ASSERT(count <= size()), BKSGE_ASSERT(offset + count <= size()), Sp{this->data() + offset, count}); } private: std::size_t m_extent; pointer m_ptr; }; #if defined(BKSGE_HAS_CXX17_DEDUCTION_GUIDES) // deduction guides template <typename T, std::size_t N> span(T(&)[N]) -> span<T, N>; template <typename T, std::size_t N> span(bksge::array<T, N>&) -> span<T, N>; template <typename T, std::size_t N> span(bksge::array<T, N> const&) -> span<T const, N>; #if defined(BKSGE_HAS_CXX20_CONCEPTS) template <bksge::contiguous_iterator It, typename End> #else template < typename It, typename End, typename = bksge::enable_if_t< bksge::contiguous_iterator<It>::value > > #endif span(It, End) -> span<bksge::remove_reference_t<bksge::iter_reference_t<It>>>; template <typename Range> span(Range&&) -> span<bksge::remove_reference_t<ranges::range_reference_t<Range&>>>; #endif } // namespace bksge #endif #include <bksge/fnd/ranges/config.hpp> #if !(defined(BKSGE_USE_STD_SPAN) && defined(BKSGE_USE_STD_RANGES)) #include <bksge/fnd/ranges/concepts/enable_borrowed_range.hpp> #include <bksge/fnd/ranges/concepts/enable_view.hpp> #include <cstddef> BKSGE_RANGES_START_NAMESPACE template <typename T, std::size_t Extent> BKSGE_RANGES_SPECIALIZE_ENABLE_BORROWED_RANGE(true, bksge::span<T, Extent>); template <typename T, std::size_t Extent> BKSGE_RANGES_SPECIALIZE_ENABLE_VIEW((Extent == 0 || Extent == bksge::dynamic_extent), bksge::span<T, Extent>); BKSGE_RANGES_END_NAMESPACE #endif #endif // BKSGE_FND_SPAN_SPAN_HPP
25.171196
111
0.685577
myoukaku
3dc351a18819d609d3b05c4c58ae34908eff6c00
1,832
cpp
C++
glass/src/libnt/native/cpp/NTSpeedController.cpp
shueja-personal/allwpilib
4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b
[ "BSD-3-Clause" ]
707
2016-05-11T16:54:13.000Z
2022-03-30T13:03:15.000Z
glass/src/libnt/native/cpp/NTSpeedController.cpp
shueja-personal/allwpilib
4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b
[ "BSD-3-Clause" ]
2,308
2016-05-12T00:17:17.000Z
2022-03-30T20:08:10.000Z
glass/src/libnt/native/cpp/NTSpeedController.cpp
shueja-personal/allwpilib
4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b
[ "BSD-3-Clause" ]
539
2016-05-11T20:33:26.000Z
2022-03-28T20:20:25.000Z
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "glass/networktables/NTSpeedController.h" #include <fmt/format.h> #include <wpi/StringExtras.h> using namespace glass; NTSpeedControllerModel::NTSpeedControllerModel(std::string_view path) : NTSpeedControllerModel(nt::GetDefaultInstance(), path) {} NTSpeedControllerModel::NTSpeedControllerModel(NT_Inst instance, std::string_view path) : m_nt(instance), m_value(m_nt.GetEntry(fmt::format("{}/Value", path))), m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), m_controllable(m_nt.GetEntry(fmt::format("{}/.controllable", path))), m_valueData(fmt::format("NT_SpdCtrl:{}", path)), m_nameValue(wpi::rsplit(path, '/').second) { m_nt.AddListener(m_value); m_nt.AddListener(m_name); m_nt.AddListener(m_controllable); } void NTSpeedControllerModel::SetPercent(double value) { nt::SetEntryValue(m_value, nt::NetworkTableValue::MakeDouble(value)); } void NTSpeedControllerModel::Update() { for (auto&& event : m_nt.PollListener()) { if (event.entry == m_value) { if (event.value && event.value->IsDouble()) { m_valueData.SetValue(event.value->GetDouble()); } } else if (event.entry == m_name) { if (event.value && event.value->IsString()) { m_nameValue = event.value->GetString(); } } else if (event.entry == m_controllable) { if (event.value && event.value->IsBoolean()) { m_controllableValue = event.value->GetBoolean(); } } } } bool NTSpeedControllerModel::Exists() { return m_nt.IsConnected() && nt::GetEntryType(m_value) != NT_UNASSIGNED; }
34.566038
75
0.670852
shueja-personal
3dc8042fc8abf17f09b30eb2226376c847630ff6
4,748
cpp
C++
src/engine/render/renderer/pass_lighting.cpp
LunarGameTeam/Lunar-GameEngine
b387d7008525681fe06db8811f4f7ee95aa7aaf1
[ "MIT" ]
4
2020-08-07T02:18:13.000Z
2021-07-08T09:46:11.000Z
src/engine/render/renderer/pass_lighting.cpp
LunarGameTeam/Lunar-GameEngine
b387d7008525681fe06db8811f4f7ee95aa7aaf1
[ "MIT" ]
null
null
null
src/engine/render/renderer/pass_lighting.cpp
LunarGameTeam/Lunar-GameEngine
b387d7008525681fe06db8811f4f7ee95aa7aaf1
[ "MIT" ]
null
null
null
#include "render/renderer/pass_lighting.h" #include "core/asset/asset_subsystem.h" #include "render/render_subsystem.h" #include "render/interface/i_light.h" #include "render/rhi/rhi_device.h" #include "render/rhi/rhi_command_list.h" namespace luna { namespace render { LightingRenderPass::LightingRenderPass(): m_default_vs(this), m_shadowmap(this) { } void LightingRenderPass::Init() { RenderPass::Init(); m_pass_name = "Lighting"; ShaderAsset *shader_asset = g_asset_sys->LoadAsset<ShaderAsset>("/assets/built-in/base_shader.hlsl"); m_default_vs = device->CreateShader(); m_default_vs->Init(shader_asset->GetContent(), "lighting_shader"); RHIPipelineStateDesc lighting_desc; lighting_desc.CullMode = LUNAR_CULL_MODE_BACK; lighting_desc.DepthClipEnable = true; lighting_desc.DepthFunc = RHIComparisionFunc::LUNAR_COMPARISON_FUNC_LESS; lighting_desc.DepthTestEnable = true; lighting_desc.DepthWriteEnable = true; lighting_desc.FillMode = LUNAR_FILL_MODE_SOLID; lighting_desc.VS = m_default_vs->VS; lighting_desc.PS = m_default_vs->PS; InitPipeline(lighting_desc); SetRenderTarget(g_render_sys->GetMainRt()); SetUsingMaterialShader(true); } bool LightingRenderPass::OnRenderObjDirtyFilter(RenderObject *node) { return true; } void LightingRenderPass::OnRenderObjPrepare(RenderObject *obj) { RenderPass::OnRenderObjPrepare(obj); if(obj->material) obj->material->Ready(); if (m_shadowmap.Get()) { context->BindTexture(1, m_shadowmap->texture->view.Get()); } BindMaterialParam(obj); } void LightingRenderPass::SetShadowMap(RenderTarget *rt) { m_shadowmap = rt; } void LightingRenderPass::OnRenderPassPrepare() { RenderPass::OnRenderPassPrepare(); IDirectionLight *main_direction_light = g_render_sys->GetMainDirectnalLight(); RHIShaderInput *cb = m_origin->PS->GetConstantBuffer("LightBuffer"); if (cb && main_direction_light) { struct { LVector4f ambient; LVector4f diffuse; LVector4f spec; LVector3f direction; LMatrix4f view; LMatrix4f projection; }buf; buf.ambient = LVector4f(0.05f, 0.05f, 0.05f, 1); buf.spec = LVector4f(0.5f, 0.5f, 0.5f, 1); LVector3f color = main_direction_light->GetColor(); buf.diffuse = LVector4f(color.x(), color.y(), color.z(), 1.f); buf.direction = main_direction_light->GetDirection(); buf.view = *main_direction_light->GetViewMatrix(); buf.projection = main_direction_light->GetProjectionMatrix(); context->UpdateCB(cb, &buf); context->BindCB(cb); } } void LightingRenderPass::BindMaterialParam(RenderObject* obj) { if (!obj->material) return; RHIShaderInput *mat_cb = m_origin->PS->GetConstantBuffer("MaterialBuffer"); LVector<byte> buffer_data; if (mat_cb) { buffer_data.resize(mat_cb->Buffer->GetSize()); byte *dst = buffer_data.data(); for (TSubPtr<ShaderParam> &param : obj->material->GetAllParams()) { auto old_Ps = m_origin->PS; auto it = mat_cb->m_shader_params.find(param->m_param_name); if (it == mat_cb->m_shader_params.end()) continue; ShaderVarInput &input = it->second; switch (param->m_param_type) { default: break; case ShaderParamType::Int: { ShaderParamInt *param_int = static_cast<ShaderParamInt *>(param.Get()); int value = param_int->value; memcpy(dst + input.offset, &value, input.size); break; } case ShaderParamType::Float: { ShaderParamFloat *param_val = static_cast<ShaderParamFloat *>(param.Get()); float value = param_val->value; memcpy(dst + input.offset, &value, input.size); break; } case ShaderParamType::Float2: break; case ShaderParamType::Float3: { ShaderParamFloat3 *param_val = static_cast<ShaderParamFloat3 *>(param.Get()); LVector3f value = param_val->value; memcpy(dst + input.offset, &value, input.size); break; } case ShaderParamType::Float4: break; } } context->UpdateCB(mat_cb, dst); context->BindCB(mat_cb); } for (TSubPtr<ShaderParam> &param : obj->material->GetAllParams()) { switch (param->m_param_type) { case ShaderParamType::Texture2D: { ShaderParamTexture2D *param_tex = static_cast<ShaderParamTexture2D *>(param.Get()); RHIShaderInput *cb = m_origin->PS->GetConstantBuffer(param->m_param_name); if (cb) { param_tex->texture->Init(); context->BindTexture(cb->Slot, param_tex->texture->m_texture->view.Get()); } } break; case ShaderParamType::TextureCube: { ShaderParamTextureCube *param_tex = static_cast<ShaderParamTextureCube *>(param.Get()); RHIShaderInput *cb = m_origin->PS->GetConstantBuffer(param->m_param_name); if (cb) { param_tex->texture->Init(); context->BindTexture(cb->Slot, param_tex->texture->m_texture->view.Get()); } break; } } } } } }
26.52514
102
0.721567
LunarGameTeam
3dca8542a1fec0d1582cd2640b4d1ddf77fd09d4
583
cpp
C++
libkiml/src/stringpool.cpp
alexanderdna/KimL
58915197ac5a85686a9d6126c4c2fe0374419fde
[ "MIT" ]
null
null
null
libkiml/src/stringpool.cpp
alexanderdna/KimL
58915197ac5a85686a9d6126c4c2fe0374419fde
[ "MIT" ]
1
2020-07-13T03:44:19.000Z
2020-07-14T08:32:03.000Z
libkiml/src/stringpool.cpp
alexanderdna/KimL
58915197ac5a85686a9d6126c4c2fe0374419fde
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "stringpool.h" void StringPool::Init(void) { this->buffer.reserve(5120); //5KB } void StringPool::AddString(KIMLCSTRING str) { std::string s(str); std::map<std::string, KIMLUINT>::iterator it = this->table.find(s); if (it == this->table.end()) { KIMLUINT ptr = this->buffer.size(); this->buffer.insert(this->buffer.end(), str, str + s.length() + 1); this->table[s] = ptr; } } KIMLUINT StringPool::GetStringAddress(KIMLCSTRING str) { return this->table[str]; } void StringPool::CleanUp() { this->buffer.clear(); this->table.clear(); }
18.21875
69
0.665523
alexanderdna
3dcaf9903b786f895d5385684bfd728f7534822c
2,455
cc
C++
cpp/src/arrow/util/compression_brotli.cc
thaining/arrow
b796b579b8aba472c6690a49f95e8e174d01a4bb
[ "Apache-2.0" ]
null
null
null
cpp/src/arrow/util/compression_brotli.cc
thaining/arrow
b796b579b8aba472c6690a49f95e8e174d01a4bb
[ "Apache-2.0" ]
null
null
null
cpp/src/arrow/util/compression_brotli.cc
thaining/arrow
b796b579b8aba472c6690a49f95e8e174d01a4bb
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/util/compression_brotli.h" #include <cstddef> #include <cstdint> #include <brotli/decode.h> #include <brotli/encode.h> #include <brotli/types.h> #include "arrow/status.h" #include "arrow/util/macros.h" namespace arrow { namespace util { // ---------------------------------------------------------------------- // Brotli implementation Status BrotliCodec::Decompress(int64_t input_len, const uint8_t* input, int64_t output_len, uint8_t* output_buffer) { std::size_t output_size = output_len; if (BrotliDecoderDecompress(input_len, input, &output_size, output_buffer) != BROTLI_DECODER_RESULT_SUCCESS) { return Status::IOError("Corrupt brotli compressed data."); } return Status::OK(); } int64_t BrotliCodec::MaxCompressedLen(int64_t input_len, const uint8_t* ARROW_ARG_UNUSED(input)) { return BrotliEncoderMaxCompressedSize(input_len); } Status BrotliCodec::Compress(int64_t input_len, const uint8_t* input, int64_t output_buffer_len, uint8_t* output_buffer, int64_t* output_length) { std::size_t output_len = output_buffer_len; // TODO: Make quality configurable. We use 8 as a default as it is the best // trade-off for Parquet workload if (BrotliEncoderCompress(8, BROTLI_DEFAULT_WINDOW, BROTLI_DEFAULT_MODE, input_len, input, &output_len, output_buffer) == BROTLI_FALSE) { return Status::IOError("Brotli compression failure."); } *output_length = output_len; return Status::OK(); } } // namespace util } // namespace arrow
36.641791
85
0.686354
thaining
3dcdd7e74d5134fba2e875283e9efd952dcb025b
36,638
cc
C++
src/brepr.cc
trucnguyenlam/mucke
bf856f0bb5e758e6c6c32766e50d7957167679d8
[ "BSD-4-Clause-UC" ]
null
null
null
src/brepr.cc
trucnguyenlam/mucke
bf856f0bb5e758e6c6c32766e50d7957167679d8
[ "BSD-4-Clause-UC" ]
null
null
null
src/brepr.cc
trucnguyenlam/mucke
bf856f0bb5e758e6c6c32766e50d7957167679d8
[ "BSD-4-Clause-UC" ]
null
null
null
/* (C) 1996-1999 Armin Biere, University of Karlsruhe * (C) 2000 Armin Biere, ETH Zuerich * $Id: brepr.cc,v 1.6 2008-03-03 11:40:40 biere Exp $ */ /*TOC------------------------------------------------------------------------. | BoolePredicate | | BoolePredicateManager | | BooleQuantification | | BooleSubstitution | `---------------------------------------------------------------------------*/ #include "brepr.h" #include "boole.h" #include "booleman.h" #include "cHash.h" #include "debug.h" #include "io.h" #include "init.h" #include "macros.h" #include "String.h" #include "Symbol.h" extern "C" { #include <stdio.h> }; #include "except.h" /*---------------------------------------------------------------------------*/ BoolePredicateManager * BoolePredicateManager::_instance = 0; /*---------------------------------------------------------------------------*/ static char BoolePredicateManager_stats_buffer [2000]; // 80 x 25 /*--------------------------------------------------------------------------*/ BooleSubstitution::BooleSubstitution() : Substitution(BoolePredicateManager::instance()), data(0) {} /*---------------------------------------------------------------------------*/ BooleSubstitution::BooleSubstitution( Allocation * f, Allocation * t, const Idx<IntAL> & m, const Idx<int> & r) : Substitution(BoolePredicateManager::instance(), f, t, m, r), data(0) {} /*---------------------------------------------------------------------------*/ BooleSubstitution::~BooleSubstitution() { if(data) delete data; } /*---------------------------------------------------------------------------*/ Substitution* BooleSubstitution::create( Allocation * f, Allocation * t, const Idx<IntAL> & i, const Idx<int> & res) { return new BooleSubstitution(f, t, i, res); } /*---------------------------------------------------------------------------*/ class BoolePredicate : public PredRepr { friend class BoolePredicateManager; Boole b; public: void setAllocation(Allocation * a) { if(_allocation) { ASSERT(_allocation == a); } else _allocation = a; } void setAllocation(BoolePredicate * a) { setAllocation(a -> allocation()); } void setAllocation(BoolePredicate * a, BoolePredicate * b) { Allocation * aalloc = a -> allocation(); if(aalloc) setAllocation(aalloc); else setAllocation(b -> allocation()); } void setAllocation( BoolePredicate * a, BoolePredicate * b, BoolePredicate * c) { Allocation * alloc = a -> allocation(); if(alloc) setAllocation(alloc); else { alloc = b -> allocation(); if(alloc) setAllocation(alloc); else setAllocation(c -> allocation()); } } void rangify_aux(Allocation * a) { ASSERT(!allocation() || allocation() == a); if(verbose > 2) verbose << "[have to rangify]\n"; ((BoolePredicateManager*)manager()) -> numRangified++; Boole tmp; ((BoolePredicateManager*)manager()) -> is_in_range_of(a, tmp); b.andop(tmp); } /* Restrict the boolean representation by the range, which defined as the * type context in which the current predice is used. This context is * determined by the allocation. */ void rangify() { if(allocation()) rangify_aux(allocation()); else ASSERT(b.isTrue() || b.isFalse()); } BoolePredicate() : PredRepr(BoolePredicateManager::instance()) { } ~BoolePredicate() { } }; /*---------------------------------------------------------------------------*/ BooleQuantification::BooleQuantification() : Quantification(BoolePredicateManager::instance()), data(0), range(0) {} /*---------------------------------------------------------------------------*/ BooleQuantification::~BooleQuantification() { if(data) delete data; if(range) delete range; } /*---------------------------------------------------------------------------*/ BooleQuantification::BooleQuantification( Allocation * w, const IdxSet & s) : Quantification(BoolePredicateManager::instance(), w, s), data(0), range(0) {} /*---------------------------------------------------------------------------*/ Quantification * BooleQuantification::create(Allocation * w, const IdxSet & s) { return new BooleQuantification(w, s); } /*---------------------------------------------------------------------------*/ Quantification * BooleQuantification::create_projection(Allocation * a, int i, AccessList * al) { BooleQuantification * res; { IdxSet empty_idx_set; res = new BooleQuantification(a, empty_idx_set); } { IdxSet boole_var_set; if(al) { AllocationBucket * bucket = a -> operator [] (i); Type * type = bucket -> type(); AccessList new_al(type); Iterator<int> it(*al); it.first(); while(true) { int k = it.get(), max = type -> num_cpts(); ASSERT(max>0); for(int j=0; j<max; j++) if(j!=k) { new_al.insert(j); { int start, end, delta; BoolePredicateManager::instance() -> indices(a, i, &new_al, start, end, delta); for(int l=start; l<=end; l+=delta) boole_var_set.put(l); } new_al.removeLast(); } it.next(); if(it.isDone()) break; else new_al.insert(k); } } res -> data = Boole::new_var_set(boole_var_set); } res -> range = BoolePredicateManager::instance() -> generate_range(a); return res; } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::indices( Allocation * alloc, int v, AccessList * al, int & start, int & end, int & delta) { AllocationBucket * bucket; int v_size; bucket = alloc -> operator [] ( v ); delta = bucket -> block() -> length(); start = v - bucket -> block() -> first() -> index(); start += sizeOfBlocksBeforeBucket(alloc, bucket); if(al) { Type * type = bucket -> type(); Iterator<int> it(*al); for(it.first(); !it.isDone(); it.next()) { int i = it.get(); Allocation * type_alloc = type -> allocation(); if(type_alloc) { Array<int> * indices = type -> indices(); int j = (*indices) [ i ]; int o = offset_in_alloc(type_alloc, j); int d = delta_in_alloc(type_alloc, j); start += o * delta; delta *= d; } else { start += sizeOfTypesBeforeInt(type, i) * delta; // delta *= 1; } if(type -> isArray() || type -> isEnum() || type -> isRange()) { type = type -> typeOfArray(); } else type = (type -> type_components()) [ i ]; } v_size = size_of(type); } else v_size = size_of(bucket -> type()); end = (v_size-1) * delta + start; } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::sizeOfBlocksBeforeBucket( Allocation * alloc, AllocationBucket * bucket) { int res = 0; AllocationBlock * p; for(p = alloc -> first(); p != bucket -> block(); p = p -> next()) { int max = 0, count = 0; AllocationBucket* q; // slow, slow , schnarch, schnarch // should store this information somewhere !!!!!!!!!!!!! for(q = p -> first(); q; q = q -> next()) { int size = size_of(q -> type()); if(size > max) max = size; count++; } res += count * max; } return res; } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::sizeOfTypesBeforeInt(Type * type, int i) { int res; if(type -> isArray()) { res = size_of(type -> typeOfArray()); res *= i; } else if(type -> isEnum() || type -> isRange()) { res = ld_ceiling32(type -> size()) - 1 - i; } else { res = 0; Type ** cpts = type -> type_components(); for(int j=0; j<i; j++) res += size_of(cpts[ j ]); } return res; } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::offset_in_alloc(Allocation * alloc, int i) { AllocationBucket * bucket = (*alloc) [ i ]; int res = i - bucket -> block() -> first() -> index(); res += sizeOfBlocksBeforeBucket(alloc, bucket); return res; } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::delta_in_alloc(Allocation * alloc, int i) { AllocationBucket * bucket = (*alloc) [ i ]; return bucket -> block() -> length(); } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::binary_size(Allocation * alloc) { AllocationBlock * p; AllocationBucket * q; int res; for(p = alloc -> first(), res = 0; p; p=p->next()) for(q=p->first(); q; q=q->next()) res += size_of(q->type()); return res; } /*---------------------------------------------------------------------------*/ // Now we have to define some bitvector to integer conversion functions // (as extension or redesign idea a strategy pattern should be used here // which encapsulates the way of conversion for basic Types) /* Explanation for geq (c0, x0 most significant bit) x0 x >= c0 c <=> x0 > c0 \/ x0 = c0 /\ x >= c <=> c0 = 0 /\ ( x0 > 0 \/ x0 = 0 /\ x >= c) \/ c0 = 1 /\ ( x0 > 1 \/ x0 = 1 /\ x >= c) <=> c0 = 0 /\ ( x0 \/ !x0 /\ x >= c) \/ c0 = 1 /\ ( 0 \/ x0 /\ x >= c) <=> c0 = 0 /\ ( x0 \/ x >= c) \/ c0 = 1 /\ ( x0 /\ x >= c) */ void BoolePredicateManager::geq( Allocation * alloc, Boole & b, int v, AccessList * al, int c) { int start, end, delta; indices(alloc, v, al, start, end, delta); b.bool_to_Boole(true); int mask = 1; int i; for(i=end; i>=start; i-=delta) { bool bit = c & mask; Boole a; a.var_to_Boole(var(i)); // the next two lines look simple, // but it took me half an hour to derive this! if(bit) b.andop(a); else b.orop(a); mask <<= 1; } } /*---------------------------------------------------------------------------*/ /* Eplanation for leq (c0, x0 most significant bit) x0 x <= c0 c <=> x0 < c0 \/ x0 = c0 /\ x <= c <=> c0 = 0 /\ ( x0 < 0 \/ x0 = 0 /\ x <= c) \/ c0 = 1 /\ ( x0 < 1 \/ x0 = 1 /\ x <= c) <=> c0 = 0 /\ ( 0 \/ !x0 /\ x <= c) \/ c0 = 1 /\ ( !x0 \/ x0 /\ x <= c) <=> c0 = 0 /\ ( !x0 /\ x <= c) \/ c0 = 1 /\ ( !x0 \/ x <= c) */ void BoolePredicateManager::leq( Allocation * alloc, Boole & b, int v, AccessList * al, int c) { int start, end, delta; indices(alloc, v, al, start, end, delta); b.bool_to_Boole(true); int mask = 1; int i; for(i=end; i>=start; i-=delta) { bool bit = c & mask; Boole a; a.var_to_Boole(var(i)); // ... it took me just 5 minutes ... ;-) a.notop(); if(bit) b.orop(a); else b.andop(a); mask <<= 1; } } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::constant_to_Boole( Allocation * alloc, int c, int v, AccessList * al, Boole & b ) { int start, end, delta; indices(alloc, v,al,start,end,delta); b.bool_to_Boole(true); for(int i=end; i>=start; i -= delta) { Boole a; a.var_to_Boole(var(i)); if( (c&1) == 0 ) // lowest bit first a.notop(); b.andop(a); c >>= 1; } } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::constant_to_predicate( Allocation * alloc, int c, int v, AccessList* al ) { BoolePredicate* res = new BoolePredicate; constant_to_Boole(alloc,c,v,al,res -> b); res -> rangify_aux(alloc); return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::onecube( Allocation * alloc, PredRepr * prp, int v, AccessList * al ) { int start, end, delta; indices(alloc, v, al, start, end, delta); IdxSet set; for(int i=start; i<=end; i += delta) set.put(var(i)); BoolePredicate * bpr = dcast(prp); BoolePredicate * res = new BoolePredicate; res -> b = bpr -> b; res -> b.onecube(set); res -> rangify_aux(alloc); ASSERT(!res -> isFalse()); return res; } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::predicate_to_constant( Allocation * alloc, PredRepr* prp, int v, AccessList * al ) { int start, end, delta; indices(alloc, v, al, start, end, delta); BoolePredicate * bpr = dcast(prp); Boole b = bpr -> b; int res=0; for(int i = start; i<=end; i+=delta) { res <<= 1; Boole tmp; tmp.var_to_Boole(var(i)); tmp.andop(b); if(!tmp.isFalse()) res++; } return res; } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::is_in_range_of(Allocation * alloc, Boole & b) { Boole * cached = (*range_cache) [ alloc ]; if(cached) { b = *cached; } else { b.bool_to_Boole(true); Iterator<int> it(*alloc); for(it.first(); !it.isDone(); it.next()) { int i = it.get(); AllocationBucket * bucket = (*alloc) [ i ]; is_in_range_of(alloc, b, i, bucket); } range_cache -> insert(alloc, new Boole(b)); } } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::is_in_range_of( Allocation * alloc, Boole & b, int v, AllocationBucket * bucket ) { Type * type = bucket -> type(); if(type -> isBasic()) { int size = type -> size(); ASSERT(size); Boole a; leq(alloc, a, v, 0, size - 1); b.andop(a); } else { AccessList al(type); is_in_range_of(alloc, b, v, al); } } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::is_in_range_of( Allocation * alloc, Boole & b, int v, AccessList & al ) { Type * type = al.last(); if(type -> isBasic()) { int size = type -> size(); ASSERT(size); Boole a; leq(alloc, a, v, &al, size - 1); b.andop(a); } else { int num_cpts = type -> num_cpts(); for(int i=0; i<num_cpts; i++) { al.insert(i); is_in_range_of(alloc, b,v,al); al.removeLast(); } } } /*---------------------------------------------------------------------------*/ BoolePredicate * BoolePredicateManager::generate_range(Allocation * alloc) { BoolePredicate * res; res = new BoolePredicate; is_in_range_of(alloc, res -> b); return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::compare_variables( Allocation * alloc, int u, AccessList * ual, int v, AccessList * val ) { int ustart, uend, udelta; indices(alloc, u,ual,ustart,uend,udelta); int vstart, vend, vdelta; indices(alloc, v,val,vstart,vend,vdelta); BoolePredicate* res = new BoolePredicate; res -> b.bool_to_Boole(true); int i, j; for(i=uend, j=vend; i>=ustart && j>=vstart; i -= udelta, j -= vdelta) { Boole a, b; a.var_to_Boole(var(i)); b.var_to_Boole(var(j)); a.equiv(b); res -> b.andop(a); } ASSERT(i < ustart && j < vstart); res -> setAllocation(alloc); res -> rangify(); return res; } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::size_of(Type* t) { if(t->isArray()) { return size_of(t->typeOfArray()) * t->num_cpts(); } else if(t->isCompound()) { int result=0; int max = t->num_cpts(); Type ** cpts = t->type_components(); for(int i=0; i<max; i++) result += size_of(cpts[i]); return result; } else return ld_ceiling32(t->size()); } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::size_of(AccessList *al) { return size_of(al->last()); } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::offset_of(AccessList * al) { int result=0; Type * t = al->type(); Iterator<int> it(*al); for(it.first(); !it.isDone(); it.next()) { int i = it.get(); if(t->isArray()) { t = t->typeOfArray(); result += size_of(t) * i; } else if(t -> isEnum() || t -> isRange()) { result += ld_ceiling32(t -> size()) - 1 - i; } else // must be compound! { Type ** cpts = t->type_components(); for(int j=0; j<i; j++) result += size_of(cpts[j]); t = cpts[i]; } } return result; } /*---------------------------------------------------------------------------*/ BoolePredicate * BoolePredicateManager::dcast(PredRepr* pr) { if(pr->manager() != this) error << "dynamic cast to `BoolePredicate *' not implemented" << TypeViolation(); return (BoolePredicate*) pr; } /*---------------------------------------------------------------------------*/ BooleQuantification * BoolePredicateManager::dcast_quant(Quantification * q) { if(q->manager() != this) error << "dynamic cast to `BooleQuantification *' not implemented" << TypeViolation(); return (BooleQuantification*) q; } /*---------------------------------------------------------------------------*/ BooleSubstitution * BoolePredicateManager::dcast_subs(Substitution * s) { if(s->manager() != this) error << "dynamic cast to `BooleSubstitution *' not implemented" << TypeViolation(); return (BooleSubstitution*) s; } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::var(unsigned int v) { if(v>=MaxVars) error << "BoolePredicateManager: Maximum Number of Variables exceeded" << Internal(); while(num_vars<=v) { variables[num_vars++] = Boole::new_var(); } return variables[v]; } /*---------------------------------------------------------------------------*/ BoolePredicateManager * BoolePredicateManager::instance() { if(_instance==0) _instance = new BoolePredicateManager(); return _instance; } /*---------------------------------------------------------------------------*/ static bool allocCmp(const Allocation *a, const Allocation *b) { return a == b; } /*---------------------------------------------------------------------------*/ static unsigned allocHash(const Allocation * a) { return (unsigned) a; } /*---------------------------------------------------------------------------*/ BoolePredicateManager::BoolePredicateManager() { _instance = this; // break circular dependency subs_exemplar = new BooleSubstitution(); quant_exemplar = new BooleQuantification(); num_vars=0; numApplications = numLazyApplications = numQuantors = numSpecialQuantors = numRangified = 0; range_cache = new cHashTable<Allocation,Boole>(allocCmp,allocHash); } /*---------------------------------------------------------------------------*/ BoolePredicateManager::~BoolePredicateManager() { delete range_cache; } /*---------------------------------------------------------------------------*/ bool BoolePredicateManager::isValid(PredRepr* pr) { return dcast(pr) -> b.isValid(); } /*---------------------------------------------------------------------------*/ bool BoolePredicateManager::isTrue(PredRepr* pr) { BoolePredicate * b = dcast(pr); if(b -> b.isTrue()) return true; if(!b -> allocation()) return false; Boole range; is_in_range_of(b -> allocation(), range); return range.doesImply(b -> b); } /*---------------------------------------------------------------------------*/ bool BoolePredicateManager::isFalse(PredRepr* pr) { BoolePredicate * b = dcast(pr); return b -> b.isFalse(); } /*---------------------------------------------------------------------------*/ bool BoolePredicateManager::areEqual(PredRepr * apr, PredRepr * bpr) { BoolePredicate * a = dcast(apr), * b = dcast(bpr); return a -> b == b -> b; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::from_bool(bool b, Allocation * a) { BoolePredicate * res = new BoolePredicate; res -> b.bool_to_Boole(b); res -> setAllocation(a); res -> rangify(); return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::copy(PredRepr* pred_rep) { BoolePredicate * br = dcast(pred_rep); BoolePredicate * res = new BoolePredicate(); res -> b = br -> b; res -> rangify(); return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::binary( PredRepr* apr, PredRepr* bpr, void (Boole::*f)(const Boole &) ) { BoolePredicate * a = dcast(apr), * b = dcast(bpr); BoolePredicate * res = new BoolePredicate(); res -> b = a -> b; (res -> b.*f)(b -> b); res -> setAllocation(a,b); res -> rangify(); return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::andop(PredRepr* a, PredRepr* b) { return binary(a,b, &Boole::andop); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::implies(PredRepr* a, PredRepr* b) { return binary(a,b, &Boole::implies); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::seilpmi(PredRepr* a, PredRepr* b) { return binary(a,b, &Boole::seilpmi); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::equiv(PredRepr* a, PredRepr* b) { return binary(a, b, &Boole::equiv); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::notequiv(PredRepr * a, PredRepr * b) { // If a and b are rangified (a=a&r, b=b&r) // a != b <=> a&!b | !a&b <=> a&r&!b | !a&b&r // <=> r & (a&!b | !a&b) <=> r&(a != b) return binary(a, b, &Boole::notequiv); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::simplify_assuming( PredRepr * a, PredRepr * b) { return binary(a, b, &Boole::simplify_assuming); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::cofactor( PredRepr * a, PredRepr * b) { return binary(a, b, &Boole::cofactor); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::orop(PredRepr* a, PredRepr* b) { return binary(a,b, &Boole::orop); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::notop(PredRepr* apr) { BoolePredicate * a = dcast(apr); BoolePredicate * res = new BoolePredicate(); res -> b = a -> b; res -> b.notop(); res -> setAllocation(a); res -> rangify(); return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::ite( PredRepr* cpr, PredRepr * tpr, PredRepr * epr) { BoolePredicate * c = dcast(cpr), * t = dcast(tpr), * e = dcast(epr); BoolePredicate * res = new BoolePredicate(); res -> b = c -> b; res -> b.ite(t -> b, e -> b); res -> setAllocation(c,t,e); res -> rangify(); return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::exists(PredRepr * apr, Quantification * q) { BooleQuantification * bq = dcast_quant(q); prepare_quantification(bq); BoolePredicate * res = new BoolePredicate(); res -> b = dcast(apr) -> b; res -> b.exists(bq -> data); res -> rangify(); numQuantors++; return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::forall(PredRepr * apr, Quantification * q) { BooleQuantification * bq = dcast_quant(q); prepare_quantification(bq); BoolePredicate * res = new BoolePredicate(); res -> b = dcast(apr) -> b; res -> b.seilpmi(bq -> range -> b); res -> b.forall(bq -> data); res -> rangify(); numQuantors++; return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::relprod( PredRepr* apr, Quantification* q, PredRepr* bpr, Substitution * s1, Substitution * s2) { BooleQuantification * bq = dcast_quant(q); BoolePredicate * a = dcast(apr), * b = dcast(bpr); prepare_quantification(bq); BoolePredicate * res = new BoolePredicate(); if(s1 || s2) { BooleSubstitution * bs; Boole tmp; if(s1 && s2) { BooleSubstitution * bs1 = dcast_subs(s1); if(!bs1->data) prepare(bs1); BooleSubstitution * bs2 = dcast_subs(s2); if(!bs2->data) prepare(bs2); if(a -> b.size() < b -> b.size()) { res -> b = a -> b; res -> b.substitute(bs1 -> data); tmp = b -> b; bs = bs2; } else { res -> b = b -> b; res -> b.substitute(bs2 -> data); tmp = a -> b; bs = bs1; } numApplications++; // ?! } else if(s1) { bs = dcast_subs(s1); if(!bs->data) prepare(bs); res -> b = b -> b; tmp = a -> b; } else { ASSERT(s2); bs = dcast_subs(s2); if(!bs->data) prepare(bs); res -> b = a -> b; tmp = b -> b; } ASSERT(bs -> data); res -> b.relprod(bq -> data, tmp, bs -> data); numLazyApplications++; numSpecialQuantors++; } else { Boole tmp; res -> b = b -> b; res -> b.relprod(bq -> data, a -> b); numSpecialQuantors++; } res -> rangify(); return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::forallImplies( PredRepr * apr, Quantification * q, PredRepr * bpr, Substitution * s1, Substitution * s2) { BoolePredicate * a = dcast(apr), * b = dcast(bpr); BooleQuantification * bq = dcast_quant(q); prepare_quantification(bq); BoolePredicate * res = new BoolePredicate(); res -> b = a -> b; if(s1) { BooleSubstitution * bs = dcast_subs(s1); if(!bs->data) prepare(bs); res -> b.substitute(bs->data); numApplications++; } Boole tmp = b -> b; if(s2) { BooleSubstitution * bs = dcast_subs(s2); if(!bs->data) prepare(bs); tmp.substitute(bs -> data); numApplications++; } tmp.seilpmi(bq -> range -> b); res -> b.forallImplies(bq -> data, tmp); res -> rangify(); numSpecialQuantors++; return res; } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::forallOr( PredRepr * apr, Quantification * q, PredRepr * bpr, Substitution * s1, Substitution * s2) { BoolePredicate * a = dcast(apr), * b = dcast(bpr); BooleQuantification * bq = dcast_quant(q); prepare_quantification(bq); BoolePredicate * res = new BoolePredicate(); res -> b = a -> b; if(s1) { BooleSubstitution * bs = dcast_subs(s1); if(!bs->data) prepare(bs); res -> b.substitute(bs->data); numApplications++; } Boole tmp = b -> b; if(s2) { BooleSubstitution * bs = dcast_subs(s2); if(!bs->data) prepare(bs); tmp.substitute(bs->data); // this could be delayed numApplications++; } tmp.seilpmi(bq -> range -> b); res -> b.forallOr(bq -> data, tmp); res -> rangify(); numSpecialQuantors++; return res; } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::prepare_quantification(BooleQuantification * bq) { if(!bq->data) { IdxSet s; IdxSetIterator it(*bq->set); for(it.first(); !it.isDone(); it.next() ) { int start, end, delta, i; indices(bq -> allocation(), it.get(), 0, start, end, delta); for(i=start; i<=end; i+=delta) s.put(var(i)); } bq->data = Boole::new_var_set(s); } if(!bq->range) { bq -> range = generate_range(bq -> allocation()); } } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::prepare(BooleSubstitution * bs) { ASSERT(!bs -> data); Idx<int> m1; IdxBoole m2; IdxIterator<IntAL> it(*bs->map); IdxIterator<int> it2(*bs->restriction); it2.first(); for(it.first(); !it.isDone(); it.next() ) { int start_from = 0, start_to = 0, end_from = 0, end_to = 0, delta_from = 0, delta_to = 0, j = 0, i = 0; indices(bs -> from, it.from(), it.to().from_al, start_from, end_from, delta_from); indices(bs -> to, it.to().i, it.to().to_al, start_to, end_to, delta_to); # ifdef DEBUG { if(!( (end_from - start_from) / delta_from == (end_to - start_to) / delta_to || (end_from == start_from && end_to == start_to) ) ) internal << "BoolePredicateManager::prepare: something went terribly wrong" << Internal(); } # endif for(i=start_from, j=start_to; i<=end_from; i+=delta_from, j+=delta_to) { if(it2.isDone()) m1.map(var(i),var(j)); else { Boole v; v.var_to_Boole(var(j)); m2.map(var(i), v); } } } if(!it2.isDone()) { for(it2.first(); !it2.isDone(); it2.next()) { int start, end, delta, c = it2.to(); indices(bs -> from, it2.from(), 0, start, end, delta); for(int i = end; i>=start; i-=delta) { Boole b; b.bool_to_Boole(c&1); m2.map(var(i), b); c >>= 1; } } bs -> data = Boole::new_sub(m2); } else bs->data = Boole::new_sub(m1); } /*---------------------------------------------------------------------------*/ PredRepr * BoolePredicateManager::apply(PredRepr* apr, Substitution * s) { BoolePredicate * a = dcast(apr); BoolePredicate * res = new BoolePredicate(); BooleSubstitution * bs = dcast_subs(s); if(!bs->data) prepare(bs); res -> b = a -> b; res -> b.substitute(bs->data); numApplications++; res -> rangify(); return res; } /*---------------------------------------------------------------------------*/ const char * BoolePredicateManager::stats() { sprintf(BoolePredicateManager_stats_buffer, "BoolePredicateManager:\n\ %d PredRepr's (subs%d lsubs%d quant%d squant%d rangified%d rangecache%u)\n%s", num_reprs, numApplications, numLazyApplications, numQuantors, numSpecialQuantors, numRangified, range_cache -> size(), Boole::manager->stats()); return BoolePredicateManager_stats_buffer; } /*---------------------------------------------------------------------------*/ int BoolePredicateManager::size(PredRepr* apr) { BoolePredicate * a = dcast(apr); return a -> b.size(); } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::addTo_IdxStrMapper( int i, char * prefix, Array<char *> * res, Type * type, int start, int delta, Type * new_type) { Allocation * type_alloc; int j, o, d, new_start, new_delta; Array<int> * indices; type_alloc = type -> allocation(); if(type_alloc) { indices = type -> indices(); j = (*indices) [ i ]; o = offset_in_alloc(type_alloc, j); d = delta_in_alloc(type_alloc, j); new_start = start + o * delta; new_delta = delta * d; } else { new_start = start + sizeOfTypesBeforeInt(type, i) * delta; new_delta = delta; } addTo_IdxStrMapper(prefix, res, new_type, new_start, new_delta); } /*------------------------------------------------------------------------*/ void BoolePredicateManager::addTo_IdxStrMapper( char * prefix, Array<char *> * res, Type * type, int start, int delta) { int i, size, j; Symbol ** symbols; Type * new_type, ** types; char * new_prefix, * tmp1, * tmp2; if(type -> isBasic()) { if(type -> isBool()) { ASSERT(start == delta); res -> operator [] (start) = duplicate(prefix); } else if(type -> isEnum() || type -> isRange()) { size = size_of(type); for(i = 0; i < size; i++) { tmp1 = duplicate(ITOA(i)); tmp2 = append("[", tmp1); delete [] tmp1; tmp1 = append(tmp2, "]"); delete [] tmp2; j = start + (size - i - 1) * delta; res -> operator [] (j) = append(prefix, tmp1); delete [] tmp1; } } else internal << "unknown Type\n" << Internal(); } else if(type -> isCompound()) { symbols = type -> symbol_components(); types = type -> type_components(); for(i = 0; i < type -> num_cpts(); i++) { tmp1 = append(".", symbols[i] -> name()); new_prefix = append(prefix, tmp1); delete [] tmp1; new_type = types[i]; addTo_IdxStrMapper(i,new_prefix,res,type,start,delta,new_type); delete [] new_prefix; } } else if(type -> isArray()) { for(i = 0; i < type -> num_cpts(); i++) { tmp1 = duplicate(ITOA(i)); tmp2 = append("[", tmp1); delete [] tmp1; tmp1 = append(tmp2, "]"); delete [] tmp2; new_prefix = append(prefix, tmp1); delete [] tmp1; new_type = type -> typeOfArray(); addTo_IdxStrMapper(i,new_prefix,res,type,start,delta,new_type); delete [] new_prefix; } } else internal << "not implemented\n" << Internal(); } /*---------------------------------------------------------------------------*/ Array<char *> * BoolePredicateManager::prepare_IdxStrMapper( Array<char *> * varnames, Allocation * alloc) { int start, delta, i, size; Array<char *> * res; AllocationBucket * bucket; Type * type; res = new Array<char*>(binary_size(alloc)); for(i = 0, size = alloc -> size(); i < size; i++) { bucket = alloc -> operator [] (i); delta = bucket -> block() -> length(); start = i - bucket -> block() -> first() -> index(); start += sizeOfBlocksBeforeBucket(alloc, bucket); type = bucket -> type(); addTo_IdxStrMapper(varnames -> operator [] (i), res, type, start, delta); } return res; } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::dump( PredRepr * apr, Array<char *> * varnames, Allocation * alloc, void (*print)(char*)) { Array<char *> * names; BoolePredicate * p; int i; ASSERT(varnames -> size() == alloc -> size()); names = prepare_IdxStrMapper(varnames, alloc); p = dcast(apr); p -> b.dump(names, print); for(i = 0; i< names -> size(); i++) delete [] names -> get(i); delete names; } /*---------------------------------------------------------------------------*/ float BoolePredicateManager::onsetsize(PredRepr * apr, Allocation * alloc) { IdxSet set; Iterator<int> it(*alloc); for(it.first(); !it.isDone(); it.next()) { int s, e, d; indices(alloc, it.get(), 0, s, e, d); for(int i = s; i<=e; i += d) set.put(i); } BoolePredicate * a = dcast(apr); Boole tmp; is_in_range_of(alloc, tmp); tmp.andop(a -> b); return tmp.onsetsize(set); } /*---------------------------------------------------------------------------*/ bool BoolePredicateManager::isExactlyOneValue( PredRepr * repr, Allocation * a, int i) { IdxSet set; int start, end, delta; indices(a, i, 0, start, end, delta); for(int j=start; j<=end; j+=delta) set.put(j); BoolePredicate * p = dcast(repr); Boole tmp; is_in_range_of(a, tmp); tmp.andop(p -> b); return tmp.onsetsize(set) == 1.0; } /*---------------------------------------------------------------------------*/ void BoolePredicateManager::visualize(PredRepr * prp) { BoolePredicate * p = dcast(prp); p -> b.visualize(); } /*---------------------------------------------------------------------------*/
23.395913
109
0.481167
trucnguyenlam
3dce70b1ce463fd95c96a45c8ad93c5d9a561d55
7,054
cpp
C++
3dparty/taglib/taglib/riff/wav/wavfile.cpp
olanser/uteg
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
[ "MIT" ]
3,066
2016-06-10T09:23:40.000Z
2022-03-31T11:01:01.000Z
3dparty/taglib/taglib/riff/wav/wavfile.cpp
olanser/uteg
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
[ "MIT" ]
414
2016-09-20T20:26:05.000Z
2022-03-29T00:43:13.000Z
3dparty/taglib/taglib/riff/wav/wavfile.cpp
olanser/uteg
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
[ "MIT" ]
310
2016-06-13T21:53:04.000Z
2022-03-18T14:36:38.000Z
/*************************************************************************** copyright : (C) 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tdebug.h> #include <tstringlist.h> #include <tpropertymap.h> #include <tagutils.h> #include "wavfile.h" #include "id3v2tag.h" #include "infotag.h" #include "tagunion.h" using namespace TagLib; namespace { enum { ID3v2Index = 0, InfoIndex = 1 }; } class RIFF::WAV::File::FilePrivate { public: FilePrivate() : properties(0), hasID3v2(false), hasInfo(false) {} ~FilePrivate() { delete properties; } Properties *properties; TagUnion tag; bool hasID3v2; bool hasInfo; }; //////////////////////////////////////////////////////////////////////////////// // static members //////////////////////////////////////////////////////////////////////////////// bool RIFF::WAV::File::isSupported(IOStream *stream) { // A WAV file has to start with "RIFF????WAVE". const ByteVector id = Utils::readHeader(stream, 12, false); return (id.startsWith("RIFF") && id.containsAt("WAVE", 8)); } //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// RIFF::WAV::File::File(FileName file, bool readProperties, Properties::ReadStyle) : RIFF::File(file, LittleEndian), d(new FilePrivate()) { if(isOpen()) read(readProperties); } RIFF::WAV::File::File(IOStream *stream, bool readProperties, Properties::ReadStyle) : RIFF::File(stream, LittleEndian), d(new FilePrivate()) { if(isOpen()) read(readProperties); } RIFF::WAV::File::~File() { delete d; } ID3v2::Tag *RIFF::WAV::File::tag() const { return ID3v2Tag(); } ID3v2::Tag *RIFF::WAV::File::ID3v2Tag() const { return d->tag.access<ID3v2::Tag>(ID3v2Index, false); } RIFF::Info::Tag *RIFF::WAV::File::InfoTag() const { return d->tag.access<RIFF::Info::Tag>(InfoIndex, false); } void RIFF::WAV::File::strip(TagTypes tags) { removeTagChunks(tags); if(tags & ID3v2) d->tag.set(ID3v2Index, new ID3v2::Tag()); if(tags & Info) d->tag.set(InfoIndex, new RIFF::Info::Tag()); } PropertyMap RIFF::WAV::File::properties() const { return d->tag.properties(); } void RIFF::WAV::File::removeUnsupportedProperties(const StringList &unsupported) { d->tag.removeUnsupportedProperties(unsupported); } PropertyMap RIFF::WAV::File::setProperties(const PropertyMap &properties) { InfoTag()->setProperties(properties); return ID3v2Tag()->setProperties(properties); } RIFF::WAV::Properties *RIFF::WAV::File::audioProperties() const { return d->properties; } bool RIFF::WAV::File::save() { return RIFF::WAV::File::save(AllTags); } bool RIFF::WAV::File::save(TagTypes tags, bool stripOthers, int id3v2Version) { return save(tags, stripOthers ? StripOthers : StripNone, id3v2Version == 3 ? ID3v2::v3 : ID3v2::v4); } bool RIFF::WAV::File::save(TagTypes tags, StripTags strip, ID3v2::Version version) { if(readOnly()) { debug("RIFF::WAV::File::save() -- File is read only."); return false; } if(!isValid()) { debug("RIFF::WAV::File::save() -- Trying to save invalid file."); return false; } if(strip == StripOthers) File::strip(static_cast<TagTypes>(AllTags & ~tags)); if(tags & ID3v2) { removeTagChunks(ID3v2); if(ID3v2Tag() && !ID3v2Tag()->isEmpty()) { setChunkData("ID3 ", ID3v2Tag()->render(version)); d->hasID3v2 = true; } } if(tags & Info) { removeTagChunks(Info); if(InfoTag() && !InfoTag()->isEmpty()) { setChunkData("LIST", InfoTag()->render(), true); d->hasInfo = true; } } return true; } bool RIFF::WAV::File::hasID3v2Tag() const { return d->hasID3v2; } bool RIFF::WAV::File::hasInfoTag() const { return d->hasInfo; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void RIFF::WAV::File::read(bool readProperties) { for(unsigned int i = 0; i < chunkCount(); ++i) { const ByteVector name = chunkName(i); if(name == "ID3 " || name == "id3 ") { if(!d->tag[ID3v2Index]) { d->tag.set(ID3v2Index, new ID3v2::Tag(this, chunkOffset(i))); d->hasID3v2 = true; } else { debug("RIFF::WAV::File::read() - Duplicate ID3v2 tag found."); } } else if(name == "LIST") { const ByteVector data = chunkData(i); if(data.startsWith("INFO")) { if(!d->tag[InfoIndex]) { d->tag.set(InfoIndex, new RIFF::Info::Tag(data)); d->hasInfo = true; } else { debug("RIFF::WAV::File::read() - Duplicate INFO tag found."); } } } } if(!d->tag[ID3v2Index]) d->tag.set(ID3v2Index, new ID3v2::Tag()); if(!d->tag[InfoIndex]) d->tag.set(InfoIndex, new RIFF::Info::Tag()); if(readProperties) d->properties = new Properties(this, Properties::Average); } void RIFF::WAV::File::removeTagChunks(TagTypes tags) { if((tags & ID3v2) && d->hasID3v2) { removeChunk("ID3 "); removeChunk("id3 "); d->hasID3v2 = false; } if((tags & Info) && d->hasInfo) { for(int i = static_cast<int>(chunkCount()) - 1; i >= 0; --i) { if(chunkName(i) == "LIST" && chunkData(i).startsWith("INFO")) removeChunk(i); } d->hasInfo = false; } }
26.618868
85
0.523391
olanser
3dcfa251c840550bb543c175dab852b9b79314ad
316,966
hpp
C++
inc/pegtl.hpp
glaba/glc
f262ee29594da9cee3ddfb476baa4a300d0eace4
[ "MIT" ]
null
null
null
inc/pegtl.hpp
glaba/glc
f262ee29594da9cee3ddfb476baa4a300d0eace4
[ "MIT" ]
null
null
null
inc/pegtl.hpp
glaba/glc
f262ee29594da9cee3ddfb476baa4a300d0eace4
[ "MIT" ]
null
null
null
/* Welcome to the Parsing Expression Grammar Template Library (PEGTL). -e See https://github.com/taocpp/PEGTL/ for more information, documentation, etc. -e The library is licensed as follows: The MIT License (MIT) Copyright (c) 2007-2020 Dr. Colin Hirsch and Daniel Frey 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. -e */ #line 1 "amalgamated.hpp" #line 1 "<built-in>" #line 1 "<command-line>" #line 1 "amalgamated.hpp" #line 1 "tao/pegtl.hpp" #line 1 "tao/pegtl.hpp" #ifndef TAO_PEGTL_HPP #define TAO_PEGTL_HPP #line 1 "tao/pegtl/config.hpp" #line 1 "tao/pegtl/config.hpp" #ifndef TAO_PEGTL_CONFIG_HPP #define TAO_PEGTL_CONFIG_HPP #if !defined( TAO_PEGTL_NAMESPACE ) #define TAO_PEGTL_NAMESPACE tao::pegtl #endif #endif #line 8 "tao/pegtl.hpp" #line 1 "tao/pegtl/version.hpp" #line 1 "tao/pegtl/version.hpp" #ifndef TAO_PEGTL_VERSION_HPP #define TAO_PEGTL_VERSION_HPP #define TAO_PEGTL_VERSION "3.0.0" #define TAO_PEGTL_VERSION_MAJOR 3 #define TAO_PEGTL_VERSION_MINOR 0 #define TAO_PEGTL_VERSION_PATCH 0 #endif #line 9 "tao/pegtl.hpp" #line 1 "tao/pegtl/parse.hpp" #line 1 "tao/pegtl/parse.hpp" #ifndef TAO_PEGTL_PARSE_HPP #define TAO_PEGTL_PARSE_HPP #include <cassert> #line 1 "tao/pegtl/apply_mode.hpp" #line 1 "tao/pegtl/apply_mode.hpp" #ifndef TAO_PEGTL_APPLY_MODE_HPP #define TAO_PEGTL_APPLY_MODE_HPP namespace TAO_PEGTL_NAMESPACE { enum class apply_mode : bool { action = true, nothing = false }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 10 "tao/pegtl/parse.hpp" #line 1 "tao/pegtl/normal.hpp" #line 1 "tao/pegtl/normal.hpp" #ifndef TAO_PEGTL_NORMAL_HPP #define TAO_PEGTL_NORMAL_HPP #include <string> #include <type_traits> #include <utility> #line 1 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/match.hpp" #ifndef TAO_PEGTL_MATCH_HPP #define TAO_PEGTL_MATCH_HPP #include <type_traits> #line 1 "tao/pegtl/nothing.hpp" #line 1 "tao/pegtl/nothing.hpp" #ifndef TAO_PEGTL_NOTHING_HPP #define TAO_PEGTL_NOTHING_HPP namespace TAO_PEGTL_NAMESPACE { template< typename Rule > struct nothing { }; using maybe_nothing = nothing< void >; } // namespace TAO_PEGTL_NAMESPACE #endif #line 12 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/require_apply.hpp" #line 1 "tao/pegtl/require_apply.hpp" #ifndef TAO_PEGTL_REQUIRE_APPLY_HPP #define TAO_PEGTL_REQUIRE_APPLY_HPP namespace TAO_PEGTL_NAMESPACE { struct require_apply {}; } // namespace TAO_PEGTL_NAMESPACE #endif #line 13 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/require_apply0.hpp" #line 1 "tao/pegtl/require_apply0.hpp" #ifndef TAO_PEGTL_REQUIRE_APPLY0_HPP #define TAO_PEGTL_REQUIRE_APPLY0_HPP namespace TAO_PEGTL_NAMESPACE { struct require_apply0 {}; } // namespace TAO_PEGTL_NAMESPACE #endif #line 14 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/rewind_mode.hpp" #line 1 "tao/pegtl/rewind_mode.hpp" #ifndef TAO_PEGTL_REWIND_MODE_HPP #define TAO_PEGTL_REWIND_MODE_HPP namespace TAO_PEGTL_NAMESPACE { enum class rewind_mode : char { active, required, dontcare }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 15 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/internal/dusel_mode.hpp" #line 1 "tao/pegtl/internal/dusel_mode.hpp" #ifndef TAO_PEGTL_INTERNAL_DUSEL_MODE_HPP #define TAO_PEGTL_INTERNAL_DUSEL_MODE_HPP namespace TAO_PEGTL_NAMESPACE::internal { enum class dusel_mode : char { nothing = 0, control = 1, control_and_apply_void = 2, control_and_apply_bool = 3, control_and_apply0_void = 4, control_and_apply0_bool = 5 }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 17 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/internal/duseltronik.hpp" #line 1 "tao/pegtl/internal/duseltronik.hpp" #ifndef TAO_PEGTL_INTERNAL_DUSELTRONIK_HPP #define TAO_PEGTL_INTERNAL_DUSELTRONIK_HPP #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4702 ) #endif namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, dusel_mode = dusel_mode::nothing > struct duseltronik; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing > { template< typename Input, typename... States > [[nodiscard]] static auto match( Input& in, States&&... st ) -> decltype( Rule::template match< A, M, Action, Control >( in, st... ) ) { return Rule::template match< A, M, Action, Control >( in, st... ); } template< typename Input, typename... States, int = 1 > [[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) -> decltype( Rule::match( in ) ) { return Rule::match( in ); } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control > { template< typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { Control< Rule >::start( static_cast< const Input& >( in ), st... ); if( duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing >::match( in, st... ) ) { Control< Rule >::success( static_cast< const Input& >( in ), st... ); return true; } Control< Rule >::failure( static_cast< const Input& >( in ), st... ); return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply_void > { template< typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::required >(); Control< Rule >::start( static_cast< const Input& >( in ), st... ); if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) { Control< Rule >::template apply< Action >( m.iterator(), static_cast< const Input& >( in ), st... ); Control< Rule >::success( static_cast< const Input& >( in ), st... ); return m( true ); } Control< Rule >::failure( static_cast< const Input& >( in ), st... ); return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply_bool > { template< typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::required >(); Control< Rule >::start( static_cast< const Input& >( in ), st... ); if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) { if( Control< Rule >::template apply< Action >( m.iterator(), static_cast< const Input& >( in ), st... ) ) { Control< Rule >::success( static_cast< const Input& >( in ), st... ); return m( true ); } } Control< Rule >::failure( static_cast< const Input& >( in ), st... ); return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply0_void > { template< typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { Control< Rule >::start( static_cast< const Input& >( in ), st... ); if( duseltronik< Rule, A, M, Action, Control, dusel_mode::nothing >::match( in, st... ) ) { Control< Rule >::template apply0< Action >( static_cast< const Input& >( in ), st... ); Control< Rule >::success( static_cast< const Input& >( in ), st... ); return true; } Control< Rule >::failure( static_cast< const Input& >( in ), st... ); return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::control_and_apply0_bool > { template< typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::required >(); Control< Rule >::start( static_cast< const Input& >( in ), st... ); if( duseltronik< Rule, A, rewind_mode::active, Action, Control, dusel_mode::nothing >::match( in, st... ) ) { if( Control< Rule >::template apply0< Action >( static_cast< const Input& >( in ), st... ) ) { Control< Rule >::success( static_cast< const Input& >( in ), st... ); return m( true ); } } Control< Rule >::failure( static_cast< const Input& >( in ), st... ); return false; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #ifdef _MSC_VER #pragma warning( pop ) #endif #endif #line 18 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/internal/has_apply.hpp" #line 1 "tao/pegtl/internal/has_apply.hpp" #ifndef TAO_PEGTL_INTERNAL_HAS_APPLY_HPP #define TAO_PEGTL_INTERNAL_HAS_APPLY_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { template< typename, typename, template< typename... > class, typename... > struct has_apply : std::false_type {}; template< typename C, template< typename... > class Action, typename... S > struct has_apply< C, decltype( C::template apply< Action >( std::declval< S >()... ) ), Action, S... > : std::true_type {}; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 19 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/internal/has_apply0.hpp" #line 1 "tao/pegtl/internal/has_apply0.hpp" #ifndef TAO_PEGTL_INTERNAL_HAS_APPLY0_HPP #define TAO_PEGTL_INTERNAL_HAS_APPLY0_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { template< typename, typename, template< typename... > class, typename... > struct has_apply0 : std::false_type {}; template< typename C, template< typename... > class Action, typename... S > struct has_apply0< C, decltype( C::template apply0< Action >( std::declval< S >()... ) ), Action, S... > : std::true_type {}; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 20 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/internal/missing_apply.hpp" #line 1 "tao/pegtl/internal/missing_apply.hpp" #ifndef TAO_PEGTL_INTERNAL_MISSING_APPLY_HPP #define TAO_PEGTL_INTERNAL_MISSING_APPLY_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< typename Control, template< typename... > class Action, typename Input, typename... States > void missing_apply( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::required >(); (void)Control::template apply< Action >( m.iterator(), in, st... ); } } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 21 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/internal/missing_apply0.hpp" #line 1 "tao/pegtl/internal/missing_apply0.hpp" #ifndef TAO_PEGTL_INTERNAL_MISSING_APPLY0_HPP #define TAO_PEGTL_INTERNAL_MISSING_APPLY0_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< typename Control, template< typename... > class Action, typename Input, typename... States > void missing_apply0( Input& in, States&&... st ) { (void)Control::template apply0< Action >( in, st... ); } } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 22 "tao/pegtl/match.hpp" #line 1 "tao/pegtl/internal/skip_control.hpp" #line 1 "tao/pegtl/internal/skip_control.hpp" #ifndef TAO_PEGTL_INTERNAL_SKIP_CONTROL_HPP #define TAO_PEGTL_INTERNAL_SKIP_CONTROL_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { // This class is a simple tagging mechanism. // By default, skip_control< Rule > is 'false'. // Each internal (!) rule that should be hidden // from the control and action class' callbacks // simply specializes skip_control<> to return // 'true' for the above expression. template< typename Rule > inline constexpr bool skip_control = false; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 23 "tao/pegtl/match.hpp" namespace TAO_PEGTL_NAMESPACE { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] bool match( Input& in, States&&... st ) { constexpr bool enable_control = !internal::skip_control< Rule >; constexpr bool enable_action = enable_control && ( A == apply_mode::action ); using iterator_t = typename Input::iterator_t; constexpr bool has_apply_void = enable_action && internal::has_apply< Control< Rule >, void, Action, const iterator_t&, const Input&, States... >::value; constexpr bool has_apply_bool = enable_action && internal::has_apply< Control< Rule >, bool, Action, const iterator_t&, const Input&, States... >::value; constexpr bool has_apply = has_apply_void || has_apply_bool; constexpr bool has_apply0_void = enable_action && internal::has_apply0< Control< Rule >, void, Action, const Input&, States... >::value; constexpr bool has_apply0_bool = enable_action && internal::has_apply0< Control< Rule >, bool, Action, const Input&, States... >::value; constexpr bool has_apply0 = has_apply0_void || has_apply0_bool; static_assert( !( has_apply && has_apply0 ), "both apply() and apply0() defined" ); constexpr bool is_nothing = std::is_base_of_v< nothing< Rule >, Action< Rule > >; static_assert( !( has_apply && is_nothing ), "unexpected apply() defined" ); static_assert( !( has_apply0 && is_nothing ), "unexpected apply0() defined" ); if constexpr( !has_apply && std::is_base_of_v< require_apply, Action< Rule > > ) { internal::missing_apply< Control< Rule >, Action >( in, st... ); } if constexpr( !has_apply0 && std::is_base_of_v< require_apply0, Action< Rule > > ) { internal::missing_apply0< Control< Rule >, Action >( in, st... ); } constexpr bool validate_nothing = std::is_base_of_v< maybe_nothing, Action< void > >; constexpr bool is_maybe_nothing = std::is_base_of_v< maybe_nothing, Action< Rule > >; static_assert( !enable_action || !validate_nothing || is_nothing || is_maybe_nothing || has_apply || has_apply0, "either apply() or apply0() must be defined" ); constexpr auto mode = static_cast< internal::dusel_mode >( enable_control + has_apply_void + 2 * has_apply_bool + 3 * has_apply0_void + 4 * has_apply0_bool ); return internal::duseltronik< Rule, A, M, Action, Control, mode >::match( in, st... ); } } // namespace TAO_PEGTL_NAMESPACE #endif #line 14 "tao/pegtl/normal.hpp" #line 1 "tao/pegtl/parse_error.hpp" #line 1 "tao/pegtl/parse_error.hpp" #ifndef TAO_PEGTL_PARSE_ERROR_HPP #define TAO_PEGTL_PARSE_ERROR_HPP #include <ostream> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <vector> #line 1 "tao/pegtl/position.hpp" #line 1 "tao/pegtl/position.hpp" #ifndef TAO_PEGTL_POSITION_HPP #define TAO_PEGTL_POSITION_HPP #include <cstdlib> #include <ostream> #include <sstream> #include <string> #include <utility> #line 1 "tao/pegtl/internal/iterator.hpp" #line 1 "tao/pegtl/internal/iterator.hpp" #ifndef TAO_PEGTL_INTERNAL_ITERATOR_HPP #define TAO_PEGTL_INTERNAL_ITERATOR_HPP #include <cstdlib> namespace TAO_PEGTL_NAMESPACE::internal { struct iterator { iterator() = default; explicit iterator( const char* in_data ) noexcept : data( in_data ) { } iterator( const char* in_data, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept : data( in_data ), byte( in_byte ), line( in_line ), byte_in_line( in_byte_in_line ) { } iterator( const iterator& ) = default; iterator( iterator&& ) = default; ~iterator() = default; iterator& operator=( const iterator& ) = default; iterator& operator=( iterator&& ) = default; void reset() noexcept { *this = iterator(); } const char* data = nullptr; std::size_t byte = 0; std::size_t line = 1; std::size_t byte_in_line = 0; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 16 "tao/pegtl/position.hpp" namespace TAO_PEGTL_NAMESPACE { struct position { position() = delete; position( position&& p ) noexcept : byte( p.byte ), line( p.line ), byte_in_line( p.byte_in_line ), source( std::move( p.source ) ) { } position( const position& ) = default; position& operator=( position&& p ) noexcept { byte = p.byte; line = p.line; byte_in_line = p.byte_in_line; source = std::move( p.source ); return *this; } position& operator=( const position& ) = default; template< typename T > position( const internal::iterator& in_iter, T&& in_source ) : byte( in_iter.byte ), line( in_iter.line ), byte_in_line( in_iter.byte_in_line ), source( std::forward< T >( in_source ) ) { } ~position() = default; std::size_t byte; std::size_t line; std::size_t byte_in_line; std::string source; }; inline std::ostream& operator<<( std::ostream& o, const position& p ) { return o << p.source << ':' << p.line << ':' << p.byte_in_line << '(' << p.byte << ')'; } [[nodiscard]] inline std::string to_string( const position& p ) { std::ostringstream o; o << p; return o.str(); } } // namespace TAO_PEGTL_NAMESPACE #endif #line 16 "tao/pegtl/parse_error.hpp" namespace TAO_PEGTL_NAMESPACE { struct parse_error : std::runtime_error { template< typename Msg > parse_error( Msg&& msg, std::vector< position > in_positions ) : std::runtime_error( std::forward< Msg >( msg ) ), positions( std::move( in_positions ) ) { } template< typename Msg > parse_error( Msg&& msg, const position& pos ) : std::runtime_error( std::forward< Msg >( msg ) ), positions( 1, pos ) { } template< typename Msg > parse_error( Msg&& msg, position&& pos ) : std::runtime_error( std::forward< Msg >( msg ) ) { positions.emplace_back( std::move( pos ) ); } template< typename Msg, typename Input > parse_error( Msg&& msg, const Input& in ) : parse_error( std::forward< Msg >( msg ), in.position() ) { } std::vector< position > positions; }; inline std::ostream& operator<<( std::ostream& o, const parse_error& e ) { for( auto it = e.positions.rbegin(); it != e.positions.rend(); ++it ) { o << *it << ": "; } return o << e.what(); } [[nodiscard]] inline std::string to_string( const parse_error& e ) { std::ostringstream o; o << e; return o.str(); } } // namespace TAO_PEGTL_NAMESPACE #endif #line 15 "tao/pegtl/normal.hpp" #line 1 "tao/pegtl/internal/demangle.hpp" #line 1 "tao/pegtl/internal/demangle.hpp" #ifndef TAO_PEGTL_INTERNAL_DEMANGLE_HPP #define TAO_PEGTL_INTERNAL_DEMANGLE_HPP #include <ciso646> #include <string_view> namespace TAO_PEGTL_NAMESPACE::internal { #if defined( __clang__ ) #if defined( _LIBCPP_VERSION ) template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = sv.find( '=' ); static_assert( begin != std::string_view::npos ); return sv.substr( begin + 2, sv.size() - begin - 3 ); } #else // When using libstdc++ with clang, std::string_view::find is not constexpr :( template< char C > constexpr const char* find( const char* p, std::size_t n ) noexcept { while( n ) { if( *p == C ) { return p; } ++p; --n; } return nullptr; } template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = find< '=' >( sv.data(), sv.size() ); static_assert( begin != nullptr ); return { begin + 2, sv.data() + sv.size() - begin - 3 }; } #endif #elif defined( __GNUC__ ) #if( __GNUC__ == 7 ) // GCC 7 wrongly sometimes disallows __PRETTY_FUNCTION__ in constexpr functions, // therefore we drop the 'constexpr' and hope for the best. template< typename T > [[nodiscard]] std::string_view demangle() noexcept { const std::string_view sv = __PRETTY_FUNCTION__; const auto begin = sv.find( '=' ); const auto tmp = sv.substr( begin + 2 ); const auto end = tmp.rfind( ';' ); return tmp.substr( 0, end ); } #elif( __GNUC__ == 9 ) && ( __GNUC_MINOR__ < 3 ) // GCC 9.1 and 9.2 have a bug that leads to truncated __PRETTY_FUNCTION__ names, // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155 template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { // fallback: requires RTTI, no demangling return typeid( T ).name(); } #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __PRETTY_FUNCTION__; constexpr auto begin = sv.find( '=' ); static_assert( begin != std::string_view::npos ); constexpr auto tmp = sv.substr( begin + 2 ); constexpr auto end = tmp.rfind( ';' ); static_assert( end != std::string_view::npos ); return tmp.substr( 0, end ); } #endif #elif defined( _MSC_VER ) #if( _MSC_VER < 1920 ) template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { const std::string_view sv = __FUNCSIG__; const auto begin = sv.find( "demangle<" ); const auto tmp = sv.substr( begin + 9 ); const auto end = tmp.rfind( '>' ); return tmp.substr( 0, end ); } #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { constexpr std::string_view sv = __FUNCSIG__; constexpr auto begin = sv.find( "demangle<" ); static_assert( begin != std::string_view::npos ); constexpr auto tmp = sv.substr( begin + 9 ); constexpr auto end = tmp.rfind( '>' ); static_assert( end != std::string_view::npos ); return tmp.substr( 0, end ); } #endif #else template< typename T > [[nodiscard]] constexpr std::string_view demangle() noexcept { // fallback: requires RTTI, no demangling return typeid( T ).name(); } #endif } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 18 "tao/pegtl/normal.hpp" #line 1 "tao/pegtl/internal/has_match.hpp" #line 1 "tao/pegtl/internal/has_match.hpp" #ifndef TAO_PEGTL_INTERNAL_HAS_MATCH_HPP #define TAO_PEGTL_INTERNAL_HAS_MATCH_HPP #include <type_traits> #include <utility> namespace TAO_PEGTL_NAMESPACE::internal { template< typename, typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > struct has_match : std::false_type {}; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > struct has_match< decltype( (void)Action< Rule >::template match< Rule, A, M, Action, Control >( std::declval< Input& >(), std::declval< States&& >()... ), void() ), Rule, A, M, Action, Control, Input, States... > : std::true_type {}; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > inline constexpr bool has_match_v = has_match< void, Rule, A, M, Action, Control, Input, States... >::value; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 19 "tao/pegtl/normal.hpp" namespace TAO_PEGTL_NAMESPACE { template< typename Rule > constexpr const char* error_message = nullptr; template< typename Rule > struct normal { template< typename Input, typename... States > static void start( const Input& /*unused*/, States&&... /*unused*/ ) noexcept { } template< typename Input, typename... States > static void success( const Input& /*unused*/, States&&... /*unused*/ ) noexcept { } template< typename Input, typename... States > static void failure( const Input& in, States&&... /*unused*/ ) noexcept( error_message< Rule > == nullptr ) { if constexpr( error_message< Rule > != nullptr ) { throw parse_error( error_message< Rule >, in ); } #if defined( _MSC_VER ) else { (void)in; } #endif } template< typename Input, typename... States > static void raise( const Input& in, States&&... /*unused*/ ) { throw parse_error( "parse error matching " + std::string( internal::demangle< Rule >() ), in ); } template< template< typename... > class Action, typename Iterator, typename Input, typename... States > static auto apply( const Iterator& begin, const Input& in, States&&... st ) noexcept( noexcept( Action< Rule >::apply( std::declval< const typename Input::action_t& >(), st... ) ) ) -> decltype( Action< Rule >::apply( std::declval< const typename Input::action_t& >(), st... ) ) { const typename Input::action_t action_input( begin, in ); return Action< Rule >::apply( action_input, st... ); } template< template< typename... > class Action, typename Input, typename... States > static auto apply0( const Input& /*unused*/, States&&... st ) noexcept( noexcept( Action< Rule >::apply0( st... ) ) ) -> decltype( Action< Rule >::apply0( st... ) ) { return Action< Rule >::apply0( st... ); } template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { constexpr rewind_mode m = ( error_message< Rule > == nullptr ) ? M : rewind_mode::dontcare; if constexpr( internal::has_match_v< Rule, A, m, Action, Control, Input, States... > ) { return Action< Rule >::template match< Rule, A, m, Action, Control >( in, st... ); } else { return TAO_PEGTL_NAMESPACE::match< Rule, A, m, Action, Control >( in, st... ); } } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 12 "tao/pegtl/parse.hpp" #line 1 "tao/pegtl/internal/action_input.hpp" #line 1 "tao/pegtl/internal/action_input.hpp" #ifndef TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP #define TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP #include <cstddef> #include <cstdint> #include <string> #include <string_view> namespace TAO_PEGTL_NAMESPACE::internal { template< typename Input > class action_input { public: using input_t = Input; using iterator_t = typename Input::iterator_t; action_input( const iterator_t& in_begin, const Input& in_input ) noexcept : m_begin( in_begin ), m_input( in_input ) { } action_input( const action_input& ) = delete; action_input( action_input&& ) = delete; ~action_input() = default; action_input& operator=( const action_input& ) = delete; action_input& operator=( action_input&& ) = delete; [[nodiscard]] const iterator_t& iterator() const noexcept { return m_begin; } [[nodiscard]] const Input& input() const noexcept { return m_input; } [[nodiscard]] const char* begin() const noexcept { if constexpr( std::is_same_v< iterator_t, const char* > ) { return iterator(); } else { return iterator().data; } } [[nodiscard]] const char* end() const noexcept { return input().current(); } [[nodiscard]] bool empty() const noexcept { return begin() == end(); } [[nodiscard]] std::size_t size() const noexcept { return std::size_t( end() - begin() ); } [[nodiscard]] std::string string() const { return std::string( begin(), size() ); } [[nodiscard]] std::string_view string_view() const noexcept { return std::string_view( begin(), size() ); } [[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept { return begin()[ offset ]; } [[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept { return static_cast< std::uint8_t >( peek_char( offset ) ); } [[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const { return input().position( iterator() ); // NOTE: Not efficient with lazy inputs. } protected: const iterator_t m_begin; const Input& m_input; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 17 "tao/pegtl/parse.hpp" namespace TAO_PEGTL_NAMESPACE { template< typename Rule, template< typename... > class Action = nothing, template< typename... > class Control = normal, apply_mode A = apply_mode::action, rewind_mode M = rewind_mode::required, typename Input, typename... States > bool parse( Input&& in, States&&... st ) { return Control< Rule >::template match< A, M, Action, Control >( in, st... ); } template< typename Rule, template< typename... > class Action = nothing, template< typename... > class Control = normal, apply_mode A = apply_mode::action, rewind_mode M = rewind_mode::required, typename Outer, typename Input, typename... States > bool parse_nested( const Outer& oi, Input&& in, States&&... st ) { try { return parse< Rule, Action, Control, A, M >( in, st... ); } catch( parse_error& e ) { e.positions.push_back( oi.position() ); throw; } } } // namespace TAO_PEGTL_NAMESPACE #endif #line 11 "tao/pegtl.hpp" #line 1 "tao/pegtl/ascii.hpp" #line 1 "tao/pegtl/ascii.hpp" #ifndef TAO_PEGTL_ASCII_HPP #define TAO_PEGTL_ASCII_HPP #line 1 "tao/pegtl/eol.hpp" #line 1 "tao/pegtl/eol.hpp" #ifndef TAO_PEGTL_EOL_HPP #define TAO_PEGTL_EOL_HPP #line 1 "tao/pegtl/internal/eol.hpp" #line 1 "tao/pegtl/internal/eol.hpp" #ifndef TAO_PEGTL_INTERNAL_EOL_HPP #define TAO_PEGTL_INTERNAL_EOL_HPP #line 1 "tao/pegtl/internal/../analysis/generic.hpp" #line 1 "tao/pegtl/internal/../analysis/generic.hpp" #ifndef TAO_PEGTL_ANALYSIS_GENERIC_HPP #define TAO_PEGTL_ANALYSIS_GENERIC_HPP #line 1 "tao/pegtl/internal/../analysis/grammar_info.hpp" #line 1 "tao/pegtl/internal/../analysis/grammar_info.hpp" #ifndef TAO_PEGTL_ANALYSIS_GRAMMAR_INFO_HPP #define TAO_PEGTL_ANALYSIS_GRAMMAR_INFO_HPP #include <map> #include <string> #include <utility> #line 1 "tao/pegtl/internal/../analysis/rule_info.hpp" #line 1 "tao/pegtl/internal/../analysis/rule_info.hpp" #ifndef TAO_PEGTL_ANALYSIS_RULE_INFO_HPP #define TAO_PEGTL_ANALYSIS_RULE_INFO_HPP #include <string> #include <vector> #line 1 "tao/pegtl/internal/../analysis/rule_type.hpp" #line 1 "tao/pegtl/internal/../analysis/rule_type.hpp" #ifndef TAO_PEGTL_ANALYSIS_RULE_TYPE_HPP #define TAO_PEGTL_ANALYSIS_RULE_TYPE_HPP namespace TAO_PEGTL_NAMESPACE::analysis { enum class rule_type : char { any, // Consumption-on-success is always true; assumes bounded repetition of conjunction of sub-rules. opt, // Consumption-on-success not necessarily true; assumes bounded repetition of conjunction of sub-rules. seq, // Consumption-on-success depends on consumption of (non-zero bounded repetition of) conjunction of sub-rules. sor // Consumption-on-success depends on consumption of (non-zero bounded repetition of) disjunction of sub-rules. }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif #line 13 "tao/pegtl/internal/../analysis/rule_info.hpp" namespace TAO_PEGTL_NAMESPACE::analysis { struct rule_info { explicit rule_info( const rule_type in_type ) noexcept : type( in_type ) { } rule_type type; std::vector< std::string > rules; }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif #line 15 "tao/pegtl/internal/../analysis/grammar_info.hpp" namespace TAO_PEGTL_NAMESPACE::analysis { struct grammar_info { using map_t = std::map< std::string_view, rule_info >; map_t map; template< typename Name > auto insert( const rule_type type ) { return map.try_emplace( internal::demangle< Name >(), rule_info( type ) ); } }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif #line 10 "tao/pegtl/internal/../analysis/generic.hpp" #line 1 "tao/pegtl/internal/../analysis/insert_rules.hpp" #line 1 "tao/pegtl/internal/../analysis/insert_rules.hpp" #ifndef TAO_PEGTL_ANALYSIS_INSERT_RULES_HPP #define TAO_PEGTL_ANALYSIS_INSERT_RULES_HPP namespace TAO_PEGTL_NAMESPACE::analysis { template< typename... Rules > struct insert_rules { static void insert( grammar_info& g, rule_info& r ) { ( r.rules.emplace_back( Rules::analyze_t::template insert< Rules >( g ) ), ... ); } }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif #line 11 "tao/pegtl/internal/../analysis/generic.hpp" namespace TAO_PEGTL_NAMESPACE::analysis { template< rule_type Type, typename... Rules > struct generic { template< typename Name > static std::string_view insert( grammar_info& g ) { const auto [ it, success ] = g.insert< Name >( Type ); if( success ) { insert_rules< Rules... >::insert( g, it->second ); } return it->first; } }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif #line 12 "tao/pegtl/internal/eol.hpp" namespace TAO_PEGTL_NAMESPACE::internal { struct eol { using analyze_t = analysis::generic< analysis::rule_type::any >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( Input::eol_t::match( in ) ) ) { return Input::eol_t::match( in ).first; } }; template<> inline constexpr bool skip_control< eol > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/eol.hpp" #line 1 "tao/pegtl/internal/cr_crlf_eol.hpp" #line 1 "tao/pegtl/internal/cr_crlf_eol.hpp" #ifndef TAO_PEGTL_INTERNAL_CR_CRLF_EOL_HPP #define TAO_PEGTL_INTERNAL_CR_CRLF_EOL_HPP #line 1 "tao/pegtl/internal/../eol_pair.hpp" #line 1 "tao/pegtl/internal/../eol_pair.hpp" #ifndef TAO_PEGTL_EOL_PAIR_HPP #define TAO_PEGTL_EOL_PAIR_HPP #include <cstddef> #include <utility> namespace TAO_PEGTL_NAMESPACE { using eol_pair = std::pair< bool, std::size_t >; } // namespace TAO_PEGTL_NAMESPACE #endif #line 9 "tao/pegtl/internal/cr_crlf_eol.hpp" namespace TAO_PEGTL_NAMESPACE::internal { struct cr_crlf_eol { static constexpr int ch = '\r'; template< typename Input > [[nodiscard]] static eol_pair match( Input& in ) noexcept( noexcept( in.size( 2 ) ) ) { eol_pair p = { false, in.size( 2 ) }; if( p.second ) { if( in.peek_char() == '\r' ) { in.bump_to_next_line( 1 + ( ( p.second > 1 ) && ( in.peek_char( 1 ) == '\n' ) ) ); p.first = true; } } return p; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 12 "tao/pegtl/eol.hpp" #line 1 "tao/pegtl/internal/cr_eol.hpp" #line 1 "tao/pegtl/internal/cr_eol.hpp" #ifndef TAO_PEGTL_INTERNAL_CR_EOL_HPP #define TAO_PEGTL_INTERNAL_CR_EOL_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct cr_eol { static constexpr int ch = '\r'; template< typename Input > [[nodiscard]] static eol_pair match( Input& in ) noexcept( noexcept( in.size( 1 ) ) ) { eol_pair p = { false, in.size( 1 ) }; if( p.second ) { if( in.peek_char() == '\r' ) { in.bump_to_next_line(); p.first = true; } } return p; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 13 "tao/pegtl/eol.hpp" #line 1 "tao/pegtl/internal/crlf_eol.hpp" #line 1 "tao/pegtl/internal/crlf_eol.hpp" #ifndef TAO_PEGTL_INTERNAL_CRLF_EOL_HPP #define TAO_PEGTL_INTERNAL_CRLF_EOL_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct crlf_eol { static constexpr int ch = '\n'; template< typename Input > [[nodiscard]] static eol_pair match( Input& in ) noexcept( noexcept( in.size( 2 ) ) ) { eol_pair p = { false, in.size( 2 ) }; if( p.second > 1 ) { if( ( in.peek_char() == '\r' ) && ( in.peek_char( 1 ) == '\n' ) ) { in.bump_to_next_line( 2 ); p.first = true; } } return p; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 14 "tao/pegtl/eol.hpp" #line 1 "tao/pegtl/internal/lf_crlf_eol.hpp" #line 1 "tao/pegtl/internal/lf_crlf_eol.hpp" #ifndef TAO_PEGTL_INTERNAL_LF_CRLF_EOL_HPP #define TAO_PEGTL_INTERNAL_LF_CRLF_EOL_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct lf_crlf_eol { static constexpr int ch = '\n'; template< typename Input > [[nodiscard]] static eol_pair match( Input& in ) noexcept( noexcept( in.size( 2 ) ) ) { eol_pair p = { false, in.size( 2 ) }; if( p.second ) { const auto a = in.peek_char(); if( a == '\n' ) { in.bump_to_next_line(); p.first = true; } else if( ( a == '\r' ) && ( p.second > 1 ) && ( in.peek_char( 1 ) == '\n' ) ) { in.bump_to_next_line( 2 ); p.first = true; } } return p; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 15 "tao/pegtl/eol.hpp" #line 1 "tao/pegtl/internal/lf_eol.hpp" #line 1 "tao/pegtl/internal/lf_eol.hpp" #ifndef TAO_PEGTL_INTERNAL_LF_EOL_HPP #define TAO_PEGTL_INTERNAL_LF_EOL_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct lf_eol { static constexpr int ch = '\n'; template< typename Input > [[nodiscard]] static eol_pair match( Input& in ) noexcept( noexcept( in.size( 1 ) ) ) { eol_pair p = { false, in.size( 1 ) }; if( p.second ) { if( in.peek_char() == '\n' ) { in.bump_to_next_line(); p.first = true; } } return p; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 16 "tao/pegtl/eol.hpp" namespace TAO_PEGTL_NAMESPACE { inline namespace ascii { // this is both a rule and a pseudo-namespace for eol::cr, ... struct eol : internal::eol { // clang-format off struct cr : internal::cr_eol {}; struct cr_crlf : internal::cr_crlf_eol {}; struct crlf : internal::crlf_eol {}; struct lf : internal::lf_eol {}; struct lf_crlf : internal::lf_crlf_eol {}; // clang-format on }; } // namespace ascii } // namespace TAO_PEGTL_NAMESPACE #endif #line 9 "tao/pegtl/ascii.hpp" #line 1 "tao/pegtl/internal/always_false.hpp" #line 1 "tao/pegtl/internal/always_false.hpp" #ifndef TAO_PEGTL_INTERNAL_ALWAYS_FALSE_HPP #define TAO_PEGTL_INTERNAL_ALWAYS_FALSE_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { template< typename... > struct always_false : std::false_type { }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 11 "tao/pegtl/ascii.hpp" #line 1 "tao/pegtl/internal/result_on_found.hpp" #line 1 "tao/pegtl/internal/result_on_found.hpp" #ifndef TAO_PEGTL_INTERNAL_RESULT_ON_FOUND_HPP #define TAO_PEGTL_INTERNAL_RESULT_ON_FOUND_HPP namespace TAO_PEGTL_NAMESPACE::internal { enum class result_on_found : bool { success = true, failure = false }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 12 "tao/pegtl/ascii.hpp" #line 1 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/rules.hpp" #ifndef TAO_PEGTL_INTERNAL_RULES_HPP #define TAO_PEGTL_INTERNAL_RULES_HPP #line 1 "tao/pegtl/internal/action.hpp" #line 1 "tao/pegtl/internal/action.hpp" #ifndef TAO_PEGTL_INTERNAL_ACTION_HPP #define TAO_PEGTL_INTERNAL_ACTION_HPP #line 1 "tao/pegtl/internal/seq.hpp" #line 1 "tao/pegtl/internal/seq.hpp" #ifndef TAO_PEGTL_INTERNAL_SEQ_HPP #define TAO_PEGTL_INTERNAL_SEQ_HPP #line 1 "tao/pegtl/internal/trivial.hpp" #line 1 "tao/pegtl/internal/trivial.hpp" #ifndef TAO_PEGTL_INTERNAL_TRIVIAL_HPP #define TAO_PEGTL_INTERNAL_TRIVIAL_HPP #line 1 "tao/pegtl/internal/../analysis/counted.hpp" #line 1 "tao/pegtl/internal/../analysis/counted.hpp" #ifndef TAO_PEGTL_ANALYSIS_COUNTED_HPP #define TAO_PEGTL_ANALYSIS_COUNTED_HPP #include <cstddef> namespace TAO_PEGTL_NAMESPACE::analysis { template< rule_type Type, std::size_t Count, typename... Rules > struct counted : generic< ( Count != 0 ) ? Type : rule_type::opt, Rules... > { }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif #line 12 "tao/pegtl/internal/trivial.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< bool Result > struct trivial { using analyze_t = analysis::counted< analysis::rule_type::any, unsigned( !Result ) >; template< typename Input > [[nodiscard]] static bool match( Input& /*unused*/ ) noexcept { return Result; } }; template< bool Result > inline constexpr bool skip_control< trivial< Result > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 11 "tao/pegtl/internal/seq.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Rules > struct seq; template<> struct seq<> : trivial< true > { }; template< typename Rule > struct seq< Rule > { using analyze_t = typename Rule::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return Control< Rule >::template match< A, M, Action, Control >( in, st... ); } }; template< typename... Rules > struct seq { using analyze_t = analysis::generic< analysis::rule_type::seq, Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< M >(); using m_t = decltype( m ); return m( ( Control< Rules >::template match< A, m_t::next_rewind_mode, Action, Control >( in, st... ) && ... ) ); } }; template< typename... Rules > inline constexpr bool skip_control< seq< Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 11 "tao/pegtl/internal/action.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< template< typename... > class Action, typename... Rules > struct action { using analyze_t = analysis::generic< analysis::rule_type::seq, Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return duseltronik< seq< Rules... >, A, M, Action, Control >::match( in, st... ); } }; template< template< typename... > class Action, typename... Rules > inline constexpr bool skip_control< action< Action, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 8 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/alnum.hpp" #line 1 "tao/pegtl/internal/alnum.hpp" #ifndef TAO_PEGTL_INTERNAL_ALNUM_HPP #define TAO_PEGTL_INTERNAL_ALNUM_HPP #line 1 "tao/pegtl/internal/peek_char.hpp" #line 1 "tao/pegtl/internal/peek_char.hpp" #ifndef TAO_PEGTL_INTERNAL_PEEK_CHAR_HPP #define TAO_PEGTL_INTERNAL_PEEK_CHAR_HPP #include <cstddef> #line 1 "tao/pegtl/internal/input_pair.hpp" #line 1 "tao/pegtl/internal/input_pair.hpp" #ifndef TAO_PEGTL_INTERNAL_INPUT_PAIR_HPP #define TAO_PEGTL_INTERNAL_INPUT_PAIR_HPP #include <cstdint> namespace TAO_PEGTL_NAMESPACE::internal { template< typename Data > struct input_pair { Data data; std::uint8_t size; using data_t = Data; explicit operator bool() const noexcept { return size > 0; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 12 "tao/pegtl/internal/peek_char.hpp" namespace TAO_PEGTL_NAMESPACE::internal { struct peek_char { using data_t = char; using pair_t = input_pair< char >; static constexpr std::size_t min_input_size = 1; static constexpr std::size_t max_input_size = 1; template< typename Input > [[nodiscard]] static pair_t peek( const Input& in, const std::size_t /*unused*/ = 1 ) noexcept { return { in.peek_char(), 1 }; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/alnum.hpp" #line 1 "tao/pegtl/internal/ranges.hpp" #line 1 "tao/pegtl/internal/ranges.hpp" #ifndef TAO_PEGTL_INTERNAL_RANGES_HPP #define TAO_PEGTL_INTERNAL_RANGES_HPP #line 1 "tao/pegtl/internal/range.hpp" #line 1 "tao/pegtl/internal/range.hpp" #ifndef TAO_PEGTL_INTERNAL_RANGE_HPP #define TAO_PEGTL_INTERNAL_RANGE_HPP #line 14 "tao/pegtl/internal/range.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< result_on_found R, typename Peek, typename Peek::data_t Lo, typename Peek::data_t Hi > struct range { static_assert( Lo <= Hi, "invalid range detected" ); using analyze_t = analysis::generic< analysis::rule_type::any >; template< int Eol > static constexpr bool can_match_eol = ( ( ( Lo <= Eol ) && ( Eol <= Hi ) ) == bool( R ) ); template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.size( Peek::max_input_size ) ) ) { if( const std::size_t s = in.size( Peek::max_input_size ); s >= Peek::min_input_size ) { if( const auto t = Peek::peek( in, s ) ) { if( ( ( Lo <= t.data ) && ( t.data <= Hi ) ) == bool( R ) ) { if constexpr( can_match_eol< Input::eol_t::ch > ) { in.bump( t.size ); } else { in.bump_in_this_line( t.size ); } return true; } } } return false; } }; template< result_on_found R, typename Peek, typename Peek::data_t Lo, typename Peek::data_t Hi > inline constexpr bool skip_control< range< R, Peek, Lo, Hi > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/ranges.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< int Eol, typename Char, Char... Cs > struct ranges_impl; template< int Eol, typename Char > struct ranges_impl< Eol, Char > { static constexpr bool can_match_eol = false; [[nodiscard]] static bool match( const Char /*unused*/ ) noexcept { return false; } }; template< int Eol, typename Char, Char Eq > struct ranges_impl< Eol, Char, Eq > { static constexpr bool can_match_eol = ( Eq == Eol ); [[nodiscard]] static bool match( const Char c ) noexcept { return c == Eq; } }; template< int Eol, typename Char, Char Lo, Char Hi, Char... Cs > struct ranges_impl< Eol, Char, Lo, Hi, Cs... > { static_assert( Lo <= Hi, "invalid range detected" ); static constexpr bool can_match_eol = ( ( ( Lo <= Eol ) && ( Eol <= Hi ) ) || ranges_impl< Eol, Char, Cs... >::can_match_eol ); [[nodiscard]] static bool match( const Char c ) noexcept { return ( ( Lo <= c ) && ( c <= Hi ) ) || ranges_impl< Eol, Char, Cs... >::match( c ); } }; template< typename Peek, typename Peek::data_t... Cs > struct ranges { using analyze_t = analysis::generic< analysis::rule_type::any >; template< int Eol > static constexpr bool can_match_eol = ranges_impl< Eol, typename Peek::data_t, Cs... >::can_match_eol; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.size( Peek::max_input_size ) ) ) { if( const std::size_t s = in.size( Peek::max_input_size ); s >= Peek::min_input_size ) { if( const auto t = Peek::peek( in, s ) ) { if( ranges_impl< Input::eol_t::ch, typename Peek::data_t, Cs... >::match( t.data ) ) { if constexpr( can_match_eol< Input::eol_t::ch > ) { in.bump( t.size ); } else { in.bump_in_this_line( t.size ); } return true; } } } return false; } }; template< typename Peek, typename Peek::data_t Lo, typename Peek::data_t Hi > struct ranges< Peek, Lo, Hi > : range< result_on_found::success, Peek, Lo, Hi > { }; template< typename Peek, typename Peek::data_t... Cs > inline constexpr bool skip_control< ranges< Peek, Cs... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 11 "tao/pegtl/internal/alnum.hpp" namespace TAO_PEGTL_NAMESPACE::internal { using alnum = ranges< peek_char, 'a', 'z', 'A', 'Z', '0', '9' >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 9 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/alpha.hpp" #line 1 "tao/pegtl/internal/alpha.hpp" #ifndef TAO_PEGTL_INTERNAL_ALPHA_HPP #define TAO_PEGTL_INTERNAL_ALPHA_HPP namespace TAO_PEGTL_NAMESPACE::internal { using alpha = ranges< peek_char, 'a', 'z', 'A', 'Z' >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/any.hpp" #line 1 "tao/pegtl/internal/any.hpp" #ifndef TAO_PEGTL_INTERNAL_ANY_HPP #define TAO_PEGTL_INTERNAL_ANY_HPP #line 14 "tao/pegtl/internal/any.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Peek > struct any; template<> struct any< peek_char > { using analyze_t = analysis::generic< analysis::rule_type::any >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.empty() ) ) { if( !in.empty() ) { in.bump(); return true; } return false; } }; template< typename Peek > struct any { using analyze_t = analysis::generic< analysis::rule_type::any >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.size( Peek::max_input_size ) ) ) { if( const std::size_t s = in.size( Peek::max_input_size ); s >= Peek::min_input_size ) { if( const auto t = Peek::peek( in, s ) ) { in.bump( t.size ); return true; } } return false; } }; template< typename Peek > inline constexpr bool skip_control< any< Peek > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 11 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/apply.hpp" #line 1 "tao/pegtl/internal/apply.hpp" #ifndef TAO_PEGTL_INTERNAL_APPLY_HPP #define TAO_PEGTL_INTERNAL_APPLY_HPP #line 1 "tao/pegtl/internal/apply_single.hpp" #line 1 "tao/pegtl/internal/apply_single.hpp" #ifndef TAO_PEGTL_INTERNAL_APPLY_SINGLE_HPP #define TAO_PEGTL_INTERNAL_APPLY_SINGLE_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { template< typename Action > struct apply_single { template< typename Input, typename... States > [[nodiscard]] static auto match( const Input& in, States&&... st ) noexcept( noexcept( Action::apply( in, st... ) ) ) -> std::enable_if_t< std::is_same_v< decltype( Action::apply( in, st... ) ), void >, bool > { Action::apply( in, st... ); return true; } template< typename Input, typename... States > [[nodiscard]] static auto match( const Input& in, States&&... st ) noexcept( noexcept( Action::apply( in, st... ) ) ) -> std::enable_if_t< std::is_same_v< decltype( Action::apply( in, st... ) ), bool >, bool > { return Action::apply( in, st... ); } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/apply.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Actions > struct apply { using analyze_t = analysis::counted< analysis::rule_type::any, 0 >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { if constexpr( ( A == apply_mode::action ) && ( sizeof...( Actions ) > 0 ) ) { using action_t = typename Input::action_t; const action_t i2( in.iterator(), in ); // No data -- range is from begin to begin. return ( apply_single< Actions >::match( i2, st... ) && ... ); } else { #if defined( _MSC_VER ) (void)in; (void)( (void)st, ... ); #endif return true; } } }; template< typename... Actions > inline constexpr bool skip_control< apply< Actions... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 12 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/apply0.hpp" #line 1 "tao/pegtl/internal/apply0.hpp" #ifndef TAO_PEGTL_INTERNAL_APPLY0_HPP #define TAO_PEGTL_INTERNAL_APPLY0_HPP #line 1 "tao/pegtl/internal/apply0_single.hpp" #line 1 "tao/pegtl/internal/apply0_single.hpp" #ifndef TAO_PEGTL_INTERNAL_APPLY0_SINGLE_HPP #define TAO_PEGTL_INTERNAL_APPLY0_SINGLE_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { template< typename Action > struct apply0_single { template< typename... States > [[nodiscard]] static auto match( States&&... st ) noexcept( noexcept( Action::apply0( st... ) ) ) -> std::enable_if_t< std::is_same_v< decltype( Action::apply0( st... ) ), void >, bool > { Action::apply0( st... ); return true; } template< typename... States > [[nodiscard]] static auto match( States&&... st ) noexcept( noexcept( Action::apply0( st... ) ) ) -> std::enable_if_t< std::is_same_v< decltype( Action::apply0( st... ) ), bool >, bool > { return Action::apply0( st... ); } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/apply0.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Actions > struct apply0 { using analyze_t = analysis::counted< analysis::rule_type::any, 0 >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& /*unused*/, States&&... st ) { if constexpr( A == apply_mode::action ) { return ( apply0_single< Actions >::match( st... ) && ... ); } else { #if defined( _MSC_VER ) (void)( (void)st, ... ); #endif return true; } } }; template< typename... Actions > inline constexpr bool skip_control< apply0< Actions... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 13 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/at.hpp" #line 1 "tao/pegtl/internal/at.hpp" #ifndef TAO_PEGTL_INTERNAL_AT_HPP #define TAO_PEGTL_INTERNAL_AT_HPP #line 17 "tao/pegtl/internal/at.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Rules > struct at; template<> struct at<> : trivial< true > { }; template< typename... Rules > struct at { using analyze_t = analysis::generic< analysis::rule_type::opt, Rules... >; template< apply_mode, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { const auto m = in.template mark< rewind_mode::required >(); return ( Control< Rules >::template match< apply_mode::nothing, rewind_mode::active, Action, Control >( in, st... ) && ... ); } }; template< typename... Rules > inline constexpr bool skip_control< at< Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 14 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/bof.hpp" #line 1 "tao/pegtl/internal/bof.hpp" #ifndef TAO_PEGTL_INTERNAL_BOF_HPP #define TAO_PEGTL_INTERNAL_BOF_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct bof { using analyze_t = analysis::generic< analysis::rule_type::opt >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept { return in.byte() == 0; } }; template<> inline constexpr bool skip_control< bof > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 15 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/bol.hpp" #line 1 "tao/pegtl/internal/bol.hpp" #ifndef TAO_PEGTL_INTERNAL_BOL_HPP #define TAO_PEGTL_INTERNAL_BOL_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct bol { using analyze_t = analysis::generic< analysis::rule_type::opt >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept { return in.byte_in_line() == 0; } }; template<> inline constexpr bool skip_control< bol > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 16 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/bytes.hpp" #line 1 "tao/pegtl/internal/bytes.hpp" #ifndef TAO_PEGTL_INTERNAL_BYTES_HPP #define TAO_PEGTL_INTERNAL_BYTES_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< unsigned Num > struct bytes { using analyze_t = analysis::counted< analysis::rule_type::any, Num >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.size( 0 ) ) ) { if( in.size( Num ) >= Num ) { in.bump( Num ); return true; } return false; } }; template< unsigned Num > inline constexpr bool skip_control< bytes< Num > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 17 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/control.hpp" #line 1 "tao/pegtl/internal/control.hpp" #ifndef TAO_PEGTL_INTERNAL_CONTROL_HPP #define TAO_PEGTL_INTERNAL_CONTROL_HPP #line 18 "tao/pegtl/internal/control.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< template< typename... > class Control, typename... Rules > struct control { using analyze_t = analysis::generic< analysis::rule_type::seq, Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return duseltronik< seq< Rules... >, A, M, Action, Control >::match( in, st... ); } }; template< template< typename... > class Control, typename... Rules > inline constexpr bool skip_control< control< Control, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 18 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/disable.hpp" #line 1 "tao/pegtl/internal/disable.hpp" #ifndef TAO_PEGTL_INTERNAL_DISABLE_HPP #define TAO_PEGTL_INTERNAL_DISABLE_HPP #line 18 "tao/pegtl/internal/disable.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Rules > struct disable { using analyze_t = analysis::generic< analysis::rule_type::seq, Rules... >; template< apply_mode, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return duseltronik< seq< Rules... >, apply_mode::nothing, M, Action, Control >::match( in, st... ); } }; template< typename... Rules > inline constexpr bool skip_control< disable< Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 19 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/discard.hpp" #line 1 "tao/pegtl/internal/discard.hpp" #ifndef TAO_PEGTL_INTERNAL_DISCARD_HPP #define TAO_PEGTL_INTERNAL_DISCARD_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct discard { using analyze_t = analysis::generic< analysis::rule_type::opt >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept { static_assert( noexcept( in.discard() ) ); in.discard(); return true; } }; template<> inline constexpr bool skip_control< discard > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 20 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/enable.hpp" #line 1 "tao/pegtl/internal/enable.hpp" #ifndef TAO_PEGTL_INTERNAL_ENABLE_HPP #define TAO_PEGTL_INTERNAL_ENABLE_HPP #line 18 "tao/pegtl/internal/enable.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Rules > struct enable { using analyze_t = analysis::generic< analysis::rule_type::seq, Rules... >; template< apply_mode, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return duseltronik< seq< Rules... >, apply_mode::action, M, Action, Control >::match( in, st... ); } }; template< typename... Rules > inline constexpr bool skip_control< enable< Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 21 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/eof.hpp" #line 1 "tao/pegtl/internal/eof.hpp" #ifndef TAO_PEGTL_INTERNAL_EOF_HPP #define TAO_PEGTL_INTERNAL_EOF_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct eof { using analyze_t = analysis::generic< analysis::rule_type::opt >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.empty() ) ) { return in.empty(); } }; template<> inline constexpr bool skip_control< eof > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 22 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/eolf.hpp" #line 1 "tao/pegtl/internal/eolf.hpp" #ifndef TAO_PEGTL_INTERNAL_EOLF_HPP #define TAO_PEGTL_INTERNAL_EOLF_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct eolf { using analyze_t = analysis::generic< analysis::rule_type::opt >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( Input::eol_t::match( in ) ) ) { const auto p = Input::eol_t::match( in ); return p.first || ( !p.second ); } }; template<> inline constexpr bool skip_control< eolf > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 24 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/identifier.hpp" #line 1 "tao/pegtl/internal/identifier.hpp" #ifndef TAO_PEGTL_INTERNAL_IDENTIFIER_HPP #define TAO_PEGTL_INTERNAL_IDENTIFIER_HPP #line 1 "tao/pegtl/internal/star.hpp" #line 1 "tao/pegtl/internal/star.hpp" #ifndef TAO_PEGTL_INTERNAL_STAR_HPP #define TAO_PEGTL_INTERNAL_STAR_HPP #include <type_traits> #line 19 "tao/pegtl/internal/star.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, typename... Rules > struct star { using analyze_t = analysis::generic< analysis::rule_type::opt, Rule, Rules..., star >; template< apply_mode A, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { while( seq< Rule, Rules... >::template match< A, rewind_mode::required, Action, Control >( in, st... ) ) { } return true; } }; template< typename Rule, typename... Rules > inline constexpr bool skip_control< star< Rule, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 13 "tao/pegtl/internal/identifier.hpp" namespace TAO_PEGTL_NAMESPACE::internal { using identifier_first = ranges< peek_char, 'a', 'z', 'A', 'Z', '_' >; using identifier_other = ranges< peek_char, 'a', 'z', 'A', 'Z', '0', '9', '_' >; using identifier = seq< identifier_first, star< identifier_other > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 25 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/if_apply.hpp" #line 1 "tao/pegtl/internal/if_apply.hpp" #ifndef TAO_PEGTL_INTERNAL_IF_APPLY_HPP #define TAO_PEGTL_INTERNAL_IF_APPLY_HPP #line 16 "tao/pegtl/internal/if_apply.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, typename... Actions > struct if_apply { using analyze_t = typename Rule::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { if constexpr( ( A == apply_mode::action ) && ( sizeof...( Actions ) != 0 ) ) { using action_t = typename Input::action_t; auto m = in.template mark< rewind_mode::required >(); if( Control< Rule >::template match< apply_mode::action, rewind_mode::active, Action, Control >( in, st... ) ) { const action_t i2( m.iterator(), in ); return m( ( apply_single< Actions >::match( i2, st... ) && ... ) ); } return false; } else { return Control< Rule >::template match< A, M, Action, Control >( in, st... ); } } }; template< typename Rule, typename... Actions > inline constexpr bool skip_control< if_apply< Rule, Actions... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 26 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/if_must.hpp" #line 1 "tao/pegtl/internal/if_must.hpp" #ifndef TAO_PEGTL_INTERNAL_IF_MUST_HPP #define TAO_PEGTL_INTERNAL_IF_MUST_HPP #line 1 "tao/pegtl/internal/must.hpp" #line 1 "tao/pegtl/internal/must.hpp" #ifndef TAO_PEGTL_INTERNAL_MUST_HPP #define TAO_PEGTL_INTERNAL_MUST_HPP #line 1 "tao/pegtl/internal/raise.hpp" #line 1 "tao/pegtl/internal/raise.hpp" #ifndef TAO_PEGTL_INTERNAL_RAISE_HPP #define TAO_PEGTL_INTERNAL_RAISE_HPP #include <cstdlib> #include <stdexcept> #include <type_traits> #line 19 "tao/pegtl/internal/raise.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename T > struct raise { using analyze_t = analysis::generic< analysis::rule_type::any >; #if defined( _MSC_VER ) #pragma warning( push ) #pragma warning( disable : 4702 ) #endif template< apply_mode, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { Control< T >::raise( static_cast< const Input& >( in ), st... ); throw std::logic_error( "code should be unreachable: Control< T >::raise() did not throw an exception" ); // LCOV_EXCL_LINE #if defined( _MSC_VER ) #pragma warning( pop ) #endif } }; template< typename T > inline constexpr bool skip_control< raise< T > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/must.hpp" namespace TAO_PEGTL_NAMESPACE::internal { // The general case applies must<> to each of the // rules in the 'Rules' parameter pack individually. template< typename... Rules > struct must { using analyze_t = analysis::generic< analysis::rule_type::seq, Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return ( Control< must< Rules > >::template match< A, M, Action, Control >( in, st... ) && ... ); } }; // While in theory the implementation for a single rule could // be simplified to must< Rule > = sor< Rule, raise< Rule > >, this // would result in some unnecessary run-time overhead. template< typename Rule > struct must< Rule > { using analyze_t = typename Rule::analyze_t; template< apply_mode A, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { if( !Control< Rule >::template match< A, rewind_mode::dontcare, Action, Control >( in, st... ) ) { (void)raise< Rule >::template match< A, rewind_mode::dontcare, Action, Control >( in, st... ); } return true; } }; template< typename... Rules > inline constexpr bool skip_control< must< Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/if_must.hpp" #line 18 "tao/pegtl/internal/if_must.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< bool Default, typename Cond, typename... Rules > struct if_must { using analyze_t = analysis::counted< analysis::rule_type::seq, Default ? 0 : 1, Cond, must< Rules... > >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { if( Control< Cond >::template match< A, M, Action, Control >( in, st... ) ) { (void)( Control< must< Rules > >::template match< A, M, Action, Control >( in, st... ) && ... ); return true; } return Default; } }; template< bool Default, typename Cond, typename... Rules > inline constexpr bool skip_control< if_must< Default, Cond, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 27 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/if_must_else.hpp" #line 1 "tao/pegtl/internal/if_must_else.hpp" #ifndef TAO_PEGTL_INTERNAL_IF_MUST_ELSE_HPP #define TAO_PEGTL_INTERNAL_IF_MUST_ELSE_HPP #line 1 "tao/pegtl/internal/if_then_else.hpp" #line 1 "tao/pegtl/internal/if_then_else.hpp" #ifndef TAO_PEGTL_INTERNAL_IF_THEN_ELSE_HPP #define TAO_PEGTL_INTERNAL_IF_THEN_ELSE_HPP #line 1 "tao/pegtl/internal/not_at.hpp" #line 1 "tao/pegtl/internal/not_at.hpp" #ifndef TAO_PEGTL_INTERNAL_NOT_AT_HPP #define TAO_PEGTL_INTERNAL_NOT_AT_HPP #line 17 "tao/pegtl/internal/not_at.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Rules > struct not_at; template<> struct not_at<> : trivial< false > { }; template< typename... Rules > struct not_at { using analyze_t = analysis::generic< analysis::rule_type::opt, Rules... >; template< apply_mode, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { const auto m = in.template mark< rewind_mode::required >(); return !( Control< Rules >::template match< apply_mode::nothing, rewind_mode::active, Action, Control >( in, st... ) && ... ); } }; template< typename... Rules > inline constexpr bool skip_control< not_at< Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/if_then_else.hpp" #line 1 "tao/pegtl/internal/sor.hpp" #line 1 "tao/pegtl/internal/sor.hpp" #ifndef TAO_PEGTL_INTERNAL_SOR_HPP #define TAO_PEGTL_INTERNAL_SOR_HPP #include <utility> #line 19 "tao/pegtl/internal/sor.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Rules > struct sor; template<> struct sor<> : trivial< false > { }; template< typename... Rules > struct sor : sor< std::index_sequence_for< Rules... >, Rules... > { }; template< std::size_t... Indices, typename... Rules > struct sor< std::index_sequence< Indices... >, Rules... > { using analyze_t = analysis::generic< analysis::rule_type::sor, Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return ( Control< Rules >::template match< A, ( ( Indices == ( sizeof...( Rules ) - 1 ) ) ? M : rewind_mode::required ), Action, Control >( in, st... ) || ... ); } }; template< typename... Rules > inline constexpr bool skip_control< sor< Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 13 "tao/pegtl/internal/if_then_else.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Cond, typename Then, typename Else > struct if_then_else { using analyze_t = analysis::generic< analysis::rule_type::sor, seq< Cond, Then >, seq< not_at< Cond >, Else > >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< M >(); using m_t = decltype( m ); if( Control< Cond >::template match< A, rewind_mode::required, Action, Control >( in, st... ) ) { return m( Control< Then >::template match< A, m_t::next_rewind_mode, Action, Control >( in, st... ) ); } return m( Control< Else >::template match< A, m_t::next_rewind_mode, Action, Control >( in, st... ) ); } }; template< typename Cond, typename Then, typename Else > inline constexpr bool skip_control< if_then_else< Cond, Then, Else > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/internal/if_must_else.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Cond, typename Then, typename Else > using if_must_else = if_then_else< Cond, must< Then >, must< Else > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 28 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/istring.hpp" #line 1 "tao/pegtl/internal/istring.hpp" #ifndef TAO_PEGTL_INTERNAL_ISTRING_HPP #define TAO_PEGTL_INTERNAL_ISTRING_HPP #include <type_traits> #line 1 "tao/pegtl/internal/bump_help.hpp" #line 1 "tao/pegtl/internal/bump_help.hpp" #ifndef TAO_PEGTL_INTERNAL_BUMP_HELP_HPP #define TAO_PEGTL_INTERNAL_BUMP_HELP_HPP #include <cstddef> #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { template< result_on_found R, typename Input, typename Char, Char... Cs > void bump_help( Input& in, const std::size_t count ) noexcept { if constexpr( ( ( Cs != Input::eol_t::ch ) && ... ) != bool( R ) ) { in.bump( count ); } else { in.bump_in_this_line( count ); } } } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 12 "tao/pegtl/internal/istring.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< char C > inline constexpr bool is_alpha = ( ( 'a' <= C ) && ( C <= 'z' ) ) || ( ( 'A' <= C ) && ( C <= 'Z' ) ); template< char C > [[nodiscard]] bool ichar_equal( const char c ) noexcept { if constexpr( is_alpha< C > ) { return ( C | 0x20 ) == ( c | 0x20 ); } else { return c == C; } } template< char... Cs > [[nodiscard]] bool istring_equal( const char* r ) noexcept { return ( ichar_equal< Cs >( *r++ ) && ... ); } template< char... Cs > struct istring; template<> struct istring<> : trivial< true > { }; template< char... Cs > struct istring { using analyze_t = analysis::counted< analysis::rule_type::any, sizeof...( Cs ) >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.size( 0 ) ) ) { if( in.size( sizeof...( Cs ) ) >= sizeof...( Cs ) ) { if( istring_equal< Cs... >( in.current() ) ) { bump_help< result_on_found::success, Input, char, Cs... >( in, sizeof...( Cs ) ); return true; } } return false; } }; template< char... Cs > inline constexpr bool skip_control< istring< Cs... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 30 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/list.hpp" #line 1 "tao/pegtl/internal/list.hpp" #ifndef TAO_PEGTL_INTERNAL_LIST_HPP #define TAO_PEGTL_INTERNAL_LIST_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, typename Sep > using list = seq< Rule, star< Sep, Rule > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 31 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/list_must.hpp" #line 1 "tao/pegtl/internal/list_must.hpp" #ifndef TAO_PEGTL_INTERNAL_LIST_MUST_HPP #define TAO_PEGTL_INTERNAL_LIST_MUST_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, typename Sep > using list_must = seq< Rule, star< Sep, must< Rule > > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 32 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/list_tail.hpp" #line 1 "tao/pegtl/internal/list_tail.hpp" #ifndef TAO_PEGTL_INTERNAL_LIST_TAIL_HPP #define TAO_PEGTL_INTERNAL_LIST_TAIL_HPP #line 1 "tao/pegtl/internal/opt.hpp" #line 1 "tao/pegtl/internal/opt.hpp" #ifndef TAO_PEGTL_INTERNAL_OPT_HPP #define TAO_PEGTL_INTERNAL_OPT_HPP #include <type_traits> #line 21 "tao/pegtl/internal/opt.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename... Rules > struct opt; template<> struct opt<> : trivial< true > { }; template< typename... Rules > struct opt { using analyze_t = analysis::generic< analysis::rule_type::opt, Rules... >; template< apply_mode A, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { (void)duseltronik< seq< Rules... >, A, rewind_mode::required, Action, Control >::match( in, st... ); return true; } }; template< typename... Rules > inline constexpr bool skip_control< opt< Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 11 "tao/pegtl/internal/list_tail.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, typename Sep > using list_tail = seq< list< Rule, Sep >, opt< Sep > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 33 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/list_tail_pad.hpp" #line 1 "tao/pegtl/internal/list_tail_pad.hpp" #ifndef TAO_PEGTL_INTERNAL_LIST_TAIL_PAD_HPP #define TAO_PEGTL_INTERNAL_LIST_TAIL_PAD_HPP #line 1 "tao/pegtl/internal/pad.hpp" #line 1 "tao/pegtl/internal/pad.hpp" #ifndef TAO_PEGTL_INTERNAL_PAD_HPP #define TAO_PEGTL_INTERNAL_PAD_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, typename Pad1, typename Pad2 = Pad1 > using pad = seq< star< Pad1 >, Rule, star< Pad2 > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 12 "tao/pegtl/internal/list_tail_pad.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, typename Sep, typename Pad > using list_tail_pad = seq< list< Rule, pad< Sep, Pad > >, opt< star< Pad >, Sep > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 34 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/one.hpp" #line 1 "tao/pegtl/internal/one.hpp" #ifndef TAO_PEGTL_INTERNAL_ONE_HPP #define TAO_PEGTL_INTERNAL_ONE_HPP #include <cstddef> #line 17 "tao/pegtl/internal/one.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< result_on_found R, typename Peek, typename Peek::data_t... Cs > struct one { using analyze_t = analysis::generic< analysis::rule_type::any >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.size( Peek::max_input_size ) ) ) { if( const std::size_t s = in.size( Peek::max_input_size ); s >= Peek::min_input_size ) { if( const auto t = Peek::peek( in, s ) ) { if( ( ( t.data == Cs ) || ... ) == bool( R ) ) { bump_help< R, Input, typename Peek::data_t, Cs... >( in, t.size ); return true; } } } return false; } }; template< result_on_found R, typename Peek, typename Peek::data_t... Cs > inline constexpr bool skip_control< one< R, Peek, Cs... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 37 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/pad_opt.hpp" #line 1 "tao/pegtl/internal/pad_opt.hpp" #ifndef TAO_PEGTL_INTERNAL_PAD_OPT_HPP #define TAO_PEGTL_INTERNAL_PAD_OPT_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< typename Rule, typename Pad > using pad_opt = seq< star< Pad >, opt< Rule, star< Pad > > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 40 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/plus.hpp" #line 1 "tao/pegtl/internal/plus.hpp" #ifndef TAO_PEGTL_INTERNAL_PLUS_HPP #define TAO_PEGTL_INTERNAL_PLUS_HPP #include <type_traits> #line 22 "tao/pegtl/internal/plus.hpp" namespace TAO_PEGTL_NAMESPACE::internal { // While plus<> could easily be implemented with // seq< Rule, Rules ..., star< Rule, Rules ... > > we // provide an explicit implementation to optimise away // the otherwise created input mark. template< typename Rule, typename... Rules > struct plus { using analyze_t = analysis::generic< analysis::rule_type::seq, Rule, Rules..., opt< plus > >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return seq< Rule, Rules... >::template match< A, M, Action, Control >( in, st... ) && star< Rule, Rules... >::template match< A, M, Action, Control >( in, st... ); } }; template< typename Rule, typename... Rules > inline constexpr bool skip_control< plus< Rule, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 41 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/rematch.hpp" #line 1 "tao/pegtl/internal/rematch.hpp" #ifndef TAO_PEGTL_INTERNAL_REMATCH_HPP #define TAO_PEGTL_INTERNAL_REMATCH_HPP #line 1 "tao/pegtl/internal/../memory_input.hpp" #line 1 "tao/pegtl/internal/../memory_input.hpp" #ifndef TAO_PEGTL_MEMORY_INPUT_HPP #define TAO_PEGTL_MEMORY_INPUT_HPP #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include <string_view> #include <type_traits> #include <utility> #line 1 "tao/pegtl/internal/../tracking_mode.hpp" #line 1 "tao/pegtl/internal/../tracking_mode.hpp" #ifndef TAO_PEGTL_TRACKING_MODE_HPP #define TAO_PEGTL_TRACKING_MODE_HPP namespace TAO_PEGTL_NAMESPACE { enum class tracking_mode : bool { eager, lazy }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 21 "tao/pegtl/internal/../memory_input.hpp" #line 1 "tao/pegtl/internal/../internal/bump.hpp" #line 1 "tao/pegtl/internal/../internal/bump.hpp" #ifndef TAO_PEGTL_INTERNAL_BUMP_HPP #define TAO_PEGTL_INTERNAL_BUMP_HPP namespace TAO_PEGTL_NAMESPACE::internal { inline void bump( iterator& iter, const std::size_t count, const int ch ) noexcept { for( std::size_t i = 0; i < count; ++i ) { if( iter.data[ i ] == ch ) { ++iter.line; iter.byte_in_line = 0; } else { ++iter.byte_in_line; } } iter.byte += count; iter.data += count; } inline void bump_in_this_line( iterator& iter, const std::size_t count ) noexcept { iter.data += count; iter.byte += count; iter.byte_in_line += count; } inline void bump_to_next_line( iterator& iter, const std::size_t count ) noexcept { ++iter.line; iter.byte += count; iter.byte_in_line = 0; iter.data += count; } } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 25 "tao/pegtl/internal/../memory_input.hpp" #line 1 "tao/pegtl/internal/../internal/marker.hpp" #line 1 "tao/pegtl/internal/../internal/marker.hpp" #ifndef TAO_PEGTL_INTERNAL_MARKER_HPP #define TAO_PEGTL_INTERNAL_MARKER_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< typename Iterator, rewind_mode M > class marker { public: static constexpr rewind_mode next_rewind_mode = M; explicit marker( const Iterator& /*unused*/ ) noexcept { } marker( const marker& ) = delete; marker( marker&& ) = delete; ~marker() = default; void operator=( const marker& ) = delete; void operator=( marker&& ) = delete; [[nodiscard]] bool operator()( const bool result ) const noexcept { return result; } }; template< typename Iterator > class marker< Iterator, rewind_mode::required > { public: static constexpr rewind_mode next_rewind_mode = rewind_mode::active; explicit marker( Iterator& i ) noexcept : m_saved( i ), m_input( &i ) { } marker( const marker& ) = delete; marker( marker&& ) = delete; ~marker() noexcept { if( m_input != nullptr ) { ( *m_input ) = m_saved; } } void operator=( const marker& ) = delete; void operator=( marker&& ) = delete; [[nodiscard]] bool operator()( const bool result ) noexcept { if( result ) { m_input = nullptr; return true; } return false; } [[nodiscard]] const Iterator& iterator() const noexcept { return m_saved; } private: const Iterator m_saved; Iterator* m_input; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 28 "tao/pegtl/internal/../memory_input.hpp" #line 1 "tao/pegtl/internal/../internal/until.hpp" #line 1 "tao/pegtl/internal/../internal/until.hpp" #ifndef TAO_PEGTL_INTERNAL_UNTIL_HPP #define TAO_PEGTL_INTERNAL_UNTIL_HPP #line 20 "tao/pegtl/internal/../internal/until.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Cond, typename... Rules > struct until; template< typename Cond > struct until< Cond > { using analyze_t = analysis::generic< analysis::rule_type::seq, star< not_at< Cond >, not_at< eof >, bytes< 1 > >, Cond >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< M >(); while( !Control< Cond >::template match< A, rewind_mode::required, Action, Control >( in, st... ) ) { if( in.empty() ) { return false; } in.bump(); } return m( true ); } }; template< typename Cond, typename... Rules > struct until { using analyze_t = analysis::generic< analysis::rule_type::seq, star< not_at< Cond >, not_at< eof >, Rules... >, Cond >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< M >(); using m_t = decltype( m ); while( !Control< Cond >::template match< A, rewind_mode::required, Action, Control >( in, st... ) ) { if( !( Control< Rules >::template match< A, m_t::next_rewind_mode, Action, Control >( in, st... ) && ... ) ) { return false; } } return m( true ); } }; template< typename Cond, typename... Rules > inline constexpr bool skip_control< until< Cond, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 29 "tao/pegtl/internal/../memory_input.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { template< tracking_mode, typename Eol, typename Source > class memory_input_base; template< typename Eol, typename Source > class memory_input_base< tracking_mode::eager, Eol, Source > { public: using iterator_t = internal::iterator; template< typename T > memory_input_base( const iterator_t& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : m_begin( in_begin.data ), m_current( in_begin ), m_end( in_end ), m_source( std::forward< T >( in_source ) ) { } template< typename T > memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : m_begin( in_begin ), m_current( in_begin ), m_end( in_end ), m_source( std::forward< T >( in_source ) ) { } memory_input_base( const memory_input_base& ) = delete; memory_input_base( memory_input_base&& ) = delete; ~memory_input_base() = default; memory_input_base operator=( const memory_input_base& ) = delete; memory_input_base operator=( memory_input_base&& ) = delete; [[nodiscard]] const char* current() const noexcept { return m_current.data; } [[nodiscard]] const char* begin() const noexcept { return m_begin; } [[nodiscard]] const char* end( const std::size_t /*unused*/ = 0 ) const noexcept { return m_end; } [[nodiscard]] std::size_t byte() const noexcept { return m_current.byte; } [[nodiscard]] std::size_t line() const noexcept { return m_current.line; } [[nodiscard]] std::size_t byte_in_line() const noexcept { return m_current.byte_in_line; } void bump( const std::size_t in_count = 1 ) noexcept { internal::bump( m_current, in_count, Eol::ch ); } void bump_in_this_line( const std::size_t in_count = 1 ) noexcept { internal::bump_in_this_line( m_current, in_count ); } void bump_to_next_line( const std::size_t in_count = 1 ) noexcept { internal::bump_to_next_line( m_current, in_count ); } [[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const { return TAO_PEGTL_NAMESPACE::position( it, m_source ); } void restart( const std::size_t in_byte = 0, const std::size_t in_line = 1, const std::size_t in_byte_in_line = 0 ) { m_current.data = m_begin; m_current.byte = in_byte; m_current.line = in_line; m_current.byte_in_line = in_byte_in_line; } template< rewind_mode M > void restart( const internal::marker< iterator_t, M >& m ) { m_current.data = m.iterator().data; m_current.byte = m.iterator().byte; m_current.line = m.iterator().line; m_current.byte_in_line = m.iterator().byte_in_line; } protected: const char* const m_begin; iterator_t m_current; const char* const m_end; const Source m_source; }; template< typename Eol, typename Source > class memory_input_base< tracking_mode::lazy, Eol, Source > { public: using iterator_t = const char*; template< typename T > memory_input_base( const internal::iterator& in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : m_begin( in_begin ), m_current( in_begin.data ), m_end( in_end ), m_source( std::forward< T >( in_source ) ) { } template< typename T > memory_input_base( const char* in_begin, const char* in_end, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : m_begin( in_begin ), m_current( in_begin ), m_end( in_end ), m_source( std::forward< T >( in_source ) ) { } memory_input_base( const memory_input_base& ) = delete; memory_input_base( memory_input_base&& ) = delete; ~memory_input_base() = default; memory_input_base operator=( const memory_input_base& ) = delete; memory_input_base operator=( memory_input_base&& ) = delete; [[nodiscard]] const char* current() const noexcept { return m_current; } [[nodiscard]] const char* begin() const noexcept { return m_begin.data; } [[nodiscard]] const char* end( const std::size_t /*unused*/ = 0 ) const noexcept { return m_end; } [[nodiscard]] std::size_t byte() const noexcept { return std::size_t( current() - m_begin.data ); } void bump( const std::size_t in_count = 1 ) noexcept { m_current += in_count; } void bump_in_this_line( const std::size_t in_count = 1 ) noexcept { m_current += in_count; } void bump_to_next_line( const std::size_t in_count = 1 ) noexcept { m_current += in_count; } [[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t it ) const { internal::iterator c( m_begin ); internal::bump( c, std::size_t( it - m_begin.data ), Eol::ch ); return TAO_PEGTL_NAMESPACE::position( c, m_source ); } void restart() { m_current = m_begin.data; } template< rewind_mode M > void restart( const internal::marker< iterator_t, M >& m ) { m_current = m.iterator(); } protected: const internal::iterator m_begin; iterator_t m_current; const char* const m_end; const Source m_source; }; } // namespace internal template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf, typename Source = std::string > class memory_input : public internal::memory_input_base< P, Eol, Source > { public: static constexpr tracking_mode tracking_mode_v = P; using eol_t = Eol; using source_t = Source; using typename internal::memory_input_base< P, Eol, Source >::iterator_t; using action_t = internal::action_input< memory_input >; using internal::memory_input_base< P, Eol, Source >::memory_input_base; template< typename T > memory_input( const char* in_begin, const std::size_t in_size, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : memory_input( in_begin, in_begin + in_size, std::forward< T >( in_source ) ) { } template< typename T > memory_input( const std::string& in_string, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) ) { } template< typename T > memory_input( const std::string_view in_string, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : memory_input( in_string.data(), in_string.size(), std::forward< T >( in_source ) ) { } template< typename T > memory_input( std::string&&, T&& ) = delete; template< typename T > memory_input( const char* in_begin, T&& in_source ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : memory_input( in_begin, std::strlen( in_begin ), std::forward< T >( in_source ) ) { } template< typename T > memory_input( const char* in_begin, const char* in_end, T&& in_source, const std::size_t in_byte, const std::size_t in_line, const std::size_t in_byte_in_line ) noexcept( std::is_nothrow_constructible_v< Source, T&& > ) : memory_input( { in_begin, in_byte, in_line, in_byte_in_line }, in_end, std::forward< T >( in_source ) ) { } memory_input( const memory_input& ) = delete; memory_input( memory_input&& ) = delete; ~memory_input() = default; memory_input operator=( const memory_input& ) = delete; memory_input operator=( memory_input&& ) = delete; [[nodiscard]] const Source& source() const noexcept { return this->m_source; } [[nodiscard]] bool empty() const noexcept { return this->current() == this->end(); } [[nodiscard]] std::size_t size( const std::size_t /*unused*/ = 0 ) const noexcept { return std::size_t( this->end() - this->current() ); } [[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept { return this->current()[ offset ]; } [[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept { return static_cast< std::uint8_t >( peek_char( offset ) ); } [[nodiscard]] iterator_t& iterator() noexcept { return this->m_current; } [[nodiscard]] const iterator_t& iterator() const noexcept { return this->m_current; } using internal::memory_input_base< P, Eol, Source >::position; [[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const { return position( iterator() ); } void discard() const noexcept { } void require( const std::size_t /*unused*/ ) const noexcept { } template< rewind_mode M > [[nodiscard]] internal::marker< iterator_t, M > mark() noexcept { return internal::marker< iterator_t, M >( iterator() ); } [[nodiscard]] const char* at( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept { return this->begin() + p.byte; } [[nodiscard]] const char* begin_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept { return at( p ) - p.byte_in_line; } [[nodiscard]] const char* end_of_line( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept { using input_t = memory_input< tracking_mode::lazy, Eol, const char* >; input_t in( at( p ), this->end(), "" ); using grammar = internal::until< internal::at< internal::eolf > >; (void)normal< grammar >::match< apply_mode::nothing, rewind_mode::dontcare, nothing, normal >( in ); return in.current(); } [[nodiscard]] std::string_view line_at( const TAO_PEGTL_NAMESPACE::position& p ) const noexcept { const char* b = begin_of_line( p ); return std::string_view( b, static_cast< std::size_t >( end_of_line( p ) - b ) ); } }; template< typename... Ts > memory_input( Ts&&... )->memory_input<>; } // namespace TAO_PEGTL_NAMESPACE #endif #line 13 "tao/pegtl/internal/rematch.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Head, typename... Rules > struct rematch; template< typename Head > struct rematch< Head > { using analyze_t = typename Head::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return Control< Head >::template match< A, M, Action, Control >( in, st... ); } }; template< typename Head, typename Rule, typename... Rules > struct rematch< Head, Rule, Rules... > { using analyze_t = typename Head::analyze_t; // NOTE: Rule and Rules are ignored for analyze(). template< apply_mode A, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::required >(); if( Control< Head >::template match< A, rewind_mode::active, Action, Control >( in, st... ) ) { memory_input< Input::tracking_mode_v, typename Input::eol_t, typename Input::source_t > i2( m.iterator(), in.current(), in.source() ); return m( ( Control< Rule >::template match< A, rewind_mode::active, Action, Control >( i2, st... ) && ... && ( i2.restart( m ), Control< Rules >::template match< A, rewind_mode::active, Action, Control >( i2, st... ) ) ) ); } return false; } }; template< typename Head, typename... Rules > inline constexpr bool skip_control< rematch< Head, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 45 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/rep.hpp" #line 1 "tao/pegtl/internal/rep.hpp" #ifndef TAO_PEGTL_INTERNAL_REP_HPP #define TAO_PEGTL_INTERNAL_REP_HPP #line 17 "tao/pegtl/internal/rep.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< unsigned Num, typename... Rules > struct rep; template< unsigned Num > struct rep< Num > : trivial< true > { }; template< typename Rule, typename... Rules > struct rep< 0, Rule, Rules... > : trivial< true > { }; template< unsigned Num, typename... Rules > struct rep { using analyze_t = analysis::counted< analysis::rule_type::seq, Num, Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< M >(); using m_t = decltype( m ); for( unsigned i = 0; i != Num; ++i ) { if( !( Control< Rules >::template match< A, m_t::next_rewind_mode, Action, Control >( in, st... ) && ... ) ) { return false; } } return m( true ); } }; template< unsigned Num, typename... Rules > inline constexpr bool skip_control< rep< Num, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 46 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/rep_min.hpp" #line 1 "tao/pegtl/internal/rep_min.hpp" #ifndef TAO_PEGTL_INTERNAL_REP_MIN_HPP #define TAO_PEGTL_INTERNAL_REP_MIN_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< unsigned Min, typename Rule, typename... Rules > using rep_min = seq< rep< Min, Rule, Rules... >, star< Rule, Rules... > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 47 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/rep_min_max.hpp" #line 1 "tao/pegtl/internal/rep_min_max.hpp" #ifndef TAO_PEGTL_INTERNAL_REP_MIN_MAX_HPP #define TAO_PEGTL_INTERNAL_REP_MIN_MAX_HPP #include <type_traits> #line 22 "tao/pegtl/internal/rep_min_max.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< unsigned Min, unsigned Max, typename... Rules > struct rep_min_max; template< unsigned Min, unsigned Max > struct rep_min_max< Min, Max > : trivial< false > { static_assert( Min <= Max ); }; template< typename Rule, typename... Rules > struct rep_min_max< 0, 0, Rule, Rules... > : not_at< Rule, Rules... > { }; template< unsigned Min, unsigned Max, typename... Rules > struct rep_min_max { using analyze_t = analysis::counted< analysis::rule_type::seq, Min, Rules... >; static_assert( Min <= Max ); template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< M >(); using m_t = decltype( m ); for( unsigned i = 0; i != Min; ++i ) { if( !( Control< Rules >::template match< A, m_t::next_rewind_mode, Action, Control >( in, st... ) && ... ) ) { return false; } } for( unsigned i = Min; i != Max; ++i ) { if( !duseltronik< seq< Rules... >, A, rewind_mode::required, Action, Control >::match( in, st... ) ) { return m( true ); } } return m( duseltronik< not_at< Rules... >, A, m_t::next_rewind_mode, Action, Control >::match( in, st... ) ); // NOTE that not_at<> will always rewind. } }; template< unsigned Min, unsigned Max, typename... Rules > inline constexpr bool skip_control< rep_min_max< Min, Max, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 48 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/rep_opt.hpp" #line 1 "tao/pegtl/internal/rep_opt.hpp" #ifndef TAO_PEGTL_INTERNAL_REP_OPT_HPP #define TAO_PEGTL_INTERNAL_REP_OPT_HPP #line 18 "tao/pegtl/internal/rep_opt.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< unsigned Max, typename... Rules > struct rep_opt { using analyze_t = analysis::generic< analysis::rule_type::opt, Rules... >; template< apply_mode A, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { for( unsigned i = 0; ( i != Max ) && duseltronik< seq< Rules... >, A, rewind_mode::required, Action, Control >::match( in, st... ); ++i ) { } return true; } }; template< unsigned Max, typename... Rules > inline constexpr bool skip_control< rep_opt< Max, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 49 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/require.hpp" #line 1 "tao/pegtl/internal/require.hpp" #ifndef TAO_PEGTL_INTERNAL_REQUIRE_HPP #define TAO_PEGTL_INTERNAL_REQUIRE_HPP #line 14 "tao/pegtl/internal/require.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< unsigned Amount > struct require; template<> struct require< 0 > : trivial< true > { }; template< unsigned Amount > struct require { using analyze_t = analysis::generic< analysis::rule_type::opt >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.size( 0 ) ) ) { return in.size( Amount ) >= Amount; } }; template< unsigned Amount > inline constexpr bool skip_control< require< Amount > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 50 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/star_must.hpp" #line 1 "tao/pegtl/internal/star_must.hpp" #ifndef TAO_PEGTL_INTERNAL_STAR_MUST_HPP #define TAO_PEGTL_INTERNAL_STAR_MUST_HPP namespace TAO_PEGTL_NAMESPACE::internal { template< typename Cond, typename... Rules > using star_must = star< if_must< false, Cond, Rules... > >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 55 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/state.hpp" #line 1 "tao/pegtl/internal/state.hpp" #ifndef TAO_PEGTL_INTERNAL_STATE_HPP #define TAO_PEGTL_INTERNAL_STATE_HPP #line 18 "tao/pegtl/internal/state.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename State, typename... Rules > struct state { using analyze_t = analysis::generic< analysis::rule_type::seq, Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { State s( static_cast< const Input& >( in ), st... ); if( duseltronik< seq< Rules... >, A, M, Action, Control >::match( in, s ) ) { s.success( static_cast< const Input& >( in ), st... ); return true; } return false; } }; template< typename State, typename... Rules > inline constexpr bool skip_control< state< State, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 56 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/string.hpp" #line 1 "tao/pegtl/internal/string.hpp" #ifndef TAO_PEGTL_INTERNAL_STRING_HPP #define TAO_PEGTL_INTERNAL_STRING_HPP #include <cstring> #include <utility> #line 19 "tao/pegtl/internal/string.hpp" namespace TAO_PEGTL_NAMESPACE::internal { [[nodiscard]] inline bool unsafe_equals( const char* s, const std::initializer_list< char >& l ) noexcept { return std::memcmp( s, &*l.begin(), l.size() ) == 0; } template< char... Cs > struct string; template<> struct string<> : trivial< true > { }; template< char... Cs > struct string { using analyze_t = analysis::counted< analysis::rule_type::any, sizeof...( Cs ) >; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.size( 0 ) ) ) { if( in.size( sizeof...( Cs ) ) >= sizeof...( Cs ) ) { if( unsafe_equals( in.current(), { Cs... } ) ) { bump_help< result_on_found::success, Input, char, Cs... >( in, sizeof...( Cs ) ); return true; } } return false; } }; template< char... Cs > inline constexpr bool skip_control< string< Cs... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 57 "tao/pegtl/internal/rules.hpp" #line 1 "tao/pegtl/internal/try_catch_type.hpp" #line 1 "tao/pegtl/internal/try_catch_type.hpp" #ifndef TAO_PEGTL_INTERNAL_TRY_CATCH_TYPE_HPP #define TAO_PEGTL_INTERNAL_TRY_CATCH_TYPE_HPP #include <type_traits> #line 21 "tao/pegtl/internal/try_catch_type.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Exception, typename... Rules > struct try_catch_type; template< typename Exception > struct try_catch_type< Exception > : trivial< true > { }; template< typename Exception, typename... Rules > struct try_catch_type { using analyze_t = analysis::generic< analysis::rule_type::seq, Rules... >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { auto m = in.template mark< M >(); using m_t = decltype( m ); try { return m( duseltronik< seq< Rules... >, A, m_t::next_rewind_mode, Action, Control >::match( in, st... ) ); } catch( const Exception& ) { return false; } } }; template< typename Exception, typename... Rules > inline constexpr bool skip_control< try_catch_type< Exception, Rules... > > = true; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 59 "tao/pegtl/internal/rules.hpp" #endif #line 13 "tao/pegtl/ascii.hpp" namespace TAO_PEGTL_NAMESPACE { inline namespace ascii { // clang-format off struct alnum : internal::alnum {}; struct alpha : internal::alpha {}; struct any : internal::any< internal::peek_char > {}; struct blank : internal::one< internal::result_on_found::success, internal::peek_char, ' ', '\t' > {}; struct digit : internal::range< internal::result_on_found::success, internal::peek_char, '0', '9' > {}; struct ellipsis : internal::string< '.', '.', '.' > {}; struct eolf : internal::eolf {}; template< char... Cs > struct forty_two : internal::rep< 42, internal::one< internal::result_on_found::success, internal::peek_char, Cs... > > {}; struct identifier_first : internal::identifier_first {}; struct identifier_other : internal::identifier_other {}; struct identifier : internal::identifier {}; template< char... Cs > struct istring : internal::istring< Cs... > {}; template< char... Cs > struct keyword : internal::seq< internal::string< Cs... >, internal::not_at< internal::identifier_other > > {}; struct lower : internal::range< internal::result_on_found::success, internal::peek_char, 'a', 'z' > {}; template< char... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_char, Cs... > {}; template< char Lo, char Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_char, Lo, Hi > {}; struct nul : internal::one< internal::result_on_found::success, internal::peek_char, char( 0 ) > {}; template< char... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_char, Cs... > {}; struct print : internal::range< internal::result_on_found::success, internal::peek_char, char( 32 ), char( 126 ) > {}; template< char Lo, char Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_char, Lo, Hi > {}; template< char... Cs > struct ranges : internal::ranges< internal::peek_char, Cs... > {}; struct seven : internal::range< internal::result_on_found::success, internal::peek_char, char( 0 ), char( 127 ) > {}; struct shebang : internal::if_must< false, internal::string< '#', '!' >, internal::until< internal::eolf > > {}; struct space : internal::one< internal::result_on_found::success, internal::peek_char, ' ', '\n', '\r', '\t', '\v', '\f' > {}; template< char... Cs > struct string : internal::string< Cs... > {}; template< char C > struct three : internal::string< C, C, C > {}; template< char C > struct two : internal::string< C, C > {}; struct upper : internal::range< internal::result_on_found::success, internal::peek_char, 'A', 'Z' > {}; struct xdigit : internal::ranges< internal::peek_char, '0', '9', 'a', 'f', 'A', 'F' > {}; // clang-format on template<> struct keyword<> { template< typename Input > [[nodiscard]] static bool match( Input& /*unused*/ ) noexcept { static_assert( internal::always_false< Input >::value, "empty keywords not allowed" ); return false; } }; } // namespace ascii } // namespace TAO_PEGTL_NAMESPACE #line 1 "tao/pegtl/internal/pegtl_string.hpp" #line 1 "tao/pegtl/internal/pegtl_string.hpp" #ifndef TAO_PEGTL_INTERNAL_PEGTL_STRING_HPP #define TAO_PEGTL_INTERNAL_PEGTL_STRING_HPP #include <cstddef> #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { // Inspired by https://github.com/irrequietus/typestring // Rewritten and reduced to what is needed for the PEGTL // and to work with Visual Studio 2015. template< typename, typename, typename, typename, typename, typename, typename, typename > struct string_join; template< template< char... > class S, char... C0s, char... C1s, char... C2s, char... C3s, char... C4s, char... C5s, char... C6s, char... C7s > struct string_join< S< C0s... >, S< C1s... >, S< C2s... >, S< C3s... >, S< C4s... >, S< C5s... >, S< C6s... >, S< C7s... > > { using type = S< C0s..., C1s..., C2s..., C3s..., C4s..., C5s..., C6s..., C7s... >; }; template< template< char... > class S, char, bool > struct string_at { using type = S<>; }; template< template< char... > class S, char C > struct string_at< S, C, true > { using type = S< C >; }; template< typename T, std::size_t S > struct string_max_length { static_assert( S <= 512, "String longer than 512 (excluding terminating \\0)!" ); using type = T; }; } // namespace TAO_PEGTL_NAMESPACE::internal #define TAO_PEGTL_INTERNAL_EMPTY() #define TAO_PEGTL_INTERNAL_DEFER( X ) X TAO_PEGTL_INTERNAL_EMPTY() #define TAO_PEGTL_INTERNAL_EXPAND( ... ) __VA_ARGS__ #define TAO_PEGTL_INTERNAL_STRING_AT( S, x, n ) TAO_PEGTL_NAMESPACE::internal::string_at< S, ( 0##n < ( sizeof( x ) / sizeof( char ) ) ) ? ( x )[ 0##n ] : 0, ( 0##n < ( sizeof( x ) / sizeof( char ) ) - 1 ) >::type #define TAO_PEGTL_INTERNAL_JOIN_8( M, S, x, n ) TAO_PEGTL_NAMESPACE::internal::string_join< TAO_PEGTL_INTERNAL_DEFER( M )( S, x, n##0 ), TAO_PEGTL_INTERNAL_DEFER( M )( S, x, n##1 ), TAO_PEGTL_INTERNAL_DEFER( M )( S, x, n##2 ), TAO_PEGTL_INTERNAL_DEFER( M )( S, x, n##3 ), TAO_PEGTL_INTERNAL_DEFER( M )( S, x, n##4 ), TAO_PEGTL_INTERNAL_DEFER( M )( S, x, n##5 ), TAO_PEGTL_INTERNAL_DEFER( M )( S, x, n##6 ), TAO_PEGTL_INTERNAL_DEFER( M )( S, x, n##7 ) >::type #line 66 "tao/pegtl/internal/pegtl_string.hpp" #define TAO_PEGTL_INTERNAL_STRING_8( S, x, n ) TAO_PEGTL_INTERNAL_JOIN_8( TAO_PEGTL_INTERNAL_STRING_AT, S, x, n ) #define TAO_PEGTL_INTERNAL_STRING_64( S, x, n ) TAO_PEGTL_INTERNAL_JOIN_8( TAO_PEGTL_INTERNAL_STRING_8, S, x, n ) #define TAO_PEGTL_INTERNAL_STRING_512( S, x, n ) TAO_PEGTL_INTERNAL_JOIN_8( TAO_PEGTL_INTERNAL_STRING_64, S, x, n ) #define TAO_PEGTL_INTERNAL_STRING( S, x ) TAO_PEGTL_INTERNAL_EXPAND( TAO_PEGTL_INTERNAL_EXPAND( TAO_PEGTL_INTERNAL_EXPAND( TAO_PEGTL_NAMESPACE::internal::string_max_length< TAO_PEGTL_INTERNAL_STRING_512( S, x, ), sizeof( x ) - 1 >::type ) ) ) #define TAO_PEGTL_STRING( x ) TAO_PEGTL_INTERNAL_STRING( TAO_PEGTL_NAMESPACE::ascii::string, x ) #define TAO_PEGTL_ISTRING( x ) TAO_PEGTL_INTERNAL_STRING( TAO_PEGTL_NAMESPACE::ascii::istring, x ) #define TAO_PEGTL_KEYWORD( x ) TAO_PEGTL_INTERNAL_STRING( TAO_PEGTL_NAMESPACE::ascii::keyword, x ) #endif #line 66 "tao/pegtl/ascii.hpp" #endif #line 13 "tao/pegtl.hpp" #line 1 "tao/pegtl/rules.hpp" #line 1 "tao/pegtl/rules.hpp" #ifndef TAO_PEGTL_RULES_HPP #define TAO_PEGTL_RULES_HPP namespace TAO_PEGTL_NAMESPACE { // clang-format off template< typename... Actions > struct apply : internal::apply< Actions... > {}; template< typename... Actions > struct apply0 : internal::apply0< Actions... > {}; template< template< typename... > class Action, typename... Rules > struct action : internal::action< Action, Rules... > {}; template< typename... Rules > struct at : internal::at< Rules... > {}; struct bof : internal::bof {}; struct bol : internal::bol {}; template< unsigned Num > struct bytes : internal::bytes< Num > {}; template< template< typename... > class Control, typename... Rules > struct control : internal::control< Control, Rules... > {}; template< typename... Rules > struct disable : internal::disable< Rules... > {}; struct discard : internal::discard {}; template< typename... Rules > struct enable : internal::enable< Rules... > {}; struct eof : internal::eof {}; struct failure : internal::trivial< false > {}; template< typename Rule, typename... Actions > struct if_apply : internal::if_apply< Rule, Actions... > {}; template< typename Cond, typename... Thens > struct if_must : internal::if_must< false, Cond, Thens... > {}; template< typename Cond, typename Then, typename Else > struct if_must_else : internal::if_must_else< Cond, Then, Else > {}; template< typename Cond, typename Then, typename Else > struct if_then_else : internal::if_then_else< Cond, Then, Else > {}; template< typename Rule, typename Sep, typename Pad = void > struct list : internal::list< Rule, internal::pad< Sep, Pad > > {}; template< typename Rule, typename Sep > struct list< Rule, Sep, void > : internal::list< Rule, Sep > {}; template< typename Rule, typename Sep, typename Pad = void > struct list_must : internal::list_must< Rule, internal::pad< Sep, Pad > > {}; template< typename Rule, typename Sep > struct list_must< Rule, Sep, void > : internal::list_must< Rule, Sep > {}; template< typename Rule, typename Sep, typename Pad = void > struct list_tail : internal::list_tail_pad< Rule, Sep, Pad > {}; template< typename Rule, typename Sep > struct list_tail< Rule, Sep, void > : internal::list_tail< Rule, Sep > {}; template< typename M, typename S > struct minus : internal::rematch< M, internal::not_at< S, internal::eof > > {}; template< typename... Rules > struct must : internal::must< Rules... > {}; template< typename... Rules > struct not_at : internal::not_at< Rules... > {}; template< typename... Rules > struct opt : internal::opt< Rules... > {}; template< typename Cond, typename... Rules > struct opt_must : internal::if_must< true, Cond, Rules... > {}; template< typename Rule, typename Pad1, typename Pad2 = Pad1 > struct pad : internal::pad< Rule, Pad1, Pad2 > {}; template< typename Rule, typename Pad > struct pad_opt : internal::pad_opt< Rule, Pad > {}; template< typename Rule, typename... Rules > struct plus : internal::plus< Rule, Rules... > {}; template< typename Exception > struct raise : internal::raise< Exception > {}; template< typename Head, typename... Rules > struct rematch : internal::rematch< Head, Rules... > {}; template< unsigned Num, typename... Rules > struct rep : internal::rep< Num, Rules... > {}; template< unsigned Max, typename... Rules > struct rep_max : internal::rep_min_max< 0, Max, Rules... > {}; template< unsigned Min, typename Rule, typename... Rules > struct rep_min : internal::rep_min< Min, Rule, Rules... > {}; template< unsigned Min, unsigned Max, typename... Rules > struct rep_min_max : internal::rep_min_max< Min, Max, Rules... > {}; template< unsigned Max, typename... Rules > struct rep_opt : internal::rep_opt< Max, Rules... > {}; template< unsigned Amount > struct require : internal::require< Amount > {}; template< typename... Rules > struct seq : internal::seq< Rules... > {}; template< typename... Rules > struct sor : internal::sor< Rules... > {}; template< typename Rule, typename... Rules > struct star : internal::star< Rule, Rules... > {}; template< typename Cond, typename... Rules > struct star_must : internal::star_must< Cond, Rules... > {}; template< typename State, typename... Rules > struct state : internal::state< State, Rules... > {}; struct success : internal::trivial< true > {}; template< typename... Rules > struct try_catch : internal::try_catch_type< parse_error, Rules... > {}; template< typename Exception, typename... Rules > struct try_catch_type : internal::try_catch_type< Exception, Rules... > {}; template< typename Cond, typename... Rules > struct until : internal::until< Cond, Rules... > {}; // clang-format on } // namespace TAO_PEGTL_NAMESPACE #endif #line 14 "tao/pegtl.hpp" #line 1 "tao/pegtl/uint16.hpp" #line 1 "tao/pegtl/uint16.hpp" #ifndef TAO_PEGTL_UINT16_HPP #define TAO_PEGTL_UINT16_HPP #line 1 "tao/pegtl/internal/peek_mask_uint.hpp" #line 1 "tao/pegtl/internal/peek_mask_uint.hpp" #ifndef TAO_PEGTL_INTERNAL_PEEK_MASK_UINT_HPP #define TAO_PEGTL_INTERNAL_PEEK_MASK_UINT_HPP #include <cstddef> #include <cstdint> #line 1 "tao/pegtl/internal/read_uint.hpp" #line 1 "tao/pegtl/internal/read_uint.hpp" #ifndef TAO_PEGTL_INTERNAL_READ_UINT_HPP #define TAO_PEGTL_INTERNAL_READ_UINT_HPP #include <cstdint> #line 1 "tao/pegtl/internal/endian.hpp" #line 1 "tao/pegtl/internal/endian.hpp" #ifndef TAO_PEGTL_INTERNAL_ENDIAN_HPP #define TAO_PEGTL_INTERNAL_ENDIAN_HPP #include <cstdint> #include <cstring> #if defined( _WIN32 ) && !defined( __MINGW32__ ) && !defined( __CYGWIN__ ) #line 1 "tao/pegtl/internal/endian_win.hpp" #line 1 "tao/pegtl/internal/endian_win.hpp" #ifndef TAO_PEGTL_INTERNAL_ENDIAN_WIN_HPP #define TAO_PEGTL_INTERNAL_ENDIAN_WIN_HPP #include <cstdint> #include <cstdlib> #include <cstring> namespace TAO_PEGTL_NAMESPACE::internal { template< std::size_t S > struct to_and_from_le { template< typename T > [[nodiscard]] static T convert( const T t ) noexcept { return t; } }; template< std::size_t S > struct to_and_from_be; template<> struct to_and_from_be< 1 > { [[nodiscard]] static std::int8_t convert( const std::int8_t n ) noexcept { return n; } [[nodiscard]] static std::uint8_t convert( const std::uint8_t n ) noexcept { return n; } }; template<> struct to_and_from_be< 2 > { [[nodiscard]] static std::int16_t convert( const std::int16_t n ) noexcept { return std::int16_t( _byteswap_ushort( std::uint16_t( n ) ) ); } [[nodiscard]] static std::uint16_t convert( const std::uint16_t n ) noexcept { return _byteswap_ushort( n ); } }; template<> struct to_and_from_be< 4 > { [[nodiscard]] static float convert( float n ) noexcept { std::uint32_t u; std::memcpy( &u, &n, 4 ); u = convert( u ); std::memcpy( &n, &u, 4 ); return n; } [[nodiscard]] static std::int32_t convert( const std::int32_t n ) noexcept { return std::int32_t( _byteswap_ulong( std::uint32_t( n ) ) ); } [[nodiscard]] static std::uint32_t convert( const std::uint32_t n ) noexcept { return _byteswap_ulong( n ); } }; template<> struct to_and_from_be< 8 > { [[nodiscard]] static double convert( double n ) noexcept { std::uint64_t u; std::memcpy( &u, &n, 8 ); u = convert( u ); std::memcpy( &n, &u, 8 ); return n; } [[nodiscard]] static std::int64_t convert( const std::int64_t n ) noexcept { return std::int64_t( _byteswap_uint64( std::uint64_t( n ) ) ); } [[nodiscard]] static std::uint64_t convert( const std::uint64_t n ) noexcept { return _byteswap_uint64( n ); } }; #define TAO_PEGTL_NATIVE_ORDER le #define TAO_PEGTL_NATIVE_UTF16 utf16_le #define TAO_PEGTL_NATIVE_UTF32 utf32_le } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 14 "tao/pegtl/internal/endian.hpp" #else #line 1 "tao/pegtl/internal/endian_gcc.hpp" #line 1 "tao/pegtl/internal/endian_gcc.hpp" #ifndef TAO_PEGTL_INTERNAL_ENDIAN_GCC_HPP #define TAO_PEGTL_INTERNAL_ENDIAN_GCC_HPP #include <cstdint> #include <cstring> namespace TAO_PEGTL_NAMESPACE::internal { #if !defined( __BYTE_ORDER__ ) #error No byte order defined! #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ template< std::size_t S > struct to_and_from_be { template< typename T > [[nodiscard]] static T convert( const T n ) noexcept { return n; } }; template< std::size_t S > struct to_and_from_le; template<> struct to_and_from_le< 1 > { [[nodiscard]] static std::uint8_t convert( const std::uint8_t n ) noexcept { return n; } [[nodiscard]] static std::int8_t convert( const std::int8_t n ) noexcept { return n; } }; template<> struct to_and_from_le< 2 > { [[nodiscard]] static std::int16_t convert( const std::int16_t n ) noexcept { return static_cast< std::int16_t >( __builtin_bswap16( static_cast< std::uint16_t >( n ) ) ); } [[nodiscard]] static std::uint16_t convert( const std::uint16_t n ) noexcept { return __builtin_bswap16( n ); } }; template<> struct to_and_from_le< 4 > { [[nodiscard]] static float convert( float n ) noexcept { std::uint32_t u; std::memcpy( &u, &n, 4 ); u = convert( u ); std::memcpy( &n, &u, 4 ); return n; } [[nodiscard]] static std::int32_t convert( const std::int32_t n ) noexcept { return static_cast< std::int32_t >( __builtin_bswap32( static_cast< std::uint32_t >( n ) ) ); } [[nodiscard]] static std::uint32_t convert( const std::uint32_t n ) noexcept { return __builtin_bswap32( n ); } }; template<> struct to_and_from_le< 8 > { [[nodiscard]] static double convert( double n ) noexcept { std::uint64_t u; std::memcpy( &u, &n, 8 ); u = convert( u ); std::memcpy( &n, &u, 8 ); return n; } [[nodiscard]] static std::int64_t convert( const std::int64_t n ) noexcept { return static_cast< std::int64_t >( __builtin_bswap64( static_cast< std::uint64_t >( n ) ) ); } [[nodiscard]] static std::uint64_t convert( const std::uint64_t n ) noexcept { return __builtin_bswap64( n ); } }; #define TAO_PEGTL_NATIVE_ORDER be #define TAO_PEGTL_NATIVE_UTF16 utf16_be #define TAO_PEGTL_NATIVE_UTF32 utf32_be #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ template< std::size_t S > struct to_and_from_le { template< typename T > [[nodiscard]] static T convert( const T n ) noexcept { return n; } }; template< std::size_t S > struct to_and_from_be; template<> struct to_and_from_be< 1 > { [[nodiscard]] static std::int8_t convert( const std::int8_t n ) noexcept { return n; } [[nodiscard]] static std::uint8_t convert( const std::uint8_t n ) noexcept { return n; } }; template<> struct to_and_from_be< 2 > { [[nodiscard]] static std::int16_t convert( const std::int16_t n ) noexcept { return static_cast< std::int16_t >( __builtin_bswap16( static_cast< std::uint16_t >( n ) ) ); } [[nodiscard]] static std::uint16_t convert( const std::uint16_t n ) noexcept { return __builtin_bswap16( n ); } }; template<> struct to_and_from_be< 4 > { [[nodiscard]] static float convert( float n ) noexcept { std::uint32_t u; std::memcpy( &u, &n, 4 ); u = convert( u ); std::memcpy( &n, &u, 4 ); return n; } [[nodiscard]] static std::int32_t convert( const std::int32_t n ) noexcept { return static_cast< std::int32_t >( __builtin_bswap32( static_cast< std::uint32_t >( n ) ) ); } [[nodiscard]] static std::uint32_t convert( const std::uint32_t n ) noexcept { return __builtin_bswap32( n ); } }; template<> struct to_and_from_be< 8 > { [[nodiscard]] static double convert( double n ) noexcept { std::uint64_t u; std::memcpy( &u, &n, 8 ); u = convert( u ); std::memcpy( &n, &u, 8 ); return n; } [[nodiscard]] static std::int64_t convert( const std::int64_t n ) noexcept { return static_cast< std::int64_t >( __builtin_bswap64( static_cast< std::uint64_t >( n ) ) ); } [[nodiscard]] static std::uint64_t convert( const std::uint64_t n ) noexcept { return __builtin_bswap64( n ); } }; #define TAO_PEGTL_NATIVE_ORDER le #define TAO_PEGTL_NATIVE_UTF16 utf16_le #define TAO_PEGTL_NATIVE_UTF32 utf32_le #else #error Unknown host byte order! #endif } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 16 "tao/pegtl/internal/endian.hpp" #endif namespace TAO_PEGTL_NAMESPACE::internal { template< typename N > [[nodiscard]] N h_to_be( const N n ) noexcept { return N( to_and_from_be< sizeof( N ) >::convert( n ) ); } template< typename N > [[nodiscard]] N be_to_h( const N n ) noexcept { return h_to_be( n ); } template< typename N > [[nodiscard]] N be_to_h( const void* p ) noexcept { N n; std::memcpy( &n, p, sizeof( n ) ); return internal::be_to_h( n ); } template< typename N > [[nodiscard]] N h_to_le( const N n ) noexcept { return N( to_and_from_le< sizeof( N ) >::convert( n ) ); } template< typename N > [[nodiscard]] N le_to_h( const N n ) noexcept { return h_to_le( n ); } template< typename N > [[nodiscard]] N le_to_h( const void* p ) noexcept { N n; std::memcpy( &n, p, sizeof( n ) ); return internal::le_to_h( n ); } } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 12 "tao/pegtl/internal/read_uint.hpp" namespace TAO_PEGTL_NAMESPACE::internal { struct read_uint16_be { using type = std::uint16_t; [[nodiscard]] static std::uint16_t read( const void* d ) noexcept { return be_to_h< std::uint16_t >( d ); } }; struct read_uint16_le { using type = std::uint16_t; [[nodiscard]] static std::uint16_t read( const void* d ) noexcept { return le_to_h< std::uint16_t >( d ); } }; struct read_uint32_be { using type = std::uint32_t; [[nodiscard]] static std::uint32_t read( const void* d ) noexcept { return be_to_h< std::uint32_t >( d ); } }; struct read_uint32_le { using type = std::uint32_t; [[nodiscard]] static std::uint32_t read( const void* d ) noexcept { return le_to_h< std::uint32_t >( d ); } }; struct read_uint64_be { using type = std::uint64_t; [[nodiscard]] static std::uint64_t read( const void* d ) noexcept { return be_to_h< std::uint64_t >( d ); } }; struct read_uint64_le { using type = std::uint64_t; [[nodiscard]] static std::uint64_t read( const void* d ) noexcept { return le_to_h< std::uint64_t >( d ); } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 14 "tao/pegtl/internal/peek_mask_uint.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename R, typename R::type M > struct peek_mask_uint_impl { using data_t = typename R::type; using pair_t = input_pair< data_t >; static constexpr std::size_t min_input_size = sizeof( data_t ); static constexpr std::size_t max_input_size = sizeof( data_t ); template< typename Input > [[nodiscard]] static pair_t peek( const Input& in, const std::size_t /*unused*/ ) noexcept { const data_t data = R::read( in.current() ) & M; return { data, sizeof( data_t ) }; } }; template< std::uint16_t M > using peek_mask_uint16_be = peek_mask_uint_impl< read_uint16_be, M >; template< std::uint16_t M > using peek_mask_uint16_le = peek_mask_uint_impl< read_uint16_le, M >; template< std::uint32_t M > using peek_mask_uint32_be = peek_mask_uint_impl< read_uint32_be, M >; template< std::uint32_t M > using peek_mask_uint32_le = peek_mask_uint_impl< read_uint32_le, M >; template< std::uint64_t M > using peek_mask_uint64_be = peek_mask_uint_impl< read_uint64_be, M >; template< std::uint64_t M > using peek_mask_uint64_le = peek_mask_uint_impl< read_uint64_le, M >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/uint16.hpp" #line 1 "tao/pegtl/internal/peek_uint.hpp" #line 1 "tao/pegtl/internal/peek_uint.hpp" #ifndef TAO_PEGTL_INTERNAL_PEEK_UINT_HPP #define TAO_PEGTL_INTERNAL_PEEK_UINT_HPP #include <cstddef> #include <cstdint> namespace TAO_PEGTL_NAMESPACE::internal { template< typename R > struct peek_uint_impl { using data_t = typename R::type; using pair_t = input_pair< data_t >; static constexpr std::size_t min_input_size = sizeof( data_t ); static constexpr std::size_t max_input_size = sizeof( data_t ); template< typename Input > [[nodiscard]] static pair_t peek( const Input& in, const std::size_t /*unused*/ ) noexcept { const data_t data = R::read( in.current() ); return { data, sizeof( data_t ) }; } }; using peek_uint16_be = peek_uint_impl< read_uint16_be >; using peek_uint16_le = peek_uint_impl< read_uint16_le >; using peek_uint32_be = peek_uint_impl< read_uint32_be >; using peek_uint32_le = peek_uint_impl< read_uint32_le >; using peek_uint64_be = peek_uint_impl< read_uint64_be >; using peek_uint64_le = peek_uint_impl< read_uint64_le >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 11 "tao/pegtl/uint16.hpp" namespace TAO_PEGTL_NAMESPACE { namespace uint16_be { // clang-format off struct any : internal::any< internal::peek_uint16_be > {}; template< std::uint16_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_uint16_be, Cs... > {}; template< std::uint16_t Lo, std::uint16_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_uint16_be, Lo, Hi > {}; template< std::uint16_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_uint16_be, Cs... > {}; template< std::uint16_t Lo, std::uint16_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_uint16_be, Lo, Hi > {}; template< std::uint16_t... Cs > struct ranges : internal::ranges< internal::peek_uint16_be, Cs... > {}; template< std::uint16_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_uint16_be, Cs >... > {}; template< std::uint16_t M, std::uint16_t... Cs > struct mask_not_one : internal::one< internal::result_on_found::failure, internal::peek_mask_uint16_be< M >, Cs... > {}; template< std::uint16_t M, std::uint16_t Lo, std::uint16_t Hi > struct mask_not_range : internal::range< internal::result_on_found::failure, internal::peek_mask_uint16_be< M >, Lo, Hi > {}; template< std::uint16_t M, std::uint16_t... Cs > struct mask_one : internal::one< internal::result_on_found::success, internal::peek_mask_uint16_be< M >, Cs... > {}; template< std::uint16_t M, std::uint16_t Lo, std::uint16_t Hi > struct mask_range : internal::range< internal::result_on_found::success, internal::peek_mask_uint16_be< M >, Lo, Hi > {}; template< std::uint16_t M, std::uint16_t... Cs > struct mask_ranges : internal::ranges< internal::peek_mask_uint16_be< M >, Cs... > {}; template< std::uint16_t M, std::uint16_t... Cs > struct mask_string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_mask_uint16_be< M >, Cs >... > {}; // clang-format on } // namespace uint16_be namespace uint16_le { // clang-format off struct any : internal::any< internal::peek_uint16_le > {}; template< std::uint16_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_uint16_le, Cs... > {}; template< std::uint16_t Lo, std::uint16_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_uint16_le, Lo, Hi > {}; template< std::uint16_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_uint16_le, Cs... > {}; template< std::uint16_t Lo, std::uint16_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_uint16_le, Lo, Hi > {}; template< std::uint16_t... Cs > struct ranges : internal::ranges< internal::peek_uint16_le, Cs... > {}; template< std::uint16_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_uint16_le, Cs >... > {}; template< std::uint16_t M, std::uint16_t... Cs > struct mask_not_one : internal::one< internal::result_on_found::failure, internal::peek_mask_uint16_le< M >, Cs... > {}; template< std::uint16_t M, std::uint16_t Lo, std::uint16_t Hi > struct mask_not_range : internal::range< internal::result_on_found::failure, internal::peek_mask_uint16_le< M >, Lo, Hi > {}; template< std::uint16_t M, std::uint16_t... Cs > struct mask_one : internal::one< internal::result_on_found::success, internal::peek_mask_uint16_le< M >, Cs... > {}; template< std::uint16_t M, std::uint16_t Lo, std::uint16_t Hi > struct mask_range : internal::range< internal::result_on_found::success, internal::peek_mask_uint16_le< M >, Lo, Hi > {}; template< std::uint16_t M, std::uint16_t... Cs > struct mask_ranges : internal::ranges< internal::peek_mask_uint16_le< M >, Cs... > {}; template< std::uint16_t M, std::uint16_t... Cs > struct mask_string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_mask_uint16_le< M >, Cs >... > {}; // clang-format on } // namespace uint16_le } // namespace TAO_PEGTL_NAMESPACE #endif #line 15 "tao/pegtl.hpp" #line 1 "tao/pegtl/uint32.hpp" #line 1 "tao/pegtl/uint32.hpp" #ifndef TAO_PEGTL_UINT32_HPP #define TAO_PEGTL_UINT32_HPP #line 14 "tao/pegtl/uint32.hpp" namespace TAO_PEGTL_NAMESPACE { namespace uint32_be { // clang-format off struct any : internal::any< internal::peek_uint32_be > {}; template< std::uint32_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_uint32_be, Cs... > {}; template< std::uint32_t Lo, std::uint32_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_uint32_be, Lo, Hi > {}; template< std::uint32_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_uint32_be, Cs... > {}; template< std::uint32_t Lo, std::uint32_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_uint32_be, Lo, Hi > {}; template< std::uint32_t... Cs > struct ranges : internal::ranges< internal::peek_uint32_be, Cs... > {}; template< std::uint32_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_uint32_be, Cs >... > {}; template< std::uint32_t M, std::uint32_t... Cs > struct mask_not_one : internal::one< internal::result_on_found::failure, internal::peek_mask_uint32_be< M >, Cs... > {}; template< std::uint32_t M, std::uint32_t Lo, std::uint32_t Hi > struct mask_not_range : internal::range< internal::result_on_found::failure, internal::peek_mask_uint32_be< M >, Lo, Hi > {}; template< std::uint32_t M, std::uint32_t... Cs > struct mask_one : internal::one< internal::result_on_found::success, internal::peek_mask_uint32_be< M >, Cs... > {}; template< std::uint32_t M, std::uint32_t Lo, std::uint32_t Hi > struct mask_range : internal::range< internal::result_on_found::success, internal::peek_mask_uint32_be< M >, Lo, Hi > {}; template< std::uint32_t M, std::uint32_t... Cs > struct mask_ranges : internal::ranges< internal::peek_mask_uint32_be< M >, Cs... > {}; template< std::uint32_t M, std::uint32_t... Cs > struct mask_string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_mask_uint32_be< M >, Cs >... > {}; // clang-format on } // namespace uint32_be namespace uint32_le { // clang-format off struct any : internal::any< internal::peek_uint32_le > {}; template< std::uint32_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_uint32_le, Cs... > {}; template< std::uint32_t Lo, std::uint32_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_uint32_le, Lo, Hi > {}; template< std::uint32_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_uint32_le, Cs... > {}; template< std::uint32_t Lo, std::uint32_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_uint32_le, Lo, Hi > {}; template< std::uint32_t... Cs > struct ranges : internal::ranges< internal::peek_uint32_le, Cs... > {}; template< std::uint32_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_uint32_le, Cs >... > {}; template< std::uint32_t M, std::uint32_t... Cs > struct mask_not_one : internal::one< internal::result_on_found::failure, internal::peek_mask_uint32_le< M >, Cs... > {}; template< std::uint32_t M, std::uint32_t Lo, std::uint32_t Hi > struct mask_not_range : internal::range< internal::result_on_found::failure, internal::peek_mask_uint32_le< M >, Lo, Hi > {}; template< std::uint32_t M, std::uint32_t... Cs > struct mask_one : internal::one< internal::result_on_found::success, internal::peek_mask_uint32_le< M >, Cs... > {}; template< std::uint32_t M, std::uint32_t Lo, std::uint32_t Hi > struct mask_range : internal::range< internal::result_on_found::success, internal::peek_mask_uint32_le< M >, Lo, Hi > {}; template< std::uint32_t M, std::uint32_t... Cs > struct mask_ranges : internal::ranges< internal::peek_mask_uint32_le< M >, Cs... > {}; template< std::uint32_t M, std::uint32_t... Cs > struct mask_string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_mask_uint32_le< M >, Cs >... > {}; // clang-format on } // namespace uint32_le } // namespace TAO_PEGTL_NAMESPACE #endif #line 16 "tao/pegtl.hpp" #line 1 "tao/pegtl/uint64.hpp" #line 1 "tao/pegtl/uint64.hpp" #ifndef TAO_PEGTL_UINT64_HPP #define TAO_PEGTL_UINT64_HPP #line 14 "tao/pegtl/uint64.hpp" namespace TAO_PEGTL_NAMESPACE { namespace uint64_be { // clang-format off struct any : internal::any< internal::peek_uint64_be > {}; template< std::uint64_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_uint64_be, Cs... > {}; template< std::uint64_t Lo, std::uint64_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_uint64_be, Lo, Hi > {}; template< std::uint64_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_uint64_be, Cs... > {}; template< std::uint64_t Lo, std::uint64_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_uint64_be, Lo, Hi > {}; template< std::uint64_t... Cs > struct ranges : internal::ranges< internal::peek_uint64_be, Cs... > {}; template< std::uint64_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_uint64_be, Cs >... > {}; template< std::uint64_t M, std::uint64_t... Cs > struct mask_not_one : internal::one< internal::result_on_found::failure, internal::peek_mask_uint64_be< M >, Cs... > {}; template< std::uint64_t M, std::uint64_t Lo, std::uint64_t Hi > struct mask_not_range : internal::range< internal::result_on_found::failure, internal::peek_mask_uint64_be< M >, Lo, Hi > {}; template< std::uint64_t M, std::uint64_t... Cs > struct mask_one : internal::one< internal::result_on_found::success, internal::peek_mask_uint64_be< M >, Cs... > {}; template< std::uint64_t M, std::uint64_t Lo, std::uint64_t Hi > struct mask_range : internal::range< internal::result_on_found::success, internal::peek_mask_uint64_be< M >, Lo, Hi > {}; template< std::uint64_t M, std::uint64_t... Cs > struct mask_ranges : internal::ranges< internal::peek_mask_uint64_be< M >, Cs... > {}; template< std::uint64_t M, std::uint64_t... Cs > struct mask_string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_mask_uint64_be< M >, Cs >... > {}; // clang-format on } // namespace uint64_be namespace uint64_le { // clang-format off struct any : internal::any< internal::peek_uint64_le > {}; template< std::uint64_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_uint64_le, Cs... > {}; template< std::uint64_t Lo, std::uint64_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_uint64_le, Lo, Hi > {}; template< std::uint64_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_uint64_le, Cs... > {}; template< std::uint64_t Lo, std::uint64_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_uint64_le, Lo, Hi > {}; template< std::uint64_t... Cs > struct ranges : internal::ranges< internal::peek_uint64_le, Cs... > {}; template< std::uint64_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_uint64_le, Cs >... > {}; template< std::uint64_t M, std::uint64_t... Cs > struct mask_not_one : internal::one< internal::result_on_found::failure, internal::peek_mask_uint64_le< M >, Cs... > {}; template< std::uint64_t M, std::uint64_t Lo, std::uint64_t Hi > struct mask_not_range : internal::range< internal::result_on_found::failure, internal::peek_mask_uint64_le< M >, Lo, Hi > {}; template< std::uint64_t M, std::uint64_t... Cs > struct mask_one : internal::one< internal::result_on_found::success, internal::peek_mask_uint64_le< M >, Cs... > {}; template< std::uint64_t M, std::uint64_t Lo, std::uint64_t Hi > struct mask_range : internal::range< internal::result_on_found::success, internal::peek_mask_uint64_le< M >, Lo, Hi > {}; template< std::uint64_t M, std::uint64_t... Cs > struct mask_ranges : internal::ranges< internal::peek_mask_uint64_le< M >, Cs... > {}; template< std::uint64_t M, std::uint64_t... Cs > struct mask_string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_mask_uint64_le< M >, Cs >... > {}; // clang-format on } // namespace uint64_le } // namespace TAO_PEGTL_NAMESPACE #endif #line 17 "tao/pegtl.hpp" #line 1 "tao/pegtl/uint8.hpp" #line 1 "tao/pegtl/uint8.hpp" #ifndef TAO_PEGTL_UINT8_HPP #define TAO_PEGTL_UINT8_HPP #line 1 "tao/pegtl/internal/peek_mask_uint8.hpp" #line 1 "tao/pegtl/internal/peek_mask_uint8.hpp" #ifndef TAO_PEGTL_INTERNAL_PEEK_MASK_UINT8_HPP #define TAO_PEGTL_INTERNAL_PEEK_MASK_UINT8_HPP #include <cstddef> #include <cstdint> namespace TAO_PEGTL_NAMESPACE::internal { template< std::uint8_t M > struct peek_mask_uint8 { using data_t = std::uint8_t; using pair_t = input_pair< std::uint8_t >; static constexpr std::size_t min_input_size = 1; static constexpr std::size_t max_input_size = 1; template< typename Input > [[nodiscard]] static pair_t peek( const Input& in, const std::size_t /*unused*/ = 1 ) noexcept { return { std::uint8_t( in.peek_uint8() & M ), 1 }; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/uint8.hpp" #line 1 "tao/pegtl/internal/peek_uint8.hpp" #line 1 "tao/pegtl/internal/peek_uint8.hpp" #ifndef TAO_PEGTL_INTERNAL_PEEK_UINT8_HPP #define TAO_PEGTL_INTERNAL_PEEK_UINT8_HPP #include <cstddef> #include <cstdint> namespace TAO_PEGTL_NAMESPACE::internal { struct peek_uint8 { using data_t = std::uint8_t; using pair_t = input_pair< std::uint8_t >; static constexpr std::size_t min_input_size = 1; static constexpr std::size_t max_input_size = 1; template< typename Input > [[nodiscard]] static pair_t peek( const Input& in, const std::size_t /*unused*/ = 1 ) noexcept { return { in.peek_uint8(), 1 }; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 11 "tao/pegtl/uint8.hpp" namespace TAO_PEGTL_NAMESPACE::uint8 { // clang-format off struct any : internal::any< internal::peek_uint8 > {}; template< std::uint8_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_uint8, Cs... > {}; template< std::uint8_t Lo, std::uint8_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_uint8, Lo, Hi > {}; template< std::uint8_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_uint8, Cs... > {}; template< std::uint8_t Lo, std::uint8_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_uint8, Lo, Hi > {}; template< std::uint8_t... Cs > struct ranges : internal::ranges< internal::peek_uint8, Cs... > {}; template< std::uint8_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_uint8, Cs >... > {}; template< std::uint8_t M, std::uint8_t... Cs > struct mask_not_one : internal::one< internal::result_on_found::failure, internal::peek_mask_uint8< M >, Cs... > {}; template< std::uint8_t M, std::uint8_t Lo, std::uint8_t Hi > struct mask_not_range : internal::range< internal::result_on_found::failure, internal::peek_mask_uint8< M >, Lo, Hi > {}; template< std::uint8_t M, std::uint8_t... Cs > struct mask_one : internal::one< internal::result_on_found::success, internal::peek_mask_uint8< M >, Cs... > {}; template< std::uint8_t M, std::uint8_t Lo, std::uint8_t Hi > struct mask_range : internal::range< internal::result_on_found::success, internal::peek_mask_uint8< M >, Lo, Hi > {}; template< std::uint8_t M, std::uint8_t... Cs > struct mask_ranges : internal::ranges< internal::peek_mask_uint8< M >, Cs... > {}; template< std::uint8_t M, std::uint8_t... Cs > struct mask_string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_mask_uint8< M >, Cs >... > {}; // clang-format on } // namespace TAO_PEGTL_NAMESPACE::uint8 #endif #line 18 "tao/pegtl.hpp" #line 1 "tao/pegtl/utf16.hpp" #line 1 "tao/pegtl/utf16.hpp" #ifndef TAO_PEGTL_UTF16_HPP #define TAO_PEGTL_UTF16_HPP #line 1 "tao/pegtl/internal/peek_utf16.hpp" #line 1 "tao/pegtl/internal/peek_utf16.hpp" #ifndef TAO_PEGTL_INTERNAL_PEEK_UTF16_HPP #define TAO_PEGTL_INTERNAL_PEEK_UTF16_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE::internal { template< typename R > struct peek_utf16_impl { using data_t = char32_t; using pair_t = input_pair< char32_t >; using short_t = std::make_unsigned< char16_t >::type; static_assert( sizeof( short_t ) == 2 ); static_assert( sizeof( char16_t ) == 2 ); static constexpr std::size_t min_input_size = 2; static constexpr std::size_t max_input_size = 4; template< typename Input > [[nodiscard]] static pair_t peek( const Input& in, const std::size_t s ) noexcept { const char32_t t = R::read( in.current() ); if( ( t < 0xd800 ) || ( t > 0xdfff ) ) { return { t, 2 }; } if( ( t >= 0xdc00 ) || ( s < 4 ) ) { return { 0, 0 }; } const char32_t u = R::read( in.current() + 2 ); if( ( u >= 0xdc00 ) && ( u <= 0xdfff ) ) { const auto cp = ( ( ( t & 0x03ff ) << 10 ) | ( u & 0x03ff ) ) + 0x10000; return { cp, 4 }; } return { 0, 0 }; } }; using peek_utf16_be = peek_utf16_impl< read_uint16_be >; using peek_utf16_le = peek_utf16_impl< read_uint16_le >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/utf16.hpp" namespace TAO_PEGTL_NAMESPACE { namespace utf16_be { // clang-format off struct any : internal::any< internal::peek_utf16_be > {}; struct bom : internal::one< internal::result_on_found::success, internal::peek_utf16_be, 0xfeff > {}; template< char32_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_utf16_be, Cs... > {}; template< char32_t Lo, char32_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_utf16_be, Lo, Hi > {}; template< char32_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_utf16_be, Cs... > {}; template< char32_t Lo, char32_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_utf16_be, Lo, Hi > {}; template< char32_t... Cs > struct ranges : internal::ranges< internal::peek_utf16_be, Cs... > {}; template< char32_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_utf16_be, Cs >... > {}; // clang-format on } // namespace utf16_be namespace utf16_le { // clang-format off struct any : internal::any< internal::peek_utf16_le > {}; struct bom : internal::one< internal::result_on_found::success, internal::peek_utf16_le, 0xfeff > {}; template< char32_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_utf16_le, Cs... > {}; template< char32_t Lo, char32_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_utf16_le, Lo, Hi > {}; template< char32_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_utf16_le, Cs... > {}; template< char32_t Lo, char32_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_utf16_le, Lo, Hi > {}; template< char32_t... Cs > struct ranges : internal::ranges< internal::peek_utf16_le, Cs... > {}; template< char32_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_utf16_le, Cs >... > {}; // clang-format on } // namespace utf16_le namespace utf16 = TAO_PEGTL_NATIVE_UTF16; } // namespace TAO_PEGTL_NAMESPACE #endif #line 19 "tao/pegtl.hpp" #line 1 "tao/pegtl/utf32.hpp" #line 1 "tao/pegtl/utf32.hpp" #ifndef TAO_PEGTL_UTF32_HPP #define TAO_PEGTL_UTF32_HPP #line 1 "tao/pegtl/internal/peek_utf32.hpp" #line 1 "tao/pegtl/internal/peek_utf32.hpp" #ifndef TAO_PEGTL_INTERNAL_PEEK_UTF32_HPP #define TAO_PEGTL_INTERNAL_PEEK_UTF32_HPP #include <cstddef> namespace TAO_PEGTL_NAMESPACE::internal { template< typename R > struct peek_utf32_impl { using data_t = char32_t; using pair_t = input_pair< char32_t >; static_assert( sizeof( char32_t ) == 4 ); static constexpr std::size_t min_input_size = 4; static constexpr std::size_t max_input_size = 4; template< typename Input > [[nodiscard]] static pair_t peek( const Input& in, const std::size_t /*unused*/ ) noexcept { const char32_t t = R::read( in.current() ); if( ( t <= 0x10ffff ) && !( t >= 0xd800 && t <= 0xdfff ) ) { return { t, 4 }; } return { 0, 0 }; } }; using peek_utf32_be = peek_utf32_impl< read_uint32_be >; using peek_utf32_le = peek_utf32_impl< read_uint32_le >; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/utf32.hpp" namespace TAO_PEGTL_NAMESPACE { namespace utf32_be { // clang-format off struct any : internal::any< internal::peek_utf32_be > {}; struct bom : internal::one< internal::result_on_found::success, internal::peek_utf32_be, 0xfeff > {}; template< char32_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_utf32_be, Cs... > {}; template< char32_t Lo, char32_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_utf32_be, Lo, Hi > {}; template< char32_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_utf32_be, Cs... > {}; template< char32_t Lo, char32_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_utf32_be, Lo, Hi > {}; template< char32_t... Cs > struct ranges : internal::ranges< internal::peek_utf32_be, Cs... > {}; template< char32_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_utf32_be, Cs >... > {}; // clang-format on } // namespace utf32_be namespace utf32_le { // clang-format off struct any : internal::any< internal::peek_utf32_le > {}; struct bom : internal::one< internal::result_on_found::success, internal::peek_utf32_le, 0xfeff > {}; template< char32_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_utf32_le, Cs... > {}; template< char32_t Lo, char32_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_utf32_le, Lo, Hi > {}; template< char32_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_utf32_le, Cs... > {}; template< char32_t Lo, char32_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_utf32_le, Lo, Hi > {}; template< char32_t... Cs > struct ranges : internal::ranges< internal::peek_utf32_le, Cs... > {}; template< char32_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_utf32_le, Cs >... > {}; // clang-format on } // namespace utf32_le namespace utf32 = TAO_PEGTL_NATIVE_UTF32; } // namespace TAO_PEGTL_NAMESPACE #endif #line 20 "tao/pegtl.hpp" #line 1 "tao/pegtl/utf8.hpp" #line 1 "tao/pegtl/utf8.hpp" #ifndef TAO_PEGTL_UTF8_HPP #define TAO_PEGTL_UTF8_HPP #line 1 "tao/pegtl/internal/peek_utf8.hpp" #line 1 "tao/pegtl/internal/peek_utf8.hpp" #ifndef TAO_PEGTL_INTERNAL_PEEK_UTF8_HPP #define TAO_PEGTL_INTERNAL_PEEK_UTF8_HPP namespace TAO_PEGTL_NAMESPACE::internal { struct peek_utf8 { using data_t = char32_t; using pair_t = input_pair< char32_t >; static constexpr std::size_t min_input_size = 1; static constexpr std::size_t max_input_size = 4; template< typename Input > [[nodiscard]] static pair_t peek( const Input& in, const std::size_t s ) noexcept { char32_t c0 = in.peek_uint8(); if( ( c0 & 0x80 ) == 0 ) { return { c0, 1 }; } return peek_impl( in, c0, s ); } private: template< typename Input > [[nodiscard]] static pair_t peek_impl( const Input& in, char32_t c0, const std::size_t s ) noexcept { if( ( c0 & 0xE0 ) == 0xC0 ) { if( s >= 2 ) { const char32_t c1 = in.peek_uint8( 1 ); if( ( c1 & 0xC0 ) == 0x80 ) { c0 &= 0x1F; c0 <<= 6; c0 |= ( c1 & 0x3F ); if( c0 >= 0x80 ) { return { c0, 2 }; } } } } else if( ( c0 & 0xF0 ) == 0xE0 ) { if( s >= 3 ) { const char32_t c1 = in.peek_uint8( 1 ); const char32_t c2 = in.peek_uint8( 2 ); if( ( ( c1 & 0xC0 ) == 0x80 ) && ( ( c2 & 0xC0 ) == 0x80 ) ) { c0 &= 0x0F; c0 <<= 6; c0 |= ( c1 & 0x3F ); c0 <<= 6; c0 |= ( c2 & 0x3F ); if( c0 >= 0x800 && !( c0 >= 0xD800 && c0 <= 0xDFFF ) ) { return { c0, 3 }; } } } } else if( ( c0 & 0xF8 ) == 0xF0 ) { if( s >= 4 ) { const char32_t c1 = in.peek_uint8( 1 ); const char32_t c2 = in.peek_uint8( 2 ); const char32_t c3 = in.peek_uint8( 3 ); if( ( ( c1 & 0xC0 ) == 0x80 ) && ( ( c2 & 0xC0 ) == 0x80 ) && ( ( c3 & 0xC0 ) == 0x80 ) ) { c0 &= 0x07; c0 <<= 6; c0 |= ( c1 & 0x3F ); c0 <<= 6; c0 |= ( c2 & 0x3F ); c0 <<= 6; c0 |= ( c3 & 0x3F ); if( c0 >= 0x10000 && c0 <= 0x10FFFF ) { return { c0, 4 }; } } } } return { 0, 0 }; } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 10 "tao/pegtl/utf8.hpp" namespace TAO_PEGTL_NAMESPACE::utf8 { // clang-format off struct any : internal::any< internal::peek_utf8 > {}; struct bom : internal::one< internal::result_on_found::success, internal::peek_utf8, 0xfeff > {}; template< char32_t... Cs > struct not_one : internal::one< internal::result_on_found::failure, internal::peek_utf8, Cs... > {}; template< char32_t Lo, char32_t Hi > struct not_range : internal::range< internal::result_on_found::failure, internal::peek_utf8, Lo, Hi > {}; template< char32_t... Cs > struct one : internal::one< internal::result_on_found::success, internal::peek_utf8, Cs... > {}; template< char32_t Lo, char32_t Hi > struct range : internal::range< internal::result_on_found::success, internal::peek_utf8, Lo, Hi > {}; template< char32_t... Cs > struct ranges : internal::ranges< internal::peek_utf8, Cs... > {}; template< char32_t... Cs > struct string : internal::seq< internal::one< internal::result_on_found::success, internal::peek_utf8, Cs >... > {}; // clang-format on } // namespace TAO_PEGTL_NAMESPACE::utf8 #endif #line 21 "tao/pegtl.hpp" #line 1 "tao/pegtl/argv_input.hpp" #line 1 "tao/pegtl/argv_input.hpp" #ifndef TAO_PEGTL_ARGV_INPUT_HPP #define TAO_PEGTL_ARGV_INPUT_HPP #include <cstddef> #include <sstream> #include <string> #include <utility> namespace TAO_PEGTL_NAMESPACE { namespace internal { [[nodiscard]] inline std::string make_argv_source( const std::size_t argn ) { std::ostringstream os; os << "argv[" << argn << ']'; return os.str(); } } // namespace internal template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf > struct argv_input : memory_input< P, Eol > { template< typename T > argv_input( char** argv, const std::size_t argn, T&& in_source ) : memory_input< P, Eol >( static_cast< const char* >( argv[ argn ] ), std::forward< T >( in_source ) ) { } argv_input( char** argv, const std::size_t argn ) : argv_input( argv, argn, internal::make_argv_source( argn ) ) { } }; template< typename... Ts > argv_input( Ts&&... )->argv_input<>; } // namespace TAO_PEGTL_NAMESPACE #endif #line 23 "tao/pegtl.hpp" #line 1 "tao/pegtl/buffer_input.hpp" #line 1 "tao/pegtl/buffer_input.hpp" #ifndef TAO_PEGTL_BUFFER_INPUT_HPP #define TAO_PEGTL_BUFFER_INPUT_HPP #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <stdexcept> #include <string> #line 27 "tao/pegtl/buffer_input.hpp" namespace TAO_PEGTL_NAMESPACE { template< typename Reader, typename Eol = eol::lf_crlf, typename Source = std::string, std::size_t Chunk = 64 > class buffer_input { public: using reader_t = Reader; using eol_t = Eol; using source_t = Source; using iterator_t = internal::iterator; using action_t = internal::action_input< buffer_input >; static constexpr std::size_t chunk_size = Chunk; static constexpr tracking_mode tracking_mode_v = tracking_mode::eager; template< typename T, typename... As > buffer_input( T&& in_source, const std::size_t maximum, As&&... as ) : m_reader( std::forward< As >( as )... ), m_maximum( maximum + Chunk ), m_buffer( new char[ maximum + Chunk ] ), m_current( m_buffer.get() ), m_end( m_buffer.get() ), m_source( std::forward< T >( in_source ) ) { static_assert( Chunk, "zero chunk size not implemented" ); assert( m_maximum > maximum ); // Catches overflow; change to >= when zero chunk size is implemented. } buffer_input( const buffer_input& ) = delete; buffer_input( buffer_input&& ) = delete; ~buffer_input() = default; void operator=( const buffer_input& ) = delete; void operator=( buffer_input&& ) = delete; [[nodiscard]] bool empty() { require( 1 ); return m_current.data == m_end; } [[nodiscard]] std::size_t size( const std::size_t amount ) { require( amount ); return buffer_occupied(); } [[nodiscard]] const char* current() const noexcept { return m_current.data; } [[nodiscard]] const char* end( const std::size_t amount ) { require( amount ); return m_end; } [[nodiscard]] std::size_t byte() const noexcept { return m_current.byte; } [[nodiscard]] std::size_t line() const noexcept { return m_current.line; } [[nodiscard]] std::size_t byte_in_line() const noexcept { return m_current.byte_in_line; } [[nodiscard]] const Source& source() const noexcept { return m_source; } [[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept { return m_current.data[ offset ]; } [[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept { return static_cast< std::uint8_t >( peek_char( offset ) ); } void bump( const std::size_t in_count = 1 ) noexcept { internal::bump( m_current, in_count, Eol::ch ); } void bump_in_this_line( const std::size_t in_count = 1 ) noexcept { internal::bump_in_this_line( m_current, in_count ); } void bump_to_next_line( const std::size_t in_count = 1 ) noexcept { internal::bump_to_next_line( m_current, in_count ); } void discard() noexcept { if( m_current.data > m_buffer.get() + Chunk ) { const auto s = m_end - m_current.data; std::memmove( m_buffer.get(), m_current.data, s ); m_current.data = m_buffer.get(); m_end = m_buffer.get() + s; } } void require( const std::size_t amount ) { if( m_current.data + amount <= m_end ) { return; } if( m_current.data + amount > m_buffer.get() + m_maximum ) { throw std::overflow_error( "require beyond end of buffer" ); } if( const auto r = m_reader( m_end, ( std::min )( buffer_free_after_end(), ( std::max )( amount, Chunk ) ) ) ) { m_end += r; } } template< rewind_mode M > [[nodiscard]] internal::marker< iterator_t, M > mark() noexcept { return internal::marker< iterator_t, M >( m_current ); } [[nodiscard]] TAO_PEGTL_NAMESPACE::position position( const iterator_t& it ) const { return TAO_PEGTL_NAMESPACE::position( it, m_source ); } [[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const { return position( m_current ); } [[nodiscard]] const iterator_t& iterator() const noexcept { return m_current; } [[nodiscard]] std::size_t buffer_capacity() const noexcept { return m_maximum; } [[nodiscard]] std::size_t buffer_occupied() const noexcept { assert( m_end >= m_current.data ); return std::size_t( m_end - m_current.data ); } [[nodiscard]] std::size_t buffer_free_before_current() const noexcept { assert( m_current.data >= m_buffer.get() ); return std::size_t( m_current.data - m_buffer.get() ); } [[nodiscard]] std::size_t buffer_free_after_end() const noexcept { assert( m_buffer.get() + m_maximum >= m_end ); return std::size_t( m_buffer.get() + m_maximum - m_end ); } private: Reader m_reader; std::size_t m_maximum; std::unique_ptr< char[] > m_buffer; iterator_t m_current; char* m_end; const Source m_source; }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 24 "tao/pegtl.hpp" #line 1 "tao/pegtl/cstream_input.hpp" #line 1 "tao/pegtl/cstream_input.hpp" #ifndef TAO_PEGTL_CSTREAM_INPUT_HPP #define TAO_PEGTL_CSTREAM_INPUT_HPP #include <cstdio> #line 1 "tao/pegtl/internal/cstream_reader.hpp" #line 1 "tao/pegtl/internal/cstream_reader.hpp" #ifndef TAO_PEGTL_INTERNAL_CSTREAM_READER_HPP #define TAO_PEGTL_INTERNAL_CSTREAM_READER_HPP #include <cassert> #include <cstddef> #include <cstdio> #include <system_error> namespace TAO_PEGTL_NAMESPACE::internal { struct cstream_reader { explicit cstream_reader( std::FILE* s ) noexcept : m_cstream( s ) { assert( m_cstream != nullptr ); } [[nodiscard]] std::size_t operator()( char* buffer, const std::size_t length ) { if( const auto r = std::fread( buffer, 1, length, m_cstream ) ) { return r; } if( std::feof( m_cstream ) != 0 ) { return 0; } // Please contact us if you know how to provoke the following exception. // The example on cppreference.com doesn't work, at least not on macOS. // LCOV_EXCL_START const auto ec = std::ferror( m_cstream ); assert( ec != 0 ); throw std::system_error( ec, std::system_category(), "fread() failed" ); // LCOV_EXCL_STOP } std::FILE* m_cstream; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 14 "tao/pegtl/cstream_input.hpp" namespace TAO_PEGTL_NAMESPACE { template< typename Eol = eol::lf_crlf, std::size_t Chunk = 64 > struct cstream_input : buffer_input< internal::cstream_reader, Eol, std::string, Chunk > { template< typename T > cstream_input( std::FILE* in_stream, const std::size_t in_maximum, T&& in_source ) : buffer_input< internal::cstream_reader, Eol, std::string, Chunk >( std::forward< T >( in_source ), in_maximum, in_stream ) { } }; template< typename... Ts > cstream_input( Ts&&... )->cstream_input<>; } // namespace TAO_PEGTL_NAMESPACE #endif #line 25 "tao/pegtl.hpp" #line 1 "tao/pegtl/istream_input.hpp" #line 1 "tao/pegtl/istream_input.hpp" #ifndef TAO_PEGTL_ISTREAM_INPUT_HPP #define TAO_PEGTL_ISTREAM_INPUT_HPP #include <istream> #line 1 "tao/pegtl/internal/istream_reader.hpp" #line 1 "tao/pegtl/internal/istream_reader.hpp" #ifndef TAO_PEGTL_INTERNAL_ISTREAM_READER_HPP #define TAO_PEGTL_INTERNAL_ISTREAM_READER_HPP #include <istream> #include <system_error> namespace TAO_PEGTL_NAMESPACE::internal { struct istream_reader { explicit istream_reader( std::istream& s ) noexcept : m_istream( s ) { } [[nodiscard]] std::size_t operator()( char* buffer, const std::size_t length ) { m_istream.read( buffer, std::streamsize( length ) ); if( const auto r = m_istream.gcount() ) { return std::size_t( r ); } if( m_istream.eof() ) { return 0; } const auto ec = errno; throw std::system_error( ec, std::system_category(), "std::istream::read() failed" ); } std::istream& m_istream; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 14 "tao/pegtl/istream_input.hpp" namespace TAO_PEGTL_NAMESPACE { template< typename Eol = eol::lf_crlf, std::size_t Chunk = 64 > struct istream_input : buffer_input< internal::istream_reader, Eol, std::string, Chunk > { template< typename T > istream_input( std::istream& in_stream, const std::size_t in_maximum, T&& in_source ) : buffer_input< internal::istream_reader, Eol, std::string, Chunk >( std::forward< T >( in_source ), in_maximum, in_stream ) { } }; template< typename... Ts > istream_input( Ts&&... )->istream_input<>; } // namespace TAO_PEGTL_NAMESPACE #endif #line 26 "tao/pegtl.hpp" #line 1 "tao/pegtl/read_input.hpp" #line 1 "tao/pegtl/read_input.hpp" #ifndef TAO_PEGTL_READ_INPUT_HPP #define TAO_PEGTL_READ_INPUT_HPP #include <string> #line 1 "tao/pegtl/string_input.hpp" #line 1 "tao/pegtl/string_input.hpp" #ifndef TAO_PEGTL_STRING_INPUT_HPP #define TAO_PEGTL_STRING_INPUT_HPP #include <string> #include <utility> namespace TAO_PEGTL_NAMESPACE { namespace internal { struct string_holder { const std::string data; template< typename T > explicit string_holder( T&& in_data ) : data( std::forward< T >( in_data ) ) { } string_holder( const string_holder& ) = delete; string_holder( string_holder&& ) = delete; ~string_holder() = default; void operator=( const string_holder& ) = delete; void operator=( string_holder&& ) = delete; }; } // namespace internal template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf, typename Source = std::string > struct string_input : private internal::string_holder, public memory_input< P, Eol, Source > { template< typename V, typename T, typename... Ts > explicit string_input( V&& in_data, T&& in_source, Ts&&... ts ) : internal::string_holder( std::forward< V >( in_data ) ), memory_input< P, Eol, Source >( data.data(), data.size(), std::forward< T >( in_source ), std::forward< Ts >( ts )... ) { } string_input( const string_input& ) = delete; string_input( string_input&& ) = delete; ~string_input() = default; void operator=( const string_input& ) = delete; void operator=( string_input&& ) = delete; }; template< typename... Ts > explicit string_input( Ts&&... )->string_input<>; } // namespace TAO_PEGTL_NAMESPACE #endif #line 12 "tao/pegtl/read_input.hpp" #line 1 "tao/pegtl/internal/file_reader.hpp" #line 1 "tao/pegtl/internal/file_reader.hpp" #ifndef TAO_PEGTL_INTERNAL_FILE_READER_HPP #define TAO_PEGTL_INTERNAL_FILE_READER_HPP #include <cstdio> #include <memory> #include <string> #include <system_error> #include <utility> namespace TAO_PEGTL_NAMESPACE::internal { [[nodiscard]] inline std::FILE* file_open( const char* filename ) { errno = 0; #if defined( _MSC_VER ) std::FILE* file; if( ::fopen_s( &file, filename, "rb" ) == 0 ) #elif defined( __MINGW32__ ) if( auto* file = std::fopen( filename, "rb" ) ) #else if( auto* file = std::fopen( filename, "rbe" ) ) #endif { return file; } const auto ec = errno; throw std::system_error( ec, std::system_category(), filename ); } struct file_close { void operator()( FILE* f ) const noexcept { std::fclose( f ); } }; class file_reader { public: explicit file_reader( const char* filename ) : m_source( filename ), m_file( file_open( m_source ) ) { } file_reader( FILE* file, const char* filename ) noexcept : m_source( filename ), m_file( file ) { } file_reader( const file_reader& ) = delete; file_reader( file_reader&& ) = delete; ~file_reader() = default; void operator=( const file_reader& ) = delete; void operator=( file_reader&& ) = delete; [[nodiscard]] std::size_t size() const { errno = 0; if( std::fseek( m_file.get(), 0, SEEK_END ) != 0 ) { // LCOV_EXCL_START const auto ec = errno; throw std::system_error( ec, std::system_category(), m_source ); // LCOV_EXCL_STOP } errno = 0; const auto s = std::ftell( m_file.get() ); if( s < 0 ) { // LCOV_EXCL_START const auto ec = errno; throw std::system_error( ec, std::system_category(), m_source ); // LCOV_EXCL_STOP } errno = 0; if( std::fseek( m_file.get(), 0, SEEK_SET ) != 0 ) { // LCOV_EXCL_START const auto ec = errno; throw std::system_error( ec, std::system_category(), m_source ); // LCOV_EXCL_STOP } return std::size_t( s ); } [[nodiscard]] std::string read() const { std::string nrv; nrv.resize( size() ); errno = 0; if( !nrv.empty() && ( std::fread( &nrv[ 0 ], nrv.size(), 1, m_file.get() ) != 1 ) ) { // LCOV_EXCL_START const auto ec = errno; throw std::system_error( ec, std::system_category(), m_source ); // LCOV_EXCL_STOP } return nrv; } private: const char* const m_source; const std::unique_ptr< std::FILE, file_close > m_file; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 15 "tao/pegtl/read_input.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { struct filename_holder { const std::string filename; template< typename T > explicit filename_holder( T&& in_filename ) : filename( std::forward< T >( in_filename ) ) { } filename_holder( const filename_holder& ) = delete; filename_holder( filename_holder&& ) = delete; ~filename_holder() = default; void operator=( const filename_holder& ) = delete; void operator=( filename_holder&& ) = delete; }; } // namespace internal template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf > struct read_input : private internal::filename_holder, public string_input< P, Eol, const char* > { template< typename T > explicit read_input( T&& in_filename ) : internal::filename_holder( std::forward< T >( in_filename ) ), string_input< P, Eol, const char* >( internal::file_reader( filename.c_str() ).read(), filename.c_str() ) { } template< typename T > read_input( FILE* in_file, T&& in_filename ) : internal::filename_holder( std::forward< T >( in_filename ) ), string_input< P, Eol, const char* >( internal::file_reader( in_file, filename.c_str() ).read(), filename.c_str() ) { } read_input( const read_input& ) = delete; read_input( read_input&& ) = delete; ~read_input() = default; void operator=( const read_input& ) = delete; void operator=( read_input&& ) = delete; }; template< typename... Ts > explicit read_input( Ts&&... )->read_input<>; } // namespace TAO_PEGTL_NAMESPACE #endif #line 28 "tao/pegtl.hpp" // this has to be included *after* the above inputs, // otherwise the amalgamated header will not work! #line 1 "tao/pegtl/file_input.hpp" #line 1 "tao/pegtl/file_input.hpp" #ifndef TAO_PEGTL_FILE_INPUT_HPP #define TAO_PEGTL_FILE_INPUT_HPP #if defined( __unix__ ) || ( defined( __APPLE__ ) && defined( __MACH__ ) ) #include <unistd.h> // Required for _POSIX_MAPPED_FILES #endif #if defined( _POSIX_MAPPED_FILES ) || defined( _WIN32 ) #line 1 "tao/pegtl/mmap_input.hpp" #line 1 "tao/pegtl/mmap_input.hpp" #ifndef TAO_PEGTL_MMAP_INPUT_HPP #define TAO_PEGTL_MMAP_INPUT_HPP #include <string> #include <utility> #if defined( __unix__ ) || ( defined( __APPLE__ ) && defined( __MACH__ ) ) #include <unistd.h> // Required for _POSIX_MAPPED_FILES #endif #if defined( _POSIX_MAPPED_FILES ) #line 1 "tao/pegtl/internal/file_mapper_posix.hpp" #line 1 "tao/pegtl/internal/file_mapper_posix.hpp" #ifndef TAO_PEGTL_INTERNAL_FILE_MAPPER_POSIX_HPP #define TAO_PEGTL_INTERNAL_FILE_MAPPER_POSIX_HPP #include <sys/mman.h> #include <unistd.h> #include <system_error> #line 1 "tao/pegtl/internal/file_opener.hpp" #line 1 "tao/pegtl/internal/file_opener.hpp" #ifndef TAO_PEGTL_INTERNAL_FILE_OPENER_HPP #define TAO_PEGTL_INTERNAL_FILE_OPENER_HPP #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <system_error> #include <utility> namespace TAO_PEGTL_NAMESPACE::internal { struct file_opener { explicit file_opener( const char* filename ) : m_source( filename ), m_fd( open() ) { } file_opener( const file_opener& ) = delete; file_opener( file_opener&& ) = delete; ~file_opener() noexcept { ::close( m_fd ); } void operator=( const file_opener& ) = delete; void operator=( file_opener&& ) = delete; [[nodiscard]] std::size_t size() const { struct stat st; errno = 0; if( ::fstat( m_fd, &st ) < 0 ) { const auto ec = errno; throw std::system_error( ec, std::system_category(), m_source ); } return std::size_t( st.st_size ); } const char* const m_source; const int m_fd; private: [[nodiscard]] int open() const { errno = 0; const int fd = ::open( m_source, O_RDONLY #if defined( O_CLOEXEC ) | O_CLOEXEC #endif ); if( fd >= 0 ) { return fd; } const auto ec = errno; throw std::system_error( ec, std::system_category(), m_source ); } }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 15 "tao/pegtl/internal/file_mapper_posix.hpp" namespace TAO_PEGTL_NAMESPACE::internal { class file_mapper { public: explicit file_mapper( const char* filename ) : file_mapper( file_opener( filename ) ) { } explicit file_mapper( const file_opener& reader ) : m_size( reader.size() ), m_data( static_cast< const char* >( ::mmap( nullptr, m_size, PROT_READ, MAP_PRIVATE, reader.m_fd, 0 ) ) ) { if( ( m_size != 0 ) && ( intptr_t( m_data ) == -1 ) ) { const auto ec = errno; throw std::system_error( ec, std::system_category(), reader.m_source ); } } file_mapper( const file_mapper& ) = delete; file_mapper( file_mapper&& ) = delete; ~file_mapper() noexcept { // Legacy C interface requires pointer-to-mutable but does not write through the pointer. ::munmap( const_cast< char* >( m_data ), m_size ); } void operator=( const file_mapper& ) = delete; void operator=( file_mapper&& ) = delete; [[nodiscard]] bool empty() const noexcept { return m_size == 0; } [[nodiscard]] std::size_t size() const noexcept { return m_size; } using iterator = const char*; using const_iterator = const char*; [[nodiscard]] iterator data() const noexcept { return m_data; } [[nodiscard]] iterator begin() const noexcept { return m_data; } [[nodiscard]] iterator end() const noexcept { return m_data + m_size; } private: const std::size_t m_size; const char* const m_data; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 21 "tao/pegtl/mmap_input.hpp" #elif defined( _WIN32 ) #line 1 "tao/pegtl/internal/file_mapper_win32.hpp" #line 1 "tao/pegtl/internal/file_mapper_win32.hpp" #ifndef TAO_PEGTL_INTERNAL_FILE_MAPPER_WIN32_HPP #define TAO_PEGTL_INTERNAL_FILE_MAPPER_WIN32_HPP #if !defined( NOMINMAX ) #define NOMINMAX #define TAO_PEGTL_NOMINMAX_WAS_DEFINED #endif #if !defined( WIN32_LEAN_AND_MEAN ) #define WIN32_LEAN_AND_MEAN #define TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED #endif #include <windows.h> #if defined( TAO_PEGTL_NOMINMAX_WAS_DEFINED ) #undef NOMINMAX #undef TAO_PEGTL_NOMINMAX_WAS_DEFINED #endif #if defined( TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED ) #undef WIN32_LEAN_AND_MEAN #undef TAO_PEGTL_WIN32_LEAN_AND_MEAN_WAS_DEFINED #endif #include <system_error> namespace TAO_PEGTL_NAMESPACE::internal { struct win32_file_opener { explicit win32_file_opener( const char* filename ) : m_source( filename ), m_handle( open() ) { } win32_file_opener( const win32_file_opener& ) = delete; win32_file_opener( win32_file_opener&& ) = delete; ~win32_file_opener() noexcept { ::CloseHandle( m_handle ); } void operator=( const win32_file_opener& ) = delete; void operator=( win32_file_opener&& ) = delete; [[nodiscard]] std::size_t size() const { LARGE_INTEGER size; if( !::GetFileSizeEx( m_handle, &size ) ) { const auto ec = ::GetLastError(); throw std::system_error( ec, std::system_category(), std::string( "GetFileSizeEx(): " ) + m_source ); } return std::size_t( size.QuadPart ); } const char* const m_source; const HANDLE m_handle; private: [[nodiscard]] HANDLE open() const { SetLastError( 0 ); std::wstring ws( m_source, m_source + strlen( m_source ) ); #if( _WIN32_WINNT >= 0x0602 ) const HANDLE handle = ::CreateFile2( ws.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr ); if( handle != INVALID_HANDLE_VALUE ) { return handle; } const auto ec = ::GetLastError(); throw std::system_error( ec, std::system_category(), std::string( "CreateFile2(): " ) + m_source ); #else const HANDLE handle = ::CreateFileW( ws.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr ); if( handle != INVALID_HANDLE_VALUE ) { return handle; } const auto ec = ::GetLastError(); throw std::system_error( ec, std::system_category(), std::string( "CreateFileW(): " ) + m_source ); #endif } }; struct win32_file_mapper { explicit win32_file_mapper( const char* filename ) : win32_file_mapper( win32_file_opener( filename ) ) { } explicit win32_file_mapper( const win32_file_opener& reader ) : m_size( reader.size() ), m_handle( open( reader ) ) { } win32_file_mapper( const win32_file_mapper& ) = delete; win32_file_mapper( win32_file_mapper&& ) = delete; ~win32_file_mapper() noexcept { ::CloseHandle( m_handle ); } void operator=( const win32_file_mapper& ) = delete; void operator=( win32_file_mapper&& ) = delete; const size_t m_size; const HANDLE m_handle; private: [[nodiscard]] HANDLE open( const win32_file_opener& reader ) const { const uint64_t file_size = reader.size(); SetLastError( 0 ); // Use `CreateFileMappingW` because a) we're not specifying a // mapping name, so the character type is of no consequence, and // b) it's defined in `memoryapi.h`, unlike // `CreateFileMappingA`(?!) const HANDLE handle = ::CreateFileMappingW( reader.m_handle, nullptr, PAGE_READONLY, DWORD( file_size >> 32 ), DWORD( file_size & 0xffffffff ), nullptr ); if( handle != NULL || file_size == 0 ) { return handle; } const auto ec = ::GetLastError(); throw std::system_error( ec, std::system_category(), std::string( "CreateFileMappingW(): " ) + reader.m_source ); } }; class file_mapper { public: explicit file_mapper( const char* filename ) : file_mapper( win32_file_mapper( filename ) ) { } explicit file_mapper( const win32_file_mapper& mapper ) : m_size( mapper.m_size ), m_data( static_cast< const char* >( ::MapViewOfFile( mapper.m_handle, FILE_MAP_READ, 0, 0, 0 ) ) ) { if( ( m_size != 0 ) && ( intptr_t( m_data ) == 0 ) ) { const auto ec = ::GetLastError(); throw std::system_error( ec, std::system_category(), "MapViewOfFile()" ); } } file_mapper( const file_mapper& ) = delete; file_mapper( file_mapper&& ) = delete; ~file_mapper() noexcept { ::UnmapViewOfFile( LPCVOID( m_data ) ); } void operator=( const file_mapper& ) = delete; void operator=( file_mapper&& ) = delete; [[nodiscard]] bool empty() const noexcept { return m_size == 0; } [[nodiscard]] std::size_t size() const noexcept { return m_size; } using iterator = const char*; using const_iterator = const char*; [[nodiscard]] iterator data() const noexcept { return m_data; } [[nodiscard]] iterator begin() const noexcept { return m_data; } [[nodiscard]] iterator end() const noexcept { return m_data + m_size; } private: const std::size_t m_size; const char* const m_data; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif #line 23 "tao/pegtl/mmap_input.hpp" #else #endif namespace TAO_PEGTL_NAMESPACE { namespace internal { struct mmap_holder { const std::string filename; const file_mapper data; template< typename T > explicit mmap_holder( T&& in_filename ) : filename( std::forward< T >( in_filename ) ), data( filename.c_str() ) { } mmap_holder( const mmap_holder& ) = delete; mmap_holder( mmap_holder&& ) = delete; ~mmap_holder() = default; void operator=( const mmap_holder& ) = delete; void operator=( mmap_holder&& ) = delete; }; } // namespace internal template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf > struct mmap_input : private internal::mmap_holder, public memory_input< P, Eol, const char* > { template< typename T > explicit mmap_input( T&& in_filename ) : internal::mmap_holder( std::forward< T >( in_filename ) ), memory_input< P, Eol, const char* >( data.begin(), data.end(), filename.c_str() ) { } mmap_input( const mmap_input& ) = delete; mmap_input( mmap_input&& ) = delete; ~mmap_input() = default; void operator=( const mmap_input& ) = delete; void operator=( mmap_input&& ) = delete; }; template< typename... Ts > explicit mmap_input( Ts&&... )->mmap_input<>; } // namespace TAO_PEGTL_NAMESPACE #endif #line 17 "tao/pegtl/file_input.hpp" #else #endif namespace TAO_PEGTL_NAMESPACE { #if defined( _POSIX_MAPPED_FILES ) || defined( _WIN32 ) template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf > struct file_input : mmap_input< P, Eol > { using mmap_input< P, Eol >::mmap_input; }; #else template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf > struct file_input : read_input< P, Eol > { using read_input< P, Eol >::read_input; }; #endif template< typename... Ts > explicit file_input( Ts&&... )->file_input<>; } // namespace TAO_PEGTL_NAMESPACE #endif #line 33 "tao/pegtl.hpp" #line 1 "tao/pegtl/change_action.hpp" #line 1 "tao/pegtl/change_action.hpp" #ifndef TAO_PEGTL_CHANGE_ACTION_HPP #define TAO_PEGTL_CHANGE_ACTION_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE { template< template< typename... > class NewAction > struct change_action : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { static_assert( !std::is_same_v< Action< void >, NewAction< void > >, "old and new action class templates are identical" ); return Control< Rule >::template match< A, M, NewAction, Control >( in, st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 35 "tao/pegtl.hpp" #line 1 "tao/pegtl/change_action_and_state.hpp" #line 1 "tao/pegtl/change_action_and_state.hpp" #ifndef TAO_PEGTL_CHANGE_ACTION_AND_STATE_HPP #define TAO_PEGTL_CHANGE_ACTION_AND_STATE_HPP #include <type_traits> namespace TAO_PEGTL_NAMESPACE { template< template< typename... > class NewAction, typename NewState > struct change_action_and_state : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { static_assert( !std::is_same_v< Action< void >, NewAction< void > >, "old and new action class templates are identical" ); NewState s( static_cast< const Input& >( in ), st... ); if( Control< Rule >::template match< A, M, NewAction, Control >( in, s ) ) { if constexpr( A == apply_mode::action ) { Action< Rule >::success( static_cast< const Input& >( in ), s, st... ); } return true; } return false; } template< typename Input, typename... States > static void success( const Input& in, NewState& s, States&&... st ) noexcept( noexcept( s.success( in, st... ) ) ) { s.success( in, st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 36 "tao/pegtl.hpp" #line 1 "tao/pegtl/change_action_and_states.hpp" #line 1 "tao/pegtl/change_action_and_states.hpp" #ifndef TAO_PEGTL_CHANGE_ACTION_AND_STATES_HPP #define TAO_PEGTL_CHANGE_ACTION_AND_STATES_HPP #include <tuple> #include <utility> namespace TAO_PEGTL_NAMESPACE { template< template< typename... > class NewAction, typename... NewStates > struct change_action_and_states : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, std::size_t... Ns, typename Input, typename... States > [[nodiscard]] static bool match( std::index_sequence< Ns... > /*unused*/, Input& in, States&&... st ) { auto t = std::tie( st... ); if( Control< Rule >::template match< A, M, NewAction, Control >( in, std::get< Ns >( t )... ) ) { if constexpr( A == apply_mode::action ) { Action< Rule >::success( static_cast< const Input& >( in ), st... ); } return true; } return false; } template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { static_assert( !std::is_same_v< Action< void >, NewAction< void > >, "old and new action class templates are identical" ); return match< Rule, A, M, Action, Control >( std::index_sequence_for< NewStates... >(), in, NewStates()..., st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 37 "tao/pegtl.hpp" #line 1 "tao/pegtl/change_control.hpp" #line 1 "tao/pegtl/change_control.hpp" #ifndef TAO_PEGTL_CHANGE_CONTROL_HPP #define TAO_PEGTL_CHANGE_CONTROL_HPP namespace TAO_PEGTL_NAMESPACE { template< template< typename... > class NewControl > struct change_control : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, NewControl >( in, st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 38 "tao/pegtl.hpp" #line 1 "tao/pegtl/change_state.hpp" #line 1 "tao/pegtl/change_state.hpp" #ifndef TAO_PEGTL_CHANGE_STATE_HPP #define TAO_PEGTL_CHANGE_STATE_HPP namespace TAO_PEGTL_NAMESPACE { template< typename NewState > struct change_state : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { NewState s( static_cast< const Input& >( in ), st... ); if( TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, Control >( in, s ) ) { if constexpr( A == apply_mode::action ) { Action< Rule >::success( static_cast< const Input& >( in ), s, st... ); } return true; } return false; } template< typename Input, typename... States > static void success( const Input& in, NewState& s, States&&... st ) noexcept( noexcept( s.success( in, st... ) ) ) { s.success( in, st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 39 "tao/pegtl.hpp" #line 1 "tao/pegtl/change_states.hpp" #line 1 "tao/pegtl/change_states.hpp" #ifndef TAO_PEGTL_CHANGE_STATES_HPP #define TAO_PEGTL_CHANGE_STATES_HPP #include <tuple> #include <utility> namespace TAO_PEGTL_NAMESPACE { template< typename... NewStates > struct change_states : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, std::size_t... Ns, typename Input, typename... States > [[nodiscard]] static bool match( std::index_sequence< Ns... > /*unused*/, Input& in, States&&... st ) { auto t = std::tie( st... ); if( TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, Control >( in, std::get< Ns >( t )... ) ) { if constexpr( A == apply_mode::action ) { Action< Rule >::success( static_cast< const Input& >( in ), st... ); } return true; } return false; } template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return match< Rule, A, M, Action, Control >( std::index_sequence_for< NewStates... >(), in, NewStates()..., st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 40 "tao/pegtl.hpp" #line 1 "tao/pegtl/disable_action.hpp" #line 1 "tao/pegtl/disable_action.hpp" #ifndef TAO_PEGTL_DISABLE_ACTION_HPP #define TAO_PEGTL_DISABLE_ACTION_HPP namespace TAO_PEGTL_NAMESPACE { struct disable_action : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return TAO_PEGTL_NAMESPACE::match< Rule, apply_mode::nothing, M, Action, Control >( in, st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 42 "tao/pegtl.hpp" #line 1 "tao/pegtl/enable_action.hpp" #line 1 "tao/pegtl/enable_action.hpp" #ifndef TAO_PEGTL_ENABLE_ACTION_HPP #define TAO_PEGTL_ENABLE_ACTION_HPP namespace TAO_PEGTL_NAMESPACE { struct enable_action : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return TAO_PEGTL_NAMESPACE::match< Rule, apply_mode::action, M, Action, Control >( in, st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 43 "tao/pegtl.hpp" #line 1 "tao/pegtl/discard_input.hpp" #line 1 "tao/pegtl/discard_input.hpp" #ifndef TAO_PEGTL_DISCARD_INPUT_HPP #define TAO_PEGTL_DISCARD_INPUT_HPP namespace TAO_PEGTL_NAMESPACE { struct discard_input : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { const bool result = TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, Control >( in, st... ); in.discard(); return result; } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 45 "tao/pegtl.hpp" #line 1 "tao/pegtl/discard_input_on_failure.hpp" #line 1 "tao/pegtl/discard_input_on_failure.hpp" #ifndef TAO_PEGTL_DISCARD_INPUT_ON_FAILURE_HPP #define TAO_PEGTL_DISCARD_INPUT_ON_FAILURE_HPP namespace TAO_PEGTL_NAMESPACE { struct discard_input_on_failure : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { const bool result = TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, Control >( in, st... ); if( !result ) { in.discard(); } return result; } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 46 "tao/pegtl.hpp" #line 1 "tao/pegtl/discard_input_on_success.hpp" #line 1 "tao/pegtl/discard_input_on_success.hpp" #ifndef TAO_PEGTL_DISCARD_INPUT_ON_SUCCESS_HPP #define TAO_PEGTL_DISCARD_INPUT_ON_SUCCESS_HPP namespace TAO_PEGTL_NAMESPACE { struct discard_input_on_success : maybe_nothing { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { const bool result = TAO_PEGTL_NAMESPACE::match< Rule, A, M, Action, Control >( in, st... ); if( result ) { in.discard(); } return result; } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 47 "tao/pegtl.hpp" // The following are not included by // default because they include <iostream>. // #include "pegtl/analyze.hpp" #endif #line 2 "amalgamated.hpp" #line 1 "tao/pegtl/analyze.hpp" #line 1 "tao/pegtl/analyze.hpp" #ifndef TAO_PEGTL_ANALYZE_HPP #define TAO_PEGTL_ANALYZE_HPP #line 1 "tao/pegtl/analysis/analyze_cycles.hpp" #line 1 "tao/pegtl/analysis/analyze_cycles.hpp" #ifndef TAO_PEGTL_ANALYSIS_ANALYZE_CYCLES_HPP #define TAO_PEGTL_ANALYSIS_ANALYZE_CYCLES_HPP #include <cassert> #include <map> #include <set> #include <stdexcept> #include <string_view> #include <iostream> #include <utility> #line 1 "tao/pegtl/analysis/insert_guard.hpp" #line 1 "tao/pegtl/analysis/insert_guard.hpp" #ifndef TAO_PEGTL_ANALYSIS_INSERT_GUARD_HPP #define TAO_PEGTL_ANALYSIS_INSERT_GUARD_HPP #include <utility> namespace TAO_PEGTL_NAMESPACE::analysis { template< typename C > class insert_guard { public: insert_guard( C& container, const typename C::value_type& value ) : m_i( container.insert( value ) ), m_c( container ) { } insert_guard( const insert_guard& ) = delete; insert_guard( insert_guard&& ) = delete; ~insert_guard() { if( m_i.second ) { m_c.erase( m_i.first ); } } void operator=( const insert_guard& ) = delete; void operator=( insert_guard&& ) = delete; explicit operator bool() const noexcept { return m_i.second; } private: const std::pair< typename C::iterator, bool > m_i; C& m_c; }; template< typename C > insert_guard( C&, const typename C::value_type& )->insert_guard< C >; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif #line 21 "tao/pegtl/analysis/analyze_cycles.hpp" namespace TAO_PEGTL_NAMESPACE::analysis { struct analyze_cycles_impl { protected: explicit analyze_cycles_impl( const bool verbose ) noexcept : m_verbose( verbose ), m_problems( 0 ) { } const bool m_verbose; unsigned m_problems; grammar_info m_info; std::set< std::string_view > m_stack; std::map< std::string_view, bool > m_cache; std::map< std::string_view, bool > m_results; [[nodiscard]] std::map< std::string_view, rule_info >::const_iterator find( const std::string_view name ) const noexcept { const auto iter = m_info.map.find( name ); assert( iter != m_info.map.end() ); return iter; } [[nodiscard]] bool work( const std::map< std::string_view, rule_info >::const_iterator& start, const bool accum ) { const auto j = m_cache.find( start->first ); if( j != m_cache.end() ) { return j->second; } if( const auto g = insert_guard( m_stack, start->first ) ) { switch( start->second.type ) { case rule_type::any: { bool a = false; for( const auto& r : start->second.rules ) { a = a || work( find( r ), accum || a ); } return m_cache[ start->first ] = true; } case rule_type::opt: { bool a = false; for( const auto& r : start->second.rules ) { a = a || work( find( r ), accum || a ); } return m_cache[ start->first ] = false; } case rule_type::seq: { bool a = false; for( const auto& r : start->second.rules ) { a = a || work( find( r ), accum || a ); } return m_cache[ start->first ] = a; } case rule_type::sor: { bool a = true; for( const auto& r : start->second.rules ) { a = a && work( find( r ), accum ); } return m_cache[ start->first ] = a; } } throw std::logic_error( "code should be unreachable: invalid rule_type value" ); // LCOV_EXCL_LINE } if( !accum ) { ++m_problems; if( m_verbose ) { std::cout << "problem: cycle without progress detected at rule class " << start->first << std::endl; // LCOV_EXCL_LINE } } return m_cache[ start->first ] = accum; } }; template< typename Grammar > struct analyze_cycles : private analyze_cycles_impl { explicit analyze_cycles( const bool verbose ) : analyze_cycles_impl( verbose ) { Grammar::analyze_t::template insert< Grammar >( m_info ); } [[nodiscard]] std::size_t problems() { for( auto i = m_info.map.begin(); i != m_info.map.end(); ++i ) { m_results[ i->first ] = work( i, false ); m_cache.clear(); } return m_problems; } template< typename Rule > [[nodiscard]] bool consumes() const noexcept { const auto i = m_results.find( internal::demangle< Rule >() ); assert( i != m_results.end() ); return i->second; } }; } // namespace TAO_PEGTL_NAMESPACE::analysis #endif #line 10 "tao/pegtl/analyze.hpp" namespace TAO_PEGTL_NAMESPACE { template< typename Rule > [[nodiscard]] std::size_t analyze( const bool verbose = true ) { return analysis::analyze_cycles< Rule >( verbose ).problems(); } } // namespace TAO_PEGTL_NAMESPACE #endif #line 3 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/abnf.hpp" #line 1 "tao/pegtl/contrib/abnf.hpp" #ifndef TAO_PEGTL_CONTRIB_ABNF_HPP #define TAO_PEGTL_CONTRIB_ABNF_HPP namespace TAO_PEGTL_NAMESPACE::abnf { // Core ABNF rules according to RFC 5234, Appendix B // clang-format off struct ALPHA : internal::ranges< internal::peek_char, 'a', 'z', 'A', 'Z' > {}; struct BIT : internal::one< internal::result_on_found::success, internal::peek_char, '0', '1' > {}; struct CHAR : internal::range< internal::result_on_found::success, internal::peek_char, char( 1 ), char( 127 ) > {}; struct CR : internal::one< internal::result_on_found::success, internal::peek_char, '\r' > {}; struct CRLF : internal::string< '\r', '\n' > {}; struct CTL : internal::ranges< internal::peek_char, char( 0 ), char( 31 ), char( 127 ) > {}; struct DIGIT : internal::range< internal::result_on_found::success, internal::peek_char, '0', '9' > {}; struct DQUOTE : internal::one< internal::result_on_found::success, internal::peek_char, '"' > {}; struct HEXDIG : internal::ranges< internal::peek_char, '0', '9', 'a', 'f', 'A', 'F' > {}; struct HTAB : internal::one< internal::result_on_found::success, internal::peek_char, '\t' > {}; struct LF : internal::one< internal::result_on_found::success, internal::peek_char, '\n' > {}; struct LWSP : internal::star< internal::sor< internal::string< '\r', '\n' >, internal::one< internal::result_on_found::success, internal::peek_char, ' ', '\t' > >, internal::one< internal::result_on_found::success, internal::peek_char, ' ', '\t' > > {}; struct OCTET : internal::any< internal::peek_char > {}; struct SP : internal::one< internal::result_on_found::success, internal::peek_char, ' ' > {}; struct VCHAR : internal::range< internal::result_on_found::success, internal::peek_char, char( 33 ), char( 126 ) > {}; struct WSP : internal::one< internal::result_on_found::success, internal::peek_char, ' ', '\t' > {}; // clang-format on } // namespace TAO_PEGTL_NAMESPACE::abnf #endif #line 4 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/alphabet.hpp" #line 1 "tao/pegtl/contrib/alphabet.hpp" #ifndef TAO_PEGTL_CONTRIB_ALPHABET_HPP #define TAO_PEGTL_CONTRIB_ALPHABET_HPP namespace TAO_PEGTL_NAMESPACE::alphabet { static const int a = 'a'; static const int b = 'b'; static const int c = 'c'; static const int d = 'd'; static const int e = 'e'; static const int f = 'f'; static const int g = 'g'; static const int h = 'h'; static const int i = 'i'; static const int j = 'j'; static const int k = 'k'; static const int l = 'l'; static const int m = 'm'; static const int n = 'n'; static const int o = 'o'; static const int p = 'p'; static const int q = 'q'; static const int r = 'r'; static const int s = 's'; static const int t = 't'; static const int u = 'u'; static const int v = 'v'; static const int w = 'w'; static const int x = 'x'; static const int y = 'y'; static const int z = 'z'; static const int A = 'A'; // NOLINT(readability-identifier-naming) static const int B = 'B'; // NOLINT(readability-identifier-naming) static const int C = 'C'; // NOLINT(readability-identifier-naming) static const int D = 'D'; // NOLINT(readability-identifier-naming) static const int E = 'E'; // NOLINT(readability-identifier-naming) static const int F = 'F'; // NOLINT(readability-identifier-naming) static const int G = 'G'; // NOLINT(readability-identifier-naming) static const int H = 'H'; // NOLINT(readability-identifier-naming) static const int I = 'I'; // NOLINT(readability-identifier-naming) static const int J = 'J'; // NOLINT(readability-identifier-naming) static const int K = 'K'; // NOLINT(readability-identifier-naming) static const int L = 'L'; // NOLINT(readability-identifier-naming) static const int M = 'M'; // NOLINT(readability-identifier-naming) static const int N = 'N'; // NOLINT(readability-identifier-naming) static const int O = 'O'; // NOLINT(readability-identifier-naming) static const int P = 'P'; // NOLINT(readability-identifier-naming) static const int Q = 'Q'; // NOLINT(readability-identifier-naming) static const int R = 'R'; // NOLINT(readability-identifier-naming) static const int S = 'S'; // NOLINT(readability-identifier-naming) static const int T = 'T'; // NOLINT(readability-identifier-naming) static const int U = 'U'; // NOLINT(readability-identifier-naming) static const int V = 'V'; // NOLINT(readability-identifier-naming) static const int W = 'W'; // NOLINT(readability-identifier-naming) static const int X = 'X'; // NOLINT(readability-identifier-naming) static const int Y = 'Y'; // NOLINT(readability-identifier-naming) static const int Z = 'Z'; // NOLINT(readability-identifier-naming) } // namespace TAO_PEGTL_NAMESPACE::alphabet #endif #line 5 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/counter.hpp" #line 1 "tao/pegtl/contrib/counter.hpp" #ifndef TAO_PEGTL_CONTRIB_COUNTER_HPP #define TAO_PEGTL_CONTRIB_COUNTER_HPP #include <map> #include <string_view> namespace TAO_PEGTL_NAMESPACE { struct counter_data { unsigned start = 0; unsigned success = 0; unsigned failure = 0; }; struct counter_state { std::map< std::string_view, counter_data > counts; }; template< typename Rule > struct counter : normal< Rule > { template< typename Input > static void start( const Input& /*unused*/, counter_state& ts ) { ++ts.counts[ internal::demangle< Rule >() ].start; } template< typename Input > static void success( const Input& /*unused*/, counter_state& ts ) { ++ts.counts[ internal::demangle< Rule >() ].success; } template< typename Input > static void failure( const Input& /*unused*/, counter_state& ts ) { ++ts.counts[ internal::demangle< Rule >() ].failure; } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 6 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/http.hpp" #line 1 "tao/pegtl/contrib/http.hpp" #ifndef TAO_PEGTL_CONTRIB_HTTP_HPP #define TAO_PEGTL_CONTRIB_HTTP_HPP #line 14 "tao/pegtl/contrib/http.hpp" #line 1 "tao/pegtl/contrib/remove_first_state.hpp" #line 1 "tao/pegtl/contrib/remove_first_state.hpp" #ifndef TAO_PEGTL_CONTRIB_REMOVE_FIRST_STATE_HPP #define TAO_PEGTL_CONTRIB_REMOVE_FIRST_STATE_HPP namespace TAO_PEGTL_NAMESPACE { // NOTE: The naming of the following classes might still change. template< typename Rule, template< typename... > class Control > struct remove_first_state_after_match : Control< Rule > { template< typename Input, typename State, typename... States > static void start( const Input& in, State&& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::start( in, st... ) ) ) { Control< Rule >::start( in, st... ); } template< typename Input, typename State, typename... States > static void success( const Input& in, State&& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::success( in, st... ) ) ) { Control< Rule >::success( in, st... ); } template< typename Input, typename State, typename... States > static void failure( const Input& in, State&& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) ) { Control< Rule >::failure( in, st... ); } template< typename Input, typename State, typename... States > static void raise( const Input& in, State&& /*unused*/, States&&... st ) { Control< Rule >::raise( in, st... ); } template< template< typename... > class Action, typename Iterator, typename Input, typename State, typename... States > static auto apply( const Iterator& begin, const Input& in, State&& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::template apply< Action >( begin, in, st... ) ) ) -> decltype( Control< Rule >::template apply< Action >( begin, in, st... ) ) { return Control< Rule >::template apply< Action >( begin, in, st... ); } template< template< typename... > class Action, typename Input, typename State, typename... States > static auto apply0( const Input& in, State&& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::template apply0< Action >( in, st... ) ) ) -> decltype( Control< Rule >::template apply0< Action >( in, st... ) ) { return Control< Rule >::template apply0< Action >( in, st... ); } }; template< typename Rule, template< typename... > class Control > struct remove_self_and_first_state : Control< Rule > { template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class, typename Input, typename State, typename... States > [[nodiscard]] static bool match( Input& in, State&& /*unused*/, States&&... st ) { return Control< Rule >::template match< A, M, Action, Control >( in, st... ); } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 15 "tao/pegtl/contrib/http.hpp" #line 1 "tao/pegtl/contrib/uri.hpp" #line 1 "tao/pegtl/contrib/uri.hpp" #ifndef TAO_PEGTL_CONTRIB_URI_HPP #define TAO_PEGTL_CONTRIB_URI_HPP #include <cstdint> #line 1 "tao/pegtl/contrib/integer.hpp" #line 1 "tao/pegtl/contrib/integer.hpp" #ifndef TAO_PEGTL_CONTRIB_INTEGER_HPP #define TAO_PEGTL_CONTRIB_INTEGER_HPP #include <cstdint> #include <cstdlib> #include <type_traits> namespace TAO_PEGTL_NAMESPACE::integer { namespace internal { struct unsigned_rule_old : plus< digit > { // Pre-3.0 version of this rule. }; struct unsigned_rule_new : if_then_else< one< '0' >, not_at< digit >, plus< digit > > { // New version that does not allow leading zeros. }; struct signed_rule_old : seq< opt< one< '-', '+' > >, plus< digit > > { // Pre-3.0 version of this rule. }; struct signed_rule_new : seq< opt< one< '-', '+' > >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > > { // New version that does not allow leading zeros. }; struct signed_rule_bis : seq< opt< one< '-' > >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > > { }; struct signed_rule_ter : seq< one< '-', '+' >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > > { }; [[nodiscard]] constexpr bool is_digit( const char c ) noexcept { // We don't use std::isdigit() because it might // return true for other values on MS platforms. return ( '0' <= c ) && ( c <= '9' ); } template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() > [[nodiscard]] constexpr bool accumulate_digit( Integer& result, const char digit ) noexcept { // Assumes that digit is a digit as per is_digit(); returns false on overflow. static_assert( std::is_integral_v< Integer > ); constexpr Integer cutoff = Maximum / 10; constexpr Integer cutlim = Maximum % 10; const Integer c = digit - '0'; if( ( result > cutoff ) || ( ( result == cutoff ) && ( c > cutlim ) ) ) { return false; } result *= 10; result += c; return true; } template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() > [[nodiscard]] constexpr bool accumulate_digits( Integer& result, const std::string_view input ) noexcept { // Assumes input is a non-empty sequence of digits; returns false on overflow. for( char c : input ) { if( !accumulate_digit< Integer, Maximum >( result, c ) ) { return false; } } return true; } template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() > [[nodiscard]] constexpr bool convert_positive( Integer& result, const std::string_view input ) noexcept { // Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow. static_assert( std::is_integral_v< Integer > ); return accumulate_digits< Integer, Maximum >( result, input ); } template< typename Signed > [[nodiscard]] constexpr bool convert_negative( Signed& result, const std::string_view input ) noexcept { // Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow. static_assert( std::is_signed_v< Signed > ); using Unsigned = std::make_unsigned_t< Signed >; constexpr Unsigned maximum = static_cast< Unsigned >( ( std::numeric_limits< Signed >::max )() ) + 1; Unsigned temporary = 0; if( accumulate_digits< Unsigned, maximum >( temporary, input ) ) { result = static_cast< Signed >( ~temporary ) + 1; return true; } return false; } template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() > [[nodiscard]] constexpr bool convert_unsigned( Unsigned& result, const std::string_view input ) noexcept { // Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow. static_assert( std::is_unsigned_v< Unsigned > ); return accumulate_digits< Unsigned, Maximum >( result, input ); } template< typename Signed > [[nodiscard]] constexpr bool convert_signed( Signed& result, const std::string_view input ) noexcept { // Assumes result == 0 and that input is an optional sign followed by a non-empty sequence of digits; returns false on overflow. static_assert( std::is_signed_v< Signed > ); if( input[ 0 ] == '-' ) { return convert_negative< Signed >( result, std::string_view( input.data() + 1, input.size() - 1 ) ); } const auto offset = unsigned( input[ 0 ] == '+' ); return convert_positive< Signed >( result, std::string_view( input.data() + offset, input.size() - offset ) ); } template< typename Input > [[nodiscard]] bool match_unsigned( Input& in ) noexcept( noexcept( in.empty() ) ) { if( !in.empty() ) { const char c = in.peek_char(); if( is_digit( c ) ) { in.bump_in_this_line(); if( c == '0' ) { return in.empty() || ( !is_digit( in.peek_char() ) ); // TODO: Throw exception on digit? } while( ( !in.empty() ) && is_digit( in.peek_char() ) ) { in.bump_in_this_line(); } return true; } } return false; } template< typename Input, typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() > [[nodiscard]] bool match_and_convert_unsigned_with_maximum( Input& in, Unsigned& st ) { // Assumes st == 0. if( !in.empty() ) { char c = in.peek_char(); if( is_digit( c ) ) { if( c == '0' ) { in.bump_in_this_line(); return in.empty() || ( !is_digit( in.peek_char() ) ); // TODO: Throw exception on digit? } do { if( !accumulate_digit< Unsigned, Maximum >( st, c ) ) { throw parse_error( "integer overflow", in ); // Consistent with "as if" an action was doing the conversion. } in.bump_in_this_line(); } while( ( !in.empty() ) && is_digit( c = in.peek_char() ) ); return true; } } return false; } } // namespace internal struct unsigned_action { // Assumes that 'in' contains a non-empty sequence of ASCII digits. template< typename Input, typename Unsigned > static auto apply( const Input& in, Unsigned& st ) -> std::enable_if_t< std::is_unsigned_v< Unsigned >, void > { // This function "only" offers basic exception safety. st = 0; if( !internal::convert_unsigned( st, in.string_view() ) ) { throw parse_error( "unsigned integer overflow", in ); } } template< typename Input, typename State > static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void > { apply( in, st.converted ); // Compatibility for pre-3.0 behaviour. } template< typename Input, typename Unsigned, typename... Ts > static auto apply( const Input& in, std::vector< Unsigned, Ts... >& st ) -> std::enable_if_t< std::is_unsigned_v< Unsigned >, void > { Unsigned u = 0; apply( in, u ); st.emplace_back( u ); } }; struct unsigned_rule { using analyze_t = internal::unsigned_rule_new::analyze_t; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.empty() ) ) { return internal::match_unsigned( in ); // Does not check for any overflow. } }; struct unsigned_rule_with_action { using analyze_t = internal::unsigned_rule_new::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) ) -> std::enable_if_t< A == apply_mode::nothing, bool > { return internal::match_unsigned( in ); // Does not check for any overflow. } template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename Unsigned > [[nodiscard]] static auto match( Input& in, Unsigned& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_unsigned_v< Unsigned >, bool > { // This function "only" offers basic exception safety. st = 0; return internal::match_and_convert_unsigned_with_maximum( in, st ); // Throws on overflow. } // TODO: Overload for st.converted? // TODO: Overload for std::vector< Unsigned >? }; template< typename Unsigned, Unsigned Maximum > struct maximum_action { // Assumes that 'in' contains a non-empty sequence of ASCII digits. static_assert( std::is_unsigned_v< Unsigned > ); template< typename Input, typename Unsigned2 > static auto apply( const Input& in, Unsigned2& st ) -> std::enable_if_t< std::is_same_v< Unsigned, Unsigned2 >, void > { // This function "only" offers basic exception safety. st = 0; if( !internal::convert_unsigned< Unsigned, Maximum >( st, in.string_view() ) ) { throw parse_error( "unsigned integer overflow", in ); } } template< typename Input, typename State > static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void > { apply( in, st.converted ); // Compatibility for pre-3.0 behaviour. } template< typename Input, typename Unsigned2, typename... Ts > static auto apply( const Input& in, std::vector< Unsigned2, Ts... >& st ) -> std::enable_if_t< std::is_same_v< Unsigned, Unsigned2 >, void > { Unsigned u = 0; apply( in, u ); st.emplace_back( u ); } }; template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() > struct maximum_rule { static_assert( std::is_unsigned_v< Unsigned > ); using analyze_t = internal::unsigned_rule_new::analyze_t; template< typename Input > [[nodiscard]] static bool match( Input& in ) { Unsigned st = 0; return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow. } }; template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() > struct maximum_rule_with_action { static_assert( std::is_unsigned_v< Unsigned > ); using analyze_t = internal::unsigned_rule_new::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) -> std::enable_if_t< A == apply_mode::nothing, bool > { Unsigned st = 0; return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow. } template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename Unsigned2 > [[nodiscard]] static auto match( Input& in, Unsigned2& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_same_v< Unsigned, Unsigned2 >, bool > { // This function "only" offers basic exception safety. st = 0; return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow. } // TODO: Overload for st.converted? // TODO: Overload for std::vector< Unsigned >? }; struct signed_action { // Assumes that 'in' contains a non-empty sequence of ASCII digits, // with optional leading sign; with sign, in.size() must be >= 2. template< typename Input, typename Signed > static auto apply( const Input& in, Signed& st ) -> std::enable_if_t< std::is_signed_v< Signed >, void > { // This function "only" offers basic exception safety. st = 0; if( !internal::convert_signed( st, in.string_view() ) ) { throw parse_error( "signed integer overflow", in ); } } template< typename Input, typename State > static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void > { apply( in, st.converted ); // Compatibility for pre-3.0 behaviour. } template< typename Input, typename Signed, typename... Ts > static auto apply( const Input& in, std::vector< Signed, Ts... >& st ) -> std::enable_if_t< std::is_signed_v< Signed >, void > { Signed s = 0; apply( in, s ); st.emplace_back( s ); } }; struct signed_rule { using analyze_t = internal::signed_rule_new::analyze_t; template< typename Input > [[nodiscard]] static bool match( Input& in ) noexcept( noexcept( in.empty() ) ) { return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new >( in ); // Does not check for any overflow. } }; namespace internal { template< typename Rule > struct signed_action_action : nothing< Rule > { }; template<> struct signed_action_action< signed_rule_new > : signed_action { }; } // namespace internal struct signed_rule_with_action { using analyze_t = internal::signed_rule_new::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) ) -> std::enable_if_t< A == apply_mode::nothing, bool > { return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new >( in ); // Does not check for any overflow. } template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename Signed > [[nodiscard]] static auto match( Input& in, Signed& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_signed_v< Signed >, bool > { return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new, internal::signed_action_action >( in, st ); // Throws on overflow. } // TODO: Overload for st.converted? // TODO: Overload for std::vector< Signed >? }; } // namespace TAO_PEGTL_NAMESPACE::integer #endif #line 16 "tao/pegtl/contrib/uri.hpp" namespace TAO_PEGTL_NAMESPACE::uri { // URI grammar according to RFC 3986. // This grammar is a direct PEG translation of the original URI grammar. // It should be considered experimental -- in case of any issues, in particular // missing rules for attached actions, please contact the developers. // Note that this grammar has multiple top-level rules. using dot = one< '.' >; using colon = one< ':' >; // clang-format off struct dec_octet : integer::maximum_rule< std::uint8_t > {}; struct IPv4address : seq< dec_octet, dot, dec_octet, dot, dec_octet, dot, dec_octet > {}; struct h16 : rep_min_max< 1, 4, abnf::HEXDIG > {}; struct ls32 : sor< seq< h16, colon, h16 >, IPv4address > {}; struct dcolon : two< ':' > {}; struct IPv6address : sor< seq< rep< 6, h16, colon >, ls32 >, seq< dcolon, rep< 5, h16, colon >, ls32 >, seq< opt< h16 >, dcolon, rep< 4, h16, colon >, ls32 >, seq< opt< h16, opt< colon, h16 > >, dcolon, rep< 3, h16, colon >, ls32 >, seq< opt< h16, rep_opt< 2, colon, h16 > >, dcolon, rep< 2, h16, colon >, ls32 >, seq< opt< h16, rep_opt< 3, colon, h16 > >, dcolon, h16, colon, ls32 >, seq< opt< h16, rep_opt< 4, colon, h16 > >, dcolon, ls32 >, seq< opt< h16, rep_opt< 5, colon, h16 > >, dcolon, h16 >, seq< opt< h16, rep_opt< 6, colon, h16 > >, dcolon > > {}; struct gen_delims : one< ':', '/', '?', '#', '[', ']', '@' > {}; struct sub_delims : one< '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=' > {}; struct unreserved : sor< abnf::ALPHA, abnf::DIGIT, one< '-', '.', '_', '~' > > {}; struct reserved : sor< gen_delims, sub_delims > {}; struct IPvFuture : if_must< one< 'v', 'V' >, plus< abnf::HEXDIG >, dot, plus< sor< unreserved, sub_delims, colon > > > {}; struct IP_literal : if_must< one< '[' >, sor< IPvFuture, IPv6address >, one< ']' > > {}; struct pct_encoded : if_must< one< '%' >, abnf::HEXDIG, abnf::HEXDIG > {}; struct pchar : sor< unreserved, pct_encoded, sub_delims, one< ':', '@' > > {}; struct query : star< sor< pchar, one< '/', '?' > > > {}; struct fragment : star< sor< pchar, one< '/', '?' > > > {}; struct segment : star< pchar > {}; struct segment_nz : plus< pchar > {}; struct segment_nz_nc : plus< sor< unreserved, pct_encoded, sub_delims, one< '@' > > > {}; // non-zero-length segment without any colon ":" struct path_abempty : star< one< '/' >, segment > {}; struct path_absolute : seq< one< '/' >, opt< segment_nz, star< one< '/' >, segment > > > {}; struct path_noscheme : seq< segment_nz_nc, star< one< '/' >, segment > > {}; struct path_rootless : seq< segment_nz, star< one< '/' >, segment > > {}; struct path_empty : success {}; struct path : sor< path_noscheme, // begins with a non-colon segment path_rootless, // begins with a segment path_absolute, // begins with "/" but not "//" path_abempty > {}; // begins with "/" or is empty struct reg_name : star< sor< unreserved, pct_encoded, sub_delims > > {}; struct port : star< abnf::DIGIT > {}; struct host : sor< IP_literal, IPv4address, reg_name > {}; struct userinfo : star< sor< unreserved, pct_encoded, sub_delims, colon > > {}; struct opt_userinfo : opt< userinfo, one< '@' > > {}; struct authority : seq< opt_userinfo, host, opt< colon, port > > {}; struct scheme : seq< abnf::ALPHA, star< sor< abnf::ALPHA, abnf::DIGIT, one< '+', '-', '.' > > > > {}; using dslash = two< '/' >; using opt_query = opt_must< one< '?' >, query >; using opt_fragment = opt_must< one< '#' >, fragment >; struct hier_part : sor< if_must< dslash, authority, path_abempty >, path_rootless, path_absolute, path_empty > {}; struct relative_part : sor< if_must< dslash, authority, path_abempty >, path_noscheme, path_absolute, path_empty > {}; struct relative_ref : seq< relative_part, opt_query, opt_fragment > {}; struct URI : seq< scheme, one< ':' >, hier_part, opt_query, opt_fragment > {}; struct URI_reference : sor< URI, relative_ref > {}; struct absolute_URI : seq< scheme, one< ':' >, hier_part, opt_query > {}; // clang-format on } // namespace TAO_PEGTL_NAMESPACE::uri #endif #line 16 "tao/pegtl/contrib/http.hpp" namespace TAO_PEGTL_NAMESPACE::http { // HTTP 1.1 grammar according to RFC 7230. // This grammar is a direct PEG translation of the original HTTP grammar. // It should be considered experimental -- in case of any issues, in particular // missing rules for attached actions, please contact the developers. using OWS = star< abnf::WSP >; // optional whitespace using RWS = plus< abnf::WSP >; // required whitespace using BWS = OWS; // "bad" whitespace using obs_text = not_range< 0x00, 0x7F >; using obs_fold = seq< abnf::CRLF, plus< abnf::WSP > >; // clang-format off struct tchar : sor< abnf::ALPHA, abnf::DIGIT, one< '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~' > > {}; struct token : plus< tchar > {}; struct field_name : token {}; struct field_vchar : sor< abnf::VCHAR, obs_text > {}; struct field_content : list< field_vchar, plus< abnf::WSP > > {}; struct field_value : star< sor< field_content, obs_fold > > {}; struct header_field : seq< field_name, one< ':' >, OWS, field_value, OWS > {}; struct method : token {}; struct absolute_path : plus< one< '/' >, uri::segment > {}; struct origin_form : seq< absolute_path, uri::opt_query > {}; struct absolute_form : uri::absolute_URI {}; struct authority_form : uri::authority {}; struct asterisk_form : one< '*' > {}; struct request_target : sor< origin_form, absolute_form, authority_form, asterisk_form > {}; struct status_code : rep< 3, abnf::DIGIT > {}; struct reason_phrase : star< sor< abnf::VCHAR, obs_text, abnf::WSP > > {}; struct HTTP_version : if_must< string< 'H', 'T', 'T', 'P', '/' >, abnf::DIGIT, one< '.' >, abnf::DIGIT > {}; struct request_line : if_must< method, abnf::SP, request_target, abnf::SP, HTTP_version, abnf::CRLF > {}; struct status_line : if_must< HTTP_version, abnf::SP, status_code, abnf::SP, reason_phrase, abnf::CRLF > {}; struct start_line : sor< status_line, request_line > {}; struct message_body : star< abnf::OCTET > {}; struct HTTP_message : seq< start_line, star< header_field, abnf::CRLF >, abnf::CRLF, opt< message_body > > {}; struct Content_Length : plus< abnf::DIGIT > {}; struct uri_host : uri::host {}; struct port : uri::port {}; struct Host : seq< uri_host, opt< one< ':' >, port > > {}; // PEG are different from CFGs! (this replaces ctext and qdtext) using text = sor< abnf::HTAB, range< 0x20, 0x7E >, obs_text >; struct quoted_pair : if_must< one< '\\' >, sor< abnf::VCHAR, obs_text, abnf::WSP > > {}; struct quoted_string : if_must< abnf::DQUOTE, until< abnf::DQUOTE, sor< quoted_pair, text > > > {}; struct transfer_parameter : seq< token, BWS, one< '=' >, BWS, sor< token, quoted_string > > {}; struct transfer_extension : seq< token, star< OWS, one< ';' >, OWS, transfer_parameter > > {}; struct transfer_coding : sor< istring< 'c', 'h', 'u', 'n', 'k', 'e', 'd' >, istring< 'c', 'o', 'm', 'p', 'r', 'e', 's', 's' >, istring< 'd', 'e', 'f', 'l', 'a', 't', 'e' >, istring< 'g', 'z', 'i', 'p' >, transfer_extension > {}; struct rank : sor< seq< one< '0' >, opt< one< '.' >, rep_opt< 3, abnf::DIGIT > > >, seq< one< '1' >, opt< one< '.' >, rep_opt< 3, one< '0' > > > > > {}; struct t_ranking : seq< OWS, one< ';' >, OWS, one< 'q', 'Q' >, one< '=' >, rank > {}; struct t_codings : sor< istring< 't', 'r', 'a', 'i', 'l', 'e', 'r', 's' >, seq< transfer_coding, opt< t_ranking > > > {}; struct TE : opt< sor< one< ',' >, t_codings >, star< OWS, one< ',' >, opt< OWS, t_codings > > > {}; template< typename T > using make_comma_list = seq< star< one< ',' >, OWS >, T, star< OWS, one< ',' >, opt< OWS, T > > >; struct connection_option : token {}; struct Connection : make_comma_list< connection_option > {}; struct Trailer : make_comma_list< field_name > {}; struct Transfer_Encoding : make_comma_list< transfer_coding > {}; struct protocol_name : token {}; struct protocol_version : token {}; struct protocol : seq< protocol_name, opt< one< '/' >, protocol_version > > {}; struct Upgrade : make_comma_list< protocol > {}; struct pseudonym : token {}; struct received_protocol : seq< opt< protocol_name, one< '/' > >, protocol_version > {}; struct received_by : sor< seq< uri_host, opt< one< ':' >, port > >, pseudonym > {}; struct comment : if_must< one< '(' >, until< one< ')' >, sor< comment, quoted_pair, text > > > {}; struct Via : make_comma_list< seq< received_protocol, RWS, received_by, opt< RWS, comment > > > {}; struct http_URI : if_must< istring< 'h', 't', 't', 'p', ':', '/', '/' >, uri::authority, uri::path_abempty, uri::opt_query, uri::opt_fragment > {}; struct https_URI : if_must< istring< 'h', 't', 't', 'p', 's', ':', '/', '/' >, uri::authority, uri::path_abempty, uri::opt_query, uri::opt_fragment > {}; struct partial_URI : seq< uri::relative_part, uri::opt_query > {}; // clang-format on struct chunk_size { using analyze_t = plus< abnf::HEXDIG >::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, std::size_t& size, States&&... /*unused*/ ) { size = 0; std::size_t i = 0; while( in.size( i + 1 ) >= i + 1 ) { const auto c = in.peek_char( i ); if( ( '0' <= c ) && ( c <= '9' ) ) { size <<= 4; size |= std::size_t( c - '0' ); ++i; continue; } if( ( 'a' <= c ) && ( c <= 'f' ) ) { size <<= 4; size |= std::size_t( c - 'a' + 10 ); ++i; continue; } if( ( 'A' <= c ) && ( c <= 'F' ) ) { size <<= 4; size |= std::size_t( c - 'A' + 10 ); ++i; continue; } break; } in.bump_in_this_line( i ); return i > 0; } }; // clang-format off struct chunk_ext_name : token {}; struct chunk_ext_val : sor< quoted_string, token > {}; struct chunk_ext : star_must< one< ';' >, chunk_ext_name, if_must< one< '=' >, chunk_ext_val > > {}; // clang-format on struct chunk_data { using analyze_t = star< abnf::OCTET >::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, const std::size_t size, States&&... /*unused*/ ) { if( in.size( size ) >= size ) { in.bump( size ); return true; } return false; } }; namespace internal::chunk_helper { template< typename Rule, template< typename... > class Control > struct control : remove_self_and_first_state< Rule, Control > {}; template< template< typename... > class Control > struct control< chunk_size, Control > : remove_first_state_after_match< chunk_size, Control > {}; template< template< typename... > class Control > struct control< chunk_data, Control > : remove_first_state_after_match< chunk_data, Control > {}; template< template< typename... > class Control > struct bind { template< typename Rule > using type = control< Rule, Control >; }; } // namespace internal::chunk_helper struct chunk { using impl = seq< chunk_size, chunk_ext, abnf::CRLF, chunk_data, abnf::CRLF >; using analyze_t = impl::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { std::size_t size{}; return impl::template match< A, M, Action, internal::chunk_helper::bind< Control >::template type >( in, size, st... ); } }; // clang-format off struct last_chunk : seq< plus< one< '0' > >, not_at< digit >, chunk_ext, abnf::CRLF > {}; struct trailer_part : star< header_field, abnf::CRLF > {}; struct chunked_body : seq< until< last_chunk, chunk >, trailer_part, abnf::CRLF > {}; // clang-format on } // namespace TAO_PEGTL_NAMESPACE::http #endif #line 7 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/if_then.hpp" #line 1 "tao/pegtl/contrib/if_then.hpp" #ifndef TAO_PEGTL_CONTRIB_IF_THEN_HPP #define TAO_PEGTL_CONTRIB_IF_THEN_HPP #include <type_traits> #line 16 "tao/pegtl/contrib/if_then.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { template< typename Cond, typename Then > struct if_pair { }; template< typename... Pairs > struct if_then; template< typename Cond, typename Then, typename... Pairs > struct if_then< if_pair< Cond, Then >, Pairs... > : if_then_else< Cond, Then, if_then< Pairs... > > { template< typename ElseCond, typename... Thens > using else_if_then = if_then< if_pair< Cond, Then >, Pairs..., if_pair< ElseCond, seq< Thens... > > >; template< typename... Thens > using else_then = if_then_else< Cond, Then, if_then< Pairs..., if_pair< trivial< true >, seq< Thens... > > > >; }; template<> struct if_then<> : trivial< false > { }; template< typename... Pairs > inline constexpr bool skip_control< if_then< Pairs... > > = true; } // namespace internal template< typename Cond, typename... Thens > using if_then = internal::if_then< internal::if_pair< Cond, internal::seq< Thens... > > >; } // namespace TAO_PEGTL_NAMESPACE #endif #line 8 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/json.hpp" #line 1 "tao/pegtl/contrib/json.hpp" #ifndef TAO_PEGTL_CONTRIB_JSON_HPP #define TAO_PEGTL_CONTRIB_JSON_HPP namespace TAO_PEGTL_NAMESPACE::json { // JSON grammar according to RFC 8259 // clang-format off struct ws : one< ' ', '\t', '\n', '\r' > {}; template< typename R, typename P = ws > struct padr : internal::seq< R, internal::star< P > > {}; struct begin_array : padr< one< '[' > > {}; struct begin_object : padr< one< '{' > > {}; struct end_array : one< ']' > {}; struct end_object : one< '}' > {}; struct name_separator : pad< one< ':' >, ws > {}; struct value_separator : padr< one< ',' > > {}; struct false_ : string< 'f', 'a', 'l', 's', 'e' > {}; // NOLINT(readability-identifier-naming) struct null : string< 'n', 'u', 'l', 'l' > {}; struct true_ : string< 't', 'r', 'u', 'e' > {}; // NOLINT(readability-identifier-naming) struct digits : plus< digit > {}; struct exp : seq< one< 'e', 'E' >, opt< one< '-', '+'> >, must< digits > > {}; struct frac : if_must< one< '.' >, digits > {}; struct int_ : sor< one< '0' >, digits > {}; // NOLINT(readability-identifier-naming) struct number : seq< opt< one< '-' > >, int_, opt< frac >, opt< exp > > {}; struct xdigit : pegtl::xdigit {}; struct unicode : list< seq< one< 'u' >, rep< 4, must< xdigit > > >, one< '\\' > > {}; struct escaped_char : one< '"', '\\', '/', 'b', 'f', 'n', 'r', 't' > {}; struct escaped : sor< escaped_char, unicode > {}; struct unescaped : utf8::range< 0x20, 0x10FFFF > {}; struct char_ : if_then_else< one< '\\' >, must< escaped >, unescaped > {}; // NOLINT(readability-identifier-naming) struct string_content : until< at< one< '"' > >, must< char_ > > {}; struct string : seq< one< '"' >, must< string_content >, any > { using content = string_content; }; struct key_content : until< at< one< '"' > >, must< char_ > > {}; struct key : seq< one< '"' >, must< key_content >, any > { using content = key_content; }; struct value; struct array_element; struct array_content : opt< list_must< array_element, value_separator > > {}; struct array : seq< begin_array, array_content, must< end_array > > { using begin = begin_array; using end = end_array; using element = array_element; using content = array_content; }; struct member : if_must< key, name_separator, value > {}; struct object_content : opt< list_must< member, value_separator > > {}; struct object : seq< begin_object, object_content, must< end_object > > { using begin = begin_object; using end = end_object; using element = member; using content = object_content; }; struct value : padr< sor< string, number, object, array, false_, true_, null > > {}; struct array_element : seq< value > {}; struct text : seq< star< ws >, value > {}; // clang-format on } // namespace TAO_PEGTL_NAMESPACE::json #endif #line 10 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/json_pointer.hpp" #line 1 "tao/pegtl/contrib/json_pointer.hpp" #ifndef TAO_PEGTL_CONTRIB_JSON_POINTER_HPP #define TAO_PEGTL_CONTRIB_JSON_POINTER_HPP namespace TAO_PEGTL_NAMESPACE::json_pointer { // JSON pointer grammar according to RFC 6901 // clang-format off struct unescaped : utf8::ranges< 0x0, 0x2E, 0x30, 0x7D, 0x7F, 0x10FFFF > {}; struct escaped : seq< one< '~' >, one< '0', '1' > > {}; struct reference_token : star< sor< unescaped, escaped > > {}; struct json_pointer : star< one< '/' >, reference_token > {}; // clang-format on // relative JSON pointer, see ... // clang-format off struct non_negative_integer : sor< one< '0' >, plus< digit > > {}; struct relative_json_pointer : seq< non_negative_integer, sor< one< '#' >, json_pointer > > {}; // clang-format on } // namespace TAO_PEGTL_NAMESPACE::json_pointer #endif #line 11 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/parse_tree.hpp" #line 1 "tao/pegtl/contrib/parse_tree.hpp" #ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_HPP #define TAO_PEGTL_CONTRIB_PARSE_TREE_HPP #include <cassert> #include <memory> #include <string> #include <string_view> #include <tuple> #include <type_traits> #include <typeindex> #include <utility> #include <vector> #line 28 "tao/pegtl/contrib/parse_tree.hpp" namespace TAO_PEGTL_NAMESPACE::parse_tree { template< typename T > struct basic_node { using node_t = T; using children_t = std::vector< std::unique_ptr< node_t > >; children_t children; std::string_view type; std::string source; TAO_PEGTL_NAMESPACE::internal::iterator m_begin; TAO_PEGTL_NAMESPACE::internal::iterator m_end; // each node will be default constructed basic_node() = default; // no copy/move is necessary // (nodes are always owned/handled by a std::unique_ptr) basic_node( const basic_node& ) = delete; basic_node( basic_node&& ) = delete; ~basic_node() = default; // no assignment either basic_node& operator=( const basic_node& ) = delete; basic_node& operator=( basic_node&& ) = delete; [[nodiscard]] bool is_root() const noexcept { return type.empty(); } template< typename U > [[nodiscard]] bool is_type() const noexcept { return type == TAO_PEGTL_NAMESPACE::internal::demangle< U >(); } template< typename U > void set_type() noexcept { type = TAO_PEGTL_NAMESPACE::internal::demangle< U >(); } [[nodiscard]] position begin() const { return position( m_begin, source ); } [[nodiscard]] position end() const { return position( m_end, source ); } [[nodiscard]] bool has_content() const noexcept { return m_end.data != nullptr; } [[nodiscard]] std::string_view string_view() const noexcept { assert( has_content() ); return std::string_view( m_begin.data, m_end.data - m_begin.data ); } [[nodiscard]] std::string string() const { assert( has_content() ); return std::string( m_begin.data, m_end.data ); } template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf > [[nodiscard]] memory_input< P, Eol > as_memory_input() const { assert( has_content() ); return { m_begin.data, m_end.data, source, m_begin.byte, m_begin.line, m_begin.byte_in_line }; } template< typename... States > void remove_content( States&&... /*unused*/ ) noexcept { m_end.reset(); } // all non-root nodes are initialized by calling this method template< typename Rule, typename Input, typename... States > void start( const Input& in, States&&... /*unused*/ ) { set_type< Rule >(); source = in.source(); m_begin = TAO_PEGTL_NAMESPACE::internal::iterator( in.iterator() ); } // if parsing of the rule succeeded, this method is called template< typename Rule, typename Input, typename... States > void success( const Input& in, States&&... /*unused*/ ) noexcept { m_end = TAO_PEGTL_NAMESPACE::internal::iterator( in.iterator() ); } // if parsing of the rule failed, this method is called template< typename Rule, typename Input, typename... States > void failure( const Input& /*unused*/, States&&... /*unused*/ ) noexcept { } // if parsing succeeded and the (optional) transform call // did not discard the node, it is appended to its parent. // note that "child" is the node whose Rule just succeeded // and "*this" is the parent where the node should be appended. template< typename... States > void emplace_back( std::unique_ptr< node_t >&& child, States&&... /*unused*/ ) { assert( child ); children.emplace_back( std::move( child ) ); } }; struct node : basic_node< node > { }; namespace internal { template< typename Node > struct state { std::vector< std::unique_ptr< Node > > stack; state() { emplace_back(); } void emplace_back() { stack.emplace_back( std::make_unique< Node >() ); } [[nodiscard]] std::unique_ptr< Node >& back() noexcept { assert( !stack.empty() ); return stack.back(); } void pop_back() noexcept { assert( !stack.empty() ); return stack.pop_back(); } }; template< typename Selector, typename... Parameters > void transform( Parameters&&... /*unused*/ ) noexcept { } template< typename Selector, typename Input, typename Node, typename... States > auto transform( const Input& in, std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( in, n, st... ) ) ) -> decltype( Selector::transform( in, n, st... ), void() ) { Selector::transform( in, n, st... ); } template< typename Selector, typename Input, typename Node, typename... States > auto transform( const Input& /*unused*/, std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( n, st... ) ) ) -> decltype( Selector::transform( n, st... ), void() ) { Selector::transform( n, st... ); } template< unsigned Level, typename Analyse, template< typename... > class Selector > struct is_leaf : std::false_type { }; template< analysis::rule_type Type, template< typename... > class Selector > struct is_leaf< 0, analysis::generic< Type >, Selector > : std::true_type { }; template< analysis::rule_type Type, std::size_t Count, template< typename... > class Selector > struct is_leaf< 0, analysis::counted< Type, Count >, Selector > : std::true_type { }; template< analysis::rule_type Type, typename... Rules, template< typename... > class Selector > struct is_leaf< 0, analysis::generic< Type, Rules... >, Selector > : std::false_type { }; template< analysis::rule_type Type, std::size_t Count, typename... Rules, template< typename... > class Selector > struct is_leaf< 0, analysis::counted< Type, Count, Rules... >, Selector > : std::false_type { }; template< unsigned Level, typename Rule, template< typename... > class Selector > inline constexpr bool is_unselected_leaf = !Selector< Rule >::value && is_leaf< Level, typename Rule::analyze_t, Selector >::value; template< unsigned Level, analysis::rule_type Type, typename... Rules, template< typename... > class Selector > struct is_leaf< Level, analysis::generic< Type, Rules... >, Selector > : std::bool_constant< ( is_unselected_leaf< Level - 1, Rules, Selector > && ... ) > { }; template< unsigned Level, analysis::rule_type Type, std::size_t Count, typename... Rules, template< typename... > class Selector > struct is_leaf< Level, analysis::counted< Type, Count, Rules... >, Selector > : std::bool_constant< ( is_unselected_leaf< Level - 1, Rules, Selector > && ... ) > { }; template< typename T > struct control { template< typename Input, typename Tuple, std::size_t... Is > static void start_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::start( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ) ) ) { T::start( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ); } template< typename Input, typename... States > static void start( const Input& in, States&&... st ) noexcept( noexcept( start_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) ) { start_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ); } template< typename Input, typename Tuple, std::size_t... Is > static void success_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::success( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ) ) ) { T::success( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ); } template< typename Input, typename... States > static void success( const Input& in, States&&... st ) noexcept( noexcept( success_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) ) { success_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ); } template< typename Input, typename Tuple, std::size_t... Is > static void failure_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::failure( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ) ) ) { T::failure( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ); } template< typename Input, typename... States > static void failure( const Input& in, States&&... st ) noexcept( noexcept( failure_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) ) { failure_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ); } template< typename Input, typename Tuple, std::size_t... Is > static void raise_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::raise( in, std::get< Is >( t )... ) ) ) { T::raise( in, std::get< Is >( t )... ); } template< typename Input, typename... States > static void raise( const Input& in, States&&... st ) noexcept( noexcept( raise_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) ) { raise_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ); } template< template< typename... > class Action, typename Iterator, typename Input, typename Tuple, std::size_t... Is > static auto apply_impl( const Iterator& begin, const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::template apply< Action >( begin, in, std::get< Is >( t )... ) ) ) -> decltype( T::template apply< Action >( begin, in, std::get< Is >( t )... ) ) { return T::template apply< Action >( begin, in, std::get< Is >( t )... ); } template< template< typename... > class Action, typename Iterator, typename Input, typename... States > static auto apply( const Iterator& begin, const Input& in, States&&... st ) noexcept( noexcept( apply_impl< Action >( begin, in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) ) -> decltype( apply_impl< Action >( begin, in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) { return apply_impl< Action >( begin, in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ); } template< template< typename... > class Action, typename Input, typename Tuple, std::size_t... Is > static auto apply0_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::template apply0< Action >( in, std::get< Is >( t )... ) ) ) -> decltype( T::template apply0< Action >( in, std::get< Is >( t )... ) ) { return T::template apply0< Action >( in, std::get< Is >( t )... ); } template< template< typename... > class Action, typename Input, typename... States > static auto apply0( const Input& in, States&&... st ) noexcept( noexcept( apply0_impl< Action >( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) ) -> decltype( apply0_impl< Action >( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) { return apply0_impl< Action >( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ); } template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { return T::template match< A, M, Action, Control >( in, st... ); } }; template< typename Node, template< typename... > class Selector, template< typename... > class Control > struct make_control { template< typename Rule, bool, bool > struct state_handler; template< typename Rule > using type = control< state_handler< Rule, Selector< Rule >::value, is_leaf< 8, typename Rule::analyze_t, Selector >::value > >; }; template< typename Node, template< typename... > class Selector, template< typename... > class Control > template< typename Rule > struct make_control< Node, Selector, Control >::state_handler< Rule, false, true > : Control< Rule > { template< typename Input, typename... States > static void start( const Input& in, state< Node >& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::start( in, st... ) ) ) { Control< Rule >::start( in, st... ); } template< typename Input, typename... States > static void success( const Input& in, state< Node >& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::success( in, st... ) ) ) { Control< Rule >::success( in, st... ); } template< typename Input, typename... States > static void failure( const Input& in, state< Node >& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) ) { Control< Rule >::failure( in, st... ); } }; template< typename Node, template< typename... > class Selector, template< typename... > class Control > template< typename Rule > struct make_control< Node, Selector, Control >::state_handler< Rule, false, false > : Control< Rule > { template< typename Input, typename... States > static void start( const Input& in, state< Node >& state, States&&... st ) { Control< Rule >::start( in, st... ); state.emplace_back(); } template< typename Input, typename... States > static void success( const Input& in, state< Node >& state, States&&... st ) { Control< Rule >::success( in, st... ); auto n = std::move( state.back() ); state.pop_back(); for( auto& c : n->children ) { state.back()->children.emplace_back( std::move( c ) ); } } template< typename Input, typename... States > static void failure( const Input& in, state< Node >& state, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) ) { Control< Rule >::failure( in, st... ); state.pop_back(); } }; template< typename Node, template< typename... > class Selector, template< typename... > class Control > template< typename Rule, bool B > struct make_control< Node, Selector, Control >::state_handler< Rule, true, B > : Control< Rule > { template< typename Input, typename... States > static void start( const Input& in, state< Node >& state, States&&... st ) { Control< Rule >::start( in, st... ); state.emplace_back(); state.back()->template start< Rule >( in, st... ); } template< typename Input, typename... States > static void success( const Input& in, state< Node >& state, States&&... st ) { Control< Rule >::success( in, st... ); auto n = std::move( state.back() ); state.pop_back(); n->template success< Rule >( in, st... ); transform< Selector< Rule > >( in, n, st... ); if( n ) { state.back()->emplace_back( std::move( n ), st... ); } } template< typename Input, typename... States > static void failure( const Input& in, state< Node >& state, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) && noexcept( std::declval< Node& >().template failure< Rule >( in, st... ) ) ) { Control< Rule >::failure( in, st... ); state.back()->template failure< Rule >( in, st... ); state.pop_back(); } }; template< typename > using store_all = std::true_type; template< typename > struct selector; template< typename T > struct selector< std::tuple< T > > { using type = typename T::type; }; template< typename... Ts > struct selector< std::tuple< Ts... > > { static_assert( sizeof...( Ts ) == 0, "multiple matches found" ); using type = std::false_type; }; template< typename T > using selector_t = typename selector< T >::type; template< typename Rule, typename Collection > using select_tuple = std::conditional_t< Collection::template contains< Rule >, std::tuple< Collection >, std::tuple<> >; } // namespace internal template< typename Rule, typename... Collections > using selector = internal::selector_t< decltype( std::tuple_cat( std::declval< internal::select_tuple< Rule, Collections > >()... ) ) >; template< typename Base > struct apply : std::true_type { template< typename... Rules > struct on { using type = Base; template< typename Rule > static constexpr bool contains = ( std::is_same_v< Rule, Rules > || ... ); }; }; struct store_content : apply< store_content > {}; // some nodes don't need to store their content struct remove_content : apply< remove_content > { template< typename Node, typename... States > static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->Node::remove_content( st... ) ) ) { n->remove_content( st... ); } }; // if a node has only one child, replace the node with its child, otherwise remove content struct fold_one : apply< fold_one > { template< typename Node, typename... States > static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.size(), n->Node::remove_content( st... ) ) ) { if( n->children.size() == 1 ) { n = std::move( n->children.front() ); } else { n->remove_content( st... ); } } }; // if a node has no children, discard the node, otherwise remove content struct discard_empty : apply< discard_empty > { template< typename Node, typename... States > static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.empty(), n->Node::remove_content( st... ) ) ) { if( n->children.empty() ) { n.reset(); } else { n->remove_content( st... ); } } }; template< typename Rule, typename Node, template< typename... > class Selector = internal::store_all, template< typename... > class Action = nothing, template< typename... > class Control = normal, typename Input, typename... States > std::unique_ptr< Node > parse( Input&& in, States&&... st ) { internal::state< Node > state; if( !TAO_PEGTL_NAMESPACE::parse< Rule, Action, internal::make_control< Node, Selector, Control >::template type >( in, st..., state ) ) { return nullptr; } assert( state.stack.size() == 1 ); return std::move( state.back() ); } template< typename Rule, template< typename... > class Selector = internal::store_all, template< typename... > class Action = nothing, template< typename... > class Control = normal, typename Input, typename... States > [[nodiscard]] std::unique_ptr< node > parse( Input&& in, States&&... st ) { return parse< Rule, node, Selector, Action, Control >( in, st... ); } } // namespace TAO_PEGTL_NAMESPACE::parse_tree #endif #line 12 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/parse_tree_to_dot.hpp" #line 1 "tao/pegtl/contrib/parse_tree_to_dot.hpp" #ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_TO_DOT_HPP #define TAO_PEGTL_CONTRIB_PARSE_TREE_TO_DOT_HPP #include <cassert> #include <ostream> #include <string> namespace TAO_PEGTL_NAMESPACE::parse_tree { namespace internal { inline void escape( std::ostream& os, const std::string_view s ) { static const char* h = "0123456789abcdef"; const char* p = s.data(); const char* l = p; const char* const e = s.data() + s.size(); while( p != e ) { const unsigned char c = *p; if( c == '\\' ) { os.write( l, p - l ); l = ++p; os << "\\\\"; } else if( c == '"' ) { os.write( l, p - l ); l = ++p; os << "\\\""; } else if( c < 32 ) { os.write( l, p - l ); l = ++p; switch( c ) { case '\b': os << "\\b"; break; case '\f': os << "\\f"; break; case '\n': os << "\\n"; break; case '\r': os << "\\r"; break; case '\t': os << "\\t"; break; default: os << "\\u00" << h[ ( c & 0xf0 ) >> 4 ] << h[ c & 0x0f ]; } } else if( c == 127 ) { os.write( l, p - l ); l = ++p; os << "\\u007f"; } else { ++p; } } os.write( l, p - l ); } template< typename Node > void print_dot_node( std::ostream& os, const Node& n, const std::string_view s ) { os << " x" << &n << " [ label=\""; escape( os, s ); if( n.has_content() ) { os << "\\n"; escape( os, n.string_view() ); } os << "\" ]\n"; if( !n.children.empty() ) { os << " x" << &n << " -> { "; for( auto& up : n.children ) { os << "x" << up.get() << ( ( up == n.children.back() ) ? " }\n" : ", " ); } for( auto& up : n.children ) { print_dot_node( os, *up, up->type ); } } } } // namespace internal template< typename Node > void print_dot( std::ostream& os, const Node& n ) { os << "digraph parse_tree\n{\n"; internal::print_dot_node( os, n, n.is_root() ? "ROOT" : n.type ); os << "}\n"; } } // namespace TAO_PEGTL_NAMESPACE::parse_tree #endif #line 13 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/raw_string.hpp" #line 1 "tao/pegtl/contrib/raw_string.hpp" #ifndef TAO_PEGTL_CONTRIB_RAW_STRING_HPP #define TAO_PEGTL_CONTRIB_RAW_STRING_HPP #include <cstddef> #include <type_traits> #line 25 "tao/pegtl/contrib/raw_string.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { template< char Open, char Marker > struct raw_string_open { using analyze_t = analysis::generic< analysis::rule_type::any >; template< apply_mode A, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, std::size_t& marker_size, States&&... /*unused*/ ) noexcept( noexcept( in.size( 0 ) ) ) { if( in.empty() || ( in.peek_char( 0 ) != Open ) ) { return false; } for( std::size_t i = 1; i < in.size( i + 1 ); ++i ) { switch( const auto c = in.peek_char( i ) ) { case Open: marker_size = i + 1; in.bump_in_this_line( marker_size ); (void)eol::match( in ); return true; case Marker: break; default: return false; } } return false; } }; template< char Open, char Marker > inline constexpr bool skip_control< raw_string_open< Open, Marker > > = true; template< char Marker, char Close > struct at_raw_string_close { using analyze_t = analysis::generic< analysis::rule_type::opt >; template< apply_mode A, rewind_mode, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, const std::size_t& marker_size, States&&... /*unused*/ ) noexcept( noexcept( in.size( 0 ) ) ) { if( in.size( marker_size ) < marker_size ) { return false; } if( in.peek_char( 0 ) != Close ) { return false; } if( in.peek_char( marker_size - 1 ) != Close ) { return false; } for( std::size_t i = 0; i < ( marker_size - 2 ); ++i ) { if( in.peek_char( i + 1 ) != Marker ) { return false; } } return true; } }; template< char Marker, char Close > inline constexpr bool skip_control< at_raw_string_close< Marker, Close > > = true; template< typename Cond, typename... Rules > struct raw_string_until; template< typename Cond > struct raw_string_until< Cond > { using analyze_t = analysis::generic< analysis::rule_type::seq, star< not_at< Cond >, not_at< eof >, bytes< 1 > >, Cond >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, const std::size_t& marker_size, States&&... st ) { auto m = in.template mark< M >(); while( !Control< Cond >::template match< A, rewind_mode::required, Action, Control >( in, marker_size, st... ) ) { if( in.empty() ) { return false; } in.bump(); } return m( true ); } }; template< typename Cond, typename... Rules > struct raw_string_until { using analyze_t = analysis::generic< analysis::rule_type::seq, star< not_at< Cond >, not_at< eof >, Rules... >, Cond >; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, const std::size_t& marker_size, States&&... st ) { auto m = in.template mark< M >(); using m_t = decltype( m ); while( !Control< Cond >::template match< A, rewind_mode::required, Action, Control >( in, marker_size, st... ) ) { if( in.empty() || !( Control< Rules >::template match< A, m_t::next_rewind_mode, Action, Control >( in, st... ) && ... ) ) { return false; } } return m( true ); } }; template< typename Cond, typename... Rules > inline constexpr bool skip_control< raw_string_until< Cond, Rules... > > = true; } // namespace internal // raw_string matches Lua-style long literals. // // The following description was taken from the Lua documentation // (see http://www.lua.org/docs.html): // // - An "opening long bracket of level n" is defined as an opening square // bracket followed by n equal signs followed by another opening square // bracket. So, an opening long bracket of level 0 is written as `[[`, // an opening long bracket of level 1 is written as `[=[`, and so on. // - A "closing long bracket" is defined similarly; for instance, a closing // long bracket of level 4 is written as `]====]`. // - A "long literal" starts with an opening long bracket of any level and // ends at the first closing long bracket of the same level. It can // contain any text except a closing bracket of the same level. // - Literals in this bracketed form can run for several lines, do not // interpret any escape sequences, and ignore long brackets of any other // level. // - For convenience, when the opening long bracket is eagerly followed // by a newline, the newline is not included in the string. // // Note that unlike Lua's long literal, a raw_string is customizable to use // other characters than `[`, `=` and `]` for matching. Also note that Lua // introduced newline-specific replacements in Lua 5.2, which we do not // support on the grammar level. template< char Open, char Marker, char Close, typename... Contents > struct raw_string { // This is used for binding the apply()-method and for error-reporting // when a raw string is not closed properly or has invalid content. struct content : internal::raw_string_until< internal::at_raw_string_close< Marker, Close >, Contents... > { }; using analyze_t = typename internal::seq< internal::bytes< 1 >, content, internal::bytes< 1 > >::analyze_t; template< apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, typename Input, typename... States > [[nodiscard]] static bool match( Input& in, States&&... st ) { std::size_t marker_size; if( internal::raw_string_open< Open, Marker >::template match< A, M, Action, Control >( in, marker_size, st... ) ) { // TODO: Do not rely on must<> (void)internal::must< content >::template match< A, M, Action, Control >( in, marker_size, st... ); in.bump_in_this_line( marker_size ); return true; } return false; } }; } // namespace TAO_PEGTL_NAMESPACE #endif #line 14 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/rep_one_min_max.hpp" #line 1 "tao/pegtl/contrib/rep_one_min_max.hpp" #ifndef TAO_PEGTL_CONTRIB_REP_ONE_MIN_MAX_HPP #define TAO_PEGTL_CONTRIB_REP_ONE_MIN_MAX_HPP #include <algorithm> #line 16 "tao/pegtl/contrib/rep_one_min_max.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { template< unsigned Min, unsigned Max, char C > struct rep_one_min_max { using analyze_t = analysis::counted< analysis::rule_type::any, Min >; static_assert( Min <= Max ); template< typename Input > [[nodiscard]] static bool match( Input& in ) { const auto size = in.size( Max + 1 ); if( size < Min ) { return false; } std::size_t i = 0; while( ( i < size ) && ( in.peek_char( i ) == C ) ) { ++i; } if( ( Min <= i ) && ( i <= Max ) ) { bump_help< result_on_found::success, Input, char, C >( in, i ); return true; } return false; } }; template< unsigned Min, unsigned Max, char C > inline constexpr bool skip_control< rep_one_min_max< Min, Max, C > > = true; } // namespace internal inline namespace ascii { template< unsigned Min, unsigned Max, char C > struct rep_one_min_max : internal::rep_one_min_max< Min, Max, C > { }; } // namespace ascii } // namespace TAO_PEGTL_NAMESPACE #endif #line 16 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/rep_string.hpp" #line 1 "tao/pegtl/contrib/rep_string.hpp" #ifndef TAO_PEGTL_CONTRIB_REP_STRING_HPP #define TAO_PEGTL_CONTRIB_REP_STRING_HPP #include <cstddef> namespace TAO_PEGTL_NAMESPACE { namespace internal { template< std::size_t, typename, char... > struct make_rep_string; template< char... Ss, char... Cs > struct make_rep_string< 0, string< Ss... >, Cs... > { using type = string< Ss... >; }; template< std::size_t N, char... Ss, char... Cs > struct make_rep_string< N, string< Ss... >, Cs... > : make_rep_string< N - 1, string< Ss..., Cs... >, Cs... > { }; } // namespace internal inline namespace ascii { template< std::size_t N, char... Cs > struct rep_string : internal::make_rep_string< N, internal::string<>, Cs... >::type {}; } // namespace ascii } // namespace TAO_PEGTL_NAMESPACE #endif #line 17 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/to_string.hpp" #line 1 "tao/pegtl/contrib/to_string.hpp" #ifndef TAO_PEGTL_CONTRIB_TO_STRING_HPP #define TAO_PEGTL_CONTRIB_TO_STRING_HPP #include <string> namespace TAO_PEGTL_NAMESPACE { namespace internal { template< typename > struct to_string; template< template< char... > class X, char... Cs > struct to_string< X< Cs... > > { [[nodiscard]] static std::string get() { const char s[] = { Cs..., 0 }; return std::string( s, sizeof...( Cs ) ); } }; } // namespace internal template< typename T > [[nodiscard]] std::string to_string() { return internal::to_string< T >::get(); } } // namespace TAO_PEGTL_NAMESPACE #endif #line 18 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/tracer.hpp" #line 1 "tao/pegtl/contrib/tracer.hpp" #ifndef TAO_PEGTL_CONTRIB_TRACER_HPP #define TAO_PEGTL_CONTRIB_TRACER_HPP #include <cassert> #include <iomanip> #include <iostream> #include <utility> #include <vector> namespace TAO_PEGTL_NAMESPACE { namespace internal { template< typename Input > void print_current( const Input& in ) { if( in.empty() ) { std::cerr << "<eof>"; } else { const auto c = in.peek_uint8(); switch( c ) { case 0: std::cerr << "<nul> = "; break; case 9: std::cerr << "<ht> = "; break; case 10: std::cerr << "<lf> = "; break; case 13: std::cerr << "<cr> = "; break; default: if( isprint( c ) ) { std::cerr << '\'' << c << "' = "; } } std::cerr << "(char)" << unsigned( c ); } } } // namespace internal struct trace_state { unsigned rule = 0; unsigned line = 0; std::vector< unsigned > stack; }; template< template< typename... > class Base > struct trace { template< typename Rule > struct control : Base< Rule > { template< typename Input, typename... States > static void start( const Input& in, States&&... st ) { std::cerr << in.position() << " start " << internal::demangle< Rule >() << "; current "; print_current( in ); std::cerr << std::endl; Base< Rule >::start( in, st... ); } template< typename Input, typename... States > static void start( const Input& in, trace_state& ts, States&&... st ) { std::cerr << std::setw( 6 ) << ++ts.line << " " << std::setw( 6 ) << ++ts.rule << " "; start( in, st... ); ts.stack.push_back( ts.rule ); } template< typename Input, typename... States > static void success( const Input& in, States&&... st ) { std::cerr << in.position() << " success " << internal::demangle< Rule >() << "; next "; print_current( in ); std::cerr << std::endl; Base< Rule >::success( in, st... ); } template< typename Input, typename... States > static void success( const Input& in, trace_state& ts, States&&... st ) { assert( !ts.stack.empty() ); std::cerr << std::setw( 6 ) << ++ts.line << " " << std::setw( 6 ) << ts.stack.back() << " "; success( in, st... ); ts.stack.pop_back(); } template< typename Input, typename... States > static void failure( const Input& in, States&&... st ) { std::cerr << in.position() << " failure " << internal::demangle< Rule >() << std::endl; Base< Rule >::failure( in, st... ); } template< typename Input, typename... States > static void failure( const Input& in, trace_state& ts, States&&... st ) { assert( !ts.stack.empty() ); std::cerr << std::setw( 6 ) << ++ts.line << " " << std::setw( 6 ) << ts.stack.back() << " "; failure( in, st... ); ts.stack.pop_back(); } template< template< typename... > class Action, typename Iterator, typename Input, typename... States > static auto apply( const Iterator& begin, const Input& in, States&&... st ) -> decltype( Base< Rule >::template apply< Action >( begin, in, st... ) ) { std::cerr << in.position() << " apply " << internal::demangle< Rule >() << std::endl; return Base< Rule >::template apply< Action >( begin, in, st... ); } template< template< typename... > class Action, typename Iterator, typename Input, typename... States > static auto apply( const Iterator& begin, const Input& in, trace_state& ts, States&&... st ) -> decltype( apply< Action >( begin, in, st... ) ) { std::cerr << std::setw( 6 ) << ++ts.line << " "; return apply< Action >( begin, in, st... ); } template< template< typename... > class Action, typename Input, typename... States > static auto apply0( const Input& in, States&&... st ) -> decltype( Base< Rule >::template apply0< Action >( in, st... ) ) { std::cerr << in.position() << " apply0 " << internal::demangle< Rule >() << std::endl; return Base< Rule >::template apply0< Action >( in, st... ); } template< template< typename... > class Action, typename Input, typename... States > static auto apply0( const Input& in, trace_state& ts, States&&... st ) -> decltype( apply0< Action >( in, st... ) ) { std::cerr << std::setw( 6 ) << ++ts.line << " "; return apply0< Action >( in, st... ); } }; }; template< typename Rule > using tracer = trace< normal >::control< Rule >; } // namespace TAO_PEGTL_NAMESPACE #endif #line 19 "amalgamated.hpp" #line 1 "tao/pegtl/contrib/unescape.hpp" #line 1 "tao/pegtl/contrib/unescape.hpp" #ifndef TAO_PEGTL_CONTRIB_UNESCAPE_HPP #define TAO_PEGTL_CONTRIB_UNESCAPE_HPP #include <cassert> #include <string> namespace TAO_PEGTL_NAMESPACE::unescape { // Utility functions for the unescape actions. [[nodiscard]] inline bool utf8_append_utf32( std::string& string, const unsigned utf32 ) { if( utf32 <= 0x7f ) { string += char( utf32 & 0xff ); return true; } if( utf32 <= 0x7ff ) { char tmp[] = { char( ( ( utf32 & 0x7c0 ) >> 6 ) | 0xc0 ), char( ( ( utf32 & 0x03f ) ) | 0x80 ) }; string.append( tmp, sizeof( tmp ) ); return true; } if( utf32 <= 0xffff ) { if( utf32 >= 0xd800 && utf32 <= 0xdfff ) { // nope, this is a UTF-16 surrogate return false; } char tmp[] = { char( ( ( utf32 & 0xf000 ) >> 12 ) | 0xe0 ), char( ( ( utf32 & 0x0fc0 ) >> 6 ) | 0x80 ), char( ( ( utf32 & 0x003f ) ) | 0x80 ) }; string.append( tmp, sizeof( tmp ) ); return true; } if( utf32 <= 0x10ffff ) { char tmp[] = { char( ( ( utf32 & 0x1c0000 ) >> 18 ) | 0xf0 ), char( ( ( utf32 & 0x03f000 ) >> 12 ) | 0x80 ), char( ( ( utf32 & 0x000fc0 ) >> 6 ) | 0x80 ), char( ( ( utf32 & 0x00003f ) ) | 0x80 ) }; string.append( tmp, sizeof( tmp ) ); return true; } return false; } // This function MUST only be called for characters matching TAO_PEGTL_NAMESPACE::ascii::xdigit! template< typename I > [[nodiscard]] I unhex_char( const char c ) { switch( c ) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return I( c - '0' ); case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': return I( c - 'a' + 10 ); case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return I( c - 'A' + 10 ); default: // LCOV_EXCL_LINE throw std::runtime_error( "invalid character in unhex" ); // LCOV_EXCL_LINE } } template< typename I > [[nodiscard]] I unhex_string( const char* begin, const char* end ) { I r = 0; while( begin != end ) { r <<= 4; r += unhex_char< I >( *begin++ ); } return r; } // Actions for common unescape situations. struct append_all { template< typename Input > static void apply( const Input& in, std::string& s ) { s.append( in.begin(), in.size() ); } }; // This action MUST be called for a character matching T which MUST be TAO_PEGTL_NAMESPACE::one< ... >. template< typename T, char... Rs > struct unescape_c { template< typename Input > static void apply( const Input& in, std::string& s ) { assert( in.size() == 1 ); s += apply_one( in, static_cast< const T* >( nullptr ) ); } template< typename Input, char... Qs > [[nodiscard]] static char apply_one( const Input& in, const one< Qs... >* /*unused*/ ) { static_assert( sizeof...( Qs ) == sizeof...( Rs ), "size mismatch between escaped characters and their mappings" ); return apply_two( in, { Qs... }, { Rs... } ); } template< typename Input > [[nodiscard]] static char apply_two( const Input& in, const std::initializer_list< char >& q, const std::initializer_list< char >& r ) { const char c = *in.begin(); for( std::size_t i = 0; i < q.size(); ++i ) { if( *( q.begin() + i ) == c ) { return *( r.begin() + i ); } } throw parse_error( "invalid character in unescape", in ); // LCOV_EXCL_LINE } }; // See src/example/pegtl/unescape.cpp for why the following two actions // skip the first input character. They also MUST be called // with non-empty matched inputs! struct unescape_u { template< typename Input > static void apply( const Input& in, std::string& s ) { assert( !in.empty() ); // First character MUST be present, usually 'u' or 'U'. if( !utf8_append_utf32( s, unhex_string< unsigned >( in.begin() + 1, in.end() ) ) ) { throw parse_error( "invalid escaped unicode code point", in ); } } }; struct unescape_x { template< typename Input > static void apply( const Input& in, std::string& s ) { assert( !in.empty() ); // First character MUST be present, usually 'x'. s += unhex_string< char >( in.begin() + 1, in.end() ); } }; // The unescape_j action is similar to unescape_u, however unlike // unescape_u it // (a) assumes exactly 4 hexdigits per escape sequence, // (b) accepts multiple consecutive escaped 16-bit values. // When applied to more than one escape sequence, unescape_j // translates UTF-16 surrogate pairs in the input into a single // UTF-8 sequence in s, as required for JSON by RFC 8259. struct unescape_j { template< typename Input > static void apply( const Input& in, std::string& s ) { assert( ( ( in.size() + 1 ) % 6 ) == 0 ); // Expects multiple "\\u1234", starting with the first "u". for( const char* b = in.begin() + 1; b < in.end(); b += 6 ) { const auto c = unhex_string< unsigned >( b, b + 4 ); if( ( 0xd800 <= c ) && ( c <= 0xdbff ) && ( b + 6 < in.end() ) ) { const auto d = unhex_string< unsigned >( b + 6, b + 10 ); if( ( 0xdc00 <= d ) && ( d <= 0xdfff ) ) { b += 6; (void)utf8_append_utf32( s, ( ( ( c & 0x03ff ) << 10 ) | ( d & 0x03ff ) ) + 0x10000 ); continue; } } if( !utf8_append_utf32( s, c ) ) { throw parse_error( "invalid escaped unicode code point", in ); } } } }; } // namespace TAO_PEGTL_NAMESPACE::unescape #endif #line 20 "amalgamated.hpp"
29.335123
834
0.592966
glaba
3dd5ffa4c785a170dafbe766a344550b60ac0d02
3,670
cc
C++
chrome/browser/first_run/first_run_gtk.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/browser/first_run/first_run_gtk.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/first_run/first_run_gtk.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/first_run/first_run.h" #include "app/app_switches.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/gtk/first_run_dialog.h" #include "chrome/browser/shell_integration.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/result_codes.h" #include "chrome/installer/util/google_update_settings.h" #include "googleurl/src/gurl.h" // TODO(port): This is just a piece of the silent import functionality from // ImportSettings for Windows. It would be nice to get the rest of it ported. bool FirstRun::ImportBookmarks(const FilePath& import_bookmarks_path) { const CommandLine& cmdline = *CommandLine::ForCurrentProcess(); CommandLine import_cmd(cmdline.GetProgram()); // Propagate user data directory switch. if (cmdline.HasSwitch(switches::kUserDataDir)) { import_cmd.AppendSwitchPath(switches::kUserDataDir, cmdline.GetSwitchValuePath(switches::kUserDataDir)); } // Since ImportSettings is called before the local state is stored on disk // we pass the language as an argument. GetApplicationLocale checks the // current command line as fallback. import_cmd.AppendSwitchASCII(switches::kLang, g_browser_process->GetApplicationLocale()); import_cmd.CommandLine::AppendSwitchPath(switches::kImportFromFile, import_bookmarks_path); // Time to launch the process that is going to do the import. We'll wait // for the process to return. return base::LaunchApp(import_cmd, true, false, NULL); } #if defined(OS_LINUX) && !defined(OS_CHROMEOS) CommandLine* Upgrade::new_command_line_ = NULL; double Upgrade::saved_last_modified_time_of_exe_ = 0; // static bool Upgrade::IsUpdatePendingRestart() { return saved_last_modified_time_of_exe_ != Upgrade::GetLastModifiedTimeOfExe(); } // static void Upgrade::SaveLastModifiedTimeOfExe() { saved_last_modified_time_of_exe_ = Upgrade::GetLastModifiedTimeOfExe(); } // static bool Upgrade::RelaunchChromeBrowser(const CommandLine& command_line) { return base::LaunchApp(command_line, false, false, NULL); } // static double Upgrade::GetLastModifiedTimeOfExe() { FilePath exe_file_path; if (!PathService::Get(base::FILE_EXE, &exe_file_path)) { LOG(WARNING) << "Failed to get FilePath object for FILE_EXE."; return saved_last_modified_time_of_exe_; } base::PlatformFileInfo exe_file_info; if (!file_util::GetFileInfo(exe_file_path, &exe_file_info)) { LOG(WARNING) << "Failed to get FileInfo object for FILE_EXE - " << exe_file_path.value(); return saved_last_modified_time_of_exe_; } return exe_file_info.last_modified.ToDoubleT(); } #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS) // static void FirstRun::ShowFirstRunDialog(Profile* profile, bool randomize_search_engine_experiment) { FirstRunDialog::Show(profile, randomize_search_engine_experiment); } // static bool FirstRun::IsOrganic() { // We treat all installs as organic. return true; } // static void FirstRun::PlatformSetup() { // Things that Windows does here (creating a desktop icon, for example) are // handled at install time on Linux. }
35.631068
78
0.741144
Gitman1989
3dd7f0638bcbd930148f051967274cf6b03883b4
13,612
cpp
C++
src/x86_energy_sync_plugin.cpp
readex-eu/scorep_plugin_x86_energy
0a46340795b0a2f2f4b6848477f3507e9c0c5803
[ "BSD-3-Clause" ]
6
2015-10-30T12:20:59.000Z
2020-05-01T09:45:25.000Z
src/x86_energy_sync_plugin.cpp
readex-eu/scorep_plugin_x86_energy
0a46340795b0a2f2f4b6848477f3507e9c0c5803
[ "BSD-3-Clause" ]
7
2017-06-01T20:53:29.000Z
2020-04-30T11:19:58.000Z
src/x86_energy_sync_plugin.cpp
readex-eu/scorep_plugin_x86_energy
0a46340795b0a2f2f4b6848477f3507e9c0c5803
[ "BSD-3-Clause" ]
2
2017-04-13T08:32:40.000Z
2018-08-22T08:34:31.000Z
/* * Copyright (c) 2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <chrono> #include <iostream> #include <limits.h> #include <string> #include <sys/syscall.h> #include <sys/types.h> #include <system_error> #include <unistd.h> #include <vector> #ifdef HAVE_MPI #include <functional> #include <mpi.h> #endif #include <x86_energy.hpp> #include <x86_energy_sync_plugin.hpp> using scorep::plugin::logging; bool global_is_resposible_process = false; pid_t global_responsible_thread = -1; x86_energy_sync_plugin::x86_energy_sync_plugin() { /* * this part restores informations saved in the global variables. * This is necessary if the plugin gets reinitalisized and the * synchronise funciton is not called, for example if PTF is used */ this->responsible_thread = global_responsible_thread; this->is_resposible = global_is_resposible_process; char c_hostname[HOST_NAME_MAX + 1]; if (gethostname(c_hostname, HOST_NAME_MAX + 1)) { int errsv = errno; switch (errsv) { case EFAULT: throw std::runtime_error("Failed to get local hostname. EFAULT"); break; case EINVAL: throw std::runtime_error("Failed to get local hostname. EINVAL"); break; case ENAMETOOLONG: throw std::runtime_error("Failed to get local hostname. ENAMETOOLONG"); break; case EPERM: throw std::runtime_error("Failed to get local hostname. EPERM"); break; default: throw std::runtime_error(std::string("Failed to get local hostname. ERRNO: ") + std::to_string(errsv)); break; } } this->hostname = std::string(c_hostname); logging::debug("X86_ENERGY_SYNC_PLUGIN") << "Using x86_energy mechanism: " << mechanism.name(); auto sources = mechanism.available_sources(); for (auto& source : sources) { try { source.init(); logging::debug() << "Add Source: " << source.name(); active_sources.push_back(std::make_unique<x86_energy::AccessSource>(std::move(source))); } catch (std::exception& e) { logging::debug("X86_ENERGY_SYNC_PLUGIN") << "Failed to initialize access source: " << source.name() << " error was: " << e.what(); } } if (active_sources.empty()) { logging::fatal() << "Failed to initialize any available source. x86_energy values won't be available."; throw std::runtime_error("Failed to initialize x86_energy access source."); } } /** * Destructor * * Stopping x86_energy */ x86_energy_sync_plugin::~x86_energy_sync_plugin() { logging::debug() << "plugin sucessfull finalized"; } /** * You don't have to do anything in this method, but it tells the plugin * that this metric will indeed be used */ void x86_energy_sync_plugin::add_metric(x86_energy_metric& m) { logging::info() << "adding x86_energy metric " << m.name(); logging::debug() << "adding counter for ptid:" << syscall(SYS_gettid); } /** Will be called for every event in by the measurement environment. * You may or may not give it a value here. * * @param m contains the sored metric informations * @param proxy get and save the results * * NOTE: In this implemenation we use a few assumptions: * * scorep calls at every event all metrics * * this metrics are called everytime in the same order **/ template <typename P> void x86_energy_sync_plugin::get_current_value(x86_energy_metric& m, P& proxy) { // retrun 0 if not responsible. Simulate PER_HOST. pid_t ptid = syscall(SYS_gettid); if (!this->is_resposible || (this->responsible_thread != ptid)) { proxy.store((int64_t)0); return; } if (m.quantity() != "E") { logging::info() << "Unknown Quantity can't be measured"; /* no results can be obtained */ proxy.store((int64_t)0); return; } double energy = m.read(); // energy of x86_energy is in Joule, retunr in mJ proxy.store((int64_t)(energy * 1000)); } /** function to determine the responsible process for x86_energy * * If there is no MPI communication, the x86_energy communication is PER_PROCESS, * so Score-P cares about everything. * If there is MPI communication and the plugin is build with -DHAVE_MPI, * we are grouping all MPI_Processes according to their hostname hash. * Then we select rank 0 to be the responsible rank for MPI communication. * * @param is_responsible the Score-P responsibility * @param sync_mode sync mode, i.e. SCOREP_METRIC_SYNCHRONIZATION_MODE_BEGIN for non MPI * programs and SCOREP_METRIC_SYNCHRONIZATION_MODE_BEGIN_MPP for MPI program. * Does not deal with SCOREP_METRIC_SYNCHRONIZATION_MODE_END */ void x86_energy_sync_plugin::synchronize(bool is_responsible, SCOREP_MetricSynchronizationMode sync_mode) { logging::debug() << "Synchronize " << is_responsible << ", " << sync_mode; if (is_responsible) { switch (sync_mode) { case SCOREP_METRIC_SYNCHRONIZATION_MODE_BEGIN: { logging::debug() << "SCOREP_METRIC_SYNCHRONIZATION_MODE_BEGIN"; this->is_resposible = true; this->responsible_thread = syscall(SYS_gettid); logging::debug() << "got responsible ptid:" << this->responsible_thread; break; } case SCOREP_METRIC_SYNCHRONIZATION_MODE_BEGIN_MPP: { logging::debug() << "SCOREP_METRIC_SYNCHRONIZATION_MODE_BEGIN_MPP"; #ifdef HAVE_MPI std::hash<std::string> mpi_color_hash; MPI_Comm node_local_comm; int myrank; int new_myrank; // TODO // we are assuming, that this is unique enough .... // we probably need a rework here int hash = abs(mpi_color_hash(this->hostname)); logging::debug() << "hash value: " << hash; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); MPI_Comm_split(MPI_COMM_WORLD, hash, myrank, &node_local_comm); MPI_Comm_rank(node_local_comm, &new_myrank); if (new_myrank == 0) { this->is_resposible = true; logging::debug() << "got responsible process for host: " << this->hostname; } else { this->is_resposible = false; } this->responsible_thread = syscall(SYS_gettid); logging::debug() << "got responsible ptid:" << this->responsible_thread; MPI_Comm_free(&node_local_comm); #else logging::warn() << "You are using the non MPI version of this " "plugin. This might lead to trouble if there is more " "than one MPI rank per node."; this->is_resposible = true; this->responsible_thread = syscall(SYS_gettid); logging::debug() << "got responsible ptid:" << this->responsible_thread; #endif break; } case SCOREP_METRIC_SYNCHRONIZATION_MODE_END: { break; } case SCOREP_METRIC_SYNCHRONIZATION_MODE_MAX: { break; } } } global_is_resposible_process = this->is_resposible; global_responsible_thread = this->responsible_thread; logging::debug() << "setting global responsible ptid to:" << this->responsible_thread; } /** * Convert a named metric (may contain wildcards or so) to a vector of * actual metrics (may have a different name) * * NOTE: Adds the metrics. Currently available metrics are depend on the * current system. In RAPL you can found the following possible ones * * * package * * core * * gpu * * dram * * dram_ch0 * * dram_ch1 * * dram_ch2 * * dram_ch3 * * Wildcards are allowed. * The metrics will be changed to upper case letters and the number ot the * package will be added at the end of the name */ std::vector<scorep::plugin::metric_property> x86_energy_sync_plugin::get_metric_properties(const std::string& name) { logging::debug() << "received get_metric_properties(" << name << ")"; std::vector<scorep::plugin::metric_property> properties; if (metric_properties_added) { logging::debug() << "Tried already to add metric properties. Do nothing."; return properties; } std::vector<x86_energy::SourceCounter> blade_sources; for (int i = 0; i < static_cast<int>(x86_energy::Counter::SIZE); i++) { auto counter = static_cast<x86_energy::Counter>(i); auto granularity = mechanism.granularity(counter); if (granularity == x86_energy::Granularity::SIZE) { logging::debug() << "Counter is not available: " << counter << " (Skipping)"; continue; } for (auto index = 0; index < architecture.size(granularity); index++) { std::stringstream str; str << mechanism.name() << " " << counter << "[" << index << "]"; std::string metric_name = str.str(); std::vector<x86_energy::SourceCounter> tmp_vec; for (auto& active_source : active_sources) { logging::debug() << "try source: " << active_source->name() << " for granularity: " << index; try { tmp_vec.emplace_back(active_source->get(counter, index)); std::stringstream str; str << active_source->name() << "/" << mechanism.name() << " " << counter << "[" << index << "]"; std::string metric_name = str.str(); auto& handle = make_handle(metric_name, metric_name, metric_name, std::move(tmp_vec), std::string("E"), false, 0); auto metric = scorep::plugin::metric_property(metric_name, " Energy Consumption", "J") .accumulated_last() .value_int() .decimal() .value_exponent(-3); properties.push_back(metric); if (counter == x86_energy::Counter::PCKG || counter == x86_energy::Counter::DRAM) { blade_sources.emplace_back(active_source->get(counter, index)); } break; } catch (std::runtime_error& e) { logging::debug() << "Could not access source: " << active_source->name() << " for granularity: " << index << " Reason : " << e.what(); } } } } if (!blade_sources.empty()) { double offset = stod(scorep::environment_variable::get("OFFSET", "70.0")); logging::info("X86_ENERGY_SYNC_PLUGIN") << "set offset to " << offset << "W"; std::string metric_name = "x86_energy/BLADE/E"; auto& handle = make_handle(metric_name, metric_name, metric_name, std::move(blade_sources), std::string("E"), true, offset); auto metric = scorep::plugin::metric_property(metric_name, " Energy Consumption", "J") .accumulated_last() .value_int() .decimal() .value_exponent(-3); properties.push_back(metric); } if (properties.empty()) { logging::error() << "Did not add any property! There will be no measurments available."; } metric_properties_added = true; return properties; } SCOREP_METRIC_PLUGIN_CLASS(x86_energy_sync_plugin, "x86_energy_sync")
35.727034
100
0.606964
readex-eu
3dd826c3ebf05ae78877f8923818494ada1ff2b2
5,033
hpp
C++
src/StateSystem.hpp
epicbrownie/Epic
c54159616b899bb24c6d59325d582e73f2803ab6
[ "MIT" ]
null
null
null
src/StateSystem.hpp
epicbrownie/Epic
c54159616b899bb24c6d59325d582e73f2803ab6
[ "MIT" ]
29
2016-08-01T14:50:12.000Z
2017-12-17T20:28:27.000Z
src/StateSystem.hpp
epicbrownie/Epic
c54159616b899bb24c6d59325d582e73f2803ab6
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017 Ronnie Brohn (EpicBrownie) // // Distributed under The MIT License (MIT). // (See accompanying file License.txt or copy at // https://opensource.org/licenses/MIT) // // Please report any bugs, typos, or suggestions to // https://github.com/epicbrownie/Epic/issues // ////////////////////////////////////////////////////////////////////////////// #pragma once #include <Epic/State.hpp> #include <Epic/StateTypes.hpp> #include <Epic/StringHash.hpp> #include <Epic/STL/Map.hpp> #include <Epic/STL/Vector.hpp> #include <Epic/STL/UniquePtr.hpp> #include <Epic/detail/StateSystemFwd.hpp> ////////////////////////////////////////////////////////////////////////////// // StateSystem class Epic::StateSystem { public: using Type = Epic::StateSystem; private: enum class eStateSystemCommand { Push, Pop, Change }; struct StateSystemCommand { constexpr StateSystemCommand(eStateSystemCommand command, StateName target = InvalidStateName) noexcept : CommandType{ command }, Target{ target } { } eStateSystemCommand CommandType; StateName Target; }; private: using StatePtr = Epic::UniquePtr<Epic::State>; using StateMap = Epic::STLUnorderedMap<Epic::StringHash, StatePtr>; using StateStack = Epic::STLVector<StatePtr::pointer>; using StateCommandBuffer = Epic::STLVector<StateSystemCommand>; private: StateMap m_States; StateStack m_StateStack; StateCommandBuffer m_Commands; public: inline StateSystem() noexcept { } ~StateSystem() { while (!m_StateStack.empty()) { m_StateStack.back()->Leave(); m_StateStack.pop_back(); } } private: StateSystem(const Type&) = delete; Type& operator= (const Type&) = delete; public: template<class StateType, class... Args> StateType* CreateState(const StateName& name, Args&&... args) noexcept { if(name == InvalidStateName) return nullptr; auto pState = Epic::MakeImpl<Epic::State, StateType>(std::forward<Args>(args)...); auto pStatePtr = static_cast<StateType*>(pState.get()); m_States[name] = std::move(pState); pStatePtr->m_pStateSystem = this; return pStatePtr; } State* GetState(const StateName& name) const noexcept { auto it = m_States.find(name); if (it == std::end(m_States)) return nullptr; return (*it).second.get(); } State* GetForeground() const noexcept { if (m_StateStack.empty()) return nullptr; return m_StateStack.back(); } private: void _Push(const StateName& name) { auto pState = GetState(name); auto pForeground = GetForeground(); m_StateStack.emplace_back(pState); if (pForeground) pForeground->LeaveForeground(); pState->Enter(); } void _Pop() { auto pState = GetForeground(); if (!pState) return; pState->Leave(); m_StateStack.pop_back(); auto pForeground = GetForeground(); if (pForeground) pForeground->EnterForeground(); } void _Change(const StateName& name) { auto pState = GetState(name); if (m_StateStack.empty()) { m_StateStack.emplace_back(pState); pState->Enter(); } else { size_t stackCount = m_StateStack.size(); // Stop all but the bottom state while (m_StateStack.size() > 1) { auto pForeground = m_StateStack.back(); pForeground->Leave(); m_StateStack.pop_back(); } // Only pop the last state if it's not the target state if (pState != m_StateStack.back()) { m_StateStack.back()->Leave(); m_StateStack.clear(); m_StateStack.emplace_back(pState); pState->Enter(); } else if (stackCount > 1) { // The remaining state is the target state // and was previously in the background pState->EnterForeground(); } } } void ProcessCommandQueue() { for (auto& cmd : m_Commands) { switch (cmd.CommandType) { case eStateSystemCommand::Change: _Change(cmd.Target); break; case eStateSystemCommand::Push: _Push(cmd.Target); break; case eStateSystemCommand::Pop: _Pop(); break; default: break; } } m_Commands.clear(); } public: void Push(const StateName& name) noexcept { if (GetState(name) != nullptr) m_Commands.emplace_back(eStateSystemCommand::Push, name); } void Pop() noexcept { if (!m_Commands.empty() && (m_Commands.back().CommandType == eStateSystemCommand::Push || m_Commands.back().CommandType == eStateSystemCommand::Change)) { // This command would cancel out the previous command m_Commands.pop_back(); } else m_Commands.emplace_back(eStateSystemCommand::Pop); } void ChangeTo(const StateName& name) noexcept { if (GetState(name) != nullptr) { // This command will cancel out previous commands m_Commands.clear(); m_Commands.emplace_back(eStateSystemCommand::Change, name); } } public: void Update() { ProcessCommandQueue(); for (auto& pState : m_StateStack) pState->Update(); } };
21.326271
84
0.641963
epicbrownie
3dd8cf6ffba045e1fc8596f8bcdf4dc6c02188f1
352
hpp
C++
components/python/detail/forward.hpp
jinntechio/RocketJoe
9b08a21fda1609c57b40ef8b9750897797ac815b
[ "BSD-3-Clause" ]
9
2020-07-20T15:32:07.000Z
2021-06-04T13:02:58.000Z
components/python/detail/forward.hpp
jinntechio/RocketJoe
9b08a21fda1609c57b40ef8b9750897797ac815b
[ "BSD-3-Clause" ]
26
2019-10-27T12:58:42.000Z
2020-05-30T16:43:48.000Z
components/python/detail/forward.hpp
jinntechio/RocketJoe
9b08a21fda1609c57b40ef8b9750897797ac815b
[ "BSD-3-Clause" ]
3
2020-08-29T07:07:49.000Z
2021-06-04T13:02:59.000Z
#pragma once namespace components { namespace python { namespace detail { class data_set; class file_manager; class file_view; class context; class context_manager; class file_manager; class pipelien_data_set; }}} // namespace components::python::detail namespace boost { template<class T> class intrusive_ptr; }
19.555556
60
0.713068
jinntechio
3ddaeb065a774d18e6ccad30062a3ed8311cb702
3,200
hpp
C++
src/common.hpp
Hardcode84/DirectDrawWrapper
71ca1caa4a77c19af71be88582c009eb79132280
[ "MIT" ]
2
2017-12-20T07:11:10.000Z
2020-05-13T08:08:47.000Z
src/common.hpp
Hardcode84/DirectDrawWrapper
71ca1caa4a77c19af71be88582c009eb79132280
[ "MIT" ]
null
null
null
src/common.hpp
Hardcode84/DirectDrawWrapper
71ca1caa4a77c19af71be88582c009eb79132280
[ "MIT" ]
2
2017-12-20T07:09:58.000Z
2021-01-21T08:29:59.000Z
#ifndef COMMON_HPP #define COMMON_HPP #include "ddraw.h" #include <atomic> #include <algorithm> #include "simple_logger/logger.hpp" #include "tools/com_ptr.hpp" #define DD_API __stdcall struct winerr_wrapper { DWORD err; winerr_wrapper(DWORD e):err(e) {} }; winerr_wrapper getWinError(); winerr_wrapper getWinErrorFromHr(HRESULT hr); template<typename STREAM> STREAM& operator<<(STREAM& s, const GUID& g) { s << (void*)g.Data1 << '-' << (void*)g.Data2 << '-' << (void*)g.Data3; for(const auto c: g.Data4) { s << '-'; s << (void*)c; } return s; } template<typename STREAM> STREAM& operator<<(STREAM& s, const DDCOLORKEY& ck) { s << "Color key: " << ck.dwColorSpaceLowValue << "-" << ck.dwColorSpaceHighValue; return s; } template<typename STREAM> STREAM& operator<<(STREAM& s, const RECT& rc) { s << "RECT: left: " << rc.left << " right: " << rc.right << " top: " << rc.top << " bottom: " << rc.bottom; return s; } template<typename STREAM> STREAM& operator<<(STREAM& s, const winerr_wrapper& e) { LPTSTR lpMsgBuf = nullptr; const DWORD size = ::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, e.err, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, nullptr); for(DWORD i = 0; i < size; ++i) { if(('\r' == lpMsgBuf[i]) || ('\n' == lpMsgBuf[i])) { lpMsgBuf[i] = ' '; } } s << '\"' << lpMsgBuf << "\", code " << e.err; LocalFree(lpMsgBuf); return s; } #define LOG_ERROR() WRITE_LOG(*mLog,logger::logERROR) #define LOG_WARNING() WRITE_LOG(*mLog,logger::logWARNING) #define LOG_INFO() WRITE_LOG(*mLog,logger::logINFO) #define LOG_DEBUG() WRITE_LOG(*mLog,logger::logDEBUG) #ifdef __GNUC__ #define FUNC_NAME __PRETTY_FUNCTION__ #else #define FUNC_NAME __func__ #endif #define WRITE_VAR(var) LOG_INFO() << #var << "=\"" << var << '\"' #define WRITE_VAR_DEBUG(var) LOG_DEBUG() << #var << "=\"" << var << '\"' #define WRITE_FLAG(var,flag) if((var) & (flag)) do{ LOG_INFO() << #var ": \"" #flag << "\" set"; }while(false) #define WRITE_THIS() WRITE_VAR_DEBUG(this) #define LOG_STATIC_FUNCTION() LOG_SCOPE((FUNC_NAME),*mLog,logger::logDEBUG); #define LOG_FUNCTION() LOG_SCOPE((FUNC_NAME),*mLog,logger::logDEBUG); \ WRITE_THIS() #define LOG_FUNCTION_E() LOG_SCOPE((FUNC_NAME),*mLog,logger::logINFO); \ WRITE_THIS(); \ LOG_ERROR() << (FUNC_NAME) << " not implemented;"; return E_NOTIMPL; #define CHECK_PARAM(param) do{ if(!(param)) { LOG_ERROR() << "Param \"" #param "\" failed"; return DDERR_INVALIDPARAMS; } }while(false) template<typename BaseT, typename SrcT> BaseT* adjust_pointer(SrcT* src) { if(nullptr == src) return nullptr; const BaseT* dummy1 = nullptr; const SrcT* dummy2 = static_cast<const SrcT*>(dummy1); const auto offset = reinterpret_cast<const char*>(dummy2) - reinterpret_cast<const char*>(dummy1); char* p = reinterpret_cast<char*>(src); p -= offset; return reinterpret_cast<BaseT*>(p); } #endif // COMMON_HPP
28.070175
135
0.629063
Hardcode84
3ddba1dee7955e894c7f5f6062caa28e9763c5d6
2,348
cpp
C++
src/extern-libs/DXInterceptorLibs/xgraph/XGraphDataNotation.cpp
heyyod/AttilaSimulator
cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1
[ "BSD-3-Clause" ]
null
null
null
src/extern-libs/DXInterceptorLibs/xgraph/XGraphDataNotation.cpp
heyyod/AttilaSimulator
cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1
[ "BSD-3-Clause" ]
1
2022-03-18T05:02:32.000Z
2022-03-21T07:27:48.000Z
src/extern-libs/DXInterceptorLibs/xgraph/XGraphDataNotation.cpp
heyyod/AttilaSimulator
cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1
[ "BSD-3-Clause" ]
null
null
null
// XGraphDataNotation.cpp: Implementierung der Klasse XGraphDataNotation. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "XGraphDataNotation.h" #include "XGraphDataSerie.h" #include "XGraph.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif IMPLEMENT_SERIAL( CXGraphDataNotation, CXGraphObject, 1 ) ////////////////////////////////////////////////////////////////////// // Konstruktion/Destruktion ////////////////////////////////////////////////////////////////////// CXGraphDataNotation::CXGraphDataNotation() { m_Font.CreateFont(12, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_CHARACTER_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Arial")); m_bCanMove = m_bCanEdit = m_bCanResize = false; m_bPositioned = false; } CXGraphDataNotation::~CXGraphDataNotation() { m_Font.DeleteObject(); } void CXGraphDataNotation::Draw(CDCEx *pDC) { TDataPoint point; if (!m_bVisible) return; if (m_bSizing) m_Tracker.Draw (pDC); CFontSelector fs(&m_Font, pDC); point.fXVal = m_fXVal; point.fYVal = m_fYVal; int nXPos = m_pGraph->GetXAxis (m_pGraph->GetCurve (m_nCurve).GetXAxis ()).GetPointForValue (&point).x; int nYPos = m_pGraph->GetYAxis (m_pGraph->GetCurve (m_nCurve).GetYAxis ()).GetPointForValue (&point).y; if (!m_bPositioned) { m_clRect.SetRect (nXPos, nYPos - 20, nXPos + 1, nYPos); pDC->DrawText(m_cText, m_clRect, DT_CENTER | DT_CALCRECT); m_bPositioned = true; } m_clRect.OffsetRect (nXPos - m_clRect.left, nYPos - m_clRect.top - 20); m_clRect.InflateRect (1,1,1,1); pDC->FillSolidRect (m_clRect, 0L); m_clRect.DeflateRect (1,1,1,1); pDC->FillSolidRect (m_clRect, RGB(255,255,255)); pDC->DrawText(m_cText, m_clRect, DT_CENTER); pDC->FillSolidRect (nXPos - 1, nYPos - 1, 3, 3, 0); pDC->MoveTo(nXPos, nYPos); pDC->LineTo(nXPos, m_clRect.bottom); } void CXGraphDataNotation::Serialize( CArchive& archive ) { CXGraphObject::Serialize (archive); if( archive.IsStoring() ) { archive << m_fXVal; archive << m_fYVal; archive << m_nCurve; archive << m_nIndex; archive << m_cText; } else { archive >> m_fXVal; archive >> m_fYVal; archive >> m_nCurve; archive >> m_nIndex; archive >> m_cText; } }
23.959184
104
0.644804
heyyod
3de367680d4198058bcc8b91c87a2267491b006a
4,221
cpp
C++
api/python/DEX/objects/pyHeader.cpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
api/python/DEX/objects/pyHeader.cpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
api/python/DEX/objects/pyHeader.cpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * 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 "LIEF/DEX/Header.hpp" #include "LIEF/DEX/hash.hpp" #include "pyDEX.hpp" namespace LIEF { namespace DEX { template <class T> using getter_t = T (Header::*)(void) const; template <class T> using setter_t = void (Header::*)(T); template <> void create<Header>(py::module& m) { py::class_<Header, LIEF::Object>(m, "Header", "DEX Header") .def_property_readonly( "magic", static_cast<getter_t<Header::magic_t>>(&Header::magic), "Magic value") .def_property_readonly( "checksum", static_cast<getter_t<uint32_t>>(&Header::checksum), "Checksum value of the rest of the file (without " RST_ATTR_REF( lief.DEX.Header.magic) ")") .def_property_readonly( "signature", static_cast<getter_t<Header::signature_t>>(&Header::signature), "SHA-1 signature of the rest of the file (without " RST_ATTR_REF( lief.DEX.Header.magic) " and " RST_ATTR_REF(lief.DEX.Header .checksum) ")") .def_property_readonly( "file_size", static_cast<getter_t<uint32_t>>(&Header::file_size), "Size of the current DEX file") .def_property_readonly( "header_size", static_cast<getter_t<uint32_t>>(&Header::header_size), "Size of this header. Should be ``0x70``") .def_property_readonly( "endian_tag", static_cast<getter_t<uint32_t>>(&Header::endian_tag), "Endianness tag. Should be ``ENDIAN_CONSTANT``") .def_property_readonly( "map_offset", static_cast<getter_t<uint32_t>>(&Header::map), "Offset from the start of the file to the map item") .def_property_readonly( "strings", static_cast<getter_t<Header::location_t>>(&Header::strings), "String identifiers") .def_property_readonly( "link", static_cast<getter_t<Header::location_t>>(&Header::link), "Link (raw data)") .def_property_readonly( "types", static_cast<getter_t<Header::location_t>>(&Header::types), "Type identifiers") .def_property_readonly( "prototypes", static_cast<getter_t<Header::location_t>>(&Header::prototypes), "Prototypes identifiers") .def_property_readonly( "fields", static_cast<getter_t<Header::location_t>>(&Header::fields), "Fields identifiers") .def_property_readonly( "methods", static_cast<getter_t<Header::location_t>>(&Header::methods), "Methods identifiers") .def_property_readonly( "classes", static_cast<getter_t<Header::location_t>>(&Header::classes), "Classess identifiers") .def_property_readonly( "data", static_cast<getter_t<Header::location_t>>(&Header::data), "Raw data. Should be align on 32-bits") .def_property_readonly( "nb_classes", static_cast<getter_t<uint32_t>>(&Header::nb_classes), "Number of classes in the current DEX") .def_property_readonly( "nb_methods", static_cast<getter_t<uint32_t>>(&Header::nb_methods), "Number of methods in the current DEX") .def("__eq__", &Header::operator==) .def("__ne__", &Header::operator!=) .def("__hash__", [](const Header& header) { return Hash::hash(header); }) .def("__str__", [](const Header& header) { std::ostringstream stream; stream << header; return stream.str(); }); } } // namespace DEX } // namespace LIEF
34.598361
79
0.631604
ahawad
3de43e659fc789111f0b749ee864dddfec0d486c
4,217
cxx
C++
source/code/core/collections/tests/test_queue.cxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
39
2019-08-17T09:08:51.000Z
2022-02-13T10:14:19.000Z
source/code/core/collections/tests/test_queue.cxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
63
2020-05-22T16:09:30.000Z
2022-01-21T14:24:05.000Z
source/code/core/collections/tests/test_queue.cxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
null
null
null
#include <catch2/catch.hpp> #include <ice/memory/memory_globals.hxx> #include <ice/memory/proxy_allocator.hxx> #include <ice/pod/queue.hxx> SCENARIO("ice :: pod :: Queue") { namespace queue = ice::pod::queue; ice::memory::ProxyAllocator alloc{ ice::memory::default_allocator(), "queue_test" }; ice::pod::Queue<int32_t> test_queue{ alloc }; CHECK(queue::size(test_queue) == 0); GIVEN("An empty Queue") { CHECK(queue::size(test_queue) == 0); WHEN("Pushing an element") { queue::push_back(test_queue, 0xd00b); CHECK(queue::size(test_queue) == 1); } WHEN("Pushing 100 elements") { for (int i = 0; i < 100; ++i) { queue::push_back(test_queue, 0xd00b); } CHECK(queue::size(test_queue) == 100); THEN("Poping 50 elements") { for (int i = 0; i < 50; ++i) { queue::pop_back(test_queue); } CHECK(queue::size(test_queue) == 50); } THEN("Consuming all elements") { queue::consume(test_queue, queue::size(test_queue)); CHECK(queue::size(test_queue) == 0); } } } GIVEN("A wrapped queue") { // Reserve space for 10 elements queue::reserve(test_queue, 10); CHECK(queue::size(test_queue) == 0); int32_t const test_values[]{ 1, 2, 3, 4, 5, 6, 7 }; // Push 7 elements so we move the offset. queue::push_back(test_queue, { test_values }); CHECK(queue::size(test_queue) == 7); // Consume the elements queue::consume(test_queue, 7); CHECK(queue::size(test_queue) == 0); // Push another 6 elements so we got 3 elements at the end of the ring buffer and 3 at the begining int32_t const test_values_2[]{ 1, 2, 3, 4, 5, 6 }; queue::push_back(test_queue, { test_values_2 }); CHECK(queue::size(test_queue) == 6); THEN("Check if we iterate in the proper order over the queue") { uint32_t const queue_size = queue::size(test_queue); for (uint32_t i = 0; i < queue_size; ++i) { CHECK(test_queue[i] == test_values_2[i]); } WHEN("Resizing the queue capacity check again") { uint32_t const alloc_count = alloc.allocation_count(); queue::reserve(test_queue, 100); // Check that we did force a reallocation CHECK(alloc_count + 1 == alloc.allocation_count()); // Check the queue is still in tact CHECK(queue_size == queue::size(test_queue)); for (uint32_t i = 0; i < queue_size; ++i) { CHECK(test_queue[i] == test_values_2[i]); } } } //THEN("Check the chunk iterators seeing only the three last elements") //{ // auto* it = queue::begin_front(test_queue); // auto* end = queue::end_front(test_queue); // int index = 0; // while (it != end) // { // CHECK(*it == test_number_array[index++]); // it++; // } // CHECK(index == 3); // WHEN("Resizing the queue we see all 6 elements now") // { // auto alloc_count = alloc.allocation_count(); // queue::reserve(test_queue, 100); // // Check that we did force a reallocation // CHECK(alloc_count + 1 == alloc.allocation_count()); // // Get the new iterators values // it = queue::begin_front(test_queue); // end = queue::end_front(test_queue); // // Check the queue is still intact // index = 0; // while (it != end) // { // CHECK(*it == test_number_array[index++]); // it++; // } // CHECK(index == 3); // } //} } }
30.338129
107
0.487076
iceshard-engine
3de4b080b151db5aded6bf2c3540ec6c597795ff
746
hpp
C++
app/app/render/material.hpp
muleax/slope
254138703163705b57332fc7490dd2eea0082b57
[ "MIT" ]
6
2022-02-05T23:28:12.000Z
2022-02-24T11:08:04.000Z
app/app/render/material.hpp
muleax/slope
254138703163705b57332fc7490dd2eea0082b57
[ "MIT" ]
null
null
null
app/app/render/material.hpp
muleax/slope
254138703163705b57332fc7490dd2eea0082b57
[ "MIT" ]
null
null
null
#pragma once #include "app/render/mesh.hpp" #include "slope/math/matrix44.hpp" namespace slope::app { class Material { public: Material(std::shared_ptr<MeshShader> shader) { m_shader = std::move(shader); } ~Material() = default; const MeshShader& shader() const { return *m_shader; } void use() const { m_shader->use(); m_shader->set_ambient_strength(m_ambient_strength); m_shader->set_color(m_color); } void set_ambient_strength(float value) { m_ambient_strength = value; } void set_color(const vec3& value) { m_color = value; } private: std::shared_ptr<MeshShader> m_shader; float m_ambient_strength = 0.25f; vec3 m_color = {1.f, 1.f, 1.f}; }; } // slope::app
22.606061
74
0.654155
muleax
3de57d997a183870d93e5a80befe88d77716c95a
6,563
cpp
C++
Project Resources/GUI/Input.cpp
Abd-ELrahmanHamza/Logic-circuit-simulator
ffb69ec135c45193ecc446ec5a27c6a0e15a09ad
[ "MIT" ]
null
null
null
Project Resources/GUI/Input.cpp
Abd-ELrahmanHamza/Logic-circuit-simulator
ffb69ec135c45193ecc446ec5a27c6a0e15a09ad
[ "MIT" ]
null
null
null
Project Resources/GUI/Input.cpp
Abd-ELrahmanHamza/Logic-circuit-simulator
ffb69ec135c45193ecc446ec5a27c6a0e15a09ad
[ "MIT" ]
null
null
null
//#include "Input.h" #include "Output.h" Input::Input(window* pW) { pWind = pW; //point to the passed window } void Input::GetPointClicked(int &x, int &y) { pWind->WaitMouseClick(x, y); //Wait for mouse click } string Input::GetSrting(Output *pOut) { ///TODO: Implement this Function //Read a complete string from the user until the user presses "ENTER". //If the user presses "ESCAPE". This function should return an empty string. //"BACKSPACE" should be also supported //User should see what he is typing at the status bar string ComponentName=""; char NameChar; enum SpecialKeys{ESC=27,ENTER=13,BACKSPACE=8}; pOut->PrintMsg("Enter the Name "); pWind->WaitKeyPress(NameChar); if (NameChar != ESC && NameChar != ENTER) ComponentName += NameChar; while(NameChar!=ESC && NameChar!=ENTER) { //ComponentName +=NameChar; pOut->PrintMsg("Enter the Name "+ComponentName); pWind->WaitKeyPress(NameChar); if(NameChar == ESC) { ComponentName = ""; break; } else if(NameChar == ENTER) { break; } else if(NameChar==BACKSPACE && ComponentName.length() > 0) { ComponentName.pop_back(); pOut->PrintMsg("Enter the Name "+ComponentName); continue; } else if(NameChar==BACKSPACE && ComponentName.length() == 0) { continue; } ComponentName+=NameChar; } pOut->PrintMsg("Entered name is "+ComponentName); return ComponentName; } char Input::GetChar(Output* pOut) { char n; pWind->WaitKeyPress(n); return n; } //This function reads the position where the user clicks to determine the desired action ActionType Input::GetUserAction() const { int x,y; pWind->WaitMouseClick(x, y); //Get the coordinates of the user click if(UI.AppMode == DESIGN ) //application is in design mode { //[1] If user clicks on the Toolbar if ( y >= 0 && y < UI.ToolBarHeight) { //Check whick Menu item was clicked //==> This assumes that menu items are lined up horizontally <== int ClickedItemOrder = (x / UI.ToolItemWidth); //Divide x coord of the point clicked by the menu item width (int division) //if division result is 0 ==> first item is clicked, if 1 ==> 2nd item and so on switch (ClickedItemOrder) { case ITM_Buff:return ADD_Buff; case ITM_INV:return ADD_INV; case ITM_AND2: return ADD_AND_GATE_2; case ITM_OR2: return ADD_OR_GATE_2; case ITM_NAND2:return ADD_NAND_GATE_2; case ITM_NOR2:return ADD_NOR_GATE_2; case ITM_XOR2:return ADD_XOR_GATE_2; case ITM_XNOR2:return ADD_XNOR_GATE_2; case ITM_AND3:return ADD_AND_GATE_3; case ITM_NOR3:return ADD_NOR_GATE_3; case ITM_XOR3:return ADD_XOR_GATE_3; case ITM_SWITCH:return ADD_Switch; case ITM_LED:return ADD_LED; case ITM_CONNECTION:return ADD_CONNECTION; case ITM_EXIT: return EXIT; default: return DSN_TOOL; //A click on empty place in desgin toolbar } } if(y >= UI.ToolBarHeight && y < UI.height - UI.StatusBarHeight && x>=UI.width-UI.MngToolItemWidth) { int ClickedItemOrder = ((y-UI.ToolBarHeight) / UI.MngToolItemWidth); //Divide x coord of the point clicked by the menu item width (int division) //if division result is 0 ==> first item is clicked, if 1 ==> 2nd item and so on switch (ClickedItemOrder) { case ITM_ADD_Label:return ADD_Label; case ITM_EDIT_Label:return EDIT_Label; //case ITM_Create_TruthTable: return Create_TruthTable; //case ITM_Change_Switch: return Change_Switch; case ITM_SELECT:return SELECT; case ITM_DEL:return DEL; case ITM_MOVE:return MOVE; case ITM_SAVE:return SAVE; case ITM_LOAD:return LOAD; case ITM_UNDO:return UNDO; case ITM_REDO:return REDO; case ITM_DSN_MODE:return DSN_MODE; case ITM_SIM_MODE:return SIM_MODE; case ITM_COPY:return COPY; case ITM_CUT:return CUT; case ITM_PASTE:return PASTE; //case ITM_STATUS_BAR:return STATUS_BAR; default: return DSN_TOOL; //A click on empty place in desgin toolbar } } //[2] User clicks on the drawing area if ( y >= UI.ToolBarHeight && y < UI.height - UI.StatusBarHeight && x<UI.width-UI.MngToolItemWidth) { return SELECT; //user want to select/unselect a component } //[3] User clicks on the status bar return STATUS_BAR; } else //Application is in Simulation mode { //return SIM_MODE; //This should be changed after creating the compelete simulation bar //[1] If user clicks on the Toolbar if ( y >= 0 && y < UI.ToolBarHeight) { //Check whick Menu item was clicked //==> This assumes that menu items are lined up horizontally <== int ClickedItemOrder = (x / UI.ToolItemWidth); //Divide x coord of the point clicked by the menu item width (int division) //if division result is 0 ==> first item is clicked, if 1 ==> 2nd item and so on switch (ClickedItemOrder) { case ITM_VALIDATE:return VALIDATE_SIM_MODE; case ITM_SIM:return SIMULATE_SIM_MODE; case ITM_TRUTH: return Create_TruthTable; //done case ITM_PROBE: return PROBE_SIM_MODE; case ITM_DESIGN:return DSN_MODE; case ITM_Change_Switch:return Change_Switch; case ITM_EXITS:return EXIT; default: return SIM_TOOL; //A click on empty place in desgin toolbar } } if(y >= UI.ToolBarHeight && y < UI.height - UI.StatusBarHeight && x>=UI.width-UI.MngToolItemWidth) { int ClickedItemOrder = ((y-UI.ToolBarHeight) / UI.MngToolItemWidth); //Divide x coord of the point clicked by the menu item width (int division) //if division result is 0 ==> first item is clicked, if 1 ==> 2nd item and so on switch (ClickedItemOrder) { //case ITM_ADD_Label:return ADD_Label; //case ITM_EDIT_Label:return EDIT_Label; //case ITM_Create_TruthTable: return Create_TruthTable; //case ITM_Change_Switch: return Change_Switch; //case ITM_SELECT:return SELECT; //case ITM_DEL:return DEL; //case ITM_MOVE:return MOVE; //case ITM_SAVE:return SAVE; //case ITM_LOAD:return LOAD; //case ITM_UNDO:return UNDO; //case ITM_REDO:return REDO; case ITM_DSN_MODE:return DSN_MODE; case ITM_SIM_MODE:return SIM_MODE; //case ITM_COPY:return COPY; //case ITM_CUT:return CUT; //case ITM_PASTE:return PASTE; //case ITM_STATUS_BAR:return STATUS_BAR; default: return DSN_TOOL; //A click on empty place in desgin toolbar } } //[2] User clicks on the drawing area if ( y >= UI.ToolBarHeight && y < UI.height - UI.StatusBarHeight && x<UI.width-UI.MngToolItemWidth) { return SELECT; //user want to select/unselect a component } //[3] User clicks on the status bar return STATUS_BAR; } } Input::~Input() { }
30.525581
101
0.705775
Abd-ELrahmanHamza
3de8f2e2d0cdf4b65cea513af95d002aa92ee99c
398
cpp
C++
Recursion/Recursion - 1 - Basics/05. CheckIfArrayIsSortedOrNot.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
2
2021-05-21T17:10:02.000Z
2021-05-29T05:13:06.000Z
Recursion/Recursion - 1 - Basics/05. CheckIfArrayIsSortedOrNot.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
Recursion/Recursion - 1 - Basics/05. CheckIfArrayIsSortedOrNot.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; bool is_sorted(int a[], int n) { if (n == 1 || n == 0) return true; // if (a[0] > a[1]) // return false; if (a[n - 1] < a[n - 2]) return false; return is_sorted(a, n - 1); } int main() { int arr[] = {0, 1, 2, 2, 3, 4, 5, 6}; int n = *(&arr + 1) - arr; cout << is_sorted(arr, n) << endl; return 0; }
18.090909
41
0.459799
sohamnandi77
3deb1cfb8b19e633f322a913e8ae03d6642deeac
27,834
cpp
C++
ace/tao/orbsvcs/orbsvcs/av/rtcp.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/orbsvcs/orbsvcs/av/rtcp.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/orbsvcs/orbsvcs/av/rtcp.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
/* * Copyright (c) 1994-1995 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and the Network Research Group at * Lawrence Berkeley Laboratory. * 4. Neither the name of the University nor of the Laboratory may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ // RTCP.cpp,v 5.10 2001/03/26 21:17:02 coryan Exp #include "ntp-time.h" #include "RTCP.h" #include "media-timer.h" #include "tao/debug.h" // TAO_AV_RTP_State TAO_AV_RTP_State::TAO_AV_RTP_State (void) :bad_version_(0), badoptions_(0), badfmt_(0), badext_(0), nrunt_(0), last_np_(0), sdes_seq_(0), rtcp_inv_bw_(0.), rtcp_avg_size_(128.), confid_(-1) { ACE_NEW (pktbuf_, u_char [2 * RTP_MTU]); } //------------------------------------------------------------ // TAO_AV_RTCP //------------------------------------------------------------ u_char* TAO_AV_RTCP::build_sdes_item (u_char* p, int code, TAO_AV_Source& s) { const char* value = s.sdes (code); if (value != 0) { int len = strlen (value); *p++ = code; *p++ = len; memcpy (p, value, len); p += len; } return (p); } int TAO_AV_RTCP::build_sdes (rtcphdr* rh, TAO_AV_Source& ls, TAO_AV_RTP_State *state) { int flags = RTP_VERSION << 14 | 1 << 8 | RTCP_PT_SDES; rh->rh_flags = htons (flags); rh->rh_ssrc = ls.srcid (); u_char* p = (u_char*) (rh + 1); p = build_sdes_item (p, RTCP_SDES_CNAME, ls); /* * We always send a cname plus one other sdes * There's a schedule for what we send sequenced by sdes_seq_: * - send 'email' every 0th & 4th packet * - send 'note' every 2nd packet * - send 'tool' every 6th packet * - send 'name' in all the odd slots * (if 'note' is not the empty string, we switch the roles * of name & note) */ int nameslot, noteslot; const char* note = ls.sdes (RTCP_SDES_NOTE); if (note) { if (*note) { nameslot = RTCP_SDES_NOTE; noteslot = RTCP_SDES_NAME; } else { nameslot = RTCP_SDES_NAME; noteslot = RTCP_SDES_NOTE; } } else { nameslot = RTCP_SDES_NAME; noteslot = RTCP_SDES_NAME; } u_int seq = (++state->sdes_seq_) & 0x7; switch (seq) { case 0: case 4: p = build_sdes_item (p, RTCP_SDES_EMAIL, ls); break; case 2: p = build_sdes_item (p, noteslot, ls); break; case 6: p = build_sdes_item (p, RTCP_SDES_TOOL, ls); break; default: p = build_sdes_item (p, nameslot, ls); } int len = p - (u_char*)rh; int pad = 4 - (len & 3); len += pad; rh->rh_len = htons ( (len >> 2) - 1); while (--pad >= 0) *p++ = 0; return (len); } int TAO_AV_RTCP::build_bye (rtcphdr* rh, TAO_AV_Source& ls) { int flags = RTP_VERSION << 14 | 1 << 8 | RTCP_PT_BYE; rh->rh_flags = ntohs (flags); rh->rh_len = htons (1); rh->rh_ssrc = ls.srcid (); return (8); } void TAO_AV_RTCP::parse_rr_records (ACE_UINT32, rtcp_rr*, int, const u_char*, ACE_UINT32) { if (TAO_debug_level > 0) ACE_DEBUG ( (LM_DEBUG,"TAO_AV_RTCP::parse_rr_records\n")); } void TAO_AV_RTCP::parse_sr (rtcphdr* rh, int flags, u_char*ep, TAO_AV_Source* ps, ACE_UINT32 addr, TAO_AV_SourceManager *source_manager) { rtcp_sr* sr = ACE_reinterpret_cast (rtcp_sr*, (rh + 1)); TAO_AV_Source* s; ACE_UINT32 ssrc = rh->rh_ssrc; if (ps->srcid () != ssrc) s = source_manager->lookup (ssrc, ssrc, addr); else s = ps; s->lts_ctrl (ACE_OS::gettimeofday ()); s->sts_ctrl (ntohl (sr->sr_ntp.upper) << 16 | ntohl (sr->sr_ntp.lower) >> 16); int cnt = flags >> 8 & 0x1f; parse_rr_records (ssrc, ACE_reinterpret_cast (rtcp_rr*, (sr + 1)), cnt, ep, addr); } void TAO_AV_RTCP::parse_rr (rtcphdr* rh, int flags, u_char* ep, TAO_AV_Source* ps, ACE_UINT32 addr, TAO_AV_SourceManager *source_manager) { TAO_AV_Source* s; ACE_UINT32 ssrc = rh->rh_ssrc; if (ps->srcid () != ssrc) s = source_manager->lookup (ssrc, ssrc, addr); else s = ps; s->lts_ctrl (ACE_OS::gettimeofday ()); int cnt = flags >> 8 & 0x1f; parse_rr_records (ssrc, ACE_reinterpret_cast (rtcp_rr*, (rh + 1)), cnt, ep, addr); } int TAO_AV_RTCP::sdesbody (ACE_UINT32* p, u_char* ep, TAO_AV_Source* ps, ACE_UINT32 addr, ACE_UINT32 ssrc, TAO_AV_SourceManager *source_manager) { TAO_AV_Source* s; ACE_UINT32 srcid = *p; if (ps->srcid () != srcid) s = source_manager->lookup (srcid, ssrc, addr); else s = ps; if (s == 0) return (0); /* * Note ctrl packet since we will never see any direct ctrl packets * from a TAO_AV_Source through a mixer (and we don't want the TAO_AV_Source to * time out). */ s->lts_ctrl (ACE_OS::gettimeofday ()); u_char* cp = (u_char*) (p + 1); while (cp < ep) { char buf[256]; u_int type = cp[0]; if (type == 0) { /* end of chunk */ return ( ( (cp - (u_char*)p) >> 2) + 1); } u_int len = cp[1]; u_char* eopt = cp + len + 2; if (eopt > ep) return (0); if (type >= RTCP_SDES_MIN && type <= RTCP_SDES_MAX) { memcpy (buf, (char*)&cp[2], len); buf[len] = 0; s->sdes (type, buf); } else /*XXX*/; cp = eopt; } return (0); } void TAO_AV_RTCP::parse_sdes (rtcphdr* rh, int flags, u_char* ep, TAO_AV_Source* ps, ACE_UINT32 addr, ACE_UINT32 ssrc, TAO_AV_SourceManager *source_manager) { int cnt = flags >> 8 & 0x1f; ACE_UINT32* p = (ACE_UINT32*)&rh->rh_ssrc; while (--cnt >= 0) { int n = TAO_AV_RTCP::sdesbody (p, ep, ps, addr, ssrc, source_manager); if (n == 0) break; p += n; } if (cnt >= 0) ps->badsdes (1); } void TAO_AV_RTCP::parse_bye (rtcphdr* rh, int flags, u_char* ep, TAO_AV_Source* ps, TAO_AV_SourceManager *source_manager) { int cnt = flags >> 8 & 0x1f; ACE_UINT32* p = (ACE_UINT32*)&rh->rh_ssrc; while (--cnt >= 0) { if (p >= (ACE_UINT32*)ep) { ps->badbye (1); return; } TAO_AV_Source* s; if (ps->srcid () != rh->rh_ssrc) s = source_manager->consult (*p); else s = ps; if (s != 0) s->lts_done (ACE_OS::gettimeofday ()); ++p; } } /*XXX check for buffer overflow*/ /* * Send an RTPv2 report packet. */ void TAO_AV_RTCP::send_report (int bye, TAO_AV_Protocol_Object *protocol_object, TAO_AV_SourceManager *source_manager, TAO_AV_RTP_State *state, TAO_AV_RTCP_Callback *callback) { if (source_manager->localsrc () == 0) return; TAO_AV_Source& s = *source_manager->localsrc (); rtcphdr* rh = (rtcphdr*)state->pktbuf_; rh->rh_ssrc = s.srcid (); int flags = RTP_VERSION << 14; timeval now = ACE_OS::gettimeofday (); s.lts_ctrl (now); int we_sent = 0; rtcp_rr* rr; /* * If we've sent data since our last sender report send a * new report. The MediaTimer check is to make sure we still * have a grabber -- if not, we won't be able to interpret the * media timestamps so there's no point in sending an SR. */ MediaTimer* mt = MediaTimer::instance (); if (s.np () != state->last_np_ && mt) { state->last_np_ = s.np (); we_sent = 1; flags |= RTCP_PT_SR; rtcp_sr* sr = ACE_reinterpret_cast (rtcp_sr*, (rh + 1)); sr->sr_ntp = ntp64time (now); sr->sr_ntp.upper = ACE_HTONL (sr->sr_ntp.upper); sr->sr_ntp.lower = ACE_HTONL (sr->sr_ntp.lower); sr->sr_ts = htonl (mt->ref_ts ()); sr->sr_np = htonl (s.np ()); sr->sr_nb = htonl (s.nb ()); rr = ACE_reinterpret_cast (rtcp_rr*, (sr + 1)); } else { flags |= RTCP_PT_RR; rr = ACE_reinterpret_cast (rtcp_rr*, (rh + 1)); } int nrr = 0; int nsrc = 0; /* * we don't want to inflate report interval if user has set * the flag that causes all TAO_AV_Sources to be 'kept' so we * consider TAO_AV_Sources 'inactive' if we haven't heard a control * msg from them for ~32 reporting intervals. */ u_int inactive = u_int (state->rint_ * (32./1000.)); if (inactive < 2) inactive = 2; for (TAO_AV_Source* sp = source_manager->sources (); sp != 0; sp = sp->next_) { ++nsrc; int received = sp->np () - sp->snp (); if (received == 0) { if (u_int (now.tv_sec - sp->lts_ctrl ().tv_sec) > inactive) --nsrc; continue; } sp->snp (sp->np ()); rr->rr_srcid = sp->srcid (); int expected = sp->ns () - sp->sns (); sp->sns (sp->ns ()); ACE_UINT32 v; int lost = expected - received; if (lost <= 0) v = 0; else /* expected != 0 if lost > 0 */ v = ( (lost << 8) / expected) << 24; /* XXX should saturate on over/underflow */ v |= (sp->ns () - sp->np ()) & 0xffffff; rr->rr_loss = htonl (v); rr->rr_ehsr = htonl (sp->ehs ()); rr->rr_dv = sp->delvar (); rr->rr_lsr = htonl (sp->sts_ctrl ()); if (sp->lts_ctrl ().tv_sec == 0) rr->rr_dlsr = 0; else { ACE_UINT32 ntp_now = ntptime (now); ACE_UINT32 ntp_then = ntptime (sp->lts_ctrl ()); rr->rr_dlsr = htonl (ntp_now - ntp_then); } ++rr; if (++nrr >= 31) break; } flags |= nrr << 8; rh->rh_flags = htons (flags); int len = (u_char*)rr - state->pktbuf_; rh->rh_len = htons ( (len >> 2) - 1); if (bye) len += build_bye ( ACE_reinterpret_cast (rtcphdr*,rr), s); else len += build_sdes ( ACE_reinterpret_cast (rtcphdr*, rr), s,state); ACE_Message_Block mb ((char *)state->pktbuf_, len); mb.wr_ptr (len); protocol_object->send_frame (&mb); state->rtcp_avg_size_ += RTCP_SIZE_GAIN * (double (len + 28) - state->rtcp_avg_size_); /* * compute the time to the next report. we do this here * because we need to know if there were any active TAO_AV_Sources * during the last report period (nrr above) & if we were * a TAO_AV_Source. The bandwidth limit for rtcp traffic was set * on startup from the session bandwidth. It is the inverse * of bandwidth (ie., ms/byte) to avoid a divide below. */ double ibw = state->rtcp_inv_bw_; if (nrr) { /* there were active TAO_AV_Sources */ if (we_sent) { ibw *= 1./RTCP_SENDER_BW_FRACTION; nsrc = nrr; } else { ibw *= 1./RTCP_RECEIVER_BW_FRACTION; nsrc -= nrr; } } double rint = state->rtcp_avg_size_ * double (nsrc) * ibw; if (rint < RTCP_MIN_RPT_TIME * 1000.) rint = RTCP_MIN_RPT_TIME * 1000.; state->rint_ = rint; callback->schedule (int (TAO_AV_RTCP::fmod (double (ACE_OS::rand ()), rint) + rint * .5 + .5)); source_manager->CheckActiveSources (rint); } int TAO_AV_RTCP::handle_input (ACE_Message_Block *data, const ACE_Addr &peer_address, rtcphdr &header, TAO_AV_SourceManager *source_manager, TAO_AV_RTP_State *state) { int cc = data->length (); int size_phdr = ACE_static_cast (int, sizeof (rtcphdr)); if (cc < size_phdr) { state->nrunt_++; ACE_ERROR_RETURN ( (LM_ERROR,"TAO_AV_RTP::handle_input:invalid header\n"),-1); } if (peer_address == ACE_Addr::sap_any) ACE_ERROR_RETURN ( (LM_ERROR,"TAO_AV_RTP::handle_input:get_peer_addr failed\n"),-1); // @@ We need to be careful of this. u_long addr = peer_address.hash (); header = * (rtcphdr*) (data->rd_ptr ()); rtcphdr *rh = (rtcphdr *)data->rd_ptr (); /* * try to filter out junk: first thing in packet must be * sr, rr or bye & version number must be correct. */ switch (ntohs (rh->rh_flags) & 0xc0ff) { case RTP_VERSION << 14 | RTCP_PT_SR: case RTP_VERSION << 14 | RTCP_PT_RR: case RTP_VERSION << 14 | RTCP_PT_BYE: break; default: /* * XXX should further categorize this error -- it is * likely that people mis-implement applications that * don't put something other than SR,RR,BYE first. */ ++state->bad_version_; return -1; } /* * at this point we think the packet's valid. Update our average * size estimator. Also, there's valid ssrc so charge errors to it */ double tmp = (cc + 28) - state->rtcp_avg_size_; tmp *= RTCP_SIZE_GAIN; state->rtcp_avg_size_ += ACE_static_cast (int, tmp); /* * First record in compound packet must be the ssrc of the * sender of the packet. Pull it out here so we can use * it in the sdes parsing, since the sdes record doesn't * contain the ssrc of the sender (in the case of mixers). */ ACE_UINT32 ssrc = rh->rh_ssrc; TAO_AV_Source* ps = source_manager->lookup (ssrc, ssrc, addr); if (ps == 0) return 0; /* * Outer loop parses multiple RTCP records of a "compound packet". * There is no framing between records. Boundaries are implicit * and the overall length comes from UDP. */ u_char* epack = (u_char*)rh + cc; while ( (u_char*)rh < epack) { u_int len = (ntohs (rh->rh_len) << 2) + 4; u_char* ep = (u_char*)rh + len; if (ep > epack) { ps->badsesslen (1); return 0; } u_int flags = ntohs (rh->rh_flags); if (flags >> 14 != RTP_VERSION) { ps->badsessver (1); return 0; } switch (flags & 0xff) { case RTCP_PT_SR: TAO_AV_RTCP::parse_sr (rh, flags, ep, ps, addr, source_manager); break; case RTCP_PT_RR: TAO_AV_RTCP::parse_rr (rh, flags, ep, ps, addr, source_manager); break; case RTCP_PT_SDES: TAO_AV_RTCP::parse_sdes (rh, flags, ep, ps, addr, ssrc, source_manager); break; case RTCP_PT_BYE: TAO_AV_RTCP::parse_bye (rh, flags, ep, ps, source_manager); break; default: ps->badsessopt (1); break; } rh = (rtcphdr*)ep; } return 0; } ACE_UINT32 TAO_AV_RTCP::alloc_srcid (ACE_UINT32 addr) { ACE_Time_Value tv = ACE_OS::gettimeofday (); ACE_UINT32 srcid = ACE_UINT32 (tv.sec () + tv.usec ()); srcid += (ACE_UINT32)ACE_OS::getuid(); srcid += (ACE_UINT32)ACE_OS::getpid(); srcid += addr; return (srcid); } double TAO_AV_RTCP::fmod (double dividend, double divisor) { //Method to calculate the fmod (x,y) int quotient = ACE_static_cast (int, (dividend / divisor)); double product = quotient * divisor; double remainder = dividend - product; return remainder; } // TAO_AV_RTCP_Flow_Factory TAO_AV_RTCP_Flow_Factory::TAO_AV_RTCP_Flow_Factory (void) { } TAO_AV_RTCP_Flow_Factory::~TAO_AV_RTCP_Flow_Factory (void) { } int TAO_AV_RTCP_Flow_Factory::match_protocol (const char *flow_string) { if (ACE_OS::strncasecmp (flow_string,"RTCP",4) == 0) return 1; return 0; } int TAO_AV_RTCP_Flow_Factory::init (int /* argc */, char * /* argv */ []) { return 0; } TAO_AV_Protocol_Object* TAO_AV_RTCP_Flow_Factory::make_protocol_object (TAO_FlowSpec_Entry *entry, TAO_Base_StreamEndPoint *endpoint, TAO_AV_Flow_Handler *handler, TAO_AV_Transport *transport) { TAO_AV_Callback *callback = 0; endpoint->get_control_callback (entry->flowname (), callback); if (callback == 0) ACE_NEW_RETURN (callback, TAO_AV_RTCP_Callback, 0); TAO_AV_Protocol_Object *object = 0; ACE_NEW_RETURN (object, TAO_AV_RTCP_Object (callback, transport), 0); callback->open (object, handler); return object; } // TAO_AV_RTCP_Object int TAO_AV_RTCP_Object::handle_input (void) { ACE_Message_Block *data; size_t bufsiz = 2*this->transport_->mtu (); ACE_NEW_RETURN (data, ACE_Message_Block (bufsiz), -1); int n = this->transport_->recv (data->rd_ptr (),bufsiz); if (n == 0) ACE_ERROR_RETURN ( (LM_ERROR,"TAO_AV_RTP::handle_input:connection closed\n"),-1); if (n < 0) ACE_ERROR_RETURN ( (LM_ERROR,"TAO_AV_RTP::handle_input:recv error\n"),-1); data->wr_ptr (n); ACE_Addr *peer_addr = this->transport_->get_peer_addr (); this->callback_->receive_control_frame (data,*peer_addr); return 0; } int TAO_AV_RTCP_Object::send_frame (ACE_Message_Block *frame, TAO_AV_frame_info * /*frame_info*/) { return this->transport_->send (frame); } int TAO_AV_RTCP_Object::send_frame (const iovec *iov, int iovcnt, TAO_AV_frame_info * /*frame_info*/) { return this->transport_->send (iov, iovcnt); } int TAO_AV_RTCP_Object::send_frame (const char*, size_t) { return 0; } TAO_AV_RTCP_Object::TAO_AV_RTCP_Object (TAO_AV_Callback *callback, TAO_AV_Transport *transport) :TAO_AV_Protocol_Object (callback,transport) { } TAO_AV_RTCP_Object::~TAO_AV_RTCP_Object (void) { } int TAO_AV_RTCP_Object::destroy (void) { this->callback_->handle_destroy (); return 0; } int TAO_AV_RTCP_Object::set_policies (const TAO_AV_PolicyList &/*policy_list*/) { return -1; } int TAO_AV_RTCP_Object::start (void) { return this->callback_->handle_start (); } int TAO_AV_RTCP_Object::stop (void) { return this->callback_->handle_stop (); } int TAO_AV_RTCP_Object::handle_control_input (ACE_Message_Block *frame, const ACE_Addr &peer_address) { // frame->rd_ptr ((size_t)0); // // Since the rd_ptr would have been moved ahead. return this->callback_->receive_frame (frame, 0, peer_address); } // TAO_AV_RTCP_Callback TAO_AV_RTCP_Callback::TAO_AV_RTCP_Callback (void) { ACE_NEW (source_manager_, TAO_AV_SourceManager (this)); ACE_NEW (this->state_, TAO_AV_RTP_State); } TAO_AV_RTCP_Callback::~TAO_AV_RTCP_Callback (void) { } TAO_AV_SourceManager* TAO_AV_RTCP_Callback::source_manager (void) { return this->source_manager_; } TAO_AV_RTP_State* TAO_AV_RTCP_Callback::state (void) { return this->state_; } int TAO_AV_RTCP_Callback::get_rtp_source (TAO_AV_Source *&source, ACE_UINT32 srcid, ACE_UINT32 ssrc, ACE_UINT32 addr) { ACE_NEW_RETURN (source, TAO_AV_Source (srcid, ssrc, addr), -1); return 0; } void TAO_AV_RTCP_Callback::schedule (int ms) { this->timeout_ = ms; } int TAO_AV_RTCP_Callback::handle_start (void) { // /* * schedule a timer for our first report using half the * min rtcp interval. This gives us some time before * our first report to learn about other sources so our * next report interval will account for them. The avg * rtcp size was initialized to 128 bytes which is * conservative (it assumes everyone else is generating * SRs instead of RRs). */ double rint = this->state_->rtcp_avg_size_ * this->state_->rtcp_inv_bw_; if (rint < RTCP_MIN_RPT_TIME / 2. * 1000.) rint = RTCP_MIN_RPT_TIME / 2. * 1000.; this->state_->rint_ = rint; this->timeout_ = int(TAO_AV_RTCP::fmod(double(ACE_OS::rand ()), rint) + rint * .5 + .5); return 0; } int TAO_AV_RTCP_Callback::handle_stop (void) { return 0; } int TAO_AV_RTCP_Callback::handle_timeout (void * /*arg*/) { // Here we do the send_report. TAO_AV_RTCP::send_report (0, this->protocol_object_, this->source_manager_, this->state_, this); return 0; } void TAO_AV_RTCP_Callback::get_timeout (ACE_Time_Value *&tv, void *& /*arg*/) { // Here we do the RTCP timeout calculation. ACE_NEW (tv, ACE_Time_Value (0,this->timeout_*ACE_ONE_SECOND_IN_MSECS)); } int TAO_AV_RTCP_Callback::handle_destroy (void) { // Here we do the send_bye. TAO_AV_RTCP::send_report (1, this->protocol_object_, this->source_manager_, this->state_, this); return 0; } int TAO_AV_RTCP_Callback::receive_frame (ACE_Message_Block *frame, TAO_AV_frame_info *, const ACE_Addr &peer_address) { char *buf = frame->rd_ptr (); TAO_AV_RTP::rtphdr *rh = (TAO_AV_RTP::rtphdr *)buf; frame->rd_ptr (sizeof (TAO_AV_RTP::rtphdr)); int result = this->demux (rh, frame, peer_address); frame->rd_ptr (buf); if (result < 0) return result; return 0; } int TAO_AV_RTCP_Callback::receive_control_frame (ACE_Message_Block *frame, const ACE_Addr &peer_address) { // Here we do the processing of the RTCP frames. TAO_AV_RTCP::rtcphdr header; int result = TAO_AV_RTCP::handle_input (frame, peer_address, header, this->source_manager_, this->state_); if (result < 0) ACE_ERROR_RETURN ((LM_ERROR,"TAO_AV_RTCP::handle_input failed\n"),-1); return 0; } int TAO_AV_RTCP_Callback::demux (TAO_AV_RTP::rtphdr* rh, ACE_Message_Block *data, const ACE_Addr &address) { char *bp = data->rd_ptr (); int cc = data->length (); if (cc < 0) { ++this->state_->nrunt_; return -1; } ACE_UINT32 srcid = rh->rh_ssrc; int flags = ntohs (rh->rh_flags); if ( (flags & RTP_X) != 0) { /* * the minimal-control audio/video profile * explicitly forbids extensions */ ++this->state_->badext_; return -1; } // @@Naga:Maybe the framework itself could check for formats making use of // the property service to query the formats supported for this flow. /* * Check for illegal payload types. Most likely this is * a session packet arriving on the data port. */ // int fmt = flags & 0x7f; // if (!check_format (fmt)) // { // ++state->badfmt_; // return; // } u_long addr = address.hash (); ACE_UINT16 seqno = ntohs (rh->rh_seqno); TAO_AV_Source* s = this->source_manager_->demux (srcid, addr, seqno); if (s == 0) /* * Takes a pair of validated packets before we will * believe the source. This prevents a runaway * allocation of Source data structures for a * stream of garbage packets. */ return -1; ACE_Time_Value now = ACE_OS::gettimeofday (); s->lts_data (now); s->sts_data (rh->rh_ts); int cnt = (flags >> 8) & 0xf; if (cnt > 0) { u_char* nh = (u_char*)rh + (cnt << 2); while (--cnt >= 0) { ACE_UINT32 csrc = * (ACE_UINT32*)bp; bp += 4; TAO_AV_Source* cs = this->source_manager_->lookup (csrc, srcid, addr); cs->lts_data (now); cs->action (); } /*XXX move header up so it's contiguous with data*/ TAO_AV_RTP::rtphdr hdr = *rh; rh = (TAO_AV_RTP::rtphdr*)nh; *rh = hdr; } else s->action (); return 0; /* * This is a data packet. If the source needs activation, * or the packet format has changed, deal with this. * Then, hand the packet off to the packet handler. * XXX might want to be careful about flip-flopping * here when format changes due to misordered packets * (easy solution -- keep rtp seqno of last fmt change). */ } ACE_FACTORY_DEFINE (AV, TAO_AV_RTCP_Flow_Factory) ACE_STATIC_SVC_DEFINE (TAO_AV_RTCP_Flow_Factory, ACE_TEXT ("RTCP_Flow_Factory"), ACE_SVC_OBJ_T, &ACE_SVC_NAME (TAO_AV_RTCP_Flow_Factory), ACE_Service_Type::DELETE_THIS | ACE_Service_Type::DELETE_OBJ, 0)
29.298947
98
0.553783
tharindusathis
3dec393e5efd50be03aacbbe26b5c971f80bae78
4,382
hpp
C++
include/list/doublelist.hpp
Dacilndak/ds
edae4a057912946329066338bada4deea8d723ab
[ "MIT" ]
null
null
null
include/list/doublelist.hpp
Dacilndak/ds
edae4a057912946329066338bada4deea8d723ab
[ "MIT" ]
null
null
null
include/list/doublelist.hpp
Dacilndak/ds
edae4a057912946329066338bada4deea8d723ab
[ "MIT" ]
null
null
null
#ifndef _MPH_DOUBLE_LIST_H_ #define _MPH_DOUBLE_LIST_H_ #include <iostream> #include "node.hpp" template <typename T> class DoubleList { public: Node<T> * fwalk(Node<T> * start, int dist) const; Node<T> * rwalk(Node<T> * start, int dist) const; Node<T> * head; Node<T> * tail; public: DoubleList(); DoubleList(T data); DoubleList(T * data, int len); DoubleList(DoubleList<T> * dl); ~DoubleList(); Node<T> * begin() const { return this->head; } Node<T> * end() const { return this->tail; } T insert(int pos, T data) { return this->add(pos, data); } T add(int pos, T data); T remove(int pos); T prepend(T data); T append(T data); void clear(); T at(int pos) const; T get(int pos) const; T set(int pos, T data); int size() const; }; template <typename T> DoubleList<T>::DoubleList(DoubleList<T> * dl) { for (int i = 0; i < dl->size(); i++) { this->append(dl->at(i)); } } template <typename T> Node<T> * DoubleList<T>::fwalk(Node<T> * start, int dist) const { Node<T> * tmp = start; for (int i = 0; i < dist; i++) { tmp = tmp->next; if (tmp->next == NULL) { return tmp; } } return tmp; } template <typename T> Node<T> * DoubleList<T>::rwalk(Node<T> * start, int dist) const { Node<T> * tmp = start; for (int i = 0; i < dist; i++) { tmp = tmp->prev; if (tmp->prev == NULL) { return tmp; } } return tmp; } template <typename T> DoubleList<T>::DoubleList() { this->head = NULL; this->tail = NULL; } template <typename T> DoubleList<T>::DoubleList(T data) { this->head = new Node<T>(data, NULL, NULL); this->tail = this->head; } template <typename T> DoubleList<T>::DoubleList(T * data, int len) { for (int i = 0; i < len; i++) { this->append(*(data + i)); } } template <typename T> DoubleList<T>::~DoubleList() { this->clear(); } template <typename T> T DoubleList<T>::add(int pos, T data) { if (pos > this->size()) { this->append(data); return data; } if (pos < 0) { this->prepend(data); return data; } Node<T> * tmp = fwalk(head, pos); Node<T> * new_node = new Node<T>(data, tmp->prev, tmp); tmp->prev = new_node; new_node->prev->next = new_node; return data; } template <typename T> T DoubleList<T>::remove(int pos) { Node<T> * tmp = fwalk(head, pos); if (tmp != this->head) { tmp->prev->next = tmp->next; } else { this->head = tmp->next; } if (tmp != this->tail) { tmp->next->prev = tmp->prev; } else { this->tail = tmp->prev; } T data = tmp->data; delete tmp; return data; } template <typename T> T DoubleList<T>::append(T data) { Node<T> * tmp = new Node<T>(data, this->tail, NULL); this->tail = tmp; if (this->head == NULL) { this->head = tmp; } else { tmp->prev->next = tmp; } return data; } template <typename T> T DoubleList<T>::prepend(T data) { Node<T> * tmp = new Node<T>(data, NULL, this->head); this->head = tmp; if (this->tail == NULL) { this->tail = tmp; } else { tmp->next->prev = tmp; } return data; } template <typename T> void DoubleList<T>::clear() { Node<T> * tmp; while (head != NULL) { tmp = head; head = tmp->next; delete tmp; } tail = head; } template <typename T> T DoubleList<T>::at(int pos) const { if (pos < 0) { return (T)(NULL); } return fwalk(head, pos)->data; } template <typename T> T DoubleList<T>::get(int pos) const { if (pos < 0) { return (T)(NULL); } return fwalk(head, pos)->data; } template <typename T> T DoubleList<T>::set(int pos, T data) { Node<T> * tmp = fwalk(head, pos); tmp->data = data; return data; } template <typename T> int DoubleList<T>::size() const { if (head == NULL) { return 0; } else if (head == tail) { return 1; } else if (head->next == tail) { return 2; } else { Node<T> * tmp = head; int count = 1; while (tmp->next != NULL) { tmp = tmp->next; count++; } return count; } } template<typename T> std::ostream & operator<<(std::ostream & out, const DoubleList<T> & l) { Node<T> * tmp = l.begin(); if (tmp == NULL) { out << "< empty >"; return out; } while (tmp != l.end()) { out << tmp->data << " <-> "; tmp = tmp->next; } out << l.end()->data; return out; } template<typename T> std::istream & operator>>(std::istream & in, DoubleList<T> & l) { T tmp; in >> tmp; l.append(tmp); return in; } #endif
20.966507
72
0.580785
Dacilndak
3dec8082c3a6bd13f612a2a986484d874d20c4c6
228
cpp
C++
Eva/Config.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
Eva/Config.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
Eva/Config.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
#include "Config.h" CONFIG Config; CONFIG DefaultConfig; const char * Config_directory = "configs"; const char * Config_file = "Eva.bin"; byte * Config_addr = (byte*)&Config; uint32 Config_size = (uint32)sizeof(CONFIG);
20.727273
44
0.714912
wangxh1007
3decb2760968d32cea50957064b14af42ff246fd
6,232
cxx
C++
main/accessibility/source/standard/vclxaccessiblemenubar.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/accessibility/source/standard/vclxaccessiblemenubar.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/accessibility/source/standard/vclxaccessiblemenubar.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_accessibility.hxx" #include <accessibility/standard/vclxaccessiblemenubar.hxx> #include <com/sun/star/accessibility/AccessibleRole.hpp> #include <vcl/svapp.hxx> #include <vcl/window.hxx> #include <vcl/menu.hxx> using namespace ::com::sun::star::accessibility; using namespace ::com::sun::star::uno; using namespace ::com::sun::star; using namespace ::comphelper; // ----------------------------------------------------------------------------- // class VCLXAccessibleMenuBar // ----------------------------------------------------------------------------- VCLXAccessibleMenuBar::VCLXAccessibleMenuBar( Menu* pMenu ) :OAccessibleMenuComponent( pMenu ) { if ( pMenu ) { m_pWindow = pMenu->GetWindow(); if ( m_pWindow ) m_pWindow->AddEventListener( LINK( this, VCLXAccessibleMenuBar, WindowEventListener ) ); } } // ----------------------------------------------------------------------------- VCLXAccessibleMenuBar::~VCLXAccessibleMenuBar() { if ( m_pWindow ) m_pWindow->RemoveEventListener( LINK( this, VCLXAccessibleMenuBar, WindowEventListener ) ); } // ----------------------------------------------------------------------------- sal_Bool VCLXAccessibleMenuBar::IsFocused() { sal_Bool bFocused = sal_False; if ( m_pWindow && m_pWindow->HasFocus() && !IsChildHighlighted() ) bFocused = sal_True; return bFocused; } // ----------------------------------------------------------------------------- IMPL_LINK( VCLXAccessibleMenuBar, WindowEventListener, VclSimpleEvent*, pEvent ) { DBG_ASSERT( pEvent && pEvent->ISA( VclWindowEvent ), "VCLXAccessibleMenuBar::WindowEventListener: unknown window event!" ); if ( pEvent && pEvent->ISA( VclWindowEvent ) ) { DBG_ASSERT( ((VclWindowEvent*)pEvent)->GetWindow(), "VCLXAccessibleMenuBar::WindowEventListener: no window!" ); if ( !((VclWindowEvent*)pEvent)->GetWindow()->IsAccessibilityEventsSuppressed() || ( pEvent->GetId() == VCLEVENT_OBJECT_DYING ) ) { ProcessWindowEvent( *(VclWindowEvent*)pEvent ); } } return 0; } // ----------------------------------------------------------------------------- void VCLXAccessibleMenuBar::ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ) { switch ( rVclWindowEvent.GetId() ) { case VCLEVENT_WINDOW_GETFOCUS: case VCLEVENT_WINDOW_LOSEFOCUS: { SetFocused( rVclWindowEvent.GetId() == VCLEVENT_WINDOW_GETFOCUS ); } break; case VCLEVENT_OBJECT_DYING: { if ( m_pWindow ) { m_pWindow->RemoveEventListener( LINK( this, VCLXAccessibleMenuBar, WindowEventListener ) ); m_pWindow = NULL; } } break; default: { } break; } } // ----------------------------------------------------------------------------- // XComponent // ----------------------------------------------------------------------------- void VCLXAccessibleMenuBar::disposing() { OAccessibleMenuComponent::disposing(); if ( m_pWindow ) { m_pWindow->RemoveEventListener( LINK( this, VCLXAccessibleMenuBar, WindowEventListener ) ); m_pWindow = NULL; } } // ----------------------------------------------------------------------------- // XServiceInfo // ----------------------------------------------------------------------------- ::rtl::OUString VCLXAccessibleMenuBar::getImplementationName() throw (RuntimeException) { return ::rtl::OUString::createFromAscii( "com.sun.star.comp.toolkit.AccessibleMenuBar" ); } // ----------------------------------------------------------------------------- Sequence< ::rtl::OUString > VCLXAccessibleMenuBar::getSupportedServiceNames() throw (RuntimeException) { Sequence< ::rtl::OUString > aNames(1); aNames[0] = ::rtl::OUString::createFromAscii( "com.sun.star.awt.AccessibleMenuBar" ); return aNames; } // ----------------------------------------------------------------------------- // XAccessibleContext // ----------------------------------------------------------------------------- sal_Int32 VCLXAccessibleMenuBar::getAccessibleIndexInParent( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); sal_Int32 nIndexInParent = -1; if ( m_pMenu ) { Window* pWindow = m_pMenu->GetWindow(); if ( pWindow ) { Window* pParent = pWindow->GetAccessibleParentWindow(); if ( pParent ) { for ( sal_uInt16 n = pParent->GetAccessibleChildWindowCount(); n; ) { Window* pChild = pParent->GetAccessibleChildWindow( --n ); if ( pChild == pWindow ) { nIndexInParent = n; break; } } } } } return nIndexInParent; } // ----------------------------------------------------------------------------- sal_Int16 VCLXAccessibleMenuBar::getAccessibleRole( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); return AccessibleRole::MENU_BAR; } // ----------------------------------------------------------------------------- // XAccessibleExtendedComponent // ----------------------------------------------------------------------------- sal_Int32 VCLXAccessibleMenuBar::getBackground( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); return Application::GetSettings().GetStyleSettings().GetMenuBarColor().GetColor(); } // -----------------------------------------------------------------------------
29.961538
131
0.55568
Alan-love
3dee87132f8f4332eeb1b1e72026fdc656db0ce2
4,311
cpp
C++
tests/src_test/config_test/config_test.cpp
dleliuhin/CV_Labs
cb8282f0e48cd022c07dafdd106f979ff679bee7
[ "DOC" ]
null
null
null
tests/src_test/config_test/config_test.cpp
dleliuhin/CV_Labs
cb8282f0e48cd022c07dafdd106f979ff679bee7
[ "DOC" ]
null
null
null
tests/src_test/config_test/config_test.cpp
dleliuhin/CV_Labs
cb8282f0e48cd022c07dafdd106f979ff679bee7
[ "DOC" ]
null
null
null
/*! \file config_test.cpp * \brief ConfigTest class implementation. * \authors Dmitrii Leliuhin * \date July 2020 */ //======================================================================================= #include "config_test.h" #include "config.h" #include <filesystem> //======================================================================================= /*! \test \fn void check_default_settings( const Config& conf ) * \brief check_default_settings * \param conf Internal Config. */ void check_default_settings( const Config& conf ) { ASSERT_EQ( "main", conf.main.str ); ASSERT_EQ( false, conf.main.debug ); ASSERT_EQ( 0, conf.main.rotate ); ASSERT_EQ( "ipc", conf.receive.target ); ASSERT_EQ( "", conf.receive.channel.prefix ); ASSERT_EQ( "", conf.receive.channel.name ); ASSERT_EQ( "", conf.receive.channel.full ); ASSERT_EQ( "receive", conf.receive.str ); ASSERT_EQ( true, conf.logs.need_trace ); ASSERT_EQ( true, conf.logs.need_shared ); ASSERT_EQ( "$$FULL_APP.log", conf.logs.shared_name ); ASSERT_EQ( true, conf.logs.need_leveled ); ASSERT_EQ( "$$APP_PATH/logs", conf.logs.leveled_path ); ASSERT_EQ( 1e6, conf.logs.file_sizes ); ASSERT_EQ( log_rotates, conf.logs.rotates ); ASSERT_EQ( "logs", conf.logs.str ); } //======================================================================================= //======================================================================================= /*! \test TEST( ConfigTest, test_structs ) * \brief Default Config structs. */ TEST( ConfigTest, test_structs ) { Config conf; check_default_settings( conf ); } //======================================================================================= /*! \test TEST( ConfigTest, test_capture ) * \brief Capture internal vsettings. */ TEST( ConfigTest, test_capture ) { Config conf; conf.capture( Config().by_default() ); check_default_settings( conf ); } //======================================================================================= /*! \test TEST( ConfigTest, test_by_default ) * \brief Default Config vsettings. */ TEST( ConfigTest, test_by_default ) { auto settings = Config::by_default(); ASSERT_EQ( "false", settings.subgroup( Config().main.str ).get( "debug" ) ); ASSERT_EQ( 0, std::stoi( settings.subgroup( Config().main.str ).get( "rotate" ) ) ); ASSERT_EQ( "ipc", settings.subgroup( Config().receive.str ).get( "target" ) ); ASSERT_EQ( "", settings.subgroup( Config().receive.str ).get( "prefix" ) ); ASSERT_EQ( "", settings.subgroup( Config().receive.str ).get( "name" ) ); ASSERT_EQ( "true", settings.subgroup( Config().logs.str ).get( "need_trace" ) ); ASSERT_EQ( "true", settings.subgroup( Config().logs.str ).get( "need_shared" ) ); ASSERT_EQ( "$$FULL_APP.log", settings.subgroup( Config().logs.str ).get( "shared_name" ) ); ASSERT_EQ( "true", settings.subgroup( Config().logs.str ).get( "need_leveled" ) ); ASSERT_EQ( "$$APP_PATH/logs", settings.subgroup( Config().logs.str ).get( "leveled_path" ) ); ASSERT_EQ( 1e6, std::stoi( settings.subgroup( Config().logs.str ).get( "file_sizes" ) ) ); ASSERT_EQ( 3, std::stoi( settings.subgroup( Config().logs.str ).get( "rotates" ) ) ); } //======================================================================================= /*! \test TEST( ConfigTest, test_setup ) * \brief Existing log files & dirs; */ TEST( ConfigTest, test_setup ) { Config conf; { conf.logs.need_trace = false; conf.logs.setup(); ASSERT_FALSE( std::filesystem::exists( "$$FULL_APP.log" ) ); } { conf.logs.need_trace = true; conf.logs.setup(); ASSERT_TRUE( std::filesystem::exists( "$$FULL_APP.log" ) ); ASSERT_TRUE( std::filesystem::exists( "$$APP_PATH" ) ); ASSERT_TRUE( std::filesystem::is_directory( "$$APP_PATH" ) ); } } //=======================================================================================
37.486957
90
0.4971
dleliuhin
3df0e55ffae6050d4fe6cdc37969f57a6834a1cd
960
hpp
C++
adobe/config/select_compiler.hpp
ilelann/adobe_source_libraries
82224d13335398dfebfc77addabab28c4296ecba
[ "BSL-1.0" ]
null
null
null
adobe/config/select_compiler.hpp
ilelann/adobe_source_libraries
82224d13335398dfebfc77addabab28c4296ecba
[ "BSL-1.0" ]
null
null
null
adobe/config/select_compiler.hpp
ilelann/adobe_source_libraries
82224d13335398dfebfc77addabab28c4296ecba
[ "BSL-1.0" ]
1
2020-06-18T12:25:12.000Z
2020-06-18T12:25:12.000Z
/* Copyright 2013 Adobe Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /*************************************************************************************************/ #ifndef ADOBE_CONFIG_SELECT_COMPILER_HPP #define ADOBE_CONFIG_SELECT_COMPILER_HPP /*************************************************************************************************/ #if defined __GNUC__ // GNU C++: (including Darwin) #include <adobe/config/compiler/gcc.hpp> #elif defined _MSC_VER // Must remain the last #elif since some other vendors (Metrowerks, for // example) also #define _MSC_VER #include <adobe/config/compiler/visualc.hpp> #endif /*************************************************************************************************/ #endif /*************************************************************************************************/
33.103448
99
0.442708
ilelann
3df35c816015d8031bd2df0f2fcc3725e7346b53
3,532
cpp
C++
tests/dcm_tests_common.cpp
skybaboon/dailycashmanager
0b022cc230a8738d5d27a799728da187e22f17f8
[ "Apache-2.0" ]
4
2016-07-05T07:42:07.000Z
2020-07-15T15:27:22.000Z
tests/dcm_tests_common.cpp
skybaboon/dailycashmanager
0b022cc230a8738d5d27a799728da187e22f17f8
[ "Apache-2.0" ]
1
2020-05-07T20:58:21.000Z
2020-05-07T20:58:21.000Z
tests/dcm_tests_common.cpp
skybaboon/dailycashmanager
0b022cc230a8738d5d27a799728da187e22f17f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2013 Matthew Harvey * * 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 "dcm_tests_common.hpp" #include "account.hpp" #include "account_type.hpp" #include "commodity.hpp" #include "dcm_database_connection.hpp" #include "visibility.hpp" #include <boost/filesystem.hpp> #include <jewel/decimal.hpp> #include <jewel/assert.hpp> #include <sqloxx/handle.hpp> #include <cstdlib> #include <iostream> using jewel::Decimal; using sqloxx::Handle; using std::abort; using std::cout; using std::cerr; using std::endl; namespace filesystem = boost::filesystem; namespace dcm { namespace test { bool file_exists(filesystem::path const& filepath) { return filesystem::exists ( filesystem::status(filepath) ); } void abort_if_exists(filesystem::path const& filepath) { if (file_exists(filepath)) { cerr << "File named \"" << filepath.string() << "\" already " << "exists. Test aborted." << endl; abort(); } return; } void setup_test_commodities(DcmDatabaseConnection& dbc) { Handle<Commodity> const australian_dollars(dbc); australian_dollars->set_abbreviation("AUD"); australian_dollars->set_name("Australian dollars"); australian_dollars->set_description("Australian currency in dollars"); australian_dollars->set_precision(2); australian_dollars->set_multiplier_to_base(Decimal(1, 0)); australian_dollars->save(); Handle<Commodity> const us_dollars(dbc); us_dollars->set_abbreviation("USD"); us_dollars->set_name("US dollars"); us_dollars->set_description("United States currency in dollars"); us_dollars->set_precision(2); us_dollars->set_multiplier_to_base(Decimal("0.95")); us_dollars->save(); return; } void setup_test_accounts(DcmDatabaseConnection& dbc) { Handle<Account> const cash(dbc); cash->set_account_type(AccountType::asset); cash->set_name("cash"); cash->set_commodity ( Handle<Commodity>(dbc, Commodity::id_for_abbreviation(dbc, "AUD")) ); cash->set_description("notes and coins"); cash->set_visibility(Visibility::visible); cash->save(); Handle<Account> const food(dbc); food->set_account_type(AccountType::expense); food->set_name("food"); food->set_commodity ( Handle<Commodity>(dbc, Commodity::id_for_abbreviation(dbc, "AUD")) ); food->set_description("food and drink"); food->set_visibility(Visibility::visible); food->save(); return; } TestFixture::TestFixture(): db_filepath("Testfile_827787293.db"), pdbc(0) { pdbc = new DcmDatabaseConnection; abort_if_exists(db_filepath); pdbc->open(db_filepath); pdbc->set_caching_level(10); setup_test_commodities(*pdbc); setup_test_accounts(*pdbc); JEWEL_ASSERT (pdbc->is_valid()); } TestFixture::~TestFixture() { JEWEL_ASSERT (pdbc->is_valid()); delete pdbc; filesystem::remove(db_filepath); JEWEL_ASSERT (!file_exists(db_filepath)); } } // namespace test } // namespace dcm
26.961832
75
0.7047
skybaboon
3df528e20f8991878d477ef35b8241d9a7f12e2a
505
cpp
C++
pg_answer/602b44e70a2a44769de13a38a02e96d0.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
8
2019-10-09T14:33:42.000Z
2020-12-03T00:49:29.000Z
pg_answer/602b44e70a2a44769de13a38a02e96d0.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
pg_answer/602b44e70a2a44769de13a38a02e96d0.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
#include <iostream> #include <vector> int ans; std::vector<int> v; void dfs(int i, int m) { if (m == 0) { ans++; return; } if (i == v.size()) return; dfs(i + 1, m - v[i]); dfs(i + 1, m); } int main() { while (true) { int n; std::cin >> n; v.push_back(n); if (std::cin.get() == '\n') break; } int m; while (std::cin >> m, m != 0) { ans = 0; dfs(0, m); std::cout << ans << std::endl; } }
16.290323
42
0.4
Guyutongxue
3df66003e156fde40e2b63dd95f57d4bfd92e27a
5,923
cc
C++
cplusplus/LearnGC/NurserySweep/nursery_sweep.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
22
2015-05-18T07:04:36.000Z
2021-08-02T03:01:43.000Z
cplusplus/LearnGC/NurserySweep/nursery_sweep.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
1
2017-08-31T22:13:57.000Z
2017-09-05T15:00:25.000Z
cplusplus/LearnGC/NurserySweep/nursery_sweep.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
6
2015-06-06T07:16:12.000Z
2021-07-06T13:45:56.000Z
// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <iostream> #include <Chaos/Base/Types.h> #include "object.h" #include "nursery_sweep.h" namespace gc { void NurserySweep::inc_nursery(BaseObject* ref) { if (nursery_.find(ref) != nursery_.end()) record_objects_.push_back(ref); } void NurserySweep::dec_nursery(BaseObject* ref) { if (nursery_.find(ref) != nursery_.end()) record_objects_.remove(ref); } void NurserySweep::write_pair(BaseObject* p, BaseObject* obj, bool is_first) { auto* pair = Chaos::down_cast<Pair*>(p); if (nursery_.find(p) == nursery_.end()) { inc_nursery(obj); if (is_first) { dec_nursery(pair->first()); pair->set_first(obj); } else { dec_nursery(pair->second()); pair->set_second(obj); } } } BaseObject* NurserySweep::create_object(std::uint8_t type) { auto alloc_fn = [this](std::uint8_t type) -> BaseObject* { if (nursery_.size() >= kMaxObjects || objects_.size() >= kMaxObjects) return nullptr; if (type == MemoryHeader::INT) return new Int(); else if (type == MemoryHeader::PAIR) return new Pair(); return nullptr; }; auto* ref = alloc_fn(type); if (ref == nullptr) { collect_nursery(); ref = alloc_fn(type); if (ref == nullptr) { collect(); ref = alloc_fn(type); CHAOS_CHECK(ref != nullptr, "out of memory"); } } nursery_.insert(ref); return ref; } void NurserySweep::roots_nursery(void) { for (auto* obj : roots_) { if (nursery_.find(obj) != nursery_.end()) record_objects_.push_back(obj); } } void NurserySweep::scan_nursery(void) { while (!record_objects_.empty()) { auto* obj = record_objects_.back(); record_objects_.pop_back(); if (obj->inc_ref() == 1 && obj->is_pair()) { auto append_fn = [this](BaseObject* obj) { if (obj != nullptr && nursery_.find(obj) != nursery_.end()) record_objects_.push_back(obj); }; append_fn(Chaos::down_cast<Pair*>(obj)->first()); append_fn(Chaos::down_cast<Pair*>(obj)->second()); } } } void NurserySweep::sweep_nursery(void) { for (auto* obj : nursery_) { if (obj->ref() == 0) { delete obj; } else { obj->set_ref(0); objects_.push_back(obj); } } nursery_.clear(); } void NurserySweep::roots_tracing(std::stack<BaseObject*>& trace_objects) { for (auto* obj : roots_) trace_objects.push(obj); } void NurserySweep::scan_tracing(std::stack<BaseObject*>& trace_objects) { while (!trace_objects.empty()) { auto* obj = trace_objects.top(); trace_objects.pop(); if (obj->inc_ref() == 1 && obj->is_pair()) { auto append_fn = [&trace_objects](BaseObject* o) { if (o != nullptr) trace_objects.push(o); }; append_fn(Chaos::down_cast<Pair*>(obj)->first()); append_fn(Chaos::down_cast<Pair*>(obj)->second()); } } } void NurserySweep::sweep_tracing(void) { for (auto it = objects_.begin(); it != objects_.end();) { if ((*it)->ref() == 0) { delete *it; objects_.erase(it++); } else { (*it)->set_ref(0); ++it; } } } NurserySweep& NurserySweep::get_instance(void) { static NurserySweep ins; return ins; } void NurserySweep::collect_nursery(void) { auto old_count = nursery_.size(); roots_nursery(); scan_nursery(); sweep_nursery(); std::cout << "[" << old_count - nursery_.size() << "] nursery objects collected, " << "[" << nursery_.size() << "] nursery objects remaining. " << "[" << objects_.size() << "] objects remaining." << std::endl; } void NurserySweep::collect(void) { auto old_count = objects_.size(); std::stack<BaseObject*> objects; roots_tracing(objects); scan_tracing(objects); sweep_tracing(); std::cout << "[" << nursery_.size() << "] nursery objects remaining. " << "[" << old_count - objects_.size() << "] objects collected, " << "[" << objects_.size() << "] objects remaining." << std::endl; } BaseObject* NurserySweep::put_in(int value) { auto* obj = Chaos::down_cast<Int*>(create_object(MemoryHeader::INT)); obj->set_value(value); roots_.push_back(obj); return obj; } BaseObject* NurserySweep::put_in(BaseObject* first, BaseObject* second) { auto* obj = create_object(MemoryHeader::PAIR); if (first != nullptr) write_pair(obj, first, true); if (second != nullptr) write_pair(obj, second, false); roots_.push_back(obj); return obj; } BaseObject* NurserySweep::fetch_out(void) { auto* obj = roots_.back(); roots_.pop_back(); return obj; } }
27.548837
78
0.652879
ASMlover
3df7776b3e580641c14fb31839fa5ebcbb135928
4,687
cpp
C++
security/wxMD5.cpp
mikewolfli/wfouttoexcel
6818774639b464f16c3e402af9c9f06634402957
[ "Unlicense" ]
3
2016-05-30T05:39:52.000Z
2017-11-10T07:26:53.000Z
security/wxMD5.cpp
mikewolfli/wfouttoexcel
6818774639b464f16c3e402af9c9f06634402957
[ "Unlicense" ]
null
null
null
security/wxMD5.cpp
mikewolfli/wfouttoexcel
6818774639b464f16c3e402af9c9f06634402957
[ "Unlicense" ]
1
2020-01-02T01:05:01.000Z
2020-01-02T01:05:01.000Z
////////////////////////////////////////////////////////////////////// // Name: wxMD5.cpp // Purpose: wxMD5 Class // Author: Casey O'Donnell // Creator: See Internet RFC 1321 // Copyright (C) 1991 - 1992 // RSA Data Security, Inc. Created 1991 // Created: 07/02/2003 // Last modified: 07/02/2003 // Licence: wxWindows license ////////////////////////////////////////////////////////////////////// // wxMD5.cpp: implementation of the wxMD5 class. // ////////////////////////////////////////////////////////////////////// #ifdef __GNUG__ #pragma implementation "wxMD5.h" #endif // for compilers that support precompilation, includes "wx.h" #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others #ifndef WX_PRECOMP #include "wx/wx.h" #include "wx/file.h" #endif #include "md5.h" #include "wxMD5.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// wxMD5::wxMD5() { m_bCalculatedDigest = false; m_pszDigestString[32] = '\0'; m_isfile = FALSE; } wxMD5::wxMD5(const wxString& szText) { m_bCalculatedDigest = false; m_pszDigestString[32] = '\0'; m_szText = szText; m_isfile = FALSE; } wxMD5::wxMD5(const wxFileName& szfile) { m_bCalculatedDigest = false; m_pszDigestString[32] = '\0'; m_file = szfile; m_isfile = TRUE; } wxMD5::~wxMD5() { } ////////////////////////////////////////////////////////////////////// // Other Methods ////////////////////////////////////////////////////////////////////// void wxMD5::SetText(const wxString& szText) { m_bCalculatedDigest = false; m_szText = szText; m_isfile = FALSE; } void wxMD5::SetFile(const wxFileName& szfile) { m_bCalculatedDigest = false; m_file = szfile; m_isfile = TRUE; } const wxString wxMD5::GetDigest(bool mainthread) { if (m_isfile) { if(m_bCalculatedDigest) { const wxString szRetVal = m_pszDigestString; return szRetVal; } else if(!m_file.FileExists()) { return wxEmptyString; } else { MD5_CTX md5Context; MD5Init(&md5Context); wxFile md5file(m_file.GetFullPath(), wxFile::read); unsigned char buffer[16384]; unsigned int i = 1; while (i >0) { i = md5file.Read(buffer,16384); MD5Update(&md5Context, buffer, (unsigned) i); if (mainthread) wxYield(); } MD5Final(m_arrDigest, &md5Context); wxString szRetVal; unsigned int j=0; for (i = 0; i < sizeof m_arrDigest; i++) { szRetVal << wxString::Format(wxT("%02X"),m_arrDigest[i]); m_pszDigestString[j] = szRetVal.GetChar(j); m_pszDigestString[j+1] = szRetVal.GetChar(j+1); j+=2; } return szRetVal; } } else { if(m_bCalculatedDigest) { const wxString szRetVal = m_pszDigestString; return szRetVal; } else if(m_szText.IsEmpty()) { return wxEmptyString; } else { MD5_CTX md5Context; MD5Init(&md5Context); char *text = new char[m_szText.Len()+1]; unsigned int i; for (i=0; i < (m_szText.Len());i++) text[i] = m_szText.GetChar(i); text[i] = '\0'; MD5Update(&md5Context, (unsigned char*)(text), strlen(text)); MD5Final(m_arrDigest, &md5Context); wxString szRetVal; unsigned int j=0; for (i = 0; i < sizeof m_arrDigest; i++) { szRetVal << wxString::Format(wxT("%02X"),m_arrDigest[i]); m_pszDigestString[j] = szRetVal.GetChar(j); m_pszDigestString[j+1] = szRetVal.GetChar(j+1); j+=2; } return szRetVal; } } } ////////////////////////////////////////////////////////////////////// // Static Methods ////////////////////////////////////////////////////////////////////// const wxString wxMD5::GetDigest(const wxString& szText) { wxMD5 md5(szText); return md5.GetDigest(); } const wxString wxMD5::GetDigest(const wxFileName& szfile) { wxMD5 md5(szfile); return md5.GetDigest(); }
25.895028
73
0.459996
mikewolfli
3df77a6245cd9674970ecbdfdc58cc8e5bb6f24f
832
hpp
C++
src/Project6/SymbolsTable.hpp
HSU-F20-CS243/p06-starter
108791397c0454575f72d6787e0214417e0f5ec2
[ "Apache-2.0" ]
null
null
null
src/Project6/SymbolsTable.hpp
HSU-F20-CS243/p06-starter
108791397c0454575f72d6787e0214417e0f5ec2
[ "Apache-2.0" ]
null
null
null
src/Project6/SymbolsTable.hpp
HSU-F20-CS243/p06-starter
108791397c0454575f72d6787e0214417e0f5ec2
[ "Apache-2.0" ]
null
null
null
#pragma once #include <unordered_map> #include <string> using std::unordered_map; using std::string; using std::to_string; class SymbolsTable { private: unordered_map<string, int> _lookup_table; int _address_counter = 16; public: SymbolsTable() { //predefined symbols (p. 110 in book) _lookup_table["SP"] = 0; _lookup_table["LCL"] = 1; _lookup_table["ARG"] = 2; _lookup_table["THIS"] = 3; _lookup_table["THAT"] = 4; _lookup_table["SCREEN"] = 16384; _lookup_table["KBD"] = 24576; for (int i = 0; i < 16; i++) { string reg = "R" + to_string(i); _lookup_table[reg] = i; } } int& operator[](string key) { //key not found, add new entry if (_lookup_table.find(key) == _lookup_table.end()) { _lookup_table[key] = _address_counter; _address_counter++; } return _lookup_table[key]; } };
20.292683
53
0.661058
HSU-F20-CS243
3dfb9a4cb4df21161cc102fcdcbaa3027a9b4430
1,141
cpp
C++
mainAP.cpp
julioofilho/AP1
0d33c2d08763e752935f11bb111a2a03223ce78c
[ "MIT" ]
null
null
null
mainAP.cpp
julioofilho/AP1
0d33c2d08763e752935f11bb111a2a03223ce78c
[ "MIT" ]
null
null
null
mainAP.cpp
julioofilho/AP1
0d33c2d08763e752935f11bb111a2a03223ce78c
[ "MIT" ]
null
null
null
#define _GLIBCXX_USE_CXX11_ABI 0 #include <iostream> #include <vector> #include <string> #include <iterator> #include <algorithm> #include "gerenciar.h" #include "automovel.h" #include "concessionaria.h" using namespace std; gerenciar listaConc; int automovel::numeroCarros = 0; int concessionaria::numeroConc = 0; int main (int argc, char const *argv[]){ int x = -1; while (x!= 0){ cout << endl << "++++++++++++++++++++++++++++++++"<<endl << endl << "Escolha a opção desejada"<<endl << "Digite 1 - Adicionar Automóvel "<<endl << "Digite 2 - Criar Concessionária"<< endl << "Digite 3 - Lista de Automoveis"<< endl << "Digite 0 - Sair"<< endl << "++++++++++++++++++++++++++++++++"<<endl << endl<< "Digite sua Escolha: " <<endl; cin >> x; switch (x){ case 1: listaConc.cadastrarCarro(); break; case 2: listaConc.criarconcessionaria (); break; case 3: listaConc.estoques(); case 0: cout<<endl<< "Ate mais!" << endl; return 0; default: cin.clear(); cin.ignore(200,'\n'); cout << endl << "Entrada inválida, digite novamente" <<endl; } } return 0; }
21.12963
63
0.584575
julioofilho
3dfd6982a5b5c71c66eb3aefe965b3a48fc7cc84
3,040
cpp
C++
collection/cp/bcw_codebook-master/Contest/PWTC2006NizhnyNovgorodSU/pC.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
1
2019-03-24T13:12:01.000Z
2019-03-24T13:12:01.000Z
collection/cp/bcw_codebook-master/Contest/PWTC2006NizhnyNovgorodSU/pC.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
collection/cp/bcw_codebook-master/Contest/PWTC2006NizhnyNovgorodSU/pC.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> #include<unistd.h> using namespace std; #define FZ(n) memset((n),0,sizeof(n)) #define FMO(n) memset((n),-1,sizeof(n)) #define F first #define S second #define PB push_back #define ALL(x) begin(x),end(x) #define SZ(x) ((int)(x).size()) #define IOS ios_base::sync_with_stdio(0); cin.tie(0) #define REP(i,x) for (int i=0; i<(x); i++) #define REP1(i,a,b) for (int i=(a); i<=(b); i++) #ifdef ONLINE_JUDGE #define FILEIO(name) \ freopen(name".in", "r", stdin); \ freopen(name".out", "w", stdout); #else #define FILEIO(name) #endif template<typename A, typename B> ostream& operator <<(ostream &s, const pair<A,B> &p) { return s<<"("<<p.first<<","<<p.second<<")"; } template<typename T> ostream& operator <<(ostream &s, const vector<T> &c) { s<<"[ "; for (auto it : c) s << it << " "; s<<"]"; return s; } // Let's Fight! const int MAXN = 131072; // (must be 2^k) typedef long double ld; typedef complex<ld> cplx; const ld PI = acosl(-1); const cplx I(0, 1); cplx omega[MAXN+1]; void pre_fft() { for(int i=0; i<=MAXN; i++) omega[i] = exp(i * 2 * PI / MAXN * I); } void fft(int n, cplx a[], bool inv=false) { int basic = MAXN / n; int theta = basic; for (int m = n; m >= 2; m >>= 1) { int mh = m >> 1; for (int i = 0; i < mh; i++) { cplx w = omega[inv ? MAXN-(i*theta%MAXN) : i*theta%MAXN]; for (int j = i; j < n; j += m) { int k = j + mh; cplx x = a[j] - a[k]; a[j] += a[k]; a[k] = w * x; } } theta = (theta * 2) % MAXN; } int i = 0; for (int j = 1; j < n - 1; j++) { for (int k = n >> 1; k > (i ^= k); k >>= 1); if (j < i) swap(a[i], a[j]); } if (inv) for (i = 0; i < n; i++) a[i] /= n; } string S1, S2; int l1, l2; int ans[5][5][MAXN]; cplx A[5][MAXN], B[5][MAXN]; cplx temp[MAXN]; void calc(int a, int b) { for (int i=0; i<MAXN; i++) { temp[i] = A[a][i] * B[b][i]; } fft(MAXN, temp, true); for (int i=0; i<MAXN; i++) { ans[a][b][i] = round(temp[i].real()); } } void calc() { pre_fft(); l1 = SZ(S1); l2 = SZ(S2); for (int i=0; i<l1+l1; i++) { int j = i%l1; int t = S1[j]-'A'; A[t][i] = 1.0; } for (int i=0; i<l2; i++) { int t = S2[l2-i-1]-'a'; B[t][i] = 1.0; } for (int i=0; i<5; i++) { fft(MAXN, A[i]); fft(MAXN, B[i]); } for (int i=0; i<5; i++) { for (int j=0; j<5; j++) { calc(i, j); } } /* for (int a=0; a<5; a++) for (int b=0; b<5; b++) { cout << char('a' + a) << ' ' << char('A' + b) << ' '; for (int i=0; i<l1; i++) { cout << ans[a][b][i] << ' '; } cout << endl; } */ vector<int> perm = {0, 1, 2, 3, 4}; int ra = 0; do { for (int i=l1; i<l1+l1; i++) { int t = 0; for (int j=0; j<5; j++) { t += ans[j][perm[j]][i]; //cout << j << ' ' << perm[j] << ' ' << i << ' ' << ans[j][perm[j]][i] << endl; //cout << "T = " << t << endl; } ra = max(ra, t); } } while (next_permutation(ALL(perm))); cout << l1-ra << endl; } int main() { IOS; cin>>S1>>S2; calc(); return 0; }
19.487179
83
0.475329
daemonslayer
3dfea706fba69eb8e27a31804902bd0a67d8e7b2
718
cpp
C++
src/base/LayerHandler.cpp
pitchShifter/liteForge
df3337842005e6b113663fcf85e9331a18e678b9
[ "MIT" ]
null
null
null
src/base/LayerHandler.cpp
pitchShifter/liteForge
df3337842005e6b113663fcf85e9331a18e678b9
[ "MIT" ]
null
null
null
src/base/LayerHandler.cpp
pitchShifter/liteForge
df3337842005e6b113663fcf85e9331a18e678b9
[ "MIT" ]
null
null
null
#include "LayerHandler.h" namespace liteForge { void LayerHandler::add( std::string name, Layer *layer ) { if( !find( name ) ) layers.insert( std::make_pair( name, layerPtr( layer ) ) ); } bool LayerHandler::find( std::string name ) { auto it = layers.find( name ); // Found if( it != layers.end() ) return true; return false; } void LayerHandler::del( std::string name ) { if( find( name ) ) layers.erase( name ); } void LayerHandler::createLayer( std::string name, unsigned int id ) { //add( name ); //get( name )->layer_id = id; } Layer *LayerHandler::get( std::string name ) { return layers[name].get(); } layerMap &LayerHandler::getAll() { return layers; } }
16.697674
68
0.622563
pitchShifter
3dff24f7a0a1e43bd6a340800d0bd6f86026f8af
540
cc
C++
clfsm/CLReflect.v1/API_Setup.cc
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
null
null
null
clfsm/CLReflect.v1/API_Setup.cc
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
null
null
null
clfsm/CLReflect.v1/API_Setup.cc
mipalgu/gufsm
d822d36fa04946ffa6c3680725dfdba03fa9a0c5
[ "BSD-4-Clause" ]
1
2021-09-14T18:37:16.000Z
2021-09-14T18:37:16.000Z
#include "CLReflect_API.h" #include "CLReflectionSystem.h" using namespace CLReflect; using namespace std; void API::initialise(shared_ptr<IMachineStorage> machineStore) { CLReflectionSystem *system = CLReflectionSystem::getInstance(); system->setMachineStorage(machineStore); } void API::registerMachine(shared_ptr<CLMetaMachine> machine) { CLReflectionSystem *system = CLReflectionSystem::getInstance(); shared_ptr<CLMetaRegister> metaRegister = system->getMetaStore(); metaRegister->registerMachine(machine); }
24.545455
69
0.781481
mipalgu
ad0227d39811a2b2a3496cf245dc27c03e17322f
3,344
hpp
C++
include/Nazara/Math/Angle.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Math/Angle.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Math/Angle.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Math module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_MATH_ANGLE_HPP #define NAZARA_MATH_ANGLE_HPP #include <Nazara/Core/TypeTag.hpp> #include <Nazara/Math/Algorithm.hpp> #include <Nazara/Math/Enums.hpp> #include <ostream> #include <string> #include <type_traits> #include <utility> namespace Nz { struct SerializationContext; template<typename T> class EulerAngles; template<typename T> class Quaternion; template<AngleUnit Unit, typename T> class Angle { public: constexpr Angle() = default; constexpr Angle(T angle); template<typename U> constexpr explicit Angle(const Angle<Unit, U>& Angle); constexpr Angle(const Angle<AngleUnit::Degree, T>& angle); constexpr Angle(const Angle<AngleUnit::Radian, T>& angle); ~Angle() = default; T GetCos() const; T GetSin() const; std::pair<T, T> GetSinCos() const; T GetTan() const; constexpr Angle& MakeZero(); constexpr Angle& Normalize(); constexpr Angle& Set(const Angle& ang); template<typename U> constexpr Angle& Set(const Angle<Unit, U>& ang); constexpr T ToDegrees() const; constexpr Angle<AngleUnit::Degree, T> ToDegreeAngle() const; EulerAngles<T> ToEulerAngles() const; Quaternion<T> ToQuaternion() const; constexpr T ToRadians() const; constexpr Angle<AngleUnit::Radian, T> ToRadianAngle() const; std::string ToString() const; constexpr Angle& operator=(const Angle&) = default; constexpr const Angle& operator+() const; constexpr Angle operator-() const; constexpr Angle operator+(const Angle& other) const; constexpr Angle operator-(const Angle& other) const; constexpr Angle operator*(T scalar) const; constexpr Angle operator/(T divider) const; constexpr Angle& operator+=(const Angle& other); constexpr Angle& operator-=(const Angle& other); constexpr Angle& operator*=(T scalar); constexpr Angle& operator/=(T divider); constexpr bool operator==(const Angle& other) const; constexpr bool operator!=(const Angle& other) const; static constexpr Angle FromDegrees(T ang); static constexpr Angle FromRadians(T ang); static constexpr Angle Zero(); T value; }; template<typename T> using DegreeAngle = Angle<AngleUnit::Degree, T>; using DegreeAngled = DegreeAngle<double>; using DegreeAnglef = DegreeAngle<float>; template<typename T> using RadianAngle = Angle<AngleUnit::Radian, T>; using RadianAngled = RadianAngle<double>; using RadianAnglef = RadianAngle<float>; template<AngleUnit Unit, typename T> bool Serialize(SerializationContext& context, const Angle<Unit, T>& angle, TypeTag<Angle<Unit, T>>); template<AngleUnit Unit, typename T> bool Unserialize(SerializationContext& context, Angle<Unit, T>* angle, TypeTag<Angle<Unit, T>>); } template<Nz::AngleUnit Unit, typename T> Nz::Angle<Unit, T> operator*(T scale, const Nz::Angle<Unit, T>& angle); template<Nz::AngleUnit Unit, typename T> Nz::Angle<Unit, T> operator/(T divider, const Nz::Angle<Unit, T>& angle); template<Nz::AngleUnit Unit, typename T> std::ostream& operator<<(std::ostream& out, const Nz::Angle<Unit, T>& angle); #include <Nazara/Math/Angle.inl> #endif // NAZARA_MATH_ANGLE_HPP
30.678899
138
0.727572
jayrulez
ad06bcad77750d86702173cdadf4e33def8bbdb7
366
cpp
C++
src/Animation/AnimationManager.cpp
Henningson/Connect2
2ccf3431016a11b7fd6aeac65e259f197c01f121
[ "MIT" ]
1
2020-01-06T21:06:29.000Z
2020-01-06T21:06:29.000Z
src/Animation/AnimationManager.cpp
Henningson/Connect2
2ccf3431016a11b7fd6aeac65e259f197c01f121
[ "MIT" ]
3
2020-01-31T11:53:50.000Z
2020-01-31T11:54:24.000Z
src/Animation/AnimationManager.cpp
Henningson/Connect2
2ccf3431016a11b7fd6aeac65e259f197c01f121
[ "MIT" ]
1
2021-06-22T19:42:00.000Z
2021-06-22T19:42:00.000Z
#pragma once #include "AnimationManager.h" AnimationManager::AnimationManager() {} void AnimationManager::drawAnimations(sf::RenderTarget& target, sf::RenderStates states) { for (AnimatedSprite* sprite : this->sprites) { //sprite->draw(target, states); } } void AnimationManager::addAnimatedSprite(AnimatedSprite* sprite) { this->sprites.push_back(sprite); }
26.142857
90
0.762295
Henningson
ad12fa59690383ce7e4478050528dea924fd56ef
9,293
cpp
C++
depspawn-blitz-0.10/benchmarks/acoustic.cpp
fraguela/depspawn
b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45
[ "MIT" ]
8
2017-04-12T11:05:40.000Z
2022-03-29T11:10:27.000Z
ibtk/third_party/blitz-0.10/benchmarks/acoustic.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
ibtk/third_party/blitz-0.10/benchmarks/acoustic.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
//#define BZ_DISABLE_RESTRICT #define BZ_ARRAY_2D_NEW_STENCIL_TILING #include <blitz/array.h> #include <blitz/timer.h> #include <blitz/benchext.h> #include <blitz/vector2.h> #ifdef BZ_HAVE_STD #include <fstream> #else #include <fstream.h> #endif BZ_USING_NAMESPACE(blitz) #if defined(BZ_FORTRAN_SYMBOLS_WITH_TRAILING_UNDERSCORES) #define echo_f90 echo_f90_ #define echo_f77 echo_f77_ #define echo_f90_tuned echo_f90_tuned_ #define echo_f77tuned echo_f77tuned_ #elif defined(BZ_FORTRAN_SYMBOLS_WITH_DOUBLE_TRAILING_UNDERSCORES) #define echo_f90 echo_f90__ #define echo_f77 echo_f77__ #define echo_f90_tuned echo_f90_tuned__ #define echo_f77tuned echo_f77tuned__ #elif defined(BZ_FORTRAN_SYMBOLS_CAPS) #define echo_f90 ECHO_F90 #define echo_f77 ECHO_F77 #define echo_f90_tuned ECHO_F90_TUNED #define echo_f77tuned ECHO_F77TUNED #endif extern "C" { void echo_f90(int& N, int& niters, float& check); void echo_f77(int& N, int& niters, float& check); void echo_f90_tuned(int& N, int& niters, float& check); void echo_f77tuned(int& N, int& niters, float& check); } void f77(BenchmarkExt<int>&); void f90(BenchmarkExt<int>&); void f77_tuned(BenchmarkExt<int>&); void f90_tuned(BenchmarkExt<int>&); void echo_BlitzInterlacedCycled(BenchmarkExt<int>&); void echo_BlitzCycled(BenchmarkExt<int>&); void echo_BlitzRaw(BenchmarkExt<int>&); void echo_BlitzStencil(BenchmarkExt<int>&); int main() { Timer timer; float check; int numBenchmarks = 6; #ifdef FORTRAN_90 numBenchmarks+=2; #endif BenchmarkExt<int> bench("Acoustic 2D Benchmark", numBenchmarks); const int numSizes=7; bench.setNumParameters(numSizes); Vector<int> parameters(numSizes); parameters=10*pow(2.0,tensor::i); Vector<double> flops(numSizes); flops=(parameters-2)*(parameters-2) * 9.0; Vector<long> iters(numSizes); // iters must be divisible by 3 for tuned fortran versions iters=cast<long>(100000000/flops)*3; bench.setParameterVector(parameters); bench.setParameterDescription("Matrix size"); bench.setIterations(iters); bench.setOpsPerIteration(flops); bench.setDependentVariable("flops"); bench.beginBenchmarking(); echo_BlitzRaw(bench); echo_BlitzStencil(bench); #if 0 echo_BlitzInterlaced(bench, c); #endif echo_BlitzCycled(bench); echo_BlitzInterlacedCycled(bench); #ifdef FORTRAN_90 f90(bench); f90_tuned(bench); #endif f77(bench); f77_tuned(bench); bench.endBenchmarking(); bench.saveMatlabGraph("acoustic.m"); return 0; } void checkArray(Array<float,2>& A, int N) { float check = 0.0; for (int i=0; i < N; ++i) for (int j=0; j < N; ++j) check += ((i+1)*N + j + 1) * A(i,j); cout << "Array check: " << check << endl; } void setInitialConditions(Array<float,2>& c, Array<float,2>& P1, Array<float,2>& P2, Array<float,2>& P3, int N); void echo_BlitzRaw(BenchmarkExt<int>&bench) { bench.beginImplementation("Blitz++ (raw)"); while (!bench.doneImplementationBenchmark()) { int N = bench.getParameter(); int niters = bench.getIterations(); Array<float,2> P1(N,N), P2(N,N), P3(N,N), c(N,N); Range I(1,N-2), J(1,N-2); setInitialConditions(c, P1, P2, P3, N); checkArray(P2, N); checkArray(c, N); bench.start(); for (int iter=0; iter < niters; ++iter) { P3(I,J) = (2-4*c(I,J)) * P2(I,J) + c(I,J)*(P2(I-1,J) + P2(I+1,J) + P2(I,J-1) + P2(I,J+1)) - P1(I,J); P1 = P2; P2 = P3; } bench.stop(); cout << P1(N/2-1,(7*N)/8-1) << endl; } bench.endImplementation(); #if 0 ofstream ofs("testecho.m"); ofs << "A = ["; for (int i=0; i < N; ++i) { for (int j=0; j < N; ++j) { ofs << int(8192*P2(i,j)+1024*c(i,j)) << " "; } if (i < N-1) ofs << ";" << endl; } ofs << "];" << endl; #endif } void echo_BlitzCycled(BenchmarkExt<int>&bench) { bench.beginImplementation("Blitz++ (cycled)"); while (!bench.doneImplementationBenchmark()) { int N = bench.getParameter(); int niters = bench.getIterations(); cout << bench.currentImplementation() << " N=" << N << endl; Array<float,2> P1(N,N), P2(N,N), P3(N,N), c(N,N); Range I(1,N-2), J(1,N-2); setInitialConditions(c, P1, P2, P3, N); checkArray(P2, N); checkArray(c, N); bench.start(); for (int iter=0; iter < niters; ++iter) { P3(I,J) = (2-4*c(I,J)) * P2(I,J) + c(I,J)*(P2(I-1,J) + P2(I+1,J) + P2(I,J-1) + P2(I,J+1)) - P1(I,J); cycleArrays(P1,P2,P3); } bench.stop(); cout << P1(N/2-1,(7*N)/8-1) << endl; } bench.endImplementation(); } void echo_BlitzInterlacedCycled(BenchmarkExt<int>&bench) { bench.beginImplementation("Blitz++ (interlaced & cycled)"); while (!bench.doneImplementationBenchmark()) { int N = bench.getParameter(); int niters = bench.getIterations(); cout << bench.currentImplementation() << " N=" << N << endl; Array<float,2> P1, P2, P3, c; allocateArrays(shape(N,N), P1, P2, P3, c); Range I(1,N-2), J(1,N-2); setInitialConditions(c, P1, P2, P3, N); checkArray(P2, N); checkArray(c, N); bench.start(); for (int iter=0; iter < niters; ++iter) { P3(I,J) = (2-4*c(I,J)) * P2(I,J) + c(I,J)*(P2(I-1,J) + P2(I+1,J) + P2(I,J-1) + P2(I,J+1)) - P1(I,J); cycleArrays(P1,P2,P3); } bench.stop(); cout << P1(N/2-1,(7*N)/8-1) << endl; } bench.endImplementation(); } BZ_DECLARE_STENCIL4(acoustic2D,P1,P2,P3,c) P3 = 2 * P2 + c * Laplacian2D_stencilop(P2) - P1; BZ_STENCIL_END void echo_BlitzStencil(BenchmarkExt<int>&bench) { bench.beginImplementation("Blitz++ (stencil)"); while (!bench.doneImplementationBenchmark()) { int N = bench.getParameter(); int niters = bench.getIterations(); cout << bench.currentImplementation() << " N=" << N << endl; Array<float,2> P1, P2, P3, c; allocateArrays(shape(N,N), P1, P2, P3, c); setInitialConditions(c, P1, P2, P3, N); checkArray(P2, N); checkArray(c, N); bench.start(); for (int iter=0; iter < niters; ++iter) { applyStencil(acoustic2D(), P1, P2, P3, c); cycleArrays(P1,P2,P3); } bench.stop(); cout << P1(N/2-1,(7*N)/8-1) << endl; } bench.endImplementation(); } void setInitialConditions(Array<float,2>& c, Array<float,2>& P1, Array<float,2>& P2, Array<float,2>& P3, int N) { // Set the velocity field c = 0.2; // Solid block with which the pulse collides int blockLeft = 0; int blockRight = int(2*N/5.0-1); int blockTop = int(N/3-1); int blockBottom = int(2*N/3.0-1); c(Range(blockTop,blockBottom),Range(blockLeft,blockRight)) = 0.5; // Channel directing the pulse leftwards int channelLeft = int(4*N/5.0-1); int channelRight = N-1; int channel1Height = int(3*N/8.0-1); int channel2Height = int(5*N/8.0-1); c(channel1Height,Range(channelLeft,channelRight)) = 0.0; c(channel2Height,Range(channelLeft,channelRight)) = 0.0; // Initial pressure distribution: gaussian pulse inside the channel BZ_USING_NAMESPACE(blitz::tensor) int cr = int(N/2-1); int cc = int(7.0*N/8.0-1); // pow2 is not defined for pod types. float s2 = 64.0 * 9.0 / pow(N/2.0,2); cout << "cr = " << cr << " cc = " << cc << " s2 = " << s2 << endl; P1 = 0.0; P2 = exp(-(pow2(i-cr)+pow2(j-cc)) * s2); P3 = 0.0; } void f77(BenchmarkExt<int>&bench) { bench.beginImplementation("Fortran77"); while (!bench.doneImplementationBenchmark()) { int N = bench.getParameter(); int niters = bench.getIterations(); cout << bench.currentImplementation() << " N=" << N << endl; float check; bench.start(); echo_f77(N, niters, check); bench.stop(); cout << check << endl; } bench.endImplementation(); }; void f77_tuned(BenchmarkExt<int>&bench) { bench.beginImplementation("Fortran77 (tuned)"); while (!bench.doneImplementationBenchmark()) { int N = bench.getParameter(); int niters = bench.getIterations(); cout << bench.currentImplementation() << " N=" << N << endl; float check; bench.start(); echo_f77tuned(N, niters, check); bench.stop(); cout << check << endl; } bench.endImplementation(); }; void f90(BenchmarkExt<int>&bench) { bench.beginImplementation("Fortran90"); while (!bench.doneImplementationBenchmark()) { int N = bench.getParameter(); int niters = bench.getIterations(); cout << bench.currentImplementation() << " N=" << N << endl; float check; bench.start(); echo_f90(N, niters, check); bench.stop(); cout << check << endl; } bench.endImplementation(); }; void f90_tuned(BenchmarkExt<int>&bench) { bench.beginImplementation("Fortran90 (tuned)"); while (!bench.doneImplementationBenchmark()) { int N = bench.getParameter(); int niters = bench.getIterations(); cout << bench.currentImplementation() << " N=" << N << endl; float check; bench.start(); echo_f90_tuned(N, niters, check); bench.stop(); cout << check << endl; } bench.endImplementation(); };
25.116216
71
0.617454
fraguela
ad14c6ccaf757e56b781bd4cd4a7f090298f563d
7,448
cpp
C++
apps/rtigo3/src/DeviceMultiGPUZeroCopy.cpp
idcrook/tweeker_raytracer
10910b4b90277fb782798f915d499dc61643efa1
[ "CC0-1.0" ]
4
2020-02-17T11:36:47.000Z
2020-04-03T19:38:09.000Z
apps/rtigo3/src/DeviceMultiGPUZeroCopy.cpp
idcrook/tweeker_raytracer
10910b4b90277fb782798f915d499dc61643efa1
[ "CC0-1.0" ]
null
null
null
apps/rtigo3/src/DeviceMultiGPUZeroCopy.cpp
idcrook/tweeker_raytracer
10910b4b90277fb782798f915d499dc61643efa1
[ "CC0-1.0" ]
null
null
null
/* * Copyright (c) 2019-2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 "inc/DeviceMultiGPUZeroCopy.h" #include "inc/CheckMacros.h" // includes OpenGL headers #include "inc/OpenGL_loader.h" // #include <GL/glew.h> // #if defined( _WIN32 ) // #include <GL/wglew.h> // #endif DeviceMultiGPUZeroCopy::DeviceMultiGPUZeroCopy(const RendererStrategy strategy, const int ordinal, const int index, const int count, const int miss, const int interop, const unsigned int tex, const unsigned int pbo) : Device(strategy, ordinal, index, count, miss, interop, tex, pbo) { if (m_deviceAttribute.canMapHostMemory == 0) { std::cout << "ERROR: DeviceMultiGPUZeroCopy() Device ordinal " << ordinal << " canMapHostMemory attribute is false." << std::endl; } } DeviceMultiGPUZeroCopy::~DeviceMultiGPUZeroCopy() { CU_CHECK_NO_THROW( cuCtxSetCurrent(m_cudaContext) ); CU_CHECK_NO_THROW( cuCtxSynchronize() ); if (m_ownsSharedBuffer) // This destruction order requires that all other devices cannot touch this shared buffer anymore. { CU_CHECK_NO_THROW( cuCtxSetCurrent(m_cudaContext) ); CU_CHECK_NO_THROW( cuMemFreeHost(reinterpret_cast<void*>(m_systemData.outputBuffer)) ); } } void DeviceMultiGPUZeroCopy::setState(DeviceState const& state) { if (m_systemData.resolution != state.resolution || m_systemData.tileSize != state.tileSize) { // Calculate the new launch width for the tiled rendering. // It must be a multiple of the tileSize width, otherwise the right-most tiles will not get filled correctly. const int width = (state.resolution.x + m_count - 1) / m_count; const int mask = state.tileSize.x - 1; m_launchWidth = (width + mask) & ~mask; // == ((width + (tileSize - 1)) / tileSize.x) * tileSize.x; } Device::setState(state); // Call the base class to track the state. } void DeviceMultiGPUZeroCopy::activateContext() { CU_CHECK( cuCtxSetCurrent(m_cudaContext) ); } void DeviceMultiGPUZeroCopy::synchronizeStream() { CU_CHECK( cuStreamSynchronize(m_cudaStream) ); } void DeviceMultiGPUZeroCopy::render(const unsigned int iterationIndex, void** buffer) { activateContext(); m_systemData.iterationIndex = iterationIndex; if (m_isDirtyOutputBuffer) { MY_ASSERT(buffer != nullptr); if (*buffer == nullptr) // The first device called handles the reallocation of the shared pinned memory buffer. { // Allocate zero-copy pinned memory on the host. CU_CHECK( cuMemFreeHost(reinterpret_cast<void*>(m_systemData.outputBuffer)) ); CU_CHECK( cuMemHostAlloc(reinterpret_cast<void**>(&m_systemData.outputBuffer), sizeof(float4) * m_systemData.resolution.x * m_systemData.resolution.y, CU_MEMHOSTALLOC_PORTABLE | CU_MEMHOSTALLOC_DEVICEMAP) ); *buffer = reinterpret_cast<void*>(m_systemData.outputBuffer); // Fill the shared buffer pointer. m_ownsSharedBuffer = true; // This device will destruct it. } else { // Use the same zero copy pinned memory buffer for all devices. // m_systemData.outputBuffer = reinterpret_cast<CUdeviceptr>(*buffer); // This call results in the same pointer because of CU_MEMHOSTALLOC_PORTABLE. CU_CHECK( cuMemHostGetDevicePointer(&m_systemData.outputBuffer, *buffer, 0) ); } m_isDirtyOutputBuffer = false; // Buffer is allocated with new size, m_isDirtySystemData = true; // Now the sysData on the device needs to be updated, and that needs a sync! } if (m_isDirtySystemData) // Update the whole SystemData block because more than the iterationIndex changed. This normally means a GUI interaction. Just sync. { synchronizeStream(); CU_CHECK( cuMemcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(m_d_systemData), &m_systemData, sizeof(SystemData), m_cudaStream) ); m_isDirtySystemData = false; } else // Just copy the new iterationIndex. { synchronizeStream(); // FIXME For some render strategy "final frame" there should be no synchronizeStream() at all here. // FIXME Then for really asynchronous copies of the iteration indices multiple source pointers are required. Good that I know the number of iterations upfront! CU_CHECK( cuMemcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(&m_d_systemData->iterationIndex), &m_systemData.iterationIndex, sizeof(unsigned int), m_cudaStream) ); } // Note the launch width per device to render in tiles. OPTIX_CHECK( m_api.optixLaunch(m_pipeline, m_cudaStream, reinterpret_cast<CUdeviceptr>(m_d_systemData), sizeof(SystemData), &m_sbt, m_launchWidth, m_systemData.resolution.y, /* depth */ 1) ); } void DeviceMultiGPUZeroCopy::updateDisplayTexture() { // All other devices have been synced by the RaytracerMultiGPUZeroCopy caller. activateContext(); synchronizeStream(); // Wait for the buffer to arrive on the host. MY_ASSERT(!m_isDirtyOutputBuffer && m_ownsSharedBuffer && m_tex != 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_tex); // RGBA32F from shared pinned memory host buffer data. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, (GLsizei) m_systemData.resolution.x, (GLsizei) m_systemData.resolution.y, 0, GL_RGBA, GL_FLOAT, reinterpret_cast<GLvoid*>(m_systemData.outputBuffer)); } const void* DeviceMultiGPUZeroCopy::getOutputBufferHost() { // All other devices have been synced by the RaytracerMultiGPUZeroCopy caller. activateContext(); synchronizeStream(); // Wait for the buffer to arrive on the host. MY_ASSERT(!m_isDirtyOutputBuffer && m_ownsSharedBuffer); return reinterpret_cast<void*>(m_systemData.outputBuffer); // This buffer is in pinned memory on the host. Just return it. }
44.071006
213
0.718179
idcrook
ad173a61a75d8a4dd633c6011e92503459e4c5f0
852
hpp
C++
src/common/interfaces/presenters/tools/inavigatetoolpresenteraux.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
3
2020-03-05T06:36:51.000Z
2020-06-20T03:25:02.000Z
src/common/interfaces/presenters/tools/inavigatetoolpresenteraux.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
13
2020-03-11T17:43:42.000Z
2020-12-11T03:36:05.000Z
src/common/interfaces/presenters/tools/inavigatetoolpresenteraux.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
1
2020-09-28T06:53:46.000Z
2020-09-28T06:53:46.000Z
/** * Addle source code * @file * @copyright Copyright 2020 Eleanor Hawk * @copyright Modification and distribution permitted under the terms of the * MIT License. See "LICENSE" for full details. */ #ifndef INAVIGATEPRESENTERAUX_HPP #define INAVIGATEPRESENTERAUX_HPP #include "compat.hpp" #include "idtypes/toolid.hpp" #include <QObject> // Separte file from INavigateToolPresenter for the benefit of AutoMoc namespace Addle { namespace INavigateToolPresenterAux { Q_NAMESPACE_EXPORT(ADDLE_COMMON_EXPORT) extern ADDLE_COMMON_EXPORT const ToolId ID; enum NavigateOperationOptions { gripPan, gripPivot, rectangleZoomTo }; Q_ENUM_NS(NavigateOperationOptions) const NavigateOperationOptions DEFAULT_NAVIGATE_OPERATION_OPTION = gripPan; } } // namespace Addle #endif // INAVIGATEPRESENTERAUX_HPP
23.666667
79
0.764085
squeevee
ad19a322ff3caa634a45e2f8fa0b235f8a42bb3a
7,754
cxx
C++
3rd/fltk/src/Choice.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
3rd/fltk/src/Choice.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
3rd/fltk/src/Choice.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
// "$Id: Choice.cxx 7513 2010-04-15 17:19:27Z spitzak $" // // Copyright 1998-2006 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems to "fltk-bugs@fltk.org". /*! \class fltk::Choice Subclass of fltk::Menu that provides a button that pops up the menu, and also displays the text of the most-recently selected menu item. \image html choice.gif The appearance is designed to look like an "uneditable ComboBox" in Windows, but it is somewhat different in that it does not contain a text editor, also the menu pops up with the current item under the cursor, which is immensely easier to use once you get used to it. This is the same UI as the Macintosh and Motif, which called this an OptionButton. The user can change the value by popping up the menu by clicking anywhere in the widget and moving the cursor to a different item, or by typing up and down arrow keys to cycle amoung the items. Typing the fltk::Widget::shortcut() of any of the items will also change the value to that item. If you set a shortcut() on this widget itself or put &x in the label, that shortcut will pop up the menu. The user can then use arrow keys or the mouse to change the selected item. When the user changes the value() the callback is done. If you wish to display text that is different than any of the menu items, you may instead want an fltk::PopupMenu. It works identically but instead displays an empty box with the label() inside it, you can then change the label() as needed. If you want a "real" ComboBox where the user edits the text, this is a planned addition to the fltk::Input widget. All text input will have menus of possible replacements and completions. Not yet implemented, unfortunately. */ #include <fltk/Choice.h> #include <fltk/events.h> #include <fltk/damage.h> #include <fltk/Box.h> #include <fltk/Item.h> #include <fltk/draw.h> #include <fltk/run.h> using namespace fltk; // The dimensions for the glyph in this and the PopupMenu are exactly // the same, so that glyphs may be shared between them. extern bool fl_hide_underscore; /*! You can change the icon drawn on the right edge by setting glyph() to your own function that draws whatever you want. */ void Choice::draw() { if (damage() & DAMAGE_ALL) draw_frame(); Rectangle r(w(),h()); box()->inset(r); int w1 = r.h()*4/5; r.move_r(-w1); // draw the little mark at the right: if (damage() & (DAMAGE_ALL|DAMAGE_HIGHLIGHT)) { drawstyle(style(), (flags() & ~FOCUSED) | OUTPUT); Rectangle gr(r.r(), r.y(), w1, r.h()); draw_glyph(ALIGN_BOTTOM|ALIGN_INSIDE, gr); } if (damage() & (DAMAGE_ALL|DAMAGE_VALUE)) { setcolor(color()); fillrect(r); Widget* o = get_item(); //if (!o && children()) o = child(0); if (o) { Item::set_style(this,false); Flags saved = o->flags(); if (focused()) o->set_flag(SELECTED); else o->clear_flag(SELECTED); if (any_of(INACTIVE|INACTIVE_R)) o->set_flag(INACTIVE_R); push_clip(r); push_matrix(); if (!o->h()) o->layout(); // make it center on only the first line of multi-line item: int h = o->h(); int n = h/int(o->labelsize()+o->leading()); if (n > 1) h -= int((n-1)*o->labelsize()+(n-1.5)*o->leading()); // center the item vertically: translate(r.x()+2, r.y()+((r.h()-h)>>1)); int save_w = o->w(); o->w(r.w()-4); fl_hide_underscore = true; o->draw(); fl_hide_underscore = false; Item::clear_style(); o->w(save_w); o->flags(saved); pop_matrix(); pop_clip(); } } } static bool try_item(Choice* choice, int i) { Widget* w = choice->child(i); if (!w->takesevents()) return false; choice->value(i); choice->execute(w); return true; } int Choice::handle(int e) { return handle(e,Rectangle(w(),h())); } int Choice::handle(int e, const Rectangle& rectangle) { int children = this->children(0,0); switch (e) { case FOCUS: case UNFOCUS: redraw(DAMAGE_VALUE); return 1; case ENTER: case LEAVE: redraw_highlight(); case MOVE: return 1; case PUSH: // Normally a mouse click pops up the menu. If you uncomment this line // (or make a subclass that does this), a mouse click will re-pick the // current item (it will popup the menu and immediately dismiss it). // Depending on the size and usage of the menu this may be more // user-friendly. // event_is_click(0); if (click_to_focus()) { take_focus(); fltk::flush(); // this is a temporary fix for Nuke! // Nuke is destroying widgets in layout(), not a good idea... if (fltk::focus() != this) return 1; // detect if take_focus destroys this } EXECUTE: if (!children) return 1; if (popup(rectangle, 0)) redraw(DAMAGE_VALUE); return 1; case SHORTCUT: if (test_shortcut()) goto EXECUTE; if (handle_shortcut()) {redraw(DAMAGE_VALUE); return 1;} return 0; case KEY: switch (event_key()) { case ReturnKey: case SpaceKey: goto EXECUTE; case UpKey: { if (!children) return 1; int i = value(); if (i < 0) i = children; while (i > 0) {--i; if (try_item(this, i)) return 1;} return 1;} case DownKey: { if (!children) return 1; int i = value(); while (++i < children) if (try_item(this,i)) return 1; return 1;} } return 0; default: return 0; } } #define MOTIF_STYLE 0 #define MAC_STYLE 0 #if MOTIF_STYLE // Glyph erases the area and draws a long, narrow box: static void glyph(int, const Rectangle& r, const Style* s, Flags) { color(s->buttoncolor()); fillrect(r); // draw a long narrow box: Rectangle r1(r, r.w()-2, r.h()/3, ALIGN_LEFT); Widget::default_glyph(0, r1, s, 0); } #endif #if MAC_STYLE // Attempt to draw an up/down arrow like the Mac uses, since the // popup menu is more like how the Mac works: static void glyph(int, const Rectangle& r, const Style* s, Flags flags) { Widget::default_glyph(0, r, s, flags); Rectangle r1(r); r1.h(r1.h()/2); r1.move_y(r1.h()/3); Widget::default_glyph(GLYPH_UP, r1, s, flags); r1.move(0,r1.h()); Widget::default_glyph(GLYPH_DOWN, r1, s, flags); } #endif static void revert(Style* s) { #if MOTIF_STYLE s->color_ = GRAY75; s->box_ = s->buttonbox_ = Widget::default_style->buttonbox_; s->glyph_ = ::glyph; #endif #if MAC_STYLE s->glyph_ = ::glyph; #endif } static NamedStyle style("Choice", revert, &Choice::default_style); NamedStyle* Choice::default_style = &::style; /*! The constructor makes the menu empty. See Menu and StringList for information on how to set the menu to a list of items. */ Choice::Choice(int x,int y,int w,int h, const char *l) : Menu(x,y,w,h,l) { value(0); // copy the leading from Menu: if (!default_style->leading_) default_style->leading_ = style()->leading_; style(default_style); clear_flag(ALIGN_MASK); set_flag(ALIGN_LEFT); set_click_to_focus(); } // // End of "$Id: Choice.cxx 7513 2010-04-15 17:19:27Z spitzak $". //
30.407843
80
0.66959
MarioHenze
ad1d04ce83b9c96dfdccff1799d52dfdd347bfef
12,453
hpp
C++
src/centurion/system.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
14
2020-05-17T21:38:03.000Z
2020-11-21T00:16:25.000Z
src/centurion/system.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
70
2020-04-26T17:08:52.000Z
2020-11-21T17:34:03.000Z
src/centurion/system.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019-2022 Albin Johansson * * 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 CENTURION_SYSTEM_SYSTEM_HPP_ #define CENTURION_SYSTEM_SYSTEM_HPP_ #include <SDL.h> #include <cassert> // assert #include <chrono> // duration_cast #include <cstddef> // size_t #include <memory> // unique_ptr #include <optional> // optional #include <ostream> // ostream #include <string> // string #include <string_view> // string_view #include "common.hpp" #include "detail/sdl_deleter.hpp" #include "detail/stdlib.hpp" namespace cen { /** * \defgroup system System * * \brief Provides system-related information, such as RAM amount, counters, and platform. */ /// \addtogroup system /// \{ /// \name Platform indicator constants /// \{ /** * \var on_linux * \brief Indicates whether the current platform is Linux. */ /** * \var on_apple * \brief Indicates whether the current platform is some sort of Apple system. */ /** * \var on_win32 * \brief Indicates whether the current platform is at least 32-bit Windows. */ /** * \var on_win64 * \brief Indicates whether the current platform is 64-bit Windows. */ /** * \var on_windows * \brief Indicates whether the current platform is some variant of Windows. */ /** * \var on_android * \brief Indicates whether the current platform is Android. */ #ifdef __linux__ inline constexpr bool on_linux = true; #else inline constexpr bool on_linux = false; #endif // __linux__ #ifdef __APPLE__ inline constexpr bool on_apple = true; #else inline constexpr bool on_apple = false; #endif // __APPLE__ #ifdef _WIN32 inline constexpr bool on_win32 = true; #else inline constexpr bool on_win32 = false; #endif // _WIN32 #ifdef _WIN64 inline constexpr bool on_win64 = true; #else inline constexpr bool on_win64 = false; #endif // _WIN64 inline constexpr bool on_windows = on_win32 || on_win64; #ifdef __ANDROID__ inline constexpr bool on_android = true; #else inline constexpr bool on_android = false; #endif // __ANDROID__ /// \} End of platform indicator constants /** * \brief Represents various operating systems. */ enum class platform_id { unknown, ///< An unknown platform. windows, ///< The Windows operating system. macos, ///< The macOS operating system. linux_os, ///< The Linux operating system. ios, ///< The iOS operating system. android ///< The Android operating system. }; /// \name Platform ID functions /// \{ [[nodiscard]] inline auto to_string(const platform_id id) -> std::string_view { switch (id) { case platform_id::unknown: return "unknown"; case platform_id::windows: return "windows"; case platform_id::macos: return "macos"; case platform_id::linux_os: return "linux_os"; case platform_id::ios: return "ios"; case platform_id::android: return "android"; default: throw exception{"Did not recognize platform!"}; } } inline auto operator<<(std::ostream& stream, const platform_id id) -> std::ostream& { return stream << to_string(id); } /// \} End of platform ID functions /** * \brief Represents a shared object, e.g. dynamic libraries. */ class shared_object final { public: /** * \brief Loads a shared object. * * \param object the name of the shared object. * * \throws sdl_error if the object cannot be loaded. */ explicit shared_object(const char* object) : mObject{SDL_LoadObject(object)} { if (!mObject) { throw sdl_error{}; } } /// \copydoc shared_object() explicit shared_object(const std::string& object) : shared_object{object.c_str()} {} /** * \brief Attempts to load a C function. * * \note This function can only load C functions. * * \tparam T the signature of the function, e.g. `void(int, float)`. * * \param name the function name. * * \return the loaded function; a null pointer is returned if something goes wrong. */ template <typename T> [[nodiscard]] auto load_function(const char* name) const noexcept -> T* { assert(name); return reinterpret_cast<T*>(SDL_LoadFunction(mObject.get(), name)); } /// \copydoc load_function() template <typename T> [[nodiscard]] auto load_function(const std::string& name) const noexcept -> T* { return load_function<T>(name.c_str()); } private: struct deleter final { void operator()(void* object) noexcept { SDL_UnloadObject(object); } }; std::unique_ptr<void, deleter> mObject; #ifdef CENTURION_MOCK_FRIENDLY_MODE public: shared_object() = default; #endif // CENTURION_MOCK_FRIENDLY_MODE }; /// \name Runtime platform information functions /// \{ /** * \brief Returns the name of the current platform. * * \return the name of the current platform; an empty optional is returned if the name cannot * be deduced. */ [[nodiscard]] inline auto platform_name() -> std::optional<std::string> { std::string name{SDL_GetPlatform()}; if (name != "Unknown") { return name; } else { return std::nullopt; } } /** * \brief Returns an identifier that represents the current platform. * * \return the current platform. */ [[nodiscard]] inline auto current_platform() noexcept -> platform_id { const auto name = platform_name(); if (name == "Windows") { return platform_id::windows; } else if (name == "Mac OS X") { return platform_id::macos; } else if (name == "Linux") { return platform_id::linux_os; } else if (name == "iOS") { return platform_id::ios; } else if (name == "Android") { return platform_id::android; } else { return platform_id::unknown; } } /** * \brief Indicates whether the current platform is Windows. * * \return `true` if the platform is Windows; `false` otherwise. */ [[nodiscard]] inline auto is_windows() noexcept -> bool { return current_platform() == platform_id::windows; } /** * \brief Indicates whether the current platform is macOS. * * \return `true` if the platform is macOS; `false` otherwise. */ [[nodiscard]] inline auto is_macos() noexcept -> bool { return current_platform() == platform_id::macos; } /** * \brief Indicates whether the current platform is Linux. * * \return `true` if the platform is Linux; `false` otherwise. */ [[nodiscard]] inline auto is_linux() noexcept -> bool { return current_platform() == platform_id::linux_os; } /** * \brief Indicates whether the current platform is iOS. * * \return `true` if the platform is iOS; `false` otherwise. */ [[nodiscard]] inline auto is_ios() noexcept -> bool { return current_platform() == platform_id::ios; } /** * \brief Indicates whether the current platform is Android. * * \return `true` if the platform is Android; `false` otherwise. */ [[nodiscard]] inline auto is_android() noexcept -> bool { return current_platform() == platform_id::android; } /** * \brief Indicates whether the current system is a tablet. * * \return `true` if the system is a tablet; `false` otherwise. */ [[nodiscard]] inline auto is_tablet() noexcept -> bool { return SDL_IsTablet() == SDL_TRUE; } /// \} End of runtime platform information functions /// \name System counter functions /// \{ /** * \brief Returns the frequency of the system high-performance counter. * * \return the counter frequency. */ [[nodiscard]] inline auto frequency() noexcept -> uint64 { return SDL_GetPerformanceFrequency(); } /** * \brief Returns the current value of the high-performance counter. * * \note The unit of the returned value is platform dependent, see `frequency()`. * * \return the current value of the counter. */ [[nodiscard]] inline auto now() noexcept -> uint64 { return SDL_GetPerformanceCounter(); } /** * \brief Returns the value of the system high-performance counter in seconds. * * \tparam T the representation type. * * \return the current value of the counter. */ [[nodiscard]] inline auto now_in_seconds() noexcept(noexcept(seconds<double>{})) -> seconds<double> { return seconds<double>{static_cast<double>(now()) / static_cast<double>(frequency())}; } #if SDL_VERSION_ATLEAST(2, 0, 18) /** * \brief Returns the amount of milliseconds since SDL was initialized. * * \return the time since SDL was initialized. * * \atleastsdl 2.0.18 */ [[nodiscard]] inline auto ticks64() noexcept(noexcept(u64ms{uint64{}})) -> u64ms { return u64ms{SDL_GetTicks64()}; } #endif // SDL_VERSION_ATLEAST(2, 0, 18) /** * \brief Returns the amount of milliseconds since SDL was initialized. * * \return the time since SDL was initialized. * * \deprecated since 7.0.0, use `ticks64()` instead. */ [[nodiscard, deprecated]] inline auto ticks32() noexcept(noexcept(u32ms{uint32{}})) -> u32ms { return u32ms{SDL_GetTicks()}; } /// \} End of system counter functions /// \name System RAM functions /// \{ /** * \brief Returns the total amount of system RAM. * * \return the amount of RAM, in megabytes. */ [[nodiscard]] inline auto ram_mb() noexcept -> int { return SDL_GetSystemRAM(); } /** * \brief Returns the total amount of system RAM. * * \return the amount of RAM, in gigabytes. */ [[nodiscard]] inline auto ram_gb() noexcept -> int { return ram_mb() / 1'000; } /// \} End of system RAM functions /// \name Clipboard functions /// \{ /** * \brief Sets the current clipboard text. * * \param text the text that will be stored in the clipboard. * * \return `success` if the clipboard text was set; `failure` otherwise. */ inline auto set_clipboard(const char* text) noexcept -> result { assert(text); return SDL_SetClipboardText(text) == 0; } /// \copydoc set_clipboard() inline auto set_clipboard(const std::string& text) noexcept -> result { return set_clipboard(text.c_str()); } /** * \brief Indicates whether the clipboard exists and contains non-empty text. * * \return `true` if the clipboard has non-empty text; `false` otherwise. */ [[nodiscard]] inline auto has_clipboard() noexcept -> bool { return SDL_HasClipboardText(); } /** * \brief Returns the current text in the clipboard. * * \details If the clipboard cannot be obtained, this function returns an empty string. * * \return the current clipboard text. */ [[nodiscard]] inline auto get_clipboard() -> std::string { const sdl_string text{SDL_GetClipboardText()}; return text.copy(); } /// \} End of clipboard functions /// \name URL functions /// \{ #if SDL_VERSION_ATLEAST(2, 0, 14) /** * \brief Attempts to open a URL using a web browser (or file manager for local files). * * \details This function will return `success` if there was at least an attempt to open * the specified URL, but it doesn't mean that the URL was successfully loaded. * * \details This function will differ greatly in its effects depending on the current platform. * * \param url the URL that should be opened. * * \return `success` if there was an attempt to open the URL; `failure` otherwise. * * \atleastsdl 2.0.14 */ inline auto open_url(const char* url) noexcept -> result { assert(url); return SDL_OpenURL(url) == 0; } /// \copydoc open_url() inline auto open_url(const std::string& url) noexcept -> result { return open_url(url.c_str()); } #endif // SDL_VERSION_ATLEAST(2, 0, 14) /// \} End of URL functions /// \} End of group system } // namespace cen #endif // CENTURION_SYSTEM_SYSTEM_HPP_
23.810707
95
0.688589
Creeperface01
ad1fb0131c5a29a41edd18d9fb0e649b5d7f10ad
720
cpp
C++
LeetCode/Stone Game VII/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
LeetCode/Stone Game VII/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
null
null
null
LeetCode/Stone Game VII/main.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
null
null
null
class Solution { private: vector<vector<int>> dp; int solve(const vector<int>& stones, int i, int j, int score) { if (i == j) return 0; if (dp[i][j] != -1) return dp[i][j]; int a = score - stones[i] - solve(stones, i + 1, j, score - stones[i]); int b = score - stones[j] - solve(stones, i, j - 1, score - stones[j]); dp[i][j] = max(a, b); return dp[i][j]; } public: int stoneGameVII(vector<int>& stones) { dp.resize(stones.size(), vector<int>(stones.size(), -1)); return solve( stones, 0, stones.size() - 1, accumulate(cbegin(stones), cend(stones), 0)); } };
31.304348
80
0.483333
Code-With-Aagam
ad23c4a6535670596a0919f02e0ffc8317792fa6
2,038
cpp
C++
test/unit/std/ranges_test.cpp
BuildJet/seqan3
fc8cb3f1db119be30ec76f3d3cec3fecd7865c1c
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/std/ranges_test.cpp
BuildJet/seqan3
fc8cb3f1db119be30ec76f3d3cec3fecd7865c1c
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/std/ranges_test.cpp
BuildJet/seqan3
fc8cb3f1db119be30ec76f3d3cec3fecd7865c1c
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <gtest/gtest.h> #include <seqan3/std/ranges> #include <string> #include <range/v3/view/take.hpp> TEST(ranges_test, combine_std_with_range_v3) { std::string str{"foo"}; auto take_first = str | std::views::take(5) | ranges::view::take(1); EXPECT_EQ(*std::ranges::begin(take_first), 'f'); } // https://github.com/ericniebler/range-v3/issues/1514 TEST(ranges_test, gcc10bug_rangev3_1514) { { auto iota = std::views::iota(0, 5); EXPECT_EQ(*ranges::begin(iota), 0); EXPECT_EQ(*std::ranges::begin(iota), 0); } { // https://github.com/ericniebler/range-v3/issues/1514 auto iota = std::views::iota(size_t{0u}, size_t{5u}); EXPECT_EQ(*ranges::begin(iota), 0u); EXPECT_EQ(*std::ranges::begin(iota), 0u); } } // https://github.com/seqan/product_backlog/issues/372 TEST(ranges_test, issue372) { #ifdef __cpp_lib_ranges // >= gcc-10, range-v3 bug std::string vec{}; std::istringstream istringstream{vec}; auto v1 = std::ranges::subrange{std::istream_iterator<char>{istringstream}, std::default_sentinel}; auto v2 = std::views::take(v1, 1); using iterator2_t = std::ranges::iterator_t<decltype(v2)>; EXPECT_TRUE(std::indirectly_readable<iterator2_t>); EXPECT_TRUE(ranges::indirectly_readable<iterator2_t>); // this failed EXPECT_TRUE(std::input_iterator<iterator2_t>); EXPECT_TRUE(ranges::input_iterator<iterator2_t>); // this failed #endif // __cpp_lib_ranges }
36.392857
104
0.619725
BuildJet
ad241f5143dd0c66c6f68cc95c4b4d7f8d842ad8
6,264
cc
C++
blades/mediatomb/src/io_handler_buffer_helper.cc
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/mediatomb/src/io_handler_buffer_helper.cc
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/mediatomb/src/io_handler_buffer_helper.cc
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
/*MT* MediaTomb - http://www.mediatomb.cc/ io_handler_buffer_helper.cc - this file is part of MediaTomb. Copyright (C) 2005 Gena Batyan <bgeradz@mediatomb.cc>, Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc> Copyright (C) 2006-2010 Gena Batyan <bgeradz@mediatomb.cc>, Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc>, Leonhard Wimmer <leo@mediatomb.cc> MediaTomb is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. MediaTomb is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License version 2 along with MediaTomb; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. $Id$ */ /// \file io_handler_buffer_helper.cc #ifdef HAVE_CONFIG_H #include "autoconfig.h" #endif #include "io_handler_buffer_helper.h" #include "config_manager.h" #include "tools.h" using namespace zmm; IOHandlerBufferHelper::IOHandlerBufferHelper(size_t bufSize, size_t initialFillSize) : IOHandler() { if (bufSize <=0) throw _Exception(_("bufSize must be positive")); if (initialFillSize < 0 || initialFillSize > bufSize) throw _Exception(_("initialFillSize must be non-negative and must be lesser than or equal to the size of the buffer")); mutex = Ref<Mutex>(new Mutex()); cond = Ref<Cond>(new Cond(mutex)); this->bufSize = bufSize; this->initialFillSize = initialFillSize; waitForInitialFillSize = (initialFillSize > 0); buffer = NULL; isOpen = false; threadShutdown = false; eof = false; readError = false; a = b = posRead = 0; empty = true; signalAfterEveryRead = false; checkSocket = false; seekEnabled = false; doSeek = false; } void IOHandlerBufferHelper::open(IN enum UpnpOpenFileMode mode) { if (isOpen) throw _Exception(_("tried to reopen an open IOHandlerBufferHelper")); buffer = (char *)MALLOC(bufSize); if (buffer == NULL) throw _Exception(_("Failed to allocate memory for transcoding buffer!")); startBufferThread(); isOpen = true; } IOHandlerBufferHelper::~IOHandlerBufferHelper() { if (isOpen) close(); } int IOHandlerBufferHelper::read(OUT char *buf, IN size_t length) { // check read on closed BufferedIOHandler assert(isOpen); // length must be positive assert(length > 0); AUTOLOCK(mutex); while ((empty || waitForInitialFillSize) && ! (threadShutdown || eof || readError)) { if (checkSocket) { checkSocket = false; return CHECK_SOCKET; } else cond->wait(); } if (readError || threadShutdown) return -1; if (empty && eof) return 0; size_t bLocal = b; AUTOUNLOCK(); // we ensured with the while above that the buffer isn't empty int currentFillSize = bLocal - a; if (currentFillSize <= 0) currentFillSize += bufSize; size_t maxRead1 = (a < bLocal ? bLocal - a : bufSize - a); size_t read1 = (maxRead1 > length ? length : maxRead1); size_t maxRead2 = currentFillSize - read1; size_t read2 = (read1 < length ? length - read1 : 0); if (read2 > maxRead2) read2 = maxRead2; memcpy(buf, buffer + a, read1); if (read2) memcpy(buf + read1, buffer, read2); size_t didRead = read1+read2; AUTORELOCK(); bool signalled = false; // was the buffer full or became it "full" while we read? if (signalAfterEveryRead || a == b) { cond->signal(); signalled = true; } a += didRead; if (a >= bufSize) a -= bufSize; if (a == b) { empty = true; if (! signalled) cond->signal(); } posRead += didRead; return didRead; } void IOHandlerBufferHelper::seek(IN off_t offset, IN int whence) { log_debug("seek called: %lld %d\n", offset, whence); if (! seekEnabled) throw _Exception(_("seek currently disabled in this IOHandlerBufferHelper")); assert(isOpen); // check for valid input assert(whence == SEEK_SET || whence == SEEK_CUR || whence == SEEK_END); assert(whence != SEEK_SET || offset >= 0); assert(whence != SEEK_END || offset <= 0); // do nothing in this case if (whence == SEEK_CUR && offset == 0) return; AUTOLOCK(mutex); // if another seek isn't processed yet - well we don't care as this new seek // will change the position anyway doSeek = true; seekOffset = offset; seekWhence = whence; // tell the probably sleeping thread to process our seek cond->signal(); // wait until the seek has been processed while(doSeek && ! (threadShutdown || eof || readError)) cond->wait(); } void IOHandlerBufferHelper::close() { if (! isOpen) throw _Exception(_("close called on closed IOHandlerBufferHelper")); isOpen = false; stopBufferThread(); FREE(buffer); buffer = NULL; } // thread stuff... void IOHandlerBufferHelper::startBufferThread() { pthread_create( &bufferThread, NULL, // attr IOHandlerBufferHelper::staticThreadProc, this ); } void IOHandlerBufferHelper::stopBufferThread() { AUTOLOCK(mutex); threadShutdown = true; cond->signal(); AUTOUNLOCK(); if (bufferThread) pthread_join(bufferThread, NULL); bufferThread = 0; } void *IOHandlerBufferHelper::staticThreadProc(void *arg) { log_debug("starting buffer thread... thread: %d\n", pthread_self()); IOHandlerBufferHelper *inst = (IOHandlerBufferHelper *)arg; inst->threadProc(); log_debug("buffer thread shut down. thread: %d\n", pthread_self()); pthread_exit(NULL); return NULL; }
27.116883
127
0.626277
krattai
ad24c72b700631e2bc7c3305809dc33de94046ea
3,291
cpp
C++
examples/Reactor/WFMO_Reactor/Abandoned.cpp
azerothcore/lib-ace
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
[ "DOC" ]
null
null
null
examples/Reactor/WFMO_Reactor/Abandoned.cpp
azerothcore/lib-ace
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
[ "DOC" ]
null
null
null
examples/Reactor/WFMO_Reactor/Abandoned.cpp
azerothcore/lib-ace
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
[ "DOC" ]
1
2020-04-26T03:07:12.000Z
2020-04-26T03:07:12.000Z
//============================================================================= /** * @file Abandoned.cpp * * Tests the WFMO_Reactor's ability to handle abandoned mutexes. * * @author Irfan Pyarali <irfan@cs.wustl.edu> */ //============================================================================= #include "ace/OS_main.h" #if defined (ACE_WIN32) #include "ace/Reactor.h" #include "ace/Thread_Manager.h" #include "ace/Process_Mutex.h" #include "ace/Auto_Event.h" class Event_Handler : public ACE_Event_Handler { public: int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0); int handle_timeout (const ACE_Time_Value &tv, const void *arg = 0); ACE_Auto_Event handle_; ACE_Process_Mutex *mutex_; int iterations_; }; static int abandon = 1; static ACE_THR_FUNC_RETURN worker (void *data) { Event_Handler *handler = (Event_Handler *) data; handler->handle_.signal (); handler->mutex_->acquire (); if (!abandon) handler->mutex_->release (); return 0; } int Event_Handler::handle_signal (int, siginfo_t *s, ucontext_t *) { ACE_HANDLE handle = s->si_handle_; if (handle == this->handle_.handle ()) ACE_Reactor::instance ()->register_handler (this, this->mutex_->lock ().proc_mutex_); else { ACE_Reactor::instance ()->remove_handler (this->mutex_->lock ().proc_mutex_, ACE_Event_Handler::DONT_CALL); delete this->mutex_; } return 0; } int Event_Handler::handle_timeout (const ACE_Time_Value &, const void *) { --this->iterations_; ACE_DEBUG ((LM_DEBUG, "(%t) timeout occured @ %T, iterations left %d\n", this->iterations_)); if (this->iterations_ == 0) { ACE_Reactor::instance ()->remove_handler (this->handle_.handle (), ACE_Event_Handler::DONT_CALL); ACE_Reactor::instance ()->cancel_timer (this); ACE_Reactor::end_event_loop (); } else { ACE_NEW_RETURN (this->mutex_, ACE_Process_Mutex, -1); int result = ACE_Thread_Manager::instance ()->spawn (&worker, this); ACE_TEST_ASSERT (result != -1); } return 0; } int ACE_TMAIN (int , ACE_TCHAR *[]) { Event_Handler event_handler; event_handler.iterations_ = 5; int result = ACE_Reactor::instance ()->register_handler (&event_handler, event_handler.handle_.handle ()); ACE_TEST_ASSERT (result == 0); ACE_Time_Value timeout (2); result = ACE_Reactor::instance ()->schedule_timer (&event_handler, 0, timeout, timeout); ACE_TEST_ASSERT (result != -1); ACE_Reactor::run_event_loop (); return 0; } #else /* !ACE_WIN32 */ int ACE_TMAIN (int , ACE_TCHAR *[]) { return 0; } #endif /* ACE_WIN32 */
24.744361
84
0.508052
azerothcore
ad24f559138c35dfb5a8732db1b7a72982c7a9c3
6,445
cpp
C++
201922/dec201922_2.cpp
jibsen/aocpp2019
99cda72f6477bde0731c5fc958eebbc2219d6fb3
[ "MIT" ]
2
2020-04-26T17:31:31.000Z
2020-10-03T00:54:16.000Z
201922/dec201922_2.cpp
jibsen/aocpp2019
99cda72f6477bde0731c5fc958eebbc2219d6fb3
[ "MIT" ]
null
null
null
201922/dec201922_2.cpp
jibsen/aocpp2019
99cda72f6477bde0731c5fc958eebbc2219d6fb3
[ "MIT" ]
null
null
null
// // Advent of Code 2019, day 22, part two // // First we note that we do not need to perform the operations on an entire // deck to be able to track the position of one card through the shuffle. // // In the modular arithmetic of the deck, the stack shuffle is equivalent to // negating the position, the cut shuffle is adding or subtracting a number, // and the increment shuffle is multiplying by a number. // // So applying the shuffle process amounts to adding an offset and multiplying // by a number. #include <algorithm> #include <cstdint> #include <fstream> #include <iostream> #include <numeric> #include <string> #include <vector> enum class Shuffle { cut, increment, stack }; constexpr uint64_t num_cards = 119315717514047ULL; constexpr uint64_t num_rounds = 101741582076661ULL; std::vector<std::pair<Shuffle, int>> read_instructions(const char *filename) { std::ifstream infile(filename); std::string line; std::vector<std::pair<Shuffle, int>> instructions; while (std::getline(infile, line)) { if (line.size() > 4 && line.substr(0, 3) == "cut") { instructions.push_back({Shuffle::cut, std::stoi(line.substr(4))}); } else if (line.size() > 20 && line.substr(5, 4) == "with") { instructions.push_back({Shuffle::increment, std::stoi(line.substr(20))}); } else if (line.size() > 9 && line.substr(5, 4) == "into") { instructions.push_back({Shuffle::stack, 0}); } else { std::cout << "unable to parse " << line << '\n'; } } return instructions; } // From https://en.wikipedia.org/wiki/Modular_arithmetic constexpr uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t m) { uint64_t d = 0, mp2 = m >> 1; if (a >= m) { a %= m; } if (b >= m) { b %= m; } for (int i = 0; i < 64; ++i) { d = (d > mp2) ? (d << 1) - m : d << 1; if (a & 0x8000000000000000ULL) { d += b; } if (d >= m) { d -= m; } a <<= 1; } return d; } // From https://en.wikipedia.org/wiki/Modular_arithmetic constexpr uint64_t pow_mod(uint64_t a, uint64_t b, uint64_t m) { uint64_t r = m == 1 ? 0 : 1; while (b > 0) { if (b & 1) { r = mul_mod(r, a, m); } b = b >> 1; a = mul_mod(a, a, m); } return r; } uint64_t cut(uint64_t pos, int n) { if (n > 0) { if (pos >= n) { return pos - n; } return pos + (num_cards - n); } if (n < 0) { n = std::abs(n); if (pos >= num_cards - n) { return pos - (num_cards - n); } return pos + n; } return pos; } uint64_t uncut(uint64_t pos, int n) { return cut(pos, -n); } uint64_t deal_with_increment(uint64_t pos, int n) { if (pos == 0) { return 0; } if (std::numeric_limits<uint64_t>::max() / pos > n) { return (pos * n) % num_cards; } return mul_mod(pos, n, num_cards); } uint64_t undeal_with_increment(uint64_t pos, int n) { if (pos == 0) { return 0; } // Since num_cards is prime, the modular inverse of n is n**(num_cards - 2) uint64_t inv = pow_mod(static_cast<uint64_t>(n), num_cards - 2, num_cards); if (std::numeric_limits<uint64_t>::max() / pos > inv) { return (pos * inv) % num_cards; } return mul_mod(pos, inv, num_cards); } uint64_t deal_into_new_stack(uint64_t pos) { return num_cards - 1 - pos; } uint64_t undeal_into_new_stack(uint64_t pos) { return num_cards - 1 - pos; } uint64_t apply_shuffle(const std::vector<std::pair<Shuffle, int>> &instructions, uint64_t pos) { for (auto [type, arg] : instructions) { switch (type) { case Shuffle::cut: pos = cut(pos, arg); break; case Shuffle::increment: pos = deal_with_increment(pos, arg); break; case Shuffle::stack: pos = deal_into_new_stack(pos); break; default: std::cerr << "unknown shuffle method\n"; exit(1); } } return pos; } uint64_t apply_reverse_shuffle(const std::vector<std::pair<Shuffle, int>> &instructions, uint64_t pos) { for (auto [type, arg] : instructions) { switch (type) { case Shuffle::cut: pos = uncut(pos, arg); break; case Shuffle::increment: pos = undeal_with_increment(pos, arg); break; case Shuffle::stack: pos = undeal_into_new_stack(pos); break; default: std::cerr << "unknown shuffle method\n"; exit(1); } } return pos; } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "no program file\n"; exit(1); } auto instructions = read_instructions(argv[1]); std::cout << "shuffle size " << instructions.size() << "\n\n"; uint64_t offset = apply_shuffle(instructions, 0); uint64_t scale = apply_shuffle(instructions, 1) - offset; std::cout << "offset " << offset << '\n'; std::cout << "scale " << scale << "\n\n"; std::reverse(instructions.begin(), instructions.end()); uint64_t rev_offset = apply_reverse_shuffle(instructions, 0); uint64_t rev_scale = apply_reverse_shuffle(instructions, 1) - rev_offset; std::cout << "rev_offset " << rev_offset << '\n'; std::cout << "rev_scale " << rev_scale << "\n\n"; // We can compute the reverse values as well std::cout << "inv offset " << num_cards - mul_mod(offset, rev_scale, num_cards) << '\n'; std::cout << "inv scale " << pow_mod(scale, num_cards - 2, num_cards) << "\n\n"; // The reverse shuffle on 0 gives 41029399044649, and the difference // between consecutive values in the forward shuffle is 27693777298340. // // The forward shuffle on 0 gives 77186865627336, and the difference // between consecutive values in the reverse shuffle is 11189855674252. // // So we get the following equations for the shuffles: // // forward: (x - 41029399044649) * 27693777298340 // reverse: (x - 77186865627336) * 11189855674252 // // Applying the formula (x - a) * b iteratively to find the source of // position x yields // // x(k) = b**k * x - b**k * a - b**(k - 1) * a - ... - ba // = b**k * x - b * a * (b**(k - 1) + b**(k - 2) + .. + b + 1) // = b**k * x - b * a * ((b**k - 1) / (b - 1)) // const uint64_t a = offset; const uint64_t b = rev_scale; // b**k const uint64_t bpow = pow_mod(b, num_rounds, num_cards); // 1 / (b - 1) const uint64_t bm1inv = pow_mod(b - 1, num_cards - 2, num_cards); // b * a * ((b**k - 1) / (b - 1)) uint64_t t2 = mul_mod(bpow - 1, bm1inv, num_cards); t2 = mul_mod(t2, a, num_cards); t2 = mul_mod(t2, b, num_cards); // b**k * x const uint64_t t1 = mul_mod(bpow, 2020, num_cards); if (t2 > t1) { std::cout << "source of position 2020 = " << t1 + (num_cards - t2) << '\n'; } else { std::cout << "source of position 2020 = " << t1 - t2 << '\n'; } return 0; }
24.788462
102
0.627463
jibsen
ad2587790e4642af3664d49bf1e33864189186c3
4,384
cpp
C++
lesson23/example13/share/MyString.cpp
Youngfellows/LinuxCPP
6148346ba2c5c0a6d29a4f3a564baf9f06d619fe
[ "Apache-2.0" ]
null
null
null
lesson23/example13/share/MyString.cpp
Youngfellows/LinuxCPP
6148346ba2c5c0a6d29a4f3a564baf9f06d619fe
[ "Apache-2.0" ]
null
null
null
lesson23/example13/share/MyString.cpp
Youngfellows/LinuxCPP
6148346ba2c5c0a6d29a4f3a564baf9f06d619fe
[ "Apache-2.0" ]
null
null
null
#include "../include/MyString.h" //在类外实现函数 - 构造函数 MyString::MyString() { cout << "MyString()构造函数" << endl; } //在类外实现函数 - 析构函数 MyString::~MyString() { cout << "~MyString()析构函数" << endl; cout << endl; } //在类外实现函数 - compare()函数 int MyString::compare(char *s1,char *s2) { cout << "compare() ..." << endl; int i = 0; while (*(s1 + i) == *(s2 + i)) { if (*(s1 + i) == '\0') { return 0;//全部字符相同返回0 } i++; } //字符不同时返回第一个不同字符的ASCII码差值 return (*(s1 + i) - *(s2 + i)); } //在类外实现函数 - input()函数 char ** MyString::input()//输入二维数组 { cout << "input():: ..." << endl; cout << "请输入" << SIZE << "个字符串" << endl; char buffer[LEN];//临时缓冲区 char *s = buffer;//指针变量s,s指向字符串buffer for(int i = 0; i < SIZE; i++) { fgets(s,LEN,stdin);//输入字符串 //拷贝字符串到字符数组 strcpy(this->str[i],s); } return get(); } //重点: 输入二维数组,返回指向一维数组的指针来实现,函数的参数是void char (*MyString::input2())[LEN] { cout << "input2():: ..." << endl; cout << "请输入" << SIZE << "个字符串" << endl; char buffer[LEN];//临时缓冲区 char *s = buffer;//指针变量s,s指向字符串buffer for(int i = 0; i < SIZE; i++) { fgets(s,LEN,stdin);//输入字符串 //拷贝字符串到字符数组 strcpy(this->str[i],s); } return get2(); } //在类外实现函数 - get()函数 char ** MyString::get()//获取二维数组,重点: 通过指向指针的指针来实现返回二维数组 { cout << "get():: ..." << endl; //动态申请内存,并返回一个二维数组 char **p = (char **)malloc(SIZE * sizeof(char *));//申请一个含有SIZE个char *元素的连续空间,及是一个二维数组 //为二维数组赋值 for(int i = 0; i < SIZE; i++) { //cout << "(p + " << i <<")=" << (p + i) << endl; //cout << "this->str[" << i <<"]=" << this->str[i] << endl; *(p + i) = this->str[i]; } return p; } //重点: 获取二维数组,通过指向一维数组的指针来实现 char (*MyString::get2())[LEN] { cout << "get2():: ..." << endl; //动态申请内存,返回一个指向一维数组的指针变量 char (*data)[LEN] = new char[SIZE][LEN]; data = this->str;//data指针变量指向二维数组str的0行元素 return data; } //在类外实现函数 - sort()函数 char ** MyString::sort()//对二维数组进行排序 { cout << "sort():: ..." << endl; char buff[LEN];//缓冲区 char *p = buff;//char *型指针变量p指向字符串buff for(int i = 0; i < SIZE; i++) { for(int j = i + 1; j < SIZE; j++) { //比较后,交换字符串的地址 if(strcmp(this->str[i],this->str[j]) > 0) { strcpy(p,this->str[i]); strcpy(this->str[i],this->str[j]); strcpy(this->str[j],p); } } } return get(); } //在类外实现函数 - sort()函数 char ** MyString::sort(char **s)//对二维数组进行排序 { cout << "sort():: 1 ..." << endl; char buff[LEN];//缓冲区 char *p = buff;//char *型指针变量p指向字符串buff for(int i = 0; i < SIZE; i++) { for(int j = i + 1; j < SIZE; j++) { //比较后,交换字符串的地址 if(strcmp(*(s + i),*(s + j)) > 0) { strcpy(p,*(s + i)); strcpy(*(s + i),*(s + j)); strcpy(*(s + j),p); } } } return get(); } //重点: 返回一个二维数组,通过指向一维数组的指针来实现.参数也是一个指向一维数组的指针(也是二维数组) char (*MyString::sort(char (*s)[LEN]))[LEN] { cout << "sort():: 2 ..." << endl; char buff[LEN];//缓冲区 char *p = buff;//char *型指针变量p指向字符串buff for(int i = 0; i < SIZE; i++) { for(int j = i + 1; j < SIZE; j++) { //比较后,交换字符串的地址 if(strcmp(*(s + i),*(s + j)) > 0) { strcpy(p,*(s + i)); strcpy(*(s + i),*(s + j)); strcpy(*(s + j),p); } } } return get2(); } //在类外实现函数 - display()函数 void MyString::display()//显示二维数组 { cout << "display():: ..." << endl; for(int i = 0; i < SIZE; i++) { cout << *(str + i); } cout << endl; } //在类外实现函数 - display()函数 void MyString::display(char **s)//显示二维数组 { cout << "display():: 1 ..." << endl; for(int i = 0; i < SIZE; i++) { cout << *(s+i); } cout << endl; } //在类外实现函数 - display()函数 void MyString::display(char (*s)[LEN])//显示二维数组 { cout << "display():: 2 ..." << endl; for(int i = 0; i < SIZE; i++) { cout << *(s + i) ; } cout << endl; }
22.95288
90
0.430885
Youngfellows
ad2a1afdd614128fb7569d950746c6408c1812d9
2,076
cpp
C++
v2/src/Neuron.cpp
cherosene/learning_algorithms
8ec9d8b7f744a375170ac2396cfb8bc216f84f53
[ "MIT" ]
null
null
null
v2/src/Neuron.cpp
cherosene/learning_algorithms
8ec9d8b7f744a375170ac2396cfb8bc216f84f53
[ "MIT" ]
null
null
null
v2/src/Neuron.cpp
cherosene/learning_algorithms
8ec9d8b7f744a375170ac2396cfb8bc216f84f53
[ "MIT" ]
null
null
null
#include "Neuron.h" #include <iostream> #include <cmath> unsigned int Neuron::idGenerator = 0; const std::function<float(float)> Neuron::SIGMOID = [](float r){ float res = 1 + exp(-r); return 1/res; }; const std::function<float(float)> Neuron::SIGMOID_DER = [](float r){ float res = 2 * ( cosh(r) + 1 ); return 1/res; }; Neuron::Neuron(std::function<float(float)> activationFunciton) { Neuron(activationFunciton, computeDerivative(activationFunciton) ); } Neuron::Neuron(std::function<float(float)> activationFunciton, std::function<float(float)> activationFuncitonDerivative) { id = idGenerator; idGenerator++; af = activationFunciton; afD = activationFuncitonDerivative; init(); } void Neuron::in(float value) { inputValue += value; } void Neuron::in(float weight, float nwValue) { inputValue += weight * nwValue; } float Neuron::out() { if(isForwardPhase) { computeOutput(); } return outputValue; } void Neuron::err(float errorToAdd) { accumulatedError += errorToAdd; } float Neuron::errModifier() { return afD(inputValue); } float Neuron::delta() { return deltaValue; } void Neuron::newRound() { inputValue = 0; outputValue = 0; accumulatedError = 0; isForwardPhase = true; } void Neuron::learn() { computeDelta(); } // neuron methods void Neuron::computeOutput() { // if(!isForwardPhase) { // throw NeuronException(id); // } outputValue = af(inputValue); isForwardPhase = false; } void Neuron::computeDelta() { // if(isForwardPhase) { // throw NeuronException(id); // } deltaValue = afD(inputValue) * accumulatedError; } // foo void Neuron::init() { isForwardPhase = true; inputValue = 0; outputValue = 0; deltaValue = 0; accumulatedError = 0; } std::function<float(float)> Neuron::computeDerivative(std::function<float(float)> fun) { std::cout << "computeDerivative: Not implemented yet." << std::endl; exit(-1); }
21.402062
122
0.630058
cherosene
ad2e5639aecfa16fcd70bc9b17e518eacc9fb232
655
cpp
C++
Chapter 3. Strings, Vectors, and Arrays/Codes/3.45.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 3. Strings, Vectors, and Arrays/Codes/3.45.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 3. Strings, Vectors, and Arrays/Codes/3.45.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
1
2021-09-30T14:08:03.000Z
2021-09-30T14:08:03.000Z
#include <iostream> using std::cout; using std::endl; int main() { int ia[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // Use a range for to manage the iteration // Use auto for (auto& p : ia) for (auto& q : p) cout << q << " "; cout << endl; // Use ordinary for loop using subscripts // Use auto for (auto i = 0; i != 3; ++i) for (auto j = 0; j != 4; ++j) cout << ia[i][j] << " "; cout << endl; // Use pointers. // Use auto for (auto p = ia; p != ia + 3; ++p) for (int* q = *p; q != *p + 4; ++q) cout << *q << " "; cout << endl; return 0; }
20.46875
62
0.432061
Yunxiang-Li
ad330f3b84f5f441445ee356b83ff25d021f5abb
56,000
cpp
C++
tests/rtest_ac_chol_d.cpp
dgburnette/ac_math
518629af779ae26167462055ea4a3c30738ba5f9
[ "Apache-2.0" ]
2
2018-03-22T08:46:54.000Z
2018-04-03T06:09:00.000Z
tests/rtest_ac_chol_d.cpp
dgburnette/ac_math
518629af779ae26167462055ea4a3c30738ba5f9
[ "Apache-2.0" ]
null
null
null
tests/rtest_ac_chol_d.cpp
dgburnette/ac_math
518629af779ae26167462055ea4a3c30738ba5f9
[ "Apache-2.0" ]
null
null
null
/************************************************************************** * * * Algorithmic C (tm) Math Library * * * * Software Version: 3.4 * * * * Release Date : Wed May 4 10:47:29 PDT 2022 * * Release Type : Production Release * * Release Build : 3.4.3 * * * * Copyright 2018 Siemens * * * ************************************************************************** * 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. * ************************************************************************** * * * The most recent version of this package is available at github. * * * *************************************************************************/ // =========================TESTBENCH======================================= // This testbench file contains a stand-alone testbench that exercises the // ac_chol_d() function using a variety of data types and bit- // widths. // To compile standalone and run: // $MGC_HOME/bin/c++ -std=c++11 -I$MGC_HOME/shared/include rtest_ac_chol_d.cpp -o design // ./design // Include the AC Math function that is exercised with this testbench #include <ac_math/ac_chol_d.h> using namespace ac_math; // ============================================================================== // Test Designs // These simple functions allow executing the ac_chol_d() function // using multiple data types at the same time. Template parameters are // used to configure the bit-widths of the types. // Test Design for real and complex fixed point values. template <bool use_pwl, unsigned M, int Wfi, int Ifi, int outWfi, int outIfi, bool outSfi> void test_ac_chol_d_fixed( const ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP> A1[M][M], ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> L1[M][M], const ac_complex<ac_fixed<Wfi + 1, Ifi + 1, true, AC_TRN, AC_WRAP> > A2[M][M], ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> > L2[M][M], const ac_matrix<ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP>, M, M> &A3, ac_matrix<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP>, M, M> &L3, const ac_matrix<ac_complex<ac_fixed<Wfi + 1, Ifi + 1, true, AC_TRN, AC_WRAP> >, M, M> &A4, ac_matrix<ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> >, M, M> &L4 ) { ac_chol_d<use_pwl>(A1, L1); ac_chol_d<use_pwl>(A2, L2); ac_chol_d<use_pwl>(A3, L3); ac_chol_d<use_pwl>(A4, L4); } // Test Design for real ac_float values. template <bool use_pwl, unsigned M, int Wfl, int Ifl, int Efl, int outWfl, int outIfl, int outEfl> void test_ac_chol_d_float( const ac_float<Wfl, Ifl, Efl, AC_TRN> A1[M][M], ac_float<outWfl, outIfl, outEfl, AC_TRN> L1[M][M], const ac_matrix<ac_float<Wfl, Ifl, Efl, AC_TRN>, M, M> &A2, ac_matrix<ac_float<outWfl, outIfl, outEfl, AC_TRN>, M, M> &L2 ) { ac_chol_d<use_pwl>(A1, L1); ac_chol_d<use_pwl>(A2, L2); } // Test Design for real ac_std_float values. template <bool use_pwl, unsigned M, int Wstfl, int Estfl, int outWstfl, int outEstfl> void test_ac_chol_d_stfloat( const ac_std_float<Wstfl, Estfl> A1[M][M], ac_std_float<outWstfl, outEstfl> L1[M][M], const ac_matrix<ac_std_float<Wstfl, Estfl>, M, M> &A2, ac_matrix<ac_std_float<outWstfl, outEstfl>, M, M> &L2 ) { ac_chol_d<use_pwl>(A1, L1); ac_chol_d<use_pwl>(A2, L2); } // Test Design for real ac_ieee_float values. template <bool use_pwl, unsigned M, ac_ieee_float_format in_format, ac_ieee_float_format out_format> void test_ac_chol_d_ifloat( const ac_ieee_float<in_format> A1[M][M], ac_ieee_float<out_format> L1[M][M], const ac_matrix<ac_ieee_float<in_format>, M, M> &A2, ac_matrix<ac_ieee_float<out_format>, M, M> &L2 ) { ac_chol_d<use_pwl>(A1, L1); ac_chol_d<use_pwl>(A2, L2); } // ============================================================================== #include <ac_math/ac_normalize.h> using namespace ac_math; #include <math.h> #include <string> #include <fstream> #include <limits> #include <random> #include <iostream> using namespace std; // ------------------------------------------------------------------------------ // Helper functions // Helper structs for printing out type info for ac_std_float and ac_ieee_float // Generic struct, enables template specialization template <typename T> struct type_string_st { }; // Specialized struct, handles ac_std_floats template <int W, int E> struct type_string_st<ac_std_float<W, E> > { static string type_string() { string format_string = "ac_std_float<"; format_string += ac_int<32,true>(W).to_string(AC_DEC); format_string += ","; format_string += ac_int<32,true>(E).to_string(AC_DEC); format_string += ">"; return format_string; } }; // Specialized struct, handles ac_ieee_floats template <ac_ieee_float_format Format> struct type_string_st<ac_ieee_float<Format> > { static string type_string() { string format_string = "ac_ieee_float<"; if (Format == binary16) { format_string += "binary16"; } if (Format == binary32) { format_string += "binary32"; } if (Format == binary64) { format_string += "binary64"; } if (Format == binary128) { format_string += "binary128"; } if (Format == binary256) { format_string += "binary256"; } format_string += ">"; return format_string; } }; #ifdef DEBUG // print_matrix functions: Print 2D C-style matrix for debugging purposes. // print_matrix for ac_fixed/ac_complex<ac_fixed>/ac_float matrix. template<unsigned M, class T> void print_matrix(const T mat[M][M]) { cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << endl; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {cout << "mat[" << i << "][" << j << "] = " << mat[i][j] << endl;} } } // print_matrix for ac_std_float matrix. template<unsigned M, int W, int E> void print_matrix(const ac_std_float<W, E> mat[M][M]) { cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << endl; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {cout << "mat[" << i << "][" << j << "] = " << mat[i][j].to_ac_float().to_double() << endl;} } } // print_matrix for ac_ieee_float matrix. template<unsigned M, ac_ieee_float_format Format> void print_matrix(const ac_ieee_float<Format> mat[M][M]) { cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << endl; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {cout << "mat[" << i << "][" << j << "] = " << mat[i][j].to_ac_float().to_double() << endl;} } } #endif // Generate positive definite matrix of ac_fixed values template<unsigned M, int W, int I, bool S, ac_q_mode Q, ac_o_mode O> void gen_matrix(ac_fixed<W, I, S, Q, O> A[M][M]) { static_assert(I - int(S) >= ac::nbits<M - 1>::val, "Not enough integer bits in input type."); static_assert(W - I >= 2, "Input type must have at least 2 fractional bits."); // Declare two MxM matrices, once of which (tbmatT) is the transpose of the other. ac_fixed<(W - I)/2, 0, false> tbmat[M][M]; ac_fixed<(W - I)/2, 0, false> tbmatT[M][M]; // Make sure the minimum limit for the random number generator is the quantum double value. double min_rand_limit = std::numeric_limits<double>::min(); // default_random_engine and uniform_real_distribution are libraries from the <random> header, // packaged with C++11 and later standards. default_random_engine generator; // Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix. // The output produced by this is similar to that of matlab's "rand" function, i.e. a randomly // selected value picked out of a uniform probability density in the range of (0, 1). uniform_real_distribution<double> distribution(min_rand_limit, 1.0); for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { tbmat[i][j] = distribution(generator); tbmatT[j][i] = tbmat[i][j]; } } #ifdef DEBUG cout << "tbmat is : " << endl; print_matrix(tbmat); cout << "tbmatT is : " << endl; print_matrix(tbmatT); #endif // Multiply tbmat by its transpose to get the positive definite input matrix for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { A[i][j] = 0; for (int k = 0; k < (int)M; k++) { A[i][j] += tbmat[i][k] * tbmatT[k][j]; } } } #ifdef DEBUG cout << "A in gen_matrix function is : " << endl; print_matrix(A); #endif } // Generate positive definite matrix of ac_complex<ac_fixed> values template<unsigned M, int W, int I, bool S, ac_q_mode Q, ac_o_mode O> void gen_matrix(ac_complex<ac_fixed<W, I, S, Q, O> > A[M][M]) { static_assert(S, "Input type must be signed"); static_assert(I - 1 >= ac::nbits<M - 1>::val, "Not enough integer bits in input type."); static_assert(W - I >= 4, "Input type must have at least 4 fractional bits."); // Declare two MxM matrices, once of which (tbmatT) is the conjugate transpose of the other. ac_complex<ac_fixed<(W - I)/2, 0, true> > tbmat[M][M]; ac_complex<ac_fixed<(W - I)/2, 0, true> > tbmatT[M][M]; // Make sure the minimum limit for the random number generator is the quantum double value. double min_rand_limit = std::numeric_limits<double>::min(); // default_random_engine and uniform_real_distribution are libraries from the <random> header, // packaged with C++11 and later standards. default_random_engine generator; // Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix. uniform_real_distribution<double> distribution(min_rand_limit, 0.5); for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { ac_fixed<(W - I)/2 - 1, -1, false> rand_val; tbmat[i][j].r() = distribution(generator); tbmat[i][j].i() = distribution(generator); tbmatT[j][i] = tbmat[i][j].conj(); } } #ifdef DEBUG cout << "tbmat is : " << endl; print_matrix(tbmat); cout << "tbmatT is : " << endl; print_matrix(tbmatT); #endif // Multiply tbmat by its transpose to get the positive definite input matrix for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { A[i][j] = 0; for (int k = 0; k < (int)M; k++) { A[i][j] += tbmat[i][k] * tbmatT[k][j]; } } } #ifdef DEBUG cout << "A in gen_matrix function is : " << endl; print_matrix(A); #endif } // Generate positive definite matrix of ac_float values template<unsigned M, int W, int I, int E, ac_q_mode Q> void gen_matrix(ac_float<W, I, E, Q> A[M][M]) { static_assert(I >= 1, "Input mantissa must have at least 1 integer bit."); static_assert(W >= ac::nbits<M - 1>::val + 2 + 1, "Not enough bitwidth for mantissa."); enum { max_int_val = ac::nbits<M - 1>::val, E_val_1 = ac::nbits<W - 1>::val, val_2 = (max_int_val - (I - 1) < 0) ? -(max_int_val - (I - 1)) : max_int_val - (I - 1), E_val_2 = ac::nbits<AC_MAX(val_2, 1)>::val, E_min = AC_MAX(int(E_val_1), int(E_val_2)) + 1, }; static_assert(E >= E_min, "Not enough exponent bits."); // Make sure the minimum limit for the random number generator is the quantum double value. double min_rand_limit = std::numeric_limits<double>::min(); // default_random_engine and uniform_real_distribution are libraries from the <random> header, // packaged with C++11 and later standards. default_random_engine generator; // Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix. // The output produced by this is similar to that of matlab's "rand" function, i.e. a randomly // selected value picked out of a uniform probability density in the range of (0, 1). uniform_real_distribution<double> distribution(min_rand_limit, 1.0); ac_fixed<(W - max_int_val - 1)/2, 0, false> tbmat[M][M], tbmatT[M][M]; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { tbmat[i][j] = distribution(generator); tbmatT[j][i] = tbmat[i][j]; } } ac_fixed<W - 1, max_int_val, false> mac_val; // Multiply tbmat by its transpose to get the positive definite input matrix for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { mac_val = 0; for (int k = 0; k < (int)M; k++) { mac_val += tbmat[i][k] * tbmatT[k][j]; } A[i][j] = mac_val; } } #ifdef DEBUG cout << "tbmat:" << endl; print_matrix(tbmat); cout << "tbmatT:" << endl; print_matrix(tbmatT); cout << "A:" << endl; print_matrix(A); #endif } // Generate positive definite matrix of ac_std_float values template<unsigned M, int W, int E> void gen_matrix(ac_std_float<W, E> A[M][M]) { static_assert(W - E - 1 >= ac::nbits<M - 1>::val + 2 + 1, "Not enough bitwidth for mantissa."); enum { max_int_val = ac::nbits<M - 1>::val, E_val_1 = ac::nbits<W - E - 1>::val, E_val_2 = ac::nbits<AC_MAX(max_int_val - 1, 1)>::val, E_min = AC_MAX(int(E_val_1), int(E_val_2)) + 1, }; static_assert(E >= E_min, "Not enough exponent bits."); // Make sure the minimum limit for the random number generator is the quantum double value. double min_rand_limit = std::numeric_limits<double>::min(); // default_random_engine and uniform_real_distribution are libraries from the <random> header, // packaged with C++11 and later standards. default_random_engine generator; // Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix. // The output produced by this is similar to that of matlab's "rand" function, i.e. a randomly // selected value picked out of a uniform probability density in the range of (0, 1). uniform_real_distribution<double> distribution(min_rand_limit, 1.0); ac_fixed<(W - E - max_int_val - 1)/2, 0, false> tbmat[M][M], tbmatT[M][M]; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { tbmat[i][j] = distribution(generator); tbmatT[j][i] = tbmat[i][j]; } } ac_fixed<W - E - 1, max_int_val, false> mac_val; // Multiply tbmat by its transpose to get the positive definite input matrix for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { mac_val = 0; for (int k = 0; k < (int)M; k++) { mac_val += tbmat[i][k] * tbmatT[k][j]; } A[i][j] = ac_std_float<W, E>(mac_val); } } #ifdef DEBUG cout << "tbmat:" << endl; print_matrix(tbmat); cout << "tbmatT:" << endl; print_matrix(tbmatT); cout << "A_ac_fl:" << endl; print_matrix(A_ac_fl); #endif } // Generate positive definite matrix of ac_ieee_float values template<unsigned M, ac_ieee_float_format Format> void gen_matrix(ac_ieee_float<Format> A[M][M]) { typedef ac_ieee_float<Format> T_in; enum { W = T_in::width, E = T_in::e_width, max_int_val = ac::nbits<M - 1>::val, }; // Make sure the minimum limit for the random number generator is the quantum double value. double min_rand_limit = std::numeric_limits<double>::min(); // default_random_engine and uniform_real_distribution are libraries from the <random> header, // packaged with C++11 and later standards. default_random_engine generator; // Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix. // The output produced by this is similar to that of matlab's "rand" function, i.e. a randomly // selected value picked out of a uniform probability density in the range of (0, 1). uniform_real_distribution<double> distribution(min_rand_limit, 1.0); ac_fixed<(W - E - max_int_val - 1)/2, 0, false> tbmat[M][M], tbmatT[M][M]; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { tbmat[i][j] = distribution(generator); tbmatT[j][i] = tbmat[i][j]; } } ac_fixed<W - E - 1, max_int_val, false> mac_val; // Multiply tbmat by its transpose to get the positive definite input matrix for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { mac_val = 0; for (int k = 0; k < (int)M; k++) { mac_val += tbmat[i][k] * tbmatT[k][j]; } A[i][j] = ac_ieee_float<Format>(mac_val); } } #ifdef DEBUG cout << "tbmat:" << endl; print_matrix(tbmat); cout << "tbmatT:" << endl; print_matrix(tbmatT); cout << "A_ac_fl:" << endl; print_matrix(A_ac_fl); #endif } // Testbench for cholesky decomposition for ac_fixed matrix // The testbench uses the cholesky-crout algorithm template<unsigned M, int W, int I, bool S, ac_q_mode Q, ac_o_mode O> void chol_d_tb( const ac_fixed<W, I, S, Q, O> A[M][M], double L_tb[M][M] ) { double sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk; // All elements of output initialized to zero by default for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {L_tb[i][j] = 0;} } // L_tb = 0; for (int j = 0; j < (int)M; j++) { sum_Ajj_Ljk_sq = A[j][j].to_double(); for (int k = 0; k < j; k++) { sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k]; } // Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal // element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the // input matrix is positive definite assert(sum_Ajj_Ljk_sq > 0); // Assign value to diagonal elements. L_tb[j][j] = sqrt(sum_Ajj_Ljk_sq); for (int i = (j+1); i < (int)M; i++) { sum_Aij_Lik_Ljk = A[i][j].to_double(); for (int k = 0; k < j; k++) { sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k]; } // Assign value to non-diagonal elements below the diagonal. L_tb[i][j] = sum_Aij_Lik_Ljk / L_tb[j][j]; } } } // Testbench for cholesky decomposition for ac_complex<ac_fixed> matrices // The testbench uses the cholesky-crout algorithm template<unsigned M, int W, int I, bool S, ac_q_mode Q, ac_o_mode O> void chol_d_tb( ac_complex<ac_fixed<W, I, S, Q, O> > A[M][M], ac_complex<double> L_tb[M][M] ) { typedef ac_complex<double> output_type; output_type zero_complex(0, 0), sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk; // All elements of output initialized to zero by default for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {L_tb[i][j] = zero_complex;} } // L_tb = zero_complex; for (int j = 0; j < (int)M; j++) { sum_Ajj_Ljk_sq.r() = A[j][j].r().to_double(); sum_Ajj_Ljk_sq.i() = A[j][j].i().to_double(); for (int k = 0; k < j; k++) { sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k].conj(); } // Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal // element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the // input matrix is positive definite assert(sum_Ajj_Ljk_sq.r() > 0); // Assign value to diagonal elements. Since the diagonal elements are real, only initialize the real part. L_tb[j][j].r() = sqrt(sum_Ajj_Ljk_sq.r()); for (int i = (j+1); i < (int)M; i++) { sum_Aij_Lik_Ljk.r() = A[i][j].r().to_double(); sum_Aij_Lik_Ljk.i() = A[i][j].i().to_double(); for (int k = 0; k < j; k++) { sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k].conj(); } // Assign value to non-diagonal elements below the diagonal. L_tb[i][j].r() = (1 / L_tb[j][j].r())*sum_Aij_Lik_Ljk.r(); L_tb[i][j].i() = (1 / L_tb[j][j].r())*sum_Aij_Lik_Ljk.i(); } } } // Testbench for cholesky decomposition for ac_float matrix // The testbench uses the cholesky-crout algorithm template<unsigned M, int W, int I, int E, ac_q_mode Q> void chol_d_tb( const ac_float<W, I, E, Q> A[M][M], double L_tb[M][M] ) { double sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk; // All elements of output initialized to zero by default for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {L_tb[i][j] = 0.0;} } for (int j = 0; j < (int)M; j++) { sum_Ajj_Ljk_sq = A[j][j].to_double(); for (int k = 0; k < j; k++) { sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k]; } // Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal // element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the // input matrix is positive definite assert(sum_Ajj_Ljk_sq > 0); // Assign value to diagonal elements. L_tb[j][j] = sqrt(sum_Ajj_Ljk_sq); for (int i = (j+1); i < (int)M; i++) { sum_Aij_Lik_Ljk = A[i][j].to_double(); for (int k = 0; k < j; k++) { sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k]; } // Assign value to non-diagonal elements below the diagonal. L_tb[i][j] = sum_Aij_Lik_Ljk / L_tb[j][j]; } } } // Testbench for cholesky decomposition for ac_std_float matrix // The testbench uses the cholesky-crout algorithm template<unsigned M, int W, int E> void chol_d_tb( const ac_std_float<W, E> A[M][M], double L_tb[M][M] ) { double sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk; // All elements of output initialized to zero by default for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {L_tb[i][j] = 0.0;} } for (int j = 0; j < (int)M; j++) { sum_Ajj_Ljk_sq = A[j][j].to_ac_float().to_double(); for (int k = 0; k < j; k++) { sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k]; } // Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal // element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the // input matrix is positive definite assert(sum_Ajj_Ljk_sq > 0); // Assign value to diagonal elements. L_tb[j][j] = sqrt(sum_Ajj_Ljk_sq); for (int i = (j+1); i < (int)M; i++) { sum_Aij_Lik_Ljk = A[i][j].to_ac_float().to_double(); for (int k = 0; k < j; k++) { sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k]; } // Assign value to non-diagonal elements below the diagonal. L_tb[i][j] = sum_Aij_Lik_Ljk / L_tb[j][j]; } } } // Testbench for cholesky decomposition for ac_ieee_float matrix // The testbench uses the cholesky-crout algorithm template<unsigned M, ac_ieee_float_format Format> void chol_d_tb( const ac_ieee_float<Format> A[M][M], double L_tb[M][M] ) { double sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk; // All elements of output initialized to zero by default for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {L_tb[i][j] = 0.0;} } for (int j = 0; j < (int)M; j++) { sum_Ajj_Ljk_sq = A[j][j].to_ac_float().to_double(); for (int k = 0; k < j; k++) { sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k]; } // Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal // element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the // input matrix is positive definite assert(sum_Ajj_Ljk_sq > 0); // Assign value to diagonal elements. L_tb[j][j] = sqrt(sum_Ajj_Ljk_sq); for (int i = (j+1); i < (int)M; i++) { sum_Aij_Lik_Ljk = A[i][j].to_ac_float().to_double(); for (int k = 0; k < j; k++) { sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k]; } // Assign value to non-diagonal elements below the diagonal. L_tb[i][j] = sum_Aij_Lik_Ljk / L_tb[j][j]; } } } // Return the absolute value of the matrix element that has the // maximum absolute value. template<unsigned M> double abs_mat_max( const double L_tb[M][M] ) { double max_val = 0; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { if (abs(L_tb[i][j]) > max_val) {max_val = abs(L_tb[i][j]);} } } return max_val; } // Return the absolute value of the matrix element that has the // maximum absolute value. template<unsigned M> double abs_mat_max( const ac_complex<double> L_tb[M][M] ) { double max_val = 0; for (int i = 0; i < M; i++) { for (int j = 0; j < M; j++) { if (L_tb[i][j].mag_sqr() > max_val) {max_val = L_tb[i][j].mag_sqr();} } } return max_val; } // Keep real, double element as it is (just kept in order to ensure that the error checking // function is compatible even for real, double values) double conv_val(double x) { return x; } // Convert real, ac_fixed element to double. template<int W, int I, bool S, ac_q_mode Q, ac_o_mode O> double conv_val(ac_fixed<W, I, S, Q, O> x) { return x.to_double(); } // Convert complex double element to mag_sqr. double conv_val(ac_complex<double> x) { return x.mag_sqr(); } // Convert complex ac_fixed element to the double of it's // mag_sqr template<int W, int I, bool S, ac_q_mode Q, ac_o_mode O> double conv_val(ac_complex<ac_fixed<W, I, S, Q, O> > x) { return x.mag_sqr().to_double(); } // Convert real, ac_float element to double. template <int W, int I, int E, ac_q_mode Q> double conv_val(ac_float<W, I, E, Q> x) { return x.to_double(); } // Convert real, ac_std_float element to double. template <int W, int E> double conv_val(ac_std_float<W, E> x) { return x.to_ac_float().to_double(); } // Convert real, ac_ieee_float element to double. template <ac_ieee_float_format Format> double conv_val(ac_ieee_float<Format> x) { return x.to_ac_float().to_double(); } // Compare DUT output matrix to testbench computed matrix and find error. template<unsigned M, class T, class T_tb> double compare_matrices( const T L[M][M], const T_tb L_tb[M][M], const double allowed_error ) { double this_error, max_error = 0, max_val; // Find the max. abs. value in the matrix. In case of complex matrices, this is the max. // mag_sqr value. For real matrices, it's the max. absolute value stored in the matrix. max_val = abs_mat_max(L_tb); #ifdef DEBUG cout << "max_val = " << max_val << endl; #endif for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { // The error is calculated as the difference between the value of the expected // vs. the actual value, normalized w.r.t. the max_value in the matrix. For complex // numbers, the expected vs actual values are first converted to the their // mag_sqr() representations. For real numbers, the values are passed as they are // for the error calculation. this_error = 100.0 * abs( conv_val(L[i][j]) - conv_val(L_tb[i][j]) ) / (max_val); if (this_error > max_error) { max_error = this_error;} #ifdef DEBUG cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << endl; cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl; cout << "L_tb[" << i << "][" << j << "] = " << L_tb[i][j] << endl; cout << "this_error = " << this_error << endl; assert(this_error < allowed_error); #endif } } return max_error; } // Check if real ac_fixed/ac_float matrix is zero matrix. template<unsigned M, class T> bool check_if_zero_matrix( const T L[M][M] ) { bool is_zero_matrix = true; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { if (L[i][j] != 0) { is_zero_matrix = false; #ifdef DEBUG cout << "Matrix was not zero for a non positive definite input. Non-zero element found:" << endl; cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl; assert(false); #endif } } } return is_zero_matrix; } // Check if complex matrix is zero matrix. template<unsigned M, class T> bool check_if_zero_matrix( const ac_complex<T> L[M][M] ) { bool is_zero_matrix = true; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { if (L[i][j].r() != 0 || L[i][j].i() != 0) { is_zero_matrix = false; #ifdef DEBUG cout << "Matrix was not zero for a non positive definite input. Non-zero element found:" << endl; cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl; assert(false); #endif } } } return is_zero_matrix; } // Check if ac_std_float matrix is zero matrix. template <unsigned M, int W, int E> bool check_if_zero_matrix( const ac_std_float<W, E> L[M][M] ) { typedef ac_std_float<W, E> T; bool is_zero_matrix = true; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { if (L[i][j] != T::zero()) { is_zero_matrix = false; #ifdef DEBUG cout << "Matrix was not zero for a non positive definite input. Non-zero element found:" << endl; cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl; assert(false); #endif } } } return is_zero_matrix; } // Check if ac_ieee_float matrix is zero matrix. template <unsigned M, ac_ieee_float_format Format> bool check_if_zero_matrix( const ac_ieee_float<Format> L[M][M] ) { typedef ac_ieee_float<Format> T; bool is_zero_matrix = true; for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) { if (L[i][j] != T::zero()) { is_zero_matrix = false; #ifdef DEBUG cout << "Matrix was not zero for a non positive definite input. Non-zero element found:" << endl; cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl; assert(false); #endif } } } return is_zero_matrix; } // Copy a C-style array's contents over to an ac_matrix. template<unsigned M, class T_matrix, class T_ac_matrix> void copy_to_ac_matrix( const T_matrix array_2D[M][M], T_ac_matrix &output ) { for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {output(i, j) = array_2D[i][j];} } } // Copy an ac_matrix's contents over to a C-style array. template<unsigned M, class T_matrix, class T_ac_matrix> void copy_to_array_2D( const T_ac_matrix &input, T_matrix array_2D[M][M] ) { for (int i = 0; i < (int)M; i++) { for (int j = 0; j < (int)M; j++) {array_2D[i][j] = input(i, j);} } } // ============================================================================== // Functions: test_driver functions // Description: Templatized functions that can be configured for certain bit- // widths of AC datatypes. They use the type information to iterate through a // range of valid values on that type in order to compare the precision of the // DUT cholesky decomposition with the computed cholesky decomposition using a // standard C double type. The maximum error for each type is accumulated // in variables defined in the calling function. // ============================================================================== // Function: test_driver_fixed() // Description: test_driver function for ac_fixed and ac_complex<ac_fixed> inputs // and outputs. // FBfi = number of fractional bits in input type. template <bool use_pwl, unsigned M, int FBfi, int outWfi, int outIfi, bool outSfi> int test_driver_fixed( double &cumulative_max_error, double &cumulative_max_error_cmplx, const double allowed_error ) { enum { Ifi = ac::nbits<M - 1>::val, Wfi = FBfi + Ifi, Ifi_c = Ifi + 1, Wfi_c = Wfi + 1 }; bool passed = true; ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP> A_C_array[M][M]; ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> L_C_array[M][M]; ac_complex<ac_fixed<Wfi_c, Ifi_c, true, AC_TRN, AC_WRAP> > cmplx_A_C_array[M][M]; ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> > cmplx_L_C_array[M][M]; ac_matrix<ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP>, M, M> A_ac_matrix; ac_matrix<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP>, M, M> L_ac_matrix; ac_matrix<ac_complex<ac_fixed<Wfi_c, Ifi_c, true, AC_TRN, AC_WRAP> >, M, M> cmplx_A_ac_matrix; ac_matrix<ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> >, M, M> cmplx_L_ac_matrix; if (use_pwl) { cout << "TEST: ac_chol_d() with PWL fns. M = "; // ac_chol_d uses PWL functions. } else { cout << "TEST: ac_chol_d() with acc fns. M = "; // ac_chol_d uses accurate functions. } cout.width(2); cout << left << M; cout << ", INPUT: "; cout.width(37); cout << left << A_C_array[0][0].type_name(); cout << "OUTPUT: "; cout.width(37); cout << left << L_C_array[0][0].type_name(); cout << "RESULT: "; double L_tb[M][M]; ac_complex<double> cmplx_L_tb[M][M]; // The gen_matrix function takes an MxM matrix, and multiplies it by its // conjugate transpose to obtain a positive definite input matrix gen_matrix(A_C_array); gen_matrix(cmplx_A_C_array); copy_to_ac_matrix(A_C_array, A_ac_matrix); copy_to_ac_matrix(cmplx_A_C_array, cmplx_A_ac_matrix); test_ac_chol_d_fixed<use_pwl>(A_C_array, L_C_array, cmplx_A_C_array, cmplx_L_C_array, A_ac_matrix, L_ac_matrix, cmplx_A_ac_matrix, cmplx_L_ac_matrix); ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> L_ac_matrix_converted[M][M]; ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> > L_cmplx_ac_matrix_converted[M][M]; copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted); copy_to_array_2D(cmplx_L_ac_matrix, L_cmplx_ac_matrix_converted); // Get output of testbench function for cholesky decomposition. chol_d_tb(A_C_array, L_tb); chol_d_tb(cmplx_A_C_array, cmplx_L_tb); #ifdef DEBUG cout << "A_C_array = " << endl; print_matrix(A_C_array); cout << "L_C_array = " << endl; print_matrix(L_C_array); cout << "L_tb = " << endl; print_matrix(L_tb); cout << "cmplx_A_C_array = " << endl; print_matrix(cmplx_A_C_array); cout << "cmplx_L_C_array = " << endl; print_matrix(cmplx_L_C_array); cout << "cmplx_L_tb = " << endl; print_matrix(cmplx_L_tb); cout << "A_ac_matrix = " << endl; cout << A_ac_matrix << endl; cout << "L_ac_matrix = " << endl; cout << L_ac_matrix << endl; cout << "cmplx_A_ac_matrix = " << endl; cout << cmplx_A_ac_matrix << endl; cout << "cmplx_L_ac_matrix = " << endl; cout << cmplx_L_ac_matrix << endl; #endif // Compare matrices and get the max error double max_error = compare_matrices(L_C_array, L_tb, allowed_error); double max_error_cmplx = compare_matrices(cmplx_L_C_array, cmplx_L_tb, allowed_error); double max_error_ac_matrix = compare_matrices(L_ac_matrix_converted, L_tb, allowed_error); double max_error_cmplx_ac_matrix = compare_matrices(L_cmplx_ac_matrix_converted, cmplx_L_tb, allowed_error); // Put max overall error in a separate variable. double max_error_overall = max_error > max_error_ac_matrix ? max_error : max_error_ac_matrix; double max_error_cmplx_overall = max_error_cmplx > max_error_cmplx_ac_matrix ? max_error_cmplx : max_error_cmplx_ac_matrix; passed = (max_error_overall < allowed_error) && (max_error_cmplx_overall < allowed_error); // Also, we must make sure that the output on passing a non-positive definite matrix is a zero matrix. To do this, we pass a matrix // with all the values set to the quantum values of the ac_fixed type as the input. ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP> ac_fixed_quantum_value; ac_fixed_quantum_value.template set_val<AC_VAL_QUANTUM>(); ac_complex<ac_fixed<Wfi_c, Ifi_c, false, AC_TRN, AC_WRAP> > ac_complex_quantum_value(ac_fixed_quantum_value, ac_fixed_quantum_value); A_ac_matrix = ac_fixed_quantum_value; cmplx_A_ac_matrix = ac_complex_quantum_value; // Copy over a non-positive definite matrix to the standard C array inputs. copy_to_array_2D(A_ac_matrix, A_C_array); copy_to_array_2D(cmplx_A_ac_matrix, cmplx_A_C_array); test_ac_chol_d_fixed<use_pwl>(A_C_array, L_C_array, cmplx_A_C_array, cmplx_L_C_array, A_ac_matrix, L_ac_matrix, cmplx_A_ac_matrix, cmplx_L_ac_matrix); copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted); copy_to_array_2D(cmplx_L_ac_matrix, L_cmplx_ac_matrix_converted); // Make sure that a zero matrix is returned at the output. passed = passed && check_if_zero_matrix(L_C_array) && check_if_zero_matrix(cmplx_L_C_array) && check_if_zero_matrix(L_ac_matrix_converted) && check_if_zero_matrix(L_cmplx_ac_matrix_converted); if (passed) { printf("PASSED , max err (%f) (%f complex)\n", max_error_overall, max_error_cmplx_overall); } else { printf("FAILED , max err (%f) (%f complex)\n", max_error_overall, max_error_cmplx_overall); } // LCOV_EXCL_LINE if (max_error_overall > cumulative_max_error) { cumulative_max_error = max_error_overall; } if (max_error_cmplx_overall > cumulative_max_error_cmplx) { cumulative_max_error_cmplx = max_error_cmplx_overall; } return 0; } // ============================================================================== // Function: test_driver_float() // Description: test_driver function for ac_float inputs and outputs. // FBfl = number of fractional bits in input mantissa type. template <bool use_pwl, unsigned M, int FBfl, int outWfl, int outIfl, int outEfl> int test_driver_float( double &cumulative_max_error, const double allowed_error ) { bool passed = true; enum { Ifl = 1, Wfl = Ifl + FBfl, E_val_1 = ac::nbits<Wfl - 1>::val, max_int_val = ac::nbits<M - 1>::val, val_2 = (max_int_val - (Ifl - 1) < 0) ? -(max_int_val - (Ifl - 1)) : max_int_val - (Ifl - 1), E_val_2 = ac::nbits<AC_MAX(int(val_2), 1)>::val, Efl = AC_MAX(int(E_val_1), int(E_val_2)) + 1, }; ac_float<Wfl, Ifl, Efl, AC_TRN> A_C_array[M][M]; ac_float<outWfl, outIfl, outEfl, AC_TRN> L_C_array[M][M]; ac_matrix<ac_float<Wfl, Ifl, Efl, AC_TRN>, M, M> A_ac_matrix; ac_matrix<ac_float<outWfl, outIfl, outEfl, AC_TRN>, M, M> L_ac_matrix; if (use_pwl) { cout << "TEST: ac_chol_d() with PWL fns. M = "; // ac_chol_d uses PWL functions. } else { cout << "TEST: ac_chol_d() with acc fns. M = "; // ac_chol_d uses accurate functions. } cout.width(2); cout << left << M; cout << ", INPUT: "; cout.width(37); cout << left << A_C_array[0][0].type_name(); cout << "OUTPUT: "; cout.width(37); cout << left << L_C_array[0][0].type_name(); cout << "RESULT: "; double L_tb[M][M]; // The gen_matrix function takes an MxM matrix, and multiplies it by its // transpose to obtain a positive definite input matrix gen_matrix(A_C_array); copy_to_ac_matrix(A_C_array, A_ac_matrix); test_ac_chol_d_float<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix); ac_float<outWfl, outIfl, outEfl, AC_TRN> L_ac_matrix_converted[M][M]; copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted); // Get output of testbench function for cholesky decomposition. chol_d_tb(A_C_array, L_tb); #ifdef DEBUG cout << "A_C_array = " << endl; print_matrix(A_C_array); cout << "L_C_array = " << endl; print_matrix(L_C_array); cout << "L_tb = " << endl; print_matrix(L_tb); cout << "A_ac_matrix = " << endl; cout << A_ac_matrix << endl; cout << "L_ac_matrix = " << endl; cout << L_ac_matrix << endl; #endif // Compare matrices and get the max error double max_error = compare_matrices(L_C_array, L_tb, allowed_error); double max_error_ac_matrix = compare_matrices(L_ac_matrix_converted, L_tb, allowed_error); // Put max overall error in a separate variable. double max_error_overall = max_error > max_error_ac_matrix ? max_error : max_error_ac_matrix; passed = (max_error_overall < allowed_error); // Also, we must make sure that the output on passing a non-positive definite matrix is a zero matrix. To do this, we pass a matrix // with all the values set to the quantum values of the ac_float type as the input. ac_float<Wfl, Ifl, Efl, AC_TRN> ac_float_quantum_value; ac_float_quantum_value.template set_val<AC_VAL_QUANTUM>(); A_ac_matrix = ac_float_quantum_value; // Copy over a non-positive definite matrix to the standard C array inputs. copy_to_array_2D(A_ac_matrix, A_C_array); test_ac_chol_d_float<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix); copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted); // Make sure that a zero matrix is returned at the output. passed = passed && check_if_zero_matrix(L_C_array) && check_if_zero_matrix(L_ac_matrix_converted); if (passed) { printf("PASSED , max err (%f)\n", max_error_overall); } else { printf("FAILED , max err (%f)\n", max_error_overall); } // LCOV_EXCL_LINE if (max_error_overall > cumulative_max_error) { cumulative_max_error = max_error_overall; } return 0; } // ============================================================================== // Function: test_driver_stfloat() // Description: test_driver function for ac_std_float inputs and outputs. // FBstfl: Number of fractional bits in input mantissa, i.e. number of bits in // significand field of ac_std_float datatype. template <bool use_pwl, unsigned M, int FBstfl, int outWstfl, int outEstfl> int test_driver_stfloat( double &cumulative_max_error, const double allowed_error ) { bool passed = true; enum { E_val_1 = ac::nbits<FBstfl>::val, E_val_2 = ac::nbits<AC_MAX(ac::nbits<M - 1>::val - 1, 1)>::val, Estfl = AC_MAX(int(E_val_1), int(E_val_2)) + 1, Wstfl = 1 + Estfl + FBstfl, }; typedef ac_std_float<Wstfl, Estfl> T_in; typedef ac_std_float<outWstfl, outEstfl> T_out; T_in A_C_array[M][M]; T_out L_C_array[M][M]; ac_matrix<T_in, M, M> A_ac_matrix; ac_matrix<T_out, M, M> L_ac_matrix; if (use_pwl) { cout << "TEST: ac_chol_d() with PWL fns. M = "; // ac_chol_d uses PWL functions. } else { cout << "TEST: ac_chol_d() with acc fns. M = "; // ac_chol_d uses accurate functions. } cout.width(2); cout << left << M; cout << ", INPUT: "; cout.width(37); cout << left << type_string_st<T_in>::type_string(); cout << "OUTPUT: "; cout.width(37); cout << left << type_string_st<T_out>::type_string(); cout << "RESULT: "; double L_tb[M][M]; // The gen_matrix function takes an MxN matrix, and multiplies it by its // transpose to obtain a positive definite input matrix gen_matrix(A_C_array); copy_to_ac_matrix(A_C_array, A_ac_matrix); test_ac_chol_d_stfloat<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix); T_out L_ac_matrix_converted[M][M]; copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted); // Get output of testbench function for cholesky decomposition. chol_d_tb(A_C_array, L_tb); #ifdef DEBUG cout << "A_C_array = " << endl; print_matrix(A_C_array); cout << "L_C_array = " << endl; print_matrix(L_C_array); cout << "L_tb = " << endl; print_matrix(L_tb); cout << "A_ac_matrix = " << endl; cout << A_ac_matrix << endl; cout << "L_ac_matrix = " << endl; cout << L_ac_matrix << endl; #endif // Compare matrices and get the max error double max_error = compare_matrices(L_C_array, L_tb, allowed_error); double max_error_ac_matrix = compare_matrices(L_ac_matrix_converted, L_tb, allowed_error); // Put max overall error in a separate variable. double max_error_overall = max_error > max_error_ac_matrix ? max_error : max_error_ac_matrix; passed = (max_error_overall < allowed_error); // Also, we must make sure that the output on passing a non-positive definite matrix is a zero matrix. To do this, we pass a matrix // with all the values set to unity. A_ac_matrix = T_in::one(); // Copy over a non-positive definite matrix to the standard C array inputs. copy_to_array_2D(A_ac_matrix, A_C_array); test_ac_chol_d_stfloat<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix); copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted); // Make sure that a zero matrix is returned at the output. passed = passed && check_if_zero_matrix(L_C_array) && check_if_zero_matrix(L_ac_matrix_converted); if (passed) { printf("PASSED , max err (%f)\n", max_error_overall); } else { printf("FAILED , max err (%f)\n", max_error_overall); } // LCOV_EXCL_LINE if (max_error_overall > cumulative_max_error) { cumulative_max_error = max_error_overall; } return 0; } // ============================================================================== // Function: test_driver_ifloat() // Description: test_driver function for ac_ieee_float inputs and outputs. template <bool use_pwl, unsigned M, ac_ieee_float_format in_format, ac_ieee_float_format out_format> int test_driver_ifloat( double &cumulative_max_error, const double allowed_error ) { bool passed = true; typedef ac_ieee_float<in_format> T_in; typedef ac_ieee_float<out_format> T_out; T_in A_C_array[M][M]; T_out L_C_array[M][M]; ac_matrix<T_in, M, M> A_ac_matrix; ac_matrix<T_out, M, M> L_ac_matrix; if (use_pwl) { cout << "TEST: ac_chol_d() with PWL fns. M = "; // ac_chol_d uses PWL functions. } else { cout << "TEST: ac_chol_d() with acc fns. M = "; // ac_chol_d uses accurate functions. } cout.width(2); cout << left << M; cout << ", INPUT: "; cout.width(37); cout << left << type_string_st<T_in>::type_string(); cout << "OUTPUT: "; cout.width(37); cout << left << type_string_st<T_out>::type_string(); cout << "RESULT: "; double L_tb[M][M]; // The gen_matrix function takes an MxN matrix, and multiplies it by its // transpose to obtain a positive definite input matrix gen_matrix(A_C_array); copy_to_ac_matrix(A_C_array, A_ac_matrix); test_ac_chol_d_ifloat<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix); T_out L_ac_matrix_converted[M][M]; copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted); // Get output of testbench function for cholesky decomposition. chol_d_tb(A_C_array, L_tb); #ifdef DEBUG cout << "A_C_array = " << endl; print_matrix(A_C_array); cout << "L_C_array = " << endl; print_matrix(L_C_array); cout << "L_tb = " << endl; print_matrix(L_tb); cout << "A_ac_matrix = " << endl; cout << A_ac_matrix << endl; cout << "L_ac_matrix = " << endl; cout << L_ac_matrix << endl; #endif // Compare matrices and get the max error double max_error = compare_matrices(L_C_array, L_tb, allowed_error); double max_error_ac_matrix = compare_matrices(L_ac_matrix_converted, L_tb, allowed_error); // Put max overall error in a separate variable. double max_error_overall = max_error > max_error_ac_matrix ? max_error : max_error_ac_matrix; passed = (max_error_overall < allowed_error); // Also, we must make sure that the output on passing a non-positive definite matrix is a zero matrix. To do this, we pass a matrix // with all the values set to unity. A_ac_matrix = T_in::one(); // Copy over a non-positive definite matrix to the standard C array inputs. copy_to_array_2D(A_ac_matrix, A_C_array); test_ac_chol_d_ifloat<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix); copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted); // Make sure that a zero matrix is returned at the output. passed = passed && check_if_zero_matrix(L_C_array) && check_if_zero_matrix(L_ac_matrix_converted); if (passed) { printf("PASSED , max err (%f)\n", max_error_overall); } else { printf("FAILED , max err (%f)\n", max_error_overall); } // LCOV_EXCL_LINE if (max_error_overall > cumulative_max_error) { cumulative_max_error = max_error_overall; } return 0; } int main(int argc, char *argv[]) { double max_error_pwl = 0, cmplx_max_error_pwl = 0, max_error_acc = 0, cmplx_max_error_acc = 0; double allowed_error_pwl = 4; double allowed_error_acc = 0.005; cout << "=============================================================================" << endl; cout << "Testing function: ac_chol_d(), for scalar and complex datatypes - allowed_error_pwl = " << allowed_error_pwl << ", allowed_error_acc = " << allowed_error_acc << endl; // template <bool use_pwl, unsigned M, int FBfi, int outWfi, int outIfi, bool outSfi> test_driver_fixed< true, 7, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl); test_driver_fixed< true, 8, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl); test_driver_fixed< true, 10, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl); test_driver_fixed< true, 11, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl); test_driver_fixed< true, 12, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl); test_driver_fixed< true, 13, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl); test_driver_fixed< true, 14, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl); test_driver_fixed<false, 7, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc); test_driver_fixed<false, 8, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc); test_driver_fixed<false, 9, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc); test_driver_fixed<false, 10, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc); test_driver_fixed<false, 11, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc); test_driver_fixed<false, 12, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc); test_driver_fixed<false, 13, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc); test_driver_fixed<false, 14, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc); // template <bool use_pwl, unsigned M, int FBfl, int outWfl, int outIfl, int outEfl> test_driver_float< true, 7, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl); test_driver_float< true, 8, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl); test_driver_float< true, 10, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl); test_driver_float< true, 11, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl); test_driver_float< true, 12, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl); test_driver_float< true, 13, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl); test_driver_float< true, 14, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl); test_driver_float<false, 7, 16, 32, 2, 10>(max_error_acc, allowed_error_acc); test_driver_float<false, 8, 16, 32, 2, 10>(max_error_acc, allowed_error_acc); test_driver_float<false, 9, 16, 32, 2, 10>(max_error_acc, allowed_error_acc); test_driver_float<false, 10, 16, 32, 2, 10>(max_error_acc, allowed_error_acc); test_driver_float<false, 11, 16, 32, 2, 10>(max_error_acc, allowed_error_acc); test_driver_float<false, 12, 16, 32, 2, 10>(max_error_acc, allowed_error_acc); test_driver_float<false, 13, 16, 32, 2, 10>(max_error_acc, allowed_error_acc); test_driver_float<false, 14, 16, 32, 2, 10>(max_error_acc, allowed_error_acc); // template <bool use_pwl, unsigned M, int FBstfl, int outWstfl, int outEstfl> test_driver_stfloat< true, 7, 23, 64, 11>(max_error_pwl, allowed_error_pwl); test_driver_stfloat< true, 8, 23, 64, 11>(max_error_pwl, allowed_error_pwl); test_driver_stfloat< true, 10, 23, 64, 11>(max_error_pwl, allowed_error_pwl); test_driver_stfloat< true, 11, 23, 64, 11>(max_error_pwl, allowed_error_pwl); test_driver_stfloat< true, 12, 23, 64, 11>(max_error_pwl, allowed_error_pwl); test_driver_stfloat< true, 13, 23, 64, 11>(max_error_pwl, allowed_error_pwl); test_driver_stfloat< true, 14, 23, 64, 11>(max_error_pwl, allowed_error_pwl); test_driver_stfloat<false, 7, 23, 64, 11>(max_error_acc, allowed_error_acc); test_driver_stfloat<false, 8, 23, 64, 11>(max_error_acc, allowed_error_acc); test_driver_stfloat<false, 9, 23, 64, 11>(max_error_acc, allowed_error_acc); test_driver_stfloat<false, 10, 23, 64, 11>(max_error_acc, allowed_error_acc); test_driver_stfloat<false, 11, 23, 64, 11>(max_error_acc, allowed_error_acc); test_driver_stfloat<false, 12, 23, 64, 11>(max_error_acc, allowed_error_acc); test_driver_stfloat<false, 13, 23, 64, 11>(max_error_acc, allowed_error_acc); test_driver_stfloat<false, 14, 23, 64, 11>(max_error_acc, allowed_error_acc); // template <bool use_pwl, unsigned M, ac_ieee_float_format in_format, ac_ieee_float_format out_format> test_driver_ifloat< true, 7, binary32, binary64>(max_error_pwl, allowed_error_pwl); test_driver_ifloat< true, 8, binary32, binary64>(max_error_pwl, allowed_error_pwl); test_driver_ifloat< true, 10, binary32, binary64>(max_error_pwl, allowed_error_pwl); test_driver_ifloat< true, 11, binary32, binary64>(max_error_pwl, allowed_error_pwl); test_driver_ifloat< true, 12, binary32, binary64>(max_error_pwl, allowed_error_pwl); test_driver_ifloat< true, 13, binary32, binary64>(max_error_pwl, allowed_error_pwl); test_driver_ifloat< true, 14, binary32, binary64>(max_error_pwl, allowed_error_pwl); test_driver_ifloat<false, 7, binary32, binary64>(max_error_acc, allowed_error_acc); test_driver_ifloat<false, 8, binary32, binary64>(max_error_acc, allowed_error_acc); test_driver_ifloat<false, 9, binary32, binary64>(max_error_acc, allowed_error_acc); test_driver_ifloat<false, 10, binary32, binary64>(max_error_acc, allowed_error_acc); test_driver_ifloat<false, 11, binary32, binary64>(max_error_acc, allowed_error_acc); test_driver_ifloat<false, 12, binary32, binary64>(max_error_acc, allowed_error_acc); test_driver_ifloat<false, 13, binary32, binary64>(max_error_acc, allowed_error_acc); test_driver_ifloat<false, 14, binary32, binary64>(max_error_acc, allowed_error_acc); cout << "=============================================================================" << endl; cout << " Testbench finished. Maximum errors observed across all data type / bit-width variations:" << endl; cout << " max_error_pwl = " << max_error_pwl << endl; cout << " cmplx_max_error_pwl = " << cmplx_max_error_pwl << endl; cout << " max_error_acc = " << max_error_acc << endl; cout << " cmplx_max_error_acc = " << cmplx_max_error_acc << endl; // If error limits on any tested datatype have been crossed, the test has failed bool test_fail = (max_error_pwl > allowed_error_pwl) || (cmplx_max_error_pwl > allowed_error_pwl) || (max_error_acc > allowed_error_acc) || (cmplx_max_error_acc > allowed_error_acc); // Notify the user whether or not the test was a failure. if (test_fail) { cout << " ac_chol_d - FAILED - Error tolerance(s) exceeded" << endl; // LCOV_EXCL_LINE cout << "=============================================================================" << endl; // LCOV_EXCL_LINE return -1; // LCOV_EXCL_LINE } else { cout << " ac_chol_d - PASSED" << endl; cout << "=============================================================================" << endl; } return 0; }
38.251366
194
0.645357
dgburnette
ad356c7c8976183d272c49e659ce12c10a3104b4
1,019
cpp
C++
LeetCode/cpp/987.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
279
2019-02-19T16:00:32.000Z
2022-03-23T12:16:30.000Z
LeetCode/cpp/987.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
2
2019-03-31T08:03:06.000Z
2021-03-07T04:54:32.000Z
LeetCode/cpp/987.cpp
ZintrulCre/LeetCode_Crawler
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
12
2019-01-29T11:45:32.000Z
2019-02-04T16:31:46.000Z
class Solution { public: unordered_map<int, unordered_map<int, set<int>>> nums; vector<vector<int>> verticalTraversal(TreeNode *root) { if (!root) return {}; nums.clear(); Traverse(root, 0, 0); vector<vector<int>> ret; for (int i = -1000; i <= 1000; ++i) { if (nums.find(i) != nums.end()) { ret.push_back(vector<int>()); for (int j = 0; j <= 1000; ++j) { if (nums[i].find(j) != nums[i].end()) ret.back().insert(end(ret.back()), begin(nums[i][j]), end(nums[i][j])); } } } return ret; } void Traverse(TreeNode *node, int i, int j) { if (nums.find(i) == nums.end()) nums[i] = unordered_map<int, set<int>>(); nums[i][j].insert(node->val); if (node->left) Traverse(node->left, i - 1, j + 1); if (node->right) Traverse(node->right, i + 1, j + 1); } };
31.84375
95
0.44946
ZintrulCre
ad37155c15863c09f98819ffa51767eeb2cdb9b1
1,959
cpp
C++
topic_wise/graphs/courseSchedule.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
topic_wise/graphs/courseSchedule.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
topic_wise/graphs/courseSchedule.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
/** * @author : archit * @GitHub : archit-1997 * @Email : architsingh456@gmail.com * @file : courseSchedule.cpp * @created : Sunday Aug 01, 2021 17:31:53 IST */ #include <bits/stdc++.h> using namespace std; class Solution { public: vector<vector<int>> buildGraph(int numCourses,vector<vector<int>> &prerequisites){ vector<vector<int>> graph(numCourses); for(int i=0;i<prerequisites.size();i++){ int a=prerequisites[i][0],b=prerequisites[i][1]; //complete course b before a graph[b].push_back(a); } return graph; } bool detectCycle(vector<vector<int>> &graph,int numCourses,vector<int> &vis,vector<int> &rec,int x){ rec[x]=1; vis[x]=1; for(int i=0;i<graph[x].size();i++){ int cur=graph[x][i]; //already present in the recursion stack if(rec[cur]) return true; //if not visited, but there is a cylce later on if(!vis[i] && detectCycle(graph,numCourses,vis,rec,cur)) return true; } //no cycles for this node rec[x]=0; return false; } bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { //if there is only one course, then you can just say finished if(numCourses==1) return true; //build the graph vector<vector<int>> graph=buildGraph(numCourses,prerequisites); vector<int> vis(numCourses,0); //vector for recursion stack vector<int> rec(numCourses,0); //check for the existence of cycle in the graph //need to apply dfs from each node for(int i=0;i<numCourses;i++){ if(detectCycle(graph,numCourses,vis,rec,i)) return false; } //no cycle in the graph, then we can complete all the courses return true; } };
29.681818
104
0.562532
archit-1997
ad383085aa0804fdebf8068daa3f340fe479f9d0
2,794
cc
C++
mindspore/lite/src/runtime/kernel/ascend/src/acl_options_parser.cc
PowerOlive/mindspore
bda20724a94113cedd12c3ed9083141012da1f15
[ "Apache-2.0" ]
1
2021-12-27T13:42:29.000Z
2021-12-27T13:42:29.000Z
mindspore/lite/src/runtime/kernel/ascend/src/acl_options_parser.cc
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/ascend/src/acl_options_parser.cc
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/runtime/kernel/ascend/src/acl_options_parser.h" #include <utility> #include <vector> #include "common/log_adapter.h" #include "src/common/log_util.h" #include "src/common/utils.h" #include "acl/acl_base.h" #include "acl/acl_rt.h" namespace mindspore::kernel { namespace acl { constexpr auto kImageHwNum = 2; STATUS AclOptionsParser::ParseAclOptions(const mindspore::Context *ctx, AclModelOptions *acl_options) { CHECK_NULL_RETURN(ctx); CHECK_NULL_RETURN(acl_options); auto context = const_cast<mindspore::Context *>(ctx); auto device_infos = context->MutableDeviceInfo(); if (device_infos.size() < 1) { MS_LOG(WARNING) << "Context is not set device info, please check."; return lite::RET_OK; } CHECK_NULL_RETURN(device_infos[0]); if (ParseOptions(device_infos[0], acl_options) != lite::RET_OK) { MS_LOG(ERROR) << "Parse acl options failed."; return lite::RET_ERROR; } return lite::RET_OK; } STATUS AclOptionsParser::ParseOptions(const std::shared_ptr<DeviceInfoContext> &device_info, AclModelOptions *acl_options) { auto ascend_info = device_info->Cast<mindspore::AscendDeviceInfo>(); if (ascend_info == nullptr) { MS_LOG(ERROR) << "There is no ascend info."; return lite::RET_ERROR; } int32_t device_id = static_cast<int32_t>(ascend_info->GetDeviceID()); if (CheckDeviceId(&device_id) != lite::RET_OK) { MS_LOG(ERROR) << "Check device id failed, device id = " << device_id; return lite::RET_ERROR; } acl_options->device_id = device_id; return lite::RET_OK; } STATUS AclOptionsParser::CheckDeviceId(int32_t *device_id) { CHECK_NULL_RETURN(device_id); uint32_t device_count; if (aclrtGetDeviceCount(&device_count) != ACL_ERROR_NONE) { MS_LOG(WARNING) << "Get device count failed."; return lite::RET_OK; } if (*device_id >= static_cast<int32_t>(device_count)) { MS_LOG(ERROR) << "Current device id " << *device_id << " is larger than max count " << device_count << ",please check the device info of context."; return lite::RET_ERROR; } return lite::RET_OK; } } // namespace acl } // namespace mindspore::kernel
34.925
103
0.708304
PowerOlive
ad3d2261d56ac74aa29612af22b45007cfa4c7ad
1,462
cpp
C++
MAze/Aliados.cpp
IzaguirreYamile/MAze
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
[ "MIT" ]
1
2021-09-02T21:19:19.000Z
2021-09-02T21:19:19.000Z
MAze/Aliados.cpp
IzaguirreYamile/MAze
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
[ "MIT" ]
null
null
null
MAze/Aliados.cpp
IzaguirreYamile/MAze
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
[ "MIT" ]
null
null
null
#include "Aliados.h" Aliados::Aliados() {} Aliados::Aliados(int px, int py, Bitmap^ aliados) { x = px; y = py; this->ancho = aliados->Width / 13; this->alto = aliados->Height / 21; dx = 4; dy = 4; direccion = Caminar2Derecha; } void Aliados::Mover(Graphics^ g) { switch(direccion) { case Caminar2Abajo: fila = 2; break; case Caminar2Izquierda: fila = 3; break; case Caminar2Derecha: fila = 1; break; case Caminar2Arriba: fila = 0; break; } x += dx; y += dy; } void Aliados::MoveType1(Graphics^ g) { if (x + dx < g->VisibleClipBounds.Left) { direccion = Caminar2Derecha; dx *= -1; } if (x + dx + ancho > g->VisibleClipBounds.Right) { direccion = Caminar2Izquierda; dx = dx * -1; } if (y + dy < g->VisibleClipBounds.Top) { dy *= -1; } if (y + dy + alto > g->VisibleClipBounds.Bottom) { dy *= -1; } x += dx; y += dy; } void Aliados::Dibujar(Graphics^ g, Bitmap^ aliados) { Rectangle corte = Rectangle(IDx * ancho, direccion * alto, ancho, alto); Rectangle zoom = Rectangle(x, y, ancho, alto); g->DrawImage(aliados, zoom, corte, GraphicsUnit::Pixel); if ((direccion >= Caminar2Arriba && direccion <= Caminar2Derecha) && dx != 0 || dy != 0) IDx = (IDx + 1) % 8; else if (direccion == Morir_enemigo) IDx = (IDx + 1) % 6; } int Aliados::Obtener_Ancho() { return ancho; } int Aliados::Obtener_Alto() { return alto; } void Aliados::Cambiar_direccion(SpriteEnemigo n) { direccion = n; } Aliados::~Aliados() {}
21.5
89
0.634063
IzaguirreYamile
ad3e5c1a1dd20a87640b1d2f075b7d587efc77ac
788
cpp
C++
src/main.cpp
a1exwang/arduino_oscilloscope
190659fec1fd18c63f606cab52ead40dd638e0e6
[ "MIT" ]
null
null
null
src/main.cpp
a1exwang/arduino_oscilloscope
190659fec1fd18c63f606cab52ead40dd638e0e6
[ "MIT" ]
null
null
null
src/main.cpp
a1exwang/arduino_oscilloscope
190659fec1fd18c63f606cab52ead40dd638e0e6
[ "MIT" ]
null
null
null
#include <Arduino.h> void setup() { Serial.begin(230400*2); // Set Timer 1 to normal mode at F_CPU. TCCR1A = 0; TCCR1B = 1; // set 32 times division // http://microelex.blogspot.com/p/2.html // 0b100 -> 1MHz, 1us // 0b101 -> 500kHz, 2us // 0b110 -> 250kHz, 4us // 0b111 -> 125kHz, 8us ADCSRA = (0b11111000u & ADCSRA) | 0b00000101u; } void loop() { while (true) { uint16_t time = TCNT1; // 10bit -> 8bit uint16_t value = analogRead(PIN_A0) >> 2; Serial.write(0xff); if (value & 0xff == 0xff) { Serial.write(0xfe); } else { Serial.write(value); } // cost 500 cycles on average, it's 32kHz Serial.write((time >> 8) & 0x7f); // uint16_t t0 = TCNT1; // uint16_t t1 = TCNT1; // Serial.println(t1 - t0); } }
21.297297
48
0.577411
a1exwang
ad458fd54d93474818b8eb7e5123e6b266c0d46e
3,905
cpp
C++
codeforces_problems/matexpo.cpp
ChanderJindal/Data_Structure_and_Algorithms
8268a5b8be6bc967af41d1985db1224d6c6afc5e
[ "MIT" ]
14
2019-10-26T11:43:56.000Z
2021-01-23T00:37:17.000Z
codeforces_problems/matexpo.cpp
ChanderJindal/Data_Structure_and_Algorithms
8268a5b8be6bc967af41d1985db1224d6c6afc5e
[ "MIT" ]
28
2019-10-13T17:49:42.000Z
2020-11-15T07:08:10.000Z
codeforces_problems/matexpo.cpp
ChanderJindal/Data_Structure_and_Algorithms
8268a5b8be6bc967af41d1985db1224d6c6afc5e
[ "MIT" ]
73
2019-10-11T06:38:10.000Z
2022-01-26T20:04:24.000Z
/*Made by Shivam Solanki*/ #include<bits/stdc++.h> #pragma GCC optimize ("Ofast") using namespace std; #define DEBUG(x) cout << '>' << #x << ':' << x << endl; #define ll long long int #define endl '\n' typedef vector<int> vi; typedef vector<ll> vll; typedef vector<vll> vvl; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef vector<vi> vvi; typedef vector<bool> vb; typedef vector<pii> vp; typedef vector<pll> vpll; typedef map<int,int> mii; typedef map<ll,ll> mll; typedef set<int> sii; typedef set<ll> sll; typedef queue<int> qii; typedef priority_queue<int> pq; typedef unordered_map<int,int> umii; typedef unordered_map<ll,ll> umll; #define all(x) x.begin(),x.end() #define rep(i,k,n) for (int i = k; i < n; ++i) #define repr(i,k,n) for (int i = n; i>=k; --i) #define repll(i,k,n) for (ll i = k; i < n; ++i) #define pb push_back #define mp make_pair #define gcd __gcd #define F first #define S second #define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); const int INF = 1e9+5; const int MOD = 1e9+7; double pi = 2 * acos(0.0); //const ll inf = 2e18+11; //Question Link //https://www.codechef.com/LRNDSA04/problems/QHOUSE void solve(){ //comment before submitting vp square(4),triangle(3); rep(i,0,4) cin>>square[i].F>>square[i].S; rep(i,0,3) cin>>triangle[i].F>>triangle[i].S; int actual_ans; cin>>actual_ans; auto valid_ans=[](pii p,vp square,vp triangle){ int s=square[0].F; if(p.F>=-s and p.F<=s and p.S>=0 and p.S<=s) return 1; //within square int x1=triangle[0].F,x2=triangle[2].F,y1=triangle[0].S,y2=triangle[2].S; int y=p.S,x=p.F; int ans1=((y-y1)*(x1-x2))-((y1-y2)*(x-x1)); x1=triangle[1].F,y1=triangle[1].S; int ans2=((y-y1)*(x1-x2))-((y1-y2)*(x-x1)); x1=triangle[0].F,y1=triangle[0].S; x2=triangle[1].F,y2=triangle[1].S; int ans3=((y-y1)*(x1-x2))-((y1-y2)*(x-x1)); if(ans1>=0 and ans2<=0 and ans3<=0) return 1; //within triangle return 0; }; //till here for(;;){ int l=0,r=1000; while(l<=r){ int m=(l+r)/2; cout<<"? "<<m<<' '<<0<<'\n'; //uncomment while submitting solution // string x; // cin>>x; // if(x=="YES"){ // l=m+1; // } if(valid_ans({m,0},square,triangle)){ //comment while submitting solution cout<<"YES\n"; l=m+1; } else{ // cout<<"NO\n"; r=m-1; } } int a=2*(l-1); l=0,r=1000; while(l<=r){ int m=(l+r)/2; cout<<"? "<<m<<' '<<a<<'\n'; // string x; // cin>>x; // if(x=="YES"){ // l=m+1; // } if(valid_ans({m,a},square,triangle)){ cout<<"YES\n"; l=m+1; } else{ // cout<<"NO\n"; r=m-1; } } int b=2*(l-1); l=0,r=1000; while(l<=r){ int m=(l+r)/2; cout<<"? "<<0<<' '<<m<<'\n'; // string x; // cin>>x; // if(x=="YES"){ // l=m+1; // } if(valid_ans({0,m},square,triangle)){ cout<<"YES\n"; l=m+1; } else{ // cout<<"NO\n"; r=m-1; } } int h=(l-1)-a; int ans=(h*b)/2+(a*a); cout<<"! "<<ans; if(ans==actual_ans) break; } } int main(){ // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif // fastio; int t=1; // cin>>t; while(t--) solve(); return 0; }
27.5
85
0.463252
ChanderJindal
ad459393c1c02e07c2383cbf3d6be37ea27cb740
4,150
cpp
C++
src/AutonomousSystem/AutonomousManager.cpp
frc2081/2018-RobotCode
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
[ "MIT" ]
null
null
null
src/AutonomousSystem/AutonomousManager.cpp
frc2081/2018-RobotCode
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
[ "MIT" ]
5
2018-01-18T03:25:07.000Z
2018-03-16T13:27:53.000Z
src/AutonomousSystem/AutonomousManager.cpp
frc2081/2018-RobotCode
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
[ "MIT" ]
null
null
null
/* * AutonomousManager.cpp * * Created on: Jan 17, 2018 * Author: Matthew */ #include "AutonomousManager.h" namespace Autonomous { AutonomousManager::AutonomousManager(IO *io, RobotCommands *commands, CubeManager *cube) { _io = io; _commands = commands; _actionselector = 0; _stationselector = 0; _waitleft = false; _waitright = true; _buildcommands = true; _fielddata = ""; _polltimer = 100; _cube = cube; _gyro = gyroManager::Get(); //_action = NONE; //_ourswitch = ''; //_scale = ''; //_station = NONE; _team = NONE; SmartDashboard::PutNumber("Auto Mode", 0); SmartDashboard::PutNumber("Auto Station", 0); SmartDashboard::PutNumber("Wait Side", 0); } void AutonomousManager::AutoInit() { printf("Starting auto\n"); _gyro->start(); _fielddata = DriverStation::GetInstance().GetGameSpecificMessage(); if (DriverStation::GetInstance().GetAlliance() == DriverStation::kRed) _team = RED; else if (DriverStation::GetInstance().GetAlliance() == DriverStation::kBlue) _team = BLUE; else _team = NONE; _actionselector = SmartDashboard::GetNumber("Auto Mode", 0); _stationselector = SmartDashboard::GetNumber("Auto Station", 0); _waitselector = SmartDashboard::GetNumber("Wait Side", 0); if (_actionselector == 0) _action = SWITCH_SHOT; else if (_actionselector == 1) _action = SCALE_SHOT; else if (_actionselector == 2) _action = DRIVE_FORWARD; else _action = NO_AUTO; if (_stationselector == 1) _station = ONE; else if (_stationselector == 2) _station = TWO; else if (_stationselector == 3) _station = THREE; else _station = UNKNOWN; if (_waitselector == 0) { _waitleft = true; _waitright = false; } else if (_waitselector == 1) { _waitright = true; _waitleft = false; } else { _waitleft = false; _waitright = false; } //if (_waitselector->getWaitSide()) { // _waitleft = true; //} else _waitright = true; //_action = SWITCH_SHOT; //Building commands in periodic to make sure the most up to date values are obtained //for more information, visit http://wpilib.screenstepslive.com/s/currentCS/m/getting_started/l/826278-2018-game-data-details } void AutonomousManager::AutoPeriodic() { printf("Entering Autoperiodic\n\n"); //if (_cube->armHome == false) _io->shooteranglmot->Set(ControlMode::Position, 50000); if(_buildcommands) { _fielddata = DriverStation::GetInstance().GetGameSpecificMessage(); printf("Checking for data\n"); if (_fielddata.length() > 0) { if (_fielddata.length() >= 2) { _ourswitch = _fielddata.at(0); _scale = _fielddata.at(1); } printf("Building commands\n"); _autocommands = new CommandManager(_team, _station, _action, _ourswitch, _scale, _waitleft, _waitright); _buildcommands = false; } } _cominput.LFWhlDrvEnc = _io->encdrvlf->GetDistance() / 100; _cominput.RFWhlDrvEnc = _io->encdrvrf->GetDistance() / 100; _cominput.LBWhlDrvEnc = _io->encdrvlb->GetDistance() / 100; _cominput.RBWhlDrvEnc = _io->encdrvrb->GetDistance() / 100; _cominput.LFWhlTurnEnc = _io->steerencdrvlf->Get(); _cominput.RFWhlTurnEnc = _io->steerencdrvrf->Get(); _cominput.LBWhlTurnEnc = _io->steerencdrvlb->Get(); _cominput.RBWhlTurnEnc = _io->steerencdrvrb->Get(); _cominput.currentGyroReading = _gyro->getLastValue(); //printf("Gyro value %.2f", _gyro->getLastValue()); _comoutput = _autocommands->tick(_cominput); //printf("Ticked\n"); //printf("Magnitude: %.2f Angle: %.2f Rotation: %.2\n", _commands->drvmag, _commands->drvang, _commands->drvrot); //printf("LFDrive: %.2f RFDrive: %.2f LBDrive: %.2f, RBDrive: %.2f\n", _io->drvlfmot->Get(), _io->drvrfmot->Get(), _io->drvlbmot->Get(), _io->drvrbmot->Get()); _commands->drvang = _comoutput.autoAng; _commands->drvrot = _comoutput.autoRot; _commands->drvmag = _comoutput.autoSpeed; _commands->cmdscaleshot = _comoutput.takeScaleShot; _commands->cmdswitchshot = _comoutput.takeSwitchShot; _commands->cmdarmtocarry = _comoutput.takeArmToCarry; } }
35.470085
164
0.673976
frc2081
ad483c2371eaf40f796b4b60b6b3ff386d0a28c6
12,445
cpp
C++
TopTestWidgets/privateSource/qcategoryaxis.cpp
cy15196/xxxxRsmTest
36577173ef2cdfc3c3d4cadd3933849d29d5b3d9
[ "MIT" ]
1
2020-02-12T03:20:37.000Z
2020-02-12T03:20:37.000Z
TopTestWidgets/privateSource/qcategoryaxis.cpp
cy15196/xxxxRsmTest
36577173ef2cdfc3c3d4cadd3933849d29d5b3d9
[ "MIT" ]
null
null
null
TopTestWidgets/privateSource/qcategoryaxis.cpp
cy15196/xxxxRsmTest
36577173ef2cdfc3c3d4cadd3933849d29d5b3d9
[ "MIT" ]
1
2019-04-14T09:58:50.000Z
2019-04-14T09:58:50.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Charts module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 or (at your option) any later version ** approved by the KDE Free Qt Foundation. The licenses are as published by ** the Free Software Foundation and appearing in the file LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCharts/QCategoryAxis> #include <private/qcategoryaxis_p.h> #include <private/chartcategoryaxisx_p.h> #include <private/chartcategoryaxisy_p.h> #include <private/polarchartcategoryaxisangular_p.h> #include <private/polarchartcategoryaxisradial_p.h> #include <QtCharts/QChart> #include <QtCore/QtMath> #include <QtCore/QDebug> QT_CHARTS_BEGIN_NAMESPACE /*! \class QCategoryAxis \inmodule Qt Charts \brief The QCategoryAxis class places named ranges on the axis. This class can be used to explain the underlying data by adding labeled categories. Unlike QBarCategoryAxis, QCategoryAxis allows the widths of the category ranges to be specified freely. Example code on how to use QCategoryAxis: \image api_category_axis.png \code QChartView *chartView = new QChartView; QLineSeries *series = new QLineSeries; // ... chartView->chart()->addSeries(series); QCategoryAxis *axisY = new QCategoryAxis; axisY->setMin(0); axisY->setMax(52); axisY->setStartValue(15); axisY->append("First", 20); axisY->append("Second", 37); axisY->append("Third", 52); chartView->chart()->setAxisY(axisY, series); \endcode */ /*! \qmltype CategoryAxis \instantiates QCategoryAxis \inqmlmodule QtCharts \inherits AbstractAxis \brief CategoryAxis places named ranges on the axis. This type can be used to explain the underlying data by adding labeled categories. The widths of the category ranges can be specified freely. For example: \image examples_qmlaxes3.png \snippet qmlaxes/qml/qmlaxes/View3.qml 1 */ /*! // \property QCategoryAxis::startValue // \brief The low end of the first category on the axis. //*/ ///*! // \qmlproperty int CategoryAxis::startValue // The low end of the first category on the axis. //*/ ///*! // \property QCategoryAxis::count // \brief The number of categories. //*/ ///*! // \qmlproperty int CategoryAxis::count // The number of categories. //*/ ///*! // \property QCategoryAxis::categoriesLabels // \brief The category labels as a string list. //*/ ///*! // \qmlproperty StringList CategoryAxis::categoriesLabels // The category labels as a list of strings. //*/ ///*! // \fn void QCategoryAxis::categoriesChanged() // This signal is emitted when the categories of the axis change. //*/ ///*! // \enum QCategoryAxis::AxisLabelsPosition // This enum describes the position of the category labels. // \value AxisLabelsPositionCenter Labels are centered to category. // \value AxisLabelsPositionOnValue Labels are positioned to the high end limit of the category. // */ ///*! // \property QCategoryAxis::labelsPosition // \brief The position of the category labels. The labels in the beginning and in the end of the // axes may overlap other axes' labels when positioned on value. //*/ ///*! // \qmlproperty enumeration CategoryAxis::labelsPosition // The position of the category labels. The labels in the beginning and in the end of the // axes may overlap other axes' labels when positioned on value. // \value CategoryAxis.AxisLabelsPositionCenter // Labels are centered to category. // \value CategoryAxis.AxisLabelsPositionOnValue // Labels are positioned to the high end limit of the category. //*/ ///*! // Constructs an axis object that is a child of \a parent. //*/ //QCategoryAxis::QCategoryAxis(QObject *parent): // QValueAxis(*new QCategoryAxisPrivate(this), parent) //{ //} ///*! // Destroys the object. //*/ //QCategoryAxis::~QCategoryAxis() //{ // Q_D(QCategoryAxis); // if (d->m_chart) // d->m_chart->removeAxis(this); //} ///*! // \internal //*/ //QCategoryAxis::QCategoryAxis(QCategoryAxisPrivate &d, QObject *parent): QValueAxis(d, parent) //{ //} ///*! // \qmlmethod CategoryAxis::append(string label, real endValue) // Appends a new category to the axis with the label \a label. A category label has to be unique. // \a endValue specifies the high end limit of the category. // It has to be greater than the high end limit of the previous category. // Otherwise the method returns without adding a new category. //*/ ///*! // Appends a new category to the axis with the label \a categoryLabel. // A category label has to be unique. // \a categoryEndValue specifies the high end limit of the category. // It has to be greater than the high end limit of the previous category. // Otherwise the method returns without adding a new category. //*/ //void QCategoryAxis::append(const QString &categoryLabel, qreal categoryEndValue) //{ // Q_D(QCategoryAxis); // if (!d->m_categories.contains(categoryLabel)) { // if (d->m_categories.isEmpty()) { // Range range(d->m_categoryMinimum, categoryEndValue); // d->m_categoriesMap.insert(categoryLabel, range); // d->m_categories.append(categoryLabel); // emit categoriesChanged(); // } else if (categoryEndValue > endValue(d->m_categories.last())) { // Range previousRange = d->m_categoriesMap.value(d->m_categories.last()); // d->m_categoriesMap.insert(categoryLabel, Range(previousRange.second, categoryEndValue)); // d->m_categories.append(categoryLabel); // emit categoriesChanged(); // } // } //} ///*! // Sets \a min to be the low end limit of the first category on the axis. // If categories have already been added to the axis, the passed value must be less // than the high end value of the already defined first category range. // Otherwise nothing is done. //*/ //void QCategoryAxis::setStartValue(qreal min) //{ // Q_D(QCategoryAxis); // if (d->m_categories.isEmpty()) { // d->m_categoryMinimum = min; // emit categoriesChanged(); // } else { // Range range = d->m_categoriesMap.value(d->m_categories.first()); // if (min < range.second) { // d->m_categoriesMap.insert(d->m_categories.first(), Range(min, range.second)); // emit categoriesChanged(); // } // } //} ///*! // Returns the low end limit of the category specified by \a categoryLabel. //*/ //qreal QCategoryAxis::startValue(const QString &categoryLabel) const //{ // Q_D(const QCategoryAxis); // if (categoryLabel.isEmpty()) // return d->m_categoryMinimum; // return d->m_categoriesMap.value(categoryLabel).first; //} ///*! // Returns the high end limit of the category specified by \a categoryLabel. //*/ //qreal QCategoryAxis::endValue(const QString &categoryLabel) const //{ // Q_D(const QCategoryAxis); // return d->m_categoriesMap.value(categoryLabel).second; //} ///*! // \qmlmethod CategoryAxis::remove(string label) // Removes a category specified by the label \a label from the axis. //*/ ///*! // Removes a category specified by the label \a categoryLabel from the axis. //*/ //void QCategoryAxis::remove(const QString &categoryLabel) //{ // Q_D(QCategoryAxis); // int labelIndex = d->m_categories.indexOf(categoryLabel); // // check if such label exists // if (labelIndex != -1) { // d->m_categories.removeAt(labelIndex); // d->m_categoriesMap.remove(categoryLabel); // // the range of the interval that follows (if exists) needs to be updated // if (labelIndex < d->m_categories.count()) { // QString label = d->m_categories.at(labelIndex); // Range range = d->m_categoriesMap.value(label); // // set the range // if (labelIndex == 0) { // range.first = d->m_categoryMinimum; // d->m_categoriesMap.insert(label, range); // } else { // range.first = d->m_categoriesMap.value(d->m_categories.at(labelIndex - 1)).second; // d->m_categoriesMap.insert(label, range); // } // } // emit categoriesChanged(); // } //} ///*! // \qmlmethod CategoryAxis::replace(string oldLabel, string newLabel) // Replaces an existing category label specified by \a oldLabel with \a newLabel. // If the old label does not exist, the method returns without making any changes. //*/ ///*! // Replaces an existing category label specified by \a oldLabel with \a newLabel. // If the old label does not exist, the method returns without making any changes. // */ //void QCategoryAxis::replaceLabel(const QString &oldLabel, const QString &newLabel) //{ // Q_D(QCategoryAxis); // int labelIndex = d->m_categories.indexOf(oldLabel); // // check if such label exists // if (labelIndex != -1) { // d->m_categories.replace(labelIndex, newLabel); // Range range = d->m_categoriesMap.value(oldLabel); // d->m_categoriesMap.remove(oldLabel); // d->m_categoriesMap.insert(newLabel, range); // emit categoriesChanged(); // } //} ///*! // Returns the list of the categories' labels. // */ //QStringList QCategoryAxis::categoriesLabels() //{ // Q_D(QCategoryAxis); // return d->m_categories; //} ///*! // Returns the number of categories. // */ //int QCategoryAxis::count() const //{ // Q_D(const QCategoryAxis); // return d->m_categories.count(); //} ///*! // Returns the type of the axis. //*/ //QAbstractAxis::AxisType QCategoryAxis::type() const //{ // return QAbstractAxis::AxisTypeCategory; //} //void QCategoryAxis::setLabelsPosition(QCategoryAxis::AxisLabelsPosition position) //{ // Q_D(QCategoryAxis); // if (d->m_labelsPosition != position) { // d->m_labelsPosition = position; // emit labelsPositionChanged(position); // } //} //QCategoryAxis::AxisLabelsPosition QCategoryAxis::labelsPosition() const //{ // Q_D(const QCategoryAxis); // return d->m_labelsPosition; //} ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// QCategoryAxisPrivate::QCategoryAxisPrivate(QCategoryAxis *q) : QValueAxisPrivate(q), m_categoryMinimum(0), m_labelsPosition(QCategoryAxis::AxisLabelsPositionCenter) { } QCategoryAxisPrivate::~QCategoryAxisPrivate() { } int QCategoryAxisPrivate::ticksCount() const { return m_categories.count() + 1; } void QCategoryAxisPrivate::initializeGraphics(QGraphicsItem *parent) { Q_Q(QCategoryAxis); ChartAxisElement *axis(0); if (m_chart->chartType() == QChart::ChartTypeCartesian) { if (orientation() == Qt::Vertical) axis = new ChartCategoryAxisY(q,parent); else if (orientation() == Qt::Horizontal) axis = new ChartCategoryAxisX(q,parent); } if (m_chart->chartType() == QChart::ChartTypePolar) { if (orientation() == Qt::Vertical) axis = new PolarChartCategoryAxisRadial(q, parent); if (orientation() == Qt::Horizontal) axis = new PolarChartCategoryAxisAngular(q, parent); } m_item.reset(axis); QAbstractAxisPrivate::initializeGraphics(parent); } //#include "moc_qcategoryaxis.cpp" #include "moc_qcategoryaxis_p.cpp" QT_CHARTS_END_NAMESPACE
32.074742
130
0.662113
cy15196
ad493ad1a9322a3fd93a8e4a7bbc106271cdba67
381
hpp
C++
Source/Game/Match3Cell.fwd.hpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
Source/Game/Match3Cell.fwd.hpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
Source/Game/Match3Cell.fwd.hpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
// // Match3Cell.fwd.hpp // // @author Roberto Cano // #pragma once #include <memory> #include <glm/glm.hpp> namespace Match3 { namespace Game { class Cell; } namespace Types { namespace Cell { using PtrType = std::shared_ptr<Match3::Game::Cell>; using Position = glm::ivec2; enum class State : int { Normal, Active, Disabled }; }; } }
11.205882
55
0.611549
gabr1e11
ad49669b2083f2df29e59344d6dbd6bc414b0947
4,025
cpp
C++
src/clock.cpp
Cyberax/lstructural
3496e46fe7e671575ea9eaf9ce6063acad8d9006
[ "Apache-2.0" ]
null
null
null
src/clock.cpp
Cyberax/lstructural
3496e46fe7e671575ea9eaf9ce6063acad8d9006
[ "Apache-2.0" ]
null
null
null
src/clock.cpp
Cyberax/lstructural
3496e46fe7e671575ea9eaf9ce6063acad8d9006
[ "Apache-2.0" ]
null
null
null
/* MIT License Copyright (c) 2013-2017 Evgeny Safronov <division494@gmail.com> Copyright (c) 2013-2017 Other contributors as noted in the AUTHORS file. 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 <cstdio> #include "clock.h" #include "log_sink.h" using namespace llog; const llog::clock_t the_clock; const llog::clock_t *llog::system_clock = &the_clock; static auto fast_gmtime(time_t t, struct tm* tp) noexcept -> struct tm* { int yday; uintptr_t n, sec, min, hour, mday, mon, year, wday, days, leap; // The calculation is valid for positive time_t only. n = t; days = n / 86400; // Jaunary 1, 1970 was Thursday wday = (4 + days) % 7; n %= 86400; hour = n / 3600; n %= 3600; min = n / 60; sec = n % 60; // The algorithm based on Gauss's formula, see src/http/ngx_http_parse_time.c. // Days since March 1, 1 BC. days = days - (31 + 28) + 719527; // The "days" should be adjusted to 1 only, however, some March 1st's go to previous year, so // we adjust them to 2. This causes also shift of the last Feburary days to next year, but we // catch the case when "yday" becomes negative. year = (days + 2) * 400 / (365 * 400 + 100 - 4 + 1); yday = static_cast<int>(days - (365 * year + year / 4 - year / 100 + year / 400)); leap = (year % 4 == 0) && (year % 100 || (year % 400 == 0)); if (yday < 0) { yday = static_cast<int>(365 + leap + static_cast<unsigned long>(yday)); year--; } // The empirical formula that maps "yday" to month. There are at least 10 variants, some of // them are: // mon = (yday + 31) * 15 / 459 // mon = (yday + 31) * 17 / 520 // mon = (yday + 31) * 20 / 612 mon = static_cast<uintptr_t>((yday + 31) * 10 / 306); // The Gauss's formula that evaluates days before the month. mday = static_cast<unsigned long>(yday)- (367 * mon / 12 - 30) + 1; if (yday >= 306) { year++; mon -= 10; yday -= 306; } else { mon += 2; yday += 31 + 28 + static_cast<int>(leap); } tp->tm_sec = static_cast<int>(sec); tp->tm_min = static_cast<int>(min); tp->tm_hour = static_cast<int>(hour); tp->tm_mday = static_cast<int>(mday); tp->tm_mon = static_cast<int>(mon - 1); tp->tm_year = static_cast<int>(year - 1900); tp->tm_yday = yday; tp->tm_wday = static_cast<int>(wday); tp->tm_isdst = 0; return tp; } class tzinit_t { public: tzinit_t() { tzset(); } }; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" static const tzinit_t tz; #pragma clang diagnostic pop static auto localtime(time_t t, struct tm* tp) noexcept -> struct tm* { time_t time = t - timezone; gmtime_r(&time, tp); tp->tm_gmtoff = timezone; tp->tm_zone = *tzname; return tp; } void llog::print_timestamp(const timespec &t, sink_t &sink) { char buff[100]; tm gmt = {}; fast_gmtime(time_t(t.tv_sec), &gmt); // size_t ln = snprintf(buff, sizeof(buff),"%4d-%2d-%2dT%2d:%2d:%2d.%ldZ", // gmt.tm_year, gmt.tm_mon, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec, // t.tv_nsec/1000); // sink.write(buff, ln); }
30.492424
95
0.680745
Cyberax
ad49f226c6b809aea3776b2e566054b365fa75cb
2,591
hh
C++
src/serialize/command.hh
chuyqa/pydoop
575f56cc66381fef08981a2452acde02bddf0363
[ "Apache-2.0" ]
null
null
null
src/serialize/command.hh
chuyqa/pydoop
575f56cc66381fef08981a2452acde02bddf0363
[ "Apache-2.0" ]
null
null
null
src/serialize/command.hh
chuyqa/pydoop
575f56cc66381fef08981a2452acde02bddf0363
[ "Apache-2.0" ]
null
null
null
// BEGIN_COPYRIGHT // // Copyright 2009-2018 CRS4. // // 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. // // END_COPYRIGHT #ifndef PYDOOP_COMMAND_HH #define PYDOOP_COMMAND_HH #include <Python.h> #include <structmember.h> #include <string> #include <vector> #include <assert.h> #include "flow.hh" PyObject* get_rules(void); class CommandReader { public: CommandReader(FlowReader* flow_reader) : _flow_reader(flow_reader) {} // returns tuple(CMD_CODE, tuple(args)) PyObject* read(void) ; inline PyObject* close(void) { return _flow_reader->close();} ~CommandReader() { delete _flow_reader; } private: FlowReader* _flow_reader; }; class CommandWriter { public: CommandWriter(FlowWriter* flow_writer) : _flow_writer(flow_writer) {} inline PyObject* flush(void) { return _flow_writer->flush(); } inline PyObject* close(void) { return _flow_writer->close(); } // tuple(CMD_CODE, tuple(args)) inline PyObject* write(PyObject* args) ; ~CommandWriter() { delete _flow_writer; } private: FlowWriter* _flow_writer; }; typedef struct { PyObject_HEAD CommandReader* reader; } CommandReaderInfo; typedef struct { PyObject_HEAD CommandWriter* writer; } CommandWriterInfo; PyObject* CommandWriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds); int CommandWriter_init(CommandWriterInfo *self, PyObject *args, PyObject *kwds); void CommandWriter_dealloc(CommandWriterInfo *self); PyObject* CommandWriter_write(CommandWriterInfo *self, PyObject* args); PyObject* CommandWriter_flush(CommandWriterInfo *self); PyObject* CommandWriter_close(CommandWriterInfo *self); PyObject* CommandReader_new(PyTypeObject *type, PyObject *args, PyObject *kwds); int CommandReader_init(CommandReaderInfo *self, PyObject *args, PyObject *kwds); void CommandReader_dealloc(CommandReaderInfo *self); PyObject* CommandReader_read(CommandReaderInfo *self); PyObject* CommandReader_close(CommandReaderInfo *self); PyObject* CommandReader_iter(PyObject* self); PyObject* CommandReader_iternext(PyObject* self); #endif // PYDOOP_COMMAND_HH
25.401961
80
0.759552
chuyqa
ad4b484f12f66e02542b58aa48c332f707c4ef57
3,258
cpp
C++
src/math/optimizer_math/sgd_momentum.cpp
Boxun-coder/magmadnn
76d23ff8ea9c63839da6965b9c5ab4aad07f9250
[ "MIT" ]
2
2020-07-20T08:39:47.000Z
2020-07-20T08:40:06.000Z
src/math/optimizer_math/sgd_momentum.cpp
Boxun-coder/magmadnn
76d23ff8ea9c63839da6965b9c5ab4aad07f9250
[ "MIT" ]
null
null
null
src/math/optimizer_math/sgd_momentum.cpp
Boxun-coder/magmadnn
76d23ff8ea9c63839da6965b9c5ab4aad07f9250
[ "MIT" ]
null
null
null
/** * @file sgd_momentum.cpp * @author Sedrick Keh * @version 1.0 * @date 2019-07-25 * * @copyright Copyright (c) 2019 */ #include "math/optimizer_math/sgd_momentum.h" #include <cassert> #include <vector> #include "magmadnn/config.h" namespace magmadnn { namespace math { template <typename T> void sgd_momentum_cpu( T learning_rate, T momentum, Tensor<T> *prev, Tensor<T> *grad, std::vector<int> *idxs, Tensor<T> *out) { assert(prev->get_size() == grad->get_size()); assert(grad->get_size() == out->get_size()); T *prev_ptr = prev->get_ptr(); T *grad_ptr = grad->get_ptr(); T *out_ptr = out->get_ptr(); // unsigned int size = out->get_size(); unsigned int sample_size = idxs->size(); for (unsigned int i = 0; i < sample_size; i++) { int idx = (*idxs)[i]; prev_ptr[idx] = momentum * prev_ptr[idx] + (1 - momentum) * grad_ptr[idx]; out_ptr[idx] = out_ptr[idx] - learning_rate * prev_ptr[idx]; } } template void sgd_momentum_cpu<float>( float learning_rate, float momentum, Tensor<float> *prev, Tensor<float> *grad, std::vector<int> *idxs, Tensor<float> *out); template void sgd_momentum_cpu<double>( double learning_rate, double momentum, Tensor<double> *prev, Tensor<double> *grad, std::vector<int> *idxs, Tensor<double> *out); template <typename T> void sgd_momentum_cpu( T learning_rate, T momentum, Tensor<T> *prev, Tensor<T> *grad, Tensor<T> *out) { assert(prev->get_size() == grad->get_size()); assert(grad->get_size() == out->get_size()); T *prev_ptr = prev->get_ptr(); T *grad_ptr = grad->get_ptr(); T *out_ptr = out->get_ptr(); unsigned int size = out->get_size(); for (unsigned int i = 0; i < size; i++) { prev_ptr[i] = momentum * prev_ptr[i] + (1 - momentum) * grad_ptr[i]; out_ptr[i] = out_ptr[i] - learning_rate * prev_ptr[i]; } } template void sgd_momentum_cpu( int learning_rate, int momentum, Tensor<int> *prev, Tensor<int> *grad, Tensor<int> *out); template void sgd_momentum_cpu( float learning_rate, float momentum, Tensor<float> *prev, Tensor<float> *grad, Tensor<float> *out); template void sgd_momentum_cpu( double learning_rate, double momentum, Tensor<double> *prev, Tensor<double> *grad, Tensor<double> *out); template <typename T> void sgd_momentum(T learning_rate, T momentum, Tensor<T> *prev, Tensor<T> *grad, Tensor<T> *out) { assert(prev->get_size() == grad->get_size()); assert(grad->get_size() == out->get_size()); if (out->get_memory_type() == HOST) { sgd_momentum_cpu(learning_rate, momentum, prev, grad, out); } #if defined(MAGMADNN_HAVE_CUDA) else { sgd_momentum_device(learning_rate, momentum, prev, grad, out); } #endif } template void sgd_momentum(int learning_rate, int momentum, Tensor<int> *prev, Tensor<int> *grad, Tensor<int> *out); template void sgd_momentum(float learning_rate, float momentum, Tensor<float> *prev, Tensor<float> *grad, Tensor<float> *out); template void sgd_momentum(double learning_rate, double momentum, Tensor<double> *prev, Tensor<double> *grad, Tensor<double> *out); } // namespace math } // namespace magmadnn
34.659574
116
0.655617
Boxun-coder
ad4b5084a5651fac8d7da4f62a637f9a26abb93f
93
cpp
C++
IA/StupidAgent.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
1
2021-05-30T02:13:37.000Z
2021-05-30T02:13:37.000Z
IA/StupidAgent.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
null
null
null
IA/StupidAgent.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
null
null
null
#include "StupidAgent.h" StupidAgent::StupidAgent() { } StupidAgent::~StupidAgent() { }
7.153846
27
0.677419
GP-S
ad4bff05071bbbce5bf15953b5213fc6cd5c2265
1,128
cpp
C++
src/tools/strong_cc_main.cpp
FantaApps/zgraph
9e25c6d52f8f730b9f65bbd92c3dea7aa20b7688
[ "MIT" ]
1
2020-11-30T04:26:41.000Z
2020-11-30T04:26:41.000Z
src/tools/strong_cc_main.cpp
FantaApps/zgraph
9e25c6d52f8f730b9f65bbd92c3dea7aa20b7688
[ "MIT" ]
9
2019-11-04T06:31:02.000Z
2019-11-28T16:19:23.000Z
src/tools/strong_cc_main.cpp
FantaApps/zgraph
9e25c6d52f8f730b9f65bbd92c3dea7aa20b7688
[ "MIT" ]
null
null
null
#include "../lib/graph.h" #include "../lib/graph_algo.h" #include <omp.h> #include <sys/resource.h> #include <map> #include <vector> using namespace std; using namespace apsara::odps::graph::query; int main(int argc, char* argv[]) { const rlim_t kStackSize = 2 * 1024 * 1024 * 1024; // min stack size = 16 MB struct rlimit rl; int result; result = getrlimit(RLIMIT_STACK, &rl); if (result == 0) { cout<<"Adjusting stack size......" <<endl; if (rl.rlim_cur < kStackSize) { rl.rlim_cur = kStackSize; result = setrlimit(RLIMIT_STACK, &rl); if (result != 0) { fprintf(stderr, "setrlimit returned result = %d\n", result); } } } string graphFolder = "/apsarapangu/disk8/twitter-2010/bfs_query/test/CSR/uint32/"; shared_ptr<Graph<uint32_t>> g = shared_ptr<Graph<uint32_t>>(new GraphCSR<uint32_t>()); g->Init(graphFolder); GraphAlgo<uint32_t> algo(g); algo.SetNumThreads(16); map<uint32_t, vector<uint32_t>> sCC; algo.StronglyCC(g, sCC); return 0; }
25.066667
86
0.590426
FantaApps
ad4de507bf1b2599fc4636a4d364f560474ca8d2
14,333
cpp
C++
external/soci/postgresql/statement.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
external/soci/postgresql/statement.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
external/soci/postgresql/statement.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// // Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton // 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) // #define SOCI_POSTGRESQL_SOURCE #include "soci-postgresql.h" #include <soci.h> #include <libpq/libpq-fs.h> // libpq #include <cctype> #include <cstdio> #include <cstring> #include <ctime> #include <sstream> #ifdef SOCI_PGSQL_NOPARAMS #define SOCI_PGSQL_NOBINDBYNAME #endif // SOCI_PGSQL_NOPARAMS #ifdef _MSC_VER #pragma warning(disable:4355) #endif using namespace SOCI; using namespace SOCI::details; PostgreSQLStatementBackEnd::PostgreSQLStatementBackEnd( PostgreSQLSessionBackEnd &session) : session_(session), result_(NULL), justDescribed_(false), hasIntoElements_(false), hasVectorIntoElements_(false), hasUseElements_(false), hasVectorUseElements_(false) { } void PostgreSQLStatementBackEnd::alloc() { // nothing to do here } void PostgreSQLStatementBackEnd::cleanUp() { if (result_ != NULL) { PQclear(result_); result_ = NULL; } } void PostgreSQLStatementBackEnd::prepare(std::string const &query, eStatementType eType) { #ifdef SOCI_PGSQL_NOBINDBYNAME query_ = query; #else // rewrite the query by transforming all named parameters into // the PostgreSQL numbers ones (:abc -> $1, etc.) enum { eNormal, eInQuotes, eInName } state = eNormal; std::string name; int position = 1; for (std::string::const_iterator it = query.begin(), end = query.end(); it != end; ++it) { switch (state) { case eNormal: if (*it == '\'') { query_ += *it; state = eInQuotes; } else if (*it == ':') { state = eInName; } else // regular character, stay in the same state { query_ += *it; } break; case eInQuotes: if (*it == '\'') { query_ += *it; state = eNormal; } else // regular quoted character { query_ += *it; } break; case eInName: if (std::isalnum(*it) || *it == '_') { name += *it; } else // end of name { names_.push_back(name); name.clear(); std::ostringstream ss; ss << '$' << position++; query_ += ss.str(); query_ += *it; state = eNormal; } break; } } if (state == eInName) { names_.push_back(name); std::ostringstream ss; ss << '$' << position++; query_ += ss.str(); } #endif // SOCI_PGSQL_NOBINDBYNAME #ifndef SOCI_PGSQL_NOPREPARE if (eType == eRepeatableQuery) { statementName_ = session_.getNextStatementName(); PGresult *res = PQprepare(session_.conn_, statementName_.c_str(), query_.c_str(), static_cast<int>(names_.size()), NULL); if (res == NULL) { throw SOCIError("Cannot prepare statement."); } ExecStatusType status = PQresultStatus(res); if (status != PGRES_COMMAND_OK) { throw SOCIError(PQresultErrorMessage(res)); } PQclear(res); } eType_ = eType; #endif // SOCI_PGSQL_NOPREPARE } StatementBackEnd::execFetchResult PostgreSQLStatementBackEnd::execute(int number) { // If the statement was "just described", then we know that // it was actually executed with all the use elements // already bound and pre-used. This means that the result of the // query is already on the client side, so there is no need // to re-execute it. if (justDescribed_ == false) { // This object could have been already filled with data before. cleanUp(); if (number > 1 && hasIntoElements_) { throw SOCIError( "Bulk use with single into elements is not supported."); } // Since the bulk operations are not natively supported by PostgreSQL, // we have to explicitly loop to achieve the bulk operations. // On the other hand, looping is not needed if there are single // use elements, even if there is a bulk fetch. // We know that single use and bulk use elements in the same query are // not supported anyway, so in the effect the 'number' parameter here // specifies the size of vectors (into/use), but 'numberOfExecutions' // specifies the number of loops that need to be performed. int numberOfExecutions = 1; if (number > 0) { numberOfExecutions = hasUseElements_ ? 1 : number; } if (!useByPosBuffers_.empty() || !useByNameBuffers_.empty()) { if (!useByPosBuffers_.empty() && !useByNameBuffers_.empty()) { throw SOCIError( "Binding for use elements must be either by position " "or by name."); } for (int i = 0; i != numberOfExecutions; ++i) { std::vector<char *> paramValues; if (!useByPosBuffers_.empty()) { // use elements bind by position // the map of use buffers can be traversed // in its natural order for (UseByPosBuffersMap::iterator it = useByPosBuffers_.begin(), end = useByPosBuffers_.end(); it != end; ++it) { char **buffers = it->second; paramValues.push_back(buffers[i]); } } else { // use elements bind by name for (std::vector<std::string>::iterator it = names_.begin(), end = names_.end(); it != end; ++it) { UseByNameBuffersMap::iterator b = useByNameBuffers_.find(*it); if (b == useByNameBuffers_.end()) { std::string msg( "Missing use element for bind by name ("); msg += *it; msg += ")."; throw SOCIError(msg); } char **buffers = b->second; paramValues.push_back(buffers[i]); } } #ifdef SOCI_PGSQL_NOPARAMS throw SOCIError("Queries with parameters are not supported."); #else #ifdef SOCI_PGSQL_NOPREPARE result_ = PQexecParams(session_.conn_, query_.c_str(), static_cast<int>(paramValues.size()), NULL, &paramValues[0], NULL, NULL, 0); #else if (eType_ == eRepeatableQuery) { // this query was separately prepared result_ = PQexecPrepared(session_.conn_, statementName_.c_str(), static_cast<int>(paramValues.size()), &paramValues[0], NULL, NULL, 0); } else // eType_ == eOneTimeQuery { // this query was not separately prepared and should // be executed as a one-time query result_ = PQexecParams(session_.conn_, query_.c_str(), static_cast<int>(paramValues.size()), NULL, &paramValues[0], NULL, NULL, 0); } #endif // SOCI_PGSQL_NOPREPARE #endif // SOCI_PGSQL_NOPARAMS if (numberOfExecutions > 1) { // there are only bulk use elements (no intos) if (result_ == NULL) { throw SOCIError("Cannot execute query."); } ExecStatusType status = PQresultStatus(result_); if (status != PGRES_COMMAND_OK) { throw SOCIError(PQresultErrorMessage(result_)); } PQclear(result_); } } if (numberOfExecutions > 1) { // it was a bulk operation result_ = NULL; return eNoData; } // otherwise (no bulk), follow the code below } else { // there are no use elements // - execute the query without parameter information #ifdef SOCI_PGSQL_NOPREPARE result_ = PQexec(session_.conn_, query_.c_str()); #else if (eType_ == eRepeatableQuery) { // this query was separately prepared result_ = PQexecPrepared(session_.conn_, statementName_.c_str(), 0, NULL, NULL, NULL, 0); } else // eType_ == eOneTimeQuery { result_ = PQexec(session_.conn_, query_.c_str()); } #endif // SOCI_PGSQL_NOPREPARE if (result_ == NULL) { throw SOCIError("Cannot execute query."); } } } else { // The optimization based on the existing results // from the row description can be performed only once. // If the same statement is re-executed, // it will be *really* re-executed, without reusing existing data. justDescribed_ = false; } ExecStatusType status = PQresultStatus(result_); if (status == PGRES_TUPLES_OK) { currentRow_ = 0; rowsToConsume_ = 0; numberOfRows_ = PQntuples(result_); if (numberOfRows_ == 0) { return eNoData; } else { if (number > 0) { // prepare for the subsequent data consumption return fetch(number); } else { // execute(0) was meant to only perform the query return eSuccess; } } } else if (status == PGRES_COMMAND_OK) { return eNoData; } else { throw SOCIError(PQresultErrorMessage(result_)); } } StatementBackEnd::execFetchResult PostgreSQLStatementBackEnd::fetch(int number) { // Note: This function does not actually fetch anything from anywhere // - the data was already retrieved from the server in the execute() // function, and the actual consumption of this data will take place // in the postFetch functions, called for each into element. // Here, we only prepare for this to happen (to emulate "the Oracle way"). // forward the "cursor" from the last fetch currentRow_ += rowsToConsume_; if (currentRow_ >= numberOfRows_) { // all rows were already consumed return eNoData; } else { if (currentRow_ + number > numberOfRows_) { rowsToConsume_ = numberOfRows_ - currentRow_; // this simulates the behaviour of Oracle // - when EOF is hit, we return eNoData even when there are // actually some rows fetched return eNoData; } else { rowsToConsume_ = number; return eSuccess; } } } int PostgreSQLStatementBackEnd::getNumberOfRows() { return numberOfRows_ - currentRow_; } std::string PostgreSQLStatementBackEnd::rewriteForProcedureCall( std::string const &query) { std::string newQuery("select "); newQuery += query; return newQuery; } int PostgreSQLStatementBackEnd::prepareForDescribe() { execute(1); justDescribed_ = true; int columns = PQnfields(result_); return columns; } void PostgreSQLStatementBackEnd::describeColumn(int colNum, eDataType &type, std::string &columnName) { // In PostgreSQL column numbers start from 0 int pos = colNum - 1; unsigned long typeOid = PQftype(result_, pos); switch (typeOid) { // Note: the following list of OIDs was taken from the pg_type table // we do not claim that this list is exchaustive or even correct. // from pg_type: case 25: // text case 1043: // varchar case 2275: // cstring case 18: // char case 1042: // bpchar type = eString; break; case 702: // abstime case 703: // reltime case 1082: // date case 1083: // time case 1114: // timestamp case 1184: // timestamptz case 1266: // timetz type = eDate; break; case 700: // float4 case 701: // float8 case 1700: // numeric type = eDouble; break; case 16: // bool case 21: // int2 case 23: // int4 case 20: // int8 type = eInteger; break; case 26: // oid type = eUnsignedLong; break; default: throw SOCIError("Unknown data type."); } columnName = PQfname(result_, pos); } PostgreSQLStandardIntoTypeBackEnd * PostgreSQLStatementBackEnd::makeIntoTypeBackEnd() { hasIntoElements_ = true; return new PostgreSQLStandardIntoTypeBackEnd(*this); } PostgreSQLStandardUseTypeBackEnd * PostgreSQLStatementBackEnd::makeUseTypeBackEnd() { hasUseElements_ = true; return new PostgreSQLStandardUseTypeBackEnd(*this); } PostgreSQLVectorIntoTypeBackEnd * PostgreSQLStatementBackEnd::makeVectorIntoTypeBackEnd() { hasVectorIntoElements_ = true; return new PostgreSQLVectorIntoTypeBackEnd(*this); } PostgreSQLVectorUseTypeBackEnd * PostgreSQLStatementBackEnd::makeVectorUseTypeBackEnd() { hasVectorUseElements_ = true; return new PostgreSQLVectorUseTypeBackEnd(*this); }
27.777132
78
0.534431
saga-project
ad4e124c911f97684146a7fc6387892dbbcc24f0
8,465
cpp
C++
ScreenKeyboard/KeyboardHandler.cpp
jscipione/HaikuUtils
82cb2c1c1484244ab1041b71ca7632b4322bd643
[ "MIT" ]
1
2021-05-23T18:03:58.000Z
2021-05-23T18:03:58.000Z
ScreenKeyboard/KeyboardHandler.cpp
jscipione/HaikuUtils
82cb2c1c1484244ab1041b71ca7632b4322bd643
[ "MIT" ]
null
null
null
ScreenKeyboard/KeyboardHandler.cpp
jscipione/HaikuUtils
82cb2c1c1484244ab1041b71ca7632b4322bd643
[ "MIT" ]
null
null
null
#include "KeyboardHandler.h" #include <Message.h> #include <malloc.h> #include <string.h> void PressKey(uint8 *state, uint32 code) { state[code/8] |= 1 << (code%8); } void ReleaseKey(uint8 *state, uint32 code) { state[code/8] &= ~(uint8)(1 << (code%8)); } bool IsKeyPressed(uint8 *state, uint32 code) { return state[code/8] & (1 << (code%8)); } void KeyboardHandler::StartRepeating(BMessage *msg) { if (repeatThread > 0) StopRepeating(); repeatMsg = *msg; repeatThread = spawn_thread(RepeatThread, "repeat thread", B_REAL_TIME_PRIORITY, this); repeatThreadSem = create_sem(0, "repeat thread sem"); if (repeatThread > 0) resume_thread(repeatThread); } void KeyboardHandler::StopRepeating() { if (repeatThread > 0) { status_t res; sem_id sem = repeatThreadSem; repeatThreadSem = B_BAD_SEM_ID; delete_sem(sem); wait_for_thread(repeatThread, &res); repeatThread = 0; } } status_t KeyboardHandler::RepeatThread(void *arg) { KeyboardHandler *h = (KeyboardHandler*)arg; int32 count; if (acquire_sem_etc(h->repeatThreadSem, 1, B_RELATIVE_TIMEOUT, h->repeatDelay) == B_BAD_SEM_ID) return B_OK; while (true) { h->repeatMsg.ReplaceInt64("when", system_time()); h->repeatMsg.FindInt32("be:key_repeat", &count); h->repeatMsg.ReplaceInt32("be:key_repeat", count + 1); BMessage *msg = new BMessage(h->repeatMsg); if (msg != NULL) if (h->dev->EnqueueMessage(msg) != B_OK) delete msg; if (acquire_sem_etc(h->repeatThreadSem, 1, B_RELATIVE_TIMEOUT, /* 1000000 / h->repeatRate */ 50000) == B_BAD_SEM_ID) return B_OK; } } KeyboardHandler::KeyboardHandler(BInputServerDevice *dev, key_map *keyMap, char *chars, bigtime_t repeatDelay, int32 repeatRate) : dev(dev), keyMap(keyMap), chars(chars), repeatDelay(repeatDelay), repeatRate(repeatRate) { repeatThread = 0; memset(state, 0, sizeof(state)); notifiers = NULL; } KeyboardHandler::~KeyboardHandler() { StopRepeating(); if (keyMap != NULL) free((void*)keyMap); if (chars != NULL) free((void*)chars); } void KeyboardHandler::SetKeyMap(key_map *keyMap, char *chars) { if (this->keyMap != NULL) free((void*)this->keyMap); if (this->chars != NULL) free((void*)this->chars); this->keyMap = keyMap; this->chars = chars; LocksChanged(keyMap->lock_settings); for (KeyboardNotifier *i = notifiers; i != NULL; i = i->next) i->KeymapChanged(); } void KeyboardHandler::SetRepeat(bigtime_t delay, int32 rate) { repeatDelay = delay; repeatRate = rate; } void KeyboardHandler::InstallNotifier(KeyboardNotifier *notifier) { notifier->next = notifiers; notifiers = notifier; } void KeyboardHandler::UninstallNotifier(KeyboardNotifier *notifier) { if (notifier == notifiers) { notifiers = notifiers->next; } else { KeyboardNotifier *prev = notifiers; while (prev->next != notifier) prev = prev->next; prev->next = notifier->next; } } void KeyboardHandler::State(uint *state) { memcpy(state, this->state, sizeof(state)); } uint32 KeyboardHandler::Modifiers() { return modifiers; } void KeyboardHandler::KeyString(uint32 code, char *str, size_t len) { uint32 i; char *ch; switch (modifiers & (B_SHIFT_KEY | B_CONTROL_KEY | B_OPTION_KEY | B_CAPS_LOCK)) { case B_OPTION_KEY | B_CAPS_LOCK | B_SHIFT_KEY: ch = chars + keyMap->option_caps_shift_map[code]; break; case B_OPTION_KEY | B_CAPS_LOCK: ch = chars + keyMap->option_caps_map[code]; break; case B_OPTION_KEY | B_SHIFT_KEY: ch = chars + keyMap->option_shift_map[code]; break; case B_OPTION_KEY: ch = chars + keyMap->option_map[code]; break; case B_CAPS_LOCK | B_SHIFT_KEY: ch = chars + keyMap->caps_shift_map[code]; break; case B_CAPS_LOCK: ch = chars + keyMap->caps_map[code]; break; case B_SHIFT_KEY: ch = chars + keyMap->shift_map[code]; break; default: if (modifiers & B_CONTROL_KEY) ch = chars + keyMap->control_map[code]; else ch = chars + keyMap->normal_map[code]; } if (len > 0) { for (i = 0; (i < (uint32)ch[0]) && (i < len-1); ++i) str[i] = ch[i+1]; str[i] = '\0'; } } void KeyboardHandler::KeyChanged(uint32 code, bool isDown) { uint8 state[16]; memcpy(state, this->state, sizeof(state)); if (isDown) state[code/8] |= 1 << (code%8); else state[code/8] &= ~(uint8)(1 << (code%8)); StateChanged(state); } void KeyboardHandler::CodelessKeyChanged(const char *str, bool isDown, bool doRepeat) { BMessage *msg = new BMessage(); if (msg == NULL) return; msg->AddInt64("when", system_time()); msg->AddInt32("key", 0); msg->AddString("bytes", str); msg->AddInt32("raw_char", 0xa); if (isDown) { msg->what = B_KEY_DOWN; if (doRepeat) { msg->AddInt32("be:key_repeat", 1); StartRepeating(msg); } } else { msg->what = B_KEY_UP; if (doRepeat) StopRepeating(); } if (dev->EnqueueMessage(msg) != B_OK) delete msg; } void KeyboardHandler::StateChanged(uint8 state[16]) { uint32 i, j; BMessage *msg; uint32 modifiers = this->modifiers & (B_CAPS_LOCK | B_SCROLL_LOCK | B_NUM_LOCK); if (IsKeyPressed(state, keyMap->left_shift_key)) modifiers |= B_SHIFT_KEY | B_LEFT_SHIFT_KEY; if (IsKeyPressed(state, keyMap->right_shift_key)) modifiers |= B_SHIFT_KEY | B_RIGHT_SHIFT_KEY; if (IsKeyPressed(state, keyMap->left_command_key)) modifiers |= B_COMMAND_KEY | B_LEFT_COMMAND_KEY; if (IsKeyPressed(state, keyMap->right_command_key)) modifiers |= B_COMMAND_KEY | B_RIGHT_COMMAND_KEY; if (IsKeyPressed(state, keyMap->left_control_key)) modifiers |= B_CONTROL_KEY | B_LEFT_CONTROL_KEY; if (IsKeyPressed(state, keyMap->right_control_key)) modifiers |= B_CONTROL_KEY | B_RIGHT_CONTROL_KEY; if (IsKeyPressed(state, keyMap->caps_key)) modifiers ^= B_CAPS_LOCK; if (IsKeyPressed(state, keyMap->scroll_key)) modifiers ^= B_SCROLL_LOCK; if (IsKeyPressed(state, keyMap->num_key)) modifiers ^= B_NUM_LOCK; if (IsKeyPressed(state, keyMap->left_option_key)) modifiers |= B_OPTION_KEY | B_LEFT_OPTION_KEY; if (IsKeyPressed(state, keyMap->right_option_key)) modifiers |= B_OPTION_KEY | B_RIGHT_OPTION_KEY; if (IsKeyPressed(state, keyMap->menu_key)) modifiers |= B_MENU_KEY; if (this->modifiers != modifiers) { msg = new BMessage(B_MODIFIERS_CHANGED); if (msg != NULL) { msg->AddInt64("when", system_time()); msg->AddInt32("modifiers", modifiers); msg->AddInt32("be:old_modifiers", this->modifiers); msg->AddData("states", B_UINT8_TYPE, state, 16); if (dev->EnqueueMessage(msg) == B_OK) this->modifiers = modifiers; else delete msg; } } uint8 diff[16]; char rawCh; char str[5]; for (i = 0; i < 16; ++i) diff[i] = this->state[i] ^ state[i]; for (i = 0; i < 128; ++i) { if (diff[i/8] & (1 << (i%8))) { msg = new BMessage(); if (msg) { KeyString(i, str, sizeof(str)); msg->AddInt64("when", system_time()); msg->AddInt32("key", i); msg->AddInt32("modifiers", modifiers); msg->AddData("states", B_UINT8_TYPE, state, 16); if (str[0] != '\0') { if (chars[keyMap->normal_map[i]] != 0) rawCh = chars[keyMap->normal_map[i] + 1]; else rawCh = str[0]; for (j = 0; str[j] != '\0'; ++j) msg->AddInt8("byte", str[j]); msg->AddString("bytes", str); msg->AddInt32("raw_char", rawCh); } if (state[i/8] & (1 << (i%8))) { if (str[0] != '\0') msg->what = B_KEY_DOWN; else msg->what = B_UNMAPPED_KEY_DOWN; msg->AddInt32("be:key_repeat", 1); StartRepeating(msg); } else { if (str[0] != '\0') msg->what = B_KEY_UP; else msg->what = B_UNMAPPED_KEY_UP; StopRepeating(); } if (dev->EnqueueMessage(msg) == B_OK) { for (j = 0; j < 16; ++j) this->state[j] = state[j]; } else delete msg; } } } } void KeyboardHandler::LocksChanged(uint32 locks) { locks &= B_CAPS_LOCK | B_NUM_LOCK | B_SCROLL_LOCK; if (modifiers != locks) { BMessage *msg = new BMessage(B_MODIFIERS_CHANGED); if (msg != NULL) { msg->AddInt64("when", system_time()); msg->AddInt32("modifiers", locks); msg->AddInt32("be:old_modifiers", modifiers); msg->AddData("states", B_UINT8_TYPE, state, 16); if (dev->EnqueueMessage(msg) == B_OK) modifiers = locks; else delete msg; } } }
27.57329
131
0.6443
jscipione
ad5073b098a914fab2c0838b03e8ebe936ff1f03
348
cpp
C++
leetcode/Two Sum II - Input array is sorted.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
2
2019-01-30T12:45:18.000Z
2021-05-06T19:02:51.000Z
leetcode/Two Sum II - Input array is sorted.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
null
null
null
leetcode/Two Sum II - Input array is sorted.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
3
2020-10-02T15:42:04.000Z
2022-03-27T15:14:16.000Z
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int l = 0, r = numbers.size()-1; while(l<r) { int sum = numbers[l] + numbers[r]; if(sum == target) return {l+1, r+1}; else if(sum < target) l++; else r--; } return {l+1, r+1}; } };
26.769231
58
0.454023
ANONYMOUS609
ad577e3639b783744ad2c4220e9095984ba8d610
3,573
cc
C++
src/messages/text_document_rename.cc
Gei0r/cquery
6ff8273e8b8624016f9363f444acfee30c4bbf64
[ "MIT" ]
1,652
2018-01-24T03:19:58.000Z
2020-07-28T19:04:00.000Z
src/messages/text_document_rename.cc
Gei0r/cquery
6ff8273e8b8624016f9363f444acfee30c4bbf64
[ "MIT" ]
490
2018-01-24T00:55:38.000Z
2020-07-03T19:44:16.000Z
src/messages/text_document_rename.cc
Gei0r/cquery
6ff8273e8b8624016f9363f444acfee30c4bbf64
[ "MIT" ]
154
2018-01-31T05:57:33.000Z
2020-07-05T00:02:46.000Z
#include "message_handler.h" #include "query_utils.h" #include "queue_manager.h" namespace { MethodType kMethodType = "textDocument/rename"; lsWorkspaceEdit BuildWorkspaceEdit(QueryDatabase* db, WorkingFiles* working_files, QueryId::SymbolRef sym, const std::string& new_text) { std::unordered_map<QueryId::File, lsTextDocumentEdit> path_to_edit; EachOccurrence(db, sym, true, [&](QueryId::LexicalRef ref) { optional<lsLocation> ls_location = GetLsLocation(db, working_files, ref); if (!ls_location) return; QueryId::File file_id = ref.file; if (path_to_edit.find(file_id) == path_to_edit.end()) { path_to_edit[file_id] = lsTextDocumentEdit(); QueryFile& file = db->files[file_id.id]; if (!file.def) return; const std::string& path = file.def->path; path_to_edit[file_id].textDocument.uri = lsDocumentUri::FromPath(path); WorkingFile* working_file = working_files->GetFileByFilename(path); if (working_file) path_to_edit[file_id].textDocument.version = working_file->version; } lsTextEdit edit; edit.range = ls_location->range; edit.newText = new_text; // vscode complains if we submit overlapping text edits. auto& edits = path_to_edit[file_id].edits; if (std::find(edits.begin(), edits.end(), edit) == edits.end()) edits.push_back(edit); }); lsWorkspaceEdit edit; for (const auto& changes : path_to_edit) edit.documentChanges.push_back(changes.second); return edit; } struct In_TextDocumentRename : public RequestInMessage { MethodType GetMethodType() const override { return kMethodType; } struct Params { // The document to format. lsTextDocumentIdentifier textDocument; // The position at which this request was sent. lsPosition position; // The new name of the symbol. If the given name is not valid the // request must return a [ResponseError](#ResponseError) with an // appropriate message set. std::string newName; }; Params params; }; MAKE_REFLECT_STRUCT(In_TextDocumentRename::Params, textDocument, position, newName); MAKE_REFLECT_STRUCT(In_TextDocumentRename, id, params); REGISTER_IN_MESSAGE(In_TextDocumentRename); struct Out_TextDocumentRename : public lsOutMessage<Out_TextDocumentRename> { lsRequestId id; lsWorkspaceEdit result; }; MAKE_REFLECT_STRUCT(Out_TextDocumentRename, jsonrpc, id, result); struct Handler_TextDocumentRename : BaseMessageHandler<In_TextDocumentRename> { MethodType GetMethodType() const override { return kMethodType; } void Run(In_TextDocumentRename* request) override { QueryId::File file_id; QueryFile* file; if (!FindFileOrFail(db, project, request->id, request->params.textDocument.uri.GetAbsolutePath(), &file, &file_id)) { return; } WorkingFile* working_file = working_files->GetFileByFilename(file->def->path); Out_TextDocumentRename out; out.id = request->id; for (QueryId::SymbolRef sym : FindSymbolsAtLocation(working_file, file, request->params.position)) { // Found symbol. Return references to rename. out.result = BuildWorkspaceEdit(db, working_files, sym, request->params.newName); break; } QueueManager::WriteStdout(kMethodType, out); } }; REGISTER_MESSAGE_HANDLER(Handler_TextDocumentRename); } // namespace
32.481818
79
0.678701
Gei0r
ad5c5bc67ba224c112effaee5146319c6b05093c
45
cpp
C++
ml/src/Serv_Converters.cpp
georgephilipp/cppgstd_legacy
e130860da7700aae42b915bc36a7efa4cae06d56
[ "MIT" ]
null
null
null
ml/src/Serv_Converters.cpp
georgephilipp/cppgstd_legacy
e130860da7700aae42b915bc36a7efa4cae06d56
[ "MIT" ]
null
null
null
ml/src/Serv_Converters.cpp
georgephilipp/cppgstd_legacy
e130860da7700aae42b915bc36a7efa4cae06d56
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Converters.h"
11.25
23
0.711111
georgephilipp
ad5d2e7f67596381adaae88265de8f7f5103396c
1,536
cpp
C++
src/common/RNG.cpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
null
null
null
src/common/RNG.cpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
null
null
null
src/common/RNG.cpp
usc-csci-545/aikido
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
[ "BSD-3-Clause" ]
null
null
null
#include <aikido/common/RNG.hpp> namespace aikido { namespace common { //============================================================================== // This namespace-scoped definition is required to enable odr-use. constexpr std::size_t RNG::NUM_BITS; //============================================================================== std::vector<std::unique_ptr<common::RNG>> cloneRNGsFrom( RNG& _engine, std::size_t _numOutputs, std::size_t _numSeeds) { // Use the input RNG to create an initial batch of seeds. std::vector<common::RNG::result_type> initialSeeds; initialSeeds.reserve(_numSeeds); for (std::size_t iseed = 0; iseed < _numSeeds; ++iseed) initialSeeds.emplace_back(_engine()); // Use seed_seq to improve the quality of our seeds. std::seed_seq seqSeeds(initialSeeds.begin(), initialSeeds.end()); std::vector<common::RNG::result_type> improvedSeeds(_numOutputs); seqSeeds.generate(std::begin(improvedSeeds), std::end(improvedSeeds)); // Create the random number generators of the same type as the input _engine. std::vector<std::unique_ptr<common::RNG>> output; output.reserve(_numOutputs); for (auto improvedSeed : improvedSeeds) output.emplace_back(_engine.clone(improvedSeed)); return output; } //============================================================================== std::vector<std::unique_ptr<common::RNG>> cloneRNGFrom( RNG& _engine, std::size_t _numSeeds) { return cloneRNGsFrom(_engine, 1, _numSeeds); } } // namespace common } // namespace aikido
34.133333
80
0.621094
usc-csci-545
ad5f309ec3a01966982ea48381ad8ad082354f9e
7,262
hpp
C++
src/shelly_hap_chars.hpp
lucaspinelli85/shelly-homekit
f22f5186284f5840fde5a595587a6957be2a15b0
[ "Apache-2.0" ]
1
2020-11-17T13:46:48.000Z
2020-11-17T13:46:48.000Z
src/shelly_hap_chars.hpp
schemhad/shelly-homekit
82d8d64524af20ba30941a64c7ba060301512785
[ "Apache-2.0" ]
null
null
null
src/shelly_hap_chars.hpp
schemhad/shelly-homekit
82d8d64524af20ba30941a64c7ba060301512785
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Deomid "rojer" Ryabkov * 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. */ #pragma once #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wnullability-completeness" #endif #include <cstring> #include <functional> #include <memory> #include <string> #include <vector> #include "HAP.h" namespace shelly { namespace hap { class Service; class Characteristic { public: Characteristic(uint16_t iid, HAPCharacteristicFormat format, const HAPUUID *type, const char *debug_description = nullptr); virtual ~Characteristic(); const Service *parent() const; void set_parent(const Service *parent); virtual const HAPCharacteristic *GetHAPCharacteristic() { return hap_charactristic(); } const HAPCharacteristic *hap_charactristic(); void RaiseEvent(); protected: struct HAPCharacteristicWithInstance { union AllHAPCHaracteristicTypes { HAPDataCharacteristic data; HAPBoolCharacteristic bool_; HAPUInt8Characteristic uint8; HAPUInt16Characteristic uint16; HAPUInt32Characteristic uint32; HAPUInt64Characteristic uint64; HAPIntCharacteristic int_; HAPFloatCharacteristic float_; HAPStringCharacteristic string; HAPTLV8Characteristic tlv8; } char_; Characteristic *inst; // Pointer back to the instance. } hap_char_; private: const Service *parent_ = nullptr; Characteristic(const Characteristic &other) = delete; }; class StringCharacteristic : public Characteristic { public: StringCharacteristic(uint16_t iid, const HAPUUID *type, uint16_t max_length, const std::string &initial_value, const char *debug_description = nullptr); virtual ~StringCharacteristic(); const std::string &value() const; void set_value(const std::string &value); private: static HAPError HandleReadCB( HAPAccessoryServerRef *server, const HAPStringCharacteristicReadRequest *request, char *value, size_t maxValueBytes, void *context); std::string value_; }; // Template class that can be used to create scalar-value characteristics. template <class ValType, class HAPBaseClass, class HAPReadRequestType, class HAPWriteRequestType> struct ScalarCharacteristic : public Characteristic { public: typedef std::function<HAPError(HAPAccessoryServerRef *server, const HAPReadRequestType *request, ValType *value)> ReadHandler; typedef std::function<HAPError(HAPAccessoryServerRef *server, const HAPWriteRequestType *request, ValType value)> WriteHandler; ScalarCharacteristic(HAPCharacteristicFormat format, uint16_t iid, const HAPUUID *type, ReadHandler read_handler, bool supports_notification, WriteHandler write_handler = nullptr, const char *debug_description = nullptr) : Characteristic(iid, format, type, debug_description), read_handler_(read_handler), write_handler_(write_handler) { HAPBaseClass *c = reinterpret_cast<HAPBaseClass *>(&hap_char_.char_); if (read_handler) { c->properties.readable = true; c->callbacks.handleRead = ScalarCharacteristic::HandleReadCB; c->properties.supportsEventNotification = supports_notification; c->properties.ble.supportsBroadcastNotification = true; c->properties.ble.supportsDisconnectedNotification = true; } if (write_handler) { c->properties.writable = true; c->callbacks.handleWrite = ScalarCharacteristic::HandleWriteCB; } } virtual ~ScalarCharacteristic() { } private: static HAPError HandleReadCB(HAPAccessoryServerRef *server, const HAPReadRequestType *request, ValType *value, void *context) { auto *hci = reinterpret_cast<const HAPCharacteristicWithInstance *>( request->characteristic); auto *c = static_cast<const ScalarCharacteristic *>(hci->inst); (void) context; return const_cast<ScalarCharacteristic *>(c)->read_handler_(server, request, value); } static HAPError HandleWriteCB(HAPAccessoryServerRef *server, const HAPWriteRequestType *request, ValType value, void *context) { auto *hci = reinterpret_cast<const HAPCharacteristicWithInstance *>( request->characteristic); auto *c = static_cast<const ScalarCharacteristic *>(hci->inst); (void) context; return const_cast<ScalarCharacteristic *>(c)->write_handler_( server, request, value); } const ReadHandler read_handler_; const WriteHandler write_handler_; }; struct BoolCharacteristic : public ScalarCharacteristic<bool, HAPBoolCharacteristic, HAPBoolCharacteristicReadRequest, HAPBoolCharacteristicWriteRequest> { public: BoolCharacteristic(uint16_t iid, const HAPUUID *type, ReadHandler read_handler, bool supports_notification, WriteHandler write_handler = nullptr, const char *debug_description = nullptr) : ScalarCharacteristic(kHAPCharacteristicFormat_Bool, iid, type, read_handler, supports_notification, write_handler, debug_description) { } virtual ~BoolCharacteristic() { } }; class UInt8Characteristic : public ScalarCharacteristic<uint8_t, HAPUInt8Characteristic, HAPUInt8CharacteristicReadRequest, HAPUInt8CharacteristicWriteRequest> { public: UInt8Characteristic(uint16_t iid, const HAPUUID *type, uint8_t min, uint8_t max, uint8_t step, ReadHandler read_handler, bool supports_notification, WriteHandler write_handler = nullptr, const char *debug_description = nullptr) : ScalarCharacteristic(kHAPCharacteristicFormat_UInt8, iid, type, read_handler, supports_notification, write_handler, debug_description) { HAPUInt8Characteristic *c = &hap_char_.char_.uint8; c->constraints.minimumValue = min; c->constraints.maximumValue = max; c->constraints.stepValue = step; } virtual ~UInt8Characteristic() { } }; } // namespace hap } // namespace shelly #ifdef __clang__ #pragma clang diagnostic pop #endif
35.252427
80
0.667585
lucaspinelli85
ad629e0ec203dc6095b34ef8fd1077d9fcde2054
3,492
cpp
C++
ork.core/src/math/math_imp.cpp
tweakoz/micro_ork
66f69d5866ca30dc6066c2dacdb7bbc5b8aa73e7
[ "MIT" ]
4
2015-06-04T01:14:43.000Z
2018-06-16T05:45:57.000Z
ork.core/src/math/math_imp.cpp
tweakoz/micro_ork
66f69d5866ca30dc6066c2dacdb7bbc5b8aa73e7
[ "MIT" ]
null
null
null
ork.core/src/math/math_imp.cpp
tweakoz/micro_ork
66f69d5866ca30dc6066c2dacdb7bbc5b8aa73e7
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // MicroOrk (Orkid) // Copyright 1996-2013, Michael T. Mayers // Provided under the MIT License (see LICENSE.txt) /////////////////////////////////////////////////////////////////////////////// #include <ork/cmatrix3.h> #include <ork/cmatrix3.hpp> #include <ork/cmatrix4.h> #include <ork/cmatrix4.hpp> #include <ork/matrix_inverseGEMS.hpp> #include <ork/cvector2.h> #include <ork/cvector2.hpp> #include <ork/cvector3.h> #include <ork/cvector3.hpp> #include <ork/cvector4.h> #include <ork/cvector4.hpp> #include <ork/quaternion.h> #include <ork/quaternion.hpp> #include <ork/plane.h> #include <ork/plane.hpp> #include <ork/perlin_noise.h> #include <stdlib.h> namespace ork { math_table_1d gsintab; math_table_1d gcostab; int* OldPerlin2D::p = 0; float* OldPerlin2D::g2 = 0; /////////////////////////////////////////////////////////////// float frand( float fscale, int irez ) { float fr = float(rand()%65536)/65536.0f; return fr*fscale; } /////////////////////////////////////////////////////////////// math_table_1d::math_table_1d() : miSize( 0 ) , mfRange(0.01) , mfSizeInvRange(0.0f) { } /////////////////////////////////////////////////////////////// void math_table_1d::fill_in(int isize, float rangeX, fn_t function ) { miSize = isize; mfRange = rangeX; mfSizeInvRange = (float(isize)/rangeX); mpTable = new float[ isize ]; for( int i=0; i<isize; i++ ) { float fx = float(i)/mfSizeInvRange; mpTable[i] = function(fx); } } /////////////////////////////////////////////////////////////// float math_table_1d::operator()(float fin) const { float fidx = fin*mfSizeInvRange; return mpTable[ int(fidx)%miSize ]; } /////////////////////////////////////////////////////////////// bool UsingOpenGl() { return true; } /////////////////////////////////////////////////////////// template<> float abs( float inp ) { return ::fabsf(inp); } template<> float sin( float inp ) { return ::sinf(inp); } template<> float cos( float inp ) { return ::cosf(inp); } template<> float tan( float inp ) { return ::tanf(inp); } template<> float sqrt( float inp ) { return ::sqrtf(inp); } template<> float arccos( float inp ) { return ::acosf(inp); } float float_epsilon() { return std::numeric_limits<float>::epsilon(); } /////////////////////////////////////////////////////////// template<> double sin( double inp ) { return ::sin(inp); } template<> double cos( double inp ) { return ::cos(inp); } template<> double tan( double inp ) { return ::tan(inp); } template<> double abs( double inp ) { return ::fabs(inp); } template<> double sqrt( double inp ) { return ::sqrt(inp); } double double_epsilon() { return std::numeric_limits<double>::epsilon(); } /////////////////////////////////////////////////////////// template class TQuaternion<float>; template class TVector2<float>; template class TVector3<float>; template class TVector4<float>; template class TMatrix3<float>; template class TMatrix4<float>; template class TVector2<double>; template class TVector3<double>; template class TVector4<double>; template class TMatrix3<double>; template class TMatrix4<double>; template class ork::TPlane<float>; };
22.101266
80
0.516323
tweakoz
ad66691feaf14dd8e16d16d863eda7eb8fed06fe
12,585
hxx
C++
printscan/ui/printui/svrprop.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/ui/printui/svrprop.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/ui/printui/svrprop.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (C) Microsoft Corporation, 1995 - 1999 All rights reserved. Module Name: srvprop.hxx Abstract: Server properties header. Author: Steve Kiraly (steveKi) 11-Nov-1995 Revision History: --*/ #ifndef _SVRPROP_HXX #define _SVRPROP_HXX /******************************************************************** Defines a function to return the specified page id. ********************************************************************/ #define DEFINE_PAGE_IDENTIFIER( PageId ) \ protected: \ UINT \ uGetPageId( \ VOID \ ) const \ { \ return PageId; \ } /******************************************************************** Server property data. ********************************************************************/ class TServerData : public MSingletonWin { SIGNATURE( 'svpr' ) SAFE_NEW public: VAR( UINT, uStartPage ); VAR( INT, iCmdShow ); VAR( BOOL, bAdministrator ); VAR( BOOL, bRebootRequired ); VAR( TString, strTitle ); VAR( HANDLE, hPrintServer ); VAR( LPCTSTR, pszServerName ); VAR( TString, strMachineName ); VAR( HICON, hDefaultSmallIcon ); VAR( BOOL, bCancelButtonIsClose ); VAR( DWORD, dwDriverVersion ); VAR( BOOL, bRemoteDownLevel ); TServerData( IN LPCTSTR pszServerName, IN INT iCmdShow, IN LPARAM lParam, IN HWND hwnd, IN BOOL bModal ); ~TServerData( VOID ); BOOL bValid( VOID ); BOOL bLoad( VOID ); private: // // Copying and assignment are not defined. // TServerData( const TServerData & ); TServerData & operator =( const TServerData & ); BOOL bStore( VOID ); VOID vCreateMachineName( IN const TString &strServerName, IN BOOL bLocal, IN TString &strMachineName ); BOOL _bIsDataStored; BOOL _bValid; }; /******************************************************************** ServerProp. Base class for server property sheets. This class should not not contain any information/services that is not generic to all derived classes. ********************************************************************/ class TServerProp : public MGenericProp { SIGNATURE( 'prsv' ) SAFE_NEW protected: TServerProp( IN TServerData *pServerData ); virtual ~TServerProp( VOID ); BOOL bValid( VOID ); BOOL bHandleMessage( IN UINT uMsg, IN WPARAM wParam, IN LPARAM lParam ); VOID vCancelToClose( IN HWND hDlg ); virtual BOOL bSetUI( VOID ) = 0; virtual BOOL bReadUI( VOID ) = 0; virtual BOOL bSaveUI( VOID ) = 0; virtual UINT uGetPageId( VOID ) const = 0; TServerData *_pServerData; private: // // Copying and assignment are not defined. // TServerProp( const TServerProp & ); TServerProp & operator =( const TServerProp & ); }; /******************************************************************** General server settings page. ********************************************************************/ class TServerSettings : public TServerProp { SIGNATURE( 'stsv' ) SAFE_NEW DEFINE_PAGE_IDENTIFIER( DLG_SERVER_SETTINGS ); public: TServerSettings( IN TServerData* pServerData ); ~TServerSettings( ); BOOL bValid( VOID ); BOOL bHandleMessage( IN UINT uMsg, IN WPARAM wParam, IN LPARAM lParam ); BOOL bSetUI( VOID ); BOOL bSetUI( INT LoadType ); BOOL bReadUI( VOID ); BOOL bSaveUI( VOID ); private: enum EStatus { kStatusError, kStatusSuccess, kStatusInvalidSpoolDirectory, kStatusCannotSaveUserNotification, }; enum CONSTANTS { kServerAttributesLoad, kServerAttributesStore, kServerAttributesDefault, }; TString _strSpoolDirectoryOrig; TString _strSpoolDirectory; BOOL _bBeepErrorJobs; BOOL _bEventLogging; BOOL _bNotifyPrintedJobs; BOOL _bNotifyLocalPrintedJobs; BOOL _bNotifyNetworkPrintedJobs; BOOL _bNotifyPrintedJobsComputer; BOOL _bChanged; BOOL _bDownLevelServer; BOOL _bNewOptionSupport; private: // // Copying and assignment are not defined. // TServerSettings( const TServerSettings & ); TServerSettings & operator =( const TServerSettings & ); INT sServerAttributes( BOOL bDirection ); VOID TServerSettings:: vEnable( BOOL bState ); }; /******************************************************************** Forms server property page. ********************************************************************/ class TServerForms : public TServerProp { SIGNATURE( 'fmsv' ) SAFE_NEW DEFINE_PAGE_IDENTIFIER( DLG_FORMS ); public: TServerForms( IN TServerData* pServerData ); ~TServerForms( VOID ); BOOL bValid( VOID ); BOOL bHandleMessage( IN UINT uMsg, IN WPARAM wParam, IN LPARAM lParam ); BOOL bSetUI( VOID ); BOOL bReadUI( VOID ); BOOL bSaveUI( VOID ); private: enum { kMagic = 0xDEAD }; // // Copying and assignment are not defined. // TServerForms( const TServerForms & ); TServerForms & operator =( const TServerForms & ); PVOID _p; }; /******************************************************************** Ports server property page. ********************************************************************/ class TServerPorts : public TServerProp { SIGNATURE( 'posv' ) SAFE_NEW DEFINE_PAGE_IDENTIFIER( DLG_SERVER_PORTS ); public: TServerPorts( IN TServerData* pServerData ); ~TServerPorts( VOID ); BOOL bValid( VOID ); BOOL bSetUI( VOID ); BOOL bReadUI( VOID ); BOOL bSaveUI( VOID ); BOOL bHandleMessage( IN UINT uMsg, IN WPARAM wParam, IN LPARAM lParam ); private: // // Copying and assignment are not defined. // TServerPorts( const TServerPorts & ); TServerPorts & operator =( const TServerPorts & ); TPortsLV _PortsLV; }; /******************************************************************** Server Driver Administration. ********************************************************************/ class TServerDrivers : public TServerProp { SIGNATURE( 'drsv' ) SAFE_NEW DEFINE_PAGE_IDENTIFIER( DLG_SERVER_DRIVERS ); friend class TServerDriverNotify; public: TServerDrivers( IN TServerData* pServerData ); ~TServerDrivers( VOID ); BOOL bValid( VOID ); BOOL bSetUI( VOID ); BOOL bReadUI( VOID ); BOOL bSaveUI( VOID ); BOOL bHandleMessage( IN UINT uMsg, IN WPARAM wParam, IN LPARAM lParam ); private: // // Copying and assignment are not defined. // TServerDrivers( const TServerDrivers & ); TServerDrivers & operator =( const TServerDrivers & ); BOOL bHandleAddDriver( UINT uMsg, WPARAM wParam, LPARAM lParam ); BOOL bHandleRemoveDriver( UINT uMsg, WPARAM wParam, LPARAM lParam ); BOOL TServerDrivers:: bHandleUpdateDriver( UINT uMsg, WPARAM wParam, LPARAM lParam ); BOOL bHandleDriverDetails( UINT uMsg, WPARAM wParam, LPARAM lParam ); BOOL bHandleDriverItemSelection( UINT uMsg, WPARAM wParam, LPARAM lParam ); VOID vUpdateButtons( VOID ); BOOL bRemoveDriverCallback( IN TDriverInfo *pDriverInfo, IN DWORD dwFlags, IN DWORD dwRefdata ); BOOL bWarnUserDriverDeletion( IN TDriverInfo *pDriverInfo, IN UINT nCount ) const; BOOL TServerDrivers:: bWarnUserDriverUpdate( IN TDriverInfo *pDriverInfo, IN UINT nCount ) const; TDriversLV _DriversLV; BOOL _bChanged; BOOL _bCanRemoveDrivers; }; /******************************************************************** Driver Remove Notify class. ********************************************************************/ class TServerDriverNotify : public TDriversLVNotify { public: TServerDriverNotify( IN TServerDrivers *ServerDrivers ); ~TServerDriverNotify( VOID ); BOOL bNotify( IN TDriverInfo *pDriverInfo ); private: // // Copying and assignment are not defined. // TServerDriverNotify( const TServerDriverNotify & ); TServerDriverNotify & operator =( const TServerDriverNotify & ); BOOL bInstall( IN TDriverInfo *pDriverInfo ); BOOL bRemove( IN TDriverInfo *pDriverInfo ); BOOL bUpdate( IN TDriverInfo *pDriverInfo ); TServerDrivers *_pServerDrivers; TPrinterDriverInstallation *_pDi; BOOL _bActionFailed; UINT _uNotifyCount; }; /******************************************************************** Server property windows. ********************************************************************/ class TServerWindows { SIGNATURE( 'svrw' ) SAFE_NEW public: TServerWindows( IN TServerData *pServerData ); ~TServerWindows( VOID ); BOOL bValid( VOID ); BOOL bBuildPages( VOID ); BOOL bDisplayPages( VOID ); private: // // Copying and assignment are not defined. // TServerWindows( const TServerWindows & ); TServerWindows & operator =( const TServerWindows & ); TServerData *_pServerData; TServerForms _Forms; TServerPorts _Ports; TServerSettings _Settings; TServerDrivers _Drivers; }; /******************************************************************** Global scoped functions. ********************************************************************/ VOID vServerPropPages( IN HWND hwnd, IN LPCTSTR pszServerName, IN INT iCmdShow, IN LPARAM lParam ); INT WINAPI iServerPropPagesProc( IN TServerData *pServerData ); #endif
17.503477
70
0.433135
npocmaka
ad67028febc405a69bfae0a4d58fd3d60ff5fa07
2,973
cpp
C++
02/src/assignment/menu.cpp
KHN190/IGME-740
0e0321ceb7a2f2ade9a99caf15be16f916b12393
[ "Unlicense" ]
null
null
null
02/src/assignment/menu.cpp
KHN190/IGME-740
0e0321ceb7a2f2ade9a99caf15be16f916b12393
[ "Unlicense" ]
null
null
null
02/src/assignment/menu.cpp
KHN190/IGME-740
0e0321ceb7a2f2ade9a99caf15be16f916b12393
[ "Unlicense" ]
null
null
null
void menu(int value) { switch (value) { // clear case 0: poly.clear(); poly_color.clear(); curr_poly.clear(); n_vertices = 0; glutPostRedisplay(); break; // exit case 1: exit(0); // color seetting case 2: // red config.color[0] = 1.0f; config.color[1] = 0.0f; config.color[2] = 0.0f; glutPostRedisplay(); break; case 3: // green config.color[0] = 0.0f; config.color[1] = 1.0f; config.color[2] = 0.0f; glutPostRedisplay(); break; case 4: // blue config.color[0] = 0.0f; config.color[1] = 0.0f; config.color[2] = 1.0f; glutPostRedisplay(); break; // brush setting case 5: if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; } else { config.type = brush_type::dot; } break; case 6: config.type = brush_type::line; if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; } else { config.type = brush_type::line; } break; case 7: if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; } else { config.type = brush_type::tri; } break; case 8: if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; } else { config.type = brush_type::quad; } break; case 9: if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; } else { config.type = brush_type::poly; } break; // cursor case 10: // small config.cursor_size = 1; break; case 11: // medium config.cursor_size = 2; break; case 12: // large config.cursor_size = 3; break; default: break; } } void createMenu() { int color_menu = glutCreateMenu(menu); glutAddMenuEntry("Red", 2); glutAddMenuEntry("Green", 3); glutAddMenuEntry("Blue", 4); int brush_menu = glutCreateMenu(menu); glutAddMenuEntry("Dot", 5); glutAddMenuEntry("Line", 6); glutAddMenuEntry("Tri", 7); glutAddMenuEntry("Quad", 8); glutAddMenuEntry("Poly", 9); int cursor_menu = glutCreateMenu(menu); glutAddMenuEntry("Small", 10); glutAddMenuEntry("Medium", 11); glutAddMenuEntry("Large", 12); glutCreateMenu(menu); glutAddMenuEntry("Clear", 0); glutAddSubMenu("Colors", color_menu); glutAddSubMenu("Brush", brush_menu); glutAddSubMenu("Cursor", cursor_menu); glutAddMenuEntry("Exit", 1); glutAttachMenu(GLUT_RIGHT_BUTTON); }
28.586538
97
0.510932
KHN190
ad67eaf99e802df0517537360e2027db6f1a45f6
2,296
cpp
C++
11_dynamic_1/6_coin_change.cpp
ShyamNandanKumar/coding-ninja2
a43a21575342261e573f71f7d8eff0572f075a17
[ "MIT" ]
11
2021-01-02T10:07:17.000Z
2022-03-16T00:18:06.000Z
11_dynamic_1/6_coin_change.cpp
meyash/cp_master
316bf47db2a5b40891edd73cff834517993c3d2a
[ "MIT" ]
null
null
null
11_dynamic_1/6_coin_change.cpp
meyash/cp_master
316bf47db2a5b40891edd73cff834517993c3d2a
[ "MIT" ]
5
2021-05-19T11:17:18.000Z
2021-09-16T06:23:31.000Z
/* You are given an infinite supply of coins of each of denominations D = {D0, D1, D2, D3, ...... Dn-1}. You need to figure out the total number of ways W, in which you can make change for Value V using coins of denominations D. Note : Return 0, if change isn't possible. Input Format Line 1 : Integer n i.e. total number of denominations Line 2 : N integers i.e. n denomination values Line 3 : Value V Output Format Line 1 : Number of ways i.e. W Constraints : 1<=n<=10 1<=V<=1000 Sample Input 1 : 3 1 2 3 4 Sample Output 4 Sample Output Explanation : Number of ways are - 4 total i.e. (1,1,1,1), (1,1,2), (1,3) and (2,2). */ #include<bits/stdc++.h> using namespace std; typedef long long ll; int find_ans(int den[],int start,int size,int curr_val,int goal,int **storage){ // base cases // current val greater than goal if(curr_val>goal){ return 0; } // goal value reached if(curr_val==goal){ return 1; } // checked all denominations if(start==size){ return 0; } if(storage[size-start][curr_val]>0){ return storage[size-start][curr_val]; } // starting element of den included int leftpossible=find_ans(den,start,size,curr_val+den[start],goal,storage); // starting element of den not included int rightpossible=find_ans(den,start+1,size,curr_val,goal,storage); storage[size-start][curr_val]=leftpossible+rightpossible; return leftpossible+rightpossible; } int countWaysToMakeChange(int denominations[], int numDenominations, int value){ sort(denominations,denominations+numDenominations); int **storage=new int*[numDenominations+1]; for(int i=0;i<numDenominations+1;i++){ storage[i]=new int[value+1]; } // set all storage elements to -1 for(int i=0;i<numDenominations+1;i++){ for(int j=0;j<value+1;j++){ storage[i][j]=-1; } } int ans=find_ans(denominations,0,numDenominations,0,value,storage); for(int i=0;i<numDenominations+1;i++){ delete storage[i]; } delete storage; return ans; } int main(){ int numDenominations; cin >> numDenominations; int* denominations = new int[numDenominations]; for(int i = 0; i < numDenominations; i++){ cin >> denominations[i]; } int value; cin >> value; cout << countWaysToMakeChange(denominations, numDenominations, value); return 0; }
26.697674
225
0.692944
ShyamNandanKumar
ad6bd0b4906714fa0faaf06944d97d1736b73e1c
15,455
cpp
C++
openstudiocore/src/model/test/AirTerminalSingleDuctVAVNoReheat_GTest.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
1
2016-12-29T08:45:03.000Z
2016-12-29T08:45:03.000Z
openstudiocore/src/model/test/AirTerminalSingleDuctVAVNoReheat_GTest.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
openstudiocore/src/model/test/AirTerminalSingleDuctVAVNoReheat_GTest.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library 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 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include "ModelFixture.hpp" #include "../AirTerminalSingleDuctVAVNoReheat.hpp" #include "../AirTerminalSingleDuctVAVNoReheat_Impl.hpp" #include "../AirLoopHVAC.hpp" #include "../PlantLoop.hpp" #include "../Node.hpp" #include "../Node_Impl.hpp" #include "../Schedule.hpp" #include "../ScheduleCompact.hpp" #include "../AirLoopHVACZoneSplitter.hpp" #include "../ThermalZone.hpp" #include "../DesignSpecificationOutdoorAir.hpp" using namespace openstudio::model; TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_DefaultConstructor) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ASSERT_EXIT ( { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); exit(0); } , ::testing::ExitedWithCode(0), "" ); } TEST_F(ModelFixture,AirTerminalSingleDuctVAVNoReheat_addToNode) { Model m; Schedule s = m.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject(m,s); AirLoopHVAC airLoop(m); Node supplyOutletNode = airLoop.supplyOutletNode(); EXPECT_FALSE(testObject.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)2, airLoop.supplyComponents().size() ); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); EXPECT_TRUE(testObject.addToNode(inletNode)); EXPECT_EQ((unsigned)7, airLoop.demandComponents().size()); PlantLoop plantLoop(m); supplyOutletNode = plantLoop.supplyOutletNode(); EXPECT_FALSE(testObject.addToNode(supplyOutletNode)); EXPECT_EQ( (unsigned)5, plantLoop.supplyComponents().size() ); Node demandOutletNode = plantLoop.demandOutletNode(); EXPECT_FALSE(testObject.addToNode(demandOutletNode)); EXPECT_EQ( (unsigned)5, plantLoop.demandComponents().size() ); AirTerminalSingleDuctVAVNoReheat testObjectClone = testObject.clone(m).cast<AirTerminalSingleDuctVAVNoReheat>(); inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); EXPECT_FALSE(testObjectClone.addToNode(inletNode)); EXPECT_TRUE(airLoop.addBranchForHVACComponent(testObjectClone)); EXPECT_EQ( (unsigned)10, airLoop.demandComponents().size() ); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_AddToNodeWithThermalZone) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirLoopHVAC airLoop(model); ThermalZone thermalZone(model); airLoop.addBranchForZone(thermalZone); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); EXPECT_TRUE(testObject.addToNode(inletNode)); EXPECT_EQ((unsigned)9, airLoop.demandComponents().size()); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_AddAirTerminalToPlantLoopAddDemandBranchForComponent) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirLoopHVAC airLoop(model); ThermalZone thermalZone(model); PlantLoop plantLoop(model); airLoop.addBranchForZone(thermalZone); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); testObject.addToNode(inletNode); EXPECT_FALSE(plantLoop.addDemandBranchForComponent(testObject)); EXPECT_EQ((unsigned)9, airLoop.demandComponents().size()); EXPECT_NE((unsigned)7, airLoop.demandComponents().size()); EXPECT_EQ((unsigned)5, plantLoop.demandComponents().size()); EXPECT_NE((unsigned)7, plantLoop.demandComponents().size()); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_AddObjectByAirLoopAddBranchForZoneWithThermalZone) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirLoopHVAC airLoop(model); ThermalZone thermalZone(model); EXPECT_TRUE(airLoop.addBranchForZone(thermalZone, testObject)); EXPECT_EQ((unsigned)9, airLoop.demandComponents().size()); EXPECT_NE((unsigned)7, airLoop.demandComponents().size()); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_AddObjectByAirLoopAddBranchForHVACComponent) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirLoopHVAC airLoop(model); EXPECT_TRUE(airLoop.addBranchForHVACComponent(testObject)); EXPECT_EQ((unsigned)7, airLoop.demandComponents().size()); EXPECT_NE((unsigned)9, airLoop.demandComponents().size()); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_AddObjectByAirLoopAddBranchForHVACComponentWithThermalZone) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirLoopHVAC airLoop(model); ThermalZone thermalZone(model); airLoop.addBranchForZone(thermalZone); EXPECT_TRUE(airLoop.addBranchForHVACComponent(testObject)); EXPECT_EQ((unsigned)10, airLoop.demandComponents().size()); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_AddToNodeTwoSameObjects) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirLoopHVAC airLoop(model); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); testObject.addToNode(inletNode); inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); EXPECT_FALSE(testObject.addToNode(inletNode)); EXPECT_TRUE(testObject.inletPort()); EXPECT_TRUE(testObject.outletPort()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_IsRemovable) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); EXPECT_TRUE(testObject.isRemovable()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_Remove) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirLoopHVAC airLoop(model); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); testObject.addToNode(inletNode); EXPECT_EQ((unsigned)7, airLoop.demandComponents().size()); testObject.remove(); EXPECT_EQ((unsigned)5, airLoop.demandComponents().size()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_RemoveObjectWithThermalZone) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirLoopHVAC airLoop(model); ThermalZone thermalZone(model); airLoop.addBranchForZone(thermalZone); Node inletNode = airLoop.zoneSplitter().lastOutletModelObject()->cast<Node>(); testObject.addToNode(inletNode); EXPECT_EQ((unsigned)9, airLoop.demandComponents().size()); testObject.remove(); EXPECT_EQ((unsigned)7, airLoop.demandComponents().size()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_CloneOneModelWithDefaultData) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirTerminalSingleDuctVAVNoReheat testObjectClone = testObject.clone(model).cast<AirTerminalSingleDuctVAVNoReheat>(); EXPECT_TRUE(testObjectClone.isMaximumAirFlowRateAutosized()); EXPECT_EQ("Constant", testObjectClone.zoneMinimumAirFlowInputMethod().get()); EXPECT_DOUBLE_EQ(0.3, testObjectClone.constantMinimumAirFlowFraction().get()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_CloneOneModelWithCustomData) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); Schedule minAirFlowSchedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); testObject.setMaximumAirFlowRate(999.0); testObject.setZoneMinimumAirFlowInputMethod("Scheduled"); testObject.setConstantMinimumAirFlowFraction(999.0); testObject.setFixedMinimumAirFlowRate(1.0); testObject.setMinimumAirFlowFractionSchedule(minAirFlowSchedule); AirTerminalSingleDuctVAVNoReheat testObjectClone = testObject.clone(model).cast<AirTerminalSingleDuctVAVNoReheat>(); EXPECT_DOUBLE_EQ(999.0, testObjectClone.maximumAirFlowRate().get()); EXPECT_EQ("Scheduled", testObjectClone.zoneMinimumAirFlowInputMethod().get()); EXPECT_DOUBLE_EQ(999.0, testObjectClone.constantMinimumAirFlowFraction().get()); EXPECT_DOUBLE_EQ(1.0, testObjectClone.fixedMinimumAirFlowRate().get()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_CloneTwoModelsWithDefaultData) { Model model; Schedule schedule = model.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(model,schedule); AirTerminalSingleDuctVAVNoReheat testObjectClone = testObject.clone(model).cast<AirTerminalSingleDuctVAVNoReheat>(); Model model2; AirTerminalSingleDuctVAVNoReheat testObjectClone2 = testObject.clone(model2).cast<AirTerminalSingleDuctVAVNoReheat>(); EXPECT_TRUE(testObjectClone2.isMaximumAirFlowRateAutosized()); EXPECT_EQ("Constant", testObjectClone2.zoneMinimumAirFlowInputMethod().get()); EXPECT_DOUBLE_EQ(0.3, testObjectClone2.constantMinimumAirFlowFraction().get()); EXPECT_NE(testObjectClone2, testObjectClone); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_MaximumAirFlowRate) { Model m; Schedule s = m.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(m,s); EXPECT_TRUE(testObject.isMaximumAirFlowRateAutosized()); testObject.setMaximumAirFlowRate(999.0); EXPECT_DOUBLE_EQ(999.0, testObject.maximumAirFlowRate().get()); testObject.setMaximumAirFlowRate(0.0); EXPECT_DOUBLE_EQ(0.0, testObject.maximumAirFlowRate().get()); EXPECT_FALSE(testObject.setMaximumAirFlowRate(-1.0)); testObject.resetMaximumAirFlowRate(); EXPECT_FALSE(testObject.isMaximumAirFlowRateAutosized()); testObject.autosizeMaximumAirFlowRate(); EXPECT_TRUE(testObject.isMaximumAirFlowRateAutosized()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_ZoneMinimumAirFlowInputMethod) { Model m; Schedule s = m.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(m,s); EXPECT_EQ("Constant", testObject.zoneMinimumAirFlowInputMethod().get()); EXPECT_TRUE(testObject.setZoneMinimumAirFlowInputMethod("FixedFlowRate")); EXPECT_EQ("FixedFlowRate", testObject.zoneMinimumAirFlowInputMethod().get()); EXPECT_TRUE(testObject.setZoneMinimumAirFlowInputMethod("Scheduled")); EXPECT_EQ("Scheduled", testObject.zoneMinimumAirFlowInputMethod().get()); EXPECT_FALSE(testObject.setZoneMinimumAirFlowInputMethod("Not Valid")); EXPECT_EQ("Scheduled", testObject.zoneMinimumAirFlowInputMethod().get()); testObject.resetZoneMinimumAirFlowInputMethod(); EXPECT_EQ("", testObject.zoneMinimumAirFlowInputMethod().get()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_ConstantMinimumAirFlowFraction) { Model m; Schedule s = m.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(m,s); EXPECT_DOUBLE_EQ(0.3, testObject.constantMinimumAirFlowFraction().get()); testObject.setConstantMinimumAirFlowFraction(999.0); EXPECT_DOUBLE_EQ(999.0, testObject.constantMinimumAirFlowFraction().get()); testObject.setConstantMinimumAirFlowFraction(0.0); EXPECT_DOUBLE_EQ(0.0, testObject.constantMinimumAirFlowFraction().get()); EXPECT_TRUE(testObject.setConstantMinimumAirFlowFraction(-1.0)); testObject.resetConstantMinimumAirFlowFraction(); EXPECT_TRUE(testObject.isConstantMinimumAirFlowFractionDefaulted()); EXPECT_DOUBLE_EQ(0.3, testObject.constantMinimumAirFlowFraction().get()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_FixedMinimumAirFlowRate) { Model m; Schedule s = m.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(m,s); EXPECT_TRUE(testObject.isFixedMinimumAirFlowRateDefaulted()); testObject.setFixedMinimumAirFlowRate(999.0); EXPECT_DOUBLE_EQ(999.0, testObject.fixedMinimumAirFlowRate().get()); testObject.setFixedMinimumAirFlowRate(0.0); EXPECT_DOUBLE_EQ(0.0, testObject.fixedMinimumAirFlowRate().get()); EXPECT_TRUE(testObject.setFixedMinimumAirFlowRate(-1.0)); testObject.resetFixedMinimumAirFlowRate(); EXPECT_TRUE(testObject.isFixedMinimumAirFlowRateDefaulted()); EXPECT_DOUBLE_EQ(0.0, testObject.fixedMinimumAirFlowRate().get()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_MinimumAirFlowFractionSchedule) { Model m; Schedule s = m.alwaysOnDiscreteSchedule(); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(m,s); ScheduleCompact alwaysOnSchedule(m); alwaysOnSchedule.setName("ALWAYS_ON"); alwaysOnSchedule.setString(3,"Through: 12/31"); alwaysOnSchedule.setString(4,"For: AllDays"); alwaysOnSchedule.setString(5,"Until: 24:00"); alwaysOnSchedule.setString(6,"1"); EXPECT_FALSE(testObject.minimumAirFlowFractionSchedule()); EXPECT_TRUE(testObject.setMinimumAirFlowFractionSchedule(alwaysOnSchedule)); EXPECT_TRUE(testObject.minimumAirFlowFractionSchedule()); EXPECT_EQ(alwaysOnSchedule, testObject.minimumAirFlowFractionSchedule().get()); } TEST_F(ModelFixture, AirTerminalSingleDuctVAVNoReheat_DesignSpecificationOutdoorAirObject) { Model m; Schedule s = m.alwaysOnDiscreteSchedule(); DesignSpecificationOutdoorAir oa = DesignSpecificationOutdoorAir(m); AirTerminalSingleDuctVAVNoReheat testObject = AirTerminalSingleDuctVAVNoReheat(m,s); }
36.536643
120
0.794371
jasondegraw