hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9108955b49f7f48dea454530454dc867462dd24c
2,495
cpp
C++
libvast/src/system/signal_monitor.cpp
vast-io/vast
6c9c787adc54079202dba85ea4a929004063f1ba
[ "BSD-3-Clause" ]
63
2016-04-22T01:50:03.000Z
2019-07-31T15:50:36.000Z
libvast/src/system/signal_monitor.cpp
vast-io/vast
6c9c787adc54079202dba85ea4a929004063f1ba
[ "BSD-3-Clause" ]
216
2017-01-24T16:25:43.000Z
2019-08-01T19:37:00.000Z
libvast/src/system/signal_monitor.cpp
vast-io/vast
6c9c787adc54079202dba85ea4a929004063f1ba
[ "BSD-3-Clause" ]
28
2016-05-19T13:09:19.000Z
2019-04-12T15:11:42.000Z
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2016 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/system/signal_monitor.hpp" #include "vast/fwd.hpp" #include "vast/atoms.hpp" #include "vast/logger.hpp" #include <caf/actor.hpp> #include <caf/send.hpp> #include <atomic> #include <csignal> #include <cstdlib> #include <cstring> #include <iostream> #include <thread> using namespace caf; namespace { // Keeps track of all signals by their value from 1 to 31. The flag at index 0 // is used to tell whether a signal has been raised or not. std::atomic<bool> signals[32]; extern "C" void signal_monitor_handler(int sig) { // Catch termination signals only once to allow forced termination by the OS // upon sending the signal a second time. if (sig == SIGINT || sig == SIGTERM) { std::cerr << "\rinitiating graceful shutdown... (repeat request to " "terminate immediately)\n"; std::signal(sig, SIG_DFL); } signals[0] = true; signals[sig] = true; } } // namespace namespace vast::system { std::atomic<bool> signal_monitor::stop; void signal_monitor::run(std::chrono::milliseconds monitoring_interval, actor receiver) { [[maybe_unused]] static constexpr auto class_name = "signal_monitor"; VAST_DEBUG("{} sends signals to {}", class_name, receiver); for (auto s : {SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGUSR1, SIGUSR2}) { VAST_DEBUG("{} registers signal handler for {}", class_name, strsignal(s)); std::signal(s, &signal_monitor_handler); } while (!stop) { std::this_thread::sleep_for(monitoring_interval); if (signals[0]) { // TODO: this handling of singals is fundamentally unsafe, because we // always have a race between the singal handler and this loop on // singals[0]. This needs to be re-implemented in a truly atomic // fashion, probably via CAS operaions and a single 32-bit integer. signals[0] = false; for (int i = 1; i < 32; ++i) { if (signals[i]) { VAST_DEBUG("{} caught signal {}", class_name, strsignal(i)); signals[i] = false; caf::anon_send<caf::message_priority::high>(receiver, atom::signal_v, i); } } } } } } // namespace vast::system
30.802469
79
0.625651
vast-io
910affbde23fb26cd3aaa8866651a6385ef9f13f
20,815
cpp
C++
src/mme-app/utils/mmeContextManagerUtils.cpp
aggarwalanubhav/Nucleus
107113cd9a1b68b1a28b35091ed17785ed32d319
[ "Apache-2.0" ]
null
null
null
src/mme-app/utils/mmeContextManagerUtils.cpp
aggarwalanubhav/Nucleus
107113cd9a1b68b1a28b35091ed17785ed32d319
[ "Apache-2.0" ]
null
null
null
src/mme-app/utils/mmeContextManagerUtils.cpp
aggarwalanubhav/Nucleus
107113cd9a1b68b1a28b35091ed17785ed32d319
[ "Apache-2.0" ]
1
2021-05-18T07:21:24.000Z
2021-05-18T07:21:24.000Z
/* * Copyright (c) 2019, Infosys Ltd. * * SPDX-License-Identifier: Apache-2.0 */ #include <cmath> #include <controlBlock.h> #include <contextManager/subsDataGroupManager.h> #include <err_codes.h> #include <log.h> #include <mmeStates/createBearerProcedureStates.h> #include <mmeStates/dedBearerActProcedureStates.h> #include <mmeStates/dedBearerDeactProcedureStates.h> #include <mmeStates/deleteBearerProcedureStates.h> #include <mmeStates/ueInitDetachStates.h> #include <mmeStates/networkInitDetachStates.h> #include <mmeStates/s1HandoverStates.h> #include <mmeStates/serviceRequestStates.h> #include <mmeStates/tauStates.h> #include <mmeStates/erabModIndicationStates.h> #include <utils/mmeContextManagerUtils.h> #include <utils/mmeCommonUtils.h> #include <utils/mmeTimerUtils.h> #include "mmeStatsPromClient.h" #define BEARER_ID_OFFSET 4 #define FIRST_SET_BIT(bits) log2(bits & -bits) + 1 #define CLEAR_BIT(bits,pos) bits &= ~(1 << pos) #define SET_BIT(bits,pos) bits |= (1 << pos) using namespace mme; MmeDetachProcedureCtxt* MmeContextManagerUtils::allocateDetachProcedureCtxt(SM::ControlBlock& cb_r, DetachType detachType) { log_msg(LOG_DEBUG, "allocateDetachProcedureCtxt: Entry"); MmeDetachProcedureCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeDetachProcedureCtxt(); if (prcdCtxt_p != NULL) { prcdCtxt_p->setCtxtType(ProcedureType::detach_c); prcdCtxt_p->setDetachType(detachType); if (detachType == ueInitDetach_c) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DETACH_PROC_UE_INIT); prcdCtxt_p->setNextState(DetachStart::Instance()); } else { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DETACH_PROC_NETWORK_INIT); prcdCtxt_p->setNextState(NiDetachStart::Instance()); } cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeSvcReqProcedureCtxt* MmeContextManagerUtils::allocateServiceRequestProcedureCtxt(SM::ControlBlock& cb_r, PagingTrigger pagingTrigger) { log_msg(LOG_DEBUG, "allocateServiceRequestProcedureCtxt: Entry"); MmeSvcReqProcedureCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeSvcReqProcedureCtxt(); if (prcdCtxt_p != NULL) { prcdCtxt_p->setCtxtType(ProcedureType::serviceRequest_c); prcdCtxt_p->setPagingTrigger(pagingTrigger); if (pagingTrigger == ddnInit_c) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_SERVICE_REQUEST_PROC_DDN_INIT); prcdCtxt_p->setNextState(PagingStart::Instance()); } else if(pagingTrigger == pgwInit_c) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_SERVICE_REQUEST_PROC_PGW_INIT); prcdCtxt_p->setNextState(PagingStart::Instance()); } else { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_SERVICE_REQUEST_PROC_UE_INIT); prcdCtxt_p->setNextState(ServiceRequestStart::Instance()); } cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeTauProcedureCtxt* MmeContextManagerUtils::allocateTauProcedureCtxt(SM::ControlBlock& cb_r) { log_msg(LOG_DEBUG, "allocateTauRequestProcedureCtxt: Entry"); MmeTauProcedureCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeTauProcedureCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_TAU_PROC); prcdCtxt_p->setCtxtType(ProcedureType::tau_c); prcdCtxt_p->setNextState(TauStart::Instance()); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeErabModIndProcedureCtxt* MmeContextManagerUtils::allocateErabModIndProcedureCtxt(SM::ControlBlock& cb_r) { log_msg(LOG_DEBUG, "allocateErabModIndRequestProcedureCtxt: Entry"); MmeErabModIndProcedureCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeErabModIndProcedureCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_ERAB_MOD_IND_PROC); prcdCtxt_p->setCtxtType(ProcedureType::erabModInd_c); prcdCtxt_p->setNextState(ErabModIndStart::Instance()); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } S1HandoverProcedureContext* MmeContextManagerUtils::allocateHoContext(SM::ControlBlock& cb_r) { log_msg(LOG_DEBUG, "allocateHoProcedureCtxt: Entry"); S1HandoverProcedureContext *prcdCtxt_p = SubsDataGroupManager::Instance()->getS1HandoverProcedureContext(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_S1_ENB_HANDOVER_PROC); prcdCtxt_p->setCtxtType(ProcedureType::s1Handover_c); prcdCtxt_p->setNextState(IntraS1HoStart::Instance()); prcdCtxt_p->setHoType(intraMmeS1Ho_c); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } SrvccProcedureContext* MmeContextManagerUtils::allocateSrvccContext(SM::ControlBlock& cb_r) { log_msg(LOG_DEBUG, "allocateSrvccContext: Entry"); SrvccProcedureContext *prcdCtxt_p = SubsDataGroupManager::Instance()->getSrvccProcedureContext(); if (prcdCtxt_p != NULL) { //mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_S1_ENB_HANDOVER_PROC); prcdCtxt_p->setCtxtType(ProcedureType::srvcc_c); //prcdCtxt_p->setNextState(IntraS1HoStart::Instance()); //prcdCtxt_p->setHoType(intraMmeS1Ho_c); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeSmCreateBearerProcCtxt* MmeContextManagerUtils::allocateCreateBearerRequestProcedureCtxt(SM::ControlBlock& cb_r, uint8_t bearerId) { log_msg(LOG_DEBUG, "allocateCreateBearerRequestProcedureCtxt: Entry"); MmeSmCreateBearerProcCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeSmCreateBearerProcCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_CREATE_BEARER_PROC); prcdCtxt_p->setCtxtType(ProcedureType::cbReq_c); prcdCtxt_p->setNextState(CreateBearerStart::Instance()); prcdCtxt_p->setBearerId(bearerId); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } MmeSmDeleteBearerProcCtxt* MmeContextManagerUtils::allocateDeleteBearerRequestProcedureCtxt(SM::ControlBlock& cb_r, uint8_t bearerId) { log_msg(LOG_DEBUG, "allocateDeleteBearerRequestProcedureCtxt: Entry"); MmeSmDeleteBearerProcCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getMmeSmDeleteBearerProcCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DELETE_BEARER_PROC); prcdCtxt_p->setCtxtType(ProcedureType::dbReq_c); prcdCtxt_p->setNextState(DeleteBearerStart::Instance()); prcdCtxt_p->setBearerId(bearerId); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } SmDedActProcCtxt* MmeContextManagerUtils::allocateDedBrActivationProcedureCtxt(SM::ControlBlock& cb_r, uint8_t bearerId) { log_msg(LOG_DEBUG, "allocateDedBrActivationProcedureCtxt: Entry"); SmDedActProcCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getSmDedActProcCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DED_BEARER_ACTIVATION_PROC); prcdCtxt_p->setCtxtType(ProcedureType::dedBrActivation_c); prcdCtxt_p->setNextState(DedActStart::Instance()); prcdCtxt_p->setBearerId(bearerId); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } SmDedDeActProcCtxt* MmeContextManagerUtils::allocateDedBrDeActivationProcedureCtxt(SM::ControlBlock& cb_r, uint8_t bearerId) { log_msg(LOG_DEBUG, "allocateDedBrDeActivationProcedureCtxt: Entry"); SmDedDeActProcCtxt *prcdCtxt_p = SubsDataGroupManager::Instance()->getSmDedDeActProcCtxt(); if (prcdCtxt_p != NULL) { mmeStats::Instance()->increment(mmeStatsCounter::MME_PROCEDURES_DED_BEARER_DEACTIVATION_PROC); prcdCtxt_p->setCtxtType(ProcedureType::dedBrDeActivation_c); prcdCtxt_p->setNextState(DedDeactStart::Instance()); prcdCtxt_p->setBearerId(bearerId); cb_r.addTempDataBlock(prcdCtxt_p); } return prcdCtxt_p; } bool MmeContextManagerUtils::deleteProcedureCtxt(MmeProcedureCtxt* procedure_p) { log_msg(LOG_DEBUG, "deleteProcedureCtxt: Entry"); if (procedure_p == NULL) { log_msg(LOG_INFO, "Procedure Context is NULL"); return false; } SubsDataGroupManager* subsDgMgr_p = SubsDataGroupManager::Instance(); log_msg(LOG_INFO, "Procedure Type is %d", procedure_p->getCtxtType()); bool rc = true; switch (procedure_p->getCtxtType()) { case attach_c: { MmeAttachProcedureCtxt* atchProc_p = static_cast<MmeAttachProcedureCtxt *>(procedure_p); subsDgMgr_p->deleteMmeAttachProcedureCtxt(atchProc_p); break; } case s1Release_c: { MmeS1RelProcedureCtxt* s1RelProc_p = static_cast<MmeS1RelProcedureCtxt *>(procedure_p); subsDgMgr_p->deleteMmeS1RelProcedureCtxt(s1RelProc_p); break; } case detach_c: { MmeDetachProcedureCtxt* detachProc_p = static_cast<MmeDetachProcedureCtxt *>(procedure_p); subsDgMgr_p->deleteMmeDetachProcedureCtxt(detachProc_p); break; } case serviceRequest_c: { MmeSvcReqProcedureCtxt* svcReqProc_p = static_cast<MmeSvcReqProcedureCtxt*>(procedure_p); subsDgMgr_p->deleteMmeSvcReqProcedureCtxt(svcReqProc_p); break; } case tau_c: { MmeTauProcedureCtxt* tauProc_p = static_cast<MmeTauProcedureCtxt*>(procedure_p); subsDgMgr_p->deleteMmeTauProcedureCtxt(tauProc_p); break; } case s1Handover_c: { S1HandoverProcedureContext* s1HoProc_p = static_cast<S1HandoverProcedureContext*>(procedure_p); subsDgMgr_p->deleteS1HandoverProcedureContext(s1HoProc_p); break; } case srvcc_c: { SrvccProcedureContext* srvcc_p = static_cast<SrvccProcedureContext*>(procedure_p); subsDgMgr_p->deleteSrvccProcedureContext(srvcc_p); break; } case erabModInd_c: { MmeErabModIndProcedureCtxt* erabModIndProc_p = static_cast<MmeErabModIndProcedureCtxt*>(procedure_p); subsDgMgr_p->deleteMmeErabModIndProcedureCtxt(erabModIndProc_p); break; } case cbReq_c: { MmeSmCreateBearerProcCtxt* cbReqProc_p = static_cast<MmeSmCreateBearerProcCtxt*>(procedure_p); subsDgMgr_p->deleteMmeSmCreateBearerProcCtxt(cbReqProc_p); break; } case dedBrActivation_c: { SmDedActProcCtxt* dedActProc_p = static_cast<SmDedActProcCtxt*>(procedure_p); subsDgMgr_p->deleteSmDedActProcCtxt(dedActProc_p); break; } case dbReq_c: { MmeSmDeleteBearerProcCtxt* dbReqProc_p = static_cast<MmeSmDeleteBearerProcCtxt*>(procedure_p); subsDgMgr_p->deleteMmeSmDeleteBearerProcCtxt(dbReqProc_p); break; } case dedBrDeActivation_c: { SmDedDeActProcCtxt* dedDeActProc_p = static_cast<SmDedDeActProcCtxt*>(procedure_p); subsDgMgr_p->deleteSmDedDeActProcCtxt(dedDeActProc_p); break; } default: { log_msg(LOG_INFO, "Unsupported procedure type %d", procedure_p->getCtxtType()); rc = false; } } return rc; } bool MmeContextManagerUtils::deallocateProcedureCtxt(SM::ControlBlock& cb_r, MmeProcedureCtxt* procedure_p) { if (procedure_p == NULL) { log_msg(LOG_DEBUG, "procedure_p is NULL "); return true; } if (procedure_p->getCtxtType() == defaultMmeProcedure_c) { log_msg(LOG_ERROR, "CB %d trying to delete default procedure context ", cb_r.getCBIndex()); return true; } bool rc = false; // Remove the procedure from the temp data block list // maintained by the control block cb_r.removeTempDataBlock(procedure_p); // Stop any timers running MmeTimerUtils::stopTimer(procedure_p->getStateGuardTimerCtxt()); // return the procedure context to mem-pool deleteProcedureCtxt(procedure_p); return rc; } bool MmeContextManagerUtils::deallocateAllProcedureCtxts(SM::ControlBlock& cb_r) { bool rc = false; MmeProcedureCtxt* procedure_p = static_cast<MmeProcedureCtxt*>(cb_r.getFirstTempDataBlock()); MmeProcedureCtxt* nextProcedure_p = NULL; while (procedure_p != NULL) { nextProcedure_p = static_cast<MmeProcedureCtxt*>(procedure_p->getNextTempDataBlock()); if (procedure_p->getCtxtType() != defaultMmeProcedure_c) { // stop state guard timer if any running deallocateProcedureCtxt(cb_r, procedure_p); } procedure_p = nextProcedure_p; } return rc; } MmeProcedureCtxt* MmeContextManagerUtils::findProcedureCtxt(SM::ControlBlock& cb_r, ProcedureType procType, uint8_t bearerId) { MmeProcedureCtxt* mmeProcCtxt_p = NULL; MmeProcedureCtxt* currentProcedure_p = static_cast<MmeProcedureCtxt*>(cb_r.getFirstTempDataBlock()); MmeProcedureCtxt* nextProcedure_p = NULL; while (currentProcedure_p != NULL) { nextProcedure_p = static_cast<MmeProcedureCtxt*>( currentProcedure_p->getNextTempDataBlock()); if (currentProcedure_p->getCtxtType() == procType) { mmeProcCtxt_p = currentProcedure_p; break; } currentProcedure_p = nextProcedure_p; } return mmeProcCtxt_p; } void MmeContextManagerUtils::deleteAllSessionContext(SM::ControlBlock& cb_r) { UEContext *ueCtxt_p = static_cast<UEContext*>(cb_r.getPermDataBlock()); if (ueCtxt_p == NULL) { log_msg(LOG_DEBUG, "Failed to retrieve UEContext from control block %u", cb_r.getCBIndex()); return; } auto &sessionCtxtContainer = ueCtxt_p->getSessionContextContainer(); if (sessionCtxtContainer.size() < 1) { log_msg(LOG_ERROR, "Session context list is empty for UE IDX %d", cb_r.getCBIndex()); return; } auto it = sessionCtxtContainer.begin(); SessionContext *session_p = NULL; while (it != sessionCtxtContainer.end()) { session_p = *it; it++; deallocateSessionContext(cb_r, session_p, ueCtxt_p); } } void MmeContextManagerUtils::deleteUEContext(uint32_t cbIndex, bool deleteControlBlockFlag) { SM::ControlBlock* cb_p = SubsDataGroupManager::Instance()->findControlBlock(cbIndex); if (cb_p == NULL) { log_msg(LOG_DEBUG, "Failed to find control block for index %u", cbIndex); return; } deallocateAllProcedureCtxts(*cb_p); deleteAllSessionContext(*cb_p); UEContext* ueCtxt_p = static_cast<UEContext *>(cb_p->getPermDataBlock()); if (ueCtxt_p == NULL) { log_msg(LOG_DEBUG, "Unable to retrieve UEContext from control block %u", cbIndex); } else { MmContext* mmContext_p = ueCtxt_p->getMmContext(); if (mmContext_p != NULL) { SubsDataGroupManager::Instance()->deleteMmContext(mmContext_p); ueCtxt_p->setMmContext(NULL); } // Remove IMSI -> CBIndex key mapping const DigitRegister15& ue_imsi = ueCtxt_p->getImsi(); SubsDataGroupManager::Instance()->deleteimsikey(ue_imsi); // Remove mTMSI -> CBIndex mapping SubsDataGroupManager::Instance()->deletemTmsikey(ueCtxt_p->getMTmsi()); SubsDataGroupManager::Instance()->deleteUEContext(ueCtxt_p); cb_p->setPermDataBlock(NULL); } if (deleteControlBlockFlag) SubsDataGroupManager::Instance()->deAllocateCB(cb_p->getCBIndex()); } SessionContext* MmeContextManagerUtils::allocateSessionContext(SM::ControlBlock &cb_r, UEContext &ueCtxt) { SessionContext *sessionCtxt_p = SubsDataGroupManager::Instance()->getSessionContext(); if (sessionCtxt_p != NULL) { BearerContext *bearerCtxt_p = MmeContextManagerUtils::allocateBearerContext(cb_r, ueCtxt, *sessionCtxt_p); if (bearerCtxt_p == NULL) { log_msg(LOG_DEBUG, "Failed to allocate bearer context"); SubsDataGroupManager::Instance()->deleteSessionContext( sessionCtxt_p); return NULL; } sessionCtxt_p->setLinkedBearerId(bearerCtxt_p->getBearerId()); ueCtxt.addSessionContext(sessionCtxt_p); } return sessionCtxt_p; } BearerContext* MmeContextManagerUtils::allocateBearerContext(SM::ControlBlock &cb_r, UEContext &uectxt, SessionContext &sessionCtxt) { BearerContext *bearerCtxt_p = NULL; uint16_t bitmap = uectxt.getBearerIdBitMap(); // 0x7FF : All bearers ids are allocated. uint8_t id = (bitmap == 0x7FF) ? 0 : (FIRST_SET_BIT(~bitmap)); if (id > 0 && id <= 11) { bearerCtxt_p = SubsDataGroupManager::Instance()->getBearerContext(); if (bearerCtxt_p != NULL) { bearerCtxt_p->setBearerId(id + BEARER_ID_OFFSET); // Bearer id start 5 id--; SET_BIT(bitmap, id); uectxt.setBearerIdBitMap(bitmap); sessionCtxt.addBearerContext(bearerCtxt_p); } } mmeStats::Instance()->increment( mmeStatsCounter::MME_NUM_BEARERS); return bearerCtxt_p; } void MmeContextManagerUtils::deallocateSessionContext(SM::ControlBlock &cb_r, SessionContext *sessionCtxt_p, UEContext* ueContext_p) { if (sessionCtxt_p != NULL) { if (ueContext_p != NULL) ueContext_p ->removeSessionContext(sessionCtxt_p); auto &bearerCtxtContainer = sessionCtxt_p->getBearerContextContainer(); if (bearerCtxtContainer.size() < 1) { log_msg(LOG_ERROR, "Bearer context list is empty for UE IDX %d", cb_r.getCBIndex()); return; } auto it = bearerCtxtContainer.begin(); BearerContext *bearer_p = NULL; while (it != bearerCtxtContainer.end()) { bearer_p = *it; it++; deallocateBearerContext(cb_r, bearer_p, sessionCtxt_p, ueContext_p); } SubsDataGroupManager::Instance()->deleteSessionContext(sessionCtxt_p); } } void MmeContextManagerUtils::deallocateBearerContext(SM::ControlBlock &cb_r, BearerContext *bearerCtxt_p, SessionContext *sessionCtxt_p, UEContext *ueCtxt_p) { if (bearerCtxt_p != NULL) { // Remove from bearer context container if (sessionCtxt_p != NULL) sessionCtxt_p->removeBearerContext(bearerCtxt_p); // clear the id in the bitmap if (ueCtxt_p != NULL) { uint16_t bitmap = ueCtxt_p->getBearerIdBitMap(); uint8_t bearerId = bearerCtxt_p->getBearerId(); if (bearerId >= 5 && bearerId <= 15) { uint8_t id = bearerId - BEARER_ID_OFFSET - 1; CLEAR_BIT(bitmap, id); ueCtxt_p->setBearerIdBitMap(bitmap); } } SubsDataGroupManager::Instance()->deleteBearerContext(bearerCtxt_p); mmeStats::Instance()->decrement( mmeStatsCounter::MME_NUM_BEARERS); } } BearerContext* MmeContextManagerUtils::findBearerContext(uint8_t bearerId, UEContext *ueCtxt_p, SessionContext *sessionCtxt_p) { BearerContext *bearerCtxt_p = NULL; if (sessionCtxt_p != NULL) { bearerCtxt_p = sessionCtxt_p->findBearerContextByBearerId(bearerId); } else { auto &sessionCtxtContainer = ueCtxt_p->getSessionContextContainer(); for (auto sessEntry : sessionCtxtContainer) { bearerCtxt_p = sessEntry->findBearerContextByBearerId(bearerId); if (bearerCtxt_p != NULL) break; } } return bearerCtxt_p; } SessionContext* MmeContextManagerUtils::findSessionCtxtForEpsBrId(uint8_t bearerId, UEContext *ueCtxt_p) { SessionContext *sessCtxt_p = NULL; BearerContext *bearerCtxt_p = NULL; auto &sessionCtxtContainer = ueCtxt_p->getSessionContextContainer(); for (auto sessEntry : sessionCtxtContainer) { bearerCtxt_p = sessEntry->findBearerContextByBearerId(bearerId); if (bearerCtxt_p != NULL) { sessCtxt_p = sessEntry; break; } } return sessCtxt_p; }
30.386861
125
0.684122
aggarwalanubhav
51066701eaff539f3f66d545f3214ad8a0d6ddef
6,239
cpp
C++
quic/api/QuicBatchWriter.cpp
neko-suki/mvfst
275edda5be49742221dfb0072e93786eb79cdc43
[ "MIT" ]
1
2020-01-29T06:41:43.000Z
2020-01-29T06:41:43.000Z
quic/api/QuicBatchWriter.cpp
neko-suki/mvfst
275edda5be49742221dfb0072e93786eb79cdc43
[ "MIT" ]
null
null
null
quic/api/QuicBatchWriter.cpp
neko-suki/mvfst
275edda5be49742221dfb0072e93786eb79cdc43
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/api/QuicBatchWriter.h> namespace quic { // BatchWriter bool BatchWriter::needsFlush(size_t /*unused*/) { return false; } // SinglePacketBatchWriter void SinglePacketBatchWriter::reset() { buf_.reset(); } bool SinglePacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& buf, size_t /*unused*/) { buf_ = std::move(buf); // needs to be flushed return true; } ssize_t SinglePacketBatchWriter::write( folly::AsyncUDPSocket& sock, const folly::SocketAddress& address) { return sock.write(address, buf_); } // GSOPacketBatchWriter GSOPacketBatchWriter::GSOPacketBatchWriter(size_t maxBufs) : maxBufs_(maxBufs) {} void GSOPacketBatchWriter::reset() { buf_.reset(nullptr); currBufs_ = 0; prevSize_ = 0; } bool GSOPacketBatchWriter::needsFlush(size_t size) { // if we get a buffer with a size that is greater // than the prev one we need to flush return (prevSize_ && (size > prevSize_)); } bool GSOPacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& buf, size_t size) { // first buffer if (!buf_) { DCHECK_EQ(currBufs_, 0); buf_ = std::move(buf); prevSize_ = size; currBufs_ = 1; return false; // continue } // now we've got an additional buffer // append it to the chain buf_->prependChain(std::move(buf)); currBufs_++; // see if we've added a different size if (size != prevSize_) { CHECK_LT(size, prevSize_); return true; } // reached max buffers if (FOLLY_UNLIKELY(currBufs_ == maxBufs_)) { return true; } // does not need to be flushed yet return false; } ssize_t GSOPacketBatchWriter::write( folly::AsyncUDPSocket& sock, const folly::SocketAddress& address) { return (currBufs_ > 1) ? sock.writeGSO(address, buf_, static_cast<int>(prevSize_)) : sock.write(address, buf_); } // SendmmsgPacketBatchWriter SendmmsgPacketBatchWriter::SendmmsgPacketBatchWriter(size_t maxBufs) : maxBufs_(maxBufs) { bufs_.reserve(maxBufs); } bool SendmmsgPacketBatchWriter::empty() const { return !currSize_; } size_t SendmmsgPacketBatchWriter::size() const { return currSize_; } void SendmmsgPacketBatchWriter::reset() { bufs_.clear(); currSize_ = 0; } bool SendmmsgPacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& buf, size_t size) { CHECK_LT(bufs_.size(), maxBufs_); bufs_.emplace_back(std::move(buf)); currSize_ += size; // reached max buffers if (FOLLY_UNLIKELY(bufs_.size() == maxBufs_)) { return true; } // does not need to be flushed yet return false; } ssize_t SendmmsgPacketBatchWriter::write( folly::AsyncUDPSocket& sock, const folly::SocketAddress& address) { CHECK_GT(bufs_.size(), 0); if (bufs_.size() == 1) { return sock.write(address, bufs_[0]); } int ret = sock.writem(address, bufs_.data(), bufs_.size()); if (ret <= 0) { return ret; } if (static_cast<size_t>(ret) == bufs_.size()) { return currSize_; } // this is a partial write - we just need to // return a different number than currSize_ return 0; } // SendmmsgGSOPacketBatchWriter SendmmsgGSOPacketBatchWriter::SendmmsgGSOPacketBatchWriter(size_t maxBufs) : maxBufs_(maxBufs) { bufs_.reserve(maxBufs); } bool SendmmsgGSOPacketBatchWriter::empty() const { return !currSize_; } size_t SendmmsgGSOPacketBatchWriter::size() const { return currSize_; } void SendmmsgGSOPacketBatchWriter::reset() { bufs_.clear(); gso_.clear(); currBufs_ = 0; currSize_ = 0; prevSize_ = 0; } bool SendmmsgGSOPacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& buf, size_t size) { currSize_ += size; // see if we need to start a new chain if (size > prevSize_) { bufs_.emplace_back(std::move(buf)); // set the gso_ value to 0 for now // this will change if we append to this chain gso_.emplace_back(0); prevSize_ = size; currBufs_++; // reached max buffers if (FOLLY_UNLIKELY(currBufs_ == maxBufs_)) { return true; } return false; } gso_.back() = prevSize_; bufs_.back()->prependChain(std::move(buf)); currBufs_++; // reached max buffers if (FOLLY_UNLIKELY(currBufs_ == maxBufs_)) { return true; } if (size < prevSize_) { // reset the prevSize_ so in the next loop // we will start a new chain prevSize_ = 0; } return false; } ssize_t SendmmsgGSOPacketBatchWriter::write( folly::AsyncUDPSocket& sock, const folly::SocketAddress& address) { CHECK_GT(bufs_.size(), 0); if (bufs_.size() == 1) { return (currBufs_ > 1) ? sock.writeGSO(address, bufs_[0], gso_[0]) : sock.write(address, bufs_[0]); } int ret = sock.writemGSO(address, bufs_.data(), bufs_.size(), gso_.data()); if (ret <= 0) { return ret; } if (static_cast<size_t>(ret) == bufs_.size()) { return currSize_; } // this is a partial write - we just need to // return a different number than currSize_ return 0; } // BatchWriterFactory std::unique_ptr<BatchWriter> BatchWriterFactory::makeBatchWriter( folly::AsyncUDPSocket& sock, const quic::QuicBatchingMode& batchingMode, uint32_t batchSize) { switch (batchingMode) { case quic::QuicBatchingMode::BATCHING_MODE_NONE: return std::make_unique<SinglePacketBatchWriter>(); case quic::QuicBatchingMode::BATCHING_MODE_GSO: { if (sock.getGSO() >= 0) { return std::make_unique<GSOPacketBatchWriter>(batchSize); } return std::make_unique<SinglePacketBatchWriter>(); } case quic::QuicBatchingMode::BATCHING_MODE_SENDMMSG: return std::make_unique<SendmmsgPacketBatchWriter>(batchSize); case quic::QuicBatchingMode::BATCHING_MODE_SENDMMSG_GSO: { if (sock.getGSO() >= 0) { return std::make_unique<SendmmsgGSOPacketBatchWriter>(batchSize); } return std::make_unique<SendmmsgPacketBatchWriter>(batchSize); } // no default so we can catch missing case at compile time } folly::assume_unreachable(); } } // namespace quic
23.279851
77
0.677032
neko-suki
51067fb7034721216304f1ce1b0206557d544038
38,851
cpp
C++
src/etl/ETLSource.cpp
crypticrabbit/clio
ffc8779a14f22e25830e801487e898cec6c2f5c2
[ "ISC" ]
null
null
null
src/etl/ETLSource.cpp
crypticrabbit/clio
ffc8779a14f22e25830e801487e898cec6c2f5c2
[ "ISC" ]
null
null
null
src/etl/ETLSource.cpp
crypticrabbit/clio
ffc8779a14f22e25830e801487e898cec6c2f5c2
[ "ISC" ]
null
null
null
#include <ripple/beast/net/IPEndpoint.h> #include <ripple/protocol/STLedgerEntry.h> #include <boost/asio/strand.hpp> #include <boost/beast/http.hpp> #include <boost/beast/ssl.hpp> #include <boost/json.hpp> #include <boost/json/src.hpp> #include <boost/log/trivial.hpp> #include <backend/DBHelpers.h> #include <etl/ETLSource.h> #include <etl/ReportingETL.h> #include <thread> // Create ETL source without grpc endpoint // Fetch ledger and load initial ledger will fail for this source // Primarly used in read-only mode, to monitor when ledgers are validated template <class Derived> ETLSourceImpl<Derived>::ETLSourceImpl( boost::json::object const& config, boost::asio::io_context& ioContext, std::shared_ptr<BackendInterface> backend, std::shared_ptr<SubscriptionManager> subscriptions, std::shared_ptr<NetworkValidatedLedgers> networkValidatedLedgers, ETLLoadBalancer& balancer) : resolver_(boost::asio::make_strand(ioContext)) , networkValidatedLedgers_(networkValidatedLedgers) , backend_(backend) , subscriptions_(subscriptions) , balancer_(balancer) , ioc_(ioContext) , timer_(ioContext) { if (config.contains("ip")) { auto ipJs = config.at("ip").as_string(); ip_ = {ipJs.c_str(), ipJs.size()}; } if (config.contains("ws_port")) { auto portjs = config.at("ws_port").as_string(); wsPort_ = {portjs.c_str(), portjs.size()}; } if (config.contains("grpc_port")) { auto portjs = config.at("grpc_port").as_string(); grpcPort_ = {portjs.c_str(), portjs.size()}; try { boost::asio::ip::tcp::endpoint endpoint{ boost::asio::ip::make_address(ip_), std::stoi(grpcPort_)}; std::stringstream ss; ss << endpoint; stub_ = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub( grpc::CreateChannel( ss.str(), grpc::InsecureChannelCredentials())); BOOST_LOG_TRIVIAL(debug) << "Made stub for remote = " << toString(); } catch (std::exception const& e) { BOOST_LOG_TRIVIAL(debug) << "Exception while creating stub = " << e.what() << " . Remote = " << toString(); } } } template <class Derived> void ETLSourceImpl<Derived>::reconnect(boost::beast::error_code ec) { connected_ = false; // These are somewhat normal errors. operation_aborted occurs on shutdown, // when the timer is cancelled. connection_refused will occur repeatedly std::string err = ec.message(); // if we cannot connect to the transaction processing process if (ec.category() == boost::asio::error::get_ssl_category()) { err = std::string(" (") + boost::lexical_cast<std::string>(ERR_GET_LIB(ec.value())) + "," + boost::lexical_cast<std::string>(ERR_GET_REASON(ec.value())) + ") "; // ERR_PACK /* crypto/err/err.h */ char buf[128]; ::ERR_error_string_n(ec.value(), buf, sizeof(buf)); err += buf; std::cout << err << std::endl; } if (ec != boost::asio::error::operation_aborted && ec != boost::asio::error::connection_refused) { BOOST_LOG_TRIVIAL(error) << __func__ << " : " << "error code = " << ec << " - " << toString(); } else { BOOST_LOG_TRIVIAL(warning) << __func__ << " : " << "error code = " << ec << " - " << toString(); } // exponentially increasing timeouts, with a max of 30 seconds size_t waitTime = std::min(pow(2, numFailures_), 30.0); numFailures_++; timer_.expires_after(boost::asio::chrono::seconds(waitTime)); timer_.async_wait([this](auto ec) { bool startAgain = (ec != boost::asio::error::operation_aborted); BOOST_LOG_TRIVIAL(trace) << __func__ << " async_wait : ec = " << ec; derived().close(startAgain); }); } void PlainETLSource::close(bool startAgain) { timer_.cancel(); ioc_.post([this, startAgain]() { if (closing_) return; if (derived().ws().is_open()) { // onStop() also calls close(). If the async_close is called twice, // an assertion fails. Using closing_ makes sure async_close is only // called once closing_ = true; derived().ws().async_close( boost::beast::websocket::close_code::normal, [this, startAgain](auto ec) { if (ec) { BOOST_LOG_TRIVIAL(error) << __func__ << " async_close : " << "error code = " << ec << " - " << toString(); } closing_ = false; if (startAgain) run(); }); } else if (startAgain) { run(); } }); } void SslETLSource::close(bool startAgain) { timer_.cancel(); ioc_.post([this, startAgain]() { if (closing_) return; if (derived().ws().is_open()) { // onStop() also calls close(). If the async_close is called twice, // an assertion fails. Using closing_ makes sure async_close is only // called once closing_ = true; derived().ws().async_close( boost::beast::websocket::close_code::normal, [this, startAgain](auto ec) { if (ec) { BOOST_LOG_TRIVIAL(error) << __func__ << " async_close : " << "error code = " << ec << " - " << toString(); } closing_ = false; if (startAgain) { ws_ = std::make_unique<boost::beast::websocket::stream< boost::beast::ssl_stream< boost::beast::tcp_stream>>>( boost::asio::make_strand(ioc_), *sslCtx_); run(); } }); } else if (startAgain) { ws_ = std::make_unique<boost::beast::websocket::stream< boost::beast::ssl_stream<boost::beast::tcp_stream>>>( boost::asio::make_strand(ioc_), *sslCtx_); run(); } }); } template <class Derived> void ETLSourceImpl<Derived>::onResolve( boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type results) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // try again reconnect(ec); } else { boost::beast::get_lowest_layer(derived().ws()) .expires_after(std::chrono::seconds(30)); boost::beast::get_lowest_layer(derived().ws()) .async_connect(results, [this](auto ec, auto ep) { derived().onConnect(ec, ep); }); } } void PlainETLSource::onConnect( boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // start over reconnect(ec); } else { numFailures_ = 0; // Turn off timeout on the tcp stream, because websocket stream has it's // own timeout system boost::beast::get_lowest_layer(derived().ws()).expires_never(); // Set suggested timeout settings for the websocket derived().ws().set_option( boost::beast::websocket::stream_base::timeout::suggested( boost::beast::role_type::client)); // Set a decorator to change the User-Agent of the handshake derived().ws().set_option( boost::beast::websocket::stream_base::decorator( [](boost::beast::websocket::request_type& req) { req.set( boost::beast::http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " clio-client"); req.set("X-User", "coro-client"); })); // Update the host_ string. This will provide the value of the // Host HTTP header during the WebSocket handshake. // See https://tools.ietf.org/html/rfc7230#section-5.4 auto host = ip_ + ':' + std::to_string(endpoint.port()); // Perform the websocket handshake derived().ws().async_handshake( host, "/", [this](auto ec) { onHandshake(ec); }); } } void SslETLSource::onConnect( boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // start over reconnect(ec); } else { numFailures_ = 0; // Turn off timeout on the tcp stream, because websocket stream has it's // own timeout system boost::beast::get_lowest_layer(derived().ws()).expires_never(); // Set suggested timeout settings for the websocket derived().ws().set_option( boost::beast::websocket::stream_base::timeout::suggested( boost::beast::role_type::client)); // Set a decorator to change the User-Agent of the handshake derived().ws().set_option( boost::beast::websocket::stream_base::decorator( [](boost::beast::websocket::request_type& req) { req.set( boost::beast::http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " clio-client"); req.set("X-User", "coro-client"); })); // Update the host_ string. This will provide the value of the // Host HTTP header during the WebSocket handshake. // See https://tools.ietf.org/html/rfc7230#section-5.4 auto host = ip_ + ':' + std::to_string(endpoint.port()); // Perform the websocket handshake ws().next_layer().async_handshake( boost::asio::ssl::stream_base::client, [this, endpoint](auto ec) { onSslHandshake(ec, endpoint); }); } } void SslETLSource::onSslHandshake( boost::beast::error_code ec, boost::asio::ip::tcp::resolver::results_type::endpoint_type endpoint) { if (ec) { reconnect(ec); } else { // Perform the websocket handshake auto host = ip_ + ':' + std::to_string(endpoint.port()); // Perform the websocket handshake ws().async_handshake(host, "/", [this](auto ec) { onHandshake(ec); }); } } template <class Derived> void ETLSourceImpl<Derived>::onHandshake(boost::beast::error_code ec) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // start over reconnect(ec); } else { boost::json::object jv{ {"command", "subscribe"}, {"streams", {"ledger", "manifests", "validations", "transactions_proposed"}}}; std::string s = boost::json::serialize(jv); BOOST_LOG_TRIVIAL(trace) << "Sending subscribe stream message"; derived().ws().set_option( boost::beast::websocket::stream_base::decorator( [](boost::beast::websocket::request_type& req) { req.set( boost::beast::http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " clio-client"); req.set("X-User", "coro-client"); })); // Send the message derived().ws().async_write( boost::asio::buffer(s), [this](auto ec, size_t size) { onWrite(ec, size); }); } } template <class Derived> void ETLSourceImpl<Derived>::onWrite( boost::beast::error_code ec, size_t bytesWritten) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); if (ec) { // start over reconnect(ec); } else { derived().ws().async_read( readBuffer_, [this](auto ec, size_t size) { onRead(ec, size); }); } } template <class Derived> void ETLSourceImpl<Derived>::onRead(boost::beast::error_code ec, size_t size) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : ec = " << ec << " - " << toString(); // if error or error reading message, start over if (ec) { reconnect(ec); } else { handleMessage(); boost::beast::flat_buffer buffer; swap(readBuffer_, buffer); BOOST_LOG_TRIVIAL(trace) << __func__ << " : calling async_read - " << toString(); derived().ws().async_read( readBuffer_, [this](auto ec, size_t size) { onRead(ec, size); }); } } template <class Derived> bool ETLSourceImpl<Derived>::handleMessage() { BOOST_LOG_TRIVIAL(trace) << __func__ << " : " << toString(); setLastMsgTime(); connected_ = true; try { std::string msg{ static_cast<char const*>(readBuffer_.data().data()), readBuffer_.size()}; BOOST_LOG_TRIVIAL(trace) << __func__ << msg; boost::json::value raw = boost::json::parse(msg); BOOST_LOG_TRIVIAL(trace) << __func__ << " parsed"; boost::json::object response = raw.as_object(); uint32_t ledgerIndex = 0; if (response.contains("result")) { boost::json::object result = response["result"].as_object(); if (result.contains("ledger_index")) { ledgerIndex = result["ledger_index"].as_int64(); } if (result.contains("validated_ledgers")) { boost::json::string const& validatedLedgers = result["validated_ledgers"].as_string(); setValidatedRange( {validatedLedgers.c_str(), validatedLedgers.size()}); } BOOST_LOG_TRIVIAL(debug) << __func__ << " : " << "Received a message on ledger " << " subscription stream. Message : " << response << " - " << toString(); } else if ( response.contains("type") && response["type"] == "ledgerClosed") { BOOST_LOG_TRIVIAL(debug) << __func__ << " : " << "Received a message on ledger " << " subscription stream. Message : " << response << " - " << toString(); if (response.contains("ledger_index")) { ledgerIndex = response["ledger_index"].as_int64(); } if (response.contains("validated_ledgers")) { boost::json::string const& validatedLedgers = response["validated_ledgers"].as_string(); setValidatedRange( {validatedLedgers.c_str(), validatedLedgers.size()}); } } else { if (balancer_.shouldPropagateTxnStream(this)) { if (response.contains("transaction")) { subscriptions_->forwardProposedTransaction(response); } else if ( response.contains("type") && response["type"] == "validationReceived") { subscriptions_->forwardValidation(response); } else if ( response.contains("type") && response["type"] == "manifestReceived") { subscriptions_->forwardManifest(response); } } } if (ledgerIndex != 0) { BOOST_LOG_TRIVIAL(trace) << __func__ << " : " << "Pushing ledger sequence = " << ledgerIndex << " - " << toString(); networkValidatedLedgers_->push(ledgerIndex); } return true; } catch (std::exception const& e) { BOOST_LOG_TRIVIAL(error) << "Exception in handleMessage : " << e.what(); return false; } } class AsyncCallData { std::unique_ptr<org::xrpl::rpc::v1::GetLedgerDataResponse> cur_; std::unique_ptr<org::xrpl::rpc::v1::GetLedgerDataResponse> next_; org::xrpl::rpc::v1::GetLedgerDataRequest request_; std::unique_ptr<grpc::ClientContext> context_; grpc::Status status_; unsigned char nextPrefix_; std::string lastKey_; public: AsyncCallData( uint32_t seq, ripple::uint256 const& marker, std::optional<ripple::uint256> const& nextMarker) { request_.mutable_ledger()->set_sequence(seq); if (marker.isNonZero()) { request_.set_marker(marker.data(), marker.size()); } request_.set_user("ETL"); nextPrefix_ = 0x00; if (nextMarker) nextPrefix_ = nextMarker->data()[0]; unsigned char prefix = marker.data()[0]; BOOST_LOG_TRIVIAL(debug) << "Setting up AsyncCallData. marker = " << ripple::strHex(marker) << " . prefix = " << ripple::strHex(std::string(1, prefix)) << " . nextPrefix_ = " << ripple::strHex(std::string(1, nextPrefix_)); assert(nextPrefix_ > prefix || nextPrefix_ == 0x00); cur_ = std::make_unique<org::xrpl::rpc::v1::GetLedgerDataResponse>(); next_ = std::make_unique<org::xrpl::rpc::v1::GetLedgerDataResponse>(); context_ = std::make_unique<grpc::ClientContext>(); } enum class CallStatus { MORE, DONE, ERRORED }; CallStatus process( std::unique_ptr<org::xrpl::rpc::v1::XRPLedgerAPIService::Stub>& stub, grpc::CompletionQueue& cq, BackendInterface& backend, bool abort, bool cacheOnly = false) { BOOST_LOG_TRIVIAL(trace) << "Processing response. " << "Marker prefix = " << getMarkerPrefix(); if (abort) { BOOST_LOG_TRIVIAL(error) << "AsyncCallData aborted"; return CallStatus::ERRORED; } if (!status_.ok()) { BOOST_LOG_TRIVIAL(error) << "AsyncCallData status_ not ok: " << " code = " << status_.error_code() << " message = " << status_.error_message(); return CallStatus::ERRORED; } if (!next_->is_unlimited()) { BOOST_LOG_TRIVIAL(warning) << "AsyncCallData is_unlimited is false. Make sure " "secure_gateway is set correctly at the ETL source"; } std::swap(cur_, next_); bool more = true; // if no marker returned, we are done if (cur_->marker().size() == 0) more = false; // if returned marker is greater than our end, we are done unsigned char prefix = cur_->marker()[0]; if (nextPrefix_ != 0x00 && prefix >= nextPrefix_) more = false; // if we are not done, make the next async call if (more) { request_.set_marker(std::move(cur_->marker())); call(stub, cq); } BOOST_LOG_TRIVIAL(trace) << "Writing objects"; std::vector<Backend::LedgerObject> cacheUpdates; cacheUpdates.reserve(cur_->ledger_objects().objects_size()); for (int i = 0; i < cur_->ledger_objects().objects_size(); ++i) { auto& obj = *(cur_->mutable_ledger_objects()->mutable_objects(i)); if (!more && nextPrefix_ != 0x00) { if (((unsigned char)obj.key()[0]) >= nextPrefix_) continue; } cacheUpdates.push_back( {*ripple::uint256::fromVoidChecked(obj.key()), {obj.mutable_data()->begin(), obj.mutable_data()->end()}}); if (!cacheOnly) { if (lastKey_.size()) backend.writeSuccessor( std::move(lastKey_), request_.ledger().sequence(), std::string{obj.key()}); lastKey_ = obj.key(); backend.writeLedgerObject( std::move(*obj.mutable_key()), request_.ledger().sequence(), std::move(*obj.mutable_data())); } } backend.cache().update( cacheUpdates, request_.ledger().sequence(), cacheOnly); BOOST_LOG_TRIVIAL(trace) << "Wrote objects"; return more ? CallStatus::MORE : CallStatus::DONE; } void call( std::unique_ptr<org::xrpl::rpc::v1::XRPLedgerAPIService::Stub>& stub, grpc::CompletionQueue& cq) { context_ = std::make_unique<grpc::ClientContext>(); std::unique_ptr<grpc::ClientAsyncResponseReader< org::xrpl::rpc::v1::GetLedgerDataResponse>> rpc(stub->PrepareAsyncGetLedgerData(context_.get(), request_, &cq)); rpc->StartCall(); rpc->Finish(next_.get(), &status_, this); } std::string getMarkerPrefix() { if (next_->marker().size() == 0) return ""; else return ripple::strHex(std::string{next_->marker().data()[0]}); } std::string getLastKey() { return lastKey_; } }; template <class Derived> bool ETLSourceImpl<Derived>::loadInitialLedger( uint32_t sequence, uint32_t numMarkers, bool cacheOnly) { if (!stub_) return false; grpc::CompletionQueue cq; void* tag; bool ok = false; std::vector<AsyncCallData> calls; auto markers = getMarkers(numMarkers); for (size_t i = 0; i < markers.size(); ++i) { std::optional<ripple::uint256> nextMarker; if (i + 1 < markers.size()) nextMarker = markers[i + 1]; calls.emplace_back(sequence, markers[i], nextMarker); } BOOST_LOG_TRIVIAL(debug) << "Starting data download for ledger " << sequence << ". Using source = " << toString(); for (auto& c : calls) c.call(stub_, cq); size_t numFinished = 0; bool abort = false; size_t incr = 500000; size_t progress = incr; std::vector<std::string> edgeKeys; while (numFinished < calls.size() && cq.Next(&tag, &ok)) { assert(tag); auto ptr = static_cast<AsyncCallData*>(tag); if (!ok) { BOOST_LOG_TRIVIAL(error) << "loadInitialLedger - ok is false"; return false; // handle cancelled } else { BOOST_LOG_TRIVIAL(trace) << "Marker prefix = " << ptr->getMarkerPrefix(); auto result = ptr->process(stub_, cq, *backend_, abort, cacheOnly); if (result != AsyncCallData::CallStatus::MORE) { numFinished++; BOOST_LOG_TRIVIAL(debug) << "Finished a marker. " << "Current number of finished = " << numFinished; std::string lastKey = ptr->getLastKey(); if (lastKey.size()) edgeKeys.push_back(ptr->getLastKey()); } if (result == AsyncCallData::CallStatus::ERRORED) { abort = true; } if (backend_->cache().size() > progress) { BOOST_LOG_TRIVIAL(info) << "Downloaded " << backend_->cache().size() << " records from rippled"; progress += incr; } } } BOOST_LOG_TRIVIAL(info) << __func__ << " - finished loadInitialLedger. cache size = " << backend_->cache().size(); size_t numWrites = 0; if (!abort) { backend_->cache().setFull(); if (!cacheOnly) { auto start = std::chrono::system_clock::now(); for (auto& key : edgeKeys) { BOOST_LOG_TRIVIAL(debug) << __func__ << " writing edge key = " << ripple::strHex(key); auto succ = backend_->cache().getSuccessor( *ripple::uint256::fromVoidChecked(key), sequence); if (succ) backend_->writeSuccessor( std::move(key), sequence, uint256ToString(succ->key)); } ripple::uint256 prev = Backend::firstKey; while (auto cur = backend_->cache().getSuccessor(prev, sequence)) { assert(cur); if (prev == Backend::firstKey) { backend_->writeSuccessor( uint256ToString(prev), sequence, uint256ToString(cur->key)); } if (isBookDir(cur->key, cur->blob)) { auto base = getBookBase(cur->key); // make sure the base is not an actual object if (!backend_->cache().get(cur->key, sequence)) { auto succ = backend_->cache().getSuccessor(base, sequence); assert(succ); if (succ->key == cur->key) { BOOST_LOG_TRIVIAL(debug) << __func__ << " Writing book successor = " << ripple::strHex(base) << " - " << ripple::strHex(cur->key); backend_->writeSuccessor( uint256ToString(base), sequence, uint256ToString(cur->key)); } } ++numWrites; } prev = std::move(cur->key); if (numWrites % 100000 == 0 && numWrites != 0) BOOST_LOG_TRIVIAL(info) << __func__ << " Wrote " << numWrites << " book successors"; } backend_->writeSuccessor( uint256ToString(prev), sequence, uint256ToString(Backend::lastKey)); ++numWrites; auto end = std::chrono::system_clock::now(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(end - start) .count(); BOOST_LOG_TRIVIAL(info) << __func__ << " - Looping through cache and submitting all writes took " << seconds << " seconds. numWrites = " << std::to_string(numWrites); } } return !abort; } template <class Derived> std::pair<grpc::Status, org::xrpl::rpc::v1::GetLedgerResponse> ETLSourceImpl<Derived>::fetchLedger( uint32_t ledgerSequence, bool getObjects, bool getObjectNeighbors) { org::xrpl::rpc::v1::GetLedgerResponse response; if (!stub_) return {{grpc::StatusCode::INTERNAL, "No Stub"}, response}; // ledger header with txns and metadata org::xrpl::rpc::v1::GetLedgerRequest request; grpc::ClientContext context; request.mutable_ledger()->set_sequence(ledgerSequence); request.set_transactions(true); request.set_expand(true); request.set_get_objects(getObjects); request.set_get_object_neighbors(getObjectNeighbors); request.set_user("ETL"); grpc::Status status = stub_->GetLedger(&context, request, &response); if (status.ok() && !response.is_unlimited()) { BOOST_LOG_TRIVIAL(warning) << "ETLSourceImpl::fetchLedger - is_unlimited is " "false. Make sure secure_gateway is set " "correctly on the ETL source. source = " << toString() << " status = " << status.error_message(); } // BOOST_LOG_TRIVIAL(debug) // << __func__ << " Message size = " << response.ByteSizeLong(); return {status, std::move(response)}; } static std::unique_ptr<ETLSource> make_ETLSource( boost::json::object const& config, boost::asio::io_context& ioContext, std::optional<std::reference_wrapper<boost::asio::ssl::context>> sslCtx, std::shared_ptr<BackendInterface> backend, std::shared_ptr<SubscriptionManager> subscriptions, std::shared_ptr<NetworkValidatedLedgers> networkValidatedLedgers, ETLLoadBalancer& balancer) { std::unique_ptr<ETLSource> src = nullptr; if (sslCtx) { src = std::make_unique<SslETLSource>( config, ioContext, sslCtx, backend, subscriptions, networkValidatedLedgers, balancer); } else { src = std::make_unique<PlainETLSource>( config, ioContext, backend, subscriptions, networkValidatedLedgers, balancer); } src->run(); return src; } ETLLoadBalancer::ETLLoadBalancer( boost::json::object const& config, boost::asio::io_context& ioContext, std::optional<std::reference_wrapper<boost::asio::ssl::context>> sslCtx, std::shared_ptr<BackendInterface> backend, std::shared_ptr<SubscriptionManager> subscriptions, std::shared_ptr<NetworkValidatedLedgers> nwvl) { if (config.contains("num_markers") && config.at("num_markers").is_int64()) { downloadRanges_ = config.at("num_markers").as_int64(); downloadRanges_ = std::clamp(downloadRanges_, {1}, {256}); } else if (backend->fetchLedgerRange()) { downloadRanges_ = 4; } for (auto& entry : config.at("etl_sources").as_array()) { std::unique_ptr<ETLSource> source = make_ETLSource( entry.as_object(), ioContext, sslCtx, backend, subscriptions, nwvl, *this); sources_.push_back(std::move(source)); BOOST_LOG_TRIVIAL(info) << __func__ << " : added etl source - " << sources_.back()->toString(); } } void ETLLoadBalancer::loadInitialLedger(uint32_t sequence, bool cacheOnly) { execute( [this, &sequence, cacheOnly](auto& source) { bool res = source->loadInitialLedger(sequence, downloadRanges_, cacheOnly); if (!res) { BOOST_LOG_TRIVIAL(error) << "Failed to download initial ledger." << " Sequence = " << sequence << " source = " << source->toString(); } return res; }, sequence); } std::optional<org::xrpl::rpc::v1::GetLedgerResponse> ETLLoadBalancer::fetchLedger( uint32_t ledgerSequence, bool getObjects, bool getObjectNeighbors) { org::xrpl::rpc::v1::GetLedgerResponse response; bool success = execute( [&response, ledgerSequence, getObjects, getObjectNeighbors]( auto& source) { auto [status, data] = source->fetchLedger( ledgerSequence, getObjects, getObjectNeighbors); response = std::move(data); if (status.ok() && (response.validated() || true)) { BOOST_LOG_TRIVIAL(info) << "Successfully fetched ledger = " << ledgerSequence << " from source = " << source->toString(); return true; } else { BOOST_LOG_TRIVIAL(warning) << "Error getting ledger = " << ledgerSequence << " Reply : " << response.DebugString() << " error_code : " << status.error_code() << " error_msg : " << status.error_message() << " source = " << source->toString(); return false; } }, ledgerSequence); if (success) return response; else return {}; } std::optional<boost::json::object> ETLLoadBalancer::forwardToRippled( boost::json::object const& request, std::string const& clientIp, boost::asio::yield_context& yield) const { srand((unsigned)time(0)); auto sourceIdx = rand() % sources_.size(); auto numAttempts = 0; while (numAttempts < sources_.size()) { if (auto res = sources_[sourceIdx]->forwardToRippled(request, clientIp, yield)) return res; sourceIdx = (sourceIdx + 1) % sources_.size(); ++numAttempts; } return {}; } template <class Derived> std::optional<boost::json::object> ETLSourceImpl<Derived>::forwardToRippled( boost::json::object const& request, std::string const& clientIp, boost::asio::yield_context& yield) const { BOOST_LOG_TRIVIAL(debug) << "Attempting to forward request to tx. " << "request = " << boost::json::serialize(request); boost::json::object response; if (!connected_) { BOOST_LOG_TRIVIAL(error) << "Attempted to proxy but failed to connect to tx"; return {}; } namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace websocket = beast::websocket; // from namespace net = boost::asio; // from using tcp = boost::asio::ip::tcp; // from try { boost::beast::error_code ec; // These objects perform our I/O tcp::resolver resolver{ioc_}; BOOST_LOG_TRIVIAL(debug) << "Creating websocket"; auto ws = std::make_unique<websocket::stream<beast::tcp_stream>>(ioc_); // Look up the domain name auto const results = resolver.async_resolve(ip_, wsPort_, yield[ec]); if (ec) return {}; ws->next_layer().expires_after(std::chrono::seconds(3)); BOOST_LOG_TRIVIAL(debug) << "Connecting websocket"; // Make the connection on the IP address we get from a lookup ws->next_layer().async_connect(results, yield[ec]); if (ec) return {}; // Set a decorator to change the User-Agent of the handshake // and to tell rippled to charge the client IP for RPC // resources. See "secure_gateway" in // // https://github.com/ripple/rippled/blob/develop/cfg/rippled-example.cfg ws->set_option(websocket::stream_base::decorator( [&clientIp](websocket::request_type& req) { req.set( http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-coro"); req.set(http::field::forwarded, "for=" + clientIp); })); BOOST_LOG_TRIVIAL(debug) << "client ip: " << clientIp; BOOST_LOG_TRIVIAL(debug) << "Performing websocket handshake"; // Perform the websocket handshake ws->async_handshake(ip_, "/", yield[ec]); if (ec) return {}; BOOST_LOG_TRIVIAL(debug) << "Sending request"; // Send the message ws->async_write( net::buffer(boost::json::serialize(request)), yield[ec]); if (ec) return {}; beast::flat_buffer buffer; ws->async_read(buffer, yield[ec]); if (ec) return {}; auto begin = static_cast<char const*>(buffer.data().data()); auto end = begin + buffer.data().size(); auto parsed = boost::json::parse(std::string(begin, end)); if (!parsed.is_object()) { BOOST_LOG_TRIVIAL(error) << "Error parsing response: " << std::string{begin, end}; return {}; } BOOST_LOG_TRIVIAL(debug) << "Successfully forward request"; response = parsed.as_object(); response["forwarded"] = true; return response; } catch (std::exception const& e) { BOOST_LOG_TRIVIAL(error) << "Encountered exception : " << e.what(); return {}; } } template <class Func> bool ETLLoadBalancer::execute(Func f, uint32_t ledgerSequence) { srand((unsigned)time(0)); auto sourceIdx = rand() % sources_.size(); auto numAttempts = 0; while (true) { auto& source = sources_[sourceIdx]; BOOST_LOG_TRIVIAL(debug) << __func__ << " : " << "Attempting to execute func. ledger sequence = " << ledgerSequence << " - source = " << source->toString(); if (source->hasLedger(ledgerSequence) || true) { bool res = f(source); if (res) { BOOST_LOG_TRIVIAL(debug) << __func__ << " : " << "Successfully executed func at source = " << source->toString() << " - ledger sequence = " << ledgerSequence; break; } else { BOOST_LOG_TRIVIAL(warning) << __func__ << " : " << "Failed to execute func at source = " << source->toString() << " - ledger sequence = " << ledgerSequence; } } else { BOOST_LOG_TRIVIAL(warning) << __func__ << " : " << "Ledger not present at source = " << source->toString() << " - ledger sequence = " << ledgerSequence; } sourceIdx = (sourceIdx + 1) % sources_.size(); numAttempts++; if (numAttempts % sources_.size() == 0) { BOOST_LOG_TRIVIAL(error) << __func__ << " : " << "Error executing function " << " - ledger sequence = " << ledgerSequence << " - Tried all sources. Sleeping and trying again"; std::this_thread::sleep_for(std::chrono::seconds(2)); } } return true; }
32.896698
81
0.524337
crypticrabbit
510a8912d1fb1aadb57f069a27baad9adb0206fc
2,279
cpp
C++
Practica2/ProyectosOGREvc15x86/IG2App/AspasMolino.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
Practica2/ProyectosOGREvc15x86/IG2App/AspasMolino.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
Practica2/ProyectosOGREvc15x86/IG2App/AspasMolino.cpp
nicoFdez/PracticasIG2
cae65f0020e9231b5575cabcc86280a26ab3ba6e
[ "MIT" ]
null
null
null
#include "AspasMolino.h" #include <OgreSceneManager.h> #include <OgreEntity.h> #include <SDL_keycode.h> #include "Avion.h" AspasMolino::AspasMolino(Ogre::SceneNode* rootNode, int numAspas, int number) : EntidadIG(), numAspas(numAspas) { Ogre::Entity* ent; if(modoGiro == 0) mNode = rootNode->createChildSceneNode("aspas" + std::to_string(number)); else { nodoFicticio = rootNode->createChildSceneNode("molino_aspas_ficticio" + std::to_string(number)); nodoFicticio->setPosition(0, 0, 0); mNode = nodoFicticio->createChildSceneNode("aspas" + std::to_string(number)); } mSM = mNode->getCreator(); arrayAspas = new Aspa*[numAspas]; for (int i = 0; i < numAspas; ++i) { Ogre::SceneNode* aspaNode = mNode->createChildSceneNode("aspa_" + std::to_string(number) + std::to_string(i)); Ogre::SceneNode* tableroNode = aspaNode->createChildSceneNode("tablero_" + std::to_string(number) + std::to_string(i)); Ogre::SceneNode* cilindroNode = aspaNode->createChildSceneNode("adorno_" + std::to_string(number) + std::to_string(i)); arrayAspas[i] = new Aspa(aspaNode, tableroNode, cilindroNode); aspaNode->roll(Ogre::Degree(-360.0/numAspas * i)); cilindroNode->roll(Ogre::Degree(360.0 / numAspas * i)); } ejeNode = mNode->createChildSceneNode("ejeAspasMolino" + std::to_string(number)); ent = mSM->createEntity("Barrel.mesh"); ent->setMaterialName("Practica1/hierro"); ejeNode->attachObject(ent); ejeNode->pitch(Ogre::Degree(90.0)); ejeNode->scale(20, 10, 20); ejeNode->setPosition(0, 0, 0); } void AspasMolino::move() { mNode->roll(Ogre::Degree(1.0)); for (int i = 0; i < numAspas; ++i) { arrayAspas[i]->move(-1.0); } } void AspasMolino::moveAxis() { ejeNode->setPosition({ 0, 0, -25 }); } void AspasMolino::rotate() { if (modoGiro == 0) { //truco mNode->setPosition(0, mNode->getPosition().y, 0); mNode->yaw(Ogre::Degree(2), Ogre::Node::TS_PARENT); rotationY += 2; mNode->translate(0, 0, 250, Ogre::Node::TS_LOCAL); } else { //Nodo ficticio nodoFicticio->yaw(Ogre::Degree(2)); } } void AspasMolino::hideOrnaments() { for (int i = 0; i < numAspas; ++i) { arrayAspas[i]->hideOrnament(); } } void AspasMolino::volar() { mNode->roll(Ogre::Degree(-25)); for (int i = 0; i < numAspas; ++i) { arrayAspas[i]->move(25); } }
27.792683
121
0.679684
nicoFdez
510d87800f34aa4a9523b96fe5dca8ba92f0c3e6
65
cpp
C++
TileDeck.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
37
2015-07-23T04:02:51.000Z
2021-09-23T08:39:12.000Z
TileDeck.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
1
2018-08-30T08:33:38.000Z
2018-08-30T08:33:38.000Z
TileDeck.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
8
2015-07-23T04:02:58.000Z
2020-11-10T14:52:12.000Z
#include "client.h" #include "TileDeck.h" int Deck::idgen = 1;
10.833333
21
0.661538
kengonakajima
511158aad9b954dfa26a6b4b65ef6b6eb0430a4b
445
hpp
C++
include/innovatrics/ansiiso_accuracy_test.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
include/innovatrics/ansiiso_accuracy_test.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
include/innovatrics/ansiiso_accuracy_test.hpp
tomas-krupa/ansi_iso_accuracy_test
a87600c1ff8997cd689539432e5badaa1bf8a776
[ "Apache-2.0" ]
null
null
null
/** * @file ansiiso_accuracy_test.hpp * * @copyright Copyright (c) 2020 Innovatrics s.r.o. All rights reserved. * * @maintainer Tomas Krupa <tomas.krupa@innovatrics.com> * @created 10.08.2020 * */ #pragma once #include <string> #include <innovatrics/config.hpp> namespace Innovatrics { class AnsiIsoAccuracyTest { public: static const std::string GetProductString() { return ANSSIISO_ACCURACY_TEST_PRODUCT_STRING; } }; }
15.344828
72
0.719101
tomas-krupa
511307c7d5ebd32269ebb54010987c6873d834ae
7,453
cpp
C++
Examples/GrandBlimpBastards/SceneDirector.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
1
2017-08-15T03:56:22.000Z
2017-08-15T03:56:22.000Z
Examples/GrandBlimpBastards/SceneDirector.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
null
null
null
Examples/GrandBlimpBastards/SceneDirector.cpp
radical-bumblebee/bumblebee-engine
c5b7eb4bcd825bc2c5be66d6306912c519a56a2d
[ "MIT" ]
null
null
null
#include "SceneDirector.h" #include "SceneInfo.h" #include <sstream> void SceneDirector::tick() { if (_world->config->game_over < 1.0f && _world->config->game_over > 0.0f) { _world->config->game_over -= 0.3f * _world->dt; if (_world->config->game_over < 0.0f) { _world->config->game_over = 0.0f; _world->scene()->ui->add(std::make_shared<BumblebeeUIElement>("Game Over", "assets/fonts/times.ttf", _world->window_w / 2.0f - 35.0f, _world->window_h / 2.0f - 50.0f, &glm::vec4(1.0f))); _world->scene()->ui->add(std::make_shared<BumblebeeUIElement>("Hit R to retry", "assets/fonts/times.ttf", _world->window_w / 2.0f - 40.0f, _world->window_h / 2.0f - 20.0f, &glm::vec4(1.0f))); } } if (_world->config->game_over > 0.0f) { difficulty += _world->dt; //clean up destroyed blimps by setting them to unused for (unsigned int i = 0; i < _world->scene()->objects->size(); i++) { switch (_world->scene()->objects->at(i)->state) { case BumblebeeObject::INACTIVE: if (_world->scene()->objects->at(i)->model->info->name == _scene_info->blimp_name) { _world->scene()->objects->at(i)->state = BumblebeeObject::UNUSED; high_score++; } break; } } _scene_info->scene_timer -= _world->dt; std::string high_score_string = "Your Score: "; high_score_string += std::to_string(high_score); _world->scene()->ui->at(0)->text = high_score_string; if (_scene_info->rotate) { _world->scene()->camera()->rotate_radians(rotation); rotation += 0.2f; if (rotation > 360.0f) { rotation = 0.0f; } } // Color the skies as time goes on if (_world->scene()->objects->at(_scene_info->skybox_id)->model->info->transparency < 3.0f) { _world->scene()->objects->at(_scene_info->skybox_id)->model->info->transparency += (difficulty / 2000.0f) * _world->dt; } else { if (_world->scene()->objects->at(_scene_info->skybox_id)->model->info->shininess > 0.2f) { _world->scene()->objects->at(_scene_info->skybox_id)->model->info->shininess -= (difficulty / 3000.0f) * _world->dt; } } // Updates player blimp location _scene_info->cannon_origin.x = _world->scene()->objects->at(_world->scene()->player_id)->spatial->position.x; _scene_info->cannon_origin.y = _world->scene()->objects->at(_world->scene()->player_id)->spatial->position.y - 2.0f; _scene_info->cannon_origin.z = _world->scene()->objects->at(_world->scene()->player_id)->spatial->position.z + 3.0f; auto data_ptr = _world->scene()->objects->at(_scene_info->line_id)->model->info->vertices.data(); data_ptr->x = _scene_info->cannon_origin.x; data_ptr->y = _scene_info->cannon_origin.y; data_ptr->z = _scene_info->cannon_origin.z; data_ptr++; int x = 0; int y = 0; SDL_GetMouseState(&x, &y); // Transforms mouse position to 3D space float depth = 0.0f; glReadPixels((GLint)x, (GLint)(_world->window_h - y - 1.0f), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); depth = glm::clamp(depth, 0.8f, 0.95f); glm::vec4 viewport = glm::vec4(0.0f, 0.0f, _world->window_w, _world->window_h); glm::vec3 window_coordinates = glm::vec3(x, _world->window_h - y - 1.0f, depth); _scene_info->target_direction = glm::unProject(window_coordinates, _world->scene()->camera()->view_matrix, _world->projection_matrix, viewport); // Updates player blimp targetting system data_ptr->x = _scene_info->target_direction.x; data_ptr->y = _scene_info->target_direction.y; data_ptr->z = _scene_info->target_direction.z; } } // Spawns a cannonball and fires it towards mouse position void SceneDirector::fire_cannon() { if (_scene_info->scene_timer < 0.0f) { auto cannonball_id = _world->scene()->objects->add(factory::create_sphere(_scene_info->cannon_origin, _world->proxy->models["assets/models/sphere.ply"], _world->proxy->textures["assets/textures/metal.dds"])); float modifier = 2.0f; auto impulse = btVector3(btScalar(_scene_info->target_direction.x * (modifier * 1.15f)), btScalar((_scene_info->target_direction.y * modifier * 1.15f) + 5.0f), btScalar(_scene_info->target_direction.z * modifier)); auto torque = btVector3(btScalar(20), btScalar(20), btScalar(0)); _world->scene()->objects->at(cannonball_id)->model->info->shininess = 20.0f; _world->scene()->objects->at(cannonball_id)->bullet->body->applyCentralImpulse(impulse); _world->scene()->objects->at(cannonball_id)->bullet->body->applyTorque(torque); _scene_info->scene_timer = RESET_PERIOD; } } void SceneDirector::blimp_collision(BumblebeeObject* obj, glm::vec3 contact_point) { obj->bullet->body->setFlags(obj->bullet->body->getFlags() & ~BT_DISABLE_WORLD_GRAVITY); if (obj->model->info->name == _scene_info->blimp_name) { obj->particle = std::make_shared<ParticleComponent>(); obj->particle->info = _world->proxy->particles["assets/textures/smoke.dds"]; obj->particle->particle_offset = glm::vec4(obj->spatial->position - (contact_point), 1.0f); if (obj->state == BumblebeeObject::ACTIVE) obj->state = BumblebeeObject::INACTIVE; } } void SceneDirector::collision_callback(unsigned int id_a, unsigned int id_b, glm::vec3 contact_point) { auto obj_a = _world->scene()->objects->at(id_a); auto obj_b = _world->scene()->objects->at(id_b); if (_world->scene()->player_id == id_a || _world->scene()->player_id == id_b) { _world->config->game_over -= 0.0000001f; if (high_score > (unsigned int)_scene_info->highest_score) { BumblebeePersist::get()->set_high_score(0, high_score); } } // Drops blimps from the sky upon impact blimp_collision(obj_a, contact_point); blimp_collision(obj_b, contact_point); } void SceneDirector::init_scene() { // Initialize scene _scene_info->scene_id = _world->create_scene(); _world->activate_scene(_scene_info->scene_id); _world->scene()->camera()->eye = glm::vec3(0.0f, 2.0f, 0.0f); _world->scene()->camera()->target = glm::vec3(0.0f, 0.0f, 5.0f); // Create player blimp auto obj = factory::create_blimp(glm::vec3(0.0f), _world->proxy->models["assets/models/capsule.ply"], _world->proxy->textures["assets/textures/marble.dds"]); _world->scene()->player_id = _world->scene()->objects->add(obj); obj->ai->ai_group = AIComponent::PLAYER; _scene_info->line_id = _world->scene()->objects->add(factory::create_soft(_world->proxy->models["line"])); _scene_info->skybox_id = _world->scene()->objects->add(factory::create_skybox(_world->proxy->models["assets/models/cube.ply"], _world->proxy->textures["skybox"])); // Create lights _world->scene()->lights->add(factory::create_light(DIRECTIONAL_LIGHT, glm::vec3(0.0f, 10.0f, 0.0f))); _world->scene()->lights->add(factory::create_light(POINT_LIGHT, glm::vec3(0.0f, 5.0f, 20.0f))); // Create ui _world->scene()->ui->add(std::make_shared<BumblebeeUIElement>("Your Score: ", "assets/fonts/times.ttf", 10.0f, _world->window_h - 30.0f, &glm::vec4(1.0f))); _scene_info->highest_score = BumblebeePersist::get()->get_high_score(0); std::string highest_score_string; if (_scene_info->highest_score > 0) { highest_score_string = std::to_string(_scene_info->highest_score); } else { highest_score_string = "-"; } _world->scene()->ui->add(std::make_shared<BumblebeeUIElement>("High Score: " + highest_score_string, "assets/fonts/times.ttf", 10.0f, _world->window_h - 55.0f, &glm::vec4(1.0f))); } bool SceneDirector::init(BumblebeeWorld::ptr world) { _world = world; rotation = 0.0f; high_score = 0; difficulty = 0.0f; return true; } void SceneDirector::destroy() { _world.reset(); }
43.331395
216
0.695693
radical-bumblebee
5114fdf5e436670aa4f96417aa6beb7218245e57
1,791
hpp
C++
teas/teaport_utils/shell.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
teas/teaport_utils/shell.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
teas/teaport_utils/shell.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
#pragma once // this is a good item to be it's own library. Cross platform process // creation library. #include <string> #include <initializer_list> #include <vector> #include <cstdint> #include "Version.hpp" namespace tea { struct CompletedProcess { int exit_code = 1; std::vector<uint8_t> stdout_data; explicit operator bool() const { return exit_code == 0; } }; typedef std::vector<std::string> CommandLine; std::string find_program(const std::string& name); std::string escape_shell_arg(std::string arg); int system(std::vector<std::string> args); CompletedProcess system_capture(std::vector<std::string> argsIn, bool capture_stderr=false); // these 2 throw CommandError if exit status is not 0 int system_checked(std::vector<std::string> args); CompletedProcess system_capture_checked(std::vector<std::string> argsIn, bool capture_stderr=false); /* because of windows we won't allow this form int system(const std::string& str); */ bool unzip(const std::string& zipfile, const std::string& output_dir); /** runs the command and tries to parse the version. @param command Either command name or path to command. @returns The version of the command parsed. or 0.0.0 if could not parse. @throw CommandError If there is an error executing the command. @throw FileNotFoundError If the command could not be found. */ StrictVersion command_version(std::string command); CommandLine parse_shebang(const std::string& line); CommandLine parse_shebang_file(const std::string& filepath); CommandLine process_shebang_recursively(CommandLine args); CommandLine process_env(CommandLine args); }
34.442308
104
0.691234
benman64
5120fed4befbeb143a9526102c6a639bf65349fd
5,051
cc
C++
src/ptr_matrix.cc
Charles-Chao-Chen/fastSolver2
60eed8825f05c29919f7153497a4b57dec1ef76d
[ "MIT" ]
1
2020-11-28T12:41:51.000Z
2020-11-28T12:41:51.000Z
src/ptr_matrix.cc
Charles-Chao-Chen/fastSolver2
60eed8825f05c29919f7153497a4b57dec1ef76d
[ "MIT" ]
2
2017-09-15T23:39:34.000Z
2017-11-21T21:43:00.000Z
src/ptr_matrix.cc
Charles-Chao-Chen/fastSolver2
60eed8825f05c29919f7153497a4b57dec1ef76d
[ "MIT" ]
3
2016-10-04T04:34:32.000Z
2017-09-15T22:16:11.000Z
#include "ptr_matrix.hpp" #include "utility.hpp" #include <assert.h> #include <stdlib.h> // for srand48_r(), lrand48_r() and drand48_r() PtrMatrix::PtrMatrix() : mRows(-1), mCols(-1), leadD(-1), ptr(NULL), has_memory(false), trans('n') {} PtrMatrix::PtrMatrix(int r, int c) : mRows(r), mCols(c), leadD(r), has_memory(true), trans('n') { ptr = new double[mRows*mCols]; } PtrMatrix::PtrMatrix(int r, int c, int l, double *p, char trans_) : mRows(r), mCols(c), leadD(l), ptr(p), has_memory(false), trans(trans_) { assert(trans_ == 't' || trans_ == 'n'); } PtrMatrix::~PtrMatrix() { if (has_memory) delete[] ptr; ptr = NULL; } // legion uses column major storage, // which is consistant with blas and lapack layout double PtrMatrix::operator()(int r, int c) const { return ptr[r+c*leadD]; } double& PtrMatrix::operator()(int r, int c) { return ptr[r+c*leadD]; } double* PtrMatrix::pointer() const {return ptr;} double* PtrMatrix::pointer(int r, int c) { return &ptr[r+c*leadD]; } void PtrMatrix::set_trans(char trans_) { assert(trans_ == 't' || trans_ == 'n'); this->trans=trans_; } void PtrMatrix::clear(double value) { for (int j=0; j<mCols; j++) for (int i=0; i<mRows; i++) (*this)(i, j) = value; } void PtrMatrix::scale(double alpha) { for (int j=0; j<mCols; j++) for (int i=0; i<mRows; i++) (*this)(i, j) *= alpha; } void PtrMatrix::rand(long seed, int offset) { struct drand48_data buffer; assert( srand48_r( seed, &buffer ) == 0 ); for (int i=0; i<mRows; i++) { for (int j=0; j<mCols; j++) { assert( drand48_r(&buffer, this->pointer(i,j) ) == 0 ); (*this)(i,j) += offset; } } } void PtrMatrix::display(const std::string& name) { std::cout << name << ":" << std::endl; for(int ri = 0; ri < mRows; ri++) { for(int ci = 0; ci < mCols; ci++) { std::cout << (*this)(ri, ci) << "\t"; } std::cout << std::endl; } } int PtrMatrix::LD() const {return leadD;} int PtrMatrix::rows() const { switch (trans) { case 'n': return mRows; break; case 't': return mCols; break; default: assert(false); break; } } int PtrMatrix::cols() const { switch (trans) { case 't': return mRows; break; case 'n': return mCols; break; default: assert(false); break; } } void PtrMatrix::solve(PtrMatrix& B) { int N = this->mRows; int NRHS = B.cols(); int LDA = leadD; int LDB = B.LD(); int IPIV[N]; int INFO; lapack::dgesv_(&N, &NRHS, ptr, &LDA, IPIV, B.pointer(), &LDB, &INFO); assert(INFO==0); /* std::cout << "Permutation:" << std::endl; for (int i=0; i<N; i++) std::cout << IPIV[i] << "\t"; std::cout << std::endl; */ } void PtrMatrix::identity() { assert(mRows==mCols); assert(mRows==leadD); memset(ptr, 0, mRows*mCols*sizeof(double)); // initialize to 0's for (int i=0; i<mRows; i++) (*this)(i, i) = 1.0; } void PtrMatrix::add (double alpha, const PtrMatrix& A, double beta, const PtrMatrix& B, PtrMatrix& C) { assert(A.rows() == B.rows() && A.rows() == C.rows()); assert(A.rows() == B.rows() && A.rows() == C.rows()); assert(A.cols() == B.cols() && A.cols() == C.cols()); for (int j=0; j<C.cols(); j++) for (int i=0; i<C.rows(); i++) { C(i, j) = alpha*A(i,j) + beta*B(i,j); //printf("(%f, %f, %f)\n", A(i, j), B(i, j), C(i, j)); } } void PtrMatrix::gemm (const PtrMatrix& U, const PtrMatrix& V, const PtrMatrix& D, PtrMatrix& res) { assert(U.cols() == V.rows()); char transa = U.trans; char transb = V.trans; int M = U.rows(); int N = V.cols(); int K = U.cols(); int LDA = U.LD(); int LDB = V.LD(); int LDC = res.LD(); double alpha = 1.0, beta = 0.0; //double alpha = 0.0, beta = 0.0; blas::dgemm_(&transa, &transb, &M, &N, &K, &alpha, U.pointer(), &LDA, V.pointer(), &LDB, &beta, res.pointer(), &LDC); // add the diagonal assert(res.rows() == res.cols()); for (int i=0; i<res.rows(); i++) res(i, i) += D(i, 0); } void PtrMatrix::gemm (double alpha, const PtrMatrix& U, const PtrMatrix& V, PtrMatrix& W) { assert(U.cols() == V.rows()); assert(U.rows() == W.rows()); assert(V.cols() == W.cols()); char transa = U.trans; char transb = V.trans; int M = U.rows(); int N = V.cols(); int K = U.cols(); int LDA = U.LD(); int LDB = V.LD(); int LDC = W.LD(); double beta = 1.0; blas::dgemm_(&transa, &transb, &M, &N, &K, &alpha, U.pointer(), &LDA, V.pointer(), &LDB, &beta, W.pointer(), &LDC); } void PtrMatrix::gemm (double alpha, const PtrMatrix& U, const PtrMatrix& V, double beta, PtrMatrix& W) { assert(U.cols() == V.rows()); assert(U.rows() == W.rows()); assert(V.cols() == W.cols()); char transa = U.trans; char transb = V.trans; int M = U.rows(); int N = V.cols(); int K = U.cols(); int LDA = U.LD(); int LDB = V.LD(); int LDC = W.LD(); blas::dgemm_(&transa, &transb, &M, &N, &K, &alpha, U.pointer(), &LDA, V.pointer(), &LDB, &beta, W.pointer(), &LDC); }
24.519417
67
0.559097
Charles-Chao-Chen
512301f537ba191042486d680edab9c600e5d49b
15,210
cpp
C++
2dSpriteGame/Monkey/Level_Editor/Classes/AppFrame.cpp
ScottRMcleod/CPLUSPLUS
94352ddf374b048fab960c1e7d5b2000d08ab399
[ "Unlicense" ]
null
null
null
2dSpriteGame/Monkey/Level_Editor/Classes/AppFrame.cpp
ScottRMcleod/CPLUSPLUS
94352ddf374b048fab960c1e7d5b2000d08ab399
[ "Unlicense" ]
null
null
null
2dSpriteGame/Monkey/Level_Editor/Classes/AppFrame.cpp
ScottRMcleod/CPLUSPLUS
94352ddf374b048fab960c1e7d5b2000d08ab399
[ "Unlicense" ]
null
null
null
#include "AppFrame.h" #define TOOLBAR_SIZE 16 #define GRID_SIZE 32 BEGIN_EVENT_TABLE(AppFrame, wxFrame) EVT_MENU( ID_New_Package, AppFrame::OnNewPackage) EVT_MENU( ID_New_Level, AppFrame::OnNewLevel) EVT_MENU( ID_Save, AppFrame::OnSave) EVT_MENU( ID_Load, AppFrame::OnLoad) EVT_MENU( ID_About, AppFrame::OnAbout) EVT_MENU( ID_Exit, AppFrame::OnExit) EVT_TOOL_RANGE( TLB_PREVIOUS_LEVEL, TLB_TEST_LEVEL, AppFrame::OnToolBarClicked) END_EVENT_TABLE() AppFrame::AppFrame(const wxString &title, const wxPoint &pos, const wxSize &size) : wxFrame((wxFrame*)NULL,-1,title,pos,size, wxDEFAULT_FRAME_STYLE | wxCLIP_CHILDREN) { mouse_grid_x = mouse_grid_y = -1; finalBackBuffer = NULL; backBuffer = NULL; package = NULL; wxMenuBar *menuBar = new wxMenuBar; menuFile = new wxMenu; menuFile->Append(ID_New_Package, "New &Package"); menuFile->Append(ID_New_Level, "&New Level"); menuFile->AppendSeparator(); menuFile->Append(ID_Load, "&Load"); menuFile->Append(ID_Save, "&Save"); menuFile->AppendSeparator(); menuFile->Append(ID_About, "&About"); menuFile->AppendSeparator(); menuFile->Append(ID_Exit, "E&xit"); menuBar->Append(menuFile, "&File"); SetMenuBar(menuBar); gameWindow = new wxWindow(this, -1); gameWindow->Connect(-1,-1, wxEVT_SIZE, (wxObjectEventFunction) &AppFrame::OnSize, NULL, this); gameWindow->Connect(-1,-1, wxEVT_PAINT, (wxObjectEventFunction) &AppFrame::OnPaint, NULL, this); gameWindow->Connect(-1,-1, wxEVT_MOTION, (wxObjectEventFunction) &AppFrame::OnMotion, NULL, this); gameWindow->Connect(-1,-1, wxEVT_LEFT_DOWN, (wxObjectEventFunction) &AppFrame::OnMouseLeft, NULL, this); CreateStatusBar(3); SetStatusText("Create a New Pakage to begin creating levels..."); toolbar = CreateToolBar(wxTB_FLAT); wxImage wallImage = wxBITMAP(WallTile).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); wallImage.SetMask(false); wxBitmap wallBitmap = (wxBitmap)wallImage; wxImage playerImage = wxBITMAP(PlayerTile).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); playerImage.SetMaskColour(255,255,255); wxBitmap playerBitmap = (wxBitmap)playerImage; wxImage enemyImage = wxBITMAP(EnemyTile).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); enemyImage.SetMaskColour(255,255,255); wxBitmap enemyBitmap = (wxBitmap)enemyImage; wxImage potionImage = wxBITMAP(PotionTile).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); potionImage.SetMaskColour(255,255,255); wxBitmap potionBitmap = (wxBitmap)potionImage; wxBitmap eraseBitmap = wxBITMAP(Eraser).ConvertToImage().Scale(TOOLBAR_SIZE,TOOLBAR_SIZE); wxBitmap arrowLeftBitmap = (wxBitmap)wxBITMAP(ArrowLeft); wxBitmap arrowRightBitmap = (wxBitmap)wxBITMAP(ArrowRight); wxBitmap executeBitmap = (wxBitmap)wxBITMAP(Execute); toolbar->AddRadioTool(TLB_WALL, "Place Wall", wallBitmap, wxNullBitmap, "Place walls"); toolbar->AddRadioTool(TLB_PLAYER, "Place Player", playerBitmap, wxNullBitmap, "Place Player"); toolbar->AddRadioTool(TLB_ENEMY, "Place Enemy", enemyBitmap, wxNullBitmap, "Place Enemy"); toolbar->AddRadioTool(TLB_POTION, "Place Potion", potionBitmap, wxNullBitmap, "Place Potion"); toolbar->AddRadioTool(TLB_ERASE, "Erase Items", eraseBitmap, wxNullBitmap, "Erase Items"); toolbar->AddSeparator(); toolbar->AddTool(TLB_PREVIOUS_LEVEL, "Previous Level", arrowLeftBitmap,"Previous Level"); toolbar->AddTool(TLB_NEXT_LEVEL, "Next Level", arrowRightBitmap,"Next Level"); toolbar->AddTool(TLB_TEST_LEVEL, "Test Level", executeBitmap,"Test Level"); toolbar->EnableTool(TLB_PREVIOUS_LEVEL, false); toolbar->EnableTool(TLB_NEXT_LEVEL, false); toolbar->Realize(); wallImage = wxBITMAP(WallTile).ConvertToImage(); wallImage.SetMask(false); wallBitmap = (wxBitmap)wallImage; playerImage = wxBITMAP(PlayerTile).ConvertToImage(); playerImage.SetMaskColour(255,255,255); playerBitmap = (wxBitmap)playerImage; enemyImage = wxBITMAP(EnemyTile).ConvertToImage(); enemyImage.SetMaskColour(255,255,255); enemyBitmap = (wxBitmap)enemyImage; potionImage = wxBITMAP(PotionTile).ConvertToImage(); potionImage.SetMaskColour(255,255,255); potionBitmap = (wxBitmap)potionImage; wxBitmap emptyBitmap = wxBITMAP(EmptyTile); items[0] = emptyBitmap; items[1] = wallBitmap; items[2] = playerBitmap; items[3] = enemyBitmap; items[4] = potionBitmap; } void AppFrame::OnNewPackage(wxCommandEvent &event) { Package *old_package = package; int old_levelIndex = levelIndex; package = new Package; levelIndex = 0; if(!createNewLevel()) { delete package; package = old_package; levelIndex = old_levelIndex; } else { delete old_package; menuFile->Enable(ID_New_Level, true); toolbar->EnableTool(TLB_PREVIOUS_LEVEL, false); toolbar->EnableTool(TLB_NEXT_LEVEL, false); } } void AppFrame::OnNewLevel(wxCommandEvent &event) { createNewLevel(); } void AppFrame::OnSave(wxCommandEvent &event) { wxFileDialog dialog(this, _T("Save Package"), _T(""), _T("Package1.pkg"), _T("Package (*.pkg)|*.pkg"), wxSAVE|wxOVERWRITE_PROMPT); if(dialog.ShowModal() == wxID_OK) { savePackage(dialog.GetPath().c_str()); } } void AppFrame::OnLoad(wxCommandEvent &event) { wxFileDialog dialog(this, _T("Load Package"), _T(""), _T(""), _T("Package (*.pkg)|*.pkg"), 0); if(dialog.ShowModal() == wxID_OK) { FILE *stream; const wxChar *filename = dialog.GetPath().c_str(); stream = fopen(filename, "r+b"); int numLevels; fread(&numLevels, sizeof(int), 1, stream); if(package) delete package; package = new Package; for(int i = 0; i < numLevels; i++) { Level_Info *level = new Level_Info; fread(&level->grid_x, sizeof(int), 1, stream); fread(&level->grid_y, sizeof(int), 1, stream); level->grid = new char *[level->grid_x]; for(int x = 0; x < level->grid_x; x++) { level->grid[x] = new char[level->grid_y]; } for (int x = 0; x < level->grid_x; x++) fread(level->grid[x], sizeof(char), level->grid_y, stream); package->push_back(level); if(i == 0) { levelIndex = 1; setCurrentLevel(level); } } fclose(stream); toolbar->EnableTool(TLB_PREVIOUS_LEVEL, levelIndex != 1); toolbar->EnableTool(TLB_NEXT_LEVEL, levelIndex != package->size()); menuFile->Enable(ID_New_Level, true); updateView(); } } void AppFrame::OnAbout(wxCommandEvent &event) { } void AppFrame::OnExit(wxCommandEvent &event) { } void AppFrame::OnToolBarClicked(wxCommandEvent &event) { bool changed = false; switch(event.GetId()) { case TLB_TEST_LEVEL: { savePackage("temp.pkg"); wxExecute(wxString::Format("EvilMonkeys.exe temp.pkg %d", levelIndex)); break; } case TLB_PREVIOUS_LEVEL: { if(levelIndex > 1) levelIndex--; changed = true; } break; case TLB_NEXT_LEVEL: { if(levelIndex < (int)package->size()) levelIndex++; changed = true; } break; } if(changed) { list<Level_Info *>::iterator it; int i = 0; for(it = package->begin(); it != package->end(); it++, i++) { if(i == levelIndex - 1) { setCurrentLevel((*it)); break; } } toolbar->EnableTool(TLB_PREVIOUS_LEVEL, levelIndex != 1); toolbar->EnableTool(TLB_NEXT_LEVEL, levelIndex != package->size()); } } void AppFrame::OnSize(wxSizeEvent &event) { event.Skip(); if(finalBackBuffer) { delete finalBackBuffer; } wxSize clientArea = gameWindow->GetClientSize(); finalBackBuffer = new wxBitmap(clientArea.GetWidth(), clientArea.GetHeight()); if(backBuffer) { stretchGameView(); flipBackBuffer(); } } void AppFrame::OnPaint(wxPaintEvent &event) { wxPaintDC dc(gameWindow); wxSize clientArea = gameWindow->GetClientSize(); if(!backBuffer) { wxClientDC screenDC(gameWindow); screenDC.Clear(); screenDC.DrawRectangle(0,0, clientArea.GetWidth(), clientArea.GetHeight()); } else { stretchGameView(); flipBackBuffer(); } } void AppFrame::updateView(void) { if(!backBuffer) { return; } wxMemoryDC backBufferDC; backBufferDC.SelectObject(*backBuffer); backBufferDC.Clear(); for(int x = 0; x < currentLevel->grid_x; x++) { for(int y = 0; y < currentLevel->grid_y; y++) { int item = currentLevel->grid[x][y]; if(item >= 0 && item <= 4) { backBufferDC.DrawBitmap(items[0], x *(GRID_SIZE + 1) + 1, y * (GRID_SIZE + 1)); backBufferDC.DrawBitmap(items[item], x *(GRID_SIZE + 1) + 1, y * (GRID_SIZE + 1), true); } } } backBufferDC.SetPen(wxPen(wxColour(128,128,128))); for(int x = 0; x <= currentLevel->grid_x; x++) backBufferDC.DrawLine(wxPoint(x*(GRID_SIZE + 1), 0), wxPoint(x * (GRID_SIZE + 1), currentLevel->grid_y * (GRID_SIZE + 1))); for(int y = 0; y <= currentLevel->grid_y; y++) backBufferDC.DrawLine(wxPoint(0, y*(GRID_SIZE + 1)), wxPoint(currentLevel->grid_x * (GRID_SIZE + 1 ), y * (GRID_SIZE + 1))); backBufferDC.SelectObject(wxNullBitmap); stretchGameView(); flipBackBuffer(); } void AppFrame::stretchGameView(void) { wxSize clientArea = gameWindow->GetClientSize(); wxSize stretchedSize; if(clientArea.GetWidth() * currentLevel->grid_y / currentLevel->grid_x < clientArea.GetHeight()) { stretchedSize.Set(clientArea.GetWidth(), clientArea.GetWidth() * currentLevel->grid_y / currentLevel->grid_x); } else { stretchedSize.Set(clientArea.GetHeight() * currentLevel->grid_x / currentLevel->grid_y, clientArea.GetHeight()); } wxImage stretchedImage = backBuffer->ConvertToImage(); stretchedImage = stretchedImage.Scale(stretchedSize.GetWidth(), stretchedSize.GetHeight()); wxMemoryDC finalDC; wxMemoryDC imageDC; finalDC.SelectObject(*finalBackBuffer); imageDC.SelectObject(stretchedImage); finalDC.SetBackground(*wxBLACK_BRUSH); finalDC.Clear(); wxPoint center; center.x = (clientArea.GetWidth() - stretchedSize.GetWidth()) / 2; center.y = (clientArea.GetHeight() - stretchedSize.GetHeight()) / 2; finalDC.Blit(center, stretchedSize, &imageDC, wxPoint(0,0)); finalDC.SetBrush(*wxTRANSPARENT_BRUSH); finalDC.DrawRectangle(wxPoint(0,0), clientArea); imageDC.SelectObject(wxNullBitmap); finalDC.SelectObject(wxNullBitmap); pos_x = center.x; pos_y = center.y; grid_width = stretchedSize.GetWidth(); grid_height = stretchedSize.GetHeight(); } void AppFrame::flipBackBuffer(void) { wxSize clientArea = gameWindow->GetClientSize(); wxMemoryDC finalDC; wxClientDC screenDC(gameWindow); finalDC.SelectObject(*finalBackBuffer); screenDC.Blit(wxPoint(0,0), clientArea, &finalDC, wxPoint(0,0)); finalDC.SelectObject(wxNullBitmap); } bool AppFrame::createNewLevel(void) { long x = wxGetNumberFromUser(_T("Enter the number of colums for the new level."), _T("Colums"),_T("New Level"), 10, 0, 100, this); if(x < 1) { return false; } long y = wxGetNumberFromUser(_T("Enter the number of rows for the new level."), _T("Rows"),_T("New Level"), 10, 0, 100, this); if(y < 1) { return false; } currentLevel = new Level_Info; package->push_back(currentLevel); levelIndex = (int)package->size(); currentLevel->grid_x = x; currentLevel->grid_y = y; currentLevel->grid = new char *[currentLevel->grid_x]; for(int i = 0; i < currentLevel->grid_x; i++) { currentLevel->grid[i] = new char[currentLevel->grid_y]; } for (int x = 0; x < currentLevel->grid_x; x++) { for(int y = 0; y < currentLevel->grid_y; y++) currentLevel->grid[x][y] = 0; } setCurrentLevel(currentLevel); if(levelIndex >= 2) { toolbar->EnableTool(TLB_PREVIOUS_LEVEL, true); toolbar->EnableTool(TLB_NEXT_LEVEL, false); } return true; } void AppFrame::setCurrentLevel(Level_Info *level) { currentLevel = level; backBuffer = new wxBitmap(currentLevel->grid_x * (GRID_SIZE + 1) + 1, currentLevel->grid_y * (GRID_SIZE + 1) + 1); wxString new_title = "Level Editor for Evil Monkeys - level"; new_title += wxString::Format("%d", levelIndex); SetTitle(new_title); wxString status_info = "Level Size"; status_info += wxString::Format("%dx%d", currentLevel->grid_x, currentLevel->grid_y); SetStatusText(status_info, 1); status_info = "Current Level"; status_info += wxString::Format("%d", levelIndex); SetStatusText(status_info, 2); updateView(); } void AppFrame::OnMotion(wxMouseEvent &event) { wxPoint mp = event.GetPosition(); if (mp.x >= pos_x && mp.x <= pos_x + grid_width && mp.y >= pos_y && mp.y <= pos_y + grid_height) { int tempX = (mp.x - pos_x) / (grid_width / currentLevel->grid_x); int tempY = (mp.y - pos_y) / (grid_height / currentLevel->grid_y); if(tempX != mouse_grid_x || tempY != mouse_grid_y) { mouse_grid_x = tempX; mouse_grid_y = tempY; if(event.LeftIsDown()) OnMouseLeft(event); } } else { if(mouse_grid_x != -1 && mouse_grid_y != -1) { mouse_grid_x = mouse_grid_y = -1; updateView(); } } } void AppFrame::OnMouseLeft(wxMouseEvent &event) { if(mouse_grid_x != -1 && mouse_grid_y != -1) { int selected = 0; if(toolbar->GetToolState(TLB_ERASE)) selected = TILE_EMPTY; else if(toolbar->GetToolState(TLB_WALL)) selected = TILE_WALL; else if(toolbar->GetToolState(TLB_PLAYER)) selected = TILE_PLAYER; else if(toolbar->GetToolState(TLB_ENEMY)) selected = TILE_ENEMY; else if(toolbar->GetToolState(TLB_POTION)) selected = TILE_POTION; else return; if(backBuffer) { wxMemoryDC backBufferDC; backBufferDC.SelectObject(*backBuffer); if(selected == 2) { for(int x = 0; x < currentLevel->grid_x; x++) for(int y = 0; y < currentLevel->grid_y; y++) if(currentLevel->grid[x][y] == 2) { currentLevel->grid[x][y] = 0; backBufferDC.DrawBitmap(items[0], x * (GRID_SIZE + 1) + 1, y * (GRID_SIZE + 1) + 1); } } if(mouse_grid_x < currentLevel->grid_x && mouse_grid_y < currentLevel->grid_y) currentLevel->grid[mouse_grid_x][mouse_grid_y] = selected; backBufferDC.DrawBitmap(items[0], mouse_grid_x * (GRID_SIZE + 1) + 1, mouse_grid_y * (GRID_SIZE + 1) + 1); backBufferDC.DrawBitmap(items[selected], mouse_grid_x * (GRID_SIZE + 1) + 1, mouse_grid_y * (GRID_SIZE + 1) + 1, true); backBufferDC.SelectObject(wxNullBitmap); stretchGameView(); flipBackBuffer(); } } } void AppFrame::savePackage(wxString filename) { FILE *stream; stream = fopen(filename, "w+b"); int numLevels = (int)package->size(); fwrite(&numLevels, sizeof(int), 1, stream); list<Level_Info *>::iterator it; for(it = package->begin(); it != package->end(); it++) { Level_Info *level = (*it); fwrite(&level->grid_x, sizeof(int), 1, stream); fwrite(&level->grid_y, sizeof(int), 1, stream); for(int x = 0; x < level->grid_x; x++) fwrite(level->grid[x], sizeof(char), level->grid_y, stream); } fclose(stream); }
25.955631
132
0.673044
ScottRMcleod
512306955fcd3f467b3442d6632e987902f2d21f
3,439
cpp
C++
desktop-ui/program/drivers.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
desktop-ui/program/drivers.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
desktop-ui/program/drivers.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
auto Program::videoDriverUpdate() -> void { ruby::video.create(settings.video.driver); ruby::video.setContext(presentation.viewport.handle()); videoMonitorUpdate(); videoFormatUpdate(); ruby::video.setExclusive(settings.video.exclusive); ruby::video.setBlocking(settings.video.blocking); ruby::video.setFlush(settings.video.flush); ruby::video.setShader(settings.video.shader); if(!ruby::video.ready()) { MessageDialog().setText({"Failed to initialize ", settings.video.driver, " video driver."}).setAlignment(presentation).error(); settings.video.driver = "None"; driverSettings.videoDriverUpdate(); } presentation.loadShaders(); } auto Program::videoMonitorUpdate() -> void { if(!ruby::video.hasMonitor(settings.video.monitor)) { settings.video.monitor = ruby::video.monitor(); } ruby::video.setMonitor(settings.video.monitor); } auto Program::videoFormatUpdate() -> void { if(!ruby::video.hasFormat(settings.video.format)) { settings.video.format = ruby::video.format(); } ruby::video.setFormat(settings.video.format); } auto Program::videoFullScreenToggle() -> void { if(!ruby::video.hasFullScreen()) return; ruby::video.clear(); if(!ruby::video.fullScreen()) { ruby::video.setFullScreen(true); if(!ruby::input.acquired()) { if(ruby::video.exclusive() || ruby::video.hasMonitors().size() == 1) { ruby::input.acquire(); } } } else { if(ruby::input.acquired()) { ruby::input.release(); } ruby::video.setFullScreen(false); presentation.viewport.setFocused(); } } // auto Program::audioDriverUpdate() -> void { ruby::audio.create(settings.audio.driver); ruby::audio.setContext(presentation.viewport.handle()); audioDeviceUpdate(); audioFrequencyUpdate(); audioLatencyUpdate(); ruby::audio.setExclusive(settings.audio.exclusive); ruby::audio.setBlocking(settings.audio.blocking); ruby::audio.setDynamic(settings.audio.dynamic); if(!ruby::audio.ready()) { MessageDialog().setText({"Failed to initialize ", settings.audio.driver, " audio driver."}).setAlignment(presentation).error(); settings.audio.driver = "None"; driverSettings.audioDriverUpdate(); } } auto Program::audioDeviceUpdate() -> void { if(!ruby::audio.hasDevice(settings.audio.device)) { settings.audio.device = ruby::audio.device(); } ruby::audio.setDevice(settings.audio.device); } auto Program::audioFrequencyUpdate() -> void { if(!ruby::audio.hasFrequency(settings.audio.frequency)) { settings.audio.frequency = ruby::audio.frequency(); } ruby::audio.setFrequency(settings.audio.frequency); for(auto& stream : streams) { stream->setResamplerFrequency(ruby::audio.frequency()); } } auto Program::audioLatencyUpdate() -> void { if(!ruby::audio.hasLatency(settings.audio.latency)) { settings.audio.latency = ruby::audio.latency(); } ruby::audio.setLatency(settings.audio.latency); } // auto Program::inputDriverUpdate() -> void { ruby::input.create(settings.input.driver); ruby::input.setContext(presentation.viewport.handle()); ruby::input.onChange({&InputManager::eventInput, &inputManager}); if(!ruby::input.ready()) { MessageDialog().setText({"Failed to initialize ", settings.input.driver, " input driver."}).setAlignment(presentation).error(); settings.input.driver = "None"; driverSettings.inputDriverUpdate(); } inputManager.poll(true); }
30.433628
131
0.700785
CasualPokePlayer
512398c8e1c780d5fd682f014a3e27bb0eb3e881
2,684
hpp
C++
modules/boost/simd/base/include/boost/simd/operator/functions/shift_right.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/base/include/boost/simd/operator/functions/shift_right.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/operator/functions/shift_right.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_OPERATOR_FUNCTIONS_SHIFT_RIGHT_HPP_INCLUDED #define BOOST_SIMD_OPERATOR_FUNCTIONS_SHIFT_RIGHT_HPP_INCLUDED #include <boost/simd/include/functor.hpp> namespace boost { namespace simd { namespace tag { /*! @brief shift_right generic tag Represents the shift_right function in generic contexts. @par Models: Hierarchy **/ struct shift_right_ : ext::elementwise_<shift_right_> { /// @brief Parent hierarchy typedef ext::elementwise_<shift_right_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_shift_right_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site> BOOST_FORCEINLINE generic_dispatcher<tag::shift_right_, Site> dispatching_shift_right_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...) { return generic_dispatcher<tag::shift_right_, Site>(); } template<class... Args> struct impl_shift_right_; } /*! return right shift of the first operand by the second that must be of integer type and of the same number of elements as the first parameter Infix notation can be used with operator '>>' @par Semantic: For every parameters of types respectively T0, T1: @code T0 r = shift_right(a0,a1); @endcode is similar to: @code T0 r = a0 >> a1; @endcode @par Alias: @c shra, @c shar, @c shrai @see @funcref{shift_left}, @funcref{shr}, @funcref{rshl}, @funcref{rshr}, @funcref{rol}, @funcref{ror} @param a0 @param a1 @return a value of the same type as the second parameter **/ BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::shift_right_ , shift_right , 2 ) BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::shift_right_ , shra , 2 ) BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::shift_right_ , shar , 2 ) BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::shift_right_ , shrai , 2 ) } } #include <boost/simd/operator/specific/common.hpp> #endif
31.952381
145
0.625931
feelpp
5124183a50986bde23dacf6d7b946a55c22a9d59
16,733
cpp
C++
src/main.cpp
MlsDmitry/RakNet-samples
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
[ "MIT" ]
null
null
null
src/main.cpp
MlsDmitry/RakNet-samples
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
[ "MIT" ]
null
null
null
src/main.cpp
MlsDmitry/RakNet-samples
05873aecb5c8dac0c0f822845c764bd5f8dc6a6d
[ "MIT" ]
null
null
null
// #include <iostream> // #include <thread> // #include <chrono> // #include <string> // #include <iomanip> // #include <cstring> // #include "RakPeerInterface.h" // #include "RakNetTypes.h" // #include "RakNetDefines.h" // #include "RakNetStatistics.h" // #include "BitStream.h" // #include "StringCompressor.h" // #include "GetTime.h" // #include "MessageIdentifiers.h" // #include "NetworkIDManager.h" // #include "RakSleep.h" // #include "sys/socket.h" // #define SERVER_PORT 30000 // #define CLIENT_PORT 40000 // unsigned char get_packet_identifier(RakNet::Packet *p) // { // if ((unsigned char)p->data[0] == ID_TIMESTAMP) // return (unsigned char)p->data[sizeof(RakNet::MessageID) + sizeof(RakNet::Time)]; // else // return (unsigned char)p->data[0]; // } // int main() // { // bool listening = true; // bool b; // RakNet::RakPeerInterface *server = RakNet::RakPeerInterface::GetInstance(); // RakNet::RakPeerInterface *client = RakNet::RakPeerInterface::GetInstance(); // printf("Server is at: %p\n", server); // RakNet::SocketDescriptor server_socket_descriptor(SERVER_PORT, "127.0.0.1"); // RakNet::SocketDescriptor client_socket_descriptor(CLIENT_PORT, "127.0.0.1"); // // start client // b = client->Startup(2, &client_socket_descriptor, 1); // RakAssert(b == RakNet::RAKNET_STARTED); // // start server // b = server->Startup(100, &server_socket_descriptor, 1); // RakAssert(b == RakNet::RAKNET_STARTED); // server->SetMaximumIncomingConnections(100); // // connect client // b = client->Connect("127.0.0.1", (unsigned short)SERVER_PORT, 0, 0); // RakAssert(b == RakNet::ID_CONNECTION_REQUEST_ACCEPTED); // std::cout << "Client connected!" << std::endl; // // send first packet // RakNet::BitStream bs; // RakNet::RakString server_blob("Hello, it's RakString here from server!"); // RakNet::RakString client_blob("Hello, it's RakString here from client!"); // bs.Write((unsigned char)ID_USER_PACKET_ENUM); // bs.WriteCompressed(server_blob); // client->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_RAKNET_GUID, true); // RakNet::Packet *packet; // bool waiting = true; // while (true) // { // while (waiting) { // packet = server->Receive(); // if (packet) { // waiting = false; // printf("Server packet id is: %d\n", get_packet_identifier(packet)); // if (get_packet_identifier(packet) == ID_USER_PACKET_ENUM) { // RakNet::BitStream data(packet->data, packet->length, true); // RakNet::RakString out; // unsigned char packetTypeID; // data.Read(packetTypeID); // data.ReadCompressed(out); // printf("Server packet data: %s\n", out.C_String()); // } // RakNet::BitStream bs; // bs.Write((unsigned char)ID_USER_PACKET_ENUM); // bs.WriteCompressed(server_blob); // server->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_RAKNET_GUID, true); // } // server->DeallocatePacket(packet); // RakSleep(500); // } // waiting = true; // while (waiting) { // packet = client->Receive(); // if (packet) { // waiting = false; // printf("Client packet id is: %d\n", get_packet_identifier(packet)); // if (get_packet_identifier(packet) == ID_USER_PACKET_ENUM) { // RakNet::BitStream data(packet->data, packet->length, true); // RakNet::RakString out; // unsigned char packetTypeID; // data.Read(packetTypeID); // data.ReadCompressed(out); // printf("Client packet data: %s\n", out.C_String()); // } // RakNet::BitStream bs; // bs.Write((unsigned char)ID_USER_PACKET_ENUM); // bs.WriteCompressed(client_blob); // client->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_RAKNET_GUID, true); // } // client->DeallocatePacket(packet); // RakSleep(500); // } // waiting = true; // } // // RakNet::RakNetGUID guid = server->GetGuidFromSystemAddress(RakNet::UNASSIGNED_SYSTEM_ADDRESS); // // RakNet::SystemAddress address("127.0.0.1", 30002); // // server->Ping(address); // // // // std::cout << "* Your GUID is: " << guid.ToString() << std::endl; // // client->Send() // // char blob_data[50]; // // for (unsigned int i = 0; i < 50; i++) // // { // // blob_data[i] = i + 10; // // std::cout << std::hex << std::setw(2) << (i + 10) << " "; // // } // // std::cout << std::endl; // // std::string blob = std::string(400, 41); // // client->Send((blob.c_str()), 401, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true); // // RakNet::Packet *packet; // // while (true) // // { // // packet = client->Receive(); // // while (packet) // // { // // printf("Data %s", packet->data); // // client->Send((const char *)&blob_data, 50, HIGH_PRIORITY, RELIABLE_SEQUENCED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // client->DeallocatePacket(packet); // // packet = client->Receive(); // // } // // packet = server->Receive(); // // while (packet) // // { // // printf("Data %s", packet->data); // // server->Send((const char *)&blob_data, (const int)strlen(blob_data), HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true); // // server->DeallocatePacket(packet); // // packet = server->Receive(); // // } // // packet = client->Receive(); // // while (packet) // // { // // printf("Data %s", packet->data); // // // server->Send((const char *)&blob_data, (const int)strlen(blob_data), HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // server->DeallocatePacket(packet); // // packet = server->Receive(); // // } // // } // printf("Last packet was: %p\n", packet); // RakNet::RakPeerInterface::DestroyInstance(server); // RakNet::RakPeerInterface::DestroyInstance(client); // return 0; // } // /* // * Copyright (c) 2014, Oculus VR, 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 "RakPeerInterface.h" // // #include "BitStream.h" // // #include <stdlib.h> // For atoi // // #include <cstring> // For strlen // // #include "Rand.h" // // #include "RakNetStatistics.h" // // #include "MessageIdentifiers.h" // // #include <stdio.h> // // #include "Kbhit.h" // // #include "GetTime.h" // // #include "RakAssert.h" // // #include "RakSleep.h" // // #include "Gets.h" // // using namespace RakNet; // // #ifdef _WIN32 // // #include "WindowsIncludes.h" // Sleep64 // // #else // // #include <unistd.h> // usleep // // #include <cstdio> // // #include "Getche.h" // // #endif // // static const int NUM_CLIENTS=100; // // #define SERVER_PORT 1234 // // #define RANDOM_DATA_SIZE_1 50 // // char randomData1[RANDOM_DATA_SIZE_1]; // // #define RANDOM_DATA_SIZE_2 100 // // char randomData2[RANDOM_DATA_SIZE_2]; // // char *remoteIPAddress=0; // // // Connects, sends data over time, disconnects, repeat // // // class Client // // { // // public: // // Client() // // { // // peer = RakNet::RakPeerInterface::GetInstance(); // // } // // ~Client() // // { // // RakNet::RakPeerInterface::DestroyInstance(peer); // // } // // void Startup(void) // // { // // RakNet::SocketDescriptor socketDescriptor; // // socketDescriptor.port=0; // // nextSendTime=0; // // StartupResult b = peer->Startup(1,&socketDescriptor,1); // // RakAssert(b==RAKNET_STARTED); // // isConnected=false; // // } // // void Connect(void) // // { // // bool b; // // b=peer->Connect(remoteIPAddress, (unsigned short) SERVER_PORT, 0, 0, 0)==RakNet::CONNECTION_ATTEMPT_STARTED; // // if (b==false) // // { // // printf("Client connect call failed!\n"); // // } // // } // // void Disconnect(void) // // { // // peer->CloseConnection(peer->GetSystemAddressFromIndex(0),true,0); // // isConnected=false; // // } // // void Update(RakNet::TimeMS curTime) // // { // // Packet *p = peer->Receive(); // // while (p) // // { // // switch (p->data[0]) // // { // // case ID_CONNECTION_REQUEST_ACCEPTED: // // printf("ID_CONNECTION_REQUEST_ACCEPTED\n"); // // isConnected=true; // // break; // // // print out errors // // case ID_CONNECTION_ATTEMPT_FAILED: // // printf("Client Error: ID_CONNECTION_ATTEMPT_FAILED\n"); // // isConnected=false; // // break; // // case ID_ALREADY_CONNECTED: // // printf("Client Error: ID_ALREADY_CONNECTED\n"); // // break; // // case ID_CONNECTION_BANNED: // // printf("Client Error: ID_CONNECTION_BANNED\n"); // // break; // // case ID_INVALID_PASSWORD: // // printf("Client Error: ID_INVALID_PASSWORD\n"); // // break; // // case ID_INCOMPATIBLE_PROTOCOL_VERSION: // // printf("Client Error: ID_INCOMPATIBLE_PROTOCOL_VERSION\n"); // // break; // // case ID_NO_FREE_INCOMING_CONNECTIONS: // // printf("Client Error: ID_NO_FREE_INCOMING_CONNECTIONS\n"); // // isConnected=false; // // break; // // case ID_DISCONNECTION_NOTIFICATION: // // //printf("ID_DISCONNECTION_NOTIFICATION\n"); // // isConnected=false; // // break; // // case ID_CONNECTION_LOST: // // printf("Client Error: ID_CONNECTION_LOST\n"); // // isConnected=false; // // break; // // } // // peer->DeallocatePacket(p); // // p = peer->Receive(); // // } // // if (curTime>nextSendTime && isConnected) // // { // // if (randomMT()%10==0) // // { // // peer->Send((const char*)&randomData2,RANDOM_DATA_SIZE_2,HIGH_PRIORITY,RELIABLE_ORDERED,0,RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // } // // else // // { // // peer->Send((const char*)&randomData1,RANDOM_DATA_SIZE_1,HIGH_PRIORITY,RELIABLE_ORDERED,0,RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // } // // nextSendTime=curTime+50; // // } // // } // // bool isConnected; // // RakPeerInterface *peer; // // RakNet::TimeMS nextSendTime; // // }; // // // Just listens for ID_USER_PACKET_ENUM and validates its integrity // // class Server // // { // // public: // // Server() // // { // // peer = RakNet::RakPeerInterface::GetInstance(); // // nextSendTime=0; // // } // // ~Server() // // { // // RakNet::RakPeerInterface::DestroyInstance(peer); // // } // // void Start(void) // // { // // RakNet::SocketDescriptor socketDescriptor; // // socketDescriptor.port=(unsigned short) SERVER_PORT; // // bool b = peer->Startup((unsigned short) 600,&socketDescriptor,1)==RakNet::RAKNET_STARTED; // // RakAssert(b); // // peer->SetMaximumIncomingConnections(600); // // } // // unsigned ConnectionCount(void) const // // { // // unsigned short numberOfSystems; // // peer->GetConnectionList(0,&numberOfSystems); // // return numberOfSystems; // // } // // void Update(RakNet::TimeMS curTime) // // { // // Packet *p = peer->Receive(); // // while (p) // // { // // switch (p->data[0]) // // { // // case ID_CONNECTION_LOST: // // case ID_DISCONNECTION_NOTIFICATION: // // case ID_NEW_INCOMING_CONNECTION: // // printf("Connections = %i\n", ConnectionCount()); // // break; // // // case ID_USER_PACKET_ENUM: // // // { // // // peer->Send((const char*) p->data, p->length, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->guid, true); // // // break; // // // } // // } // // peer->DeallocatePacket(p); // // p = peer->Receive(); // // } // // if (curTime>nextSendTime) // // { // // if (randomMT()%10==0) // // { // // peer->Send((const char*)&randomData2,RANDOM_DATA_SIZE_2,HIGH_PRIORITY,RELIABLE_ORDERED,0,RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // } // // else // // { // // peer->Send((const char*)&randomData1,RANDOM_DATA_SIZE_1,HIGH_PRIORITY,RELIABLE_ORDERED,0,RakNet::UNASSIGNED_SYSTEM_ADDRESS,true); // // } // // nextSendTime=curTime+100; // // } // // } // // RakNet::TimeMS nextSendTime; // // RakPeerInterface *peer; // // }; // // int main(void) // // { // // Client clients[NUM_CLIENTS]; // // Server server; // // // int clientIndex; // // int mode; // // printf("Connects many clients to a single server.\n"); // // printf("Difficulty: Intermediate\n\n"); // // printf("Run as (S)erver or (C)lient or (B)oth? "); // // char ch = getche(); // // static char *defaultRemoteIP="127.0.0.1"; // // char remoteIP[128]; // // static char *localIP="127.0.0.1"; // // if (ch=='s' || ch=='S') // // { // // mode=0; // // } // // else if (ch=='c' || ch=='c') // // { // // mode=1; // // remoteIPAddress=remoteIP; // // } // // else // // { // // mode=2; // // remoteIPAddress=localIP; // // } // // printf("\n"); // // if (mode==1 || mode==2) // // { // // printf("Enter remote IP: "); // // Gets(remoteIP, sizeof(remoteIP)); // // if (remoteIP[0]==0) // // { // // strcpy(remoteIP, defaultRemoteIP); // // printf("Using %s\n", defaultRemoteIP); // // } // // } // // unsigned i; // // randomData1[0]=(char) ID_USER_PACKET_ENUM; // // for (i=0; i < RANDOM_DATA_SIZE_1-1; i++) // // randomData1[i+1]=i; // // randomData2[0]=(char) ID_USER_PACKET_ENUM; // // for (i=0; i < RANDOM_DATA_SIZE_2-1; i++) // // randomData2[i+1]=i; // // if (mode==0 || mode==2) // // { // // server.Start(); // // printf("Started server\n"); // // } // // if (mode==1 || mode==2) // // { // // printf("Starting clients...\n"); // // for (i=0; i < NUM_CLIENTS; i++) // // clients[i].Startup(); // // printf("Started clients\n"); // // printf("Connecting clients...\n"); // // for (i=0; i < NUM_CLIENTS; i++) // // clients[i].Connect(); // // printf("Done.\n"); // // } // // RakNet::TimeMS endTime = RakNet::GetTimeMS()+60000*5; // // RakNet::TimeMS time = RakNet::GetTimeMS(); // // while (time < endTime) // // { // // if (mode==0 || mode==2) // // server.Update(time); // // if (mode==1 || mode==2) // // { // // for (i=0; i < NUM_CLIENTS; i++) // // clients[i].Update(time); // // } // // if (kbhit()) // // { // // char ch = getch(); // // if (ch==' ') // // { // // FILE *fp; // // char text[2048]; // // if (mode==0 || mode==2) // // { // // printf("Logging server statistics to ServerStats.txt\n"); // // fp=fopen("ServerStats.txt","wt"); // // for (i=0; i < NUM_CLIENTS; i++) // // { // // RakNetStatistics *rssSender; // // rssSender=server.peer->GetStatistics(server.peer->GetSystemAddressFromIndex(i)); // // StatisticsToString(rssSender, text, 3); // // fprintf(fp,"==== System %i ====\n", i+1); // // fprintf(fp,"%s\n\n", text); // // } // // fclose(fp); // // } // // if (mode==1 || mode==2) // // { // // printf("Logging client statistics to ClientStats.txt\n"); // // fp=fopen("ClientStats.txt","wt"); // // for (i=0; i < NUM_CLIENTS; i++) // // { // // RakNetStatistics *rssSender; // // rssSender=clients[i].peer->GetStatistics(clients[i].peer->GetSystemAddressFromIndex(0)); // // StatisticsToString(rssSender, text, 3); // // fprintf(fp,"==== Client %i ====\n", i+1); // // fprintf(fp,"%s\n\n", text); // // } // // fclose(fp); // // } // // } // // if (ch=='q' || ch==0) // // break; // // } // // time = RakNet::GetTimeMS(); // // RakSleep(30); // // } // // if (mode==0 || mode==2) // // server.peer->Shutdown(0); // // if (mode==1 || mode==2) // // for (i=0; i < NUM_CLIENTS; i++) // // clients[i].peer->Shutdown(0); // // printf("Test completed"); // // return 0; // // }
32.874263
166
0.541804
MlsDmitry
512d3ec39e3fa15402e93f461609be030e11f815
7,821
cc
C++
benchmarks/benchmark.cc
jlquinn/intgemm
a56f8225c2ebade4a742b1e691514c7d6c9def3d
[ "MIT" ]
37
2018-06-25T07:08:05.000Z
2022-03-30T05:10:19.000Z
benchmarks/benchmark.cc
jlquinn/intgemm
a56f8225c2ebade4a742b1e691514c7d6c9def3d
[ "MIT" ]
50
2019-03-20T10:34:34.000Z
2022-03-30T16:49:10.000Z
benchmarks/benchmark.cc
jlquinn/intgemm
a56f8225c2ebade4a742b1e691514c7d6c9def3d
[ "MIT" ]
16
2018-10-10T11:58:32.000Z
2022-01-28T23:19:05.000Z
#include "../intgemm/aligned.h" #include "intgemm/intgemm_config.h" #include "../intgemm/avx512_gemm.h" #include "../intgemm/sse2_gemm.h" #include "../intgemm/avx2_gemm.h" #include "../intgemm/ssse3_gemm.h" #include "../intgemm/intgemm.h" #include "../intgemm/stats.h" #include "../intgemm/callbacks.h" #include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> #include <random> namespace intgemm { namespace { struct RandomMatrices { RandomMatrices(Index A_rows_in, Index width_in, Index B_cols_in) : A_rows(A_rows_in), width(width_in), B_cols(B_cols_in), A(A_rows * width), B(width * B_cols) { std::mt19937 gen; std::uniform_real_distribution<float> dist(-1.f, 1.f); gen.seed(45678); for (auto& it : A) { it = dist(gen); } for (auto& it : B) { it = dist(gen); } } const Index A_rows, width, B_cols; AlignedVector<float> A, B; }; template <class Backend> double Run(const RandomMatrices &m) { using Integer = typename Backend::Integer; float quant_mult = 127.0f / 2.0f; float unquant_mult = 1.0f / (quant_mult * quant_mult); AlignedVector<Integer> A_prepared(m.A_rows * m.width); Backend::PrepareA(m.A.begin(), A_prepared.begin(), quant_mult, m.A_rows, m.width); AlignedVector<Integer> B_prepared(m.width * m.B_cols); Backend::PrepareB(m.B.begin(), B_prepared.begin(), quant_mult, m.width, m.B_cols); AlignedVector<float> output(m.A_rows * m.B_cols); // Burn in Backend::Multiply(A_prepared.begin(), B_prepared.begin(), m.A_rows, m.width, m.B_cols, callbacks::UnquantizeAndWrite(unquant_mult, output.begin())); auto start = std::chrono::steady_clock::now(); Backend::Multiply(A_prepared.begin(), B_prepared.begin(), m.A_rows, m.width, m.B_cols, callbacks::UnquantizeAndWrite(unquant_mult, output.begin())); return std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count(); } template <class Backend> void RunAll(RandomMatrices *matrices, RandomMatrices *matrices_end, std::vector<std::vector<double>> &stats) { if (Backend::kUses > kCPU) return; std::size_t size = matrices_end - matrices; if (stats.size() < size) stats.resize(size); for (std::size_t i = 0; i < size; ++i) { stats[i].push_back(Run<Backend>(matrices[i])); } } struct BackendStats { std::vector<std::vector<double>> ssse3_8bit; std::vector<std::vector<double>> avx2_8bit; std::vector<std::vector<double>> avx512_8bit; std::vector<std::vector<double>> avx512vnni_8bit; std::vector<std::vector<double>> sse2_16bit; std::vector<std::vector<double>> avx2_16bit; std::vector<std::vector<double>> avx512_16bit; }; const float kOutlierThreshold = 0.75; void Summarize(std::vector<double> &stats) { // Throw out outliers. std::vector<double>::iterator keep = stats.begin() + static_cast<std::size_t>(static_cast<float>(stats.size()) * kOutlierThreshold); std::nth_element(stats.begin(), keep, stats.end()); double avg = 0.0; for (std::vector<double>::const_iterator i = stats.begin(); i != keep; ++i) { avg += *i; } avg /= (keep - stats.begin()); double stddev = 0.0; for (std::vector<double>::const_iterator i = stats.begin(); i != keep; ++i) { double off = (double)*i - avg; stddev += off * off; } stddev = sqrt(stddev / (keep - stats.begin() - 1)); std::cout << std::setw(10) << *std::min_element(stats.begin(), stats.end()) << '\t' << std::setw(8) << avg << '\t' << std::setw(8) << stddev; } template <class Backend> void Print(std::vector<std::vector<double>> &stats, std::size_t index) { if (stats.empty()) return; std::cout << std::setw(16) << Backend::kName << '\t'; Summarize(stats[index]); std::cout << '\n'; } } // namespace intgemm } // namespace // Program takes no input int main(int, char ** argv) { std::cerr << "Remember to run this on a specific core:\ntaskset --cpu-list 0 " << argv[0] << std::endl; using namespace intgemm; RandomMatrices matrices[] = { {1, 64, 8}, {8, 256, 256}, {8, 2048, 256}, {8, 256, 2048}, {320, 256, 256}, {472, 256, 256}, {248, 256, 256}, {200, 256, 256}, // Additional stuff {256, 256, 256}, {512, 512, 512}, {1024, 1024, 1024}, /* {4096, 4096, 4096}, {4096, 4096, 2048}, {4096, 4096, 1024}, {4096, 4096, 512}, {4096, 4096, 256},*/ {4096, 4096, 128} }; RandomMatrices *matrices_end = (RandomMatrices*)matrices + sizeof(matrices) / sizeof(RandomMatrices); // Only do full sampling for <1024 rows. RandomMatrices *full_sample; for (full_sample = matrices_end - 1; full_sample >= matrices && full_sample->A_rows >= 1024; --full_sample) {} ++full_sample; BackendStats stats; const int kSamples = 100; // Realistically, we don't expect different architectures or different precisions to run in the // same run of an application. Benchmark per architecture and per precision level. std::cerr << "SSSE3 8bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<SSSE3::Kernels8>(matrices, end, stats.ssse3_8bit); } std::cerr << "SSE2 16bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<SSE2::Kernels16>(matrices, end, stats.sse2_16bit); } #ifdef INTGEMM_COMPILER_SUPPORTS_AVX2 std::cerr << "AVX2 8bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX2::Kernels8>(matrices, end, stats.avx2_8bit); } std::cerr << "AVX2 16bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX2::Kernels16>(matrices, end, stats.avx2_16bit); } #endif #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW std::cerr << "AVX512 8bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX512BW::Kernels8>(matrices, end, stats.avx512_8bit); } std::cerr << "AVX512 16bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX512BW::Kernels16>(matrices, end, stats.avx512_16bit); } #endif #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512VNNI std::cerr << "AVX512VNNI 8bit, 100 samples..." << std::endl; for (int samples = 0; samples < kSamples; ++samples) { RandomMatrices *end = (samples < 4) ? matrices_end : full_sample; RunAll<AVX512VNNI::Kernels8>(matrices, end, stats.avx512vnni_8bit); } #endif if (stats.sse2_16bit.empty()) { std::cerr << "No CPU support." << std::endl; return 1; } for (std::size_t i = 0; i < sizeof(matrices) / sizeof(RandomMatrices); ++i) { std::cout << "Multiply\t" << matrices[i].A_rows << '\t' << matrices[i].width << '\t' << matrices[i].B_cols << '\t' << "Samples=" << (kOutlierThreshold * stats.sse2_16bit[i].size()) << '\n'; Print<SSSE3::Kernels8>(stats.ssse3_8bit, i); Print<AVX2::Kernels8>(stats.avx2_8bit, i); #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW Print<AVX512BW::Kernels8>(stats.avx512_8bit, i); #endif #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512VNNI Print<AVX512VNNI::Kernels8>(stats.avx512vnni_8bit, i); #endif Print<SSE2::Kernels16>(stats.sse2_16bit, i); Print<AVX2::Kernels16>(stats.avx2_16bit, i); #ifdef INTGEMM_COMPILER_SUPPORTS_AVX512BW Print<AVX512BW::Kernels16>(stats.avx512_16bit, i); #endif } return 0; }
36.376744
193
0.664749
jlquinn
512f0745860519e583a559b258a8aecc0b41b6a7
905
cpp
C++
mp32wav/tests/LittleBigEndian_Test.cpp
dissabte/mp32wav
6b3e8e08f94df0db84ff99fe4bdf5f6aa92c7cee
[ "MIT" ]
3
2018-03-26T03:54:14.000Z
2021-12-27T14:04:03.000Z
mp32wav/tests/LittleBigEndian_Test.cpp
dissabte/mp32wav
6b3e8e08f94df0db84ff99fe4bdf5f6aa92c7cee
[ "MIT" ]
null
null
null
mp32wav/tests/LittleBigEndian_Test.cpp
dissabte/mp32wav
6b3e8e08f94df0db84ff99fe4bdf5f6aa92c7cee
[ "MIT" ]
null
null
null
#include <UnitTest++/UnitTest++.h> #include "../src/LittleBigEndian.h" #include <cstring> SUITE(AudilFileTest) { TEST(LittleEndianTest) { const uint32_t testValue = 0x00AACCBB; LittleEndian<uint32_t> leValue; std::memcpy(leValue.bytes, &testValue, sizeof(uint32_t)); uint32_t leCheckValue = leValue; CHECK_EQUAL(leCheckValue, testValue); unsigned char buffer[4] = {0xAA, 0xBB, 0xCC, 0xDD}; leCheckValue = LittleEndian<uint32_t>::fromBuffer(buffer); CHECK_EQUAL(leCheckValue, 0xDDCCBBAA); } TEST(BigEndianTest) { const uint32_t testValue = 0x00AACCBB; BigEndian<uint32_t> beValue; std::memcpy(beValue.bytes, &testValue, sizeof(uint32_t)); uint32_t beCheckValue = beValue; CHECK_EQUAL(beCheckValue, 0xBBCCAA00); unsigned char buffer[4] = {0xAA, 0xBB, 0xCC, 0xDD}; beCheckValue = BigEndian<uint32_t>::fromBuffer(buffer); CHECK_EQUAL(beCheckValue, 0xAABBCCDD); } }
25.857143
60
0.740331
dissabte
5130edb3dd55fe64a3752239e9d9ca4d6f82a649
10,497
cc
C++
unittests/libtests/meshio/TestMeshIO.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
1
2021-09-09T06:24:11.000Z
2021-09-09T06:24:11.000Z
unittests/libtests/meshio/TestMeshIO.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
unittests/libtests/meshio/TestMeshIO.cc
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "TestMeshIO.hh" // Implementation of class methods #include "pylith/topology/Mesh.hh" // USES Mesh #include "pylith/topology/MeshOps.hh" // USES MeshOps::nondimensionalize() #include "pylith/topology/Stratum.hh" // USES Stratum #include "pylith/topology/CoordsVisitor.hh" // USES CoordsVisitor #include "pylith/meshio/MeshIO.hh" // USES MeshIO #include "pylith/utils/array.hh" // USES int_array #include "data/MeshData.hh" #include "spatialdata/geocoords/CSCart.hh" // USES CSCart #include "spatialdata/units/Nondimensional.hh" // USES Nondimensional #include <strings.h> // USES strcasecmp() #include <stdexcept> // USES std::logic_error // ---------------------------------------------------------------------- // Setup testing data. void pylith::meshio::TestMeshIO::setUp(void) { // setUp PYLITH_METHOD_BEGIN; _mesh = 0; PYLITH_METHOD_END; } // setUp // ---------------------------------------------------------------------- // Tear down testing data. void pylith::meshio::TestMeshIO::tearDown(void) { // tearDown PYLITH_METHOD_BEGIN; delete _mesh; _mesh = 0; PYLITH_METHOD_END; } // tearDown // ---------------------------------------------------------------------- // Get simple mesh for testing I/O. void pylith::meshio::TestMeshIO::_createMesh(const MeshData& data) { // _createMesh PYLITH_METHOD_BEGIN; // buildTopology() requires zero based index CPPUNIT_ASSERT_EQUAL(true, data.useIndexZero); CPPUNIT_ASSERT(data.vertices); CPPUNIT_ASSERT(data.cells); CPPUNIT_ASSERT(data.materialIds); if (data.numGroups > 0) { CPPUNIT_ASSERT(data.groups); CPPUNIT_ASSERT(data.groupSizes); CPPUNIT_ASSERT(data.groupNames); CPPUNIT_ASSERT(data.groupTypes); } // if delete _mesh; _mesh = new topology::Mesh(data.cellDim);CPPUNIT_ASSERT(_mesh); // Cells and vertices const bool interpolate = false; PetscDM dmMesh = NULL; PetscBool interpolateMesh = interpolate ? PETSC_TRUE : PETSC_FALSE; PetscInt bound = data.numCells*data.numCorners; PetscErrorCode err; int *cells = new int[bound]; for (PetscInt coff = 0; coff < bound; ++coff) {cells[coff] = data.cells[coff];} for (PetscInt coff = 0; coff < bound; coff += data.numCorners) { err = DMPlexInvertCell(data.cellDim, data.numCorners, &cells[coff]);PYLITH_CHECK_ERROR(err); } err = DMPlexCreateFromCellList(_mesh->comm(), data.cellDim, data.numCells, data.numVertices, data.numCorners, interpolateMesh, cells, data.spaceDim, data.vertices, &dmMesh);PYLITH_CHECK_ERROR(err); delete [] cells; _mesh->dmMesh(dmMesh); // Material ids PetscInt cStart, cEnd; err = DMPlexGetHeightStratum(dmMesh, 0, &cStart, &cEnd);PYLITH_CHECK_ERROR(err); for(PetscInt c = cStart; c < cEnd; ++c) { err = DMSetLabelValue(dmMesh, "material-id", c, data.materialIds[c-cStart]);PYLITH_CHECK_ERROR(err); } // for // Groups for (int iGroup=0, index=0; iGroup < data.numGroups; ++iGroup) { err = DMCreateLabel(dmMesh, data.groupNames[iGroup]);PYLITH_CHECK_ERROR(err); MeshIO::GroupPtType type; const int numPoints = data.groupSizes[iGroup]; if (0 == strcasecmp("cell", data.groupTypes[iGroup])) { type = MeshIO::CELL; for(int i=0; i < numPoints; ++i, ++index) { err = DMSetLabelValue(dmMesh, data.groupNames[iGroup], data.groups[index], 1);PYLITH_CHECK_ERROR(err); } // for } else if (0 == strcasecmp("vertex", data.groupTypes[iGroup])) { type = MeshIO::VERTEX; PetscInt numCells; err = DMPlexGetHeightStratum(dmMesh, 0, NULL, &numCells);PYLITH_CHECK_ERROR(err); for(int i=0; i < numPoints; ++i, ++index) { err = DMSetLabelValue(dmMesh, data.groupNames[iGroup], data.groups[index]+numCells, 1);PYLITH_CHECK_ERROR(err); } // for } else throw std::logic_error("Could not parse group type."); } // for // Set coordinate system spatialdata::geocoords::CSCart cs; cs.setSpaceDim(data.spaceDim); cs.initialize(); _mesh->coordsys(&cs); spatialdata::units::Nondimensional normalizer; normalizer.lengthScale(10.0); topology::MeshOps::nondimensionalize(_mesh, normalizer); PYLITH_METHOD_END; } // _createMesh // ---------------------------------------------------------------------- // Check values in mesh against data. void pylith::meshio::TestMeshIO::_checkVals(const MeshData& data) { // _checkVals PYLITH_METHOD_BEGIN; CPPUNIT_ASSERT(_mesh); // Check mesh dimension CPPUNIT_ASSERT_EQUAL(data.cellDim, _mesh->dimension()); const int spaceDim = data.spaceDim; PetscDM dmMesh = _mesh->dmMesh();CPPUNIT_ASSERT(dmMesh); // Check vertices topology::Stratum verticesStratum(dmMesh, topology::Stratum::DEPTH, 0); const PetscInt vStart = verticesStratum.begin(); const PetscInt vEnd = verticesStratum.end(); CPPUNIT_ASSERT_EQUAL(data.numVertices, verticesStratum.size()); topology::CoordsVisitor coordsVisitor(dmMesh); const PetscScalar* coordsArray = coordsVisitor.localArray(); const PylithScalar tolerance = 1.0e-06; for (PetscInt v = vStart, index = 0; v < vEnd; ++v) { const PetscInt off = coordsVisitor.sectionOffset(v); CPPUNIT_ASSERT_EQUAL(spaceDim, coordsVisitor.sectionDof(v)); for (int iDim=0; iDim < spaceDim; ++iDim, ++index) { if (data.vertices[index] < 1.0) { CPPUNIT_ASSERT_DOUBLES_EQUAL(data.vertices[index], coordsArray[off+iDim], tolerance); } else { CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0, coordsArray[off+iDim]/data.vertices[index], tolerance); } // if/else } // for } // for // Check cells topology::Stratum cellsStratum(dmMesh, topology::Stratum::HEIGHT, 0); const PetscInt cStart = cellsStratum.begin(); const PetscInt cEnd = cellsStratum.end(); const PetscInt numCells = cellsStratum.size(); CPPUNIT_ASSERT_EQUAL(data.numCells, numCells); const int offset = numCells; PetscErrorCode err = 0; for(PetscInt c = cStart, index = 0; c < cEnd; ++c) { PetscInt *closure = PETSC_NULL; PetscInt closureSize, numCorners = 0; err = DMPlexGetTransitiveClosure(dmMesh, c, PETSC_TRUE, &closureSize, &closure);PYLITH_CHECK_ERROR(err); for(PetscInt p = 0; p < closureSize*2; p += 2) { const PetscInt point = closure[p]; if ((point >= vStart) && (point < vEnd)) { closure[numCorners++] = point; } // if } // for err = DMPlexInvertCell(data.cellDim, numCorners, closure);PYLITH_CHECK_ERROR(err); CPPUNIT_ASSERT_EQUAL(data.numCorners, numCorners); for(PetscInt p = 0; p < numCorners; ++p, ++index) { CPPUNIT_ASSERT_EQUAL(data.cells[index], closure[p]-offset); } // for err = DMPlexRestoreTransitiveClosure(dmMesh, c, PETSC_TRUE, &closureSize, &closure);PYLITH_CHECK_ERROR(err); } // for // check materials PetscInt matId = 0; for(PetscInt c = cStart; c < cEnd; ++c) { err = DMGetLabelValue(dmMesh, "material-id", c, &matId);PYLITH_CHECK_ERROR(err); CPPUNIT_ASSERT_EQUAL(data.materialIds[c-cStart], matId); } // for // Check groups PetscInt numGroups, pStart, pEnd; err = DMPlexGetChart(dmMesh, &pStart, &pEnd);PYLITH_CHECK_ERROR(err); err = DMGetNumLabels(dmMesh, &numGroups);PYLITH_CHECK_ERROR(err); numGroups -= 2; // Remove depth and material labels. CPPUNIT_ASSERT_EQUAL(data.numGroups, numGroups); PetscInt index = 0; for(PetscInt iGroup = 0, iLabel = numGroups-1; iGroup < numGroups; ++iGroup, --iLabel) { const char *name = NULL; PetscInt firstPoint = 0; err = DMGetLabelName(dmMesh, iLabel, &name);PYLITH_CHECK_ERROR(err); CPPUNIT_ASSERT_EQUAL(std::string(data.groupNames[iGroup]), std::string(name)); for(PetscInt p = pStart; p < pEnd; ++p) { PetscInt val; err = DMGetLabelValue(dmMesh, name, p, &val);PYLITH_CHECK_ERROR(err); if (val >= 0) { firstPoint = p; break; } // if } // for std::string groupType = (firstPoint >= cStart && firstPoint < cEnd) ? "cell" : "vertex"; CPPUNIT_ASSERT_EQUAL(std::string(data.groupTypes[iGroup]), groupType); PetscInt numPoints, numVertices = 0; err = DMGetStratumSize(dmMesh, name, 1, &numPoints);PYLITH_CHECK_ERROR(err); PetscIS pointIS = NULL; const PetscInt *points = NULL; const PetscInt offset = ("vertex" == groupType) ? numCells : 0; err = DMGetStratumIS(dmMesh, name, 1, &pointIS);PYLITH_CHECK_ERROR(err); err = ISGetIndices(pointIS, &points);PYLITH_CHECK_ERROR(err); for(PetscInt p = 0; p < numPoints; ++p) { const PetscInt pStart = ("vertex" == groupType) ? vStart : cStart; const PetscInt pEnd = ("vertex" == groupType) ? vEnd : cEnd; if ((points[p] >= pStart) && (points[p] < pEnd)) { CPPUNIT_ASSERT_EQUAL(data.groups[index++], points[p]-offset); ++numVertices; } } // for CPPUNIT_ASSERT_EQUAL(data.groupSizes[iGroup], numVertices); err = ISRestoreIndices(pointIS, &points);PYLITH_CHECK_ERROR(err); err = ISDestroy(&pointIS);PYLITH_CHECK_ERROR(err); } // for PYLITH_METHOD_END; } // _checkVals // ---------------------------------------------------------------------- // Test debug() void pylith::meshio::TestMeshIO::_testDebug(MeshIO& iohandler) { // _testDebug PYLITH_METHOD_BEGIN; bool debug = false; iohandler.debug(debug); CPPUNIT_ASSERT_EQUAL(debug, iohandler.debug()); debug = true; iohandler.debug(debug); CPPUNIT_ASSERT_EQUAL(debug, iohandler.debug()); PYLITH_METHOD_END; } // _testDebug // ---------------------------------------------------------------------- // Test interpolate() void pylith::meshio::TestMeshIO::_testInterpolate(MeshIO& iohandler) { // _testInterpolate PYLITH_METHOD_BEGIN; bool interpolate = false; iohandler.interpolate(interpolate); CPPUNIT_ASSERT_EQUAL(interpolate, iohandler.interpolate()); interpolate = true; iohandler.interpolate(interpolate); CPPUNIT_ASSERT_EQUAL(interpolate, iohandler.interpolate()); PYLITH_METHOD_END; } // _testInterpolate // End of file
34.758278
199
0.656187
joegeisz
51382e19cbcbdfcb6b312e8d57c035f52a61d321
21,914
hpp
C++
unit_test/tstGridOperator3d.hpp
abisner/picasso
06c1ae58e75f7da4c3eb2421c3297e5258c2ad90
[ "BSD-3-Clause" ]
null
null
null
unit_test/tstGridOperator3d.hpp
abisner/picasso
06c1ae58e75f7da4c3eb2421c3297e5258c2ad90
[ "BSD-3-Clause" ]
null
null
null
unit_test/tstGridOperator3d.hpp
abisner/picasso
06c1ae58e75f7da4c3eb2421c3297e5258c2ad90
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2021 by the Picasso authors * * All rights reserved. * * * * This file is part of the Picasso library. Picasso is distributed under a * * BSD 3-clause license. For the licensing terms see the LICENSE file in * * the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <Picasso_FieldManager.hpp> #include <Picasso_FieldTypes.hpp> #include <Picasso_GridOperator.hpp> #include <Picasso_InputParser.hpp> #include <Picasso_ParticleInit.hpp> #include <Picasso_ParticleInterpolation.hpp> #include <Picasso_ParticleList.hpp> #include <Picasso_Types.hpp> #include <Cajita.hpp> #include <Cabana_Core.hpp> #include <Kokkos_Core.hpp> #include <gtest/gtest.h> using namespace Picasso; namespace Test { //---------------------------------------------------------------------------// // Field tags. struct FooP : Field::Vector<double, 3> { static std::string label() { return "foo_p"; } }; struct FooIn : Field::Vector<double, 3> { static std::string label() { return "foo_in"; } }; struct FezIn : Field::Vector<double, 3> { static std::string label() { return "fez_in"; } }; struct FooOut : Field::Vector<double, 3> { static std::string label() { return "foo_out"; } }; struct BarP : Field::Scalar<double> { static std::string label() { return "bar_p"; } }; struct BarIn : Field::Scalar<double> { static std::string label() { return "bar_in"; } }; struct BarOut : Field::Scalar<double> { static std::string label() { return "bar_out"; } }; struct Baz : Field::Matrix<double, 3, 3> { static std::string label() { return "baz"; } }; struct MatI : Field::Matrix<double, 3, 3> { static std::string label() { return "mat_I"; } }; struct MatJ : Field::Matrix<double, 3, 3> { static std::string label() { return "mat_J"; } }; struct MatK : Field::Matrix<double, 3, 3> { static std::string label() { return "mat_K"; } }; struct Boo : Field::Tensor3<double, 3, 3, 3> { static std::string label() { return "boo"; } }; struct Cam : Field::Tensor4<double, 3, 3, 3, 3> { static std::string label() { return "cam"; } }; //---------------------------------------------------------------------------// // Particle operation. struct ParticleFunc { template <class LocalMeshType, class GatherDependencies, class ScatterDependencies, class LocalDependencies, class ParticleViewType> KOKKOS_INLINE_FUNCTION void operator()( const LocalMeshType& local_mesh, const GatherDependencies& gather_deps, const ScatterDependencies& scatter_deps, const LocalDependencies&, ParticleViewType& particle ) const { // Get input dependencies. auto foo_in = gather_deps.get( FieldLocation::Cell(), FooIn() ); auto bar_in = gather_deps.get( FieldLocation::Cell(), BarIn() ); // Get output dependencies. auto foo_out = scatter_deps.get( FieldLocation::Cell(), FooOut() ); auto bar_out = scatter_deps.get( FieldLocation::Cell(), BarOut() ); // Get particle data. auto foop = get( particle, FooP() ); auto& barp = get( particle, BarP() ); // Zero-order cell interpolant. auto spline = createSpline( FieldLocation::Cell(), InterpolationOrder<0>(), local_mesh, get( particle, Field::LogicalPosition<3>() ), SplineValue() ); // Interpolate to the particles. G2P::value( spline, foo_in, foop ); G2P::value( spline, bar_in, barp ); // Interpolate back to the grid. P2G::value( spline, foop, foo_out ); P2G::value( spline, barp, bar_out ); } }; //---------------------------------------------------------------------------// // Grid operation. struct GridFunc { struct Tag { }; template <class LocalMeshType, class GatherDependencies, class ScatterDependencies, class LocalDependencies> KOKKOS_INLINE_FUNCTION void operator()( Tag, const LocalMeshType&, const GatherDependencies& gather_deps, const ScatterDependencies& scatter_deps, const LocalDependencies& local_deps, const int i, const int j, const int k ) const { // Get input dependencies. auto foo_in = gather_deps.get( FieldLocation::Cell(), FooIn() ); auto bar_in = gather_deps.get( FieldLocation::Cell(), BarIn() ); // Get output dependencies. auto foo_out = scatter_deps.get( FieldLocation::Cell(), FooOut() ); auto bar_out = scatter_deps.get( FieldLocation::Cell(), BarOut() ); // Get scatter view accessors. auto foo_out_access = foo_out.access(); auto bar_out_access = bar_out.access(); // Get local dependencies. auto baz = local_deps.get( FieldLocation::Cell(), Baz() ); // Set up the local dependency to be the identity. baz( i, j, k ) = { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } }; // Assign foo_out - build a point-wise expression to do this. Test out // both separate index and array-based indices. const int index[3] = { i, j, k }; auto baz_t_foo_in_t_2 = baz( index ) * ( foo_in( index ) + foo_in( i, j, k ) ); for ( int d = 0; d < 3; ++d ) foo_out_access( i, j, k, d ) += baz_t_foo_in_t_2( d ) + i + j + k; // Assign the bar_out - use mixture of field dimension indices // or direct ijk access. bar_out_access( i, j, k, 0 ) += bar_in( i, j, k, 0 ) + bar_in( i, j, k ) + i + j + k; } }; //---------------------------------------------------------------------------// // Grid operation using a Tensor3 struct GridTensor3Func { struct Tag { }; template <class LocalMeshType, class GatherDependencies, class ScatterDependencies, class LocalDependencies> KOKKOS_INLINE_FUNCTION void operator()( Tag, const LocalMeshType&, const GatherDependencies& gather_deps, const ScatterDependencies& scatter_deps, const LocalDependencies& local_deps, const int i, const int j, const int k ) const { // Get input dependencies auto foo_in = gather_deps.get( FieldLocation::Cell(), FooIn() ); auto fez_in = gather_deps.get( FieldLocation::Cell(), FezIn() ); // Get output dependencies auto foo_out = scatter_deps.get( FieldLocation::Cell(), FooOut() ); auto foo_out_access = foo_out.access(); // Get local dependencies auto boo = local_deps.get( FieldLocation::Cell(), Boo() ); auto mat_i_out = local_deps.get( FieldLocation::Cell(), MatI() ); auto mat_j_out = local_deps.get( FieldLocation::Cell(), MatJ() ); auto mat_k_out = local_deps.get( FieldLocation::Cell(), MatK() ); foo_in( i, j, k, 0 ) = 1.0; foo_in( i, j, k, 1 ) = 2.0; foo_in( i, j, k, 2 ) = 3.0; fez_in( i, j, k, 0 ) = 3.0; fez_in( i, j, k, 1 ) = 4.0; fez_in( i, j, k, 2 ) = 3.0; // Set up the local dependency to be the Levi-Civita tensor. Picasso::LinearAlgebra::Tensor3<double, 3, 3, 3> levi_civita; Picasso::LinearAlgebra::permutation( levi_civita ); boo( i, j, k ) = levi_civita; const int index[3] = { i, j, k }; auto boo_t_foo_in = LinearAlgebra::contract( boo( index ), foo_in( index ), SpaceDim<2>{} ); auto boo_t_foo_in_t_fez_in = boo_t_foo_in * fez_in( index ); for ( int d = 0; d < 3; ++d ) { foo_out_access( i, j, k, d ) += boo_t_foo_in_t_fez_in( d ); } // Now test contraction along the other dimensions of a Tensor3 Picasso::LinearAlgebra::Tensor3<double, 3, 3, 3> tensor = { { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } }, { { 9, 10, 11 }, { 12, 13, 14 }, { 15, 16, 17 } }, { { 18, 19, 20 }, { 21, 22, 23 }, { 24, 25, 26 } } }; mat_i_out( index ) = LinearAlgebra::contract( tensor, foo_in( index ), SpaceDim<0>() ); mat_j_out( index ) = LinearAlgebra::contract( tensor, foo_in( index ), SpaceDim<1>() ); mat_k_out( index ) = LinearAlgebra::contract( tensor, foo_in( index ), SpaceDim<2>() ); } }; // Grid operation using a Tensor4 struct GridTensor4Func { struct Tag { }; template <class LocalMeshType, class GatherDependencies, class ScatterDependencies, class LocalDependencies> KOKKOS_INLINE_FUNCTION void operator()( Tag, const LocalMeshType&, const GatherDependencies& gather_deps, const ScatterDependencies& scatter_deps, const LocalDependencies& local_deps, const int i, const int j, const int k ) const { // // Get input dependencies auto foo_in = gather_deps.get( FieldLocation::Cell(), FooIn() ); auto fez_in = gather_deps.get( FieldLocation::Cell(), FezIn() ); // Get output dependencies auto foo_out = scatter_deps.get( FieldLocation::Cell(), FooOut() ); auto foo_out_access = foo_out.access(); // Get local dependencies auto cam = local_deps.get( FieldLocation::Cell(), Cam() ); auto baz_out = local_deps.get( FieldLocation::Cell(), Baz() ); // Set up the local dependency to be the linear elasticity tensor // (3x3x3x3) double mu = 1; double lam = 0.5; cam( i, j, k ) = { { { { lam + 2 * mu, 0.0, 0.0 }, { 0.0, lam, 0.0 }, { 0.0, 0.0, lam } }, { { 0.0, mu, 0.0 }, { mu, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } }, { { 0.0, 0.0, mu }, { 0.0, 0.0, 0.0 }, { mu, 0.0, 0.0 } } }, { { { 0.0, mu, 0.0 }, { mu, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } }, { { lam, 0.0, 0.0 }, { 0.0, lam + 2 * mu, 0.0 }, { 0.0, 0.0, lam } }, { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, mu }, { 0.0, mu, 0.0 } } }, { { { 0.0, 0.0, mu }, { 0.0, 0.0, 0.0 }, { mu, 0.0, 0.0 } }, { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, mu }, { 0.0, mu, 0.0 } }, { { lam, 0.0, 0.0 }, { 0.0, lam, 0.0 }, { 0.0, 0.0, lam + 2 * mu } } } }; Picasso::Mat3<double> strain = { { 0.5, 1.0, 0 }, { 1.0, 0, 0 }, { 0, 0, 0 } }; const int index[3] = { i, j, k }; // This operation represents a stress tensor evaluation from the // "generalized" Hook's law, which is just a double contraction of a // fourth-order stiffness tensor with a strain tensor. baz_out is the // stress tensor in this example baz_out( index ) = LinearAlgebra::contract( cam( index ), strain ); } }; //---------------------------------------------------------------------------// void gatherScatterTest() { // Global bounding box. double cell_size = 0.23; std::array<int, 3> global_num_cell = { 43, 32, 39 }; std::array<double, 3> global_low_corner = { 1.2, 3.3, -2.8 }; std::array<double, 3> global_high_corner = { global_low_corner[0] + cell_size * global_num_cell[0], global_low_corner[1] + cell_size * global_num_cell[1], global_low_corner[2] + cell_size * global_num_cell[2] }; // Get inputs for mesh. InputParser parser( "particle_init_test.json", "json" ); Kokkos::Array<double, 6> global_box = { global_low_corner[0], global_low_corner[1], global_low_corner[2], global_high_corner[0], global_high_corner[1], global_high_corner[2] }; int minimum_halo_size = 0; // Make mesh. auto mesh = createUniformMesh( TEST_MEMSPACE(), parser.propertyTree(), global_box, minimum_halo_size, MPI_COMM_WORLD ); // Make a particle list. using list_type = ParticleList<UniformMesh<TEST_MEMSPACE>, Field::LogicalPosition<3>, FooP, BarP>; list_type particles( "test_particles", mesh ); using particle_type = typename list_type::particle_type; // Particle initialization functor. Make particles everywhere. auto particle_init_func = KOKKOS_LAMBDA( const double x[3], const double, particle_type& p ) { for ( int d = 0; d < 3; ++d ) get( p, Field::LogicalPosition<3>(), d ) = x[d]; return true; }; // Initialize particles. int ppc = 10; initializeParticles( InitRandom(), TEST_EXECSPACE(), ppc, particle_init_func, particles ); // Make an operator. using gather_deps = GatherDependencies<FieldLayout<FieldLocation::Cell, FooIn>, FieldLayout<FieldLocation::Cell, FezIn>, FieldLayout<FieldLocation::Cell, BarIn>>; using scatter_deps = ScatterDependencies<FieldLayout<FieldLocation::Cell, FooOut>, FieldLayout<FieldLocation::Cell, BarOut>>; using local_deps = LocalDependencies<FieldLayout<FieldLocation::Cell, Baz>, FieldLayout<FieldLocation::Cell, Boo>, FieldLayout<FieldLocation::Cell, Cam>, FieldLayout<FieldLocation::Cell, MatI>, FieldLayout<FieldLocation::Cell, MatJ>, FieldLayout<FieldLocation::Cell, MatK>>; auto grid_op = createGridOperator( mesh, gather_deps(), scatter_deps(), local_deps() ); // Make a field manager. auto fm = createFieldManager( mesh ); // Setup the field manager. grid_op->setup( *fm ); // Initialize gather fields. Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FooIn() ), 2.0 ); Kokkos::deep_copy( fm->view( FieldLocation::Cell(), BarIn() ), 3.0 ); // Initialize scatter fields to wrong data to make sure they get reset to // zero and then overwritten with the data we assign in the operator. Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FooOut() ), -1.1 ); Kokkos::deep_copy( fm->view( FieldLocation::Cell(), BarOut() ), -2.2 ); // Apply the particle operator. ParticleFunc particle_func; grid_op->apply( "particle_op", FieldLocation::Particle(), TEST_EXECSPACE(), *fm, particles, particle_func ); // Check the particle results. auto host_aosoa = Cabana::create_mirror_view_and_copy( Kokkos::HostSpace(), particles.aosoa() ); auto foo_p_host = Cabana::slice<1>( host_aosoa ); auto bar_p_host = Cabana::slice<2>( host_aosoa ); for ( std::size_t p = 0; p < particles.size(); ++p ) { for ( int d = 0; d < 3; ++d ) EXPECT_EQ( foo_p_host( p, d ), 2.0 ); EXPECT_EQ( bar_p_host( p ), 3.0 ); } // Check the grid results. auto foo_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), FooOut() ) ); auto bar_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), BarOut() ) ); Cajita::grid_parallel_for( "check_grid_out", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { for ( int d = 0; d < 3; ++d ) EXPECT_EQ( foo_out_host( i, j, k, d ), ppc * 2.0 ); EXPECT_EQ( bar_out_host( i, j, k, 0 ), ppc * 3.0 ); } ); // Apply the grid operator. Use a tag. GridFunc grid_func; grid_op->apply( "grid_op", FieldLocation::Cell(), TEST_EXECSPACE(), *fm, GridFunc::Tag(), grid_func ); // Check the grid results. Kokkos::deep_copy( foo_out_host, fm->view( FieldLocation::Cell(), FooOut() ) ); Kokkos::deep_copy( bar_out_host, fm->view( FieldLocation::Cell(), BarOut() ) ); Cajita::grid_parallel_for( "check_grid_out", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { for ( int d = 0; d < 3; ++d ) EXPECT_EQ( foo_out_host( i, j, k, d ), 4.0 + i + j + k ); EXPECT_EQ( bar_out_host( i, j, k, 0 ), 6.0 + i + j + k ); } ); // Re-initialize gather fields Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FooIn() ), 0.0 ); Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FezIn() ), 0.0 ); // Re-initialize scatter field to wrong value. Kokkos::deep_copy( fm->view( FieldLocation::Cell(), FooOut() ), -1.1 ); // Apply the tensor3 grid operator. Use a tag. GridTensor3Func grid_tensor3_func; grid_op->apply( "grid_tensor3_op", FieldLocation::Cell(), TEST_EXECSPACE(), *fm, GridTensor3Func::Tag(), grid_tensor3_func ); // Check the grid results. Kokkos::deep_copy( foo_out_host, fm->view( FieldLocation::Cell(), FooOut() ) ); auto mi_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), MatI() ) ); auto mj_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), MatJ() ) ); auto mk_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), MatK() ) ); // Expect the correct cross-product for the given vector fields Cajita::grid_parallel_for( "check_tensor3_cross_product", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { EXPECT_EQ( foo_out_host( i, j, k, 0 ), -6.0 ); EXPECT_EQ( foo_out_host( i, j, k, 1 ), 6.0 ); EXPECT_EQ( foo_out_host( i, j, k, 2 ), -2.0 ); } ); // Expect the correct matrices from the various Tensor3 contractions Cajita::grid_parallel_for( "check_tensor3_vector_contract", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { EXPECT_EQ( mi_out_host( i, j, k, 0 ), 72 ); EXPECT_EQ( mi_out_host( i, j, k, 1 ), 78 ); EXPECT_EQ( mi_out_host( i, j, k, 2 ), 84 ); EXPECT_EQ( mi_out_host( i, j, k, 3 ), 90 ); EXPECT_EQ( mi_out_host( i, j, k, 4 ), 96 ); EXPECT_EQ( mi_out_host( i, j, k, 5 ), 102 ); EXPECT_EQ( mi_out_host( i, j, k, 6 ), 108 ); EXPECT_EQ( mi_out_host( i, j, k, 7 ), 114 ); EXPECT_EQ( mi_out_host( i, j, k, 8 ), 120 ); EXPECT_EQ( mj_out_host( i, j, k, 0 ), 24 ); EXPECT_EQ( mj_out_host( i, j, k, 1 ), 30 ); EXPECT_EQ( mj_out_host( i, j, k, 2 ), 36 ); EXPECT_EQ( mj_out_host( i, j, k, 3 ), 78 ); EXPECT_EQ( mj_out_host( i, j, k, 4 ), 84 ); EXPECT_EQ( mj_out_host( i, j, k, 5 ), 90 ); EXPECT_EQ( mj_out_host( i, j, k, 6 ), 132 ); EXPECT_EQ( mj_out_host( i, j, k, 7 ), 138 ); EXPECT_EQ( mj_out_host( i, j, k, 8 ), 144 ); EXPECT_EQ( mk_out_host( i, j, k, 0 ), 8 ); EXPECT_EQ( mk_out_host( i, j, k, 1 ), 26 ); EXPECT_EQ( mk_out_host( i, j, k, 2 ), 44 ); EXPECT_EQ( mk_out_host( i, j, k, 3 ), 62 ); EXPECT_EQ( mk_out_host( i, j, k, 4 ), 80 ); EXPECT_EQ( mk_out_host( i, j, k, 5 ), 98 ); EXPECT_EQ( mk_out_host( i, j, k, 6 ), 116 ); EXPECT_EQ( mk_out_host( i, j, k, 7 ), 134 ); EXPECT_EQ( mk_out_host( i, j, k, 8 ), 152 ); } ); GridTensor4Func grid_tensor4_func; grid_op->apply( "grid_tensor4_op", FieldLocation::Cell(), TEST_EXECSPACE(), *fm, GridTensor4Func::Tag(), grid_tensor4_func ); auto baz_out_host = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), fm->view( FieldLocation::Cell(), Baz() ) ); // Expect the correct matrices from the various tensor contractions Cajita::grid_parallel_for( "check_tensor4_matrix_contract", Kokkos::DefaultHostExecutionSpace(), *( mesh->localGrid() ), Cajita::Own(), Cajita::Cell(), KOKKOS_LAMBDA( const int i, const int j, const int k ) { EXPECT_EQ( baz_out_host( i, j, k, 0 ), 1.25 ); EXPECT_EQ( baz_out_host( i, j, k, 1 ), 2 ); EXPECT_EQ( baz_out_host( i, j, k, 2 ), 0 ); EXPECT_EQ( baz_out_host( i, j, k, 3 ), 2 ); EXPECT_EQ( baz_out_host( i, j, k, 4 ), 0.25 ); EXPECT_EQ( baz_out_host( i, j, k, 5 ), 0 ); EXPECT_EQ( baz_out_host( i, j, k, 6 ), 0 ); EXPECT_EQ( baz_out_host( i, j, k, 7 ), 0 ); EXPECT_EQ( baz_out_host( i, j, k, 8 ), 0.25 ); } ); } //---------------------------------------------------------------------------// // RUN TESTS //---------------------------------------------------------------------------// TEST( TEST_CATEGORY, gather_scatter_test ) { gatherScatterTest(); } //---------------------------------------------------------------------------// } // end namespace Test
39.843636
80
0.544401
abisner
5138a09ebc9f4012bdbaa539c9546a9ea4fa182c
1,368
cpp
C++
tests/transactions/helpers.cpp
brett19/couchbase-transactions-cxx
468342818a62b8648798b112618afb47ed229c0b
[ "Apache-2.0" ]
null
null
null
tests/transactions/helpers.cpp
brett19/couchbase-transactions-cxx
468342818a62b8648798b112618afb47ed229c0b
[ "Apache-2.0" ]
null
null
null
tests/transactions/helpers.cpp
brett19/couchbase-transactions-cxx
468342818a62b8648798b112618afb47ed229c0b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "helpers.hxx" bool operator==(const SimpleObject& lhs, const SimpleObject& rhs) { return (rhs.name == lhs.name) && (rhs.number == lhs.number); } void to_json(nlohmann::json& j, const SimpleObject& o) { j = nlohmann::json{ { "name", o.name }, { "number", o.number } }; } void from_json(const nlohmann::json& j, SimpleObject& o) { j.at("name").get_to(o.name); j.at("number").get_to(o.number); } bool operator==(const AnotherSimpleObject& lhs, const AnotherSimpleObject& rhs) { return lhs.foo == rhs.foo; } void to_json(nlohmann::json& j, const AnotherSimpleObject& o) { j = nlohmann::json{ { "foo", o.foo } }; } void from_json(const nlohmann::json& j, AnotherSimpleObject& o) { j.at("foo").get_to(o.foo); }
25.811321
77
0.679094
brett19
513d3587339e31c9de95dc67bba5ced73c4966b9
19,821
cpp
C++
gtest/containers/set_test.cpp
public-jun/42_ft_containers
28e32632ebf7100537fc2c0bc85438ada9f0e4f0
[ "MIT" ]
null
null
null
gtest/containers/set_test.cpp
public-jun/42_ft_containers
28e32632ebf7100537fc2c0bc85438ada9f0e4f0
[ "MIT" ]
40
2022-02-12T06:50:14.000Z
2022-03-31T14:43:29.000Z
gtest/containers/set_test.cpp
public-jun/42_ft_containers
28e32632ebf7100537fc2c0bc85438ada9f0e4f0
[ "MIT" ]
null
null
null
#if STL // -DTEST=1 #else // -DTEST=0 #include <set.hpp> #endif #if __cplusplus >= 201103L #include <gtest/gtest.h> #else #include "../ft_test.hpp" #endif #include <set> #include <time.h> // 内部構造はmapと同じなのでテストは簡易 template <class T> void compare_set_iterator(T first1, T end1, T first2) { for (; first1 != end1; ++first1, ++first2) EXPECT_EQ(*first1, *first2); } TEST(Set, Constructor) { // set(); { ft::set<int> s; EXPECT_EQ(0, s.size()); EXPECT_EQ(true, s.empty()); EXPECT_EQ(s.begin(), s.end()); EXPECT_EQ(s.rbegin(), s.rend()); } // explicit set(const Compare& comp, const Allocator& alloc = Allocator()); { ft::set<int, std::greater<int> > s((std::greater<int>()), (std::allocator<int>())); EXPECT_EQ(0, s.size()); EXPECT_EQ(true, s.empty()); } // template< class InputIt > // set(InputIt first, InputIt last, const Compare& comp = Compare(), // const Allocator& alloc = Allocator()); { ft::set<int> s1; for (int i = 0; i < 10; ++i) s1.insert(i); ft::set<int> s2(s1.begin(), s1.end(), (std::less<int>()), (std::allocator<int>())); compare_set_iterator(s1.begin(), s1.end(), s2.begin()); EXPECT_EQ(s1.size(), s2.size()); EXPECT_EQ(s1.get_allocator(), s2.get_allocator()); } // set( const set& other ); { ft::set<int> s1; for (int i = 0; i < 10; ++i) s1.insert(i); ft::set<int> s2(s1); compare_set_iterator(s1.begin(), s1.end(), s2.begin()); EXPECT_EQ(s1.size(), s2.size()); EXPECT_EQ(s1.get_allocator(), s2.get_allocator()); } // operator=(const set& other); { ft::set<int> s1; for (int i = 0; i < 10; ++i) s1.insert(i); ft::set<int> s2; s2 = s1; compare_set_iterator(s1.begin(), s1.end(), s2.begin()); EXPECT_EQ(s1.size(), s2.size()); EXPECT_EQ(s1.get_allocator(), s2.get_allocator()); ft::set<int> s3; for (int i = 10; i < 30; ++i) s3.insert(i); s2 = s3; compare_set_iterator(s3.begin(), s3.end(), s2.begin()); EXPECT_EQ(s3.size(), s2.size()); EXPECT_EQ(s3.get_allocator(), s2.get_allocator()); } } TEST(Set, Iterator) { ft::set<int> s; for (int i = 0; i < 10; ++i) s.insert(i); // Non const map && Non const iterator ft::set<int>::iterator it = s.begin(); EXPECT_EQ(0, *it); ++it; EXPECT_EQ(1, *it); it = s.end(); --it; EXPECT_EQ(9, *it); // Non const map && const iterator ft::set<int>::const_iterator cit = s.begin(); EXPECT_EQ(0, *cit); ++cit; EXPECT_EQ(1, *cit); cit = s.end(); --cit; EXPECT_EQ(9, *cit); // const map && const iterator const ft::set<int> cs1(s); ft::set<int>::const_iterator cit2 = cs1.begin(); EXPECT_EQ(0, *cit2); const ft::set<int> cs2(cs1); cit2 = cs2.begin(); EXPECT_EQ(0, *cit2); ft::set<int>::const_iterator cit3; cit3 = cit2; EXPECT_EQ(0, *cit3); cit3++; EXPECT_EQ(1, *cit3); cit3 = cs1.end(); --cit3; EXPECT_EQ(9, *cit3); } TEST(Set, ReverseIterator) { // reverse_iterator ft::set<int> s; for (int i = 0; i < 10; ++i) s.insert(i); ft::set<int>::reverse_iterator rit = s.rbegin(); int j = 9; for (ft::set<int>::reverse_iterator end = s.rend(); rit != end; ++rit, --j) { EXPECT_EQ(j, *rit); } // const_reverse_iterator const ft::set<int> cs(s); ft::set<int>::const_reverse_iterator crit = cs.rbegin(); j = 9; for (ft::set<int>::const_reverse_iterator end = cs.rend(); crit != end; ++crit, --j) { EXPECT_EQ(j, *crit); } } TEST(Set, CapacitySizeAndEmpty) { ft::set<int> s; EXPECT_TRUE(s.empty()); for (std::size_t i = 0; i < 10; ++i) { s.insert(i); EXPECT_EQ(i + 1, s.size()); } EXPECT_FALSE(s.empty()); const ft::set<int> cs(s); EXPECT_EQ(s.size(), cs.size()); } TEST(Set, CapacityMaxSize) { { ft::set<int> ft_s; std::set<int> stl_s; EXPECT_EQ(stl_s.max_size(), ft_s.max_size()); } { ft::set<std::string, std::less<std::string> > ft_s; std::set<std::string, std::less<std::string> > stl_s; EXPECT_EQ(stl_s.max_size(), ft_s.max_size()); } { ft::set<std::string, std::less<std::string> > ft_s; std::set<std::string, std::less<std::string> > stl_s; EXPECT_EQ(stl_s.max_size(), ft_s.max_size()); } { ft::set<double, std::less<double> > ft_s; std::set<double, std::less<double> > stl_s; EXPECT_EQ(stl_s.max_size(), ft_s.max_size()); } } TEST(Set, ModifiersInsert) { // std::pair<iterator,bool> insert( const value_type& value ); std::srand(time(NULL)); { std::vector<int> v; ft::set<int> s; ft::pair<ft::set<int>::iterator, bool> ret; for (int i = 0; i < SIZE; ++i) { int key = std::rand(); ret = s.insert(key); EXPECT_EQ(*(ret.first), key); if (ret.second == true) v.insert(v.begin(), key); } std::sort(v.begin(), v.end()); ft::set<int>::iterator it = s.begin(); ft::set<int>::iterator end = s.end(); int i = 0; while (it != end) { EXPECT_EQ((*it), v.at(i++)); ++it; } } // iterator insert( iterator hint, const value_type& value ); { std::set<int> stl_s; std::set<int>::iterator sit; ft::set<int> s; ft::set<int>::iterator it = s.begin(); ft::set<int>::iterator end; for (int i = 0; i < SIZE; ++i) { int key = std::rand() / SIZE; it = s.insert(it, key); EXPECT_EQ(*it, key); ++it; stl_s.insert(key); } it = s.begin(); end = s.end(); sit = stl_s.begin(); while (it != end) { EXPECT_EQ(*it, *sit); ++sit; ++it; } } // template< class InputIt > // void insert(InputIt first, InputIt last) { ft::set<int> s; for (int i = 1; i <= 20; ++i) s.insert(i); for (int i = 41; i <= 60; ++i) s.insert(i); ft::set<int> s1; for (int i = 21; i <= 40; ++i) s1.insert(i); s.insert(s1.begin(), s1.end()); ft::set<int>::iterator it = s.begin(); for (int i = 1; i <= 60; ++i) EXPECT_EQ(i, *(it++)); } } TEST(Set, ModifiersErase) { std::srand(time(NULL)); // void erase( iterator pos ); { std::vector<int> v; ft::set<int> s; ft::pair<ft::set<int>::iterator, bool> ret; for (int i = 0; i < SIZE; ++i) { int key = std::rand() % SIZE; ret = s.insert(key); EXPECT_EQ(*(ret.first), key); if (ret.second == true) v.insert(v.begin(), key); } std::vector<int>::iterator it = v.begin(); for (std::vector<int>::iterator end = v.end(); it != end; ++it) { s.erase(s.find(*it)); } EXPECT_EQ(s.size(), 0); EXPECT_TRUE(s.empty()); } // void erase( iterator first, iterator last ); { std::vector<int> v; ft::set<int> s; ft::pair<ft::set<int>::iterator, bool> ret; for (int i = 0; i < SIZE; ++i) { int key = std::rand() % SIZE; ret = s.insert(key); EXPECT_EQ(*(ret.first), key); if (ret.second == true) v.insert(v.begin(), key); } std::sort(v.begin(), v.end()); std::vector<int>::iterator vf, vl, vtmp; // 削除する範囲の値を得る while (true) { vf = find(v.begin(), v.end(), std::rand() % SIZE); vl = find(vf, v.end(), std::rand() % SIZE); if (vf != v.end() && vl != v.end()) break; } ft::set<int>::iterator first, last, stmp; first = s.find(*vf); last = s.find(*vl); s.erase(first, last); vtmp = v.begin(); stmp = s.begin(); std::size_t size = 0; bool is_removed_range = false; for (; vtmp != v.end(); ++vtmp) { if (vtmp == vf) is_removed_range = true; if (vtmp == vl) is_removed_range = false; if (is_removed_range == false) { EXPECT_EQ(*vtmp, *stmp); ++size; ++stmp; } // [first, last) が消去されているか確認 if (is_removed_range == true) EXPECT_EQ(s.end(), s.find(*vtmp)); } EXPECT_EQ(size, s.size()); EXPECT_FALSE(s.empty()); } // size_type erase( const key_type& key ); { std::vector<int> v; ft::set<int> s; int key; ft::pair<ft::set<int>::iterator, bool> ret; for (int i = 0; i < SIZE; ++i) { key = std::rand() % SIZE; ret = s.insert(key); EXPECT_EQ(*ret.first, key); if (ret.second == true) v.insert(v.begin(), key); } std::sort(v.begin(), v.end()); for (int i = 0; i < SIZE; ++i) { key = std::rand() % SIZE; std::vector<int>::iterator it = find(v.begin(), v.end(), key); if (it != v.end()) { EXPECT_EQ(1, s.erase(key)); v.erase(it); } else EXPECT_EQ(0, s.erase(key)); EXPECT_EQ(v.size(), s.size()); } } } TEST(Set, ModifiersClear) { ft::set<int> s; for (int i = 0; i < 10; ++i) s.insert(i); s.clear(); s.clear(); EXPECT_EQ(0, s.size()); EXPECT_TRUE(s.empty()); } TEST(Set, ModifiersMemberSwap) { ft::set<char> s1; for (int i = 0; i < 10; ++i) s1.insert('a' + i); ft::set<char> s2; for (int i = -10; i < -4; ++i) s2.insert('z' - i); ft::set<char>::iterator prev_s1_it = s1.begin(); ft::set<char>::iterator prev_s2_it = s2.begin(); ft::set<char>::iterator tmp_it; s1.swap(s2); tmp_it = s2.begin(); for (ft::set<char>::iterator end = s2.end(); tmp_it != end; ++tmp_it, ++prev_s1_it) { EXPECT_EQ(prev_s1_it, tmp_it); EXPECT_EQ(*prev_s1_it, *tmp_it); } tmp_it = s1.begin(); for (ft::set<char>::iterator end = s1.end(); tmp_it != end; ++tmp_it, ++prev_s2_it) { EXPECT_EQ(prev_s2_it, tmp_it); EXPECT_EQ(*prev_s2_it, *tmp_it); } prev_s1_it = s1.begin(); ft::set<char> empty1; ft::set<char>::iterator prev_empty_it = empty1.begin(); ft::set<char>::iterator prev_empty_end = empty1.end(); empty1.swap(s1); tmp_it = empty1.begin(); for (ft::set<char>::iterator end = empty1.end(); tmp_it != end; ++tmp_it, ++prev_s1_it) { EXPECT_EQ(prev_s1_it, tmp_it); EXPECT_EQ(*prev_s1_it, *tmp_it); } EXPECT_NE(prev_empty_it, s1.begin()); EXPECT_NE(prev_empty_end, s1.end()); for (int i = 0; i < 10; ++i) s1.insert('a' + i); tmp_it = s1.begin(); for (int i = 0; i < 10; ++i, ++tmp_it) { EXPECT_EQ('a' + i, *tmp_it); } } TEST(Set, LookupCount) { ft::set<int> s; for (int i = 0; i < 10; ++i) s.insert(i); EXPECT_EQ(1, s.count(1)); EXPECT_EQ(0, s.count(42)); s.insert(42); EXPECT_EQ(1, s.count(42)); } TEST(Set, Lookupfind) { ft::set<int> s; for (int i = 1; i < 20; i *= 2) s.insert(i); ft::set<int>::iterator it = s.find(2); EXPECT_EQ(2, *it); it = s.find(3); EXPECT_EQ(s.end(), it); const ft::set<int> cs(s); ft::set<int>::const_iterator cit = cs.find(2); EXPECT_EQ(2, *cit); cit = cs.find(3); EXPECT_EQ(cs.end(), cit); } TEST(Set, LookupEqualRange) { // Non Const // std::pair<iterator,iterator> equal_range( const Key& key ); ft::set<int> s; for (int i = 0; i < 100; i += 10) s.insert(i); ft::pair<ft::set<int>::iterator, ft::set<int>::iterator> ret; ret = s.equal_range(-10); EXPECT_EQ(0, *ret.first); EXPECT_EQ(0, *ret.second); ret = s.equal_range(0); EXPECT_EQ(0, *ret.first); EXPECT_EQ(10, *ret.second); ret = s.equal_range(42); EXPECT_EQ(50, *ret.first); EXPECT_EQ(50, *ret.second); ret = s.equal_range(50); EXPECT_EQ(50, *ret.first); EXPECT_EQ(60, *ret.second); ret = s.equal_range(90); EXPECT_EQ(90, *ret.first); EXPECT_EQ(s.end(), ret.second); ret = s.equal_range(100); EXPECT_EQ(s.end(), ret.first); EXPECT_EQ(s.end(), ret.second); // Const // ft::pair<const_iterator, const_iterator> equal_range(const Key& key) // const; const ft::set<int> cs(s); ft::pair<ft::set<int>::const_iterator, ft::set<int>::const_iterator> cret; cret = cs.equal_range(-10); EXPECT_EQ(0, *cret.first); EXPECT_EQ(0, *cret.second); cret = cs.equal_range(0); EXPECT_EQ(0, *cret.first); EXPECT_EQ(10, *cret.second); cret = cs.equal_range(42); EXPECT_EQ(50, *cret.first); EXPECT_EQ(50, *cret.second); cret = cs.equal_range(50); EXPECT_EQ(50, *cret.first); EXPECT_EQ(60, *cret.second); cret = cs.equal_range(90); EXPECT_EQ(90, *cret.first); EXPECT_EQ(cs.end(), cret.second); cret = cs.equal_range(100); EXPECT_EQ(cs.end(), cret.first); EXPECT_EQ(cs.end(), cret.second); } TEST(Set, LookupLowerBound) { // Non const ft::set<int> s; for (int i = 0; i < 50; i += 10) s.insert(i); ft::set<int>::iterator it; it = s.lower_bound(0); EXPECT_EQ(0, *it); it = s.lower_bound(23); EXPECT_EQ(30, *it); it = s.lower_bound(53); EXPECT_TRUE(s.end() == it); // Const ft::set<int> cs = s; ft::set<int>::const_iterator cit; cit = cs.lower_bound(0); EXPECT_EQ(0, *cit); cit = s.lower_bound(23); EXPECT_EQ(30, *cit); cit = cs.lower_bound(53); EXPECT_TRUE(cs.end() == cit); } TEST(Set, LookupUpperBound) { // Non const // iterator upper_bound( const Key& key ); ft::set<int> s; for (int i = 0; i < 50; i += 10) s.insert(i); ft::set<int>::iterator it; it = s.upper_bound(-100); EXPECT_EQ(s.begin(), it); EXPECT_EQ(0, *it); it = s.upper_bound(10); EXPECT_EQ(20, *it); it = s.upper_bound(100); EXPECT_EQ(s.end(), it); // Const // const_iterator upper_bound( const Key& key ) const; const ft::set<int> cs(s); ft::set<int>::const_iterator cit; cit = cs.upper_bound(-100); EXPECT_EQ(cs.begin(), cit); EXPECT_EQ(0, *cit); cit = cs.upper_bound(10); EXPECT_EQ(20, *cit); cit = cs.upper_bound(100); EXPECT_EQ(cs.end(), cit); } TEST(Set, ObserversKeyComp) { { ft::set<int> s; ft::set<int>::key_compare comp; comp = s.key_comp(); EXPECT_TRUE(comp(1, 2)); EXPECT_FALSE(comp(2, 2)); EXPECT_FALSE(comp(3, 2)); } { ft::set<int, std::greater<int> > s; ft::set<int, std::greater<int> >::key_compare comp; comp = s.key_comp(); EXPECT_FALSE(comp(1, 2)); EXPECT_FALSE(comp(2, 2)); EXPECT_TRUE(comp(3, 2)); } { ft::set<std::string, std::less<std::string> > s; ft::set<std::string, std::less<std::string> >::key_compare comp; comp = s.key_comp(); EXPECT_TRUE(comp("abc", "xyz")); EXPECT_FALSE(comp("abc", "abc")); EXPECT_FALSE(comp("xyz", "abc")); } { ft::set<std::string, std::greater<std::string> > s; ft::set<std::string, std::greater<std::string> >::key_compare comp; comp = s.key_comp(); EXPECT_FALSE(comp("abc", "xyz")); EXPECT_FALSE(comp("abc", "abc")); EXPECT_TRUE(comp("xyz", "abc")); } } TEST(Set, ObserversValueComp) { { ft::set<int> s; ft::set<int>::value_compare comp; comp = s.key_comp(); EXPECT_TRUE(comp(1, 2)); EXPECT_FALSE(comp(2, 2)); EXPECT_FALSE(comp(3, 2)); } { ft::set<int, std::greater<int> > s; ft::set<int, std::greater<int> >::value_compare comp; comp = s.key_comp(); EXPECT_FALSE(comp(1, 2)); EXPECT_FALSE(comp(2, 2)); EXPECT_TRUE(comp(3, 2)); } { ft::set<std::string, std::less<std::string> > s; ft::set<std::string, std::less<std::string> >::value_compare comp; comp = s.key_comp(); EXPECT_TRUE(comp("abc", "xyz")); EXPECT_FALSE(comp("abc", "abc")); EXPECT_FALSE(comp("xyz", "abc")); } { ft::set<std::string, std::greater<std::string> > s; ft::set<std::string, std::greater<std::string> >::value_compare comp; comp = s.key_comp(); EXPECT_FALSE(comp("abc", "xyz")); EXPECT_FALSE(comp("abc", "abc")); EXPECT_TRUE(comp("xyz", "abc")); } } TEST(Set, NonMemberFunctionsLexicographical) { ft::set<int> s1; ft::set<int> s2; s1.insert(10); s2.insert(10); EXPECT_TRUE(s1 == s2); EXPECT_FALSE(s1 != s2); EXPECT_FALSE(s1 < s2); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s1 > s2); EXPECT_TRUE(s1 >= s2); s2.insert(20); EXPECT_FALSE(s1 == s2); EXPECT_TRUE(s1 != s2); EXPECT_TRUE(s1 < s2); EXPECT_TRUE(s1 <= s2); EXPECT_FALSE(s1 > s2); EXPECT_FALSE(s1 >= s2); s1.insert(30); EXPECT_FALSE(s1 == s2); EXPECT_TRUE(s1 != s2); EXPECT_FALSE(s1 < s2); EXPECT_FALSE(s1 <= s2); EXPECT_TRUE(s1 > s2); EXPECT_TRUE(s1 >= s2); } TEST(Set, NonMemberFunctionsSwap) { ft::set<char> s1; for (int i = 0; i < 10; ++i) s1.insert('a' + i); ft::set<char> s2; for (int i = -10; i < -4; ++i) s2.insert('z' - i); ft::set<char>::iterator prev_s1_it = s1.begin(); ft::set<char>::iterator prev_s2_it = s2.begin(); ft::set<char>::iterator tmp_it; ft::swap(s1, s2); tmp_it = s2.begin(); for (ft::set<char>::iterator end = s2.end(); tmp_it != end; ++tmp_it, ++prev_s1_it) { EXPECT_EQ(prev_s1_it, tmp_it); EXPECT_EQ(*prev_s1_it, *tmp_it); } tmp_it = s1.begin(); for (ft::set<char>::iterator end = s1.end(); tmp_it != end; ++tmp_it, ++prev_s2_it) { EXPECT_EQ(prev_s2_it, tmp_it); EXPECT_EQ(*prev_s2_it, *tmp_it); } prev_s1_it = s1.begin(); ft::set<char> empty1; ft::set<char>::iterator prev_empty_it = empty1.begin(); ft::set<char>::iterator prev_empty_end = empty1.end(); ft::swap(empty1, s1); tmp_it = empty1.begin(); for (ft::set<char>::iterator end = empty1.end(); tmp_it != end; ++tmp_it, ++prev_s1_it) { EXPECT_EQ(prev_s1_it, tmp_it); EXPECT_EQ(*prev_s1_it, *tmp_it); } EXPECT_NE(prev_empty_it, s1.begin()); EXPECT_NE(prev_empty_end, s1.end()); for (int i = 0; i < 10; ++i) s1.insert('a' + i); tmp_it = s1.begin(); for (int i = 0; i < 10; ++i, ++tmp_it) { EXPECT_EQ('a' + i, *tmp_it); } }
27.152055
79
0.498007
public-jun
5148c105f61a8d9a40261bdc33f36e846b1d9c63
1,030
hpp
C++
src/controls/color_picker.hpp
AndrewGrim/Agro
f065920ab665938852bc8aa7e38d4d73f7e3ec0d
[ "MIT" ]
null
null
null
src/controls/color_picker.hpp
AndrewGrim/Agro
f065920ab665938852bc8aa7e38d4d73f7e3ec0d
[ "MIT" ]
null
null
null
src/controls/color_picker.hpp
AndrewGrim/Agro
f065920ab665938852bc8aa7e38d4d73f7e3ec0d
[ "MIT" ]
1
2021-04-18T12:06:55.000Z
2021-04-18T12:06:55.000Z
#pragma once #include "widget.hpp" #include "label.hpp" #include "line_edit.hpp" #define COLOR_PICKER_WIDTH 300 #define COLOR_PICKER_HEIGHT 200 class ColorPicker : public Widget { public: EventListener<Widget*, Color> onColorChanged = EventListener<Widget*, Color>(); ColorPicker(); ~ColorPicker(); virtual const char* name() override; virtual void draw(DrawingContext &dc, Rect rect, int state) override; virtual Size sizeHint(DrawingContext &dc) override; bool isLayout() override; int isFocusable() override; Widget* handleFocusEvent(FocusEvent event, State *state, FocusPropagationData data) override; Color color(); int m_cursor_width = 10; Color m_color = COLOR_NONE; Point m_position = Point(0, 0); TextureCoordinates m_coords; LineEdit *m_color_edit = nullptr; Label *m_color_label = nullptr; float *m_texture_data = new float[COLOR_PICKER_HEIGHT * COLOR_PICKER_WIDTH * 4]; };
32.1875
101
0.675728
AndrewGrim
514c8365dd9993283844233c553e94c886391f7a
1,453
cpp
C++
aws-cpp-sdk-lexv2-runtime/source/model/DialogAction.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lexv2-runtime/source/model/DialogAction.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lexv2-runtime/source/model/DialogAction.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lexv2-runtime/model/DialogAction.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace LexRuntimeV2 { namespace Model { DialogAction::DialogAction() : m_type(DialogActionType::NOT_SET), m_typeHasBeenSet(false), m_slotToElicitHasBeenSet(false) { } DialogAction::DialogAction(JsonView jsonValue) : m_type(DialogActionType::NOT_SET), m_typeHasBeenSet(false), m_slotToElicitHasBeenSet(false) { *this = jsonValue; } DialogAction& DialogAction::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("type")) { m_type = DialogActionTypeMapper::GetDialogActionTypeForName(jsonValue.GetString("type")); m_typeHasBeenSet = true; } if(jsonValue.ValueExists("slotToElicit")) { m_slotToElicit = jsonValue.GetString("slotToElicit"); m_slotToElicitHasBeenSet = true; } return *this; } JsonValue DialogAction::Jsonize() const { JsonValue payload; if(m_typeHasBeenSet) { payload.WithString("type", DialogActionTypeMapper::GetNameForDialogActionType(m_type)); } if(m_slotToElicitHasBeenSet) { payload.WithString("slotToElicit", m_slotToElicit); } return payload; } } // namespace Model } // namespace LexRuntimeV2 } // namespace Aws
19.118421
93
0.73159
blinemedical
5150a860afb3aa8901f132cbdf37307813c7e933
3,867
cc
C++
dash/test/meta/RangeTest.cc
RuhanDev/dash
c56193149c334e552df6f8439c3fb1510048b7f1
[ "BSD-3-Clause" ]
1
2019-05-19T20:31:20.000Z
2019-05-19T20:31:20.000Z
dash/test/meta/RangeTest.cc
RuhanDev/dash
c56193149c334e552df6f8439c3fb1510048b7f1
[ "BSD-3-Clause" ]
null
null
null
dash/test/meta/RangeTest.cc
RuhanDev/dash
c56193149c334e552df6f8439c3fb1510048b7f1
[ "BSD-3-Clause" ]
2
2019-10-02T23:19:22.000Z
2020-06-27T09:23:31.000Z
#include "RangeTest.h" #include <gtest/gtest.h> #include <dash/View.h> #include <dash/Array.h> #include <dash/Matrix.h> #include <dash/internal/StreamConversion.h> #include <array> #include <iterator> TEST_F(RangeTest, RangeTraits) { dash::Array<int> array(dash::size() * 10); auto v_sub = dash::sub(0, 10, array); auto i_sub = dash::index(v_sub); auto v_ssub = dash::sub(0, 5, (dash::sub(0, 10, array))); auto v_loc = dash::local(array); auto i_loc = dash::index(dash::local(array)); // auto v_gloc = dash::global(dash::local(array)); // auto i_glo = dash::global(dash::index(dash::local(array))); auto v_bsub = *dash::begin(dash::blocks(v_sub)); static_assert(dash::is_range< dash::Array<int> >::value == true, "dash::is_range<dash::Array>::value not matched"); static_assert(dash::is_range< typename dash::Array<int>::local_type >::value == true, "dash::is_range<dash::Array::local_type>::value not matched"); static_assert(dash::is_range< typename dash::Array<int>::iterator >::value == false, "dash::is_range<dash::Array<...>>::value not matched"); static_assert(dash::is_range<decltype(array)>::value == true, "range type trait for dash::Array not matched"); static_assert(dash::is_range<decltype(v_loc)>::value == true, "range type trait for local(dash::Array) not matched"); static_assert(dash::is_range<decltype(v_sub)>::value == true, "range type trait for sub(dash::Array) not matched"); static_assert(dash::is_range<decltype(v_ssub)>::value == true, "range type trait for sub(sub(dash::Array)) not matched"); static_assert(dash::is_range<decltype(v_bsub)>::value == true, "range type trait for begin(blocks(sub(dash::Array))) " "not matched"); static_assert(dash::is_range<decltype(i_sub)>::value == true, "range type trait for index(sub(dash::Array)) not matched"); static_assert(dash::is_range<decltype(i_loc)>::value == true, "range type trait for index(local(dash::Array)) not matched"); // Index set iterators implement random access iterator concept: // static_assert(std::is_same< typename std::iterator_traits< decltype(i_sub.begin()) >::iterator_category, std::random_access_iterator_tag >::value == true, "iterator trait iterator_category of " "index(local(dash::Array))::iterator not matched"); static_assert(std::is_same< typename std::iterator_traits< decltype(i_loc.begin()) >::iterator_category, std::random_access_iterator_tag >::value == true, "iterator trait iterator_category of " "index(local(dash::Array))::iterator not matched"); //static_assert(std::is_same< // typename std::iterator_traits< // decltype(i_glo.begin()) // >::iterator_category, // std::random_access_iterator_tag // >::value == true, // "iterator trait iterator_category of " // "global(index(local(dash::Array)))::iterator not matched"); static_assert( dash::is_range<decltype(array)>::value == true, "dash::is_range<dash::Array<...>>::value not matched"); auto l_range = dash::make_range(array.local.begin(), array.local.end()); static_assert( dash::is_range<decltype(l_range)>::value == true, "dash::is_range<dash::make_range(...)>::value not matched"); }
39.865979
78
0.57564
RuhanDev
51519fac19dcbe9973762850e55c65a79c3c9ff2
1,550
cpp
C++
src/efscape/utils/type.cpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
1
2019-07-29T07:44:13.000Z
2019-07-29T07:44:13.000Z
src/efscape/utils/type.cpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
null
null
null
src/efscape/utils/type.cpp
clinejc/efscape
ef8bbf272827c7b364aa02af33dc5d239f070e0b
[ "0BSD" ]
1
2019-07-11T10:49:48.000Z
2019-07-11T10:49:48.000Z
// __COPYRIGHT_START__ // Package Name : efscape // File Name : type.cpp // Copyright (C) 2006-2018 Jon C. Cline // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. // __COPYRIGHT_END__ #include <efscape/utils/type.hpp> #ifdef __GNUG__ #include <cstdlib> #include <memory> #include <cxxabi.h> namespace efscape { namespace utils { struct handle { char* p; handle(char* ptr) : p(ptr) { } ~handle() { std::free(p); } }; std::string demangle(const char* name) { int status = -4; // some arbitrary value to eliminate the compiler warning handle result( abi::__cxa_demangle(name, NULL, NULL, &status) ); return (status==0) ? result.p : name ; } } } #else namespace efscape { namespace utils { // does nothing if not g++ std::string demangle(const char* name) { return name; } } } #endif
27.678571
158
0.694194
clinejc
51594205af499ec87806554cc33848bb3ce7283d
1,124
cpp
C++
dbus-cxx/standard-interfaces/peerinterfaceproxy.cpp
tvladax/dbus-cxx
396041a2130985acd72bb801b7137ec06e04b161
[ "BSD-3-Clause" ]
null
null
null
dbus-cxx/standard-interfaces/peerinterfaceproxy.cpp
tvladax/dbus-cxx
396041a2130985acd72bb801b7137ec06e04b161
[ "BSD-3-Clause" ]
null
null
null
dbus-cxx/standard-interfaces/peerinterfaceproxy.cpp
tvladax/dbus-cxx
396041a2130985acd72bb801b7137ec06e04b161
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: LGPL-3.0-or-later OR BSD-3-Clause /*************************************************************************** * Copyright (C) 2020 by Robert Middleton * * robert.middleton@rm5248.com * * * * This file is part of the dbus-cxx library. * ***************************************************************************/ #include "peerinterfaceproxy.h" using DBus::PeerInterfaceProxy; PeerInterfaceProxy::PeerInterfaceProxy() : DBus::InterfaceProxy( DBUS_CXX_PEER_INTERFACE ){ m_ping_method = this->create_method<void()>( "Ping" ); m_get_machine_method = this->create_method<std::string()>( "GetMachineId" ); } std::shared_ptr<PeerInterfaceProxy> PeerInterfaceProxy::create(){ return std::shared_ptr<PeerInterfaceProxy>( new PeerInterfaceProxy() ); } void PeerInterfaceProxy::Ping(){ (*m_ping_method)(); } std::string PeerInterfaceProxy::GetMachineId(){ return (*m_get_machine_method)(); }
37.466667
80
0.513345
tvladax
515b7518098672ff18f2ff1ec2ade048038696b1
2,540
cpp
C++
src/xray/editor/world/sources/command_delete_object.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/world/sources/command_delete_object.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/world/sources/command_delete_object.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 02.04.2009 // Author : Armen Abroyan // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "command_delete_object.h" #include "level_editor.h" #include "tool_base.h" #include "object_base.h" #include "project.h" #include "command_select.h" #include "project_items.h" namespace xray { namespace editor { command_delete_selected_objects::command_delete_selected_objects( level_editor^ le ): m_level_editor(le) { } bool command_delete_selected_objects::commit () { id_list^ ids = gcnew id_list; object_list objects = m_level_editor->get_project()->selection_list(); for each(object_base^ o in objects) ids->Add( o->id() ); m_level_editor->get_command_engine()->run( gcnew command_select(m_level_editor) ); return m_level_editor->get_command_engine()->run( gcnew command_delete_object_impl(m_level_editor, ids )); } command_delete_object::command_delete_object( level_editor^ le, int id ): m_level_editor ( le ), m_id ( id ) { } bool command_delete_object::commit () { m_level_editor->get_command_engine()->run( gcnew command_select(m_level_editor) ); id_list^ ids = gcnew id_list; ids->Add ( m_id ); return m_level_editor->get_command_engine()->run( gcnew command_delete_object_impl(m_level_editor, ids )); } command_delete_object_impl::command_delete_object_impl (level_editor^ le, id_list^ objects_id ): m_level_editor ( le ) { m_ids = objects_id; m_objects = gcnew object_list; m_configs = NEW (configs::lua_config_ptr)(); *m_configs = configs::create_lua_config( "d:\\asd.lua"); } command_delete_object_impl::~command_delete_object_impl() { DELETE (m_configs); } bool command_delete_object_impl::commit () { xray::configs::lua_config_value value = (*m_configs)->get_root(); u32 index = 0; id_list^ idlist = m_ids; for each (System::UInt32^ it in idlist) { object_base^ o = object_base::object_by_id(*it); m_objects->Add (o); m_level_editor->get_project()->save_to_config(value, o, true ); m_level_editor->get_project()->remove_item( o->m_owner_project_item, true ); ++index; } return true; } void command_delete_object_impl::rollback () { configs::lua_config_value value = (*m_configs)->get_root(); m_level_editor->get_project()->load( value, true ); } }// namespace editor }// namespace xray
26.736842
108
0.666929
ixray-team
5160a119e018d97e0d7c700ff5632049d9c9de36
447
cpp
C++
nhn_next_gameserver_lab_2017_IocpServer/Samples/ObjectPoolTest/main.cpp
jacking75/Netowrok_Projects
7788a9265818db6d781620fd644124aca425fe3c
[ "MIT" ]
25
2019-05-20T08:07:39.000Z
2021-08-17T11:25:02.000Z
nhn_next_gameserver_lab_2017_IocpServer/Samples/ObjectPoolTest/main.cpp
jacking75/Netowrok_Projects
7788a9265818db6d781620fd644124aca425fe3c
[ "MIT" ]
null
null
null
nhn_next_gameserver_lab_2017_IocpServer/Samples/ObjectPoolTest/main.cpp
jacking75/Netowrok_Projects
7788a9265818db6d781620fd644124aca425fe3c
[ "MIT" ]
17
2019-07-07T12:20:16.000Z
2022-01-11T08:27:44.000Z
#include <iostream> #include <vector> #include "ClientSession.h" int main() { std::vector<ClientSession*> sessions; for (int i = 0; i < 3; ++i) { auto session = new ClientSession(); sessions.push_back(session); } for (int i = 0; i < 3; ++i) { delete sessions[i]; } sessions.clear(); for (int i = 0; i < 3; ++i) { auto session = new ClientSession(); sessions.push_back(session); } return 0; }
15.413793
39
0.572707
jacking75
5162729d357122aa639de9b836496c5469f72068
2,113
cpp
C++
test/training_data/plag_original_codes/abc037_c_6420655_827.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/abc037_c_6420655_827.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/abc037_c_6420655_827.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
/* 引用元:https://atcoder.jp/contests/abc037/tasks/abc037_c C - 総和Editorial // ソースコードの引用元 : https://atcoder.jp/contests/abc037/submissions/6420655 // 提出ID : 6420655 // 問題ID : abc037_c // コンテストID : abc037 // ユーザID : xryuseix // コード長 : 1857 // 実行時間 : 11 */ #include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <vector> #include <list> #include <set> #include <map> #include <queue> #include <stack> #include <cctype> #include <climits> #include <string> #include <bitset> using namespace std; typedef long double ld; typedef long long int ll; typedef unsigned long long int ull; typedef vector<int> vi; typedef vector<char> vc; typedef vector<string> vs; typedef vector<ll> vll; typedef vector<pair<int, int>> vpii; typedef vector<vector<int>> vvi; typedef vector<vector<char>> vvc; typedef vector<vector<string>> vvs; typedef vector<vector<ll>> vvll; #define rep(i, n) for (int i = 0; i < (n); ++i) #define rrep(i, n) for (int i = 1; i <= (n); ++i) #define drep(i, n) for (int i = (n)-1; i >= 0; --i) #define fin(ans) cout << (ans) << endl #define STI(s) atoi(s.c_str()) #define mp(p, q) make_pair(p, q) #define pb(n) push_back(n) #define Sort(a) sort(a.begin(), a.end()) #define Rort(a) sort(a.rbegin(), a.rend()) template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return 1; } return 0; } template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return 1; } return 0; } const int P = 1000000007; const int INF = INT_MAX; const ll LLINF = 1LL << 60; // g++ -std=c++1z temp.cpp //./a.out int main(void) { ios::sync_with_stdio(false); cin.tie(0); ////////////////////////////////////////////////////// ll n, k; cin >> n >> k; vll v(n), w(n, INF); rep(i, n) cin >> v[i]; ll ans = 0; ll l = 1, r = k; ll sum = 0; for (int i = 0; i < k; i++) { sum += v[i]; } ans += sum; // fin(ans); for (int i = 1; r < n; i++) { sum += v[r]; r++; sum -= v[l - 1]; l++; ans += sum; // fin(ans); } fin(ans); ////////////////////////////////////////////////////// return 0; }
20.920792
70
0.563654
xryuseix
516441de661be2abaab3cbf612dac08b81f2820d
11,487
cpp
C++
libRaftExt/protobuffer/RaftProtoBufferSerializer.cpp
ZhenYongFan/libRaft
7da0b124d9eed800bebaff39b01c9d1ae36c1ccd
[ "Apache-2.0" ]
4
2019-08-21T06:32:36.000Z
2021-12-16T09:30:48.000Z
libRaftExt/protobuffer/RaftProtoBufferSerializer.cpp
ZhenYongFan/libRaft
7da0b124d9eed800bebaff39b01c9d1ae36c1ccd
[ "Apache-2.0" ]
1
2019-08-20T07:11:42.000Z
2019-08-26T00:03:22.000Z
libRaftExt/protobuffer/RaftProtoBufferSerializer.cpp
ZhenYongFan/libRaft
7da0b124d9eed800bebaff39b01c9d1ae36c1ccd
[ "Apache-2.0" ]
2
2020-03-09T06:03:02.000Z
2021-02-03T03:21:57.000Z
#include "stdafx.h" #include "RaftProtoBufferSerializer.h" #include "raft.pb.h" #include "rpc.pb.h" #include <RaftEntry.h> #include <RequestOp.h> void LocalToPb(const CRaftEntry &entry, raftpb::Entry &entryPb) { entryPb.set_term(entry.m_u64Term); entryPb.set_index(entry.m_u64Index); entryPb.set_type(raftpb::EntryType(entry.m_eType)); entryPb.set_data(entry.m_strData); } void LocalToPb(const CConfState &stateConf, raftpb::ConfState &stateConfPb) { for (int nIndex = 0; nIndex < stateConf.m_nNum; nIndex++) stateConfPb.add_nodes(stateConf.m_pnNodes[nIndex]); } void LocalToPb(const CSnapshotMetadata &metaDat, raftpb::SnapshotMetadata &metaDatPb) { metaDatPb.set_index(metaDat.m_u64Index); metaDatPb.set_term(metaDat.m_u64Term); raftpb::ConfState* pConfStatePb = metaDatPb.mutable_conf_state(); LocalToPb(metaDat.m_stateConf, *pConfStatePb); } void LocalToPb(const CSnapshot &snapshot, raftpb::Snapshot &snapshotPb) { if (snapshot.m_u32DatLen > 0) snapshotPb.set_data(std::string((char *)snapshot.m_pData, snapshot.m_u32DatLen)); raftpb::SnapshotMetadata * pMetaData = snapshotPb.mutable_metadata(); LocalToPb(snapshot.m_metaDat, *pMetaData); } void LocalToPb(const CMessage &msg, raftpb::Message &msgPb) { msgPb.set_index(msg.m_u64Index); msgPb.set_commit(msg.m_u64Committed); msgPb.set_context(msg.m_strContext); msgPb.set_from(msg.m_nFromID); msgPb.set_logterm(msg.m_u64LogTerm); msgPb.set_reject(msg.m_bReject); msgPb.set_rejecthint(msg.m_u64RejectHint); msgPb.set_term(msg.m_u64Term); msgPb.set_to(msg.m_nToID); msgPb.set_type(raftpb::MessageType(msg.m_typeMsg)); raftpb::Snapshot *pSnapshot = msgPb.mutable_snapshot(); if (NULL != pSnapshot) LocalToPb(msg.m_snapshotLog, *pSnapshot); for (int nIndex = 0 ; nIndex < msg.m_nEntryNum ; nIndex ++) { raftpb::Entry *pEntry = msgPb.add_entries(); LocalToPb(msg.m_pEntry[nIndex], *pEntry); } } void LocalToPb(const CConfChange &conf, raftpb::ConfChange &confPb) { confPb.set_id(conf.m_nID); confPb.set_nodeid(conf.m_nRaftID); confPb.set_type(raftpb::ConfChangeType(conf.m_typeChange)); if (conf.m_u32Len > 0) confPb.set_context(std::string((char *)conf.m_pContext, conf.m_u32Len)); } void PbToLocal(const raftpb::Entry &entryPb, CRaftEntry &entry) { entry.set_term(entryPb.term()); entry.set_index(entryPb.index()); entry.set_type(CRaftEntry::EType(entryPb.type())); entry.set_data(entryPb.data()); } void PbToLocal(const raftpb::ConfState &stateConfPb,CConfState &stateConf) { for (int nIndex = 0; nIndex < stateConfPb.nodes_size(); nIndex++) stateConf.add_nodes(stateConfPb.nodes(nIndex)); } void PbToLocal(const raftpb::SnapshotMetadata &metaDatPb, CSnapshotMetadata &metaDat) { metaDat.set_index(metaDatPb.index()); metaDat.set_term(metaDatPb.term()); if(metaDatPb.has_conf_state()) PbToLocal(metaDatPb.conf_state(), metaDat.m_stateConf); } void PbToLocal(const raftpb::Snapshot &snapshotPb, CSnapshot &snapshot) { snapshot.set_data(snapshotPb.data()); if (snapshotPb.has_metadata()) PbToLocal(snapshotPb.metadata(), snapshot.m_metaDat); } void PbToLocal(const raftpb::Message &msgPb, CMessage &msg) { msg.set_index(msgPb.index()); msg.set_commit(msgPb.commit()); msg.set_context(msgPb.context()); msg.set_from(msgPb.from()); msg.set_logterm(msgPb.logterm()); msg.set_reject(msgPb.reject()); msg.set_rejecthint(msgPb.rejecthint()); msg.set_term(msgPb.term()); msg.set_to(msgPb.to()); msg.set_type(CMessage::EMessageType(msgPb.type())); if (msgPb.has_snapshot()) PbToLocal(msgPb.snapshot(), msg.m_snapshotLog); if (msgPb.entries_size() > 0) { msg.m_nEntryNum = msgPb.entries_size(); msg.m_pEntry = new CRaftEntry[msg.m_nEntryNum]; for (int nIndex = 0; nIndex < msgPb.entries_size(); nIndex++) PbToLocal(msgPb.entries(nIndex), msg.m_pEntry[nIndex]); } } void PbToLocal(const raftpb::ConfChange &confPb, CConfChange &conf) { conf.set_id(confPb.id()); conf.set_nodeid(confPb.nodeid()); conf.set_type(CConfChange::EConfChangeType(confPb.type())); conf.set_context(confPb.context()); } void RequestOpLocalToPb(const CRequestOp &opRequest, raftserverpb::RequestOp &opRequestPb) { opRequestPb.set_clientid(opRequest.clientid()); opRequestPb.set_subsessionid(opRequest.subsessionid()); if (opRequest.has_request_delete_range()) { raftserverpb::DeleteRangeRequest* pRequest = opRequestPb.mutable_request_delete_range(); const CDeleteRangeRequest &request = opRequest.request_delete_range(); pRequest->set_key(request.key()); } else if (opRequest.has_request_put()) { raftserverpb::PutRequest* pRequest = opRequestPb.mutable_request_put(); const CPutRequest &request = opRequest.request_put(); pRequest->set_key(request.key()); pRequest->set_value(request.value()); } else if (opRequest.has_request_range()) { raftserverpb::RangeRequest* pRequest = opRequestPb.mutable_request_range(); const CRangeRequest &request = opRequest.request_range(); pRequest->set_key(request.key()); } } void RequestOpPbToLocal(const raftserverpb::RequestOp &opRequestPb, CRequestOp &opRequest) { opRequest.set_clientid(opRequestPb.clientid()); opRequest.set_subsessionid(opRequestPb.subsessionid()); if (opRequestPb.has_request_delete_range()) { CDeleteRangeRequest* pRequest = opRequest.mutable_request_delete_range(); const raftserverpb::DeleteRangeRequest &request = opRequestPb.request_delete_range(); pRequest->set_key(request.key()); } else if (opRequestPb.has_request_put()) { CPutRequest* pRequest = opRequest.mutable_request_put(); const raftserverpb::PutRequest &request = opRequestPb.request_put(); pRequest->set_key(request.key()); pRequest->set_value(request.value()); } else if (opRequestPb.has_request_range()) { CRangeRequest* pRequest = opRequest.mutable_request_range(); const raftserverpb::RangeRequest &request = opRequestPb.request_range(); pRequest->set_key(request.key()); } } void ResponseOpLocalToPb(const CResponseOp &opResponse, raftserverpb::ResponseOp &opResponsePb) { opResponsePb.set_errorno(opResponse.errorno()); opResponsePb.set_subsessionid(opResponse.subsessionid()); if (opResponse.has_response_delete_range()) { raftserverpb::DeleteRangeResponse* pResponse = opResponsePb.mutable_response_delete_range(); const CDeleteRangeResponse &response = opResponse.response_delete_range(); } else if (opResponse.has_response_put()) { raftserverpb::PutResponse* pResponse = opResponsePb.mutable_response_put(); const CPutResponse &response = opResponse.response_put(); } else if (opResponse.has_response_range()) { raftserverpb::RangeResponse* pResponse = opResponsePb.mutable_response_range(); const CRangeResponse &response = opResponse.response_range(); const std::list<CKeyValue *> &listKeyvalues = response.GetKeyValues(); for (auto pKeyValue : listKeyvalues) { raftserverpb::KeyValue* pPbKeyValue = pResponse->add_kvs(); pPbKeyValue->set_key(pKeyValue->key()); pPbKeyValue->set_value(pKeyValue->value()); } } } void ResponseOpPbToLocal(const raftserverpb::ResponseOp &opResponsePb, CResponseOp &opResponse) { opResponse.set_errorno(opResponsePb.errorno()); opResponse.set_subsessionid(opResponsePb.subsessionid()); if (opResponsePb.has_response_delete_range()) { CDeleteRangeResponse* pResponse = opResponse.mutable_response_delete_range(); const raftserverpb::DeleteRangeResponse &response = opResponsePb.response_delete_range(); } else if (opResponsePb.has_response_put()) { CPutResponse* pResponse = opResponse.mutable_response_put(); const raftserverpb::PutResponse &response = opResponsePb.response_put(); } else if (opResponsePb.has_response_range()) { CRangeResponse* pResponse = opResponse.mutable_response_range(); const raftserverpb::RangeResponse &response = opResponsePb.response_range(); for (int nIndex = 0 ; nIndex < response.kvs_size(); nIndex ++) { const raftserverpb::KeyValue &keyValue = response.kvs(nIndex); CKeyValue* pKeyValue = pResponse->add_kvs(); pKeyValue->set_key(keyValue.key()); pKeyValue->set_value(keyValue.value()); } } } CRaftProtoBufferSerializer::CRaftProtoBufferSerializer() { } CRaftProtoBufferSerializer::~CRaftProtoBufferSerializer() { } size_t CRaftProtoBufferSerializer::ByteSize(const CRaftEntry &entry) const { raftpb::Entry entryPb; LocalToPb(entry, entryPb); return entryPb.ByteSize(); } void CRaftProtoBufferSerializer::SerializeEntry(const CRaftEntry &entry, std::string &strValue) { raftpb::Entry entryPb; LocalToPb(entry, entryPb); strValue = entryPb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseEntry(CRaftEntry &entry, const std::string &strValue) { raftpb::Entry entryPb; bool bParse = entryPb.ParseFromString(strValue); if (bParse) PbToLocal(entryPb, entry); return bParse; } void CRaftProtoBufferSerializer::SerializeMessage(const CMessage &msg, std::string &strValue) { raftpb::Message msgPb; LocalToPb(msg, msgPb); strValue = msgPb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseMessage(CMessage &msg, const std::string &strValue) { raftpb::Message msgPb; bool bParse = msgPb.ParseFromString(strValue); if (bParse) PbToLocal(msgPb, msg); return bParse; } void CRaftProtoBufferSerializer::SerializeConfChangee(const CConfChange &conf, std::string &strValue) { raftpb::ConfChange confPb; LocalToPb(conf, confPb); strValue = confPb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseConfChange(CConfChange &conf, const std::string &strValue) { raftpb::ConfChange confPb; bool bParse = confPb.ParseFromString(strValue); if (bParse) PbToLocal(confPb, conf); return bParse; } void CRaftProtoBufferSerializer::SerializeRequestOp(const CRequestOp &opRequest, std::string &strValue) { raftserverpb::RequestOp opRequestPb; RequestOpLocalToPb(opRequest, opRequestPb); strValue = opRequestPb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseRequestOp(CRequestOp &opRequest, const std::string &strValue) { raftserverpb::RequestOp opRequestPb; bool bParse = opRequestPb.ParseFromString(strValue); if (bParse) RequestOpPbToLocal(opRequestPb, opRequest); return bParse; } void CRaftProtoBufferSerializer::SerializeResponseOp(const CResponseOp &opResponse, std::string &strValue) { raftserverpb::ResponseOp opResponsePb; ResponseOpLocalToPb(opResponse, opResponsePb); strValue = opResponsePb.SerializeAsString(); } bool CRaftProtoBufferSerializer::ParseResponseOp(CResponseOp &opResponse, const std::string &strValue) { raftserverpb::ResponseOp opResponsePb; bool bParse = opResponsePb.ParseFromString(strValue); if (bParse) ResponseOpPbToLocal(opResponsePb, opResponse); return bParse; }
34.809091
106
0.716984
ZhenYongFan
5166174d985515dd0a3fa627f1c1736d6b152600
4,659
cpp
C++
src/generic_cpu/b_ipc_target.cpp
cicerone/kosim
a9f718a19019c11fd6e6c6fc0164d4d214bbb5e2
[ "BSL-1.0" ]
2
2019-11-15T19:15:36.000Z
2022-03-14T12:53:18.000Z
src/generic_cpu/b_ipc_target.cpp
cicerone/kosim
a9f718a19019c11fd6e6c6fc0164d4d214bbb5e2
[ "BSL-1.0" ]
null
null
null
src/generic_cpu/b_ipc_target.cpp
cicerone/kosim
a9f718a19019c11fd6e6c6fc0164d4d214bbb5e2
[ "BSL-1.0" ]
null
null
null
/*=============================================================================================== Copyright (c) 2009 Kotys LLC. 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) Author: Cicerone Mihalache Support: kosim@kotys.biz ===============================================================================================*/ #include "b_ipc_target.h" #include "memory_map_builder.h" #include "memory_map.h" using namespace sc_core; using namespace sc_dt; using namespace std; // BIPCTarget - blocking target (the target that used TLM2 blocking interface) ///////////////////////////////////////////////////////////////////////////////////////////////// // // IN: // OUT: // RET: BIPCTarget::BIPCTarget(sc_module_name name_, uint32_t id_) : sc_module(name_), socket("gc_target_socket"), DMI_LATENCY(10, SC_NS), mp_memory_map(0), m_id(id_), mp_last_tlm_payload(0) { // Register callbacks for incoming interface method calls socket.register_b_transport( this, &BIPCTarget::b_transport); socket.register_get_direct_mem_ptr(this, &BIPCTarget::get_direct_mem_ptr); socket.register_transport_dbg( this, &BIPCTarget::transport_dbg); mp_memory_map = MemoryMapBuilder::GetInstance()->GetMemoryMap(m_id); } ///////////////////////////////////////////////////////////////////////////////////////////////// // TLM-2 blocking transport method // IN: // OUT: // RET: void BIPCTarget::b_transport( tlm::tlm_generic_payload& payload_, sc_time& delay_ ) { tlm::tlm_command command = payload_.get_command(); // sc_dt::uint64 mem_address = payload_.get_address() / sizeof(mem[0]); sc_dt::uint64 mem_address = payload_.get_address(); uint8_t* data_ptr = payload_.get_data_ptr(); uint32_t data_length = payload_.get_data_length(); uint8_t* byte_enable = payload_.get_byte_enable_ptr(); uint32_t stream_width = payload_.get_streaming_width(); // Generate the appropriate error response if (mem_address >= mp_memory_map->get_memory_space()) { payload_.set_response_status( tlm::TLM_ADDRESS_ERROR_RESPONSE ); return; } if (byte_enable != 0) { payload_.set_response_status( tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE ); return; } mp_last_tlm_payload = &payload_; // Set DMI hint to indicated that DMI is supported // payload_.set_dmi_allowed(true); // Obliged to set response status to indicate successful completion // payload_.set_response_status( tlm::TLM_OK_RESPONSE ); m_io_event.notify(SC_ZERO_TIME); wait(SC_ZERO_TIME); // let the target adaptor to use the payload wait(delay_); // implement the delay from initiator delay_ = SC_ZERO_TIME; } ///////////////////////////////////////////////////////////////////////////////////////////////// // TLM-2 forward DMI method // IN: // OUT: // RET: bool BIPCTarget::get_direct_mem_ptr(tlm::tlm_generic_payload& payload_, tlm::tlm_dmi& dmi_data_) { /* // Permit read and write access dmi_data_.allow_read_write(); // Set other details of DMI region dmi_data_.set_dmi_ptr( reinterpret_cast<unsigned char*>( &mem[0] ) ); dmi_data_.set_start_address( 0 ); dmi_data_.set_end_address( SIZE * sizeof(mem[0]) - 1 ); dmi_data_.set_read_latency( DMI_LATENCY ); dmi_data_.set_write_latency( DMI_LATENCY ); return true; */ return false; } ///////////////////////////////////////////////////////////////////////////////////////////////// // TLM-2 debug transaction method // IN: // OUT: // RET: unsigned int BIPCTarget::transport_dbg(tlm::tlm_generic_payload& payload_) { fprintf(stderr, "ERROR! %s not implemented!\n"); exit(1); tlm::tlm_command command = payload_.get_command(); sc_dt::uint64 mem_address = payload_.get_address(); uint8_t* data_ptr = payload_.get_data_ptr(); uint32_t data_length = payload_.get_data_length(); // Calculate the number of bytes to be actually copied sc_dt::uint64 length_to_end = mp_memory_map->get_memory_space() - mem_address; sc_dt::uint64 num_bytes = data_length < length_to_end ? data_length : length_to_end ; if ( command == tlm::TLM_READ_COMMAND ) { memcpy(data_ptr, mp_memory_map->GetPhysicalAddress(mem_address), data_length); } else if ( command == tlm::TLM_WRITE_COMMAND ) { memcpy(mp_memory_map->GetPhysicalAddress(mem_address), data_ptr, data_length); } return num_bytes; }
36.116279
97
0.605924
cicerone
51681500c39ac4640164102458d08cbc89d5e7c2
807
cpp
C++
Codeforces/r217d2/B.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Codeforces/r217d2/B.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Codeforces/r217d2/B.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <queue> #include <vector> #define sz(X) (int)X.size() using namespace std; typedef vector<int> vi; int n; vi m[100]; int main() { cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; m[i].resize(x); for (int j = 0; j < x; j++) cin >> m[i][j]; sort(m[i].begin(), m[i].end()); } for (int i = 0; i < n; i++) { bool ok = true; for (int j = 0; j < n; j++) { if (i == j) continue; if (sz(m[i]) < sz(m[j])) continue; int l = 0; int r = 0; while (l < sz(m[i]) && r < sz(m[j])) { if (m[i][l] == m[j][r]) { l++; r++; } else { l++; } } if (r == sz(m[j])) { ok = false; break; } } cout << (ok ?"YES" :"NO") << "\n"; } return 0; }
13.016129
41
0.408922
s9v
516c8c98979cb71a25f3b40f2ed3b4509106adba
600
hpp
C++
include/kjq_navigation/BiPridgeNode.hpp
CtfChan/kjq_navigation
4969fe633c74fa19ab3330e30a561efbcacc6b03
[ "BSD-3-Clause" ]
null
null
null
include/kjq_navigation/BiPridgeNode.hpp
CtfChan/kjq_navigation
4969fe633c74fa19ab3330e30a561efbcacc6b03
[ "BSD-3-Clause" ]
null
null
null
include/kjq_navigation/BiPridgeNode.hpp
CtfChan/kjq_navigation
4969fe633c74fa19ab3330e30a561efbcacc6b03
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <ros/ros.h> #include <sensor_msgs/LaserScan.h> #include <geometry_msgs/Pose.h> #include <tf/transform_broadcaster.h> namespace kjq_navigation { class PiBridgeNode { public: PiBridgeNode(ros::NodeHandle& nh); private: void scanCallback(sensor_msgs::LaserScan::Ptr msg); void odomCallback(geometry_msgs::Pose::Ptr msg); ros::NodeHandle n_; geometry_msgs::TransformStamped t_; tf::TransformBroadcaster broadcaster_; ros::Subscriber laser_sub_; ros::Subscriber odom_sub_; ros::Publisher laser_pub_; ros::Publisher odom_pub_; }; }
17.142857
55
0.728333
CtfChan
516d06a3b4c1c5d214b2de1e4313584fe89cae16
54,826
cpp
C++
include/enki/viewer/objects/EPuckBody.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
include/enki/viewer/objects/EPuckBody.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
include/enki/viewer/objects/EPuckBody.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
/* Enki - a fast 2D robot simulator Copyright (C) 1999-2013 Stephane Magnenat <stephane at magnenat dot net> Copyright (C) 2004-2005 Markus Waibel <markus dot waibel at epfl dot ch> Copyright (c) 2004-2005 Antoine Beyeler <abeyeler at ab-ware dot com> Copyright (C) 2005-2006 Laboratory of Intelligent Systems, EPFL, Lausanne Copyright (C) 2006 Laboratory of Robotics Systems, EPFL, Lausanne See AUTHORS for details This program is free software; the authors of any publication arising from research using this software are asked to add the following reference: Enki - a fast 2D robot simulator http://home.gna.org/enki Stephane Magnenat <stephane at magnenat dot net>, Markus Waibel <markus dot waibel at epfl dot ch> Laboratory of Intelligent Systems, EPFL, Lausanne. You can redistribute this program and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // E-puck object file #include <QtOpenGL> namespace Enki { // 262 Verticies // 610 Texture Coordinates // 275 Normals // 536 Triangles static short face_indicies[536][9] = { // (unnamed) {204,188,217 ,0,1,2 ,0,1,2 }, {179,162,172 ,3,4,5 ,3,4,5 }, {179,180,162 ,3,0,4 ,3,6,4 }, {235,261,233 ,6,7,8 ,7,8,9 }, {235,244,261 ,6,9,7 ,7,10,8 }, {231,261,1 ,10,7,11 ,11,8,12 }, {231,233,261 ,10,8,7 ,11,9,8 }, {257,1,261 ,12,11,7 ,13,12,8 }, {234,247,235 ,13,14,6 ,14,15,7 }, {234,246,247 ,13,15,14 ,14,16,15 }, {215,234,196 ,16,13,0 ,17,14,18 }, {215,245,234 ,16,17,13 ,17,19,14 }, {245,246,234 ,17,15,13 ,19,16,14 }, {216,196,205 ,18,0,0 ,20,18,21 }, {216,215,196 ,18,16,0 ,20,17,18 }, {162,150,172 ,4,19,5 ,4,22,5 }, {162,149,150 ,4,20,19 ,4,23,22 }, {205,204,216 ,0,0,18 ,21,24,20 }, {188,179,172 ,1,3,5 ,1,3,5 }, {188,189,179 ,1,21,3 ,1,25,3 }, {247,244,235 ,14,9,6 ,15,10,7 }, {216,204,217 ,18,0,2 ,20,24,26 }, {217,188,172 ,2,1,5 ,2,1,5 }, {231,222,223 ,10,22,23 ,11,27,28 }, {231,0,222 ,10,24,22 ,11,29,27 }, {2,231,1 ,25,10,11 ,30,11,12 }, {2,0,231 ,25,24,10 ,30,29,11 }, {183,199,211 ,26,21,27 ,31,32,33 }, {154,176,166 ,28,29,30 ,34,35,36 }, {154,175,176 ,28,21,29 ,34,37,35 }, {249,226,225 ,31,32,33 ,38,39,40 }, {249,238,226 ,31,34,32 ,38,41,39 }, {249,229,3 ,31,35,36 ,38,42,43 }, {249,225,229 ,31,33,35 ,38,40,42 }, {249,3,253 ,31,36,37 ,38,43,44 }, {241,227,226 ,38,39,32 ,45,46,39 }, {241,240,227 ,38,40,39 ,45,47,46 }, {227,209,192 ,39,41,21 ,46,48,49 }, {227,239,209 ,39,42,41 ,46,50,48 }, {240,239,227 ,40,42,39 ,47,50,46 }, {192,210,200 ,21,43,21 ,49,51,52 }, {192,209,210 ,21,41,43 ,49,48,51 }, {142,154,166 ,44,28,30 ,53,34,36 }, {142,143,154 ,44,45,28 ,53,54,34 }, {199,200,210 ,21,21,43 ,32,52,51 }, {176,183,166 ,29,26,30 ,35,31,36 }, {176,184,183 ,29,0,26 ,35,55,31 }, {238,241,226 ,34,38,32 ,41,45,39 }, {199,210,211 ,21,43,27 ,32,51,33 }, {183,211,166 ,26,27,30 ,31,33,36 }, {222,229,219 ,22,35,46 ,27,42,56 }, {222,0,229 ,22,24,35 ,27,29,42 }, {3,0,2 ,36,24,25 ,43,29,30 }, {3,229,0 ,36,35,24 ,43,42,29 }, {257,259,1 ,12,47,11 ,13,57,12 }, {2,259,258 ,25,47,48 ,30,57,58 }, {2,1,259 ,25,11,47 ,30,12,57 }, {252,2,258 ,49,25,48 ,59,30,58 }, {252,3,2 ,49,36,25 ,59,43,30 }, {3,252,253 ,36,49,37 ,43,59,44 }, {163,173,172 ,50,51,5 ,60,61,5 }, {163,158,173 ,50,52,51 ,60,62,61 }, {150,163,172 ,19,50,5 ,22,60,5 }, {150,151,163 ,19,53,50 ,22,63,60 }, {173,159,169 ,51,54,55 ,61,64,65 }, {173,158,159 ,51,52,54 ,61,62,64 }, {167,155,166 ,56,57,30 ,66,67,36 }, {167,156,155 ,56,58,57 ,66,68,67 }, {155,142,166 ,57,44,30 ,67,53,36 }, {155,144,142 ,57,59,44 ,67,69,53 }, {159,167,169 ,54,56,55 ,64,66,65 }, {159,156,167 ,54,58,56 ,64,68,66 }, {195,196,234 ,0,0,13 ,70,18,14 }, {192,191,227 ,21,21,39 ,49,71,46 }, {151,148,163 ,53,60,50 ,63,72,60 }, {141,144,155 ,61,59,57 ,73,69,67 }, {234,235,232 ,62,62,62 ,74,75,76 }, {226,227,224 ,62,62,62 ,77,78,79 }, {203,205,196 ,63,64,65 ,80,81,82 }, {228,219,229 ,21,21,21 ,83,84,85 }, {228,218,219 ,21,21,21 ,83,86,84 }, {158,163,159 ,62,62,62 ,87,88,89 }, {146,163,148 ,21,21,21 ,90,91,92 }, {146,160,163 ,21,21,21 ,90,93,91 }, {180,161,162 ,62,62,62 ,94,95,96 }, {180,178,161 ,62,62,62 ,94,97,95 }, {161,149,162 ,66,66,66 ,98,99,100 }, {161,145,149 ,66,66,66 ,98,101,99 }, {233,231,235 ,62,62,62 ,102,103,104 }, {230,232,231 ,62,62,62 ,105,106,107 }, {232,235,231 ,62,62,62 ,106,108,109 }, {223,230,231 ,0,0,0 ,110,111,112 }, {223,221,230 ,0,0,0 ,110,113,111 }, {234,194,195 ,62,62,62 ,114,115,116 }, {234,232,194 ,62,62,62 ,114,117,115 }, {189,187,179 ,67,68,69 ,118,119,120 }, {186,189,188 ,70,67,71 ,121,122,123 }, {186,187,189 ,70,68,67 ,121,124,122 }, {204,186,188 ,72,70,71 ,125,126,127 }, {204,202,186 ,72,73,70 ,125,128,126 }, {205,202,204 ,64,73,72 ,129,130,131 }, {205,203,202 ,64,63,73 ,129,132,130 }, {148,147,146 ,62,62,62 ,133,134,135 }, {148,151,147 ,62,62,62 ,133,136,134 }, {147,149,145 ,62,62,62 ,134,137,138 }, {147,150,149 ,62,62,62 ,134,139,137 }, {150,147,151 ,62,62,62 ,140,141,142 }, {159,160,157 ,62,62,62 ,143,144,145 }, {159,163,160 ,62,62,62 ,143,146,144 }, {222,4,223 ,62,62,62 ,147,148,149 }, {223,220,221 ,62,62,62 ,150,151,152 }, {223,4,220 ,62,62,62 ,150,148,151 }, {179,185,5 ,69,74,75 ,153,154,155 }, {179,187,185 ,69,68,74 ,153,119,154 }, {8,196,195 ,76,65,76 ,156,82,157 }, {8,7,196 ,76,77,65 ,156,158,82 }, {6,178,180 ,62,62,62 ,159,160,161 }, {6,177,178 ,62,62,62 ,159,162,160 }, {5,180,179 ,75,66,69 ,155,163,153 }, {5,6,180 ,75,66,66 ,155,159,163 }, {195,193,8 ,62,62,62 ,157,164,156 }, {195,194,193 ,62,62,62 ,157,165,164 }, {7,203,196 ,77,63,65 ,158,166,167 }, {7,201,203 ,77,78,63 ,158,168,166 }, {155,156,159 ,62,62,62 ,169,170,171 }, {155,140,141 ,0,0,0 ,172,173,174 }, {155,153,140 ,0,0,0 ,172,175,173 }, {152,175,154 ,62,62,62 ,176,177,178 }, {152,174,175 ,62,62,62 ,176,179,177 }, {143,152,154 ,66,66,66 ,180,181,182 }, {143,138,152 ,66,66,66 ,180,183,181 }, {229,225,226 ,62,62,62 ,184,185,186 }, {224,228,229 ,62,62,62 ,187,188,184 }, {226,224,229 ,62,62,62 ,189,190,191 }, {190,227,191 ,62,62,62 ,192,193,194 }, {190,224,227 ,62,62,62 ,192,195,193 }, {182,184,176 ,79,80,81 ,196,197,198 }, {184,181,183 ,80,82,83 ,199,200,201 }, {184,182,181 ,80,79,82 ,199,196,200 }, {181,199,183 ,82,84,83 ,202,203,204 }, {181,197,199 ,82,85,84 ,202,205,203 }, {197,200,199 ,85,86,84 ,206,207,208 }, {197,198,200 ,85,87,86 ,206,209,207 }, {139,141,140 ,62,62,62 ,210,211,212 }, {139,144,141 ,62,62,62 ,210,213,211 }, {143,139,138 ,62,62,62 ,214,215,216 }, {143,142,139 ,62,62,62 ,214,217,215 }, {139,142,144 ,62,62,62 ,218,219,220 }, {200,198,192 ,86,87,88 ,221,222,223 }, {153,159,157 ,62,62,62 ,224,225,226 }, {153,155,159 ,62,62,62 ,224,227,225 }, {4,222,219 ,62,62,62 ,148,228,229 }, {220,219,218 ,62,62,62 ,230,229,231 }, {220,4,219 ,62,62,62 ,230,148,229 }, {185,176,5 ,74,81,75 ,232,233,155 }, {185,182,176 ,74,79,81 ,232,234,233 }, {192,8,191 ,88,76,76 ,235,156,194 }, {192,7,8 ,88,77,76 ,235,158,156 }, {174,6,175 ,62,62,62 ,236,159,237 }, {174,177,6 ,62,62,62 ,236,238,159 }, {175,5,176 ,66,75,81 ,239,155,198 }, {175,6,5 ,66,66,75 ,239,159,155 }, {193,191,8 ,62,62,62 ,240,241,156 }, {193,190,191 ,62,62,62 ,240,242,241 }, {198,7,192 ,87,77,88 ,243,158,244 }, {198,201,7 ,87,78,77 ,243,245,158 }, {51,48,60 ,0,0,0 ,246,247,248 }, {51,46,48 ,0,0,0 ,246,249,247 }, {44,48,46 ,89,90,91 ,250,247,249 }, {44,45,48 ,89,92,90 ,250,251,247 }, {42,44,40 ,93,94,95 ,252,250,253 }, {42,45,44 ,93,93,94 ,252,251,250 }, {25,68,20 ,96,97,98 ,254,255,256 }, {25,55,68 ,96,99,97 ,254,257,255 }, {31,37,36 ,100,101,102 ,258,259,260 }, {31,30,37 ,100,103,101 ,258,261,259 }, {53,31,36 ,104,100,102 ,262,258,260 }, {53,24,31 ,104,105,100 ,262,263,258 }, {68,173,20 ,97,51,98 ,255,264,256 }, {68,172,173 ,97,5,51 ,255,265,264 }, {247,63,244 ,14,106,107 ,266,267,268 }, {247,244,63 ,14,107,106 ,266,10,267 }, {244,61,261 ,107,108,109 ,269,270,271 }, {244,63,61 ,107,106,108 ,269,267,270 }, {58,257,62 ,110,111,112 ,272,273,274 }, {58,259,257 ,110,113,111 ,272,275,273 }, {61,257,261 ,108,111,109 ,270,273,276 }, {61,62,257 ,108,112,111 ,270,274,273 }, {50,259,58 ,114,113,110 ,277,278,272 }, {50,49,259 ,114,115,113 ,277,279,278 }, {63,242,243 ,106,116,21 ,267,280,281 }, {63,56,242 ,106,117,116 ,267,282,280 }, {242,23,212 ,116,118,119 ,280,283,284 }, {242,56,23 ,116,117,118 ,280,282,283 }, {212,27,213 ,119,120,121 ,284,285,286 }, {212,23,27 ,119,118,120 ,284,283,285 }, {24,213,27 ,122,121,120 ,263,287,285 }, {24,53,213 ,122,104,121 ,263,262,287 }, {21,245,215 ,123,17,16 ,288,289,290 }, {21,57,245 ,123,124,17 ,288,291,289 }, {28,215,216 ,125,16,18 ,292,290,293 }, {28,21,215 ,125,123,16 ,292,288,290 }, {245,247,246 ,17,14,15 ,294,295,296 }, {245,57,247 ,17,124,14 ,294,291,295 }, {256,40,44 ,126,95,94 ,297,253,250 }, {256,41,40 ,126,127,95 ,297,298,253 }, {44,43,256 ,94,128,126 ,250,299,300 }, {254,61,260 ,129,108,130 ,301,270,302 }, {254,62,61 ,129,112,108 ,301,274,270 }, {256,62,254 ,126,112,129 ,300,274,303 }, {256,43,62 ,126,128,112 ,300,299,274 }, {61,63,260 ,108,106,130 ,270,267,304 }, {247,57,39 ,14,124,131 ,305,291,306 }, {39,244,247 ,131,107,14 ,306,307,308 }, {39,38,244 ,131,132,107 ,306,309,307 }, {38,35,32 ,132,133,134 ,309,310,311 }, {38,39,35 ,132,131,133 ,309,306,310 }, {35,28,34 ,133,125,135 ,310,292,312 }, {35,21,28 ,133,123,125 ,310,288,292 }, {32,34,33 ,134,135,136 ,311,312,313 }, {32,35,34 ,134,133,135 ,311,310,312 }, {39,21,35 ,131,123,133 ,306,288,310 }, {39,57,21 ,131,124,123 ,306,291,288 }, {30,33,34 ,103,136,135 ,261,313,312 }, {30,31,33 ,103,100,136 ,261,258,313 }, {28,30,34 ,125,103,135 ,292,261,312 }, {28,22,30 ,125,137,103 ,292,314,261 }, {32,56,38 ,134,117,132 ,311,282,309 }, {32,23,56 ,134,118,117 ,311,283,282 }, {33,23,32 ,136,118,134 ,313,283,311 }, {33,27,23 ,136,120,118 ,313,285,283 }, {38,63,244 ,132,106,107 ,309,267,315 }, {38,56,63 ,132,117,106 ,309,282,267 }, {44,47,43 ,89,138,139 ,250,316,299 }, {44,46,47 ,89,91,138 ,250,249,316 }, {59,49,50 ,140,115,114 ,317,279,277 }, {52,50,58 ,141,142,143 ,318,277,272 }, {52,51,50 ,141,144,142 ,318,246,277 }, {33,24,27 ,136,122,120 ,313,263,285 }, {33,31,24 ,136,100,122 ,313,258,263 }, {37,22,29 ,101,145,146 ,259,314,319 }, {37,30,22 ,101,103,145 ,259,261,314 }, {51,47,46 ,0,0,0 ,246,316,249 }, {51,52,47 ,0,0,0 ,246,318,316 }, {51,59,50 ,144,147,142 ,246,317,277 }, {51,60,59 ,144,148,147 ,246,248,317 }, {22,216,29 ,145,18,146 ,314,320,319 }, {22,28,216 ,145,125,18 ,314,292,320 }, {10,25,20 ,149,96,98 ,321,254,256 }, {10,69,25 ,149,150,96 ,321,322,254 }, {10,173,169 ,149,51,55 ,321,323,324 }, {10,20,173 ,149,98,51 ,321,256,323 }, {49,258,259 ,151,48,47 ,279,325,326 }, {49,9,258 ,151,152,48 ,279,327,325 }, {18,60,48 ,153,148,90 ,328,248,247 }, {18,19,60 ,153,154,148 ,328,329,248 }, {18,48,45 ,62,62,62 ,328,247,251 }, {17,45,42 ,155,92,156 ,330,251,252 }, {17,18,45 ,155,153,92 ,330,328,251 }, {16,42,40 ,157,156,158 ,331,252,253 }, {16,17,42 ,157,155,156 ,331,330,252 }, {12,54,26 ,159,160,161 ,332,333,334 }, {12,15,54 ,159,162,160 ,332,335,333 }, {14,171,170 ,62,62,62 ,336,337,338 }, {14,168,171 ,62,62,62 ,336,339,337 }, {15,170,54 ,162,163,160 ,335,340,333 }, {15,14,170 ,162,163,163 ,335,336,340 }, {256,13,41 ,62,62,62 ,341,342,298 }, {256,255,13 ,62,62,62 ,341,343,342 }, {13,40,41 ,164,158,165 ,342,253,298 }, {13,16,40 ,164,157,158 ,342,331,253 }, {59,9,49 ,166,152,151 ,317,327,279 }, {59,60,9 ,166,148,152 ,317,248,327 }, {60,19,9 ,148,154,152 ,248,329,327 }, {58,47,52 ,167,167,167 ,272,316,318 }, {58,43,47 ,167,167,167 ,272,299,316 }, {58,62,43 ,110,112,128 ,272,274,299 }, {260,63,243 ,76,76,76 ,344,267,345 }, {55,65,64 ,99,168,169 ,257,346,347 }, {55,26,65 ,99,161,168 ,257,334,346 }, {64,36,37 ,169,102,101 ,347,260,259 }, {64,65,36 ,169,168,102 ,347,346,260 }, {66,37,29 ,170,101,146 ,348,259,319 }, {66,64,37 ,170,169,101 ,348,347,259 }, {64,68,55 ,169,97,99 ,347,255,257 }, {64,66,68 ,169,170,97 ,347,348,255 }, {26,67,65 ,161,171,168 ,334,349,346 }, {26,54,67 ,161,160,171 ,334,333,349 }, {65,53,36 ,168,104,102 ,346,262,260 }, {65,67,53 ,168,171,104 ,346,349,262 }, {214,53,67 ,172,104,171 ,350,262,349 }, {214,213,53 ,172,121,104 ,350,286,262 }, {170,67,54 ,173,171,160 ,351,349,333 }, {170,214,67 ,173,172,171 ,351,350,349 }, {29,217,66 ,146,2,170 ,319,352,348 }, {29,216,217 ,146,18,2 ,319,353,352 }, {66,172,68 ,170,5,97 ,348,354,255 }, {66,217,172 ,170,2,5 ,348,355,354 }, {55,69,11 ,99,150,167 ,257,322,356 }, {55,25,69 ,99,96,150 ,257,254,322 }, {11,26,55 ,167,161,99 ,356,334,257 }, {11,12,26 ,167,159,161 ,356,332,334 }, {98,101,110 ,21,21,21 ,357,358,359 }, {98,96,101 ,21,21,21 ,357,360,358 }, {98,94,96 ,174,175,176 ,357,361,360 }, {98,95,94 ,174,92,175 ,357,362,361 }, {94,92,90 ,177,178,179 ,361,363,364 }, {94,95,92 ,177,178,178 ,361,362,363 }, {118,75,70 ,180,181,182 ,365,366,367 }, {118,105,75 ,180,183,181 ,365,368,366 }, {87,81,86 ,184,185,186 ,369,370,371 }, {87,80,81 ,184,187,185 ,369,372,370 }, {81,103,86 ,185,188,186 ,370,373,371 }, {81,74,103 ,185,189,188 ,370,374,373 }, {167,118,70 ,56,180,182 ,375,365,367 }, {167,166,118 ,56,30,180 ,375,376,365 }, {113,241,238 ,190,38,191 ,377,378,379 }, {113,238,241 ,190,191,38 ,377,41,378 }, {111,238,249 ,192,191,193 ,380,381,382 }, {111,113,238 ,192,190,191 ,380,377,381 }, {253,108,112 ,194,195,196 ,383,384,385 }, {253,252,108 ,194,197,195 ,383,386,384 }, {253,111,249 ,194,192,193 ,387,380,388 }, {253,112,111 ,194,196,192 ,387,385,380 }, {252,100,108 ,197,198,195 ,389,390,384 }, {252,99,100 ,197,199,198 ,389,391,390 }, {236,113,237 ,200,190,0 ,392,377,393 }, {236,106,113 ,200,201,190 ,392,394,377 }, {73,236,206 ,202,200,203 ,395,392,396 }, {73,106,236 ,202,201,200 ,395,394,392 }, {77,206,207 ,204,203,205 ,397,396,398 }, {77,73,206 ,204,202,203 ,397,395,396 }, {207,74,77 ,205,206,204 ,399,374,397 }, {207,103,74 ,205,188,206 ,399,373,374 }, {239,71,209 ,42,207,41 ,400,401,402 }, {239,107,71 ,42,208,207 ,400,403,401 }, {209,78,210 ,41,209,43 ,402,404,405 }, {209,71,78 ,41,207,209 ,402,401,404 }, {241,239,240 ,38,42,40 ,406,407,408 }, {241,107,239 ,38,208,42 ,406,403,407 }, {90,250,94 ,179,210,177 ,364,409,361 }, {90,91,250 ,179,211,210 ,364,410,409 }, {93,94,250 ,212,177,210 ,411,361,412 }, {111,251,248 ,192,213,214 ,380,413,414 }, {111,112,251 ,192,196,213 ,380,385,413 }, {112,250,251 ,196,210,213 ,385,412,415 }, {112,93,250 ,196,212,210 ,385,411,412 }, {113,111,248 ,190,192,214 ,377,380,416 }, {107,241,89 ,208,38,215 ,403,417,418 }, {238,89,241 ,191,215,38 ,419,418,420 }, {238,88,89 ,191,216,215 ,419,421,418 }, {85,88,82 ,217,216,218 ,422,421,423 }, {85,89,88 ,217,215,216 ,422,418,421 }, {78,85,84 ,209,217,219 ,404,422,424 }, {78,71,85 ,209,207,217 ,404,401,422 }, {84,82,83 ,219,218,220 ,424,423,425 }, {84,85,82 ,219,217,218 ,424,422,423 }, {71,89,85 ,207,215,217 ,401,418,422 }, {71,107,89 ,207,208,215 ,401,403,418 }, {83,80,84 ,220,187,219 ,425,372,424 }, {83,81,80 ,220,185,187 ,425,370,372 }, {80,78,84 ,187,209,219 ,372,404,424 }, {80,72,78 ,187,221,209 ,372,426,404 }, {106,82,88 ,201,218,216 ,394,423,421 }, {106,73,82 ,201,202,218 ,394,395,423 }, {73,83,82 ,202,220,218 ,395,425,423 }, {73,77,83 ,202,204,220 ,395,397,425 }, {113,88,238 ,190,216,191 ,377,421,427 }, {113,106,88 ,190,201,216 ,377,394,421 }, {97,94,93 ,222,175,139 ,428,361,411 }, {97,96,94 ,222,176,175 ,428,360,361 }, {99,109,100 ,199,223,198 ,391,429,390 }, {100,102,108 ,224,225,226 ,390,430,384 }, {100,101,102 ,224,227,225 ,390,358,430 }, {74,83,77 ,206,220,204 ,374,425,397 }, {74,81,83 ,206,185,220 ,374,370,425 }, {72,87,79 ,228,184,229 ,426,369,431 }, {72,80,87 ,228,187,184 ,426,372,369 }, {97,101,96 ,21,21,21 ,428,358,360 }, {97,102,101 ,21,21,21 ,428,430,358 }, {109,101,100 ,230,227,224 ,429,358,390 }, {109,110,101 ,230,231,227 ,429,359,358 }, {210,72,79 ,43,228,229 ,432,426,431 }, {210,78,72 ,43,209,228 ,432,404,426 }, {75,10,70 ,181,149,182 ,366,321,367 }, {75,69,10 ,181,150,149 ,366,322,321 }, {167,10,169 ,56,149,55 ,433,321,434 }, {167,70,10 ,56,182,149 ,433,367,321 }, {258,99,252 ,48,232,49 ,435,391,436 }, {258,9,99 ,48,152,232 ,435,327,391 }, {110,18,98 ,231,153,174 ,359,328,357 }, {110,19,18 ,231,154,153 ,359,329,328 }, {98,18,95 ,62,62,62 ,357,328,362 }, {95,17,92 ,92,155,233 ,362,330,363 }, {95,18,17 ,92,153,155 ,362,328,330 }, {92,16,90 ,233,157,234 ,363,331,364 }, {92,17,16 ,233,155,157 ,363,330,331 }, {104,12,76 ,235,159,236 ,437,332,438 }, {104,15,12 ,235,162,159 ,437,335,332 }, {165,14,164 ,62,62,62 ,439,336,440 }, {165,168,14 ,62,62,62 ,439,441,336 }, {164,15,104 ,163,162,235 ,442,335,437 }, {164,14,15 ,163,163,162 ,442,336,335 }, {13,250,91 ,62,62,62 ,342,443,410 }, {13,255,250 ,62,62,62 ,342,444,443 }, {90,13,91 ,234,164,165 ,364,342,410 }, {90,16,13 ,234,157,164 ,364,331,342 }, {9,109,99 ,152,237,232 ,327,429,391 }, {9,110,109 ,152,231,237 ,327,359,429 }, {19,110,9 ,154,231,152 ,329,359,327 }, {97,108,102 ,167,167,167 ,428,384,430 }, {97,93,108 ,167,167,167 ,428,411,384 }, {112,108,93 ,196,195,212 ,385,384,411 }, {113,248,237 ,76,76,76 ,377,445,446 }, {115,105,114 ,238,183,239 ,447,368,448 }, {115,76,105 ,238,236,183 ,447,438,368 }, {86,114,87 ,186,239,184 ,371,448,369 }, {86,115,114 ,186,238,239 ,371,447,448 }, {87,116,79 ,184,240,229 ,369,449,431 }, {87,114,116 ,184,239,240 ,369,448,449 }, {118,114,105 ,180,239,183 ,365,448,368 }, {118,116,114 ,180,240,239 ,365,449,448 }, {117,76,115 ,241,236,238 ,450,438,447 }, {117,104,76 ,241,235,236 ,450,437,438 }, {103,115,86 ,188,238,186 ,373,447,371 }, {103,117,115 ,188,241,238 ,373,450,447 }, {103,208,117 ,188,242,241 ,373,451,450 }, {103,207,208 ,188,205,242 ,373,398,451 }, {117,164,104 ,241,243,235 ,450,452,437 }, {117,208,164 ,241,242,243 ,450,453,452 }, {211,79,116 ,27,229,240 ,454,431,449 }, {211,210,79 ,27,43,229 ,454,405,431 }, {166,116,118 ,30,240,180 ,455,449,365 }, {166,211,116 ,30,27,240 ,455,456,449 }, {69,105,11 ,150,183,167 ,322,368,356 }, {69,75,105 ,150,181,183 ,322,366,368 }, {76,11,105 ,236,167,183 ,438,356,368 }, {76,12,11 ,236,159,167 ,438,332,356 }, {171,146,147 ,244,245,66 ,457,458,459 }, {171,160,146 ,244,246,245 ,457,460,458 }, {147,170,171 ,21,173,21 ,461,462,463 }, {147,161,170 ,21,21,173 ,461,464,462 }, {260,232,230 ,76,76,76 ,465,466,467 }, {260,243,232 ,76,76,76 ,465,468,466 }, {256,254,230 ,76,76,76 ,469,470,471 }, {232,242,194 ,21,116,21 ,472,473,474 }, {232,243,242 ,21,21,116 ,472,475,473 }, {168,160,171 ,247,246,244 ,476,477,478 }, {168,157,160 ,247,247,246 ,476,479,477 }, {256,119,255 ,76,76,76 ,480,481,482 }, {256,230,119 ,76,76,76 ,480,483,481 }, {220,230,221 ,76,76,76 ,484,485,486 }, {220,119,230 ,76,76,76 ,484,487,485 }, {254,260,230 ,76,76,76 ,488,489,490 }, {120,131,127 ,248,249,248 ,491,492,493 }, {120,125,131 ,248,250,249 ,491,494,492 }, {130,123,129 ,251,252,252 ,495,496,497 }, {130,124,123 ,251,253,252 ,495,498,496 }, {123,128,129 ,254,255,256 ,496,499,497 }, {123,122,128 ,254,257,255 ,496,500,499 }, {201,130,203 ,78,251,63 ,501,495,502 }, {201,124,130 ,78,253,251 ,501,498,495 }, {125,187,131 ,250,68,249 ,494,503,492 }, {125,185,187 ,250,74,68 ,494,504,503 }, {121,127,126 ,258,259,260 ,505,493,506 }, {121,120,127 ,258,261,259 ,505,491,493 }, {122,194,128 ,257,262,255 ,500,507,499 }, {122,193,194 ,257,263,262 ,500,508,507 }, {121,178,177 ,258,264,265 ,505,509,510 }, {121,126,178 ,258,260,264 ,505,506,509 }, {130,213,214 ,21,121,172 ,495,511,512 }, {130,129,213 ,21,21,121 ,495,497,511 }, {203,130,202 ,21,21,21 ,513,495,514 }, {202,130,214 ,21,21,172 ,515,516,517 }, {131,187,186 ,21,21,21 ,492,518,519 }, {186,202,214 ,21,21,172 ,520,521,522 }, {131,186,214 ,21,21,172 ,492,523,524 }, {170,131,214 ,173,21,172 ,525,492,526 }, {170,127,131 ,173,21,21 ,525,493,492 }, {213,128,212 ,121,21,119 ,527,499,528 }, {213,129,128 ,121,21,21 ,527,497,499 }, {212,194,242 ,119,21,116 ,529,530,531 }, {212,128,194 ,119,21,21 ,529,499,530 }, {170,126,127 ,173,21,21 ,462,506,493 }, {178,170,161 ,21,173,21 ,532,533,534 }, {178,126,170 ,21,21,173 ,532,506,533 }, {140,165,139 ,266,267,66 ,535,536,537 }, {140,153,165 ,266,268,267 ,535,538,536 }, {164,139,165 ,243,0,0 ,539,540,541 }, {164,152,139 ,243,0,0 ,539,542,540 }, {224,248,228 ,76,76,76 ,543,544,545 }, {224,237,248 ,76,76,76 ,543,546,544 }, {251,250,228 ,76,76,76 ,547,548,549 }, {236,224,190 ,200,0,0 ,550,551,552 }, {236,237,224 ,200,0,0 ,550,553,551 }, {153,168,165 ,268,247,267 ,554,555,556 }, {153,157,168 ,268,247,247 ,554,557,555 }, {119,250,255 ,76,76,76 ,481,558,559 }, {119,228,250 ,76,76,76 ,481,560,558 }, {228,220,218 ,76,76,76 ,561,562,563 }, {228,119,220 ,76,76,76 ,561,564,562 }, {248,251,228 ,76,76,76 ,565,566,567 }, {137,120,133 ,249,248,248 ,568,491,569 }, {137,125,120 ,249,250,248 ,568,494,491 }, {123,136,135 ,252,251,252 ,496,570,571 }, {123,124,136 ,252,253,251 ,496,498,570 }, {134,123,135 ,269,254,256 ,572,496,571 }, {134,122,123 ,269,257,254 ,572,500,496 }, {136,201,198 ,251,78,87 ,570,573,574 }, {136,124,201 ,251,253,78 ,570,498,573 }, {182,125,137 ,79,250,249 ,575,494,568 }, {182,185,125 ,79,74,250 ,575,576,494 }, {133,121,132 ,270,258,271 ,569,505,577 }, {133,120,121 ,270,261,258 ,569,491,505 }, {190,122,134 ,272,257,269 ,578,500,572 }, {190,193,122 ,272,263,257 ,578,579,500 }, {174,121,177 ,273,258,265 ,580,505,581 }, {174,132,121 ,273,271,258 ,580,577,505 }, {207,136,208 ,205,0,242 ,582,570,583 }, {207,135,136 ,205,0,0 ,582,571,570 }, {136,198,197 ,0,0,0 ,570,584,585 }, {136,197,208 ,0,0,242 ,570,586,587 }, {182,137,181 ,0,0,0 ,588,568,589 }, {197,181,208 ,0,0,242 ,590,591,592 }, {181,137,208 ,0,0,242 ,593,568,592 }, {137,164,208 ,0,243,242 ,568,594,595 }, {137,133,164 ,0,0,243 ,568,569,594 }, {134,207,206 ,0,205,203 ,572,596,597 }, {134,135,207 ,0,0,205 ,572,571,596 }, {190,206,236 ,0,203,200 ,598,599,600 }, {190,134,206 ,0,0,203 ,598,572,599 }, {132,164,133 ,0,243,0 ,577,601,569 }, {164,174,152 ,243,0,0 ,602,603,604 }, {164,132,174 ,243,0,0 ,602,577,603 }, {147,145,161 ,21,21,21 ,605,606,607 }, {138,139,152 ,0,0,0 ,608,540,609 } }; static GLfloat vertices [262][3] = { {0.0f,-3.49998f,0.35235f},{-0.789509f,-3.40949f,-1.38255f},{0.0f,-3.5f,-1.33903f}, {0.790101f,-3.40936f,-1.38255f},{0.0f,-3.42929f,1.60235f},{0.0f,0.775f,0.00235001f}, {0.0f,0.775f,0.35235f},{0.0f,-0.775f,0.00235001f},{0.0f,-0.775f,0.35235f}, {0.0f,-3.4799f,-1.92265f},{0.0f,3.44142f,-1.93907f},{0.0f,2.58603f,-1.99765f}, {0.0f,2.05f,-1.99765f},{0.0f,-2.55f,-1.84765f},{0.0f,1.9f,-1.84765f}, {0.0f,1.93867f,-1.94817f},{0.0f,-2.59428f,-1.95406f},{0.0f,-2.7f,-1.99765f}, {0.0f,-2.75f,-1.99765f},{0.0f,-3.4f,-1.98255f},{-1.1183f,3.25465f,-1.93907f}, {-2.15607f,-1.6893f,-1.40561f},{-2.12344f,-1.51075f,-1.93083f},{-1.84393f,-1.6893f,-1.40561f}, {-1.87653f,-1.47911f,-1.95856f},{-1.0865f,3.11599f,-1.99765f},{-1.95f,2.05f,-1.99765f}, {-1.84393f,-1.51498f,-1.86148f},{-2.15607f,-1.51498f,-1.86148f},{-2.15607f,-1.40982f,-1.95372f}, {-2.05f,-1.50873f,-1.96042f},{-1.95f,-1.50873f,-1.96042f},{-1.95f,-1.731f,-1.42385f}, {-1.95f,-1.55854f,-1.86722f},{-2.05f,-1.55854f,-1.86722f},{-2.05f,-1.73096f,-1.42391f}, {-1.95f,-1.40982f,-1.99765f},{-2.05f,-1.40982f,-1.99765f},{-1.95f,-2.08797f,-1.11079f}, {-2.05f,-2.08779f,-1.11088f},{-0.800937f,-2.5946f,-1.95438f},{-0.811314f,-2.55f,-1.84765f}, {-0.8f,-2.7f,-1.99765f},{-0.811314f,-2.9f,-1.84765f},{-0.800937f,-2.8554f,-1.95438f}, {-0.8f,-2.75f,-1.99765f},{-0.2f,-2.85603f,-1.95375f},{-0.2f,-2.9f,-1.84765f}, {-0.2f,-2.75f,-1.99765f},{-0.802028f,-3.37875f,-1.934f},{-0.802002f,-3.22955f,-1.9344f}, {-0.2f,-3.32142f,-1.93412f},{-0.2f,-3.29393f,-1.84765f},{-1.83058f,-1.40982f,-1.93842f}, {-1.83867f,1.93867f,-1.94817f},{-2.05f,2.58603f,-1.99765f},{-1.84393f,-2.04195f,-1.04672f}, {-2.15607f,-2.04195f,-1.04672f},{-0.811314f,-3.19871f,-1.84765f},{-0.800037f,-3.30454f,-1.98904f}, {-0.2f,-3.39411f,-1.98907f},{-1.28094f,-3.04125f,-1.14291f},{-0.998289f,-3.14538f,-1.39994f}, {-1.8f,-2.7f,-0.99765f},{-2.05f,0.0f,-1.99765f},{-1.95f,0.0f,-1.99765f}, {-2.15607f,0.0f,-1.95372f},{-1.83398f,0.0f,-1.94253f},{-2.15607f,2.66025f,-1.93818f}, {0.0f,3.29998f,-1.99765f},{1.1183f,3.25465f,-1.93907f},{2.15607f,-1.6893f,-1.40561f}, {2.12344f,-1.51075f,-1.93083f},{1.84393f,-1.6893f,-1.40561f},{1.87653f,-1.47911f,-1.95856f}, {1.0865f,3.11599f,-1.99765f},{1.95f,2.05f,-1.99765f},{1.84393f,-1.51498f,-1.86148f}, {2.15607f,-1.51498f,-1.86148f},{2.15607f,-1.40982f,-1.95372f},{2.05f,-1.50873f,-1.96042f}, {1.95f,-1.50873f,-1.96042f},{1.95f,-1.731f,-1.42385f},{1.95f,-1.55854f,-1.86722f}, {2.05f,-1.55854f,-1.86722f},{2.05f,-1.73096f,-1.42391f},{1.95f,-1.40982f,-1.99765f}, {2.05f,-1.40982f,-1.99765f},{1.95f,-2.08797f,-1.11079f},{2.05f,-2.08779f,-1.11088f}, {0.800937f,-2.5946f,-1.95438f},{0.811314f,-2.55f,-1.84765f},{0.8f,-2.7f,-1.99765f}, {0.811314f,-2.9f,-1.84765f},{0.800937f,-2.8554f,-1.95438f},{0.8f,-2.75f,-1.99765f}, {0.2f,-2.85603f,-1.95375f},{0.2f,-2.9f,-1.84765f},{0.2f,-2.75f,-1.99765f}, {0.802028f,-3.37875f,-1.934f},{0.802002f,-3.22955f,-1.9344f},{0.2f,-3.32142f,-1.93412f}, {0.2f,-3.29393f,-1.84765f},{1.83058f,-1.40982f,-1.93842f},{1.83867f,1.93867f,-1.94817f}, {2.05f,2.58603f,-1.99765f},{1.84393f,-2.04195f,-1.04672f},{2.15607f,-2.04195f,-1.04672f}, {0.811314f,-3.19871f,-1.84765f},{0.800037f,-3.30454f,-1.98904f},{0.2f,-3.39411f,-1.98907f}, {1.28094f,-3.04125f,-1.14291f},{0.998289f,-3.14538f,-1.39994f},{1.8f,-2.7f,-0.99765f}, {2.05f,0.0f,-1.99765f},{1.95f,0.0f,-1.99765f},{2.15607f,0.0f,-1.95372f}, {1.83398f,0.0f,-1.94253f},{2.15607f,2.66025f,-1.93818f},{0.0f,-2.7f,0.35235f}, {0.0f,1.0f,-0.74765f},{0.0f,1.18582f,-0.392925f},{0.0f,-1.18582f,-0.392925f}, {0.0f,-1.0f,-0.74765f},{0.0f,-0.672987f,-0.697837f},{0.0f,0.672987f,-0.697837f}, {-1.8f,1.1858f,-0.392915f},{-1.8f,1.0f,-0.74765f},{-1.8f,-1.1858f,-0.392915f}, {-1.8f,-1.0f,-0.74765f},{-1.8f,-0.672987f,-0.697837f},{-1.8f,0.672987f,-0.697837f}, {1.8f,1.1858f,-0.392915f},{1.8f,1.0f,-0.74765f},{1.8f,-1.1858f,-0.392915f}, {1.8f,-1.0f,-0.74765f},{1.8f,-0.672987f,-0.697837f},{1.8f,0.672987f,-0.697837f}, {1.8f,2.15f,1.60235f},{1.8f,2.67f,1.60235f},{1.4f,2.67f,1.60235f}, {1.4f,3.2078f,1.60235f},{2.18467f,2.71558f,1.60235f},{2.2f,2.15f,1.60235f}, {1.78458f,3.01085f,1.60235f},{-1.8f,2.15f,1.60235f},{-1.4f,2.67f,1.60235f}, {-1.8f,2.67f,1.60235f},{-1.4f,3.2078f,1.60235f},{-2.2f,2.15f,1.60235f}, {-2.18467f,2.71558f,1.60235f},{-1.78458f,3.01085f,1.60235f},{1.8f,2.15f,0.35235f}, {1.4f,2.7f,0.35235f},{2.2f,2.15f,0.35235f},{1.4f,3.2078f,0.35235f}, {0.948198f,3.36911f,0.35235f},{0.0f,2.7f,0.35235f},{-0.948198f,3.36911f,0.35235f}, {0.0f,3.48711f,0.35235f},{-1.4f,2.7f,0.35235f},{-1.8f,2.15f,0.35235f}, {-2.2f,2.15f,0.35235f},{-1.4f,3.2078f,0.35235f},{1.8f,1.9f,-1.84765f}, {1.8f,2.67f,-1.84765f},{2.18466f,2.7156f,-1.79765f},{1.13241f,3.31174f,-1.79765f}, {0.0f,2.67f,-1.84765f},{0.0f,3.5f,-1.79765f},{-1.8f,1.9f,-1.84765f}, {-1.8f,2.67f,-1.84765f},{-2.18466f,2.7156f,-1.79765f},{-1.13241f,3.31174f,-1.79765f}, {1.8f,1.25f,0.35235f},{2.2f,0.775f,0.35235f},{2.2f,0.775f,0.00235001f}, {0.0f,1.25f,0.35235f},{-1.8f,1.25f,0.35235f},{-2.2f,0.775f,0.00235001f}, {-2.2f,0.775f,0.35235f},{1.8f,0.2465f,-0.732382f},{1.8f,0.606556f,-0.572051f}, {2.2f,0.239526f,-0.734681f},{2.2f,0.627035f,-0.453101f},{0.0f,0.606556f,-0.572051f}, {-1.8f,0.2465f,-0.732382f},{-1.8f,0.606556f,-0.572051f},{-2.2f,0.239526f,-0.734681f}, {-2.2f,0.627035f,-0.453101f},{1.8f,-1.25f,0.35235f},{2.2f,-0.775f,0.35235f}, {2.2f,-0.775f,0.00235001f},{0.0f,-1.25f,0.35235f},{-1.8f,-1.25f,0.35235f}, {-2.2f,-0.775f,0.35235f},{-2.2f,-0.775f,0.00235001f},{1.8f,-0.246935f,-0.732237f}, {1.8f,-0.606556f,-0.572051f},{2.2f,-0.239526f,-0.734681f},{2.2f,-0.627035f,-0.453101f}, {0.0f,-0.606556f,-0.572051f},{-1.8f,-0.246935f,-0.732237f},{-1.8f,-0.606556f,-0.572051f}, {-2.2f,-0.239526f,-0.734681f},{-2.2f,-0.627035f,-0.453101f},{1.8f,-1.60818f,-1.33776f}, {1.8f,-1.40982f,-1.84765f},{1.8f,0.0f,-1.84765f},{2.2f,-1.6081f,-1.33787f}, {2.2f,-1.40982f,-1.84765f},{2.2f,0.0f,-1.84765f},{-1.8f,-1.60818f,-1.33776f}, {-1.8f,-1.40982f,-1.84765f},{-1.8f,0.0f,-1.84765f},{-2.2f,-1.6081f,-1.33787f}, {-2.2f,-1.40982f,-1.84765f},{-2.2f,0.0f,-1.84765f},{0.7f,-2.7f,1.60235f}, {0.7f,-3.42929f,1.60235f},{0.0f,-2.7f,1.60235f},{-0.7f,-2.7f,1.60235f}, {0.0f,-3.49997f,1.60235f},{-0.7f,-3.42929f,1.60235f},{1.8f,-2.7f,0.35235f}, {1.45894f,-3.18143f,0.35235f},{2.14179f,-2.76816f,0.35235f},{2.2f,-2.64953f,0.35235f}, {0.7f,-2.7f,0.35235f},{0.7f,-3.42929f,0.35235f},{-0.7f,-2.7f,0.35235f}, {-0.7f,-3.42929f,0.35235f},{-1.8f,-2.7f,0.35235f},{-1.45894f,-3.18143f,0.35235f}, {-2.2f,-2.64953f,0.35235f},{-2.14179f,-2.76816f,0.35235f},{1.8f,-2.01865f,-0.97777f}, {1.8f,-2.7f,-0.84765f},{1.92676f,-2.92192f,-0.99765f},{2.2f,-2.01835f,-0.977926f}, {2.2f,-2.64953f,-0.84765f},{2.14179f,-2.76816f,-0.966286f},{-1.8f,-2.01865f,-0.97777f}, {-1.8f,-2.7f,-0.84765f},{-1.92676f,-2.92192f,-0.99765f},{-2.2f,-2.01835f,-0.977926f}, {-2.2f,-2.64953f,-0.84765f},{-2.14179f,-2.76816f,-0.966286f},{1.34394f,-2.7f,-1.1077f}, {1.35582f,-3.22672f,-1.10171f},{0.811314f,-2.7f,-1.84765f},{0.988348f,-2.7f,-1.41351f}, {0.811314f,-3.40467f,-1.84765f},{0.994882f,-3.35562f,-1.40454f},{-0.988348f,-2.7f,-1.41351f}, {0.0f,-2.7f,-1.84765f},{-0.811314f,-2.7f,-1.84765f},{-0.994882f,-3.35562f,-1.40454f}, {0.0f,-3.5f,-1.84765f},{-0.811314f,-3.40467f,-1.84765f},{-1.34394f,-2.7f,-1.1077f}, {-1.35582f,-3.22672f,-1.10171f} }; static GLfloat normals [274][3] = { {-1.0f,0.0f,0.0f},{-0.999984f,0.00519551f,-0.00232515f},{-0.980741f,0.00304722f,-0.195287f}, {-0.999982f,0.00321145f,-0.0050577f},{-0.999901f,0.0139735f,-0.00167206f},{-0.936619f,0.325635f,-0.129252f}, {-0.635574f,-0.772028f,0.00417741f},{-0.374979f,-0.926692f,0.0251491f},{-0.416825f,-0.908986f,-0.00124481f}, {-0.525586f,-0.850639f,0.0131636f},{-0.172574f,-0.984996f,0.00117284f},{-0.210513f,-0.977414f,0.0185848f}, {-0.258321f,-0.96481f,0.0491156f},{-0.988643f,-0.150284f,0.0f},{-0.823776f,-0.351623f,-0.444696f}, {-0.975233f,-0.179062f,-0.129837f},{-0.980566f,-0.16978f,-0.0983098f},{-0.952236f,-0.138993f,-0.271897f}, {-0.976766f,-0.13269f,-0.168292f},{-0.877679f,0.478993f,-0.0156877f},{-0.999633f,0.0270911f,0.0f}, {1.0f,0.0f,0.0f},{-1.87212e-009f,-1.0f,3.52859e-006f},{-0.100472f,-0.99494f,0.0f}, {0.0229096f,-0.999737f,-0.0012419f},{-0.014379f,-0.999894f,-0.00219243f},{0.999984f,0.00519551f,-0.00232515f}, {0.980741f,0.00304722f,-0.195287f},{0.999901f,0.0139735f,-0.00167206f},{0.999982f,0.00321145f,-0.0050577f}, {0.936619f,0.325635f,-0.129252f},{0.375017f,-0.926677f,0.0251251f},{0.635574f,-0.772028f,0.00417741f}, {0.416825f,-0.908986f,-0.00124481f},{0.525586f,-0.850639f,0.0131636f},{0.184376f,-0.982855f,0.00126651f}, {0.19241f,-0.981194f,0.0153646f},{0.258434f,-0.964785f,0.0490148f},{0.823776f,-0.351623f,-0.444696f}, {0.988643f,-0.150284f,0.0f},{0.975233f,-0.179062f,-0.129837f},{0.980566f,-0.16978f,-0.0983098f}, {0.952236f,-0.138993f,-0.271897f},{0.976766f,-0.13269f,-0.168292f},{0.877679f,0.478993f,-0.0156877f}, {0.999633f,0.0270911f,0.0f},{0.100472f,-0.99494f,0.0f},{-0.150459f,-0.985712f,-0.0757187f}, {-1.26142e-009f,-0.982267f,-0.187487f},{0.150508f,-0.985707f,-0.0756957f},{-0.48425f,0.874812f,-0.0143577f}, {-0.3013f,0.931914f,-0.201876f},{-0.231256f,0.972873f,-0.00614353f},{-0.526289f,0.849844f,-0.0280189f}, {1.88271e-009f,0.999987f,-0.00504398f},{0.0f,0.981327f,-0.192344f},{0.3013f,0.931914f,-0.201876f}, {0.48425f,0.874812f,-0.0143577f},{0.231256f,0.972873f,-0.00614353f},{0.526289f,0.849844f,-0.0280189f}, {-0.455821f,0.890072f,0.0f},{0.455821f,0.890072f,0.0f},{0.0f,0.0f,1.0f}, {0.0657879f,0.952791f,0.296413f},{0.10445f,0.69044f,0.715809f},{0.0109124f,0.988743f,0.149229f}, {0.0f,-1.0f,0.0f},{0.104335f,-0.690422f,0.715843f},{0.0695468f,-0.988856f,0.131634f}, {0.0108787f,-0.975504f,0.219712f},{0.0618815f,-0.25638f,0.964593f},{-7.68889e-005f,-0.309048f,0.951047f}, {-0.00205735f,0.204931f,0.978774f},{0.0844502f,0.341379f,0.936124f},{0.0f,-0.999417f,0.0341539f}, {0.0f,-0.99551f,0.0946543f},{0.0f,1.0f,0.0f},{0.0f,0.981918f,0.189309f}, {0.0f,0.972561f,-0.232648f},{-0.0695468f,-0.988856f,0.131634f},{-0.104335f,-0.690422f,0.715843f}, {-0.0108787f,-0.975504f,0.219712f},{-0.0618815f,-0.25638f,0.964593f},{7.68889e-005f,-0.309048f,0.951047f}, {0.00205735f,0.204931f,0.978774f},{-0.0844502f,0.341379f,0.936124f},{-0.10445f,0.69044f,0.715809f}, {-0.0657879f,0.952791f,0.296413f},{-0.0109124f,0.988743f,0.149229f},{-2.695e-006f,-0.70594f,-0.708272f}, {0.000192697f,-0.262692f,-0.96488f},{-5.38999e-006f,-0.707003f,-0.707211f},{0.0f,-0.128752f,-0.991677f}, {-0.999766f,0.0f,-0.0216409f},{-0.998243f,0.0f,-0.0592487f},{-0.997421f,0.0f,-0.0717738f}, {-0.110602f,0.30484f,-0.94596f},{-0.5256f,0.388284f,-0.756954f},{-0.238354f,0.664347f,-0.7084f}, {-0.104052f,0.0586272f,-0.992842f},{0.125063f,-0.459593f,-0.87928f},{-0.217416f,-0.199415f,-0.955492f}, {0.180023f,-0.139748f,-0.973685f},{-0.1298f,-0.788311f,-0.60143f},{0.652009f,-0.0742063f,-0.754571f}, {-0.116753f,0.347918f,-0.930227f},{0.447525f,0.0067279f,-0.894246f},{-0.0972002f,-0.0882603f,-0.991344f}, {-0.485837f,0.0128693f,-0.873955f},{-0.443782f,-0.019869f,-0.895914f},{-0.948313f,-0.00164689f,-0.317333f}, {-0.808553f,0.0200673f,-0.588081f},{-0.858391f,8.64955e-005f,-0.512997f},{-0.979669f,-3.89778e-005f,-0.20062f}, {-0.996525f,-1.42301e-005f,-0.0832893f},{-0.997437f,-2.13467e-005f,-0.0715458f},{0.978716f,-0.0949488f,-0.181931f}, {0.67714f,-0.343528f,-0.650745f},{0.686377f,-0.616067f,-0.386455f},{0.980566f,-0.169777f,-0.0983178f}, {0.74217f,-0.592683f,-0.312907f},{0.977835f,-0.147992f,-0.148113f},{0.639882f,-0.647718f,-0.413536f}, {-0.715589f,-0.549052f,-0.431825f},{-0.73778f,-0.301487f,-0.603976f},{-0.610268f,-0.733583f,-0.299047f}, {-0.97708f,0.00185179f,-0.212865f},{-0.995307f,0.0f,-0.0967725f},{-0.956401f,0.0f,-0.292057f}, {-0.768622f,-0.0137886f,-0.639555f},{-0.456092f,0.00761986f,-0.8899f},{-0.315155f,-0.404027f,-0.858743f}, {0.242533f,-0.386677f,-0.889752f},{-0.197382f,-0.801534f,-0.564432f},{0.24008f,-0.806336f,-0.54054f}, {-0.149757f,-0.90336f,-0.401889f},{0.214947f,-0.884715f,-0.413614f},{0.00361947f,-0.998239f,-0.0592032f}, {-0.000289462f,-0.923248f,-0.384205f},{0.0f,-0.922669f,-0.385593f},{-0.99935f,7.32087e-005f,-0.0360433f}, {0.145011f,0.940077f,-0.308588f},{0.132303f,0.859023f,-0.494545f},{0.145949f,0.936997f,-0.317387f}, {0.112723f,0.742104f,-0.660738f},{-0.647982f,-0.349544f,-0.676712f},{-0.75514f,-0.147652f,-0.638719f}, {0.0898762f,0.594363f,-0.799159f},{0.00381381f,-0.184719f,-0.982784f},{0.0f,0.703645f,-0.710552f}, {0.0f,0.129579f,-0.991569f},{-0.102191f,-0.87449f,-0.474155f},{3.63993e-010f,-0.758864f,-0.651249f}, {0.0f,-0.0121772f,-0.999926f},{-2.44554e-010f,-0.327201f,-0.944955f},{0.0f,0.129244f,-0.991613f}, {7.33698e-005f,0.257996f,-0.966146f},{0.0f,0.602021f,-0.79848f},{-7.75359e-008f,0.795583f,-0.605844f}, {0.0f,-0.276074f,-0.961136f},{0.326394f,-0.425868f,-0.843862f},{0.143616f,-0.0702339f,-0.987138f}, {0.0f,-0.812299f,-0.583242f},{0.0f,-0.933328f,-0.359024f},{0.0f,0.922958f,-0.384901f}, {0.0f,0.922669f,-0.385593f},{-0.0891187f,-0.681542f,-0.726332f},{0.0f,0.0f,-1.0f}, {0.222711f,-0.000272707f,-0.974885f},{-0.214215f,0.000921458f,-0.976786f},{-0.728642f,0.00345042f,-0.684886f}, {0.735846f,-0.00014084f,-0.677148f},{0.992044f,0.00016362f,-0.125893f},{0.99694f,0.000135919f,-0.0781646f}, {-0.000192697f,-0.262692f,-0.96488f},{2.695e-006f,-0.70594f,-0.708272f},{5.38999e-006f,-0.707003f,-0.707211f}, {0.998243f,0.0f,-0.0592487f},{0.999766f,0.0f,-0.0216409f},{0.997421f,0.0f,-0.0717738f}, {0.5256f,0.388284f,-0.756954f},{0.110602f,0.30484f,-0.94596f},{0.238354f,0.664347f,-0.7084f}, {0.104052f,0.0586272f,-0.992842f},{0.217416f,-0.199415f,-0.955492f},{-0.125063f,-0.459593f,-0.87928f}, {-0.180023f,-0.139748f,-0.973685f},{0.1298f,-0.788311f,-0.60143f},{-0.652009f,-0.0742063f,-0.754571f}, {0.116753f,0.347918f,-0.930227f},{-0.447525f,0.0067279f,-0.894246f},{0.0972002f,-0.0882603f,-0.991344f}, {0.485837f,0.0128693f,-0.873955f},{0.443782f,-0.019869f,-0.895914f},{0.808553f,0.0200673f,-0.588081f}, {0.948313f,-0.00164689f,-0.317333f},{0.858391f,8.64955e-005f,-0.512997f},{0.979669f,-3.89778e-005f,-0.20062f}, {0.996525f,-1.42301e-005f,-0.0832893f},{0.997437f,-2.13467e-005f,-0.0715458f},{-0.978716f,-0.0949488f,-0.181931f}, {-0.67714f,-0.343528f,-0.650745f},{-0.686377f,-0.616067f,-0.386455f},{-0.980566f,-0.169777f,-0.0983178f}, {-0.74217f,-0.592683f,-0.312907f},{-0.977835f,-0.147992f,-0.148113f},{-0.639882f,-0.647718f,-0.413536f}, {0.715589f,-0.549052f,-0.431825f},{0.73778f,-0.301487f,-0.603976f},{0.610268f,-0.733583f,-0.299047f}, {0.97708f,0.00185179f,-0.212865f},{0.995307f,0.0f,-0.0967725f},{0.956401f,0.0f,-0.292057f}, {0.768622f,-0.0137886f,-0.639555f},{0.456092f,0.00761986f,-0.8899f},{0.315155f,-0.404027f,-0.858743f}, {-0.242533f,-0.386677f,-0.889752f},{0.197382f,-0.801534f,-0.564432f},{-0.24008f,-0.806336f,-0.54054f}, {0.149757f,-0.90336f,-0.401889f},{-0.214947f,-0.884715f,-0.413614f},{-0.00361947f,-0.998239f,-0.0592032f}, {0.000289462f,-0.923248f,-0.384205f},{0.99935f,7.32087e-005f,-0.0360433f},{-0.132303f,0.859023f,-0.494545f}, {-0.145011f,0.940077f,-0.308588f},{-0.145949f,0.936997f,-0.317387f},{-0.112723f,0.742104f,-0.660738f}, {0.647982f,-0.349544f,-0.676712f},{0.75514f,-0.147652f,-0.638719f},{-0.0898762f,0.594363f,-0.799159f}, {-0.00381381f,-0.184719f,-0.982784f},{0.102191f,-0.87449f,-0.474155f},{-7.33698e-005f,0.257996f,-0.966146f}, {7.75359e-008f,0.795583f,-0.605844f},{-0.326394f,-0.425868f,-0.843862f},{-0.143616f,-0.0702339f,-0.987138f}, {0.0891187f,-0.681542f,-0.726332f},{-0.222711f,-0.000272707f,-0.974885f},{0.214215f,0.000921458f,-0.976786f}, {0.728642f,0.00345042f,-0.684886f},{-0.735846f,-0.00014084f,-0.677148f},{-0.992044f,0.00016362f,-0.125893f}, {-0.99694f,0.000135919f,-0.0781646f},{0.0678716f,-0.997689f,-0.00330243f},{0.101862f,-0.994729f,-0.0118101f}, {0.0678741f,-0.997693f,0.00126437f},{0.0f,-0.999907f,0.0136353f},{0.0f,-0.150591f,-0.988596f}, {0.0f,-0.436386f,-0.89976f},{0.0f,-0.706465f,-0.707748f},{0.0f,0.579434f,-0.815019f}, {0.0f,0.150591f,-0.988596f},{0.0f,0.579434f,-0.815019f},{0.0f,-0.885832f,-0.464006f}, {-1.14482e-005f,-0.938995f,-0.343931f},{0.0f,-0.88585f,-0.463972f},{0.0f,-0.976473f,-0.215641f}, {0.0f,0.959882f,-0.280404f},{-8.40575e-006f,0.885832f,-0.464005f},{-1.702e-005f,0.959885f,-0.280395f}, {0.0f,0.885815f,-0.464039f},{-8.37983e-006f,-0.996311f,-0.0858118f},{0.0f,-0.996313f,-0.0857917f}, {-8.28085e-006f,0.996311f,-0.085812f},{0.0f,0.996313f,-0.0857922f},{-0.101862f,-0.994729f,-0.0118101f}, {-0.0678716f,-0.997689f,-0.00330243f},{-0.0678741f,-0.997693f,0.00126437f},{1.14482e-005f,-0.938995f,-0.343931f}, {8.40575e-006f,0.885832f,-0.464005f},{1.702e-005f,0.959885f,-0.280395f},{8.37983e-006f,-0.996311f,-0.0858118f}, {8.28085e-006f,0.996311f,-0.085812f} }; static GLfloat textures [610][2] = { {0.340065f,0.804648f},{0.328884f,0.804648f},{0.334475f,0.764f}, {0.317013f,0.831565f},{0.294577f,0.844348f},{0.28842f,0.765826f}, {0.317013f,0.844348f},{0.0575824f,0.844348f},{0.0710239f,0.791243f}, {0.0693647f,0.844348f},{0.061477f,0.795044f},{0.0811505f,0.844348f}, {0.0798001f,0.780986f},{0.0766721f,0.780183f},{0.055806f,0.844348f}, {0.0575824f,0.796189f},{0.055806f,0.800522f},{0.0430913f,0.782618f}, {0.0280116f,0.831565f},{0.0488222f,0.795764f},{0.039931f,0.764f}, {0.0248645f,0.814931f},{0.28842f,0.89f},{0.294577f,0.89f}, {0.0161413f,0.804648f},{0.32016f,0.814931f},{0.0105503f,0.764f}, {0.0915314f,0.89f},{0.0811505f,0.89f},{0.0915314f,0.844348f}, {0.0915314f,0.782576f},{0.178103f,0.804648f},{0.166921f,0.804648f}, {0.172512f,0.764f},{0.21241f,0.844348f},{0.189974f,0.831565f}, {0.218567f,0.765826f},{0.189974f,0.844348f},{0.112039f,0.791243f}, {0.12548f,0.844348f},{0.113698f,0.844348f},{0.121586f,0.795044f}, {0.101912f,0.844348f},{0.103272f,0.780986f},{0.106391f,0.780183f}, {0.12548f,0.796189f},{0.127257f,0.844348f},{0.127257f,0.800522f}, {0.139971f,0.782618f},{0.155051f,0.831565f},{0.134241f,0.795764f}, {0.143132f,0.764f},{0.158198f,0.814931f},{0.218567f,0.89f}, {0.21241f,0.89f},{0.186827f,0.814931f},{0.101912f,0.89f}, {0.0794712f,0.764f},{0.0915314f,0.764f},{0.103592f,0.764f}, {0.274709f,0.844348f},{0.270479f,0.765826f},{0.267637f,0.844348f}, {0.281077f,0.89f},{0.253494f,0.844348f},{0.253494f,0.765826f}, {0.236508f,0.765826f},{0.232278f,0.844348f},{0.23935f,0.844348f}, {0.22591f,0.89f},{0.0280116f,0.844348f},{0.155051f,0.844348f}, {0.274709f,0.89f},{0.232278f,0.89f},{0.008048f,0.861444f}, {0.00884048f,0.860022f},{0.0134938f,0.860839f},{0.0671595f,0.860022f}, {0.067952f,0.861444f},{0.0625062f,0.860839f},{0.0134938f,0.887895f}, {0.008048f,0.887711f},{0.008048f,0.886381f},{0.0475302f,0.860839f}, {0.0439019f,0.852099f},{0.0475302f,0.852099f},{0.0439019f,0.860839f}, {0.0250907f,0.933573f},{0.0189396f,0.93164f},{0.038f,0.934748f}, {0.0165435f,0.925242f},{0.0189396f,0.93164f},{0.0165435f,0.928851f}, {0.0189396f,0.925555f},{0.008048f,0.902485f},{0.0134938f,0.918963f}, {0.008048f,0.918963f},{0.0134938f,0.908177f},{0.0134938f,0.918963f}, {0.0104442f,0.921752f},{0.008048f,0.918963f},{0.0134938f,0.921752f}, {0.0181371f,0.85507f},{0.0284698f,0.852099f},{0.00884048f,0.860022f}, {0.0284698f,0.860839f},{0.0134938f,0.860839f},{0.0284698f,0.852099f}, {0.00884048f,0.860022f},{0.0284698f,0.852099f},{0.0326563f,0.852099f}, {0.0284698f,0.860839f},{0.0284698f,0.852099f},{0.0326563f,0.860839f}, {0.008048f,0.861444f},{0.0134938f,0.878217f},{0.008048f,0.883909f}, {0.0134938f,0.860839f},{0.008048f,0.898983f},{0.0134938f,0.898799f}, {0.008048f,0.900313f},{0.0134938f,0.895562f},{0.008048f,0.898983f}, {0.008048f,0.8955f},{0.0134938f,0.898799f},{0.008048f,0.891194f}, {0.0134938f,0.895562f},{0.008048f,0.8955f},{0.0134938f,0.891127f}, {0.008048f,0.887711f},{0.0134938f,0.891127f},{0.008048f,0.891194f}, {0.0134938f,0.887895f},{0.0165435f,0.928851f},{0.0134938f,0.925242f}, {0.0165435f,0.925242f},{0.0136114f,0.92753f},{0.0104442f,0.921752f}, {0.0134938f,0.921752f},{0.010561f,0.925548f},{0.010561f,0.925548f}, {0.0134938f,0.925242f},{0.0136114f,0.92753f},{0.038f,0.934748f}, {0.0189396f,0.925555f},{0.038f,0.925555f},{0.0189396f,0.93164f}, {0.0382791f,0.851252f},{0.0382791f,0.852099f},{0.0326563f,0.852099f}, {0.0326563f,0.852099f},{0.0382791f,0.860839f},{0.0326563f,0.860839f}, {0.008048f,0.900313f},{0.038f,0.898799f},{0.038f,0.900313f}, {0.038f,0.883909f},{0.008048f,0.883909f},{0.038f,0.886381f}, {0.038f,0.902485f},{0.0134938f,0.908177f},{0.008048f,0.902485f}, {0.038f,0.908177f},{0.008048f,0.902485f},{0.038f,0.878217f}, {0.0134938f,0.878217f},{0.0134938f,0.887895f},{0.008048f,0.886381f}, {0.038f,0.887895f},{0.0570604f,0.93164f},{0.0509093f,0.933573f}, {0.038f,0.934748f},{0.0570604f,0.93164f},{0.0594565f,0.925242f}, {0.0594565f,0.928851f},{0.0570604f,0.925555f},{0.0625062f,0.918963f}, {0.067952f,0.902485f},{0.067952f,0.918963f},{0.0625062f,0.908177f}, {0.0655558f,0.921752f},{0.0625062f,0.918963f},{0.067952f,0.918963f}, {0.0625062f,0.921752f},{0.0475302f,0.852099f},{0.0578629f,0.85507f}, {0.0671595f,0.860022f},{0.0625062f,0.860839f},{0.0475302f,0.860839f}, {0.0671595f,0.860022f},{0.0625062f,0.860839f},{0.0475302f,0.852099f}, {0.0625062f,0.878217f},{0.067952f,0.861444f},{0.067952f,0.883909f}, {0.0625062f,0.860839f},{0.0625062f,0.898799f},{0.067952f,0.898983f}, {0.067952f,0.900313f},{0.067952f,0.898983f},{0.0625062f,0.895562f}, {0.067952f,0.8955f},{0.0625062f,0.895562f},{0.067952f,0.891194f}, {0.067952f,0.8955f},{0.0625062f,0.891127f},{0.0625062f,0.891127f}, {0.067952f,0.887711f},{0.067952f,0.891194f},{0.0625062f,0.887895f}, {0.0625062f,0.925242f},{0.0594565f,0.928851f},{0.0594565f,0.925242f}, {0.0623886f,0.92753f},{0.0655558f,0.921752f},{0.0625062f,0.925242f}, {0.0625062f,0.921752f},{0.065439f,0.925548f},{0.0625062f,0.925242f}, {0.065439f,0.925548f},{0.0623886f,0.92753f},{0.067952f,0.887711f}, {0.0625062f,0.887895f},{0.067952f,0.886381f},{0.0570604f,0.925555f}, {0.038f,0.934748f},{0.038f,0.925555f},{0.0570604f,0.93164f}, {0.0382791f,0.851252f},{0.0439019f,0.852099f},{0.0382791f,0.860839f}, {0.0439019f,0.860839f},{0.038f,0.898799f},{0.067952f,0.900313f}, {0.0625062f,0.898799f},{0.067952f,0.886381f},{0.0625062f,0.908177f}, {0.067952f,0.902485f},{0.038f,0.908177f},{0.067952f,0.902485f}, {0.038f,0.878217f},{0.067952f,0.883909f},{0.0625062f,0.878217f}, {0.0625062f,0.887895f},{0.067952f,0.886381f},{0.038f,0.887895f}, {0.162107f,0.851171f},{0.162107f,0.858711f},{0.162107f,0.850212f}, {0.162107f,0.857312f},{0.153415f,0.857321f},{0.153428f,0.858711f}, {0.153428f,0.859371f},{0.153415f,0.860762f},{0.149284f,0.936118f}, {0.133814f,0.930104f},{0.148824f,0.937948f},{0.135348f,0.929125f}, {0.136794f,0.875091f},{0.135348f,0.876396f},{0.136794f,0.876396f}, {0.135348f,0.875091f},{0.138522f,0.876396f},{0.137857f,0.875482f}, {0.14862f,0.938701f},{0.1334f,0.930835f},{0.13402f,0.858472f}, {0.138964f,0.859371f},{0.137131f,0.856443f},{0.137131f,0.856443f}, {0.146472f,0.854868f},{0.145389f,0.852421f},{0.153265f,0.85279f}, {0.15061f,0.85072f},{0.15056f,0.853494f},{0.153265f,0.850073f}, {0.145389f,0.852421f},{0.1534f,0.852383f},{0.153265f,0.850073f}, {0.153399f,0.850415f},{0.138964f,0.868362f},{0.138964f,0.859371f}, {0.138329f,0.868055f},{0.138329f,0.8735f},{0.138964f,0.873779f}, {0.138329f,0.875009f},{0.138964f,0.876396f},{0.138964f,0.876396f}, {0.133814f,0.8735f},{0.133178f,0.868366f},{0.133178f,0.87378f}, {0.133814f,0.868055f},{0.133814f,0.875009f},{0.133178f,0.876396f}, {0.133178f,0.868366f},{0.13402f,0.858472f},{0.133178f,0.860037f}, {0.153265f,0.859371f},{0.153265f,0.861351f},{0.153265f,0.856732f}, {0.153265f,0.859371f},{0.150704f,0.859371f},{0.145561f,0.859371f}, {0.150704f,0.859371f},{0.145561f,0.859371f},{0.13402f,0.858472f}, {0.135348f,0.86745f},{0.137131f,0.856443f},{0.13402f,0.858472f}, {0.136794f,0.867448f},{0.135348f,0.872158f},{0.136794f,0.872158f}, {0.135348f,0.874434f},{0.136794f,0.874434f},{0.134286f,0.875064f}, {0.137131f,0.856443f},{0.162107f,0.856732f},{0.153428f,0.851394f}, {0.162107f,0.851534f},{0.133814f,0.876396f},{0.133178f,0.876396f}, {0.165f,0.940413f},{0.165f,0.938546f},{0.14862f,0.938701f}, {0.165f,0.941186f},{0.165f,0.848815f},{0.153265f,0.850073f}, {0.165f,0.84908f},{0.165f,0.858711f},{0.165f,0.850134f}, {0.165f,0.859371f},{0.165f,0.860766f},{0.165f,0.922052f}, {0.138405f,0.920582f},{0.136794f,0.922052f},{0.165f,0.920582f}, {0.165f,0.920072f},{0.138964f,0.930233f},{0.138964f,0.920072f}, {0.165f,0.930233f},{0.138964f,0.920072f},{0.153265f,0.859371f}, {0.165f,0.861351f},{0.165f,0.859371f},{0.145561f,0.859371f}, {0.138964f,0.859371f},{0.136794f,0.895f},{0.135348f,0.895f}, {0.133814f,0.895f},{0.138472f,0.895f},{0.138964f,0.895f}, {0.138964f,0.920072f},{0.133178f,0.895f},{0.133178f,0.876396f}, {0.1334f,0.930835f},{0.133178f,0.895f},{0.165f,0.929125f}, {0.167893f,0.858711f},{0.167893f,0.851171f},{0.167893f,0.850212f}, {0.167893f,0.857312f},{0.176585f,0.857321f},{0.176572f,0.858711f}, {0.176572f,0.859371f},{0.176585f,0.860762f},{0.196186f,0.930104f}, {0.180716f,0.936118f},{0.181176f,0.937948f},{0.194652f,0.929125f}, {0.194652f,0.876396f},{0.193206f,0.875091f},{0.193206f,0.876396f}, {0.194652f,0.875091f},{0.191478f,0.876396f},{0.192143f,0.875482f}, {0.18138f,0.938701f},{0.1966f,0.930835f},{0.191036f,0.859371f}, {0.19598f,0.858472f},{0.192869f,0.856443f},{0.183528f,0.854868f}, {0.192869f,0.856443f},{0.184611f,0.852421f},{0.17939f,0.85072f}, {0.176735f,0.85279f},{0.17944f,0.853494f},{0.176735f,0.850073f}, {0.17939f,0.85072f},{0.184611f,0.852421f},{0.176735f,0.850073f}, {0.176601f,0.852383f},{0.176601f,0.850415f},{0.191036f,0.868362f}, {0.191036f,0.859371f},{0.191671f,0.868055f},{0.191671f,0.8735f}, {0.191036f,0.873779f},{0.191671f,0.875009f},{0.191036f,0.876396f}, {0.191036f,0.876396f},{0.196822f,0.868366f},{0.196186f,0.8735f}, {0.196822f,0.87378f},{0.196186f,0.868055f},{0.196186f,0.875009f}, {0.196822f,0.876396f},{0.19598f,0.858472f},{0.196822f,0.868366f}, {0.196822f,0.860037f},{0.176735f,0.859371f},{0.176735f,0.861351f}, {0.176735f,0.856732f},{0.176735f,0.859371f},{0.179296f,0.859371f}, {0.184439f,0.859371f},{0.179296f,0.859371f},{0.184439f,0.859371f}, {0.19598f,0.858472f},{0.194652f,0.86745f},{0.192869f,0.856443f}, {0.19598f,0.858472f},{0.193206f,0.867448f},{0.194652f,0.872158f}, {0.193206f,0.872158f},{0.194652f,0.874434f},{0.193206f,0.874434f}, {0.195714f,0.875064f},{0.192869f,0.856443f},{0.167893f,0.856732f}, {0.176572f,0.851394f},{0.167893f,0.851534f},{0.196186f,0.876396f}, {0.196822f,0.876396f},{0.18138f,0.938701f},{0.165f,0.941186f}, {0.165f,0.848815f},{0.176735f,0.850073f},{0.191595f,0.920582f}, {0.193206f,0.922052f},{0.191036f,0.930233f},{0.191036f,0.920072f}, {0.165f,0.930233f},{0.191036f,0.920072f},{0.176735f,0.859371f}, {0.165f,0.859371f},{0.184439f,0.859371f},{0.191036f,0.859371f}, {0.193206f,0.895f},{0.194652f,0.895f},{0.196186f,0.895f}, {0.191528f,0.895f},{0.191036f,0.895f},{0.191036f,0.920072f}, {0.191036f,0.895f},{0.196822f,0.895f},{0.1966f,0.930835f}, {0.196822f,0.895f},{0.28202f,0.9905f},{0.276337f,0.99941f}, {0.28202f,0.99941f},{0.277101f,0.990239f},{0.28202f,0.99941f}, {0.290538f,0.9905f},{0.28202f,0.9905f},{0.287374f,0.996384f}, {0.0656675f,0.985714f},{0.0651311f,0.974239f},{0.0789199f,0.974239f}, {0.0591638f,0.983435f},{0.074429f,0.9905f},{0.0713872f,0.988395f}, {0.0789199f,0.974239f},{0.0651311f,0.974239f},{0.051936f,0.984575f}, {0.0496316f,0.974239f},{0.0591638f,0.983435f},{0.25144f,0.9905f}, {0.276101f,0.966239f},{0.28202f,0.9905f},{0.25144f,0.966239f}, {0.074429f,0.9905f},{0.0893823f,0.974239f},{0.0894779f,0.9905f}, {0.0789199f,0.974239f},{0.0644779f,0.988f},{0.0539199f,0.991239f}, {0.0513999f,0.988f},{0.0643823f,0.991239f},{0.0713872f,0.988395f}, {0.0656675f,0.985714f},{0.0789199f,0.974239f},{0.25144f,0.96337f}, {0.313976f,0.959005f},{0.306278f,0.96337f},{0.25144f,0.959005f}, {0.0269423f,0.959005f},{0.0894779f,0.96037f},{0.0346399f,0.96037f}, {0.0894779f,0.959005f},{0.0455281f,0.968653f},{0.0894779f,0.968653f}, {0.0894779f,0.94556f},{0.0252532f,0.94656f},{0.315665f,0.95556f}, {0.25144f,0.95556f},{0.25144f,0.965653f},{0.30339f,0.965653f}, {0.0496316f,0.974239f},{0.0893823f,0.974239f},{0.301128f,0.966239f}, {0.25144f,0.966239f},{0.0427511f,0.9905f},{0.00144966f,0.9905f}, {0.0252532f,0.94656f},{0.0155255f,0.959947f},{0.0155255f,0.959947f}, {0.0269423f,0.959005f},{0.00144966f,0.9905f},{0.315665f,0.95556f}, {0.325405f,0.959951f},{0.00846608f,0.959951f},{0.0155255f,0.959947f}, {0.00144966f,0.9905f},{0.325405f,0.959951f},{0.332421f,0.9905f}, {0.290538f,0.9905f},{0.332421f,0.9905f},{0.0427511f,0.9905f}, {0.0460888f,0.987731f},{0.0460888f,0.987731f},{0.0496316f,0.974239f}, {0.051936f,0.984575f},{0.301128f,0.966239f},{0.290538f,0.9905f}, {0.287374f,0.966239f},{0.226543f,0.999f},{0.22086f,0.9905f}, {0.22086f,0.999f},{0.226779f,0.990739f},{0.219342f,0.99f}, {0.22086f,0.999f},{0.22086f,0.9905f},{0.215506f,0.990239f}, {0.113633f,0.974239f},{0.113288f,0.985714f},{0.0998447f,0.974239f}, {0.119792f,0.983435f},{0.107568f,0.988395f},{0.104527f,0.9905f}, {0.0998447f,0.974239f},{0.12702f,0.984575f},{0.113633f,0.974239f}, {0.129133f,0.974239f},{0.119792f,0.983435f},{0.223779f,0.985239f}, {0.25144f,0.9905f},{0.22086f,0.9905f},{0.25144f,0.966239f}, {0.104527f,0.9905f},{0.0894779f,0.9905f},{0.0998447f,0.974239f}, {0.124845f,0.990739f},{0.114478f,0.9875f},{0.127556f,0.9875f}, {0.114382f,0.990739f},{0.113288f,0.985714f},{0.107568f,0.988395f}, {0.0998447f,0.974239f},{0.188904f,0.959005f},{0.196602f,0.96337f}, {0.152013f,0.959005f},{0.144316f,0.96037f},{0.132428f,0.968653f}, {0.0894779f,0.94556f},{0.153703f,0.94656f},{0.187215f,0.95556f}, {0.25144f,0.95556f},{0.20049f,0.965653f},{0.129133f,0.974239f}, {0.0893823f,0.974239f},{0.201752f,0.966239f},{0.25144f,0.966239f}, {0.136205f,0.9905f},{0.170459f,0.9905f},{0.153703f,0.94656f}, {0.16343f,0.959947f},{0.16343f,0.959947f},{0.170459f,0.9905f}, {0.187215f,0.95556f},{0.177475f,0.959951f},{0.16343f,0.959947f}, {0.177475f,0.959951f},{0.170459f,0.9905f},{0.177475f,0.959951f}, {0.212342f,0.9905f},{0.170459f,0.9905f},{0.136205f,0.9905f}, {0.132867f,0.987731f},{0.129133f,0.974239f},{0.132867f,0.987731f}, {0.12702f,0.984575f},{0.212342f,0.9905f},{0.212342f,0.9905f}, {0.201752f,0.966239f},{0.215506f,0.990239f},{0.28202f,0.99941f}, {0.287374f,0.99941f},{0.287374f,0.996384f},{0.215506f,0.996094f}, {0.215506f,0.990239f} }; GLint GenEPuckBody() { unsigned i; unsigned j; GLint lid=glGenLists(1); glNewList(lid, GL_COMPILE); glBegin (GL_TRIANGLES); for(i=0;i<sizeof(face_indicies)/sizeof(face_indicies[0]);i++) { for(j=0;j<3;j++) { int vi=face_indicies[i][j]; int ni=face_indicies[i][j+3];//Normal index int ti=face_indicies[i][j+6];//Texture index /*glNormal3f (normals[ni][0],normals[ni][1],normals[ni][2]); glTexCoord2f(textures[ti][0],textures[ti][1]); glVertex3f (vertices[vi][0],vertices[vi][1],vertices[vi][2]);*/ // rotate 90 deg around z glNormal3f (normals[ni][1],-normals[ni][0],normals[ni][2]); glTexCoord2f(textures[ti][0],textures[ti][1]); glVertex3f (vertices[vi][1],-vertices[vi][0],vertices[vi][2]); } } glEnd (); glEndList(); return lid; }; }
74.189445
117
0.6378
ou-real
516ee4d8d4246c315aa8525ee046b6e0ae3f44e7
1,962
cpp
C++
tree/search_tree/best_fit/bestFit.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
tree/search_tree/best_fit/bestFit.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
tree/search_tree/best_fit/bestFit.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
// best fit bin packing #include <iostream> #include "dBinarySearchTreeWithGE.h" using namespace std; void bestFitPack(int *objectSize, int numberOfObjects, int binCapacity) {// Output best-fit packing into bins of size binCapacity. // objectSize[1:numberOfObjects] are the object sizes. int n = numberOfObjects; int binsUsed = 0; dBinarySearchTreeWithGE<int,int> theTree; // tree of bin capacities pair<int, int> theBin; // pack objects one by one for (int i = 1; i <= n; i++) {// pack object i // find best bin pair<const int, int> *bestBin = theTree.findGE(objectSize[i]); if (bestBin == NULL) {// no bin large enough, start a new bin theBin.first = binCapacity; theBin.second = ++binsUsed; } else {// remove best bin from theTree theBin = *bestBin; theTree.erase(bestBin->first); } cout << "Pack object " << i << " in bin " << theBin.second << endl; // insert bin in tree unless bin is full theBin.first -= objectSize[i]; if (theBin.first > 0) theTree.insert(theBin); } } // test program int main(void) { cout << "Enter number of objects and bin capacity" << endl; int numberOfObjects, binCapacity; cin >> numberOfObjects >> binCapacity; if (numberOfObjects < 2) { cout << "Too few objects" << endl; exit(1); } // input the object sizes objectSize[1:numberOfObjects] int *objectSize = new int [numberOfObjects + 1]; for (int i = 1; i <= numberOfObjects; i++) { cout << "Enter space requirement of object " << i << endl; cin >> objectSize[i]; if (objectSize[i] > binCapacity) { cout << "Object too large to fit in a bin" << endl; exit(1); } } // output the packing bestFitPack(objectSize, numberOfObjects, binCapacity); }
27.633803
72
0.583588
vectordb-io
516fb1cfc8317517817557bd7bd6fe676725cda1
5,187
cpp
C++
ethernet_bridge/src/tcp_client/node.cpp
UniBwTAS/ethernet_bridge
c13c537b0c08326728911687dddfcdf14a727798
[ "BSD-3-Clause" ]
5
2021-06-06T18:38:35.000Z
2021-08-09T22:31:13.000Z
ethernet_bridge/src/tcp_client/node.cpp
UniBwTAS/ethernet_bridge
c13c537b0c08326728911687dddfcdf14a727798
[ "BSD-3-Clause" ]
null
null
null
ethernet_bridge/src/tcp_client/node.cpp
UniBwTAS/ethernet_bridge
c13c537b0c08326728911687dddfcdf14a727798
[ "BSD-3-Clause" ]
4
2021-08-08T23:50:59.000Z
2021-08-09T22:31:39.000Z
#include "node.h" #include <QTcpSocket> #include <QHostAddress> #include <ethernet_msgs/Event.h> #include <ethernet_msgs/EventType.h> #include <ethernet_msgs/ProtocolType.h> #include <ethernet_msgs/utils.h> Node::Node(ros::NodeHandle& nh, ros::NodeHandle& private_nh) : nh_(nh), private_nh_(nh) { /// Parameter // Topics private_nh.param<std::string>("topic_busToHost", configuration_.topic_busToHost, "bus_to_host"); private_nh.param<std::string>("topic_hostToBus", configuration_.topic_hostToBus, "host_to_bus"); private_nh.param<std::string>("topic_event", configuration_.topic_event, "event"); // Frame private_nh.param<std::string>("frame", configuration_.frame, ""); // Ethernet connection private_nh.param<std::string>("ethernet_peerAddress", configuration_.ethernet_peerAddress, "127.0.0.1"); private_nh.param<int>("ethernet_peerPort", configuration_.ethernet_peerPort, 55555); private_nh.param<int>("ethernet_bufferSize", configuration_.ethernet_bufferSize, 0); private_nh.param<int>("ethernet_reconnectInterval", configuration_.ethernet_reconnectInterval, 500); /// Subscribing & Publishing subscriber_ethernet_ = nh.subscribe(configuration_.topic_hostToBus, 100, &Node::rosCallback_ethernet, this); publisher_ethernet_packet_ = nh.advertise<ethernet_msgs::Packet>(configuration_.topic_busToHost, 100); publisher_ethernet_event_ = nh.advertise<ethernet_msgs::Event>(configuration_.topic_event, 100, true); /// Bring up socket // Initialiazation socket_ = new QTcpSocket(this); connect(socket_, SIGNAL(readyRead()), this, SLOT(slotEthernetNewData())); connect(socket_, SIGNAL(connected()), this, SLOT(slotEthernetConnected())); connect(socket_, SIGNAL(disconnected()), this, SLOT(slotEthernetDisconnected())); #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)) connect(socket_, SIGNAL(errorOccured(QAbstractSocket::SocketError)), this, SLOT(slotEthernetError(QAbstractSocket::SocketError))); #endif // Publish unconnected state slotEthernetDisconnected(); // Configuration if (configuration_.ethernet_bufferSize > 0) socket_->setReadBufferSize(configuration_.ethernet_bufferSize); // Initial connection ROS_INFO("Connecting to %s:%u ...", configuration_.ethernet_peerAddress.data(), configuration_.ethernet_peerPort); socket_->connectToHost(QString::fromStdString(configuration_.ethernet_peerAddress), configuration_.ethernet_peerPort); /// Initialize timer for reconnecting on connection loss connect(&timer_, SIGNAL(timeout()), this, SLOT(slotTimer())); if (configuration_.ethernet_reconnectInterval > 0) { timer_.setInterval(configuration_.ethernet_reconnectInterval); timer_.start(); } } Node::~Node() { delete socket_; } void Node::rosCallback_ethernet(const ethernet_msgs::Packet::ConstPtr &msg) { socket_->write(reinterpret_cast<const char*>(msg->payload.data()), msg->payload.size()); } void Node::slotEthernetNewData() { while (socket_->bytesAvailable()) { packet.header.stamp = ros::Time::now(); packet.header.frame_id = configuration_.frame; packet.sender_ip = ethernet_msgs::arrayByNativeIp4(socket_->peerAddress().toIPv4Address()); packet.sender_port = socket_->peerPort(); packet.receiver_ip = ethernet_msgs::arrayByNativeIp4(socket_->localAddress().toIPv4Address()); packet.receiver_port = socket_->localPort(); packet.payload.clear(); packet.payload.reserve(socket_->bytesAvailable()); QByteArray payload = socket_->readAll(); std::copy(payload.constBegin(), payload.constEnd(), std::back_inserter(packet.payload)); publisher_ethernet_packet_.publish(packet); } } void Node::slotEthernetConnected() { ethernet_msgs::Event event; event.header.stamp = ros::Time::now(); event.header.frame_id = configuration_.frame; event.type = ethernet_msgs::EventType::CONNECTED; publisher_ethernet_event_.publish(event); ROS_INFO("Connected."); } void Node::slotEthernetDisconnected() { ethernet_msgs::Event event; event.header.stamp = ros::Time::now(); event.header.frame_id = configuration_.frame; event.type = ethernet_msgs::EventType::DISCONNECTED; publisher_ethernet_event_.publish(event); ROS_INFO("Disconnected."); } void Node::slotEthernetError(int error_code) { ethernet_msgs::Event event; event.header.stamp = ros::Time::now(); event.header.frame_id = configuration_.frame; event.type = ethernet_msgs::EventType::SOCKETERROR; event.value = error_code; publisher_ethernet_event_.publish(event); ROS_WARN("Connection error occured, socket error code: %i", error_code); } void Node::slotTimer() { if (socket_->state() != QAbstractSocket::ConnectedState) // also covers deadlocks in other states like "ConnectingState" socket_->connectToHost(QString::fromStdString(configuration_.ethernet_peerAddress), configuration_.ethernet_peerPort); }
36.787234
135
0.710816
UniBwTAS
51706b4bc2a573e50ce30f7eebe1e9225cc7608a
196
cpp
C++
Floating_Point_Instructions/DP_Instructions/Conversion_and_Move/FMV.D.X.cpp
vinodganesan/shaktiISS
fb48e202596989004136b3d44e6fcfa191ba6ea8
[ "BSD-3-Clause" ]
null
null
null
Floating_Point_Instructions/DP_Instructions/Conversion_and_Move/FMV.D.X.cpp
vinodganesan/shaktiISS
fb48e202596989004136b3d44e6fcfa191ba6ea8
[ "BSD-3-Clause" ]
null
null
null
Floating_Point_Instructions/DP_Instructions/Conversion_and_Move/FMV.D.X.cpp
vinodganesan/shaktiISS
fb48e202596989004136b3d44e6fcfa191ba6ea8
[ "BSD-3-Clause" ]
null
null
null
#include<stdio.h> #include<sstream> #include<iostream> #include<string> void fmvdx(int rd, int rs1, std::string rm) { getrounding(rm); for(int i= 0; i < 64 ; ++i) Rreg[rs1][i] = Freg[rd][i]; }
15.076923
43
0.642857
vinodganesan
517089bb21af2202511875938970efe499b93c99
2,469
cpp
C++
2021day21/run.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
2021day21/run.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
2021day21/run.cpp
AntonJoha/AdventOfCode
3349f789adf3dc1d8062d56ba3efb20fbb0ee335
[ "MIT" ]
null
null
null
#include "run.h" #include <iostream> #define STARTONE 1 #define STARTTWO 7 //FIRST PROBLEM HERE #ifdef FIRST #define MAXSIZE 10 #define WINNING 1000 std::string run::solve(std::ifstream* file){ unsigned int point1 = 0; unsigned int point2 = 0; unsigned int pos1 = STARTONE; unsigned int pos2 = STARTTWO; unsigned int count = 1; while (true){ for (size_t i = 0; i < 3; ++i){ pos1 = ((count%100) + pos1) % 10; ++count; } point1 += 1 + pos1; if (point1 >= WINNING){ return std::to_string( (count - 1)*point2); } for (size_t i = 0; i < 3; ++i){ pos2 = ((count%100) + pos2) % 10; ++count; } point2 += 1 + pos2; if (point2 >= WINNING){ return std::to_string( (count - 1)*point1); } } return ""; } #endif //SECOND PROBLEM HERE #ifdef SECOND #define WINNING 21 unsigned long points(unsigned int val1, unsigned int val2, unsigned int pos1, unsigned int pos2, bool turnP1, bool retP1); unsigned long callNew(unsigned int val1, unsigned int val2, unsigned int pos1, unsigned int pos2, bool turnP1, bool retP1, unsigned int add){ if (turnP1){ pos1 = (pos1 + add)%10; val1 += pos1 + 1; } else{ pos2 = (pos2 + add)%10; val2 += pos2 + 1; } return points(val1, val2, pos1, pos2, !turnP1, retP1); } unsigned long points(unsigned int val1, unsigned int val2, unsigned int pos1, unsigned int pos2, bool turnP1, bool retP1){ if (val1 >= WINNING){ if (retP1) return 1; else return 0; } if (val2 >= WINNING){ if (retP1) return 0; else return 1; } unsigned long toReturn = 0; #define MORE(x, y, z) x += y*callNew(val1, val2, pos1, pos2, turnP1, retP1, z) //There are 21 different combinations // 3 3 3 one time 9 //9 , 1 MORE(toReturn, 1, 9); // 3 3 2 three times 8 // 8, 3 MORE(toReturn, 3, 8); // 3 3 1 three times 7 // 2 2 3 three times 7 // 7, 6 MORE(toReturn, 6, 7); // 2 2 2 one time 6 // 3 2 1 six times 6 // 6, 7 MORE(toReturn, 7, 6); // 2 2 1 three times 5 // 1 1 3 three times 5 // 5, 6 MORE(toReturn, 6, 5); // 1 1 2 three times 4 // 4, 3 MORE(toReturn, 3, 4); // 1 1 1 one time 3 // 3, 1 MORE(toReturn, 1, 3); return toReturn; } std::string run::solve(std::ifstream* file){ unsigned long first = points(0,0, STARTONE, STARTTWO, true, true); unsigned long second = points(0,0, STARTONE, STARTTWO, true, false); if (first < second) return std::to_string(second); return std::to_string(first); } #endif
16.243421
141
0.617659
AntonJoha
517d4a1a62061ad5166536ef1e0a5fd4a610adcc
708
cpp
C++
src/plugins/monocle/plugins/dik/util.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/monocle/plugins/dik/util.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/monocle/plugins/dik/util.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "util.h" #include <QByteArray> namespace LC { namespace Monocle { namespace Dik { quint32 Read32 (const QByteArray& data, int offset) { quint32 result = 0; for (int i = 0; i < 4; ++i) { result <<= 8; result += static_cast<uchar> (data [offset + i]); } return result; } } } }
22.83871
83
0.538136
Maledictus
517dc23312aef835ebeb65f481f6b9e7f0cfea00
18,480
cpp
C++
src/editor/BMC-Editor.midi.utility.cpp
neroroxxx/BMC
ec85174f5398e548c829821f75a14edfeabfecf1
[ "MIT" ]
36
2020-07-16T02:19:21.000Z
2022-03-21T22:11:41.000Z
src/editor/BMC-Editor.midi.utility.cpp
neroroxxx/BMC
ec85174f5398e548c829821f75a14edfeabfecf1
[ "MIT" ]
1
2021-11-24T05:49:19.000Z
2021-11-24T15:01:57.000Z
src/editor/BMC-Editor.midi.utility.cpp
neroroxxx/BMC
ec85174f5398e548c829821f75a14edfeabfecf1
[ "MIT" ]
null
null
null
/* See https://www.RoxXxtar.com/bmc for more details Copyright (c) 2020 RoxXxtar.com Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "editor/BMC-Editor.h" void BMCEditor::utilityCommand(){ dataForBMC.reset(); if(dataForBMC.set(isWriteMessage(), incoming)){ flags.on(BMC_EDITOR_FLAG_DATA_FOR_BMC_AVAILABLE); } } // on all the following functions onlyIfConnected is used by // BMC when buttons are being read or leds have changed states. // all those functions will notify the editor but with onlyIfConnected set to "true" // This is so that these are skipped when the editor is not connected, however // if another BMC build is connected to this BMC build they can request data // from each other thru other means, those requests would have onlyIfConnected set to "false" // Additionally BMC can enable/disabled editor real time feedback which turns leds on/off // lights up buttons when pressed etc on the editor app. // this option is not store in EEPROM instead is stored in the editor app local settings // and the editor app will send it as needed. This is so that the PERFORMANCE mode // don't get these messages making the MIDI traffic less. #if BMC_MAX_BUTTONS > 32 void BMCEditor::utilitySendButtonActivity(uint32_t states, uint32_t states2, bool onlyIfConnected){ #else void BMCEditor::utilitySendButtonActivity(uint32_t states, bool onlyIfConnected){ #endif #if BMC_MAX_BUTTONS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_BUTTON ); buff.appendToSysEx32Bits(states); #if BMC_MAX_BUTTONS > 32 buff.appendToSysEx32Bits(states2); #endif // don't show midi activity sendToEditor(buff,true,false); } #endif } void BMCEditor::utilitySendGlobalButtonActivity(uint32_t states, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_BUTTONS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_BUTTON ); buff.appendToSysEx32Bits(states); // don't show midi activity sendToEditor(buff,true,false); } #endif } void BMCEditor::utilitySendLedActivity(uint32_t data, bool onlyIfConnected){ #if BMC_MAX_LEDS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_LED ); buff.appendToSysEx32Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendAuxJackActivity(uint8_t data, bool onlyIfConnected){ #if BMC_MAX_AUX_JACKS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_AUX_JACK ); buff.appendToSysEx7Bits(data); sendToEditor(buff, true, false); // don't show midi activity } #endif } void BMCEditor::utilitySendFasState(uint8_t data, bool onlyIfConnected){ #if defined(BMC_USE_FAS) if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_FAS_STATE ); buff.appendToSysEx7Bits(data); sendToEditor(buff, true, false); // don't show midi activity } #endif } void BMCEditor::utilitySendNLRelayActivity(uint16_t data, bool onlyIfConnected){ #if BMC_MAX_NL_RELAYS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_NL_RELAY ); buff.appendToSysEx16Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendLRelayActivity(uint16_t data, bool onlyIfConnected){ #if BMC_MAX_L_RELAYS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_L_RELAY ); buff.appendToSysEx16Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPixelActivity(uint32_t data, bool onlyIfConnected){ #if BMC_MAX_PIXELS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_PIXEL ); buff.appendToSysEx32Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendRgbPixelActivity(uint32_t red, uint32_t green, uint32_t blue, bool onlyIfConnected){ #if BMC_MAX_RGB_PIXELS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_RGB_PIXEL ); buff.appendToSysEx32Bits(red); buff.appendToSysEx32Bits(green); buff.appendToSysEx32Bits(blue); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendGlobalLedActivity(uint16_t data, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_LEDS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_LED ); buff.appendToSysEx16Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPwmLedActivity(uint32_t data, bool onlyIfConnected){ #if BMC_MAX_PWM_LEDS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_PWM_LED ); buff.appendToSysEx32Bits(data); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPotActivity(uint8_t index, uint8_t value, bool onlyIfConnected){ #if BMC_MAX_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing() && index < BMC_MAX_POTS){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_POT); buff.appendToSysEx7Bits(index); buff.appendToSysEx7Bits(value); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPotsActivity(uint8_t *values, uint8_t length, bool onlyIfConnected){ #if BMC_MAX_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_POTS ); buff.appendToSysEx7Bits(length); for(uint8_t i = 0; i < length; i++){ buff.appendToSysEx7Bits(values[i]); } sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendGlobalPotActivity(uint8_t index, uint8_t value, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing() && index < BMC_MAX_GLOBAL_POTS){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_POT); buff.appendToSysEx7Bits(index); buff.appendToSysEx7Bits(value); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendGlobalPotsActivity(uint8_t *values, uint8_t length, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing()){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_POTS ); buff.appendToSysEx7Bits(length); for(uint8_t i = 0; i < length; i++){ buff.appendToSysEx7Bits(values[i]); } sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendEncoderActivity(uint8_t index, bool increased, bool onlyIfConnected){ #if BMC_MAX_ENCODERS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing() && index < BMC_MAX_ENCODERS){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_ENCODER ); buff.appendToSysEx7Bits(index); buff.appendToSysEx7Bits(increased); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendGlobalEncoderActivity(uint8_t index, bool increased, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_ENCODERS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } if(!connectionOngoing() && index < BMC_MAX_GLOBAL_ENCODERS){ BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_GLOBAL_ENCODER ); buff.appendToSysEx7Bits(index); buff.appendToSysEx7Bits(increased); sendToEditor(buff,true,false); // don't show midi activity } #endif } void BMCEditor::utilitySendPreset(bmcPreset_t presetNumber, bool onlyIfConnected){ #if BMC_MAX_PRESETS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } if(presetNumber >= BMC_MAX_PRESETS){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_PRESET ); buff.appendToSysEx8Bits(presetNumber); #if BMC_NAME_LEN_PRESETS > 1 bmcStoreGlobalPresets& item = store.global.presets[presetNumber]; buff.appendToSysEx7Bits(BMC_NAME_LEN_PRESETS); buff.appendCharArrayToSysEx(item.name, BMC_NAME_LEN_PRESETS); #endif sendToEditor(buff,true,false); // don't show midi activity #endif } void BMCEditor::utilitySendClickTrackData(uint16_t freq, uint8_t level, uint8_t state, bool onlyIfConnected){ #ifdef BMC_USE_CLICK_TRACK if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } BMCEditorMidiFlags flag; flag.setWrite(true); BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, flag, BMC_UTILF_CLICK_TRACK ); buff.appendToSysEx16Bits(freq); buff.appendToSysEx7Bits(level); buff.appendToSysEx7Bits(state); sendToEditor(buff,true,false); // don't show midi activity #endif } void BMCEditor::utilitySendPotCalibrationStatus(bool status, bool canceled, bool onlyIfConnected){ #if BMC_MAX_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, 0, BMC_UTILF_POT_CALIBRATION_STATUS ); buff.appendToSysEx7Bits(status?1:0); buff.appendToSysEx7Bits(canceled?1:0); // don't show midi activity sendToEditor(buff,true,false); #endif } void BMCEditor::utilitySendGlobalPotCalibrationStatus(bool status, bool canceled, bool onlyIfConnected){ #if BMC_MAX_GLOBAL_POTS > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, 0, BMC_UTILF_GLOBAL_POT_CALIBRATION_STATUS ); buff.appendToSysEx7Bits(status?1:0); buff.appendToSysEx7Bits(canceled?1:0); // don't show midi activity sendToEditor(buff,true,false); #endif } // send a message to the editor with the sketchbytes // used when sketch bytes are updated by the Sketch API void BMCEditor::utilitySendSketchBytes(bool onlyIfConnected){ #if BMC_MAX_SKETCH_BYTES > 0 if(flags.read(BMC_EDITOR_FLAG_BACKUP_ACTIVE)){ return; } if(onlyIfConnected && !midi.globals.editorConnected()){ return; } // if editor feedback is disabled... if(onlyIfConnected && !flags.read(BMC_EDITOR_FLAG_EDITOR_FEEDBACK)){ return; } BMCMidiMessage buff; buff.prepareEditorMessage( port, deviceId, BMC_GLOBALF_UTILITY, 0, BMC_UTILF_SKETCH_BYTES ); buff.appendToSysEx7Bits(BMC_MAX_SKETCH_BYTES); for(uint8_t i = 0 ; i < BMC_MAX_SKETCH_BYTES ; i++){ buff.appendToSysEx8Bits(store.global.sketchBytes[i]); } // don't show midi activity sendToEditor(buff,true,false); #endif }
29.010989
93
0.695238
neroroxxx
517efa2467c899b605c19800a56ab2b618abba44
8,412
cpp
C++
newweb/browser/render_process/webengine/dom/Document.cpp
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
newweb/browser/render_process/webengine/dom/Document.cpp
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
newweb/browser/render_process/webengine/dom/Document.cpp
cauthu/shadow-browser-plugin
e1eb930b1bdf71cb3cdcbb1d70467e6e6203c298
[ "BSD-3-Clause" ]
null
null
null
#include <event2/event.h> #include <strings.h> #include <boost/bind.hpp> #include "../../../../utility/easylogging++.h" #include "../../../../utility/common.hpp" #include "../../../../utility/folly/ScopeGuard.h" #include "Document.hpp" #include "../webengine.hpp" #include "../events/EventTypeNames.hpp" #include "../html/HTMLScriptElement.hpp" #include "../html/HTMLLinkElement.hpp" #include "../html/HTMLImageElement.hpp" using std::make_pair; using std::shared_ptr; #define _LOG_PREFIX(inst) << "doc= " << (inst)->objId() << ": " /* "inst" stands for instance, as in, instance of a class */ #define vloginst(level, inst) VLOG(level) _LOG_PREFIX(inst) #define vlogself(level) vloginst(level, this) #define dvloginst(level, inst) DVLOG(level) _LOG_PREFIX(inst) #define dvlogself(level) dvloginst(level, this) #define loginst(level, inst) LOG(level) _LOG_PREFIX(inst) #define logself(level) loginst(level, this) namespace blink { Document::Document(struct ::event_base* evbase, const uint32_t& instNum, Webengine* webengine, const PageModel* page_model, ResourceFetcher* resource_fetcher) : EventTarget(instNum, webengine) , evbase_(evbase) , webengine_(webengine) , page_model_(page_model) , resource_fetcher_(resource_fetcher) , state_(ReadyState::Initial) , executeScriptsWaitingForResourcesTimer_( new Timer(evbase, true, boost::bind(&Document::_executeScriptsWaitingForResourcesTimerFired, this, _1))) , has_body_element_(false) , finished_parsing_(false) , load_start_time_ms_(0) { CHECK_NOTNULL(evbase_); PageModel::DocumentInfo doc_info; auto rv = page_model_->get_main_doc_info(doc_info); CHECK(rv); add_event_handling_scopes(doc_info.event_handling_scopes); vlogself(2) << "number of event handling scopes: " << doc_info.event_handling_scopes.size(); parser_.reset( new HTMLDocumentParser(page_model, this, webengine_, resource_fetcher_)); } void Document::load() { CHECK_EQ(state_, ReadyState::Initial); state_ = ReadyState::Loading; load_start_time_ms_ = common::gettimeofdayMs(); _load_main_resource(); } void Document::setReadyState(ReadyState readyState) { if (readyState == state_) { return; } state_ = readyState; switch (readyState) { case ReadyState::Initial: case ReadyState::Loading: case ReadyState::Interactive: break; case ReadyState::Complete: fireEventHandlingScopes(EventTypeNames::readystatechange_complete); break; } } void Document::implicitClose() { CHECK_EQ(state_, ReadyState::Complete); // in real webkit, this will be done by LocalDOMWindow, i.e., the // window, not the document, fires "load" event. but we'll // approximate it here fireEventHandlingScopes(EventTypeNames::load); } bool Document::parsing() const { return !finished_parsing_; } void Document::add_elem(const uint32_t& elemInstNum) { PageModel::ElementInfo elem_info; vlogself(2) << "begin, elem:" << elemInstNum; CHECK(!inMap(elements_, elemInstNum)); const auto rv = page_model_->get_element_info(elemInstNum, elem_info); CHECK(rv); Element* element = nullptr; SCOPE_EXIT { // should have cleared element before exiting this func CHECK(!element); }; if (elem_info.tag == "script") { element = new HTMLScriptElement(elemInstNum, this, elem_info); HTMLScriptElement* script_elem = (HTMLScriptElement*)element; if (script_elem->is_parser_blocking()) { vlogself(2) << "this script blocks parser"; parser_->set_parser_blocking_script(script_elem); } } else if (elem_info.tag == "link") { element = new HTMLLinkElement(elemInstNum, this, elem_info); } else if (elem_info.tag == "img") { element = new HTMLImageElement(elemInstNum, this, elem_info); } else if (elem_info.tag == "body") { CHECK(!has_body_element_); has_body_element_ = true; webengine_->maybe_sched_INITIAL_render_update_scope(); return; } else { logself(FATAL) << "element tag [" << elem_info.tag << "] not supported"; } CHECK_NOTNULL(element); std::shared_ptr<Element> elem_shptr( element, [](Element* e) { e->destroy(); } ); element = nullptr; const auto ret = elements_.insert(make_pair(elemInstNum, elem_shptr)); CHECK(ret.second); vlogself(2) << "done"; } void Document::set_elem_res(const uint32_t elemInstNum, const uint32_t resInstNum) { VLOG(2) << "begin, elem:" << elemInstNum << " res:" << resInstNum; if (inMap(elements_, elemInstNum)) { shared_ptr<Element> element = elements_[elemInstNum]; CHECK_NOTNULL(element.get()); element->setResInstNum(resInstNum); } else { // this can happen because scripts can set diff elems // depending on their existence. but that is something we // cannot model yet LOG(WARNING) << "elem:" << elemInstNum << " does not (yet) exist"; } VLOG(2) << "done"; } bool Document::isScriptExecutionReady() const { return pendingStylesheets_.empty(); } void Document::addPendingSheet(Element* element) { const auto elemInstNum = element->instNum(); const auto it = pendingStylesheets_.find(elemInstNum); CHECK(it == pendingStylesheets_.end()) << "elem:" << elemInstNum << " already a pending stylesheet"; pendingStylesheets_.insert(elemInstNum); vlogself(2) << "elem:" << elemInstNum << " increments pendingStylesheets_ to " << pendingStylesheets_.size(); } void Document::removePendingSheet(Element* element) { const auto elemInstNum = element->instNum(); const auto it = pendingStylesheets_.find(elemInstNum); CHECK(it != pendingStylesheets_.end()) << "elem:" << element->instNum() << " not a pending stylesheet"; pendingStylesheets_.erase(it); vlogself(2) << "elem:" << elemInstNum << " decrements pendingStylesheets_ to " << pendingStylesheets_.size(); if (pendingStylesheets_.size()) { return; } vlogself(2) << "schedule timer to execute scripts"; _didLoadAllScriptBlockingResources(); } void Document::finishedParsing() { const auto elapsed_ms = common::gettimeofdayMs() - load_start_time_ms_; logself(INFO) << "has finished parsing (after " << elapsed_ms << " ms)"; finished_parsing_ = true; fireEventHandlingScopes(EventTypeNames::DOMContentLoaded); webengine_->finishedParsing(); } void Document::_didLoadAllScriptBlockingResources() { if (!executeScriptsWaitingForResourcesTimer_->is_running()) { // fire asap static const uint32_t delayMs = 0; const auto rv = executeScriptsWaitingForResourcesTimer_->start(delayMs, false); CHECK(rv); } } void Document::_executeScriptsWaitingForResourcesTimerFired(Timer*) { // after the timer is scheduled but before it fires, more blocking // style sheets can be added (e.g., by script) if (pendingStylesheets_.empty()) { parser_->executeScriptsWaitingForResources(); } } void Document::_load_main_resource() { main_resource_ = resource_fetcher_->getMainResource(); CHECK(main_resource_); // make sure it's not being loaded yet CHECK(!main_resource_->isFinished()); CHECK(!main_resource_->isLoading()); main_resource_->addClient(this); main_resource_->load(); } void Document::notifyFinished(Resource* resource, bool success) { /* the only resource we watch is our main resource */ vlogself(2) << "begin, success= " << success; CHECK_EQ(main_resource_.get(), resource); CHECK(success) << "TODO: deal with failure of main resource"; parser_->finish_receive(); vlogself(2) << "done"; } void Document::dataReceived(Resource* resource, size_t length) { vlogself(2) << "begin, " << length << " more bytes"; CHECK_EQ(main_resource_.get(), resource); vlogself(2) << "pump the parser"; parser_->appendBytes(length); parser_->pumpTokenizerIfPossible(); vlogself(2) << "done"; } void Document::responseReceived(Resource* resource) { CHECK_EQ(main_resource_.get(), resource); } } // end namespace blink
26.620253
98
0.666429
cauthu
5183065061469c4b6fdb4010bde946649fdbeff5
1,487
cpp
C++
src/search/searchdata.cpp
l1422586361/vnote
606dcef16f882350cc2be2fd108625894d13143b
[ "MIT" ]
1
2021-09-13T04:38:27.000Z
2021-09-13T04:38:27.000Z
src/search/searchdata.cpp
micalstanley/vnote-1
606dcef16f882350cc2be2fd108625894d13143b
[ "MIT" ]
null
null
null
src/search/searchdata.cpp
micalstanley/vnote-1
606dcef16f882350cc2be2fd108625894d13143b
[ "MIT" ]
null
null
null
#include "searchdata.h" #include <QJsonObject> using namespace vnotex; SearchOption::SearchOption() : m_objects(SearchObject::SearchName | SearchObject::SearchContent), m_targets(SearchTarget::SearchFile | SearchTarget::SearchFolder) { } QJsonObject SearchOption::toJson() const { QJsonObject obj; obj["file_pattern"] = m_filePattern; obj["scope"] = static_cast<int>(m_scope); obj["objects"] = static_cast<int>(m_objects); obj["targets"] = static_cast<int>(m_targets); obj["engine"] = static_cast<int>(m_engine); obj["find_options"] = static_cast<int>(m_findOptions); return obj; } void SearchOption::fromJson(const QJsonObject &p_obj) { if (p_obj.isEmpty()) { return; } m_filePattern = p_obj["file_pattern"].toString(); m_scope = static_cast<SearchScope>(p_obj["scope"].toInt()); m_objects = static_cast<SearchObjects>(p_obj["objects"].toInt()); m_targets = static_cast<SearchTargets>(p_obj["targets"].toInt()); m_engine = static_cast<SearchEngine>(p_obj["engine"].toInt()); m_findOptions = static_cast<FindOptions>(p_obj["find_options"].toInt()); } bool SearchOption::operator==(const SearchOption &p_other) const { return m_filePattern == p_other.m_filePattern && m_scope == p_other.m_scope && m_objects == p_other.m_objects && m_targets == p_other.m_targets && m_engine == p_other.m_engine && m_findOptions == p_other.m_findOptions; }
30.979167
76
0.68191
l1422586361
3d674e75f4301f260f133e265014501c3167b91e
20,853
cpp
C++
module/mpc-be/SRC/src/filters/source/SubtitleSource/SubtitleSource.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/source/SubtitleSource/SubtitleSource.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/source/SubtitleSource/SubtitleSource.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
/* * (C) 2003-2006 Gabest * (C) 2006-2020 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * MPC-BE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include "SubtitleSource.h" #include "../../../DSUtil/DSUtil.h" #include <moreuuids.h> #include <basestruct.h> static int _WIDTH = 640; static int _HEIGHT = 480; static int _ATPF = 400000; #ifdef REGISTER_FILTER const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = { {&MEDIATYPE_Subtitle, &MEDIASUBTYPE_NULL}, {&MEDIATYPE_Text, &MEDIASUBTYPE_NULL}, {&MEDIATYPE_Video, &MEDIASUBTYPE_RGB32}, }; const AMOVIESETUP_PIN sudOpPin[] = { {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut}, }; const AMOVIESETUP_FILTER sudFilter[] = { {&__uuidof(CSubtitleSourceASCII), L"MPC SubtitleSource (S_TEXT/ASCII)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceUTF8), L"MPC SubtitleSource (S_TEXT/UTF8)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceSSA), L"MPC SubtitleSource (S_TEXT/SSA)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceASS), L"MPC SubtitleSource (S_TEXT/ASS)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceUSF), L"MPC SubtitleSource (S_TEXT/USF)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourcePreview), L"MPC SubtitleSource (Preview)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, {&__uuidof(CSubtitleSourceARGB), L"MPC SubtitleSource (ARGB)", MERIT_NORMAL, _countof(sudOpPin), sudOpPin, CLSID_LegacyAmFilterCategory}, }; CFactoryTemplate g_Templates[] = { {sudFilter[0].strName, sudFilter[0].clsID, CreateInstance<CSubtitleSourceASCII>, nullptr, &sudFilter[0]}, {sudFilter[1].strName, sudFilter[1].clsID, CreateInstance<CSubtitleSourceUTF8>, nullptr, &sudFilter[1]}, {sudFilter[2].strName, sudFilter[2].clsID, CreateInstance<CSubtitleSourceSSA>, nullptr, &sudFilter[2]}, {sudFilter[3].strName, sudFilter[3].clsID, CreateInstance<CSubtitleSourceASS>, nullptr, &sudFilter[3]}, // {sudFilter[4].strName, sudFilter[4].clsID, CreateInstance<CSubtitleSourceUSF>, nullptr, &sudFilter[4]}, {sudFilter[5].strName, sudFilter[5].clsID, CreateInstance<CSubtitleSourcePreview>, nullptr, &sudFilter[5]}, {sudFilter[6].strName, sudFilter[6].clsID, CreateInstance<CSubtitleSourceARGB>, nullptr, &sudFilter[6]}, }; int g_cTemplates = _countof(g_Templates); STDAPI DllRegisterServer() { /*CString clsid = CStringFromGUID(__uuidof(CSubtitleSourcePreview)); SetRegKeyValue( L"Media Type\\Extensions", L".sub", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".srt", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".smi", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".ssa", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".ass", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".xss", L"Source Filter", clsid); SetRegKeyValue( L"Media Type\\Extensions", L".usf", L"Source Filter", clsid);*/ return AMovieDllRegisterServer2(TRUE); } STDAPI DllUnregisterServer() { DeleteRegKey(L"Media Type\\Extensions", L".sub"); DeleteRegKey(L"Media Type\\Extensions", L".srt"); DeleteRegKey(L"Media Type\\Extensions", L".smi"); DeleteRegKey(L"Media Type\\Extensions", L".ssa"); DeleteRegKey(L"Media Type\\Extensions", L".ass"); DeleteRegKey(L"Media Type\\Extensions", L".xss"); DeleteRegKey(L"Media Type\\Extensions", L".usf"); /**/ return AMovieDllRegisterServer2(FALSE); } #include "../../filters/Filters.h" class CSubtitleSourceApp : public CFilterApp { public: BOOL InitInstance() { if (!__super::InitInstance()) { return FALSE; } _WIDTH = GetProfileInt(L"SubtitleSource", L"w", 640); _HEIGHT = GetProfileInt(L"SubtitleSource", L"h", 480); _ATPF = GetProfileInt(L"SubtitleSource", L"atpf", 400000); if (_ATPF <= 0) { _ATPF = 400000; } WriteProfileInt(L"SubtitleSource", L"w", _WIDTH); WriteProfileInt(L"SubtitleSource", L"h", _HEIGHT); WriteProfileInt(L"SubtitleSource", L"atpf", _ATPF); return TRUE; } }; CSubtitleSourceApp theApp; #endif // // CSubtitleSource // CSubtitleSource::CSubtitleSource(LPUNKNOWN lpunk, HRESULT* phr, const CLSID& clsid) : CSource(L"CSubtitleSource", lpunk, clsid) { } CSubtitleSource::~CSubtitleSource() { } STDMETHODIMP CSubtitleSource::NonDelegatingQueryInterface(REFIID riid, void** ppv) { CheckPointer(ppv, E_POINTER); return QI(IFileSourceFilter) QI(IAMFilterMiscFlags) __super::NonDelegatingQueryInterface(riid, ppv); } // IFileSourceFilter STDMETHODIMP CSubtitleSource::Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE* pmt) { if (GetPinCount() > 0) { return VFW_E_ALREADY_CONNECTED; } HRESULT hr = S_OK; if (!(DNew CSubtitleStream(pszFileName, this, &hr))) { return E_OUTOFMEMORY; } if (FAILED(hr)) { return hr; } m_fn = pszFileName; return S_OK; } STDMETHODIMP CSubtitleSource::GetCurFile(LPOLESTR* ppszFileName, AM_MEDIA_TYPE* pmt) { CheckPointer(ppszFileName, E_POINTER); size_t nCount = m_fn.GetLength() + 1; *ppszFileName = (LPOLESTR)CoTaskMemAlloc(nCount * sizeof(WCHAR)); CheckPointer(*ppszFileName, E_OUTOFMEMORY); wcscpy_s(*ppszFileName, nCount, m_fn); return S_OK; } // IAMFilterMiscFlags ULONG CSubtitleSource::GetMiscFlags() { return AM_FILTER_MISC_FLAGS_IS_SOURCE; } STDMETHODIMP CSubtitleSource::QueryFilterInfo(FILTER_INFO* pInfo) { CheckPointer(pInfo, E_POINTER); ValidateReadWritePtr(pInfo, sizeof(FILTER_INFO)); wcscpy_s(pInfo->achName, SubtitleSourceName); pInfo->pGraph = m_pGraph; if (m_pGraph) { m_pGraph->AddRef(); } return S_OK; } // // CSubtitleStream // CSubtitleStream::CSubtitleStream(const WCHAR* wfn, CSubtitleSource* pParent, HRESULT* phr) : CSourceStream(L"SubtitleStream", phr, pParent, L"Output") , CSourceSeeking(L"SubtitleStream", (IPin*)this, phr, &m_cSharedState) , m_bDiscontinuity(FALSE), m_bFlushing(FALSE) , m_nPosition(0) , m_rts(nullptr) { CAutoLock cAutoLock(&m_cSharedState); CString fn(wfn); if (!m_rts.Open(fn, DEFAULT_CHARSET)) { if (phr) { *phr = E_FAIL; } return; } m_rts.CreateDefaultStyle(DEFAULT_CHARSET); m_rts.ConvertToTimeBased(25); m_rts.Sort(); m_rtDuration = 0; for (size_t i = 0, cnt = m_rts.GetCount(); i < cnt; i++) { m_rtDuration = std::max(m_rtDuration.GetUnits(), 10000i64*m_rts[i].end); } m_rtStop = m_rtDuration; if (phr) { *phr = m_rtDuration > 0 ? S_OK : E_FAIL; } } CSubtitleStream::~CSubtitleStream() { CAutoLock cAutoLock(&m_cSharedState); } STDMETHODIMP CSubtitleStream::NonDelegatingQueryInterface(REFIID riid, void** ppv) { CheckPointer(ppv, E_POINTER); return (riid == IID_IMediaSeeking) ? CSourceSeeking::NonDelegatingQueryInterface(riid, ppv) //GetInterface((IMediaSeeking*)this, ppv) : CSourceStream::NonDelegatingQueryInterface(riid, ppv); } void CSubtitleStream::UpdateFromSeek() { if (ThreadExists()) { // next time around the loop, the worker thread will // pick up the position change. // We need to flush all the existing data - we must do that here // as our thread will probably be blocked in GetBuffer otherwise m_bFlushing = TRUE; DeliverBeginFlush(); // make sure we have stopped pushing Stop(); // complete the flush DeliverEndFlush(); m_bFlushing = FALSE; // restart Run(); } } HRESULT CSubtitleStream::SetRate(double dRate) { if (dRate <= 0) { return E_INVALIDARG; } { CAutoLock lock(CSourceSeeking::m_pLock); m_dRateSeeking = dRate; } UpdateFromSeek(); return S_OK; } HRESULT CSubtitleStream::OnThreadStartPlay() { m_bDiscontinuity = TRUE; return DeliverNewSegment(m_rtStart, m_rtStop, m_dRateSeeking); } HRESULT CSubtitleStream::ChangeStart() { { CAutoLock lock(CSourceSeeking::m_pLock); OnThreadCreate(); /*if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_ARGB32) { m_nPosition = (int)(m_rtStart/10000)*1/1000; } else if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_RGB32) { int m_nSegments = 0; if (!m_rts.SearchSubs((int)(m_rtStart/10000), 25, &m_nPosition, &m_nSegments)) m_nPosition = m_nSegments; } else { m_nPosition = m_rts.SearchSub((int)(m_rtStart/10000), 25); if (m_nPosition < 0) m_nPosition = 0; else if (m_rts[m_nPosition].end <= (int)(m_rtStart/10000)) m_nPosition++; }*/ } UpdateFromSeek(); return S_OK; } HRESULT CSubtitleStream::ChangeStop() { /*{ CAutoLock lock(CSourceSeeking::m_pLock); if (m_rtPosition < m_rtStop) return S_OK; }*/ // We're already past the new stop time -- better flush the graph. UpdateFromSeek(); return S_OK; } HRESULT CSubtitleStream::OnThreadCreate() { CAutoLock cAutoLockShared(&m_cSharedState); if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_ARGB32) { m_nPosition = (int)(m_rtStart/_ATPF); } else if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_RGB32) { int m_nSegments = 0; if (!m_rts.SearchSubs((int)(m_rtStart/10000), 10000000.0/_ATPF, &m_nPosition, &m_nSegments)) { m_nPosition = m_nSegments; } } else { m_nPosition = m_rts.SearchSub((int)(m_rtStart/10000), 25); if (m_nPosition < 0) { m_nPosition = 0; } else if (m_rts[m_nPosition].end <= (int)(m_rtStart/10000)) { m_nPosition++; } } return CSourceStream::OnThreadCreate(); } HRESULT CSubtitleStream::DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties) { //CAutoLock cAutoLock(m_pFilter->pStateLock()); ASSERT(pAlloc); ASSERT(pProperties); HRESULT hr = NOERROR; if (m_mt.majortype == MEDIATYPE_Video) { pProperties->cBuffers = 2; pProperties->cbBuffer = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader.biSizeImage; } else { pProperties->cBuffers = 1; pProperties->cbBuffer = 0x10000; } ALLOCATOR_PROPERTIES Actual; if (FAILED(hr = pAlloc->SetProperties(pProperties, &Actual))) { return hr; } if (Actual.cbBuffer < pProperties->cbBuffer) { return E_FAIL; } ASSERT(Actual.cBuffers == pProperties->cBuffers); return NOERROR; } HRESULT CSubtitleStream::FillBuffer(IMediaSample* pSample) { HRESULT hr; { CAutoLock cAutoLockShared(&m_cSharedState); BYTE* pData = nullptr; if (FAILED(hr = pSample->GetPointer(&pData)) || !pData) { return S_FALSE; } AM_MEDIA_TYPE* pmt; if (SUCCEEDED(pSample->GetMediaType(&pmt)) && pmt) { CMediaType mt(*pmt); SetMediaType(&mt); DeleteMediaType(pmt); } int len = 0; REFERENCE_TIME rtStart, rtStop; if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_ARGB32) { rtStart = (REFERENCE_TIME)((m_nPosition*_ATPF - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)(((m_nPosition+1)*_ATPF - m_rtStart) / m_dRateSeeking); if (m_rtStart+rtStart >= m_rtDuration) { return S_FALSE; } BITMAPINFOHEADER& bmi = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader; SubPicDesc spd; spd.w = _WIDTH; spd.h = _HEIGHT; spd.bpp = 32; spd.pitch = bmi.biWidth*4; spd.bits = pData; len = spd.h*spd.pitch; for (int y = 0; y < spd.h; y++) { memsetd((DWORD*)(pData + spd.pitch*y), 0xff000000, spd.w*4); } RECT bbox; m_rts.Render(spd, m_nPosition*_ATPF, 10000000.0/_ATPF, bbox); for (int y = 0; y < spd.h; y++) { DWORD* p = (DWORD*)(pData + spd.pitch*y); for (int x = 0; x < spd.w; x++, p++) { *p = (0xff000000-(*p&0xff000000))|(*p&0xffffff); } } } else if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_RGB32) { const STSSegment* stss = m_rts.GetSegment(m_nPosition); if (!stss) { return S_FALSE; } BITMAPINFOHEADER& bmi = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader; SubPicDesc spd; spd.w = _WIDTH; spd.h = _HEIGHT; spd.bpp = 32; spd.pitch = bmi.biWidth*4; spd.bits = pData; len = spd.h*spd.pitch; for (int y = 0; y < spd.h; y++) { DWORD c1 = 0xff606060, c2 = 0xffa0a0a0; if (y&32) { c1 ^= c2, c2 ^= c1, c1 ^= c2; } DWORD* p = (DWORD*)(pData + spd.pitch*y); for (int x = 0; x < spd.w; x+=32, p+=32) { memsetd(p, (x&32) ? c1 : c2, std::min(spd.w-x, 32) * 4); } } RECT bbox; m_rts.Render(spd, 10000i64*(stss->start+stss->end)/2, 10000000.0/_ATPF, bbox); rtStart = (REFERENCE_TIME)((10000i64*stss->start - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)((10000i64*stss->end - m_rtStart) / m_dRateSeeking); } else { if ((size_t)m_nPosition >= m_rts.GetCount()) { return S_FALSE; } STSEntry& stse = m_rts[m_nPosition]; if (stse.start >= m_rtStop/10000) { return S_FALSE; } if (m_mt.majortype == MEDIATYPE_Subtitle && m_mt.subtype == MEDIASUBTYPE_UTF8) { CStringA str = WStrToUTF8(m_rts.GetStrW(m_nPosition, false)); memcpy((char*)pData, str, len = str.GetLength()); } else if (m_mt.majortype == MEDIATYPE_Subtitle && (m_mt.subtype == MEDIASUBTYPE_SSA || m_mt.subtype == MEDIASUBTYPE_ASS)) { CStringW line; line.Format(L"%d,%d,%s,%s,%d,%d,%d,%s,%s", stse.readorder, stse.layer, CStringW(stse.style), CStringW(stse.actor), stse.marginRect.left, stse.marginRect.right, (stse.marginRect.top+stse.marginRect.bottom)/2, CStringW(stse.effect), m_rts.GetStrW(m_nPosition, true)); CStringA str = WStrToUTF8(line); memcpy((char*)pData, str, len = str.GetLength()); } else if (m_mt.majortype == MEDIATYPE_Text && m_mt.subtype == MEDIASUBTYPE_NULL) { CStringA str = m_rts.GetStrA(m_nPosition, false); memcpy((char*)pData, str, len = str.GetLength()); } else { return S_FALSE; } rtStart = (REFERENCE_TIME)((10000i64*stse.start - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)((10000i64*stse.end - m_rtStart) / m_dRateSeeking); } pSample->SetTime(&rtStart, &rtStop); pSample->SetActualDataLength(len); m_nPosition++; } pSample->SetSyncPoint(TRUE); if (m_bDiscontinuity) { pSample->SetDiscontinuity(TRUE); m_bDiscontinuity = FALSE; } return S_OK; } HRESULT CSubtitleStream::GetMediaType(CMediaType* pmt) { return (static_cast<CSubtitleSource*>(m_pFilter))->GetMediaType(pmt); } HRESULT CSubtitleStream::CheckMediaType(const CMediaType* pmt) { CAutoLock lock(m_pFilter->pStateLock()); CMediaType mt; GetMediaType(&mt); if (mt.majortype == pmt->majortype && mt.subtype == pmt->subtype) { return NOERROR; } return E_FAIL; } STDMETHODIMP CSubtitleStream::Notify(IBaseFilter* pSender, Quality q) { return E_NOTIMPL; } // // CSubtitleSourceASCII // CSubtitleSourceASCII::CSubtitleSourceASCII(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceASCII::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Text); pmt->SetSubtype(&MEDIASUBTYPE_NULL); pmt->SetFormatType(&FORMAT_None); pmt->ResetFormatBuffer(); return NOERROR; } // // CSubtitleSourceUTF8 // CSubtitleSourceUTF8::CSubtitleSourceUTF8(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceUTF8::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Subtitle); pmt->SetSubtype(&MEDIASUBTYPE_UTF8); pmt->SetFormatType(&FORMAT_SubtitleInfo); SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO)); memset(psi, 0, pmt->FormatLength()); strcpy_s(psi->IsoLang, "eng"); return NOERROR; } // // CSubtitleSourceSSA // CSubtitleSourceSSA::CSubtitleSourceSSA(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceSSA::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Subtitle); pmt->SetSubtype(&MEDIASUBTYPE_SSA); pmt->SetFormatType(&FORMAT_SubtitleInfo); CSimpleTextSubtitle sts; sts.Open(CString(m_fn), DEFAULT_CHARSET); sts.RemoveAll(); CFile f; WCHAR path[MAX_PATH], fn[MAX_PATH]; if (!GetTempPath(MAX_PATH, path) || !GetTempFileName(path, L"mpc_sts", 0, fn)) { return E_FAIL; } _wremove(fn); wcscat_s(fn, L".ssa"); if (!sts.SaveAs(fn, Subtitle::SSA, -1, 0, CTextFile::UTF8, false) || !f.Open(fn, CFile::modeRead)) { return E_FAIL; } int len = (int)f.GetLength() - 3; f.Seek(3, CFile::begin); SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO) + len); memset(psi, 0, pmt->FormatLength()); psi->dwOffset = sizeof(SUBTITLEINFO); strcpy_s(psi->IsoLang, "eng"); f.Read(pmt->pbFormat + psi->dwOffset, len); f.Close(); _wremove(fn); return NOERROR; } // // CSubtitleSourceASS // CSubtitleSourceASS::CSubtitleSourceASS(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceASS::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Subtitle); pmt->SetSubtype(&MEDIASUBTYPE_ASS); pmt->SetFormatType(&FORMAT_SubtitleInfo); CSimpleTextSubtitle sts; sts.Open(CString(m_fn), DEFAULT_CHARSET); sts.RemoveAll(); CFile f; WCHAR path[MAX_PATH], fn[MAX_PATH]; if (!GetTempPath(MAX_PATH, path) || !GetTempFileName(path, L"mpc_sts", 0, fn)) { return E_FAIL; } _wremove(fn); wcscat_s(fn, L".ass"); if (!sts.SaveAs(fn, Subtitle::ASS, -1, CTextFile::UTF8) || !f.Open(fn, CFile::modeRead)) { return E_FAIL; } int len = (int)f.GetLength(); SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO) + len); memset(psi, 0, pmt->FormatLength()); psi->dwOffset = sizeof(SUBTITLEINFO); strcpy_s(psi->IsoLang, "eng"); f.Read(pmt->pbFormat + psi->dwOffset, len); f.Close(); _wremove(fn); return NOERROR; } // // CSubtitleSourceUSF // CSubtitleSourceUSF::CSubtitleSourceUSF(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceUSF::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Subtitle); pmt->SetSubtype(&MEDIASUBTYPE_USF); pmt->SetFormatType(&FORMAT_SubtitleInfo); SUBTITLEINFO* psi = (SUBTITLEINFO*)pmt->AllocFormatBuffer(sizeof(SUBTITLEINFO)); memset(psi, 0, pmt->FormatLength()); strcpy_s(psi->IsoLang, "eng"); // TODO: ... return NOERROR; } // // CSubtitleSourcePreview // CSubtitleSourcePreview::CSubtitleSourcePreview(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourcePreview::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Video); pmt->SetSubtype(&MEDIASUBTYPE_RGB32); pmt->SetFormatType(&FORMAT_VideoInfo); VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)pmt->AllocFormatBuffer(sizeof(VIDEOINFOHEADER)); memset(pvih, 0, pmt->FormatLength()); pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader); pvih->bmiHeader.biWidth = _WIDTH; pvih->bmiHeader.biHeight = _HEIGHT; pvih->bmiHeader.biBitCount = 32; pvih->bmiHeader.biCompression = BI_RGB; pvih->bmiHeader.biPlanes = 1; pvih->bmiHeader.biSizeImage = DIBSIZE(pvih->bmiHeader); return NOERROR; } // // CSubtitleSourceARGB // CSubtitleSourceARGB::CSubtitleSourceARGB(LPUNKNOWN lpunk, HRESULT* phr) : CSubtitleSource(lpunk, phr, __uuidof(this)) { } HRESULT CSubtitleSourceARGB::GetMediaType(CMediaType* pmt) { CAutoLock cAutoLock(pStateLock()); pmt->InitMediaType(); pmt->SetType(&MEDIATYPE_Video); pmt->SetSubtype(&MEDIASUBTYPE_ARGB32); pmt->SetFormatType(&FORMAT_VideoInfo); VIDEOINFOHEADER* pvih = (VIDEOINFOHEADER*)pmt->AllocFormatBuffer(sizeof(VIDEOINFOHEADER)); memset(pvih, 0, pmt->FormatLength()); pvih->bmiHeader.biSize = sizeof(pvih->bmiHeader); // TODO: read w,h,fps from a config file or registry pvih->bmiHeader.biWidth = _WIDTH; pvih->bmiHeader.biHeight = _HEIGHT; pvih->bmiHeader.biBitCount = 32; pvih->bmiHeader.biCompression = BI_RGB; pvih->bmiHeader.biPlanes = 1; pvih->bmiHeader.biSizeImage = pvih->bmiHeader.biWidth*abs(pvih->bmiHeader.biHeight)*pvih->bmiHeader.biBitCount>>3; return NOERROR; }
26.06625
147
0.714669
1aq
3d6b7d93ea70ca5f0d91a162cb8c03dc2179ee6c
1,496
cc
C++
src/Queue/lockFreeQueue.cc
josebrandao13/MDTs
923251280beebb10127c5216c2ef6d7789261e94
[ "MIT" ]
null
null
null
src/Queue/lockFreeQueue.cc
josebrandao13/MDTs
923251280beebb10127c5216c2ef6d7789261e94
[ "MIT" ]
null
null
null
src/Queue/lockFreeQueue.cc
josebrandao13/MDTs
923251280beebb10127c5216c2ef6d7789261e94
[ "MIT" ]
null
null
null
#include <boost/lockfree/queue.hpp> #include <boost/thread/thread.hpp> #include <thread> #include <iostream> #define LOOP 500000 #define BENCH_RUNS 5 using namespace std; boost::lockfree::queue<int> q{LOOP}; vector<int> NTHREADS; int poped; void lockFree(){ for (int i=0; i < LOOP; i++){ q.push(i); if(i%1000==0){ q.pop(poped); } } } void benchmark(void (*function)()){ using namespace std::chrono; for(int k = 0; k < NTHREADS.size(); k++){ std::list<double> times; for(int i = 0; i< BENCH_RUNS; i++){ steady_clock::time_point t1 = steady_clock::now(); boost::thread_group threads; for (int a=0; a < NTHREADS[k]; a++){ threads.create_thread(function); } threads.join_all(); steady_clock::time_point t2 = steady_clock::now(); duration<double> ti = duration_cast<duration<double>>(t2 - t1); times.push_back(ti.count()); } double sumTimes = 0; for(double t: times){ sumTimes += t; } double finalTime = sumTimes/times.size(); cout << fixed; cout << "Time: " << finalTime << endl << endl; cout << "THREADS NO: " << NTHREADS[k] << endl; cout << "Throughput: " << (int)(LOOP/finalTime) << endl; } } int main(int argc, char** argv){ for(int i=1; i<argc; i++){ NTHREADS.push_back(atoi(argv[i])); } cout << "***************** LOCK FREE *********************" << endl; benchmark(lockFree); }
22.666667
71
0.556818
josebrandao13
3d6dd30c1e48578bce39c83660ffea14e92d3371
3,227
cpp
C++
ordered_set.cpp
shiningflash/Advance-Data-Structure
87f1813c5bcfb2ad77b8f1f2d8f0259d3f87371a
[ "MIT" ]
3
2020-11-09T18:36:48.000Z
2020-12-31T03:51:08.000Z
ordered_set.cpp
shiningflash/data-structure
87f1813c5bcfb2ad77b8f1f2d8f0259d3f87371a
[ "MIT" ]
null
null
null
ordered_set.cpp
shiningflash/data-structure
87f1813c5bcfb2ad77b8f1f2d8f0259d3f87371a
[ "MIT" ]
3
2019-04-30T22:11:19.000Z
2020-04-11T18:34:27.000Z
/* +> Ordered set is a policy based data structure in g++ that keeps the unique elements in sorted order. It performs all the operations as performed by the set data structure in STL in log(n) complexity and performs two additional operations also in log(n) complexity. - order_of_key (k) : Number of items strictly smaller than k - find_by_order(k) : K-th element in a set (counting from zero) +> For implementing ordered_set and GNU C++ library contains other Policy based data structures we need to include: include <ext/pb_ds/assoc_container.hpp> include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; +> The ordered set implementation is: tree < int , null_type , less , rb_tree_tag , tree_order_statistics_node_update > Here, - int : It is the type of the data that we want to insert (KEY).It can be integer, float or pair of int etc - null_type : It is the mapped policy. It is null here to use it as a set - less : It is the basis for comparison of two functions - rb_tree_tag : type of tree used. It is generally Red black trees because it takes log(n) time for insertion and deletion - tree_order_statistics_node__update : It contains various operations for updating the node variants of a tree-based container Along with the previous operations of the set, it supports two main important operations ** find_by_order(k): It returns to an iterator to the kth element (counting from zero) in the set in O(logn) time. To find the first element k must be zero. Let us assume we have a set s : {1, 5, 6, 17, 88}, then : *(s.find_by_order(2)) : 3rd element in the set i.e. 6 *(s.find_by_order(4)) : 5th element in the set i.e. 88 ** order_of_key(k) : It returns to the number of items that are strictly smaller than our item k in O(logn) time. Let us assume we have a set s : {1, 5, 6, 17, 88}, then : s.order_of_key(6) : Count of elements strictly smaller than 6 is 2. s.order_of_key(25) : Count of elements strictly smaller than 25 is 4. ** count of elements between l and r can be found by: o_set.order_of_key(r+1) – o_set.order_of_key(l) ref: https://www.geeksforgeeks.org/ordered-set-gnu-c-pbds */ /* two fundamental operations INSERT(S,x): if x is not in S, insert x into S DELETE(S,x): if x is in S, delete x from S and the two type of queries K-TH(S) : return the k-th smallest element of S COUNT(S,x): return the number of elements of S smaller than x */ #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> int main() { //freopen("in", "r", stdin); int t, n; char ch; ordered_set s; for (cin >> t; t--; ) { cin >> ch >> n; if (ch == 'I') s.insert(n); else if (ch == 'D') s.erase(n); else if (ch == 'C') cout << s.order_of_key(n) << "\n"; else if (ch == 'K') { if (n > s.size()) cout << "invalid\n"; else cout << *s.find_by_order(n-1) << "\n"; } } return 0; } /* Input: 8 I -1 I -1 I 2 C 0 K 2 D -1 K 1 K 2 Output: 1 2 2 invalid ref: https://www.spoj.com/problems/ORDERSET */
30.158879
156
0.693214
shiningflash
3d6f50e094123507a09b9784d36d9a35c3bf0f29
2,157
cpp
C++
modules/OCULUS/external/oculusSDK/LibOVRKernel/Src/Kernel/OVR_Rand.cpp
Mithsen/Gallbladder
981cec68ca9e9af8613a6bf5a71048f86c16a070
[ "BSD-3-Clause" ]
3
2016-01-18T06:15:18.000Z
2016-05-23T22:21:16.000Z
modules/OCULUS/external/oculusSDK/LibOVRKernel/Src/Kernel/OVR_Rand.cpp
Mithsen/Gallbladder
981cec68ca9e9af8613a6bf5a71048f86c16a070
[ "BSD-3-Clause" ]
null
null
null
modules/OCULUS/external/oculusSDK/LibOVRKernel/Src/Kernel/OVR_Rand.cpp
Mithsen/Gallbladder
981cec68ca9e9af8613a6bf5a71048f86c16a070
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** Filename : OVR_Rand.cpp Content : Random number generator Created : Aug 28, 2014 Author : Chris Taylor Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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 "OVR_Rand.h" #include "OVR_Timer.h" namespace OVR { void RandomNumberGenerator::SeedRandom() { uint64_t seed = Timer::GetTicksNanos(); uint32_t x = (uint32_t)seed, y = (uint32_t)(seed >> 32); Seed(x, y); } void RandomNumberGenerator::Seed(uint32_t x, uint32_t y) { // Based on the mixing functions of MurmurHash3 static const uint64_t C1 = 0xff51afd7ed558ccdULL; static const uint64_t C2 = 0xc4ceb9fe1a85ec53ULL; x += y; y += x; uint64_t seed_x = 0x9368e53c2f6af274ULL ^ x; uint64_t seed_y = 0x586dcd208f7cd3fdULL ^ y; seed_x *= C1; seed_x ^= seed_x >> 33; seed_x *= C2; seed_x ^= seed_x >> 33; seed_y *= C1; seed_y ^= seed_y >> 33; seed_y *= C2; seed_y ^= seed_y >> 33; Rx = seed_x; Ry = seed_y; // Inlined Next(): Discard first output Rx = (uint64_t)0xfffd21a7 * (uint32_t)Rx + (uint32_t)(Rx >> 32); Ry = (uint64_t)0xfffd1361 * (uint32_t)Ry + (uint32_t)(Ry >> 32); // Throw away any saved RandN() state HaveRandN = false; Seeded = true; } } // namespace OVR
26.9625
85
0.634678
Mithsen
3d73f71afaf2e57b2d8224491cd80507a053becb
22,080
cpp
C++
src/fred2/campaigneditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
1
2020-07-14T07:29:18.000Z
2020-07-14T07:29:18.000Z
src/fred2/campaigneditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2019-01-01T22:35:56.000Z
2022-03-14T07:34:00.000Z
src/fred2/campaigneditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2021-03-07T11:40:42.000Z
2021-12-26T21:40:39.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ // CampaignEditorDlg.cpp : implementation file // #include <setjmp.h> #include "stdafx.h" #include "fred.h" #include "campaigneditordlg.h" #include "campaigntreeview.h" #include "campaigntreewnd.h" #include "management.h" #include "freddoc.h" #include "parselo.h" #include "missiongoals.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif int Cur_campaign_mission = -1; int Cur_campaign_link = -1; // determine the node number that would be allocated without actually allocating it yet. int campaign_sexp_tree::get_new_node_position() { int i; for (i=0; i<MAX_SEXP_TREE_SIZE; i++){ if (nodes[i].type == SEXPT_UNUSED){ return i; } } return -1; } // construct tree nodes for an sexp, adding them to the list and returning first node int campaign_sexp_tree::load_sub_tree(int index) { int cur; if (index < 0) { cur = allocate_node(-1); set_node(cur, (SEXPT_OPERATOR | SEXPT_VALID), "do-nothing"); // setup a default tree if none return cur; } // assumption: first token is an operator. I require this because it would cause problems // with child/parent relations otherwise, and it should be this way anyway, since the // return type of the whole sexp is boolean, and only operators can satisfy this. Assert(Sexp_nodes[index].subtype == SEXP_ATOM_OPERATOR); cur = get_new_node_position(); load_branch(index, -1); return cur; } ///////////////////////////////////////////////////////////////////////////// // campaign_editor IMPLEMENT_DYNCREATE(campaign_editor, CFormView) campaign_editor *Campaign_tree_formp; campaign_editor::campaign_editor() : CFormView(campaign_editor::IDD) { //{{AFX_DATA_INIT(campaign_editor) m_name = _T(""); m_type = -1; m_num_players = _T(""); m_desc = _T(""); m_loop_desc = _T(""); m_loop_brief_anim = _T(""); m_loop_brief_sound = _T(""); //}}AFX_DATA_INIT m_tree.m_mode = MODE_CAMPAIGN; m_num_links = 0; m_tree.link_modified(&Campaign_modified); m_last_mission = -1; } campaign_editor::~campaign_editor() { } void campaign_editor::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); //{{AFX_DATA_MAP(campaign_editor) DDX_Control(pDX, IDC_SEXP_TREE, m_tree); DDX_Control(pDX, IDC_FILELIST, m_filelist); DDX_Text(pDX, IDC_NAME, m_name); DDX_CBIndex(pDX, IDC_CAMPAIGN_TYPE, m_type); DDX_Text(pDX, IDC_NUM_PLAYERS, m_num_players); DDX_Text(pDX, IDC_DESC2, m_desc); DDX_Text(pDX, IDC_MISSISON_LOOP_DESC, m_loop_desc); DDX_Text(pDX, IDC_LOOP_BRIEF_ANIM, m_loop_brief_anim); DDX_Text(pDX, IDC_LOOP_BRIEF_SOUND, m_loop_brief_sound); //}}AFX_DATA_MAP DDV_MaxChars(pDX, m_desc, MISSION_DESC_LENGTH - 1); DDV_MaxChars(pDX, m_loop_desc, MISSION_DESC_LENGTH - 1); } BEGIN_MESSAGE_MAP(campaign_editor, CFormView) //{{AFX_MSG_MAP(campaign_editor) ON_BN_CLICKED(ID_LOAD, OnLoad) ON_BN_CLICKED(IDC_ALIGN, OnAlign) ON_BN_CLICKED(ID_CPGN_CLOSE, OnCpgnClose) ON_NOTIFY(NM_RCLICK, IDC_SEXP_TREE, OnRclickTree) ON_NOTIFY(TVN_BEGINLABELEDIT, IDC_SEXP_TREE, OnBeginlabeleditSexpTree) ON_NOTIFY(TVN_ENDLABELEDIT, IDC_SEXP_TREE, OnEndlabeleditSexpTree) ON_NOTIFY(TVN_SELCHANGED, IDC_SEXP_TREE, OnSelchangedSexpTree) ON_BN_CLICKED(IDC_MOVE_UP, OnMoveUp) ON_BN_CLICKED(IDC_MOVE_DOWN, OnMoveDown) ON_COMMAND(ID_END_EDIT, OnEndEdit) ON_EN_CHANGE(IDC_BRIEFING_CUTSCENE, OnChangeBriefingCutscene) ON_CBN_SELCHANGE(IDC_CAMPAIGN_TYPE, OnSelchangeType) ON_BN_CLICKED(IDC_GALATEA, OnGalatea) ON_BN_CLICKED(IDC_BASTION, OnBastion) ON_BN_CLICKED(IDC_TOGGLE_LOOP, OnToggleLoop) ON_BN_CLICKED(IDC_LOOP_BRIEF_BROWSE, OnBrowseLoopAni) ON_BN_CLICKED(IDC_LOOP_BRIEF_SOUND_BROWSE, OnBrowseLoopSound) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // campaign_editor diagnostics #ifdef _DEBUG void campaign_editor::AssertValid() const { CFormView::AssertValid(); } void campaign_editor::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // campaign_editor message handlers void campaign_editor::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { UpdateData(FALSE); } void campaign_editor::OnLoad() { char buf[512]; if (Cur_campaign_mission < 0){ return; } if (Campaign_modified){ if (Campaign_wnd->save_modified()){ return; } } GetCurrentDirectory(512, buf); strcat(buf, "\\"); strcat(buf, Campaign.missions[Cur_campaign_mission].name); FREDDoc_ptr->SetPathName(buf); Campaign_wnd->DestroyWindow(); // if (FREDDoc_ptr->OnOpenDocument(Campaign.missions[Cur_campaign_mission].name)) { // Bypass_clear_mission = 1; // Campaign_wnd->DestroyWindow(); // // } else { // MessageBox("Failed to load mission!", "Error"); // } } BOOL campaign_editor::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext) { int i; BOOL r; CComboBox *box; r = CFormView::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext); if (r) { box = (CComboBox *) GetDlgItem(IDC_CAMPAIGN_TYPE); box->ResetContent(); for (i=0; i<MAX_CAMPAIGN_TYPES; i++){ box->AddString(campaign_types[i]); } } return r; } void campaign_editor::load_campaign() { Cur_campaign_mission = Cur_campaign_link = -1; load_tree(0); if (!strlen(Campaign.filename)) strcpy(Campaign.filename, BUILTIN_CAMPAIGN); if (mission_campaign_load(Campaign.filename, 0)) { MessageBox("Couldn't open Campaign file!", "Error"); Campaign_wnd->OnCpgnFileNew(); return; } Campaign_modified = 0; Campaign_tree_viewp->construct_tree(); initialize(); } void campaign_editor::OnAlign() { Campaign_tree_viewp->sort_elements(); Campaign_tree_viewp->realign_tree(); Campaign_tree_viewp->Invalidate(); } void campaign_editor::initialize( int init_files ) { Cur_campaign_mission = Cur_campaign_link = -1; m_tree.setup((CEdit *) GetDlgItem(IDC_HELP_BOX)); load_tree(0); Campaign_tree_viewp->initialize(); // only initialize the file dialog box when the parameter says to. This should // only happen when a campaign type changes if ( init_files ){ m_filelist.initialize(); } m_name = Campaign.name; m_type = Campaign.type; m_num_players.Format("%d", Campaign.num_players); if (Campaign.desc) { m_desc = convert_multiline_string(Campaign.desc); } else { m_desc = _T(""); } m_loop_desc = _T(""); m_loop_brief_anim = _T(""); m_loop_brief_sound = _T(""); // single player should hide the two dialog items about number of players allowed if ( m_type == CAMPAIGN_TYPE_SINGLE ) { GetDlgItem(IDC_NUM_PLAYERS)->ShowWindow( SW_HIDE ); GetDlgItem(IDC_PLAYERS_LABEL)->ShowWindow( SW_HIDE ); } else { GetDlgItem(IDC_NUM_PLAYERS)->ShowWindow( SW_SHOW ); GetDlgItem(IDC_PLAYERS_LABEL)->ShowWindow( SW_SHOW ); } UpdateData(FALSE); } void campaign_editor::mission_selected(int num) { CEdit *bc_dialog; bc_dialog = (CEdit *) GetDlgItem(IDC_BRIEFING_CUTSCENE); // clear out the text for the briefing cutscene, and put in new text if specified bc_dialog->SetWindowText(""); if ( strlen(Campaign.missions[num].briefing_cutscene) ) bc_dialog->SetWindowText(Campaign.missions[num].briefing_cutscene); if (Campaign.missions[num].flags & CMISSION_FLAG_BASTION) { ((CButton *) GetDlgItem(IDC_GALATEA)) -> SetCheck(0); ((CButton *) GetDlgItem(IDC_BASTION)) -> SetCheck(1); } else { ((CButton *) GetDlgItem(IDC_GALATEA)) -> SetCheck(1); ((CButton *) GetDlgItem(IDC_BASTION)) -> SetCheck(0); } } void campaign_editor::update() { char buf[MISSION_DESC_LENGTH]; // get data from dlog box UpdateData(TRUE); // update campaign name string_copy(Campaign.name, m_name, NAME_LENGTH); Campaign.type = m_type; // update campaign desc deconvert_multiline_string(buf, m_desc, MISSION_DESC_LENGTH); if (Campaign.desc) { free(Campaign.desc); } Campaign.desc = NULL; if (strlen(buf)) { Campaign.desc = strdup(buf); } // maybe update mission loop text save_loop_desc_window(); // set the number of players in a multiplayer mission equal to the number of players in the first mission if ( Campaign.type != CAMPAIGN_TYPE_SINGLE ) { if ( Campaign.num_missions == 0 ) { Campaign.num_players = 0; } else { mission a_mission; get_mission_info(Campaign.missions[0].name, &a_mission); Campaign.num_players = a_mission.num_players; } } } void campaign_editor::OnCpgnClose() { Campaign_wnd->OnClose(); } void campaign_editor::load_tree(int save_first) { char text[80]; int i; HTREEITEM h; if (save_first) save_tree(); m_tree.clear_tree(); m_tree.DeleteAllItems(); m_num_links = 0; UpdateData(TRUE); update_loop_desc_window(); m_last_mission = Cur_campaign_mission; if (Cur_campaign_mission < 0) { GetDlgItem(IDC_SEXP_TREE)->EnableWindow(FALSE); GetDlgItem(IDC_BRIEFING_CUTSCENE)->EnableWindow(FALSE); return; } GetDlgItem(IDC_SEXP_TREE)->EnableWindow(TRUE); GetDlgItem(IDC_BRIEFING_CUTSCENE)->EnableWindow(TRUE); GetDlgItem(IDC_MISSISON_LOOP_DESC)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_ANIM)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_SOUND)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_BROWSE)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_SOUND_BROWSE)->EnableWindow(FALSE); for (i=0; i<Total_links; i++) { if (Links[i].from == Cur_campaign_mission) { Links[i].node = m_tree.load_sub_tree(Links[i].sexp); m_num_links++; if (Links[i].from == Links[i].to) { strcpy(text, "Repeat mission"); } else if ( (Links[i].to == -1) && (Links[i].from != -1) ) { strcpy(text, "End of Campaign"); } else { sprintf(text, "Branch to %s", Campaign.missions[Links[i].to].name); } // insert item into tree int image, sel_image; if (Links[i].mission_loop) { image = BITMAP_BLUE_DOT; sel_image = BITMAP_GREEN_DOT; } else { image = BITMAP_BLACK_DOT; sel_image = BITMAP_RED_DOT; } h = m_tree.insert(text, image, sel_image); m_tree.SetItemData(h, Links[i].node); m_tree.add_sub_tree(Links[i].node, h); } } } void campaign_editor::OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult) { m_tree.right_clicked(MODE_CAMPAIGN); *pResult = 0; } void campaign_editor::OnBeginlabeleditSexpTree(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; if (m_tree.edit_label(pTVDispInfo->item.hItem) == 1) { *pResult = 0; Campaign_modified = 1; } else { *pResult = 1; } } void campaign_editor::OnEndlabeleditSexpTree(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; *pResult = m_tree.end_label_edit(pTVDispInfo->item.hItem, pTVDispInfo->item.pszText); } int campaign_editor::handler(int code, int node, char *str) { int i; switch (code) { case ROOT_DELETED: for (i=0; i<Total_links; i++){ if ((Links[i].from == Cur_campaign_mission) && (Links[i].node == node)){ break; } } Campaign_tree_viewp->delete_link(i); m_num_links--; return node; default: Int3(); } return -1; } void campaign_editor::save_tree(int clear) { int i; if (m_last_mission < 0){ return; // nothing to save } for (i=0; i<Total_links; i++){ if (Links[i].from == m_last_mission) { sexp_unmark_persistent(Links[i].sexp); free_sexp2(Links[i].sexp); Links[i].sexp = m_tree.save_tree(Links[i].node); sexp_mark_persistent(Links[i].sexp); } } if (clear){ m_last_mission = -1; } } void campaign_editor::OnSelchangedSexpTree(NMHDR* pNMHDR, LRESULT* pResult) { int i, node; HTREEITEM h, h2; // get handle of selected item NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; h = pNMTreeView->itemNew.hItem; Assert(h); // update help on sexp m_tree.update_help(h); // get handle of parent while ((h2 = m_tree.GetParentItem(h))>0){ h = h2; } // get identifier of parent node = m_tree.GetItemData(h); for (i=0; i<Total_links; i++){ if ((Links[i].from == Cur_campaign_mission) && (Links[i].node == node)){ break; } } if (i == Total_links) { Cur_campaign_link = -1; return; } // update mission loop text UpdateData(TRUE); save_loop_desc_window(); Cur_campaign_link = i; update_loop_desc_window(); Campaign_tree_viewp->Invalidate(); *pResult = 0; } void campaign_editor::OnMoveUp() { int i, last = -1; campaign_tree_link temp; HTREEITEM h1, h2; if (Cur_campaign_link >= 0) { save_tree(); for (i=0; i<Total_links; i++){ if (Links[i].from == Cur_campaign_mission) { if (i == Cur_campaign_link){ break; } last = i; } } if ((last != -1) && (i < Total_links)) { h1 = m_tree.GetParentItem(m_tree.handle(Links[i].node)); h2 = m_tree.GetParentItem(m_tree.handle(Links[last].node)); m_tree.swap_roots(h1, h2); m_tree.SelectItem(m_tree.GetParentItem(m_tree.handle(Links[i].node))); temp = Links[last]; Links[last] = Links[i]; Links[i] = temp; Cur_campaign_link = last; } } GetDlgItem(IDC_SEXP_TREE)->SetFocus(); } void campaign_editor::OnMoveDown() { int i, j; campaign_tree_link temp; HTREEITEM h1, h2; if (Cur_campaign_link >= 0) { save_tree(); for (i=0; i<Total_links; i++) if (Links[i].from == Cur_campaign_mission) if (i == Cur_campaign_link) break; for (j=i+1; j<Total_links; j++) if (Links[j].from == Cur_campaign_mission) break; if (j < Total_links) { h1 = m_tree.GetParentItem(m_tree.handle(Links[i].node)); h2 = m_tree.GetParentItem(m_tree.handle(Links[j].node)); m_tree.swap_roots(h1, h2); m_tree.SelectItem(m_tree.GetParentItem(m_tree.handle(Links[i].node))); temp = Links[j]; Links[j] = Links[i]; Links[i] = temp; Cur_campaign_link = j; } } GetDlgItem(IDC_SEXP_TREE)->SetFocus(); } void campaign_editor::swap_handler(int node1, int node2) { int index1, index2; campaign_tree_link temp; for (index1=0; index1<Total_links; index1++){ if ((Links[index1].from == Cur_campaign_mission) && (Links[index1].node == node1)){ break; } } Assert(index1 < Total_links); for (index2=0; index2<Total_links; index2++){ if ((Links[index2].from == Cur_campaign_mission) && (Links[index2].node == node2)){ break; } } Assert(index2 < Total_links); temp = Links[index1]; // Links[index1] = Links[index2]; while (index1 < index2) { Links[index1] = Links[index1 + 1]; index1++; } while (index1 > index2 + 1) { Links[index1] = Links[index1 - 1]; index1--; } // update Cur_campaign_link Cur_campaign_link = index1; Links[index1] = temp; } void campaign_editor::insert_handler(int old, int node) { int i; for (i=0; i<Total_links; i++){ if ((Links[i].from == Cur_campaign_mission) && (Links[i].node == old)){ break; } } Assert(i < Total_links); Links[i].node = node; return; } void campaign_editor::OnEndEdit() { HWND h; CWnd *w; w = GetFocus(); if (w) { h = w->m_hWnd; GetDlgItem(IDC_SEXP_TREE)->SetFocus(); ::SetFocus(h); } } void campaign_editor::OnChangeBriefingCutscene() { CEdit *bc_dialog; bc_dialog = (CEdit *) GetDlgItem(IDC_BRIEFING_CUTSCENE); // maybe save off the current cutscene names. if ( Cur_campaign_mission != -1 ) { // see if the contents of the edit box have changed. Luckily, this returns 0 when the edit box is // cleared. if ( bc_dialog->GetModify() ) { bc_dialog->GetWindowText( Campaign.missions[Cur_campaign_mission].briefing_cutscene, NAME_LENGTH ); Campaign_modified = 1; } } } // what to do when changing campaign type void campaign_editor::OnSelchangeType() { // if campaign type is single player, then disable the multiplayer items update(); initialize(); Campaign_modified = 1; } void campaign_editor::OnGalatea() { if (Cur_campaign_mission >= 0){ Campaign.missions[Cur_campaign_mission].flags &= ~CMISSION_FLAG_BASTION; } } void campaign_editor::OnBastion() { if (Cur_campaign_mission >= 0){ Campaign.missions[Cur_campaign_mission].flags |= CMISSION_FLAG_BASTION; } } // update the loop mission text void campaign_editor::save_loop_desc_window() { char buffer[MISSION_DESC_LENGTH]; // update only if active link and there is a mission has mission loop if ( (Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop ) { deconvert_multiline_string(buffer, m_loop_desc, MISSION_DESC_LENGTH); if (Links[Cur_campaign_link].mission_loop_txt) { free(Links[Cur_campaign_link].mission_loop_txt); } if (Links[Cur_campaign_link].mission_loop_brief_anim) { free(Links[Cur_campaign_link].mission_loop_brief_anim); } if (Links[Cur_campaign_link].mission_loop_brief_sound) { free(Links[Cur_campaign_link].mission_loop_brief_sound); } if (strlen(buffer)) { Links[Cur_campaign_link].mission_loop_txt = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_txt = NULL; } deconvert_multiline_string(buffer, m_loop_brief_anim, MAX_FILENAME_LEN); if(strlen(buffer)){ Links[Cur_campaign_link].mission_loop_brief_anim = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_brief_anim = NULL; } deconvert_multiline_string(buffer, m_loop_brief_sound, MAX_FILENAME_LEN); if(strlen(buffer)){ Links[Cur_campaign_link].mission_loop_brief_sound = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_brief_sound = NULL; } } } void campaign_editor::update_loop_desc_window() { bool enable_loop_desc_window; enable_loop_desc_window = false; if ((Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop) { enable_loop_desc_window = true; } // maybe enable description window GetDlgItem(IDC_MISSISON_LOOP_DESC)->EnableWindow(enable_loop_desc_window); GetDlgItem(IDC_LOOP_BRIEF_ANIM)->EnableWindow(enable_loop_desc_window); GetDlgItem(IDC_LOOP_BRIEF_SOUND)->EnableWindow(enable_loop_desc_window); GetDlgItem(IDC_LOOP_BRIEF_BROWSE)->EnableWindow(enable_loop_desc_window); GetDlgItem(IDC_LOOP_BRIEF_SOUND_BROWSE)->EnableWindow(enable_loop_desc_window); // set new text if ((Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop_txt && enable_loop_desc_window) { m_loop_desc = convert_multiline_string(Links[Cur_campaign_link].mission_loop_txt); } else { m_loop_desc = _T(""); } // set new text if ((Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop_brief_anim && enable_loop_desc_window) { m_loop_brief_anim = convert_multiline_string(Links[Cur_campaign_link].mission_loop_brief_anim); } else { m_loop_brief_anim = _T(""); } // set new text if ((Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop_brief_sound && enable_loop_desc_window) { m_loop_brief_sound = convert_multiline_string(Links[Cur_campaign_link].mission_loop_brief_sound); } else { m_loop_brief_sound = _T(""); } // reset text UpdateData(FALSE); } void campaign_editor::OnToggleLoop() { // check if branch selected if (Cur_campaign_link == -1) { return; } // store mission looop text UpdateData(TRUE); if ( (Cur_campaign_link >= 0) && Links[Cur_campaign_link].mission_loop ) { if (Links[Cur_campaign_link].mission_loop_txt) { free(Links[Cur_campaign_link].mission_loop_txt); } if (Links[Cur_campaign_link].mission_loop_brief_anim) { free(Links[Cur_campaign_link].mission_loop_brief_anim); } if (Links[Cur_campaign_link].mission_loop_brief_sound) { free(Links[Cur_campaign_link].mission_loop_brief_sound); } char buffer[MISSION_DESC_LENGTH]; deconvert_multiline_string(buffer, m_loop_desc, MISSION_DESC_LENGTH); if (m_loop_desc && strlen(buffer)) { Links[Cur_campaign_link].mission_loop_txt = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_txt = NULL; } deconvert_multiline_string(buffer, m_loop_brief_anim, MISSION_DESC_LENGTH); if (m_loop_brief_anim && strlen(buffer)) { Links[Cur_campaign_link].mission_loop_brief_anim = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_brief_anim = NULL; } deconvert_multiline_string(buffer, m_loop_brief_sound, MISSION_DESC_LENGTH); if (m_loop_brief_sound && strlen(buffer)) { Links[Cur_campaign_link].mission_loop_brief_sound = strdup(buffer); } else { Links[Cur_campaign_link].mission_loop_brief_sound = NULL; } } // toggle to mission_loop setting Links[Cur_campaign_link].mission_loop = !Links[Cur_campaign_link].mission_loop; // reset loop desc window (gray if inactive) update_loop_desc_window(); // set root icon int bitmap1, bitmap2; if (Links[Cur_campaign_link].mission_loop) { bitmap2 = BITMAP_GREEN_DOT; bitmap1 = BITMAP_BLUE_DOT; } else { bitmap1 = BITMAP_BLACK_DOT; bitmap2 = BITMAP_RED_DOT; } // Search for item and update bitmap HTREEITEM h = m_tree.GetRootItem(); while (h) { if ((int) m_tree.GetItemData(h) == Links[Cur_campaign_link].node) { m_tree.SetItemImage(h, bitmap1, bitmap2); break; } h = m_tree.GetNextSiblingItem(h); } // set to redraw Campaign_tree_viewp->Invalidate(); } void campaign_editor::OnBrowseLoopAni() { int pushed_dir; UpdateData(TRUE); // switch directories pushed_dir = cfile_push_chdir(CF_TYPE_INTERFACE); CFileDialog dlg(TRUE, "ani", NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, "Ani Files (*.ani)|*.ani"); if (dlg.DoModal() == IDOK) { m_loop_brief_anim = dlg.GetFileName(); UpdateData(FALSE); } // move back to the proper directory if (!pushed_dir){ cfile_pop_dir(); } } void campaign_editor::OnBrowseLoopSound() { int pushed_dir; UpdateData(TRUE); // switch directories pushed_dir = cfile_push_chdir(CF_TYPE_VOICE_CMD_BRIEF); CFileDialog dlg(TRUE, "wav", NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, "Wave Files (*.wav)|*.wav||"); if (dlg.DoModal() == IDOK) { m_loop_brief_sound = dlg.GetFileName(); UpdateData(FALSE); } // move back to the proper directory if (!pushed_dir){ cfile_pop_dir(); } }
24.949153
163
0.71721
ptitSeb
3d75c6be53f8faf936c05a7ea8f4ebbaa3cf55d7
10,769
hpp
C++
rapi_core/include/core/port.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
rapi_core/include/core/port.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
rapi_core/include/core/port.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cassert> #include <condition_variable> #include <deque> #include <functional> #include <limits> #include <map> #include <memory> #include <mutex> #include <iostream> #include "adstlog_cxx/adstlog.hpp" #include "adstutil_cxx/compiler_diagnostics.hpp" #include "core/impl/async_call_back_vector.hpp" #include "core/impl/common.hpp" #include "core/network.hpp" namespace adst::ep::test_engine::core { class Actor; /** * Used by an actor to represent an incoming entity. * * Listen on the port registers the actor in the network with the given event. * * Handles event callback dispatching when an event is received by an actor from a network. */ class Port { public: /** * ctor. * * A port is always owned by an actor. * * Port schedules itself on an actor when there is a command or event to dispatch. * * The actor schedule function makes sure that the actor only exists once in the dispatching * queue of the priority. * * @param actor Actor which ownes this port. * @param network The network this port is connected to. */ explicit Port(Actor& actor, Network& network); ~Port() { std::lock_guard<std::mutex> guard{callbacksMutex_}; callbacks_.clear(); } Port() = delete; Port(const Port&) = delete; Port(Port&&) = delete; Port& operator=(Port&&) = delete; Port& operator=(const Port&) = delete; /** * Creates unique handle for each listen registration. * * @return A unique handle. */ CallBackHandle newHandle() { std::lock_guard<std::mutex> guard{eventMutex_}; auto handle = ++handleCounter_; return handle; } /** * Used by the actor to register a callback to a given port (network). * * @tparam Event The event type used for callback (and for registration). * @param callback The callback to be called when a publish happens on a network. * @return Unique ID to identify the callback during unlisten. */ template <typename Event> CallBackHandle listen(std::function<void(const Event&)> callback) { static_assert(impl::validateEvent<Event>(), "Invalid event"); auto handle = newHandle(); listen<Event>(handle, std::move(callback)); return handle; } /** * Listen can be changed to a different function by providing the unique id and a new callback. * * @tparam Event the event type used for dispatch. * @param handle Unique handle of the initial listen. * @param callback The callback to register under for handle. */ template <typename Event> void listen(const CallBackHandle handle, std::function<void(const Event&)> callback); /** * Removes all callback from all event type with a given handle. * * @param handle Unique handle of the initial listen. */ void unlistenAll(const CallBackHandle handle) { std::lock_guard<std::mutex> unListenCmdQueueGuard{eventMutex_}; commandsQueue_.emplace_back([this, handle]() { std::lock_guard<std::mutex> lambdaCallbacksGuard{callbacksMutex_}; for (auto& element : callbacks_) { element.second->remove(handle); } }); } /** * Removes callback from the listen container. * * @tparam Event Type of the event used in the callback. * @param handle Unique id (from the listen call). */ template <typename Event> void unlisten(CallBackHandle handle); /** * Called by the the Actor when it has a message to be dispatched. * * @tparam Event The type of the message. * @param event A unique_ptr to Event/Message. */ template <typename Event> void schedule(Event event); // ToDo type it to unique ptr. /** * Allows direct message dispatch to self. Not used for now. * * @tparam Event The event type to dispatch. * @param event A unique_ptr to Event/Message. */ template <typename Event> void notify(const Event& event) { schedule(event); consume(1); } /** * Consumes all commands and event from the queue which was pushed by schedule to the port. * * @param max might be that not all event needs to be dispatched so a maximum number of event to dispatch * @return the number of event has been dispatched. */ int consume(int max = std::numeric_limits<int>::max()); /** * The number of events in the queue (waiting to be dispatched). * * @return size of the event queue */ std::size_t getQueueEventCount() const { std::lock_guard<std::mutex> guard{eventMutex_}; return eventQueue_.size(); } private: /** * Stores the AsyncCallBackVector by base class CallbackVector event is hidden. */ using CallBackVector = std::unique_ptr<impl::CallbackVector>; /** * Mapping of type_id and CallBackVector is used at runtime to get back the callbacks for a * specific event type. */ using TypeIdToCallBackVector = std::map<impl::type_id_t, CallBackVector>; /** * Helper to process the CommandQueue and return the event queue size as a single operation * used in a while loop during consume * * Since the logic is first process all Commands (CallBack manipulation) then process the * events. * * @return Size of the event queue. */ std::size_t processCommandsAndGetQueuedEventsCount(); /** * If Port has either Command or Message to dispatch it schedules itself on the Actor. * * All prot activity is processed in actor context. */ void scheduleOnOwner(); // must be called from locked queue mutex content; ToDo RSZRSZ Add enforcement. CallBackHandle handleCounter_ = 0; /// used as a counter to generate unique callback handles TypeIdToCallBackVector callbacks_ = {}; /// the store for the callbacks registered for an event mutable std::mutex callbacksMutex_; /// guard for the command queue mutable std::mutex eventMutex_; /// quard for the event queue /** * Queue stores all events for dispatching */ std::deque<std::function<void()>> eventQueue_; /** * Queue stores all commands for dispatching */ std::deque<std::function<void()>> commandsQueue_; Actor& owner_; // it is a reference because ports are owned by actor and port schedules itself on an actor. Network& network_; // it is now a reference it probably ones dynamic connections are allowed must change to some /** * A state has to be maintained that the port is already in the actors queue. If it is there is * no need to add to it since it is already waiting for scheduling. */ bool scheduled_ = false; ADSTLOG_DEF_ACTOR_TRACE_MODULES(); }; } // namespace adst::ep::test_engine::core #include "core/actor.hpp" namespace adst::ep::test_engine::core { template <typename Event> void Port::listen(const CallBackHandle handle, std::function<void(const Event&)> callback) { static_assert(impl::validateEvent<Event>(), "Invalid event"); std::lock_guard<std::mutex> listenCmdQueueGuard{eventMutex_}; commandsQueue_.push_back([this, handle, callback = std::move(callback)]() { // it is not shadowing since the lambda is not executed in the listen call context std::lock_guard<std::mutex> lambdaCallbacksGuard{callbacksMutex_}; using Vector = impl::AsyncCallbackVector<Event>; // GCOVR_EXCL_START assert(callback && "callback should be valid"); // Check for valid object // GCOVR_EXCL_STOP auto& vector = callbacks_[impl::type_id<Event>()]; // GCOVR_EXCL_START if (vector == nullptr) { // GCOVR_EXCL_STOP vector.reset(new Vector{}); network_.listen<Event>([this](const std::shared_ptr<Event> event) { schedule(event); }); } // assert(dynamic_cast<Vector*>(vector.get())); // ToDo RSZRSZ Create ifdef for RTTI enabled ... auto callbacks = static_cast<Vector*>(vector.get()); LOG_C_D("Port::listen:{%s}", impl::getTypeName<Event>().c_str()); callbacks->add(handle, callback); }); scheduleOnOwner(); } template <typename Event> void Port::schedule(Event event) { using EventT = typename std::remove_reference<decltype(*Event())>::type; static_assert(impl::validateEvent<EventT>(), "Invalid event"); std::shared_ptr<EventT> shareableEvent = std::move(event); std::lock_guard<std::mutex> scheduleCmdQueueGuard{eventMutex_}; LOG_C_D("Port::schedule, dispatch:{%s}", impl::getTypeName<EventT>().c_str()); eventQueue_.push_back([this, event = std::move(shareableEvent)]() { std::lock_guard<std::mutex> lambdaCallbacksGuard{callbacksMutex_}; using Vector = impl::AsyncCallbackVector<EventT>; auto found = callbacks_.find(impl::type_id<EventT>()); LOG_C_D("Port::schedule, dispatch:{%s}", impl::getTypeName<EventT>().c_str()); // GCOVR_EXCL_START if (found == callbacks_.end()) { // GCOVR_EXCL_STOP LOG_C_D("Port::schedule, no listener:{%s}", impl::getTypeName<EventT>().c_str()); return; // no such notifications } std::unique_ptr<impl::CallbackVector>& vector = found->second; // assert(dynamic_cast<Vector*>(vector.get())); auto callbacks = static_cast<Vector*>(vector.get()); LOG_C_D("Port::schedule, dispatch:{%s}, callbacks.size=%d", impl::getTypeName<EventT>().c_str(), callbacks->container_.size()); for (const auto& element : callbacks->container_) { LOG_CH_D(MSG_RX, "%s", impl::getTypeName<EventT>().c_str()); element.second(*event); } }); scheduleOnOwner(); } template <typename Event> void Port::unlisten(const CallBackHandle handle) { static_assert(impl::validateEvent<Event>(), "Invalid event"); std::lock_guard<std::mutex> unListenCmdQueueGuard{eventMutex_}; commandsQueue_.push_back([this, handle]() { std::lock_guard<std::mutex> lambdaCallbacksGuard{callbacksMutex_}; auto found = callbacks_.find(impl::type_id<Event>()); if (found != callbacks_.end()) { LOG_C_D("Port::unlisten:{%s}", impl::getTypeName<Event>().c_str()); found->second->remove(handle); // ToDo RSZRSZ unlisten from Network. } }); scheduleOnOwner(); } } // namespace adst::ep::test_engine::core
34.73871
116
0.642957
csitarichie
3d7a945d5c2782cee1353075fa0211fbc70be92d
3,371
cpp
C++
2JCIE-EV01/OPT3001DNP.cpp
takjn/GRMOmronTest
26478958be0c623ac8c1cbc9bbfd607f7c9bf245
[ "MIT" ]
null
null
null
2JCIE-EV01/OPT3001DNP.cpp
takjn/GRMOmronTest
26478958be0c623ac8c1cbc9bbfd607f7c9bf245
[ "MIT" ]
null
null
null
2JCIE-EV01/OPT3001DNP.cpp
takjn/GRMOmronTest
26478958be0c623ac8c1cbc9bbfd607f7c9bf245
[ "MIT" ]
1
2020-02-14T06:49:41.000Z
2020-02-14T06:49:41.000Z
// SPDX-License-Identifier: MIT /* * MIT License * Copyright (c) 2019, 2018 - present OMRON Corporation * Copyright (c) 2019 Renesas Electronics Corporation * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "OPT3001DNP.h" #define OPT3001_ADDR (0x45 << 1) #define OPT3001_REG_RESULT 0x00 #define OPT3001_REG_CONFIG 0x01 #define OPT3001_REG_LOLIMIT 0x02 #define OPT3001_REG_HILIMIT 0x03 #define OPT3001_REG_MANUFACTUREID 0x7E #define OPT3001_DEVICEID 0x7F #define OPT3001_CMD_CONFIG_MSB 0xC6 #define OPT3001_CMD_CONFIG_LSB 0x10 #define conv8s_u16_be(b, n) \ (uint16_t)(((uint16_t)b[n] << 8) | (uint16_t)b[n + 1]) // OPT3001DNP implementation OPT3001DNP::OPT3001DNP(PinName sda, PinName scl, int hz) : mI2c_(sda, scl) { mAddr = OPT3001_ADDR; mI2c_.frequency(hz); } bool OPT3001DNP::setup(void) { int ret; uint8_t wk_buf[3]; wk_buf[0] = OPT3001_REG_CONFIG; wk_buf[1] = OPT3001_CMD_CONFIG_MSB; wk_buf[2] = OPT3001_CMD_CONFIG_LSB; ret = mI2c_.write(mAddr, (char *)wk_buf, 3); if (ret != 0) { return false; } return true; } bool OPT3001DNP::read(uint32_t* light) { int ret; uint8_t rbuf[2]; uint16_t raw_data; ret = read_reg(OPT3001_REG_CONFIG, rbuf, sizeof(rbuf)); if (ret != 0) { return false; } if ((rbuf[1] & 0x80) == 0) { return false; // sensor is working... } ret = read_reg(OPT3001_REG_RESULT, rbuf, sizeof(rbuf)); if (ret != 0) { return false; } raw_data = conv8s_u16_be(rbuf, 0); if (light != NULL) { *light = convert_lux_value_x100(raw_data); } return true; } uint32_t OPT3001DNP::convert_lux_value_x100(uint16_t value_raw) { uint32_t value_converted; uint32_t lsb_size_x100; uint32_t data; // Convert the value to centi-percent RH lsb_size_x100 = 1 << ((value_raw >> 12) & 0x0F); data = value_raw & 0x0FFF; value_converted = lsb_size_x100 * data; return value_converted; } int OPT3001DNP::read_reg(uint8_t reg, uint8_t* pbuf, uint8_t len) { int ret; mI2c_.lock(); ret = mI2c_.write(mAddr, (char *)&reg, 1); if (ret == 0) { ret = mI2c_.read(mAddr, (char *)pbuf, len); } mI2c_.unlock(); return ret; }
27.185484
78
0.677544
takjn
3d7b0b4c14ef977d5aad1ddab068dd5a80480113
18,514
hh
C++
Kaskade/io/lossystorageDUNE.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
Kaskade/io/lossystorageDUNE.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:31.000Z
2021-12-09T22:02:36.000Z
Kaskade/io/lossystorageDUNE.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
#ifndef LOSSYSTORAGEDUNE_HH #define LOSSYSTORAGEDUNE_HH #include <map> #include <cassert> #include "dune/grid/common/grid.hh" #include "dune/grid/common/entitypointer.hh" #include "dune/grid/common/entity.hh" #include "dune/grid/io/file/dgfparser/dgfparser.hh" #include "dune/istl/matrix.hh" #include "dune/istl/bcrsmatrix.hh" #include "dune/common/fmatrix.hh" #include "dune/common/iteratorfacades.hh" #include "dune/istl/matrixindexset.hh" #include "rangecoder.hh" #include "lossy_helper.hh" // #define USEBOUNDS #define USEFREQ // #define LEVELWISE template <class Grid, class CoeffVector> class LossyStorage { public: static const int dim = Grid::dimension ; // degree of interpolation polynomials; currently only linear interpolation is supported static const int order = 1 ; // some typedefs used throughout the class typedef typename Grid::template Codim<dim>::LevelIterator VertexLevelIterator ; typedef typename Grid::template Codim<dim>::LeafIterator VertexLeafIterator ; typedef typename Grid::LeafIndexSet IndexSet; typedef typename Grid::LevelGridView::IndexSet::IndexType IndexType; typedef typename Grid::LeafGridView::IndexSet::IndexType LeafIndexType; typedef typename Grid::Traits::GlobalIdSet::IdType IdType; typedef unsigned long int ULong; LossyStorage( int coarseLevel_, double aTol_) : ps(NULL), coarseLevel(coarseLevel_), aTol(aTol_), accumulatedEntropy(0), accumulatedOverhead(0), accumulatedUncompressed(0), accumulatedCompressed(0) { /*#ifdef USEFREQ std::cout << "USES PRECOMPUTED FREQUENCIES FOR ENCODING A SINGLE FUNCTION!\nBEWARE OF THE OVERHEAD!\n"; std::cout << "Due to implementation, not using pre-computed frequencies fails, as the vectors used for\n" << "Alphabet are too large.\n"; #else std::cout << "Uses dictionary for encoding. Beware of the overhead!\n"; std::cout << "Due to implementation, not using the dictionary fails, as the vectors used for\n" << "Alphabet would be too large for fine quantization.\n"; #endif*/ } ~LossyStorage() { if( ps != NULL ) delete ps; } // returns the entropy (summed since the last call to resetEntropy/resetSizes) // of the data (= average symbol size in byte needed to store the file) double reportEntropy() { return accumulatedEntropy; } void resetEntropy() { accumulatedEntropy = 0; } // reports the overhead (summed since last call to resetOverhead/resetSizes) // i.e. interval bounds, frequencies, etc. double reportOverhead() { return accumulatedOverhead; } void resetOverhead() { accumulatedOverhead = 0; } // returns the compressed size // which is (in the best case) the size of the encoded, compressed file // without the overhead from storing intervals etc. double reportCompressedSize() { return accumulatedCompressed; } void resetCompressedSize() { accumulatedCompressed = 0 ; } // returns the compressed size + overhead, which is (in the best case/in the limit) // the size of the compressed file (including all side information) double reportOverallSize() { return accumulatedCompressed + accumulatedOverhead; } // reset everything void resetSizes() { accumulatedEntropy = 0; accumulatedOverhead = 0; accumulatedCompressed = 0; accumulatedUncompressed = 0; } // returns the size needed for uncompressed storage of the data double reportUncompressedSize() { return accumulatedUncompressed; } void resetUncompressedSize() { accumulatedUncompressed = 0 ; } // returns the compression factor (=uncompressed size/compressed size) double reportRatio() { if( accumulatedCompressed + accumulatedOverhead > 0 ) return accumulatedUncompressed / (accumulatedCompressed + accumulatedOverhead ); return -1; } // TODO: has to be faster for adaptive meshes! void setup( Grid const& grid ) { if( ps != NULL ) delete ps; ps = new Lossy_Detail::Prolongation<Grid>(grid); // auto foo = Lossy_Detail::ProlongationStack<Grid>(grid); // for debugging, should use ps = new Prolongation<Grid> instead! typename Grid::GlobalIdSet const& idSet = grid.globalIdSet(); levelInfo.clear(); for( int level = grid.maxLevel(); level >= 0; --level ) { VertexLevelIterator lEnd = grid.template lend <dim>( level ); for( VertexLevelIterator it = grid.template lbegin <dim>( level ); it != lEnd; ++it ) { levelInfo[idSet.id( *it )] = level ; } } } /** * Encode a given state, e.g. the difference between to timesteps. * Quantized values are written to a file specified by fn. */ void encode( Grid const& grid, CoeffVector const& sol, std::string fn, double aTol_ = 0, int maxLevel_ = -1 ) { std::ofstream out( fn.c_str(), std::ios::binary ) ; encode( grid, sol, out, aTol_, maxLevel_); out.close(); } void encode( Grid const& grid, CoeffVector const& sol, std::ostream& out, double aTol_ = 0, int maxLevel_ = -1 ) { double aTolSave = aTol ; if( aTol_ > 0 ) aTol = aTol_ ; // use maxLevel_ instead of maxLevel member int maxLevel = maxLevel_; if( maxLevel < 0 ) maxLevel = grid.maxLevel() ; double overhead = 0, entropy = 0, compressed = 0 ; size_t nNodes = grid.size(dim); typename Grid::GlobalIdSet const& idSet = grid.globalIdSet(); typename Grid::LeafGridView::IndexSet const& leafIndexSet = grid.leafIndexSet(); std::vector<long int> indices ; std::vector<double> predictionError ; std::vector<std::vector<long int> > levelIndices; VertexLevelIterator itEnd = grid.template lend<dim>(coarseLevel); for( VertexLevelIterator it = grid.template lbegin<dim>( coarseLevel ) ; it != itEnd; ++it ) { predictionError.push_back( -sol[leafIndexSet.index(*it)] ) ; } quantize( predictionError, indices) ; reconstruct( predictionError, indices ) ; levelIndices.push_back(indices); CoeffVector reconstruction(grid.size(coarseLevel, dim) ) ; // assign reconstructed coarse grid values size_t nEntries = sol.size(); std::vector<long int> intervalIndicesTmp( nEntries ); long int minIndex = 0; size_t vertexCount = 0 ; for( VertexLevelIterator it = grid.template lbegin<dim>(coarseLevel); it != itEnd; ++it) { reconstruction[vertexCount] = -predictionError[vertexCount] ; long int tmpIndex = indices[vertexCount]; intervalIndicesTmp[leafIndexSet.index(*it)] = tmpIndex; if( tmpIndex < minIndex ) minIndex = tmpIndex; vertexCount++ ; } CoeffVector prediction; for( int l = coarseLevel ; l < maxLevel ; l++ ) { ps->mv(l, reconstruction, prediction) ; std::vector<std::vector<size_t> > vertexInfo( prediction.size(), std::vector<size_t>(3) ); predictionError.clear(); predictionError.reserve( prediction.size() ); // avoid reallocations vertexCount = 0 ; typename Grid::LevelGridView::IndexSet const& levelIndexSet = grid.levelGridView(l+1).indexSet(); itEnd = grid.template lend<dim>(l+1); for( VertexLevelIterator it = grid.template lbegin<dim>(l+1); it != itEnd; ++it) { unsigned char vertexLevel = levelInfo[idSet.id( *it )] ; if( vertexLevel == l+1 ) { predictionError.push_back(prediction[levelIndexSet.index(*it)] - sol[leafIndexSet.index(*it)] ); } vertexInfo[vertexCount][0] = levelIndexSet.index(*it) ; vertexInfo[vertexCount][1] = leafIndexSet.index(*it) ; vertexInfo[vertexCount][2] = vertexLevel ; vertexCount++; } quantize( predictionError, indices) ; reconstruct( predictionError, indices) ; levelIndices.push_back(indices); if( (l+1) < maxLevel ) { // prepare prediction on next level -- use reconstructed values reconstruction.resize( prediction.size() ); vertexCount = 0 ; for( size_t ii = 0 ; ii < vertexInfo.size(); ii++ ) { // correction only for the nodes on level l+1 unsigned char vertexLevel = vertexInfo[ii][2]; IndexType levelIndex = vertexInfo[ii][0]; if( vertexLevel < l+1 ) { reconstruction[levelIndex] = prediction[levelIndex]; } else { long int tmpIndex = indices[vertexCount]; intervalIndicesTmp[vertexInfo[ii][1] ] = tmpIndex; if( tmpIndex < minIndex ) minIndex = tmpIndex; reconstruction[levelIndex] = prediction[levelIndex]-predictionError[vertexCount] ; vertexCount++; } } } else { vertexCount = 0 ; for( size_t ii = 0 ; ii < vertexInfo.size(); ii++ ) { unsigned char vertexLevel = vertexInfo[ii][2];//levelInfo[idSet.id( *it )] ; if( vertexLevel < l+1 ) continue; long int tmpIndex = indices[vertexCount]; intervalIndicesTmp[vertexInfo[ii][1] ] = tmpIndex; if( tmpIndex < minIndex ) minIndex = tmpIndex; vertexCount++ ; } } } std::vector<ULong> intervalIndices( nEntries ) ; for( size_t i = 0; i < nEntries; i++ ) intervalIndices[i] = intervalIndicesTmp[i] - minIndex ; out.write(reinterpret_cast<char*>( &minIndex ), sizeof(long int) ) ; overhead += sizeof(long int); std::map<unsigned long, unsigned long> freqMap; unsigned int nnz = 0; for( size_t i = 0 ; i < nEntries ; i++ ) { if( freqMap.find(intervalIndices[i] ) != freqMap.end() ) // already there, increment { freqMap[intervalIndices[i]]++ ; } else // new nonzero, add to map { nnz++; freqMap[intervalIndices[i]] = 1; } } out.write(reinterpret_cast<char*>( &nnz ), sizeof(unsigned int) ) ; overhead += sizeof(unsigned int); std::vector<unsigned long> frequenciesForRangeCoder(nnz); std::map<unsigned long, unsigned long> dictMap; unsigned long curNo = 0 ; std::map<unsigned long,unsigned long>::iterator mapIt; std::map<unsigned long,unsigned long>::iterator mapEnd = freqMap.end(); for( mapIt = freqMap.begin(); mapIt != mapEnd; ++mapIt ) { unsigned long lv = mapIt->first; frequenciesForRangeCoder[curNo] = mapIt->second; dictMap.insert( dictMap.begin(), std::pair<unsigned long, unsigned long>(lv, curNo) ) ; out.write(reinterpret_cast<char*>( &lv ), sizeof(unsigned long) ) ; overhead += sizeof(unsigned long); curNo++; } for( unsigned int i = 0 ; i < nnz ; i++ ) { #ifdef USEFREQ out.write(reinterpret_cast<char*>( &frequenciesForRangeCoder[i] ), sizeof(unsigned long) ) ; overhead += sizeof(unsigned long); #endif double tmp = -ld(frequenciesForRangeCoder[i]/((double)nNodes)) * frequenciesForRangeCoder[i]/((double)nNodes); entropy += tmp; compressed += tmp; } accumulatedCompressed += compressed/8*nNodes; compressed = 0; #ifndef USEFREQ frequenciesForRangeCoder.clear(); freqMap.clear(); #endif std::cout.flush(); #ifdef USEFREQ Alphabet<unsigned long> alphabet( frequenciesForRangeCoder.begin(), frequenciesForRangeCoder.end() ) ; RangeEncoder<unsigned long> encoder( out ) ; for( size_t i = 0 ; i < nEntries; i++ ) { encodeSymbol( encoder, alphabet, dictMap.find(intervalIndices[i])->second/* dictMap[intervalIndices[i]]*/ ); } #else size_t symbolCounter = 0 ; std::vector<unsigned long> count(nnz, 1) ; Alphabet<unsigned long> alphabet( count.begin(), count.end() ) ; RangeEncoder<unsigned long> encoder(out) ; for( size_t i = 0 ; i < nEntries; i++ ) { encodeSymbol( encoder, alphabet, dictMap.find(intervalIndices[i])->second); ++count[dictMap[intervalIndices[i]]]; ++symbolCounter ; if (symbolCounter>0.1*nEntries) { alphabet.update(count.begin(),count.end()); symbolCounter=0; } } #endif accumulatedEntropy += entropy/8 ; accumulatedOverhead += overhead; accumulatedUncompressed += 8*nNodes; aTol = aTolSave; } /** * Decode quantized values and store in a VariableSet::Representation. * The file to be read is specified by fn. */ void decode( Grid const& gridState, CoeffVector& sol, std::string fn, double aTol_ = 0, int maxLevel_ = -1 ) { std::ifstream in( fn.c_str(), std::ios::binary ) ; decode(gridState, sol, in, aTol_, maxLevel_); in.close() ; } void decode( Grid const& gridState, CoeffVector& sol, std::istream& in, double aTol_ = 0, int maxLevel_ = -1 ) { double aTolSave = aTol ; if( aTol_ > 0 ) aTol = aTol_ ; int maxLevel = maxLevel_; if( maxLevel < 0 ) maxLevel = gridState.maxLevel(); // prepare prediction typename Grid::GlobalIdSet const& idSet = gridState.globalIdSet(); IndexSet const& indexSet = gridState.leafIndexSet(); std::vector<double> values ; std::vector<long int> intervalIndices( gridState.size(dim) ); size_t nEntries = intervalIndices.size(); VertexLevelIterator itEnd = gridState.template lend<dim>(coarseLevel); // read in indices from file long int minIndex ; in.read(reinterpret_cast<char*>( &minIndex ), sizeof(long int) ) ; unsigned int nnz ; in.read(reinterpret_cast<char*>( &nnz ), sizeof(unsigned int) ) ; // # non-empty intervals std::vector<long int> dictionary( nnz ) ; for( int i = 0 ; i < nnz ; i++ ) { in.read(reinterpret_cast<char*>( &dictionary[i] ), sizeof(unsigned long) ) ; // existing intervals (dictionary) } #ifdef USEFREQ std::vector<unsigned long> frequencies( nnz, 0 ) ; for( int i = 0 ; i < nnz ; i++ ) { in.read(reinterpret_cast<char*>( &frequencies[i] ), sizeof(unsigned long) ) ; // frequencies } Alphabet<unsigned long> alphabet( frequencies.begin(), frequencies.end() ) ; try { RangeDecoder<unsigned long> decoder( in ) ; for( int i = 0 ; i < intervalIndices.size() ; i++ ) { unsigned long s = decodeSymbol(decoder,alphabet) ; intervalIndices[i] = dictionary[s] + minIndex ; } } catch( std::ios_base::failure& e ) { if (in.rdstate() & std::ifstream::eofbit) { std::cout << "EOF reached.\n"; } else { std::cout << " Decoding error\n" << e.what() << "\n"; } } #else size_t symbolCounter = 0 ; std::vector<unsigned long> symcount(nnz, 1) ; Alphabet<unsigned long> alphabet( symcount.begin(), symcount.end() ) ; try { RangeDecoder<unsigned long> decoder( in ) ; for( size_t i = 0 ; i < nEntries ; i++ ) { unsigned long s = decodeSymbol(decoder,alphabet) ; intervalIndices[i] = dictionary[s] + minIndex ; ++symcount[s]; ++symbolCounter ; if (symbolCounter>0.1*nEntries) { alphabet.update(symcount.begin(),symcount.end()); symbolCounter=0; } } } catch( std::ios_base::failure& e ) { if (in.rdstate() & std::ifstream::eofbit) { std::cout << "EOF reached.\n"; } else { std::cout << " Decoding error\n" << e.what() << "\n"; } } #endif // in.close() ; // start reconstruction int vertexCount = 0; CoeffVector reconstruction( gridState.size(coarseLevel, dim) ); sol.resize( gridState.size(dim) ); for( VertexLevelIterator it = gridState.template lbegin<dim>( coarseLevel ); it != itEnd; ++it) { double recVal = reconstruct( intervalIndices[indexSet.index(*it)]); reconstruction[gridState.levelGridView(coarseLevel).indexSet().index(*it)] = -recVal ; // store predicted values for the coarse grid in solution vector sol[ indexSet.index(*it) ] = -recVal ; vertexCount++ ; } CoeffVector prediction; // perform prediction and correction for( int l = coarseLevel ; l < maxLevel ; l++ ) { ps->mv( l, reconstruction, prediction ) ; reconstruction.resize( prediction.size() ); typename Grid::LevelGridView::IndexSet const& levelIndexSet = gridState.levelGridView(l+1).indexSet(); vertexCount = 0 ; itEnd = gridState.template lend<dim>(l+1); for( VertexLevelIterator it = gridState.template lbegin<dim>(l+1); it != itEnd ; ++it) { IndexType levelIndex = levelIndexSet.index(*it); if(levelInfo[gridState.globalIdSet().id(*it)] == l+1) //correct only vertices on level l+1 { reconstruction[levelIndex] = prediction[levelIndex] - reconstruct( intervalIndices[indexSet.index(*it)]); } else { reconstruction[levelIndex] = prediction[levelIndex]; } sol[indexSet.index(*it)] = reconstruction[ levelIndex] ; vertexCount++ ; } } aTol = aTolSave ; } private: LossyStorage( LossyStorage const& ); LossyStorage& operator=( LossyStorage const& ) ; /** Helper method to perform the actual quantization for a whole level. */ void quantize( std::vector<double> const& values, std::vector<long int>& indices) { indices.clear() ; indices.resize( values.size(), 0 ) ; for( size_t i = 0 ; i < values.size() ; i++ ) { indices[i] = static_cast<long int>( floor( values[i] / (2*aTol) + 0.5 ) ); } } /** Helper method to perform the actual reconstruction of quantized values without lb, ub. */ void reconstruct( std::vector<double>& values, std::vector<long int> const& indices) { values.clear() ; values.resize( indices.size() ) ; for( size_t i = 0 ; i < indices.size() ; i++ ) { values[i] = indices[i] * 2* aTol ; } } /** Helper method to perform the actual reconstruction of quantized values without lb, ub. */ double reconstruct( long int const& index ) { return index*2*aTol; } /** Helper method returning the base 2-logarithm. */ double ld( double val ) { return log(val)/log(2.0) ; } Lossy_Detail::Prolongation<Grid> * ps; std::map<IdType, unsigned char> levelInfo ; int coarseLevel ; double aTol ; double accumulatedEntropy, accumulatedOverhead, accumulatedUncompressed, accumulatedCompressed; } ; #endif
30.35082
128
0.633737
chenzongxiong
3d7b49ae1d91f630dd24ca58761b05eec3f2eb85
841
cpp
C++
Leetcode/Coding Interviews/56_01_Single_Numbers.cpp
ZR-Huang/AlgorithmPractices
226cecde136531341ce23cdf88529345be1912fc
[ "BSD-3-Clause" ]
1
2019-11-26T11:52:25.000Z
2019-11-26T11:52:25.000Z
Leetcode/Coding Interviews/56_01_Single_Numbers.cpp
ZR-Huang/AlgorithmPractices
226cecde136531341ce23cdf88529345be1912fc
[ "BSD-3-Clause" ]
null
null
null
Leetcode/Coding Interviews/56_01_Single_Numbers.cpp
ZR-Huang/AlgorithmPractices
226cecde136531341ce23cdf88529345be1912fc
[ "BSD-3-Clause" ]
null
null
null
/* 一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。 要求时间复杂度是O(n),空间复杂度是O(1)。 示例 1: 输入:nums = [4,1,4,6] 输出:[1,6] 或 [6,1] 示例 2: 输入:nums = [1,2,10,4,1,4,3,3] 输出:[2,10] 或 [10,2] 限制: 2 <= nums <= 10000 */ #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> singleNumbers(vector<int>& nums) { // https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/solution/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-by-leetcode/ vector<int> ans = {0, 0}; int sum = 0; for(int num: nums) sum ^= num; int flag = 1; while((flag & sum) == 0) flag <<= 1; for(int num: nums) if(num & flag) ans[0] ^= num; else ans[1] ^= num; return ans; } };
21.564103
148
0.525565
ZR-Huang
3d7dc2702f89d2573a9aa8f59d12c1217bcd3428
2,199
hpp
C++
plugins/history_plugin/include/eosio/history_plugin/public_key_history_object.hpp
linapex/eos-chinese
33539709c30940b6489cec1ed2d982ff76da5cc5
[ "MIT" ]
null
null
null
plugins/history_plugin/include/eosio/history_plugin/public_key_history_object.hpp
linapex/eos-chinese
33539709c30940b6489cec1ed2d982ff76da5cc5
[ "MIT" ]
null
null
null
plugins/history_plugin/include/eosio/history_plugin/public_key_history_object.hpp
linapex/eos-chinese
33539709c30940b6489cec1ed2d982ff76da5cc5
[ "MIT" ]
null
null
null
//<developer> // <name>linapex 曹一峰</name> // <email>linapex@163.com</email> // <wx>superexc</wx> // <qqgroup>128148617</qqgroup> // <url>https://jsq.ink</url> // <role>pku engineer</role> // <date>2019-03-16 19:44:17</date> //</624457052034437120> /* *@文件 *@eos/license中定义的版权 **/ #pragma once #include <chainbase/chainbase.hpp> #include <fc/array.hpp> namespace eosio { using chain::account_name; using chain::public_key_type; using chain::permission_name; using namespace boost::multi_index; class public_key_history_object : public chainbase::object<chain::public_key_history_object_type, public_key_history_object> { OBJECT_CTOR(public_key_history_object) id_type id; public_key_type public_key; account_name name; permission_name permission; }; struct by_id; struct by_pub_key; struct by_account_permission; using public_key_history_multi_index = chainbase::shared_multi_index_container< public_key_history_object, indexed_by< ordered_unique<tag<by_id>, BOOST_MULTI_INDEX_MEMBER(public_key_history_object, public_key_history_object::id_type, id)>, ordered_unique<tag<by_pub_key>, composite_key< public_key_history_object, member<public_key_history_object, public_key_type, &public_key_history_object::public_key>, member<public_key_history_object, public_key_history_object::id_type, &public_key_history_object::id> > >, ordered_unique<tag<by_account_permission>, composite_key< public_key_history_object, member<public_key_history_object, account_name, &public_key_history_object::name>, member<public_key_history_object, permission_name, &public_key_history_object::permission>, member<public_key_history_object, public_key_history_object::id_type, &public_key_history_object::id> > > > >; typedef chainbase::generic_index<public_key_history_multi_index> public_key_history_index; } CHAINBASE_SET_INDEX_TYPE( eosio::public_key_history_object, eosio::public_key_history_multi_index ) FC_REFLECT( eosio::public_key_history_object, (public_key)(name)(permission) )
31.869565
126
0.740791
linapex
3d8369e2d74a6da787ed278e972c1233294725a3
1,117
cpp
C++
oclint-core/lib/RuleBase.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
3,128
2015-01-01T06:00:31.000Z
2022-03-29T23:43:20.000Z
oclint-core/lib/RuleBase.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
432
2015-01-03T15:43:08.000Z
2022-03-29T02:32:48.000Z
oclint-core/lib/RuleBase.cpp
BGU-AiDnD/oclint
484fed44ca0e34532745b3d4f04124cbf5bb42fa
[ "BSD-3-Clause" ]
454
2015-01-06T03:11:12.000Z
2022-03-22T05:49:38.000Z
#include "oclint/RuleBase.h" using namespace oclint; void RuleBase::takeoff(RuleCarrier *carrier) { _carrier = carrier; apply(); } const std::string RuleBase::attributeName() const { return name(); } const std::string RuleBase::identifier() const { std::string copy = name(); if (copy.empty()) { return copy; } copy[0] = toupper(copy[0]); for (std::string::iterator it = copy.begin() + 1; it != copy.end(); ++it) { if (!isalpha(*(it - 1)) && islower(*it)) { *it = toupper(*it); } } copy.erase(std::remove_if(copy.begin(), copy.end(), [](char eachChar){return !isalpha(eachChar);}), copy.end()); return copy; } #ifdef DOCGEN const std::string RuleBase::fileName() const { return identifier() + "Rule.cpp"; } bool RuleBase::enableSuppress() const { return false; } const std::map<std::string, std::string> RuleBase::thresholds() const { std::map<std::string, std::string> emptyMap; return emptyMap; } const std::string RuleBase::additionalDocument() const { return ""; } #endif
18.616667
77
0.59803
BGU-AiDnD
3d85a355c011f71f3f8f59494c3b6a539c6ba3c6
6,869
cpp
C++
src/Huffman.cpp
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
src/Huffman.cpp
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
src/Huffman.cpp
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
#include "Huffman.h" #include <cstdlib> #include <cstring> #include <exception> #include <fstream> #include <map> #include <queue> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include "ArbolCodificacion.hxx" #include "CodigoElemento.hxx" #include "Imagen.h" #include "NodoCodificacion.hxx" #include "NodoElemento.hxx" #include "NodoFrecuencia.hxx" Huffman::Huffman(const Imagen &img) : ancho(img.get_ancho()), alto(img.get_alto()), maximo(img.get_max_tam()), imagen(&img) { // Verificar normalización if (img.get_max_tam() > 255) throw std::invalid_argument("La imagen no está normalizada"); // Construir mapa de frecuencias std::map<byte_t, freq_t> frecuencias{}; for (int i = 0; i <= 255; i++) frecuencias[i] = 0; // Calcular frecuencias en la imágen Imagen::matriz_t pixeles = img.get_pixeles(); for (int i = 0; i < img.get_alto(); i++) for (int j = 0; j < img.get_ancho(); j++) frecuencias[(byte_t)pixeles[i][j]]++; // Cada vez que se encuentra un // pixel, le suma 1 a su frecuencia // Se crea el árbol de codificacion this->arbol = new ArbolCodificacion<byte_t>{frecuencias}; std::vector<CodigoElemento<byte_t>> datos = arbol->codigos_elementos(); // Se obtienen las frecuencias y valores de los bytes for (int i = 0; i < datos.size(); i++) codigos[datos[i].elemento] = datos[i]; } Huffman::Huffman(const std::string nombre_archivo, std::string salida) : imagen{nullptr} { //* Abrir el archivo std::ifstream archivo(nombre_archivo, std::ios::binary | std::ios::in); // Verificar que se pudo abrir if (!archivo.is_open()) throw std::runtime_error("No se pudo abrir el archivo"); //* Header archivo.read((char *)(&this->ancho), sizeof(word_t)); archivo.read((char *)(&this->alto), sizeof(word_t)); archivo.read((char *)(&this->maximo), sizeof(byte_t)); //* Frecuencias // Escribir todas las frecuencias for (byte_t i = 0; i < 255; i++) { if (!codigos.count(i)) codigos[i] = CodigoElemento<byte_t>{i, 0, ""}; // Read binary archivo.read((char *)&codigos[i].frecuencia, sizeof(lword_t)); } //* Construir el árbol std::map<byte_t, freq_t> frecuencias{}; for (std::pair<byte_t, CodigoElemento<byte_t>> codigo : codigos) frecuencias[codigo.first] = codigo.second.frecuencia; this->arbol = new ArbolCodificacion<byte_t>{frecuencias}; //* Obtener los bits std::vector<byte_t> bytes{}; std::queue<int> cadenabits{}; while (!archivo.eof()) { byte_t byte = 0x0000; archivo.read((char *)&byte, sizeof(byte_t)); // If there's nothing to read if (archivo.gcount() == 0) break; // Transform every bit for (int k = 8; k > 0; k--) cadenabits.push(static_cast<int>((byte >> (k - 1)) & 1)); } std::queue<byte_t> pixeles{}; NodoCodificacion<byte_t> *actual = arbol->raiz; std::vector<CodigoElemento<byte_t>> codigos = arbol->codigos_elementos(); int total_leer = 0; for (auto cod : codigos) total_leer += cod.codigo.size() * cod.frecuencia; for (int leidos = 0; leidos <= total_leer;) { // Si es una hoja if (typeid(*actual) == typeid(NodoElemento<byte_t>)) { pixeles.push(dynamic_cast<NodoElemento<byte_t> *>(actual)->dato); actual = arbol->raiz; } else { // Si es 1 int bit = cadenabits.front(); if (bit == 1) actual = dynamic_cast<NodoFrecuencia<byte_t> *>(actual)->hijoDer; // Si es 0 else if (bit == 0) actual = dynamic_cast<NodoFrecuencia<byte_t> *>(actual)->hijoIzq; cadenabits.pop(); leidos++; } } // Pasar los datos a la imagen Imagen::matriz_t matriz = Imagen::matriz_vacia(this->ancho, this->alto); for (int i = 0; i < this->alto; i++) for (int j = 0; j < this->ancho; j++) { matriz[i][j] = pixeles.front(); pixeles.pop(); } Imagen imgp{matriz}; imgp.set_max_tam(static_cast<int>(this->maximo)); imgp.set_nombre_archivo(salida); imgp.guardar_archivo(salida); //* Cerrar archivos archivo.close(); } Huffman::~Huffman() { if (this->arbol != nullptr) { delete arbol; arbol = nullptr; } } void Huffman::guardar_archivo(std::string nombre_archivo) { //* Abrir el archivo std::ofstream archivo(nombre_archivo, std::ios::binary | std::ios::out); #ifdef _DEBUG_ std::ofstream debugf(nombre_archivo + ".debug.txt", std::ios::out); #endif // Verificar que se pudo abrir if (!archivo.is_open()) throw std::runtime_error("No se pudo abrir el archivo"); //* Header archivo.write((char *)(&this->ancho), sizeof(word_t)); archivo.write((char *)(&this->alto), sizeof(word_t)); archivo.write((char *)(&this->maximo), sizeof(byte_t)); #ifdef _DEBUG_ debugf << "# HEADER #\n"; debugf << "WIDTH\t" << (int)this->ancho << '\t' << "WORD (2)" << '\n'; debugf << "HEIGHT\t" << (int)this->alto << '\t' << "WORD (2)" << '\n'; debugf << "VALMAX\t" << (int)this->maximo << '\t' << "BYTE (1)" << '\n'; debugf << "# FREQ TABLE #\n"; #endif //* Frecuencias // Escribir todas las frecuencias for (byte_t i = 0; i < 255; i++) { if (!codigos.count(i)) codigos[i] = CodigoElemento<byte_t>{i, 0, ""}; // Write binary archivo.write((char *)&codigos[i].frecuencia, sizeof(lword_t)); #ifdef _DEBUG_ debugf << static_cast<int>(codigos[i].elemento) << "\tBYTE (1)\t" << codigos[i].frecuencia << "\t\tDWORD (4)\t" << codigos[i].codigo << "\t\t\t\t BITS(" << codigos[i].codigo.size() << ")\n"; #endif } //* Calcular codigo general std::stringstream generalss; Imagen::matriz_t pixels = imagen->get_pixeles(); // Tomar todos los elementos de la imagen y colocarlos en codigo for (int i = 0; i < imagen->get_alto(); i++) for (int j = 0; j < imagen->get_ancho(); j++) generalss << codigos[pixels[i][j]].codigo; const std::string general = generalss.str(); #ifdef _DEBUG_ debugf << "# CODE #\n" << general << "\n# END #"; #endif //* Transformar a bytes for (int i = 0; i < general.size();) { byte_t byte = 0x0000; // Transform every bit for (int k = 8; k > 0; k--, i++) { if (i >= general.size()) break; if (general.at(i) == '1') (byte |= (1 << (k - 1))); } // Escribir el bit archivo.write((char *)&byte, sizeof(byte_t)); } //* Cerrar archivos archivo.close(); #ifdef _DEBUG_ debugf.close(); #endif }
31.081448
78
0.579706
taleroangel
3d85a65106b3b1cbf38d423250ae88c711eb6ae9
22,475
cpp
C++
Blizzlike/ArcEmu/C++/Battlegrounds/StrandOfTheAncient.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/Battlegrounds/StrandOfTheAncient.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/Battlegrounds/StrandOfTheAncient.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * ArcEmu MMORPG Server * Copyright (C) 2008-2011 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /*********************************************************************** Strand of the Ancients ====================== * Other Game Objects * Defender's Portal, 190763 * Defender's Portal, 191575 * Defender's Portal, 192819 -gps at: -gps to: * Titan Relic, 194083 (different one, not supported atm) * Collision PC Size, 188215 * The Coffin Carrier, 193184 * The Blightbringer, 193183 * The Frostbreaker, 193185 * The Graceful Maiden (boat?), 193182 * Doodad_WG_Keep_Door01_collision01, 194162 (Not implemented atm) * Revive everyone after round one * bg->EventResurrectPlayers() * Setup index 34 in worldstring_tables to equal "Strand of the Ancients" * Fix level requirements to join the battleground. And fix which npc text is used for the battlemaster gossip scripts, displaying the proper of 3 messages npc_text 13832 = You are not yet strong enough to do battle in the Strand of the Ancients. Return when you have gained more experience. 13834 = We cannot allow the Alliance to turn the hidden secrets of the Strand of the Ancients against us. Will you join our brave warriors there? +13833 = We cannot allow the Horde to turn the hidden secrets of the Strand of the Ancients against us. Will you join our brave warriors there? * Increase the view distance on map 607 to 500 or 0 (Unlimited). See the transporter patch... Need a way to see the gates from as far away as the boats. * Besure to spawn, platforms, vehicels, and relic so only the proper faction can use them. * Fix it where a BG is instanced as soon as the first player joins, only after one faction has field their entire queue for a particular battlefield, would a new BG instance be created. It might actually be this way, if so just patch so that these pre-loaded instances appear in the battlemaster lists. * Also change so numbers are reused, once SOTA instance 1 is deleted, there is no reason why that instance id can't be reused. Also each BG needs it own unique numbering, instead of a shared pool. ************************************************************************/ #include "StdAfx.h" #include "StrandOfTheAncient.h" #define GO_RELIC 192834 const float sotaTitanRelic[4] = { 836.5f, -108.8f, 111.59f, 0.0f }; const uint32 GateGOIds[6] = { 190722, // Gate of the Green Emerald 190727, // Gate of the Yellow Moon 190724, // Gate of the Blue Sapphire 190726, // Gate of the Red Sun 190723, // Gate of the Purple Amethyst 192549, // Chamber of Ancient Relics }; const float sotaGates[GATE_COUNT][4] = { { 1411.57f, 108.163f, 28.692f, 5.441f }, { 1055.452f, -108.1f, 82.134f, 0.034f }, { 1431.3413f, -219.437f, 30.893f, 0.9736f }, { 1227.667f, -212.555f, 55.372f, 0.5023f }, { 1214.681f, 81.21f, 53.413f, 5.745f }, }; const float sotaChamberGate[4] = { 878.555f, -108.989f, 119.835f, 0.0565f }; // Things radiating out from the gates... same orientation as door. const uint32 GateSigilGOIds[5] = { 192687, 192685, 192689, 192690, 192691, }; const float sotaGateSigils[GATE_COUNT][4] = { { 1414.054f, 106.72f, 41.442f, 5.441f }, { 1060.63f, -107.8f, 94.7f, 0.034f }, { 1433.383f, -216.4f, 43.642f, 0.9736f }, { 1230.75f, -210.724f, 67.611f, 0.5023f }, { 1217.8f, 79.532f, 66.58f, 5.745f }, }; // Defender transporter platform locations const float sotaTransporters[GATE_COUNT][4] = { { 1394.0444f, 72.586f, 31.0535f, 0.0f }, { 1065.0f, -89.7f, 81.08f, 0.0f }, { 1467.95f, -225.67f, 30.9f, 0.0f }, { 1255.93f, -233.382f, 56.44f, 0.0f }, { 1215.679f, 47.47f, 54.281f, 0.0f }, }; // Defender transporter destination locations const float sotaTransporterDestination[GATE_COUNT][4] = { { 1388.94f, 103.067f, 34.49f, 5.4571f }, { 1043.69f, -87.95f, 87.12f, 0.003f }, { 1441.0411f, -240.974f, 35.264f, 0.949f }, { 1228.342f, -235.234f, 60.03f, 0.4584f }, { 1193.857f, 69.9f, 58.046f, 5.7245f }, }; // Two guns per gate, GUN_LEFT and GUN_RIGHT static LocationVector CanonLocations[ SOTA_NUM_CANONS ] = { LocationVector( 1436.429f, 110.05f, 41.407f, 5.4f ), LocationVector( 1404.9023f, 84.758f, 41.183f, 5.46f ), LocationVector( 1068.693f, -86.951f, 93.81f, 0.02f ), LocationVector( 1068.83f, -127.56f, 96.45f, 0.0912f ), LocationVector( 1422.115f, -196.433f, 42.1825f, 1.0222f ), LocationVector( 1454.887f, -220.454f, 41.956f, 0.9627f ), LocationVector( 1232.345f, -187.517f, 66.945f, 0.45f ), LocationVector( 1249.634f, -224.189f, 66.72f, 0.635f ), LocationVector( 1236.213f, 92.287f, 64.965f, 5.751f ), LocationVector( 1215.11f, 57.772f, 64.739f, 5.78f ) }; static LocationVector DemolisherLocations[ SOTA_NUM_DEMOLISHERS ] = { LocationVector( 1620.71f, 64.04f, 7.19f, 3.78f ), LocationVector( 1593.59f, 40.8f, 7.52f, 0.86f ), LocationVector( 1582.42f, -93.75f, 8.49f, 5.7f ), LocationVector( 1611.19f, -117.4f, 8.77f, 2.55f ), LocationVector( 1353.34f, 224.01f, 35.24f, 4.236f ), LocationVector( 1371.03f, -317.06f, 35.01f, 1.85f ) }; // ---- Verify remaining ----- // // There should only be two boats. boats three and four here // are a lazy hack for not wanting to program the boats to move via waypoints const float sotaBoats[4][4] = { { 1623.34f, 37.0f, 1.0f, 3.65f }, { 2439.4f, 845.38f, 1.0f, 3.35f }, { 1623.34f, 37.0f, 1.0f, 3.65f }, { 2439.4f, 845.38f, 1.0f, 3.35f }, }; static LocationVector sotaAttackerStartingPosition[ SOTA_NUM_ROUND_STAGES ] = { LocationVector( 2445.288f, 849.35f, 10.0f, 3.76f ), LocationVector( 1624.7f, 42.93f, 10.0f, 2.63f ) }; static LocationVector sotaDefenderStartingPosition = LocationVector( 1209.7f, -65.16f, 70.1f, 0.0f ); static LocationVector FlagPolePositions[ NUM_SOTA_CONTROL_POINTS ] = { LocationVector( 1338.863892f, -153.336533f, 30.895121f, -2.530723f ), LocationVector( 1309.124268f, 9.410645f, 30.893402f, -1.623156f ), LocationVector( 1215.114258f, -65.711861f, 70.084267f, -3.124123f ) }; static LocationVector FlagPositions[ NUM_SOTA_CONTROL_POINTS ] = { LocationVector( 1338.859253f, -153.327316f, 30.895077f, -2.530723f ), LocationVector( 1309.192017f, 9.416233f, 30.893402f, 1.518436f ), LocationVector( 1215.108032f, -65.715767f, 70.084267f, -3.124123f ) }; static const uint32 FlagIDs[ NUM_SOTA_CONTROL_POINTS ][ MAX_PLAYER_TEAMS ] = { { 191306, 191305 }, { 191308, 191307 }, { 191310, 191309 } }; static const uint32 CPWorldstates[ NUM_SOTA_CONTROL_POINTS ][ MAX_PLAYER_TEAMS ] = { { WORLDSTATE_SOTA_GY_E_A, WORLDSTATE_SOTA_GY_E_H }, { WORLDSTATE_SOTA_GY_W_A, WORLDSTATE_SOTA_GY_W_H }, { WORLDSTATE_SOTA_GY_S_A, WORLDSTATE_SOTA_GY_S_H } }; static const uint32 SOTA_FLAGPOLE_ID = 191311; const char* ControlPointNames[ NUM_SOTA_CONTROL_POINTS ] = { "East Graveyard", "West Graveyard", "South Graveyard" }; static LocationVector GraveyardLocations[ NUM_SOTA_GRAVEYARDS ] = { LocationVector( 1396.06018066f, -288.036895752f, 32.0815124512f, 0.0f ), LocationVector( 1388.80358887f, 203.354873657f, 32.1526679993f, 0.0f ), LocationVector( 1122.27844238f, 4.41617822647f, 68.9358291626f, 0.0f ), LocationVector( 964.595275879f, -189.784011841f, 90.6604995728f, 0.0f ), LocationVector( 1457.19372559f, -53.7132720947f, 5.18109416962f, 0.0f ), }; static const uint32 TeamFactions[ MAX_PLAYER_TEAMS ] = { 1, 2 }; StrandOfTheAncient::StrandOfTheAncient( MapMgr* mgr, uint32 id, uint32 lgroup, uint32 t ) : CBattleground( mgr, id, lgroup, t ){ m_zoneid = 4384; std::fill( &canon[ 0 ], &canon[ SOTA_NUM_CANONS ], reinterpret_cast< Creature* >( NULL ) ); std::fill( &demolisher[ 0 ], &demolisher[ SOTA_NUM_DEMOLISHERS ], reinterpret_cast< Creature* >( NULL ) ); } StrandOfTheAncient::~StrandOfTheAncient(){ std::fill( &canon[ 0 ], &canon[ SOTA_NUM_CANONS ], reinterpret_cast< Creature* >( NULL ) ); std::fill( &demolisher[ 0 ], &demolisher[ SOTA_NUM_DEMOLISHERS ], reinterpret_cast< Creature* >( NULL ) ); } void StrandOfTheAncient::HookOnAreaTrigger(Player* plr, uint32 id) { } void StrandOfTheAncient::HookOnPlayerKill(Player* plr, Player* pVictim) { plr->m_bgScore.KillingBlows++; UpdatePvPData(); } void StrandOfTheAncient::HookOnHK(Player* plr) { plr->m_bgScore.HonorableKills++; UpdatePvPData(); } void StrandOfTheAncient::OnPlatformTeleport(Player* plr) { } void StrandOfTheAncient::OnAddPlayer(Player* plr) { if(!m_started) plr->CastSpell(plr, BG_PREPARATION, true); } void StrandOfTheAncient::OnRemovePlayer(Player* plr) { if(!m_started) plr->RemoveAura(BG_PREPARATION); } LocationVector StrandOfTheAncient::GetStartingCoords( uint32 team ){ if( team == Attackers ) return sotaAttackerStartingPosition[ roundprogress ]; else return sotaDefenderStartingPosition; } void StrandOfTheAncient::HookOnPlayerDeath(Player* plr) { plr->m_bgScore.Deaths++; UpdatePvPData(); } void StrandOfTheAncient::HookOnMount(Player* plr) { /* Allowed */ } bool StrandOfTheAncient::HookHandleRepop( Player *plr ){ float dist = 999999.0f; LocationVector dest_pos; uint32 id = 0; // Let's find the closests GY for( uint32 i = SOTA_GY_EAST; i < NUM_SOTA_GRAVEYARDS; i++ ){ if( graveyard[ i ].faction == plr->GetTeam() ){ if( graveyard[ i ].spiritguide == NULL ) continue; float gydist = plr->CalcDistance( graveyard[ i ].spiritguide ); if( gydist > dist ) continue; dist = gydist; dest_pos = graveyard[ i ].spiritguide->GetPosition(); id = i; } } if( id >= NUM_SOTA_GRAVEYARDS ) return false; // port to it and queue for auto-resurrect plr->SafeTeleport( plr->GetMapId(), plr->GetInstanceID(), dest_pos ); QueuePlayerForResurrect( plr, graveyard[ id ].spiritguide ); return true; } void StrandOfTheAncient::OnCreate() { { uint32 i; BattleRound = 1; roundprogress = SOTA_ROUND_PREPARATION; for(i = 0; i < 2; i++) { m_players[i].clear(); m_pendPlayers[i].clear(); RoundFinishTime[ i ] = 10 * 60; } m_pvpData.clear(); m_resurrectMap.clear(); // Boats for(i = 0; i < 4; i++) { m_boats[i] = m_mapMgr->CreateAndSpawnGameObject(20808, sotaBoats[i][0], sotaBoats[i][1], sotaBoats[i][2], sotaBoats[i][3], 1.0f); m_boats[i]->PushToWorld( m_mapMgr ); } /* Relic */ m_relic = m_mapMgr->CreateAndSpawnGameObject(GO_RELIC, sotaTitanRelic[0], sotaTitanRelic[1], sotaTitanRelic[2], sotaTitanRelic[3], 1.0f); for(i = 0; i < GATE_COUNT; i++) { m_gates[i] = m_mapMgr->CreateAndSpawnGameObject(GateGOIds[i], sotaGates[i][0], sotaGates[i][1], sotaGates[i][2], sotaGates[i][3], 1.0f); m_gateSigils[i] = m_mapMgr->CreateAndSpawnGameObject(GateSigilGOIds[i], sotaGateSigils[i][0], sotaGateSigils[i][1], sotaGateSigils[i][2], sotaGateSigils[i][3], 1.0f); m_gateTransporters[i] = m_mapMgr->CreateAndSpawnGameObject(192819, sotaTransporters[i][0], sotaTransporters[i][1], sotaTransporters[i][2], sotaTransporters[i][3], 1.0f); } // Spawn door for Chamber of Ancient Relics m_endgate = m_mapMgr->CreateAndSpawnGameObject(GateGOIds[i], sotaChamberGate[0], sotaChamberGate[1], sotaChamberGate[2], sotaChamberGate[3], 1.0f); } PrepareRound(); } void StrandOfTheAncient::OnStart(){ m_started = true; StartRound(); } void StrandOfTheAncient::HookGenerateLoot(Player* plr, Object* pOCorpse) { LOG_DEBUG("*** StrandOfTheAncient::HookGenerateLoot"); } void StrandOfTheAncient::HookOnUnitKill( Player* plr, Unit* pVictim ){ } void StrandOfTheAncient::HookOnUnitDied( Unit *victim ){ if( victim->IsCreature() ){ for( uint32 i = 0; i < SOTA_NUM_DEMOLISHERS; i++ ){ Creature *c = demolisher[ i ]; if( c == NULL ) continue; if( victim->GetGUID() != c->GetGUID() ) continue; demolisher[ i ] = SpawnCreature( 28781, DemolisherLocations[ i ], TeamFactions[ Attackers ] ); c->Despawn( 1, 0 ); } for( uint32 i = 0; i < SOTA_NUM_CANONS; i++ ){ if( canon[ i ] == NULL ) continue; if( victim->GetGUID() != canon[ i ]->GetGUID() ) continue; canon[ i ]->Despawn( 1, 0 ); canon[ i ] = NULL; } } } void StrandOfTheAncient::SetIsWeekend(bool isweekend) { LOG_DEBUG("*** StrandOfTheAncient::SetIsWeekend"); m_isWeekend = isweekend; } bool StrandOfTheAncient::HookSlowLockOpen( GameObject *go, Player *player, Spell *spell ){ uint32 goentry = go->GetEntry(); switch( goentry ){ case 191305: case 191306: CaptureControlPoint( SOTA_CONTROL_POINT_EAST_GY ); return true; break; case 191307: case 191308: CaptureControlPoint( SOTA_CONTROL_POINT_WEST_GY ); return true; break; case 191309: case 191310: CaptureControlPoint( SOTA_CONTROL_POINT_SOUTH_GY ); return true; break; } return true; } bool StrandOfTheAncient::HookQuickLockOpen( GameObject *go, Player *player, Spell *spell ){ uint32 entry = go->GetEntry(); if( entry == GO_RELIC ) FinishRound(); return true; } // For banners void StrandOfTheAncient::HookFlagStand(Player* plr, GameObject* obj) { } // time in seconds void StrandOfTheAncient::SetTime( uint32 secs ){ uint32 minutes = secs / TIME_MINUTE; uint32 seconds = secs % TIME_MINUTE; uint32 digits[3]; digits[0] = minutes; digits[1] = seconds / 10; digits[2] = seconds % 10; SetWorldState(WORLDSTATE_SOTA_TIMER_1, digits[0]); SetWorldState(WORLDSTATE_SOTA_TIMER_2, digits[1]); SetWorldState(WORLDSTATE_SOTA_TIMER_3, digits[2]); SetRoundTime(secs); } void StrandOfTheAncient::PrepareRound(){ roundprogress = SOTA_ROUND_PREPARATION; if( BattleRound == 1 ){ Attackers = RandomUInt( 1 ); if( Attackers == TEAM_ALLIANCE ) Defenders = TEAM_HORDE; else Defenders = TEAM_ALLIANCE; }else{ std::swap( Attackers, Defenders ); } for( uint32 i = 0; i < GATE_COUNT; i++ ){ m_gates[ i ]->Rebuild(); m_gates[ i ]->SetFaction( TeamFactions[ Defenders ] ); } m_endgate->Rebuild(); m_endgate->SetFaction( TeamFactions[ Defenders ] ); m_relic->SetFaction( TeamFactions[ Attackers ] ); for( uint32 i = 0; i < GATE_COUNT; i++ ) m_gateTransporters[ i ]->SetFaction( TeamFactions[ Defenders ] ); for( uint32 i = 0; i < SOTA_NUM_CANONS; i++ ){ if( canon[ i ] != NULL ) canon[ i ]->Despawn( 0, 0 ); canon[ i ] = SpawnCreature( 27894, CanonLocations[ i ], TeamFactions[ Defenders ] ); } for( uint32 i = 0; i < SOTA_NUM_DOCK_DEMOLISHERS; i++ ){ Creature *c = demolisher[ i ]; demolisher[ i ] = SpawnCreature( 28781, DemolisherLocations[ i ], TeamFactions[ Attackers ] ); if( c != NULL ) c->Despawn( 0, 0 ); } for( uint32 i = SOTA_WEST_WS_DEMOLISHER_INDEX; i < SOTA_NUM_DEMOLISHERS; i++ ){ if( demolisher[ i ] != NULL ){ demolisher[ i ]->Despawn( 0, 0 ); demolisher[ i ] = NULL; } } SOTACPStates state; if( Attackers == TEAM_ALLIANCE ){ state = SOTA_CP_STATE_HORDE_CONTROL; SetWorldState( WORLDSTATE_SOTA_HORDE_ATTACKER, 0 ); SetWorldState( WORLDSTATE_SOTA_ALLIANCE_ATTACKER, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_ROUND, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_ROUND, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_DEFENSE, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_DEFENSE, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_BEACHHEAD1, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_BEACHHEAD2, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_BEACHHEAD1, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_BEACHHEAD2, 0 ); }else{ state = SOTA_CP_STATE_ALLY_CONTROL; SetWorldState( WORLDSTATE_SOTA_HORDE_ATTACKER, 1 ); SetWorldState( WORLDSTATE_SOTA_ALLIANCE_ATTACKER, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_ROUND, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_ROUND, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_DEFENSE, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_DEFENSE, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_BEACHHEAD1, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_ALLY_BEACHHEAD2, 0 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_BEACHHEAD1, 1 ); SetWorldState( WORLDSTATE_SOTA_SHOW_HORDE_BEACHHEAD2, 1 ); } SpawnControlPoint( SOTA_CONTROL_POINT_EAST_GY, state ); SpawnControlPoint( SOTA_CONTROL_POINT_WEST_GY, state ); SpawnControlPoint( SOTA_CONTROL_POINT_SOUTH_GY, state ); SpawnGraveyard( SOTA_GY_ATTACKER_BEACH, Attackers ); SpawnGraveyard( SOTA_GY_DEFENDER, Defenders ); if( BattleRound == 2 ){ // Teleport players to their place and cast preparation on them m_mainLock.Acquire(); for( std::set< Player* >::iterator itr = m_players[ Attackers ].begin(); itr != m_players[ Attackers ].end(); ++itr ){ Player *p = *itr; p->SafeTeleport( p->GetMapId(), p->GetInstanceID(), sotaAttackerStartingPosition[ 0 ] ); p->CastSpell( p, BG_PREPARATION, true ); } for( std::set< Player* >::iterator itr = m_players[ Defenders ].begin(); itr != m_players[ Defenders ].end(); ++itr ){ Player *p = *itr; p->SafeTeleport( p->GetMapId(), p->GetInstanceID(), sotaDefenderStartingPosition ); p->CastSpell( p, BG_PREPARATION, true ); } m_mainLock.Release(); sEventMgr.AddEvent( this, &StrandOfTheAncient::StartRound, EVENT_SOTA_START_ROUND, 1 * 10 * 1000, 1, 0 ); } }; void StrandOfTheAncient::StartRound(){ roundprogress = SOTA_ROUND_STARTED; m_mainLock.Acquire(); for( std::set< Player* >::iterator itr = m_players[ Attackers ].begin(); itr != m_players[ Attackers ].end(); itr++ ){ Player *p = *itr; p->SafeTeleport( p->GetMapId(), p->GetInstanceID(), sotaAttackerStartingPosition[ SOTA_ROUND_STARTED ] ); p->RemoveAura( BG_PREPARATION ); } m_mainLock.Release(); RemoveAuraFromTeam( Defenders, BG_PREPARATION ); SetWorldState( WORLDSTATE_SOTA_TIMER_1, 10 ); SetTime( ROUND_LENGTH ); sEventMgr.AddEvent( this, &StrandOfTheAncient::TimeTick, EVENT_SOTA_TIMER, MSTIME_SECOND * 5, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT ); UpdatePvPData(); } void StrandOfTheAncient::FinishRound(){ sEventMgr.RemoveEvents( this, EVENT_SOTA_TIMER ); EventResurrectPlayers(); RoundFinishTime[ BattleRound - 1 ] = RoundTime; if( BattleRound == 1 ){ BattleRound = 2; PrepareRound(); }else{ if( RoundFinishTime[ 0 ] < RoundFinishTime[ 1 ] ) Finish( Attackers ); else Finish( Defenders ); } } void StrandOfTheAncient::Finish( uint32 winningteam ){ sEventMgr.RemoveEvents( this ); m_ended = true; m_winningteam = winningteam; uint32 losingteam; if( winningteam == TEAM_ALLIANCE ) losingteam = TEAM_HORDE; else losingteam = TEAM_ALLIANCE; AddHonorToTeam( winningteam, 3 * 185 ); AddHonorToTeam( losingteam, 1 * 185 ); CastSpellOnTeam( m_winningteam, 61213 ); UpdatePvPData(); sEventMgr.AddEvent( TO< CBattleground* >( this ), &CBattleground::Close, EVENT_BATTLEGROUND_CLOSE, 120 * 1000, 1,0 ); } void StrandOfTheAncient::TimeTick(){ SetTime( RoundTime - 5 ); if( RoundTime == 0){ sEventMgr.RemoveEvents(this, EVENT_SOTA_TIMER); FinishRound(); } }; // Not used? void StrandOfTheAncient::HookOnFlagDrop(Player* plr) { } void StrandOfTheAncient::HookFlagDrop(Player* plr, GameObject* obj) { } void StrandOfTheAncient::HookOnShadowSight() { } void StrandOfTheAncient::SpawnControlPoint( SOTAControlPoints point, SOTACPStates state ){ if( state >= MAX_SOTA_CP_STATES ) return; SOTAControlPoint &cp = controlpoint[ point ]; if( cp.worldstate != 0 ) SetWorldState( cp.worldstate, 0 ); uint32 team = TEAM_ALLIANCE; uint32 faction = 0; switch( state ){ case SOTA_CP_STATE_ALLY_CONTROL: team = TEAM_ALLIANCE; faction = 2; break; case SOTA_CP_STATE_HORDE_CONTROL: team = TEAM_HORDE; faction = 1; break; default: return; break; } // First time spawning if( cp.pole == NULL ){ cp.pole = SpawnGameObject( SOTA_FLAGPOLE_ID, FlagPolePositions[ point ], 0, 35, 1.0f ); cp.pole->PushToWorld( m_mapMgr ); }else{ Arcemu::Util::ArcemuAssert( cp.banner != NULL ); cp.banner->Despawn( 0, 0 ); } cp.banner = SpawnGameObject( FlagIDs[ point ][ team ], FlagPositions[ point ], 0, faction, 1.0f ); cp.banner->PushToWorld( m_mapMgr ); cp.state = state; cp.worldstate = CPWorldstates[ point ][ team ]; SetWorldState( cp.worldstate, 1 ); //Spawn graveyard SpawnGraveyard( SOTAGraveyards( uint32( point ) ), team ); } void StrandOfTheAncient::CaptureControlPoint( SOTAControlPoints point ){ if( point >= NUM_SOTA_CONTROL_POINTS ) return; SOTAControlPoint &cp = controlpoint[ point ]; if( cp.banner->GetFaction() == 14 ) return; switch( cp.state ){ case SOTA_CP_STATE_ALLY_CONTROL: SpawnControlPoint( point, SOTA_CP_STATE_HORDE_CONTROL ); PlaySoundToAll( SOUND_HORDE_CAPTURE ); SendChatMessage( CHAT_MSG_BG_EVENT_HORDE, 0, "The horde has captured the %s!", ControlPointNames[ point ] ); break; case SOTA_CP_STATE_HORDE_CONTROL: SpawnControlPoint( point, SOTA_CP_STATE_ALLY_CONTROL ); PlaySoundToAll( SOUND_ALLIANCE_CAPTURE ); SendChatMessage( CHAT_MSG_BG_EVENT_ALLIANCE, 0, "The alliance has captured the %s!", ControlPointNames[ point ] ); break; } cp.banner->SetFaction( 14 ); // So they cannot be recaptured as per SOTA rules //Spawn workshop demolisher switch( point ){ case SOTA_CONTROL_POINT_EAST_GY: demolisher[ SOTA_EAST_WS_DEMOLISHER_INDEX ] = SpawnCreature( 28781, DemolisherLocations[ SOTA_EAST_WS_DEMOLISHER_INDEX ], TeamFactions[ Attackers ] ); break; case SOTA_CONTROL_POINT_WEST_GY: demolisher[ SOTA_WEST_WS_DEMOLISHER_INDEX ] = SpawnCreature( 28781, DemolisherLocations[ SOTA_WEST_WS_DEMOLISHER_INDEX ], TeamFactions[ Attackers ] ); break; } } void StrandOfTheAncient::SpawnGraveyard( SOTAGraveyards gyid, uint32 team ){ if( gyid >= NUM_SOTA_GRAVEYARDS ) return; SOTAGraveyard &gy = graveyard[ gyid ]; gy.faction = team; if( gy.spiritguide != NULL ) gy.spiritguide->Despawn( 0, 0 ); gy.spiritguide = SpawnSpiritGuide( GraveyardLocations[ gyid ], team ); AddSpiritGuide( gy.spiritguide ); }
30.127346
153
0.703671
499453466
3d863b82983aeee62a5aacb13b2ba80e00c330b0
2,932
cc
C++
tests/test_routing_table2.cc
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
13
2019-09-16T13:34:35.000Z
2020-01-13T08:06:17.000Z
tests/test_routing_table2.cc
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
null
null
null
tests/test_routing_table2.cc
telosprotocol/xkad
f3591d5544bf26ba486cb4a7f141d9500422206e
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2019 Telos Foundation & contributors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <stdio.h> #include <string.h> #include <string> #include <memory> #include <fstream> #include <gtest/gtest.h> #include "xpbase/base/top_utils.h" #include "xpbase/base/top_timer.h" #include "xpbase/base/line_parser.h" #include "xpbase/base/kad_key/platform_kadmlia_key.h" #include "xtransport/udp_transport/udp_transport.h" #include "xtransport/src/message_manager.h" #include "node_mgr.h" namespace top { namespace kadmlia { namespace test { class TestRoutingTable2 : public testing::Test { public: static void SetUpTestCase() { mgr1_ = std::make_shared<NodeMgr>(); ASSERT_TRUE(mgr1_->Init(true, "1")); } static void TearDownTestCase() { mgr1_ = nullptr; } virtual void SetUp() {} virtual void TearDown() {} protected: static std::shared_ptr<NodeMgr> mgr1_; }; std::shared_ptr<NodeMgr> TestRoutingTable2::mgr1_; TEST_F(TestRoutingTable2, NatDetect) { auto mgr2 = std::make_shared<NodeMgr>(); ASSERT_TRUE(mgr2->Init(false, "2")); ASSERT_TRUE(mgr2->NatDetect(mgr1_->LocalIp(), mgr1_->RealLocalPort())); mgr2 = nullptr; } TEST_F(TestRoutingTable2, Join) { auto mgr2 = std::make_shared<NodeMgr>(); ASSERT_TRUE(mgr2->Init(false, "3")); ASSERT_TRUE(mgr2->JoinRt(mgr1_->LocalIp(), mgr1_->RealLocalPort())); mgr2 = nullptr; } // handle message TEST_F(TestRoutingTable2, kKadConnectRequest) { transport::protobuf::RoutingMessage message; message.set_type(kKadConnectRequest); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectRequest) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectRequest); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectResponse) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectResponse); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectHandshake2Node) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectHandshake2Node); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectHandshake2Boot) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectHandshake2Boot); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } TEST_F(TestRoutingTable2, kKadNatDetectFinish) { transport::protobuf::RoutingMessage message; message.set_type(kKadNatDetectFinish); base::xpacket_t packet; mgr1_->HandleMessage(message, packet); } } // namespace test } // namespace kadmlia } // namespace top
27.401869
75
0.731924
telosprotocol
3d8b9179a7bc8e45d7a7a15a1fa954ca8e555e82
4,822
cpp
C++
P9/BST/main.cpp
summerwish/DataStructure_homework
7ba86f69edd413643679aba3cf9da5e987b14055
[ "MIT" ]
null
null
null
P9/BST/main.cpp
summerwish/DataStructure_homework
7ba86f69edd413643679aba3cf9da5e987b14055
[ "MIT" ]
null
null
null
P9/BST/main.cpp
summerwish/DataStructure_homework
7ba86f69edd413643679aba3cf9da5e987b14055
[ "MIT" ]
null
null
null
// // main.cpp // BST // // Created by Breezewish on 11/24/14. // Copyright (c) 2014 BW. All rights reserved. // #include <iostream> #include <string> using namespace std; class Node { public: int key; int n; Node* left; Node* right; Node(int k):key(k),n(1),left(NULL),right(NULL){}; }; void insert(Node* &node, int key) { if (node == NULL) { node = new Node(key); return; } if (key < node->key) { insert(node->left, key); } else if (key > node->key) { insert(node->right, key); } else { node->n++; } } Node* find(Node* node, int key) { if (node == NULL) { return NULL; } if (key < node->key) { return find(node->left, key); } else if (key > node->key) { return find(node->right, key); } else { return node; } } void remove(Node* &node, int key) { if (node == NULL) { return; } if (key < node->key) { remove(node->left, key); } else if (key > node->key) { remove(node->right, key); } else { if (node->n > 1) { node->n--; return; } if (node->left == NULL) { Node *temp = node; node = node->right; delete temp; } else if (node->right == NULL) { Node *temp = node; node = node->left; delete temp; } else { Node *min = node->right; while (min->left != NULL) min = min->left; node->key = min->key; node->n = min->n; remove(node->right, min->key); } } } string inorder(Node* node) { string ret = ""; if (node != NULL) { ret += inorder(node->left); for (int i = 0; i < node->n; ++i) { ret += to_string(node->key); ret += " "; } ret += inorder(node->right); } return ret; } const int OP_CREATE = 1; const int OP_INSERT = 2; const int OP_SEARCH = 3; const int OP_DELETE = 4; const int OP_EXIT = 5; #include <vector> #include <sstream> #include <algorithm> #include <iterator> Node* root = NULL; int main(int argc, const char * argv[]) { cout << "Binary Search Tree Demo" << endl; cout << "1 -- Create BST" << endl; cout << "2 -- Insert element" << endl; cout << "3 -- Search element" << endl; cout << "4 -- Delete element" << endl; cout << "5 -- Exit" << endl; int operation; do { string opl; cout << endl; cout << ">> "; getline(cin, opl); operation = stoi(opl); switch (operation) { case OP_CREATE: { cout << "Input initial elements: "; string line; getline(cin, line); vector<int> elements; istringstream iss(line); copy(istream_iterator<int>(iss), istream_iterator<int>(), back_inserter(elements)); for (int i = 0; i < elements.size(); ++i) { insert(root, elements[i]); } cout << endl << "Operation done." << endl; cout << "Inorder Tree: " << inorder(root) << endl; break; } case OP_INSERT: { cout << "Input the element to insert: "; int el; cin >> el; getchar(); insert(root, el); cout << endl << "Operation done." << endl; cout << "Inorder Tree: " << inorder(root) << endl; break; } case OP_SEARCH: { cout << "Input the element to find: "; int el; cin >> el; getchar(); Node* n = find(root, el); if (n == NULL) { cout << "Cannot find element in the tree!" << endl; } else { cout << "Element found in the tree." << endl; } break; } case OP_DELETE: { cout << "Input the element to delete: "; int el; cin >> el; getchar(); remove(root, el); cout << endl << "Operation done." << endl; cout << "Inorder Tree: " << inorder(root) << endl; break; } case OP_EXIT: { break; } default: { cout << "Unknown operation." << endl; break; } } } while (operation != OP_EXIT); cout << "bye!" << endl; return 0; }
24.602041
71
0.421609
summerwish
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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