blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
b0936cbb7391bb97db5d53bfc83600a8f350b8e2
dd5b9eaab20645d35d18986e041bd8db9f349667
/egl-x11.cpp
612502b0e6e408bc08f2b8aa018e62a5946021a3
[ "ISC", "Apache-2.0" ]
permissive
noirmist/sre
d7660cf1d79e4e584ceccef585af6121537d2cac
7f226413c616bcf37fc5dfb39cce8e05c4dc8a42
refs/heads/master
2021-01-15T13:14:26.120402
2015-04-02T11:08:18
2015-04-02T11:08:18
37,549,177
0
0
null
2015-06-16T18:43:00
2015-06-16T18:43:00
null
UTF-8
C++
false
false
3,348
cpp
/* Copyright (c) 2014 Harm Hanemaaijer <fgenfb@yahoo.com> 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. */ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <stdlib.h> #include <math.h> #include <sys/time.h> #include "sre.h" #include "sreBackend.h" #include "gui-common.h" #include "x11-common.h" #include "egl-common.h" class sreBackendGLES2X11 : public sreBackend { public : virtual void Initialize(int *argc, char ***argv, int window_width, int window_height, int& actual_width, int& actual_height, unsigned int backend_flags); virtual void Finalize(); virtual void GLSwapBuffers(); virtual void GLSync(); virtual double GetCurrentTime(); virtual void ProcessGUIEvents(); virtual void ToggleFullScreenMode(int& width, int& height, bool pan_with_mouse); virtual void HideCursor(); virtual void RestoreCursor(); virtual void WarpCursor(int x, int y); }; sreBackend *sreCreateBackendGLES2X11() { sreBackend *b = new sreBackendGLES2X11; b->name = "OpenGL-ES2.0 X11"; return b; } // Functions called from common functions in egl-common.c. void *EGLGetNativeDisplay() { return X11GetDisplay(); } void EGLInitializeSubsystemWindow(int requested_width, int requested_height, int& width, int &height, void *&window) { // Use configured window size. width = requested_width; height = requested_height; X11CreateWindow(width, height, NULL, "SRE OpenGL-ES2.0 X11 demo"); window = (void *)X11GetWindow(); } void EGLDeinitializeSubsystem() { X11DestroyWindow(); X11CloseDisplay(); } // Back-end class implementation. void sreBackendGLES2X11::Initialize(int *argc, char ***argv, int requested_width, int requested_height, int& actual_width, int& actual_height, unsigned int backend_flags) { EGLInitialize(argc, argv, requested_width, requested_height, actual_width, actual_height, backend_flags); } void sreBackendGLES2X11::Finalize() { EGLFinalize(); } void sreBackendGLES2X11::GLSwapBuffers() { EGLSwapBuffers(); } void sreBackendGLES2X11::GLSync() { EGLSync(); } double sreBackendGLES2X11::GetCurrentTime() { struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; } void sreBackendGLES2X11::ProcessGUIEvents() { X11ProcessGUIEvents(); } void sreBackendGLES2X11::ToggleFullScreenMode(int& width, int& height, bool pan_with_mouse) { X11ToggleFullScreenMode(width, height, pan_with_mouse); } void sreBackendGLES2X11::HideCursor() { X11HideCursor(); } void sreBackendGLES2X11::RestoreCursor() { X11RestoreCursor(); } void sreBackendGLES2X11::WarpCursor(int x, int y) { X11WarpCursor(x, y); }
[ "fgenfb@yahoo.com" ]
fgenfb@yahoo.com
84d8901ccf42686d26fe388c87007fc76dc222d0
a65f9b10689fb555608f3742deedad06a87ac03a
/libs/yas/include/yas/types/boost/chrono.hpp
8fd0a8ecb45fc49a049464a2dbef9edf86370b87
[ "MIT" ]
permissive
hanasaan/ofxYas
5cafb7144625b9939e31dc321cd181fd407d0e87
94ccf0ccc6e93c5d35ad20e67a1a3def238c8f57
refs/heads/master
2021-04-29T16:34:28.190797
2020-09-28T10:52:25
2020-09-28T10:52:25
121,653,426
7
1
null
null
null
null
UTF-8
C++
false
false
3,628
hpp
// Copyright (c) 2010-2017 niXman (i dot nixman dog gmail dot com). All // rights reserved. // // This file is part of YAS(https://github.com/niXman/yas) project. // // 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) // // // // Boost Software License - Version 1.0 - August 17th, 2003 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef __yas__types__boost__boost_chrono_serializers_hpp #define __yas__types__boost__boost_chrono_serializers_hpp #if defined(YAS_SERIALIZE_BOOST_TYPES) #include <yas/detail/type_traits/type_traits.hpp> #include <yas/detail/type_traits/serializer.hpp> #include <yas/detail/io/serialization_exception.hpp> #include <boost/ratio/ratio_fwd.hpp> #include <boost/chrono/duration.hpp> #include <boost/chrono/system_clocks.hpp> namespace yas { namespace detail { /***************************************************************************/ template<std::size_t F, typename R, typename P> struct serializer< type_prop::not_a_fundamental, ser_method::use_internal_serializer, F, boost::chrono::duration<R, P> > { template<typename Archive> static Archive& save(Archive& ar, const boost::chrono::duration<R, P> &d) { ar.write(d.count()); return ar; } template<typename Archive> static Archive& load(Archive& ar, boost::chrono::duration<R, P> &d) { R count{}; ar.read(count); d = boost::chrono::duration<R, P>(count); return ar; } }; /***************************************************************************/ template<std::size_t F, typename C, typename D> struct serializer< type_prop::not_a_fundamental, ser_method::use_internal_serializer, F, boost::chrono::time_point<C, D> > { template<typename Archive> static Archive& save(Archive& ar, const boost::chrono::time_point<C, D> &t) { ar & t.time_since_epoch(); return ar; } template<typename Archive> static Archive& load(Archive& ar, boost::chrono::time_point<C, D> &t) { D duration{}; ar & duration; t = boost::chrono::time_point<C, D>(duration); return ar; } }; /***************************************************************************/ } // namespace detail } // namespace yas #endif // defined(YAS_SERIALIZE_BOOST_TYPES) #endif // __yas__types__boost__boost_chrono_serializers_hpp
[ "yuya@rhizomatiks.com" ]
yuya@rhizomatiks.com
d15cd337bdf7838ff50e627001c0591184deece4
361722e937bb17bf1a3959297dacdfc501fe2fe8
/src/Robot_Type_I/Robot_Type_I.h
672e2bec5941e21d696ededaceef90692c27b82e
[]
no_license
loomplyty/Robots
60d61615914bce64c22f0b4c8def0f16bce4e9b9
2b64893228ad8b7e946bc28ff1f8c104502dd8ba
refs/heads/master
2020-05-29T12:29:22.639308
2017-04-18T07:47:43
2017-04-18T07:47:43
35,534,203
0
0
null
2015-05-13T07:19:35
2015-05-13T07:19:35
null
UTF-8
C++
false
false
9,518
h
#ifndef ROBOT_III_H #define ROBOT_III_H #include <aris.h> #include <Robot_Base.h> #include <Robot_Gait.h> namespace Robots { class RobotTypeI; class LegI :public Robots::LegBase { public: auto partAt(std::size_t id)->aris::dynamic::Part& { return *prt_array_[id]; }; auto markerAt(std::size_t id)->aris::dynamic::Marker& { return *mak_array_[id]; }; auto jointAt(std::size_t id)->aris::dynamic::Joint& { return *jnt_array_[id]; }; auto motionAt(std::size_t id)->aris::dynamic::Motion& { return *mot_array_[id];}; auto forceAt(std::size_t id)->aris::dynamic::SingleComponentForce& { return static_cast<aris::dynamic::SingleComponentForce&>(*fce_array_[id]); }; auto p1a()->aris::dynamic::Part& { return static_cast<aris::dynamic::Part&>(*p1a_); }; auto p2a()->aris::dynamic::Part& { return static_cast<aris::dynamic::Part&>(*p2a_); }; auto p3a()->aris::dynamic::Part& { return static_cast<aris::dynamic::Part&>(*p3a_); }; auto thigh()->aris::dynamic::Part& { return static_cast<aris::dynamic::Part&>(*thigh_); }; auto p2b()->aris::dynamic::Part& { return static_cast<aris::dynamic::Part&>(*p2b_); }; auto p3b()->aris::dynamic::Part& { return static_cast<aris::dynamic::Part&>(*p3b_); }; auto u1i()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*u1i_); }; auto u1j()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*u1j_); }; auto u2i()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*u2i_); }; auto u2j()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*u2j_); }; auto u3i()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*u3i_); }; auto u3j()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*u3j_); }; auto p1i()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*p1i_); }; auto p1j()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*p1j_); }; auto p2i()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*p2i_); }; auto p2j()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*p2j_); }; auto p3i()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*p3i_); }; auto p3j()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*p3j_); }; auto sfi()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*sfi_); }; auto sfj()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*sfj_); }; auto s2i()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*s2i_); }; auto s2j()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*s2j_); }; auto s3i()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*s3i_); }; auto s3j()->aris::dynamic::Marker& { return static_cast<aris::dynamic::Marker&>(*s3j_); }; auto u1()->aris::dynamic::UniversalJoint& { return static_cast<aris::dynamic::UniversalJoint&>(*u1_); }; auto u2()->aris::dynamic::UniversalJoint& { return static_cast<aris::dynamic::UniversalJoint&>(*u2_); }; auto u3()->aris::dynamic::UniversalJoint& { return static_cast<aris::dynamic::UniversalJoint&>(*u3_); }; auto p1()->aris::dynamic::TranslationalJoint& { return static_cast<aris::dynamic::TranslationalJoint&>(*p1_); }; auto p2()->aris::dynamic::TranslationalJoint& { return static_cast<aris::dynamic::TranslationalJoint&>(*p2_); }; auto p3()->aris::dynamic::TranslationalJoint& { return static_cast<aris::dynamic::TranslationalJoint&>(*p3_); }; auto sf()->aris::dynamic::SphericalJoint& { return static_cast<aris::dynamic::SphericalJoint&>(*sf_); }; auto s2()->aris::dynamic::SphericalJoint& { return static_cast<aris::dynamic::SphericalJoint&>(*s2_); }; auto s3()->aris::dynamic::SphericalJoint& { return static_cast<aris::dynamic::SphericalJoint&>(*s3_); }; auto m1()->aris::dynamic::SingleComponentMotion& { return static_cast<aris::dynamic::SingleComponentMotion&>(*m1_); }; auto m2()->aris::dynamic::SingleComponentMotion& { return static_cast<aris::dynamic::SingleComponentMotion&>(*m2_); }; auto m3()->aris::dynamic::SingleComponentMotion& { return static_cast<aris::dynamic::SingleComponentMotion&>(*m3_); }; auto f1()->aris::dynamic::SingleComponentForce& { return static_cast<aris::dynamic::SingleComponentForce&>(*f1_); }; auto f2()->aris::dynamic::SingleComponentForce& { return static_cast<aris::dynamic::SingleComponentForce&>(*f2_); }; auto f3()->aris::dynamic::SingleComponentForce& { return static_cast<aris::dynamic::SingleComponentForce&>(*f3_); }; void GetdJacOverPee(double *dJi_x, double *dJi_y, double *dJi_z, const char *relativeCoordinate="G")const; private: LegI(const char *Name, RobotTypeI* pRobot); virtual ~LegI() = default; void FastDyn(); void GetFin(double *fIn) const; void GetFinDyn(double *fIn) const; void GetFinFrc(double *fIn) const; virtual void calculate_from_pEE(); virtual void calculate_from_pIn(); virtual void calculate_from_vEE(); virtual void calculate_from_vIn(); virtual void calculate_from_aEE(); virtual void calculate_from_aIn(); virtual void calculate_jac(); virtual void calculate_diff_jac(); void _CalCdByPos(); void _CalCdByPlen(); void _CalCdByPlen2(); void _CalVarByCd(); void _CalPartByVar(); void _CalVcdByVpos(); void _CalVcdByVplen(); void _CalVvarByVcd(); void _CalVpartByVvar(); void _CalAcdByApos(); void _CalAcdByAplen(); void _CalAvarByAcd(); void _CalApartByAvar(); private: typedef aris::dynamic::Part* PartPtr; union { PartPtr prt_array_[6]; struct { PartPtr p1a_, p2a_, p3a_, thigh_, p2b_, p3b_; }; }; typedef aris::dynamic::Marker* MarkerPtr; union { MarkerPtr mak_array_[18]; struct { MarkerPtr u1i_, u1j_, u2i_, u2j_, u3i_, u3j_; MarkerPtr p1i_, p1j_, p2i_, p2j_, p3i_, p3j_; MarkerPtr sfi_, sfj_, s2i_, s2j_, s3i_, s3j_; }; }; typedef aris::dynamic::Joint* JointPtr; union { JointPtr jnt_array_[9]; struct { JointPtr u1_, u2_, u3_, p1_, p2_, p3_, sf_, s2_, s3_; }; }; typedef aris::dynamic::Motion* MotionPtr; union { MotionPtr mot_array_[3]; struct { MotionPtr m1_, m2_, m3_; }; }; typedef aris::dynamic::Force* ForcePtr; union { ForcePtr fce_array_[3]; struct { ForcePtr f1_, f2_, f3_; }; }; union { double fIn_dyn[3]; struct { double f1_dyn; double f2_dyn; double f3_dyn; }; }; union { double fIn_frc[3]; struct { double f1_frc; double f2_frc; double f3_frc; }; }; private: RobotTypeI *pRobot; const double U2x{ 0 }, U2y{ 0 }, U2z{ 0 }, U3x{ 0 }, U3y{ 0 }, U3z{ 0 }; const double S2x{ 0 }, S2y{ 0 }, S2z{ 0 }, S3x{ 0 }, S3y{ 0 }, S3z{ 0 }; const double Sfx{ 0 }, Sfy{ 0 }, Sfz{ 0 }; const double D1{ 0 }, H1{ 0 }, D2{ 0 }, H2{ 0 }; double a1, b1, va1, vb1, aa1, ab1; double x2, y2, z2, x3, y3, z3; double a2, b2, a3, b3; double sa1, ca1, sb1, cb1, sa2, ca2, sb2, cb2, sa3, ca3, sb3, cb3; double pa1, qa1, pb1, qb1, pa2, qa2, pb2, qb2, pa3, qa3, pb3, qb3; double vx2, vy2, vz2, vx3, vy3, vz3; double va2, vb2, va3, vb3; double ax2, ay2, az2, ax3, ay3, az3; double aa2, ab2, aa3, ab3; double H11, H12, H21, H22; double k21, k22, k23, k31, k32, k33; double vk21, vk22, vk23, vk31, vk32, vk33; double J1[3][3], J2[3][3], vJ1[3][3], vJ2[3][3]; double inv_J1[3][3], inv_J2[3][3]; double _C[36][36]; double _c_M[36][4]; friend class RobotTypeI; }; class RobotTypeI :public Robots::RobotBase { public: RobotTypeI(); ~RobotTypeI() = default; virtual auto loadXml(const aris::core::XmlElement &xml_ele)->void override; virtual auto saveXml(aris::core::XmlElement &xml_ele)const->void override; using Model::loadXml; using Model::saveXml; void GetFin(double *Fin) const; void GetFinDyn(double *Fin) const; void GetFinFrc(double *Fin) const; void FastDyn(); virtual void dyn()override; void SetFixFeet(const char* fix_feet); const char* FixFeet() const; void SetActiveMotion(const char* active_motion); const char* ActiveMotion() const; virtual void kinFromPin()override { double Pin[18]; for (int i = 0; i < 18; ++i) { Pin[i] = motionPool().at(i).motPos(); } double pe[6]; this->GetPeb(pe); SetPinFixFeet(Pin, FixFeet(), ActiveMotion(), pe); }; virtual void kinFromVin()override { double Vin[18]; for (int i = 0; i < 18; ++i) { Vin[i] = motionPool().at(i).motVel(); } SetVinFixFeet(Vin, FixFeet(), ActiveMotion()); }; auto simToAdams(const std::string &adams_file, const aris::dynamic::PlanFunc &fun, const aris::dynamic::PlanParamBase &param, int ms_dt)->aris::dynamic::SimResult; public: union { struct { LegI *const pLF; LegI *const pLM; LegI *const pLR; LegI *const pRF; LegI *const pRM; LegI *const pRR; }; LegI *const pLegs[6]; }; private: LegI LF_Leg{ "LF", this }; LegI LM_Leg{ "LM", this }; LegI LR_Leg{ "LR", this }; LegI RF_Leg{ "RF", this }; LegI RM_Leg{ "RM", this }; LegI RR_Leg{ "RR", this }; friend class LegI; }; } #endif
[ "tianyuan_123abc@sjtu.edu.cn" ]
tianyuan_123abc@sjtu.edu.cn
984f708fc70441822f06bd699d1934acaf9bfbf9
72af4ae88195e8b3ea3aa763a87d30b6e0602161
/src/wallet.cpp
af201f94674c070f78891151d8886af80d27fb2c
[ "MIT" ]
permissive
rivercoin/facilecoin-core
2374f29acd6c692796a434b9a4b42a5355d58a82
0cb393087f2a8aa2122a6c9a2aca4d487a20c580
refs/heads/master
2021-01-09T06:35:11.827404
2016-05-25T19:32:03
2016-05-25T19:32:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
77,948
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The FacileCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "base58.h" #include "checkpoints.h" #include "coincontrol.h" #include "net.h" #include "script/script.h" #include "script/sign.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include <assert.h> #include <boost/algorithm/string/replace.hpp> #include <boost/thread.hpp> using namespace std; /** * Settings */ CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE); CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE; unsigned int nTxConfirmTarget = 1; bool bSpendZeroConfChange = true; bool fSendFreeTransactions = false; bool fPayAtLeastCustomFee = true; /** * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) * Override with -mintxfee */ CFeeRate CWallet::minTxFee = CFeeRate(1000); /** @defgroup mapWallet * * @{ */ struct CompareValueOnly { bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1, const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; std::string COutput::ToString() const { return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue)); } const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const { LOCK(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash); if (it == mapWallet.end()) return NULL; return &(it->second); } CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); assert(secret.VerifyPubKey(pubkey)); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; // check if we need to remove from watch-only CScript script; script = GetScriptForDestination(pubkey.GetID()); if (HaveWatchOnly(script)) RemoveWatchOnly(script); if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::LoadCScript(const CScript& redeemScript) { /* A sanity check was added in pull #3843 to avoid adding redeemScripts * that never can be redeemed. However, old wallets may still contain * these. Do not add them to the wallet and warn. */ if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) { std::string strAddr = CFacileCoinAddress(CScriptID(redeemScript)).ToString(); LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); return true; } return CCryptoKeyStore::AddCScript(redeemScript); } bool CWallet::AddWatchOnly(const CScript &dest) { if (!CCryptoKeyStore::AddWatchOnly(dest)) return false; nTimeFirstKey = 1; // No birthday information for watch-only keys. NotifyWatchonlyChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteWatchOnly(dest); } bool CWallet::RemoveWatchOnly(const CScript &dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveWatchOnly(dest)) return false; if (!HaveWatchOnly()) NotifyWatchonlyChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseWatchOnly(dest)) return false; return true; } bool CWallet::LoadWatchOnly(const CScript &dest) { return CCryptoKeyStore::AddWatchOnly(dest); } bool CWallet::Unlock(const SecureString& strWalletPassphrase) { CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) continue; // try another master key if (CCryptoKeyStore::Unlock(vMasterKey)) return true; } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } set<uint256> CWallet::GetConflicts(const uint256& txid) const { set<uint256> result; AssertLockHeld(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid); if (it == mapWallet.end()) return result; const CWalletTx& wtx = it->second; std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range; BOOST_FOREACH(const CTxIn& txin, wtx.vin) { if (mapTxSpends.count(txin.prevout) <= 1) continue; // No conflict if zero or one spends range = mapTxSpends.equal_range(txin.prevout); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) result.insert(it->second); } return result; } void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) { // We want all the wallet transactions in range to have the same metadata as // the oldest (smallest nOrderPos). // So: find smallest nOrderPos: int nMinOrderPos = std::numeric_limits<int>::max(); const CWalletTx* copyFrom = NULL; for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; int n = mapWallet[hash].nOrderPos; if (n < nMinOrderPos) { nMinOrderPos = n; copyFrom = &mapWallet[hash]; } } // Now copy data from copyFrom to rest: for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; CWalletTx* copyTo = &mapWallet[hash]; if (copyFrom == copyTo) continue; copyTo->mapValue = copyFrom->mapValue; copyTo->vOrderForm = copyFrom->vOrderForm; // fTimeReceivedIsTxTime not copied on purpose // nTimeReceived not copied on purpose copyTo->nTimeSmart = copyFrom->nTimeSmart; copyTo->fFromMe = copyFrom->fFromMe; copyTo->strFromAccount = copyFrom->strFromAccount; // nOrderPos not copied on purpose // cached members not copied on purpose } } /** * Outpoint is spent if any non-conflicted transaction * spends it: */ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const { const COutPoint outpoint(hash, n); pair<TxSpends::const_iterator, TxSpends::const_iterator> range; range = mapTxSpends.equal_range(outpoint); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) { const uint256& wtxid = it->second; std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid); if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) return true; // Spent } return false; } void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) { mapTxSpends.insert(make_pair(outpoint, wtxid)); pair<TxSpends::iterator, TxSpends::iterator> range; range = mapTxSpends.equal_range(outpoint); SyncMetaData(range); } void CWallet::AddToSpends(const uint256& wtxid) { assert(mapWallet.count(wtxid)); CWalletTx& thisTx = mapWallet[wtxid]; if (thisTx.IsCoinBase()) // Coinbases don't spend anything! return; BOOST_FOREACH(const CTxIn& txin, thisTx.vin) AddToSpends(txin.prevout, wtxid); } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { assert(!pwalletdbEncryption); pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) { delete pwalletdbEncryption; pwalletdbEncryption = NULL; return false; } pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) { pwalletdbEncryption->TxnAbort(); delete pwalletdbEncryption; } // We now probably have half of our keys encrypted in memory, and half not... // die and let the user reload their unencrypted wallet. assert(false); } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) { delete pwalletdbEncryption; // We now have keys encrypted in memory, but not on disk... // die to avoid confusion and let the user reload their unencrypted wallet. assert(false); } delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { AssertLockHeld(cs_wallet); // mapWallet CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) { uint256 hash = wtxIn.GetHash(); if (fFromLoadWallet) { mapWallet[hash] = wtxIn; mapWallet[hash].BindWallet(this); AddToSpends(hash); } else { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { int64_t latestNow = wtx.nTimeReceived; int64_t latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64_t latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry *const pacentry = (*it).second.second; int64_t nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime(); wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString(), wtxIn.hashBlock.ToString()); } AddToSpends(hash); } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } } //// debug print LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; // Break debit/credit balance caches: wtx.MarkDirty(); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if ( !strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } return true; } /** * Add a transaction to the wallet, or update it. * pblock is optional, but should be provided if the transaction is known to be in a block. * If fUpdate is true, existing transactions will be updated. */ bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { { AssertLockHeld(cs_wallet); bool fExisted = mapWallet.count(tx.GetHash()) != 0; if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(*pblock); return AddToWallet(wtx); } } return false; } void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock) { LOCK2(cs_main, cs_wallet); if (!AddToWalletIfInvolvingMe(tx, pblock, true)) return; // Not one of ours // If a transaction changes 'conflicted' state, that changes the balance // available of the outputs it spends. So force those to be // recomputed, also: BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mapWallet.count(txin.prevout.hash)) mapWallet[txin.prevout.hash].MarkDirty(); } } void CWallet::EraseFromWallet(const uint256 &hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } isminetype CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsMine(prev.vout[txin.prevout.n]); } } return ISMINE_NO; } CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n]) & filter) return prev.vout[txin.prevout.n].nValue; } } return 0; } bool CWallet::IsChange(const CTxOut& txout) const { // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a script that is ours, but is not in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (::IsMine(*this, txout.scriptPubKey)) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) return true; LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; return n ? n : nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(list<COutputEntry>& listReceived, list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const { nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: CAmount nDebit = GetDebit(filter); if (nDebit > 0) // debit>0 means we signed/sent this transaction { CAmount nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. for (unsigned int i = 0; i < vout.size(); ++i) { const CTxOut& txout = vout[i]; isminetype fIsMine = pwallet->IsMine(txout); // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (nDebit > 0) { // Don't report 'change' txouts if (pwallet->IsChange(txout)) continue; } else if (!(fIsMine & filter)) continue; // In either case, we need to get the destination address CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString()); address = CNoDestination(); } COutputEntry output = {address, txout.nValue, (int)i}; // If we are debited by the transaction, add the output as a "sent" entry if (nDebit > 0) listSent.push_back(output); // If we are receiving the output, add it as a "received" entry if (fIsMine & filter) listReceived.push_back(output); } } void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const { nReceived = nSent = nFee = 0; CAmount allFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (strAccount == strSentAccount) { BOOST_FOREACH(const COutputEntry& s, listSent) nSent += s.amount; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH(const COutputEntry& r, listReceived) { if (pwallet->mapAddressBook.count(r.destination)) { map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination); if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) nReceived += r.amount; } else if (strAccount.empty()) { nReceived += r.amount; } } } } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } /** * Scan the block chain (starting in pindexStart) for transactions * from or to us. If fUpdate is true, found transactions that already * exist in the wallet will be updated. */ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; int64_t nNow = GetTime(); CBlockIndex* pindex = pindexStart; { LOCK2(cs_main, cs_wallet); // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) pindex = chainActive.Next(pindex); ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false); double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false); while (pindex) { if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; ReadBlockFromDisk(block, pindex); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = chainActive.Next(pindex); if (GetTime() >= nNow + 60) { nNow = GetTime(); LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex)); } } ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI } return ret; } void CWallet::ReacceptWalletTransactions() { LOCK2(cs_main, cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { const uint256& wtxid = item.first; CWalletTx& wtx = item.second; assert(wtx.GetHash() == wtxid); int nDepth = wtx.GetDepthInMainChain(); if (!wtx.IsCoinBase() && nDepth < 0) { // Try to add to memory pool LOCK(mempool.cs); wtx.AcceptToMemoryPool(false); } } } void CWalletTx::RelayWalletTransaction() { if (!IsCoinBase()) { if (GetDepthInMainChain() == 0) { LogPrintf("Relaying wtx %s\n", GetHash().ToString()); RelayTransaction((CTransaction)*this); } } } set<uint256> CWalletTx::GetConflicts() const { set<uint256> result; if (pwallet != NULL) { uint256 myHash = GetHash(); result = pwallet->GetConflicts(myHash); result.erase(myHash); } return result; } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. if (GetTime() < nNextResend) return; bool fFirst = (nNextResend == 0); nNextResend = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time if (nTimeBestReceived < nLastResend) return; nLastResend = GetTime(); // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(); } } } /** @} */ // end of mapWallet /** @defgroup Actions * * @{ */ CAmount CWallet::GetBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetUnconfirmedBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetImmatureBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureCredit(); } } return nTotal; } CAmount CWallet::GetWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetImmatureWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureWatchOnlyCredit(); } } return nTotal; } /** * populate vCoins with vector of available COutputs. */ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const uint256& wtxid = it->first; const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < 0) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { isminetype mine = IsMine(pcoin->vout[i]); if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO && !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO)); } } } } static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, vector<char>& vfBest, CAmount& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); CAmount nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng is fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<CAmount>::max(); coinLowestLarger.second.first = NULL; vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue; CAmount nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); BOOST_FOREACH(const COutput &output, vCoins) { if (!output.fSpendable) continue; const CWalletTx *pcoin = output.tx; if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs)) continue; int i = output.i; CAmount n = pcoin->vout[i].nValue; pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; CAmount nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } LogPrint("selectcoins", "SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first)); LogPrint("selectcoins", "total %s\n", FormatMoney(nBest)); } return true; } bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const { vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH(const COutput& out, vCoins) { if(!out.fSpendable) continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet))); } bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl) { CAmount nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend) { if (nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } nValue += s.second; } if (vecSend.empty() || nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } wtxNew.fTimeReceivedIsTxTime = true; wtxNew.BindWallet(this); CMutableTransaction txNew; { LOCK2(cs_main, cs_wallet); { nFeeRet = 0; while (true) { txNew.vin.clear(); txNew.vout.clear(); wtxNew.fFromMe = true; CAmount nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend) { CTxOut txout(s.second, s.first); if (txout.IsDust(::minRelayTxFee)) { strFailReason = _("Transaction amount too small"); return false; } txNew.vout.push_back(txout); } // Choose coins to use set<pair<const CWalletTx*,unsigned int> > setCoins; CAmount nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl)) { strFailReason = _("Insufficient funds"); return false; } BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CAmount nCredit = pcoin.first->vout[pcoin.second].nValue; //The coin age after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. //But mempool inputs might still be in the mempool, so their age stays 0 int age = pcoin.first->GetDepthInMainChain(); if (age != 0) age += 1; dPriority += (double)nCredit * age; } CAmount nChange = nValueIn - nValue - nFeeRet; if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-facilecoin-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange = GetScriptForDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; bool ret; ret = reservekey.GetReservedKey(vchPubKey); assert(ret); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); } CTxOut newTxOut(nChange, scriptChange); // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust(::minRelayTxFee)) { nFeeRet += nChange; reservekey.ReturnKey(); } else { // Insert change txn at random position: vector<CTxOut>::iterator position = txNew.vout.begin()+GetRandInt(txNew.vout.size()+1); txNew.vout.insert(position, newTxOut); } } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, txNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } // Embed the constructed transaction data in wtxNew. *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew); // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strFailReason = _("Transaction too large"); return false; } dPriority = wtxNew.ComputePriority(dPriority, nBytes); // Can we complete this as a free transaction? if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) { // Not enough fee: enough priority? double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget); // Not enough mempool history to estimate: use hard-coded AllowFree. if (dPriorityNeeded <= 0 && AllowFree(dPriority)) break; // Small enough, and priority high enough, to send for free if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded) break; } CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) { strFailReason = _("Transaction too large for fee policy"); return false; } if (nFeeRet >= nFeeNeeded) break; // Done, enough fee included. // Include more fee and try again. nFeeRet = nFeeNeeded; continue; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl) { vector< pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl); } /** * Call after CreateTransaction unless you want to abort */ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Notify that old coins are spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid"); return false; } wtxNew.RelayWalletTransaction(); } return true; } CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool) { // payTxFee is user-set "I want to pay this much" CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes); // user selected total at least (default=true) if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK()) nFeeNeeded = payTxFee.GetFeePerK(); // User didn't set: use -txconfirmtarget to estimate... if (nFeeNeeded == 0) nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes); // ... unless we don't have enough mempool data, in which case fall // back to a hard-coded fee if (nFeeNeeded == 0) nFeeNeeded = minTxFee.GetFee(nTxBytes); // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes)) nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes); // But always obey the maximum if (nFeeNeeded > maxTxFee) nFeeNeeded = maxTxFee; return nFeeNeeded; } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); uiInterface.LoadWallet(this); return DB_LOAD_OK; } DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx) { if (!fFileBacked) return DB_LOAD_OK; DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx); if (nZapWalletTxRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // that requires a new key. } } if (nZapWalletTxRet != DB_LOAD_OK) return nZapWalletTxRet; return DB_LOAD_OK; } bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose) { bool fUpdated = false; { LOCK(cs_wallet); // mapAddressBook std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address); fUpdated = mi != mapAddressBook.end(); mapAddressBook[address].name = strName; if (!strPurpose.empty()) /* update purpose only if requested */ mapAddressBook[address].purpose = strPurpose; } NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO, strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) ); if (!fFileBacked) return false; if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CFacileCoinAddress(address).ToString(), strPurpose)) return false; return CWalletDB(strWalletFile).WriteName(CFacileCoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBook(const CTxDestination& address) { { LOCK(cs_wallet); // mapAddressBook if(fFileBacked) { // Delete destdata tuples associated with address std::string strAddress = CFacileCoinAddress(address).ToString(); BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata) { CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); } } mapAddressBook.erase(address); } NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED); if (!fFileBacked) return false; CWalletDB(strWalletFile).ErasePurpose(CFacileCoinAddress(address).ToString()); return CWalletDB(strWalletFile).EraseName(CFacileCoinAddress(address).ToString()); } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } /** * Mark old keypool keys as used, * and generate all new keys */ bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int kpSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; if (kpSize > 0) nTargetSize = kpSize; else nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %d\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %d\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() { map<CTxDestination, CAmount> balances; { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set< set<CTxDestination> > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet set< set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (pcoin->vin.size() > 0) { bool any_mine = false; // group all input addresses with each other BOOST_FOREACH(CTxIn txin, pcoin->vin) { CTxDestination address; if(!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); any_mine = true; } // group change with input addresses if (any_mine) { BOOST_FOREACH(CTxOut txout, pcoin->vout) if (IsChange(txout)) { CTxDestination txoutAddr; if(!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } } if (grouping.size() > 0) { groupings.insert(grouping); grouping.clear(); } } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it BOOST_FOREACH(set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set< set<CTxDestination>* > hits; map< CTxDestination, set<CTxDestination>* >::iterator it; BOOST_FOREACH(CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH(set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH(CTxDestination element, *merged) setmap[element] = merged; } set< set<CTxDestination> > ret; BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const { LOCK(cs_wallet); set<CTxDestination> result; BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second.name; if (strName == strAccount) result.insert(address); } return result; } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } void CWallet::UpdatedTransaction(const uint256 &hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) NotifyTransactionChanged(this, hashTx, CT_UPDATED); } } void CWallet::LockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { AssertLockHeld(cs_wallet); // setLockedCoins COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { AssertLockHeld(cs_wallet); // setLockedCoins for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } } /** @} */ // end of Actions class CAffectedKeysVisitor : public boost::static_visitor<void> { private: const CKeyStore &keystore; std::vector<CKeyID> &vKeys; public: CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {} void Process(const CScript &script) { txnouttype type; std::vector<CTxDestination> vDest; int nRequired; if (ExtractDestinations(script, type, vDest, nRequired)) { BOOST_FOREACH(const CTxDestination &dest, vDest) boost::apply_visitor(*this, dest); } } void operator()(const CKeyID &keyId) { if (keystore.HaveKey(keyId)) vKeys.push_back(keyId); } void operator()(const CScriptID &scriptId) { CScript script; if (keystore.GetCScript(scriptId, script)) Process(script); } void operator()(const CNoDestination &none) {} }; void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH(const CKeyID &keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx &wtx = (*it).second; BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH(const CTxOut &txout, wtx.vout) { // iterate over all their outputs CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey); BOOST_FOREACH(const CKeyID &keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off } bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value) { if (boost::get<CNoDestination>(&dest)) return false; mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteDestData(CFacileCoinAddress(dest).ToString(), key, value); } bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key) { if (!mapAddressBook[dest].destdata.erase(key)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).EraseDestData(CFacileCoinAddress(dest).ToString(), key); } bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value) { mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); return true; } bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const { std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest); if(i != mapAddressBook.end()) { CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key); if(j != i->second.destdata.end()) { if(value) *value = j->second; return true; } } return false; } CKeyPool::CKeyPool() { nTime = GetTime(); } CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn) { nTime = GetTime(); vchPubKey = vchPubKeyIn; } CWalletKey::CWalletKey(int64_t nExpires) { nTimeCreated = (nExpires ? GetTime() : 0); nTimeExpires = nExpires; } int CMerkleTx::SetMerkleBranch(const CBlock& block) { AssertLockHeld(cs_main); CBlock blockTmp; // Update the tx's hashBlock hashBlock = block.GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++) if (block.vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)block.vtx.size()) { vMerkleBranch.clear(); nIndex = -1; LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = block.GetMerkleBranch(nIndex); // Is the tx in a block that's in the main chain BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; const CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const { AssertLockHeld(cs_main); int nResult = GetDepthInMainChainINTERNAL(pindexRet); if (nResult == 0 && !mempool.exists(GetHash())) return -1; // Not in chain, not in mempool return nResult; } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee) { CValidationState state; return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee); }
[ "fcn@facilecoin.org" ]
fcn@facilecoin.org
41883279f880bbb28d58b6917c2fe47c2127db52
4d31cccd4ef81252f2ccda50638f348d71d202a4
/Team_Training/15、2019-hdu-multi-4/code/1007.cpp
db3bf029141f602815162cfe26fa384475278e7b
[]
no_license
FZU-GummyBear/Dream
9a104b917d32d6d333811a2311b5d2c976d51d10
460cfc3db912e38f4ef9dc447238cfcc60fe0b01
refs/heads/master
2020-04-28T00:48:17.089644
2020-04-19T12:22:20
2020-04-19T12:22:20
174,829,686
18
7
null
null
null
null
UTF-8
C++
false
false
1,773
cpp
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define pb push_back #define mp make_pair #define per(i, a, b) for(int i = (b) - 1; i >= (a); --i) #define rep(i, a, b) for(int i = (a); i < (b); ++i) #define de(x) cout << #x << " = " << x << endl #define dd(x) cout << #x << " = " << x << " " #define endl "\n" #define pw(x) (1ll<<(x)) #define all(x) x.begin(), x.end() #define sz(x) (int)x.size() typedef __int128 ll; typedef pair<int, int> pii; typedef double db; typedef vector<int> vi; map<ll, int> dis; int pre[16]; int find(int x) { return x == pre[x] ? x : pre[x] = find(pre[x]); } void join(int x, int y) { x = find(x); y = find(y); pre[x] = y; } ll get(int a[]) { ll ans = 0; rep(i, 0, 16) ans = ans * 16 + a[i]; return ans; } void print(int a[]) { int return ; rep(i, 0, 16) cout << a[i] << " \n"[i == 15]; cout << endl; } void print(ll x) { if(x < 0) de("ERR"); } bool check(int i, int j) { if(abs(i - j) == 4) return 1; if(i / 4 == j / 4 && abs(i % 4 - j % 4) == 1) return 1; return 0; } int C = 120; int main() { // std::ios::sync_with_stdio(0); // std::cin.tie(0); vector<ll> que; int a[16]; rep(i, 0, 16) a[i] = (i + 1) % 16; ll u = get(a); dis[u] = 0; que.pb(u); rep(i, 0, sz(que)) { ll u = que[i]; int D = dis[u]; de(D); if(D >= C) continue; int p = 15; ll x = u; while(p >= 0) { a[p] = x % 16; x /= 16; --p; } print(a, D); rep(j, 0, 16) if(!a[j]) p = j; rep(j, 0, 16) if(j != p && check(p, j)) { swap(a[p], a[j]); ll v = get(a); if(!dis.count(v)) { dis[v] = D + 1; que.pb(v); } swap(a[p], a[j]); } } int T; cin >> T; while(T--) { rep(i, 0, 16) cin >> a[i]; ll u = get(a); cout << (dis.count(u) ? "Yes" : "No") << endl; } return 0; }
[ "jslijin2016@qq.com" ]
jslijin2016@qq.com
cdb69f1a7ea9bb9f06712ff60d05ff9377e2fbcd
66e1b48e66e8e00a047071257a8058eefbebe8cd
/less_functor.h
f821ce1b412a6f678fcd673373e3a9a4fe450b13
[]
no_license
feghalim/ucd-csci2312-pa5
6cbd8d99b3e54bfd6b444d721e7258262d2b80bd
96817d0336715b53326eae2973ad9b32079fbf0f
refs/heads/master
2021-01-14T14:18:39.842399
2016-05-06T17:08:18
2016-05-06T17:08:18
58,165,790
0
0
null
2016-05-05T22:58:46
2016-05-05T22:58:45
C++
UTF-8
C++
false
false
558
h
// // Created by Mario on 5/5/2016. // #ifndef UCD_CSCI2312_PA5_LESS_FUNCTOR_H #define UCD_CSCI2312_PA5_LESS_FUNCTOR_H #endif //UCD_CSCI2312_PA5_LESS_FUNCTOR_H namespace CS2312 { template <typename T> class less { public: bool operator()(const T &lhs, const T &rhs) { return lhs < rhs;}; }; template <> class less<const char*> { public: bool operator()(const char * lhs, const char * rhs) { string _a, _b; _a = lhs; _b = rhs; return (_a < _b); }; }; }
[ "mibikin@gmail.com" ]
mibikin@gmail.com
8bba5a46d38df5f42af158d058ef1e7fa1ce9313
ce59981300bff0317ef393b84261856656710ef8
/graph.hpp
e7f7cb753f5e03973d44acea3bb5909867f9a2b1
[]
no_license
postbacc/graphs
6148161c29414cd38a2283824839ffb9b0b277fa
876681901827043e3427b101f5dfc417e422a566
refs/heads/master
2020-03-11T10:21:29.413356
2018-11-19T22:41:46
2018-11-19T22:41:46
129,940,396
0
3
null
2018-11-19T22:41:47
2018-04-17T17:20:52
C++
UTF-8
C++
false
false
7,913
hpp
#ifndef __graph_h__ #define __graph_h__ #include <vector> #include <set> #include <string> // Node colors are described at the bottom of the file. #define WHITE 1 #define GRAY 2 #define BLACK 3 // Edge types are described at the bottom of the file. #define UNDISCOVERED_EDGE 9 #define TREE_EDGE 10 #define BACK_EDGE 11 #define FORWARD_EDGE 12 #define CROSS_EDGE 13 using namespace std; // forward declarations so Graph understands class Node; class Edge; class Graph { private: bool directed; vector<Node*> nodes; vector<Edge*> edges; // The next two vectors may be used in your search algorithms. vector<Edge*> search_edges; vector<Node*> search_nodes; // The clock is used to set discovery/finish times. Increment it by // one every time a Node color changes to GRAY or BLACK. int clock; public: // The first block of public members are implemented for you. Graph(); ~Graph(); vector<Node*> getNodes(); vector<Edge*> getEdges(); int getClock(); void addNode(Node& n); void addEdge(Edge& e); void removeNode(Node& n); void removeEdge(Edge& e); bool isDirected(); void setDirected(bool val); set<Edge*> getAdjacentEdges(Node& n); friend std::ostream &operator << (std::ostream& out, Graph graph); // clear resets all nodes to have WHITE color, with -1 discovery and // finish times and rank. Resets all edges to type // UNDISCOVERED_EDGE. It resets the graph clock to 0. void clear(); // tick is an OPTIONAL debugging method. Use this after every time // you increment the clock. You might pass in a string // to describe what just happened. If you are having trouble, // consider using this function as a place to track your algorithm's // progress. Print out your graph on each tick. If you want to get // very fancy, you can output your graph in 'dot' format. This is // the same format we used in the B-Tree assignment for debugging. // // This function is 100% optional, though. void tick(string message); // dfs(start) runs a depth-first search from the indicated start // node, and explores all reachable nodes. This ignores unreachable // nodes. When this function returns, all explored nodes are colored // BLACK, all unreachable nodes are WHITE. All explored nodes have // correct discovery/exit time information. All edges have correct // edge types (unfollowed edges should remain UNDISCOVERED). // // For a DFS, mark nodes GRAY when we first discover them, and BLACK // when we exit (finish) them. void dfs(Node& start); // bfs(start) runs a breadth-first search starting from the given // node. It sets the 'rank' value on all nodes to something // appropriate: -1 for unreachable nodes, 0 for the start node, 1 // for nodes that are one edge from the start node, and so forth. // // For a BFS, mark nodes GRAY when they are enqueued, and BLACK when // they are dequeued. void bfs(Node& start); // bfs(start, target) has the same requirements as the other version // of `bfs`, except this one stops after the target node is // reached. If found, the target node should be marked BLACK, and // its rank should be correctly set on exit. If it is not found, the // target node should remain WHITE with a rank of -1. void bfs(Node& start, Node& target); }; class Node { private: string data; int color; // WHITE, GRAY, or BLACK. int discovery_time; // clock value when the node was discovered by search. int completion_time; // clock value when node was completely finished. int rank; // Number of steps from source node in a BFS. 0 // means it was the source node. Node* predecessor; // The predecessor node in the spanning tree. public: // Public Node members in this block are implemented for you. Node(string s); ~Node(); string getData(); void setData(string s); void setRank(int rank); friend std::ostream &operator << (std::ostream& out, Node node); // Public Node methods to implement are below here. // clear sets the color to WHITE, the discovery/finish time and rank // to -1, and sets the predecessor to NULL. void clear(); // setColor sets the 'color' of a node. Be sure to set the // appropriate time variable depending on what the new color is: set // discovery_time if the node is now GRAY, and completion_time if // the node is now BLACK. If it is now WHITE, this should be // equivalent to calling clear(). void setColor(int search_color, int time); // getDiscoveryInformation gets the color, discovery time, and // finish time to 'color', 'disco_time', 'finish_time', and // 'bfs_rank' respectively. // // 'disco_time' and 'finish_time' are only meaningful if the search // was dfs (though there is no reason to not use these for debugging // purposes). // // 'bfs_rank' is only meaningful if bfs was the most recent search. // // By the way, these parameters are called 'output parameters', or // 'out params' because they serve as the output of the function. void getDiscoveryInformation(int& color, int& disco_time, int& finish_time, int& bfs_rank); // isAncestor returns true if the given node is reachable by // traversing the other node's predecessor list. It is like // searching through a linked list. You can do this iteratively // (with a cursor) or recursively by calling isAncestor on non-null // predecessors. Try it both ways and impress your friends. bool isAncestor(Node& other); // Sets the predecessor node in the spanning tree. The predecessor // node was the node that we were exploring when we first discovered // a node (e.g. it was WHITE when we found it). void setPredecessor(Node& other); }; class Edge { private: Node* a; // start node Node* b; // end node int type; // one of the edge types defined in graph.hpp public: Edge(Node& n1, Node& n2); ~Edge(); int getType(); Node* getStart(); Node* getEnd(); void setWeight(float val); friend std::ostream &operator << (std::ostream& out, Edge edge); // Set the edge type to the given value (see edge type #define // statements). void setType(int edge_type); }; #endif /* Node color tells us if we have discovered a node, if we're in the middle of finishing a node, or if we've finished a node. They are: WHITE: Node has not yet been reached by the search. GRAY: Node has been reached by the search but is not yet complete. BLACK: Node has been completely explored. Edge type tells us information about how the path was discovered during a depth-first search, and it also might give us valuable information about the shape of the graph. There are four kinds of edges, though it is not necessary to use all of them all of the time. They are: TREE: A tree edge from A to B indicates that B was discovered via A. BACK: A back edge from C to A indicates that A was discovered before C, and C was discovered while A was still being explored. FORWARD: A forward edge from A to C indicates that C was completely examined when we found it, and A is an ancestor of C in the DFS spanning tree. CROSS: A cross edge from A to C indicates the C was completely examined when we found it, and A is NOT an ancestor of C in the DFS spanning tree. These edge types are summarized graphically at http://en.wikipedia.org/wiki/Depth-first_search and does a much better job than words can do. To determine edge types, you need to use both the discovery information (the color of the ending node) and the predecessor information (to distinguish between Cross and Forward edges). Tree edges are when the end node is white. Back edges are when the end node is gray. Forward and cross edges are when the end node is black. If the start node is an ancestor of the end node, it is a forward edge. Otherwise it is a cross edge. */
[ "gabe@blankslatesystems.com" ]
gabe@blankslatesystems.com
4306cdfb36d7070800845a911efd268c829e56d8
c2497a68c41632ff41ac1f4b8868648582d1bed4
/simulation/photoconversion/src/PrimaryGeneratorAction.cpp
04300d4ef4cb3ffb92b447530771f9b5a68e7f66
[]
no_license
rwestenberger/MicroMegas-Simulation
30c872ced6f1ceae760b81bbcf55518791e7057d
5c28b88c221fc42bdd14161fcd240b4105200c21
refs/heads/master
2021-01-15T15:27:25.901477
2016-06-29T15:27:18
2016-06-29T15:27:18
43,747,181
7
4
null
2018-02-01T15:40:58
2015-10-06T11:46:19
C++
UTF-8
C++
false
false
1,612
cpp
#include "PrimaryGeneratorAction.hpp" #include "G4LogicalVolumeStore.hh" #include "G4LogicalVolume.hh" #include "G4Box.hh" #include "G4RunManager.hh" #include "G4ParticleGun.hh" #include "G4ParticleTable.hh" #include "G4ParticleDefinition.hh" #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" #include "Randomize.hh" PrimaryGeneratorAction::PrimaryGeneratorAction() : G4VUserPrimaryGeneratorAction(), fParticleGun(0) { G4int n_particle = 1; fParticleGun = new G4ParticleGun(n_particle); // default particle kinematic G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable(); G4ParticleDefinition* particle = particleTable->FindParticle("gamma"); fParticleGun->SetParticleDefinition(particle); fParticleGun->SetParticleMomentumDirection(G4ThreeVector(0.,0.,-1.)); fParticleGun->SetParticleEnergy(200.*keV); } PrimaryGeneratorAction::~PrimaryGeneratorAction() { delete fParticleGun; } void PrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent) { G4double x0 = 0, y0 = 0; /*[[[cog from MMconfig import * cog.outl("G4double z0 = {}*cm + {}*cm + {}*cm + {}*cm + 1*mm;".format( conf["photoconversion"]["z_cathode"], conf["detector"]["cathode_thickness"], conf["detector"]["shield_thickness"], conf["detector"]["shield_cover_thickness"] )) ]]]*/ G4double z0 = 3.*cm + 4.e-4*cm + .5*cm + 4.e-4*cm + 1*mm; //[[[end]]] fParticleGun->SetParticlePosition(G4ThreeVector(x0,y0,z0)); /* G4double angle = G4UniformRand()*pi; fParticleGun->SetParticleMomentumDirection(G4ThreeVector(0,0,1).rotateX(angle)); */ fParticleGun->GeneratePrimaryVertex(anEvent); }
[ "rwestenb@students.uni-mainz.de" ]
rwestenb@students.uni-mainz.de
671e23e0da2afec1d3a4227fe77fef9182308ea5
0b793bce2da8c3d09b7956c0672ddbffd46feaed
/aoj/20/aoj2011.cpp
f2c7abafa1d802f9af820014b3a2b67efc6e201b
[ "MIT" ]
permissive
knuu/competitive-programming
c6c4e08fb231937d988bdc5a60a8ad6b31b97616
16bc68fdaedd6f96ae24310d697585ca8836ab6e
refs/heads/master
2021-01-17T09:39:02.647688
2020-11-07T03:17:22
2020-11-07T03:17:22
27,886,732
1
0
null
null
null
null
UTF-8
C++
false
false
1,180
cpp
#include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> P; typedef pair<ll, ll> Pll; typedef vector<int> Vi; typedef tuple<int, int, int> T; #define FOR(i,s,x) for(int i=s;i<(int)(x);i++) #define REP(i,x) FOR(i,0,x) #define ALL(c) c.begin(), c.end() #define DUMP( x ) cerr << #x << " = " << ( x ) << endl const int dr[4] = {-1, 0, 1, 0}; const int dc[4] = {0, 1, 0, -1}; int N; bool s[50][50]; bool check() { REP(i, N) { bool flag = true; REP(j, N) flag &= s[i][j]; if (flag) return true; } return false; } int main() { // use scanf in CodeForces! cin.tie(0); ios_base::sync_with_stdio(false); while (true) { cin >> N; if (N == 0) break; Vi edge[30]; REP(i, N) { int c; cin >> c; REP(j, c) { int k; cin >> k; k--; edge[k].push_back(i); } } REP(i, N) fill(s[i], s[i] + N, false); REP(d, 30) { for (int i : edge[d]) { for (int j : edge[d]) { s[i][j] = true; REP(k, N) s[i][k] |= s[j][k]; } } if (check()) { cout << d + 1 << endl; break; } else if (d == 29) { cout << -1 << endl; break; } } } return 0; }
[ "premier3next@gmail.com" ]
premier3next@gmail.com
de30e87afda84603dc89ab4a434144aacac7c86e
3106397a9ede72b504719ee0088406dbcfff3e2f
/software/tractor/ros_lib/ram_modify_trajectory/GetPosesFromLayersList.h
e51d76ea2c8b1c1cf7008d9dc8f920c33b2acb6b
[ "MIT" ]
permissive
rje1974/Proyecto-Pochito
a9f60f711bd2f5187ca6173ed0b34df67389158f
3bb7cfd159a3c24e5cef3523d51e3ee2c54be7d0
refs/heads/master
2021-06-29T03:17:08.377252
2020-11-21T20:27:38
2020-11-21T20:27:38
192,087,298
2
1
null
null
null
null
UTF-8
C++
false
false
5,184
h
#ifndef _ROS_SERVICE_GetPosesFromLayersList_h #define _ROS_SERVICE_GetPosesFromLayersList_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "ram_msgs/AdditiveManufacturingPose.h" namespace ram_modify_trajectory { static const char GETPOSESFROMLAYERSLIST[] = "ram_modify_trajectory/GetPosesFromLayersList"; class GetPosesFromLayersListRequest : public ros::Msg { public: uint32_t layer_level_list_length; typedef uint32_t _layer_level_list_type; _layer_level_list_type st_layer_level_list; _layer_level_list_type * layer_level_list; GetPosesFromLayersListRequest(): layer_level_list_length(0), layer_level_list(NULL) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; *(outbuffer + offset + 0) = (this->layer_level_list_length >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->layer_level_list_length >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->layer_level_list_length >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->layer_level_list_length >> (8 * 3)) & 0xFF; offset += sizeof(this->layer_level_list_length); for( uint32_t i = 0; i < layer_level_list_length; i++){ *(outbuffer + offset + 0) = (this->layer_level_list[i] >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->layer_level_list[i] >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->layer_level_list[i] >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->layer_level_list[i] >> (8 * 3)) & 0xFF; offset += sizeof(this->layer_level_list[i]); } return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t layer_level_list_lengthT = ((uint32_t) (*(inbuffer + offset))); layer_level_list_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); layer_level_list_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); layer_level_list_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->layer_level_list_length); if(layer_level_list_lengthT > layer_level_list_length) this->layer_level_list = (uint32_t*)realloc(this->layer_level_list, layer_level_list_lengthT * sizeof(uint32_t)); layer_level_list_length = layer_level_list_lengthT; for( uint32_t i = 0; i < layer_level_list_length; i++){ this->st_layer_level_list = ((uint32_t) (*(inbuffer + offset))); this->st_layer_level_list |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); this->st_layer_level_list |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); this->st_layer_level_list |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->st_layer_level_list); memcpy( &(this->layer_level_list[i]), &(this->st_layer_level_list), sizeof(uint32_t)); } return offset; } const char * getType(){ return GETPOSESFROMLAYERSLIST; }; const char * getMD5(){ return "679d154e8037a273f18c70341905eba3"; }; }; class GetPosesFromLayersListResponse : public ros::Msg { public: uint32_t poses_length; typedef ram_msgs::AdditiveManufacturingPose _poses_type; _poses_type st_poses; _poses_type * poses; GetPosesFromLayersListResponse(): poses_length(0), poses(NULL) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; *(outbuffer + offset + 0) = (this->poses_length >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->poses_length >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->poses_length >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->poses_length >> (8 * 3)) & 0xFF; offset += sizeof(this->poses_length); for( uint32_t i = 0; i < poses_length; i++){ offset += this->poses[i].serialize(outbuffer + offset); } return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t poses_lengthT = ((uint32_t) (*(inbuffer + offset))); poses_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); poses_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); poses_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->poses_length); if(poses_lengthT > poses_length) this->poses = (ram_msgs::AdditiveManufacturingPose*)realloc(this->poses, poses_lengthT * sizeof(ram_msgs::AdditiveManufacturingPose)); poses_length = poses_lengthT; for( uint32_t i = 0; i < poses_length; i++){ offset += this->st_poses.deserialize(inbuffer + offset); memcpy( &(this->poses[i]), &(this->st_poses), sizeof(ram_msgs::AdditiveManufacturingPose)); } return offset; } const char * getType(){ return GETPOSESFROMLAYERSLIST; }; const char * getMD5(){ return "f6ccb95f5843381777dba4bb5d0e3f7d"; }; }; class GetPosesFromLayersList { public: typedef GetPosesFromLayersListRequest Request; typedef GetPosesFromLayersListResponse Response; }; } #endif
[ "juaneduardoriva@gmail.com" ]
juaneduardoriva@gmail.com
1979546b1cc661979e15e422fc383030f0ed7313
c780a2df884dcace0ae5bfa8a20ac00039807c80
/1.4/test1-9.cpp
ea78d8072bd840723741b338f0942997f911402e
[ "MIT" ]
permissive
xiaolei-shuai/cpp-primer-learning
e4d7b5bddd466b76744fa36dcad3ce50daf48169
ad66899d8e2db1b296b46163a3d6b426a8500bbf
refs/heads/master
2022-11-27T05:06:59.230730
2020-07-26T13:48:01
2020-07-26T13:48:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include <iostream> int main(){ int sum = 0, val = 50; while (val <= 100){ sum += val; ++val; } std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl; return 0; }
[ "abc1870819884@163.com" ]
abc1870819884@163.com
81c48cb479b1a9af38e577ae0b32baaaab98fd2d
fd7a802ff482231123b6adb48b3f5fa11bdc406b
/hud.cpp
a266c3c198e05a829ecb6a4d3dac2c959ba67bfe
[]
no_license
erikhallin/Kragzhor
7ffff43836b72fbe7be6c0fb257f9eeba320baf4
54d68ce57228285997d9783a8847bea5717ceab4
refs/heads/master
2020-07-03T05:18:52.404002
2019-08-11T17:44:19
2019-08-11T17:44:19
201,796,415
0
0
null
null
null
null
UTF-8
C++
false
false
4,909
cpp
#include "hud.h" hud::hud() { //ctor } bool hud::init(int texture,int screen_size[2],int font_texture[3],int tex_hud_health) { m_player_health_rel=1; m_score=0; m_texture=texture; m_tex_hud_health=tex_hud_health; m_screen_size[0]=screen_size[0]; m_screen_size[1]=screen_size[1]; m_tex_font[0]=font_texture[0]; m_tex_font[1]=font_texture[1]; m_tex_font[2]=font_texture[2]; m_noise_prog=0; m_won=false; m_end=false; //init score display int disp_x=m_screen_size[0]*0.65; int disp_y=m_screen_size[1]*0.06; int disp_width=m_screen_size[0]*0.3; int disp_height=m_screen_size[1]*0.05; m_disp_score=display(disp_x,disp_y,disp_width,disp_height,10,m_tex_font,0); disp_x=m_screen_size[0]*0.33; disp_y=m_screen_size[1]*0.90; disp_width=m_screen_size[0]*0.5; disp_height=m_screen_size[1]*0.04; m_disp_message_won=display(disp_x,disp_y,disp_width,disp_height,27,m_tex_font, "THE VILLAGE HAS BEEN SLAIN"); m_disp_message_won.setting_flags(false); m_disp_message_lost=display(disp_x,disp_y,disp_width,disp_height,27,m_tex_font," KRAGZHOR HAS BEEN SLAIN "); m_disp_message_lost.setting_flags(false); return true; } bool hud::update(float player_health_rel) { m_player_health_rel=player_health_rel; m_noise_prog+=_time_step*0.01; if(m_noise_prog>=1.0) m_noise_prog-=1; return true; } bool hud::draw(void) { glPushMatrix(); //m_disp_message_won.draw_display(); //m_disp_message_lost.draw_display(); //m_disp_score.draw_display(); if(m_end) { //draw text if(m_won) m_disp_message_won.draw_display(); else m_disp_message_lost.draw_display(); //draw score m_disp_score.draw_display(); } else { //draw health bar float bar_height=(float)m_screen_size[1]*0.045; float bar_width =(float)m_screen_size[0]*0.294; float bar_pos_x =(float)m_screen_size[0]*0.5-bar_width*0.5; float bar_pos_y =(float)m_screen_size[1]*0.9; //background /*glColor3f(0.2,0.2,0.2); glBegin(GL_QUADS); glVertex2f(bar_pos_x,bar_pos_y); glVertex2f(bar_pos_x,bar_pos_y+bar_height); glVertex2f(bar_pos_x+bar_width,bar_pos_y+bar_height); glVertex2f(bar_pos_x+bar_width,bar_pos_y); glEnd();*/ //health float tex_x=0.25+0.25*cosf(m_noise_prog*3.0*_pi); float tex_y=0.25+0.25*sinf(m_noise_prog*6.0*_pi); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,m_texture); //glEnable(GL_BLEND); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor3f(0.7,0.3,0.3); glBegin(GL_QUADS); glTexCoord2f(tex_x*(m_player_health_rel), tex_y); glVertex2f(bar_pos_x+(1.0-m_player_health_rel)*bar_width*0.5, bar_pos_y); glTexCoord2f(tex_x*(m_player_health_rel), tex_y+0.5); glVertex2f(bar_pos_x+(1.0-m_player_health_rel)*bar_width*0.5, bar_pos_y+bar_height); glTexCoord2f(tex_x*(m_player_health_rel)+0.5*(m_player_health_rel), tex_y+0.5); glVertex2f(bar_pos_x+(1.0+m_player_health_rel)*bar_width*0.5, bar_pos_y+bar_height); glTexCoord2f(tex_x*(m_player_health_rel)+0.5*(m_player_health_rel), tex_y); glVertex2f(bar_pos_x+(1.0+m_player_health_rel)*bar_width*0.5, bar_pos_y); glEnd(); //bar bar_height=(float)m_screen_size[1]*0.05; bar_width =(float)m_screen_size[0]*0.3; bar_pos_x =(float)m_screen_size[0]*0.5-bar_width*0.5; bar_pos_y =(float)m_screen_size[1]*0.9; glBindTexture(GL_TEXTURE_2D,m_tex_hud_health); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor3f(1.0,1.0,1.0); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex2f(bar_pos_x, bar_pos_y); glTexCoord2f(0,1); glVertex2f(bar_pos_x, bar_pos_y+bar_height); glTexCoord2f(1,1); glVertex2f(bar_pos_x+bar_width, bar_pos_y+bar_height); glTexCoord2f(1,0); glVertex2f(bar_pos_x+bar_width, bar_pos_y); glEnd(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); //draw score m_disp_score.draw_display(); } glPopMatrix(); /*glBegin(GL_QUADS); glVertex2f(0,0); glVertex2f(0,0+m_screen_size[1]); glVertex2f(0+m_screen_size[0],0+m_screen_size[1]); glVertex2f(0+m_screen_size[0],0); glEnd();*/ return true; } bool hud::add_score(int score_addition) { m_score+=score_addition; //update display m_disp_score.set_value(m_score); return true; } bool hud::end(bool won) { m_end=true; m_won=won; return true; }
[ "erik-hallin@hotmail.com" ]
erik-hallin@hotmail.com
f5b83a951be104e8919f5b0e133f1193b96b1580
1b22474d3c143a9d39106ab9c8543938534eacae
/Homework-2/Map.cpp
a652e9d524175ad027b1dadb1f361a033a506023
[]
no_license
monilpat/CS-32
2ce90ae5d311532ae06726f61a795b8b3e4e4c31
075b65b199885783cb9d6a16edf9e3aabc0ec448
refs/heads/master
2021-01-10T06:09:35.325280
2016-03-24T20:25:04
2016-03-24T20:25:04
54,517,541
0
1
null
null
null
null
UTF-8
C++
false
false
6,850
cpp
// // Map.cpp // CS32Homework2 // // Created by Monil Patel on 1/28/16. // Copyright © 2016 Monil Patel. All rights reserved. // // Map.cpp #include "Map.h" Map::Map() : m_size(0) { // create dummy node m_head = new Node; m_head->m_next = m_head; m_head->m_prev = m_head; } Map::~Map() { // Delete the m_size non-dummy nodes plus the dummy node for (Node* p = m_head->m_prev ; m_size >= 0; m_size--) { Node* toBeDeleted = p; p = p->m_prev; delete toBeDeleted; } } Map::Map(const Map& other) : m_size(other.m_size) { // Create dummy node; don't initialize its pointers m_head = new Node; // Initialize prev to last node created Node* prev = m_head; // Copy each non-dummy node from the other list; each iteration will set // the m_next of the previous node copied for (Node* p = other.m_head->m_next ; p != other.m_head; p = p->m_next) { // Create a copy of the node p points to Node* pnew = new Node; pnew->m_key = p->m_key; pnew->m_value = p->m_value; // Connect the new node to the previous one pnew->m_prev = prev; prev->m_next = pnew; // Reset prev to last node created prev = pnew; } // Connect last node created to m_head m_head->m_prev = prev; prev->m_next = m_head; } Map& Map::operator=(const Map& rhs) { if (this != &rhs) { Map temp(rhs); swap(temp); } return *this; } bool Map::erase(const KeyType& key) { Node* p = find(key); if (p == m_head) // not found return false; // unlink the node from the list and destroy it p->m_prev->m_next = p->m_next; p->m_next->m_prev = p->m_prev; delete p; m_size--; return true; } bool Map::get(const KeyType& key, ValueType& value) const { Node* p = find(key); if (p == m_head) // not found return false; value = p->m_value; return true; } bool Map::get(int i, KeyType& key, ValueType& value) const { if (i < 0 || i >= m_size) return false; // Return the key and value at position i. This is one way of ensuring // the required behavior of get: If the Map doesn't change in the // interim, // * calling get with each i in 0 <= i < size() gets each of the // Map pairs, and // * calling get with the same value of i each time gets the same pair. // If i is closer to the head of the list, go forward to reach that // position; otherwise, start from tail and go backward. Node* p; if (i < m_size / 2) // closer to head { p = m_head->m_next; for (int k = 0; k != i; k++) p = p->m_next; } else // closer to tail { p = m_head->m_prev; for (int k = m_size-1; k != i; k--) p = p->m_prev; } key = p->m_key; value = p->m_value; return true; } void Map::swap(Map& other) { // swap head pointers Node* tempHead = m_head; m_head = other.m_head; other.m_head = tempHead; // swap sizes int t = m_size; m_size = other.m_size; other.m_size = t; } Map::Node* Map::find(const KeyType& key) const { // Do a linear search through the list Node* p; for (p = m_head->m_next; p != m_head && p->m_key != key; p = p->m_next) ; return p; } bool Map::doInsertOrUpdate(const KeyType& key, const ValueType& value, bool mayInsert, bool mayUpdate) { Node* p = find(key); if (p != m_head) // found { if (mayUpdate) p->m_value = value; return mayUpdate; } if (!mayInsert) // not found, and not allowed to insert return false; // Create a new node p = new Node; p->m_key = key; p->m_value = value; // Insert new item at tail of list (arbitrary choice of position) // Connect it to tail p->m_prev = m_head->m_prev; p->m_prev->m_next = p; // Connect it to dummy node p->m_next = m_head; m_head->m_prev = p; m_size++; return true; } bool combine(const Map& m1, const Map& m2, Map& result) { // For better performance, the bigger map should be the basis for // the result, and we should iterate over the elements of the // smaller one, adjusting the result as required. const Map* bigger; const Map* smaller; if (m1.size() >= m2.size()) { bigger = &m1; smaller = &m2; } else { bigger = &m2; smaller = &m1; } // Guard against the case that result is an alias for m1 or m2 // (i.e., that result is a reference to the same map that m1 or m2 // refers to) by building the answer in a local variable res. When // done, swap res with result; the old value of result (now in res) will // be destroyed when res is destroyed. bool status = true; Map res(*bigger); // res starts as a copy of the bigger map for (int n = 0; n < smaller->size(); n++) // for each pair in smaller { KeyType k; ValueType vsmall; smaller->get(n, k, vsmall); ValueType vbig; if (!res.get(k, vbig)) // key in smaller doesn't appear in bigger res.insert(k, vsmall); // so add it to res else if (vbig != vsmall) // same key, different value { // so pair shouldn't be in res res.erase(k); status = false; } } result.swap(res); return status; } void subtract(const Map& m1, const Map& m2, Map& result) { // Guard against the case that result is an alias for m1 or m2 // (i.e., that result is a reference to the same map that m1 or m2 // refers to) by building the answer in a local variable res. When // done, swap res with result; the old value of result (now in res) will // be destroyed when res is destroyed. if (m1.size() <= m2.size()) { // If m1 is smaller, if an item in m1 should be in the result because // its key is not in m2, add it Map res; for (int n = 0; n < m1.size(); n++) { KeyType k; ValueType v; m1.get(n, k, v); if (!m2.contains(k)) res.insert(k, v); } result.swap(res); } else { // If m1 is larger, copy it to the result and remove from result // keys that are in m2 Map res(m1); for (int n = 0; n < m2.size(); n++) { KeyType k; ValueType v; m2.get(n, k, v); res.erase(k); } result.swap(res); } }
[ "monilpat@gmail.com" ]
monilpat@gmail.com
965f05e2f5ecceecefde30a6b060efa8a04b3c2c
7e48d392300fbc123396c6a517dfe8ed1ea7179f
/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/MaterialExpression.gen.cpp
ac21e873b806c15ce40540249f85beda4c142448
[]
no_license
WestRyanK/Rodent-VR
f4920071b716df6a006b15c132bc72d3b0cba002
2033946f197a07b8c851b9a5075f0cb276033af6
refs/heads/master
2021-06-14T18:33:22.141793
2020-10-27T03:25:33
2020-10-27T03:25:33
154,956,842
1
1
null
2018-11-29T09:56:21
2018-10-27T11:23:11
C++
UTF-8
C++
false
false
61,464
cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "Engine/Classes/Materials/MaterialExpression.h" #include "Serialization/StructuredArchive.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeMaterialExpression() {} // Cross Module References ENGINE_API UScriptStruct* Z_Construct_UScriptStruct_FExpressionOutput(); UPackage* Z_Construct_UPackage__Script_Engine(); ENGINE_API UScriptStruct* Z_Construct_UScriptStruct_FMaterialAttributesInput(); ENGINE_API UScriptStruct* Z_Construct_UScriptStruct_FExpressionInput(); ENGINE_API UClass* Z_Construct_UClass_UMaterialExpression_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UMaterialExpression(); COREUOBJECT_API UClass* Z_Construct_UClass_UObject(); ENGINE_API UClass* Z_Construct_UClass_UMaterialFunction_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UMaterial_NoRegister(); COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FGuid(); ENGINE_API UClass* Z_Construct_UClass_UEdGraphNode_NoRegister(); // End Cross Module References struct Z_Construct_UScriptStruct_FExpressionOutput_Statics { struct FExpressionOutput { FName OutputName; #if WITH_EDITORONLY_DATA int32 Mask; int32 MaskR; int32 MaskG; int32 MaskB; int32 MaskA; #endif // WITH_EDITORONLY_DATA }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Struct_MetaDataParams[]; #endif #if WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaskA_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaskA; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaskB_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaskB; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaskG_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaskG; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaskR_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaskR; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Mask_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_Mask; #endif // WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_OutputName_MetaData[]; #endif static const UE4CodeGen_Private::FNamePropertyParams NewProp_OutputName; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_EDITORONLY_DATA #endif // WITH_EDITORONLY_DATA static const UE4CodeGen_Private::FStructParams ReturnStructParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionOutput_Statics::Struct_MetaDataParams[] = { { "Comment", "/** Struct that represents an expression's output. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Struct that represents an expression's output." }, }; #endif #if WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskA_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskA = { "MaskA", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionOutput, MaskA), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskA_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskA_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskB_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskB = { "MaskB", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionOutput, MaskB), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskB_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskB_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskG_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskG = { "MaskG", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionOutput, MaskG), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskG_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskG_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskR_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskR = { "MaskR", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionOutput, MaskR), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskR_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskR_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_Mask_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_Mask = { "Mask", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionOutput, Mask), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_Mask_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_Mask_MetaData)) }; #endif // WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_OutputName_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FNamePropertyParams Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_OutputName = { "OutputName", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionOutput, OutputName), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_OutputName_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_OutputName_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UScriptStruct_FExpressionOutput_Statics::PropPointers[] = { #if WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskA, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskB, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskG, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_MaskR, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_Mask, #endif // WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionOutput_Statics::NewProp_OutputName, }; const UE4CodeGen_Private::FStructParams Z_Construct_UScriptStruct_FExpressionOutput_Statics::ReturnStructParams = { (UObject* (*)())Z_Construct_UPackage__Script_Engine, nullptr, nullptr, "ExpressionOutput", sizeof(FExpressionOutput), alignof(FExpressionOutput), Z_Construct_UScriptStruct_FExpressionOutput_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionOutput_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, EStructFlags(0x00000008), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionOutput_Statics::Struct_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionOutput_Statics::Struct_MetaDataParams)) }; UScriptStruct* Z_Construct_UScriptStruct_FExpressionOutput() { #if WITH_HOT_RELOAD extern uint32 Get_Z_Construct_UScriptStruct_FExpressionOutput_Hash(); UPackage* Outer = Z_Construct_UPackage__Script_Engine(); static UScriptStruct* ReturnStruct = FindExistingStructIfHotReloadOrDynamic(Outer, TEXT("ExpressionOutput"), sizeof(Z_Construct_UScriptStruct_FExpressionOutput_Statics::FExpressionOutput), Get_Z_Construct_UScriptStruct_FExpressionOutput_Hash(), false); #else static UScriptStruct* ReturnStruct = nullptr; #endif if (!ReturnStruct) { UE4CodeGen_Private::ConstructUScriptStruct(ReturnStruct, Z_Construct_UScriptStruct_FExpressionOutput_Statics::ReturnStructParams); } return ReturnStruct; } uint32 Get_Z_Construct_UScriptStruct_FExpressionOutput_Hash() { return 3778394203U; } struct Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics { struct FExpressionInput { #if WITH_EDITORONLY_DATA UMaterialExpression* Expression; #endif // WITH_EDITORONLY_DATA int32 OutputIndex; #if WITH_EDITORONLY_DATA FName InputName; int32 Mask; int32 MaskR; int32 MaskG; int32 MaskB; int32 MaskA; #endif // WITH_EDITORONLY_DATA FName ExpressionName; }; struct FMaterialAttributesInput : public FExpressionInput { int32 PropertyConnectedBitmask; }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Struct_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_PropertyConnectedBitmask_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_PropertyConnectedBitmask; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const UE4CodeGen_Private::FStructParams ReturnStructParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::Struct_MetaDataParams[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::NewProp_PropertyConnectedBitmask_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::NewProp_PropertyConnectedBitmask = { "PropertyConnectedBitmask", nullptr, (EPropertyFlags)0x0010000000002000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FMaterialAttributesInput, PropertyConnectedBitmask), METADATA_PARAMS(Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::NewProp_PropertyConnectedBitmask_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::NewProp_PropertyConnectedBitmask_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::NewProp_PropertyConnectedBitmask, }; const UE4CodeGen_Private::FStructParams Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::ReturnStructParams = { (UObject* (*)())Z_Construct_UPackage__Script_Engine, Z_Construct_UScriptStruct_FExpressionInput, nullptr, "MaterialAttributesInput", sizeof(FMaterialAttributesInput), alignof(FMaterialAttributesInput), Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, EStructFlags(0x00000008), METADATA_PARAMS(Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::Struct_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::Struct_MetaDataParams)) }; UScriptStruct* Z_Construct_UScriptStruct_FMaterialAttributesInput() { #if WITH_HOT_RELOAD extern uint32 Get_Z_Construct_UScriptStruct_FMaterialAttributesInput_Hash(); UPackage* Outer = Z_Construct_UPackage__Script_Engine(); static UScriptStruct* ReturnStruct = FindExistingStructIfHotReloadOrDynamic(Outer, TEXT("MaterialAttributesInput"), sizeof(Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::FMaterialAttributesInput), Get_Z_Construct_UScriptStruct_FMaterialAttributesInput_Hash(), false); #else static UScriptStruct* ReturnStruct = nullptr; #endif if (!ReturnStruct) { UE4CodeGen_Private::ConstructUScriptStruct(ReturnStruct, Z_Construct_UScriptStruct_FMaterialAttributesInput_Statics::ReturnStructParams); } return ReturnStruct; } uint32 Get_Z_Construct_UScriptStruct_FMaterialAttributesInput_Hash() { return 1947575238U; } struct Z_Construct_UScriptStruct_FExpressionInput_Statics { struct FExpressionInput { #if WITH_EDITORONLY_DATA UMaterialExpression* Expression; #endif // WITH_EDITORONLY_DATA int32 OutputIndex; #if WITH_EDITORONLY_DATA FName InputName; int32 Mask; int32 MaskR; int32 MaskG; int32 MaskB; int32 MaskA; #endif // WITH_EDITORONLY_DATA FName ExpressionName; }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Struct_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ExpressionName_MetaData[]; #endif static const UE4CodeGen_Private::FNamePropertyParams NewProp_ExpressionName; #if WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaskA_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaskA; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaskB_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaskB; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaskG_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaskG; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaskR_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaskR; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Mask_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_Mask; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_InputName_MetaData[]; #endif static const UE4CodeGen_Private::FNamePropertyParams NewProp_InputName; #endif // WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_OutputIndex_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_OutputIndex; #if WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Expression_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Expression; #endif // WITH_EDITORONLY_DATA static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_EDITORONLY_DATA #endif // WITH_EDITORONLY_DATA #if WITH_EDITORONLY_DATA #endif // WITH_EDITORONLY_DATA static const UE4CodeGen_Private::FStructParams ReturnStructParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::Struct_MetaDataParams[] = { { "Comment", "//@warning: FExpressionInput is mirrored in MaterialShared.h and manually \"subclassed\" in Material.h (FMaterialInput)\n" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "@warning: FExpressionInput is mirrored in MaterialShared.h and manually \"subclassed\" in Material.h (FMaterialInput)" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_ExpressionName_MetaData[] = { { "Comment", "/** Material expression name that this input is connected to, or None if not connected. Used only in cooked builds */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Material expression name that this input is connected to, or None if not connected. Used only in cooked builds" }, }; #endif const UE4CodeGen_Private::FNamePropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_ExpressionName = { "ExpressionName", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, ExpressionName), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_ExpressionName_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_ExpressionName_MetaData)) }; #if WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskA_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskA = { "MaskA", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, MaskA), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskA_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskA_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskB_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskB = { "MaskB", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, MaskB), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskB_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskB_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskG_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskG = { "MaskG", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, MaskG), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskG_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskG_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskR_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskR = { "MaskR", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, MaskR), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskR_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskR_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Mask_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Mask = { "Mask", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, Mask), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Mask_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Mask_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_InputName_MetaData[] = { { "Comment", "/** \n\x09 * optional FName of the input. \n\x09 * Note that this is the only member which is not derived from the output currently connected. \n\x09 */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "optional FName of the input.\nNote that this is the only member which is not derived from the output currently connected." }, }; #endif const UE4CodeGen_Private::FNamePropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_InputName = { "InputName", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, InputName), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_InputName_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_InputName_MetaData)) }; #endif // WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_OutputIndex_MetaData[] = { { "Comment", "/** Index into Expression's outputs array that this input is connected to. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Index into Expression's outputs array that this input is connected to." }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_OutputIndex = { "OutputIndex", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, OutputIndex), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_OutputIndex_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_OutputIndex_MetaData)) }; #if WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Expression_MetaData[] = { { "Comment", "/** UMaterial expression that this input is connected to, or NULL if not connected. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "UMaterial expression that this input is connected to, or NULL if not connected." }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Expression = { "Expression", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FExpressionInput, Expression), Z_Construct_UClass_UMaterialExpression_NoRegister, METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Expression_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Expression_MetaData)) }; #endif // WITH_EDITORONLY_DATA const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UScriptStruct_FExpressionInput_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_ExpressionName, #if WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskA, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskB, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskG, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_MaskR, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Mask, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_InputName, #endif // WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_OutputIndex, #if WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FExpressionInput_Statics::NewProp_Expression, #endif // WITH_EDITORONLY_DATA }; const UE4CodeGen_Private::FStructParams Z_Construct_UScriptStruct_FExpressionInput_Statics::ReturnStructParams = { (UObject* (*)())Z_Construct_UPackage__Script_Engine, nullptr, nullptr, "ExpressionInput", sizeof(FExpressionInput), alignof(FExpressionInput), Z_Construct_UScriptStruct_FExpressionInput_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, EStructFlags(0x00000008), METADATA_PARAMS(Z_Construct_UScriptStruct_FExpressionInput_Statics::Struct_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FExpressionInput_Statics::Struct_MetaDataParams)) }; UScriptStruct* Z_Construct_UScriptStruct_FExpressionInput() { #if WITH_HOT_RELOAD extern uint32 Get_Z_Construct_UScriptStruct_FExpressionInput_Hash(); UPackage* Outer = Z_Construct_UPackage__Script_Engine(); static UScriptStruct* ReturnStruct = FindExistingStructIfHotReloadOrDynamic(Outer, TEXT("ExpressionInput"), sizeof(Z_Construct_UScriptStruct_FExpressionInput_Statics::FExpressionInput), Get_Z_Construct_UScriptStruct_FExpressionInput_Hash(), false); #else static UScriptStruct* ReturnStruct = nullptr; #endif if (!ReturnStruct) { UE4CodeGen_Private::ConstructUScriptStruct(ReturnStruct, Z_Construct_UScriptStruct_FExpressionInput_Statics::ReturnStructParams); } return ReturnStruct; } uint32 Get_Z_Construct_UScriptStruct_FExpressionInput_Hash() { return 1008690408U; } void UMaterialExpression::StaticRegisterNativesUMaterialExpression() { } UClass* Z_Construct_UClass_UMaterialExpression_NoRegister() { return UMaterialExpression::StaticClass(); } struct Z_Construct_UClass_UMaterialExpression_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Outputs_MetaData[]; #endif static const UE4CodeGen_Private::FArrayPropertyParams NewProp_Outputs; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Outputs_Inner; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MenuCategories_MetaData[]; #endif static const UE4CodeGen_Private::FArrayPropertyParams NewProp_MenuCategories; static const UE4CodeGen_Private::FTextPropertyParams NewProp_MenuCategories_Inner; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bShowOutputs_MetaData[]; #endif static void NewProp_bShowOutputs_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bShowOutputs; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bShowInputs_MetaData[]; #endif static void NewProp_bShowInputs_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bShowInputs; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bShaderInputData_MetaData[]; #endif static void NewProp_bShaderInputData_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bShaderInputData; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bCollapsed_MetaData[]; #endif static void NewProp_bCollapsed_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bCollapsed; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bHidePreviewWindow_MetaData[]; #endif static void NewProp_bHidePreviewWindow_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bHidePreviewWindow; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bShowMaskColorsOnPin_MetaData[]; #endif static void NewProp_bShowMaskColorsOnPin_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bShowMaskColorsOnPin; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bShowOutputNameOnPin_MetaData[]; #endif static void NewProp_bShowOutputNameOnPin_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bShowOutputNameOnPin; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bCommentBubbleVisible_MetaData[]; #endif static void NewProp_bCommentBubbleVisible_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bCommentBubbleVisible; #endif // WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bIsParameterExpression_MetaData[]; #endif static void NewProp_bIsParameterExpression_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsParameterExpression; #if WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bNeedToUpdatePreview_MetaData[]; #endif static void NewProp_bNeedToUpdatePreview_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bNeedToUpdatePreview; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bRealtimePreview_MetaData[]; #endif static void NewProp_bRealtimePreview_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bRealtimePreview; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Desc_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_Desc; #endif // WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Function_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Function; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Material_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Material; #if WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaterialExpressionGuid_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_MaterialExpressionGuid; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GraphNode_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_GraphNode; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaterialExpressionEditorY_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaterialExpressionEditorY; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaterialExpressionEditorX_MetaData[]; #endif static const UE4CodeGen_Private::FIntPropertyParams NewProp_MaterialExpressionEditorX; #endif // WITH_EDITORONLY_DATA static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_EDITORONLY_DATA #endif // WITH_EDITORONLY_DATA #if WITH_EDITORONLY_DATA #endif // WITH_EDITORONLY_DATA #if WITH_EDITORONLY_DATA #endif // WITH_EDITORONLY_DATA static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UMaterialExpression_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UObject, (UObject* (*)())Z_Construct_UPackage__Script_Engine, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::Class_MetaDataParams[] = { { "BlueprintType", "true" }, { "HideCategories", "Object" }, { "IncludePath", "Materials/MaterialExpression.h" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif #if WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Outputs_MetaData[] = { { "Comment", "/** The expression's outputs, which are set in default properties by derived classes. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "The expression's outputs, which are set in default properties by derived classes." }, }; #endif const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Outputs = { "Outputs", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, Outputs), EArrayPropertyFlags::None, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Outputs_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Outputs_MetaData)) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Outputs_Inner = { "Outputs", nullptr, (EPropertyFlags)0x0000000800000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UScriptStruct_FExpressionOutput, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MenuCategories_MetaData[] = { { "Comment", "/** Localized categories to sort this expression into... */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Localized categories to sort this expression into..." }, }; #endif const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MenuCategories = { "MenuCategories", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, MenuCategories), EArrayPropertyFlags::None, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MenuCategories_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MenuCategories_MetaData)) }; const UE4CodeGen_Private::FTextPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MenuCategories_Inner = { "MenuCategories", nullptr, (EPropertyFlags)0x0000000800000000, UE4CodeGen_Private::EPropertyGenFlags::Text, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputs_MetaData[] = { { "Comment", "/** Whether to draw the expression's outputs. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Whether to draw the expression's outputs." }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputs_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bShowOutputs = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputs = { "bShowOutputs", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputs_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputs_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputs_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowInputs_MetaData[] = { { "Comment", "/** Whether to draw the expression's inputs. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Whether to draw the expression's inputs." }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowInputs_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bShowInputs = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowInputs = { "bShowInputs", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowInputs_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowInputs_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowInputs_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShaderInputData_MetaData[] = { { "Comment", "/** Whether the node represents an input to the shader or not. Used to color the node's background. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Whether the node represents an input to the shader or not. Used to color the node's background." }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShaderInputData_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bShaderInputData = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShaderInputData = { "bShaderInputData", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShaderInputData_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShaderInputData_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShaderInputData_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCollapsed_MetaData[] = { { "Comment", "/** If true, show a collapsed version of the node */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "If true, show a collapsed version of the node" }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCollapsed_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bCollapsed = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCollapsed = { "bCollapsed", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCollapsed_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCollapsed_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCollapsed_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bHidePreviewWindow_MetaData[] = { { "Comment", "/** If true, do not render the preview window for the expression */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "If true, do not render the preview window for the expression" }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bHidePreviewWindow_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bHidePreviewWindow = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bHidePreviewWindow = { "bHidePreviewWindow", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bHidePreviewWindow_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bHidePreviewWindow_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bHidePreviewWindow_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowMaskColorsOnPin_MetaData[] = { { "Comment", "/** If true, changes the pin color to match the output mask */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "If true, changes the pin color to match the output mask" }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowMaskColorsOnPin_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bShowMaskColorsOnPin = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowMaskColorsOnPin = { "bShowMaskColorsOnPin", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowMaskColorsOnPin_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowMaskColorsOnPin_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowMaskColorsOnPin_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputNameOnPin_MetaData[] = { { "Comment", "/** If true, use the output name as the label for the pin */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "If true, use the output name as the label for the pin" }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputNameOnPin_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bShowOutputNameOnPin = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputNameOnPin = { "bShowOutputNameOnPin", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputNameOnPin_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputNameOnPin_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputNameOnPin_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCommentBubbleVisible_MetaData[] = { { "Comment", "/** If true, the comment bubble will be visible in the graph editor */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "If true, the comment bubble will be visible in the graph editor" }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCommentBubbleVisible_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bCommentBubbleVisible = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCommentBubbleVisible = { "bCommentBubbleVisible", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCommentBubbleVisible_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCommentBubbleVisible_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCommentBubbleVisible_MetaData)) }; #endif // WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bIsParameterExpression_MetaData[] = { { "Comment", "/** Indicates that this is a 'parameter' type of expression and should always be loaded (ie not cooked away) because we might want the default parameter. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Indicates that this is a 'parameter' type of expression and should always be loaded (ie not cooked away) because we might want the default parameter." }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bIsParameterExpression_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bIsParameterExpression = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bIsParameterExpression = { "bIsParameterExpression", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bIsParameterExpression_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bIsParameterExpression_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bIsParameterExpression_MetaData)) }; #if WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bNeedToUpdatePreview_MetaData[] = { { "Comment", "/** If true, we should update the preview next render. This is set when changing bRealtimePreview. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "If true, we should update the preview next render. This is set when changing bRealtimePreview." }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bNeedToUpdatePreview_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bNeedToUpdatePreview = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bNeedToUpdatePreview = { "bNeedToUpdatePreview", nullptr, (EPropertyFlags)0x0010000800002000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bNeedToUpdatePreview_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bNeedToUpdatePreview_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bNeedToUpdatePreview_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bRealtimePreview_MetaData[] = { { "Comment", "/** Set to true by RecursiveUpdateRealtimePreview() if the expression's preview needs to be updated in realtime in the material editor. */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Set to true by RecursiveUpdateRealtimePreview() if the expression's preview needs to be updated in realtime in the material editor." }, }; #endif void Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bRealtimePreview_SetBit(void* Obj) { ((UMaterialExpression*)Obj)->bRealtimePreview = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bRealtimePreview = { "bRealtimePreview", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UMaterialExpression), &Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bRealtimePreview_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bRealtimePreview_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bRealtimePreview_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Desc_MetaData[] = { { "Category", "MaterialExpression" }, { "Comment", "/** A description that level designers can add (shows in the material editor UI). */" }, { "DisplayAfter", "SortPriority" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "MultiLine", "TRUE" }, { "ToolTip", "A description that level designers can add (shows in the material editor UI)." }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Desc = { "Desc", nullptr, (EPropertyFlags)0x0010000800000001, UE4CodeGen_Private::EPropertyGenFlags::Str, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, Desc), METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Desc_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Desc_MetaData)) }; #endif // WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Function_MetaData[] = { { "Comment", "/** \n\x09 * The material function that this expression is being used with, if any.\n\x09 * This will be NULL if the expression belongs to a function that is currently being edited, \n\x09 */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "The material function that this expression is being used with, if any.\nThis will be NULL if the expression belongs to a function that is currently being edited," }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Function = { "Function", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, Function), Z_Construct_UClass_UMaterialFunction_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Function_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Function_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Material_MetaData[] = { { "Comment", "/** \n\x09 * The material that this expression is currently being compiled in. \n\x09 * This is not necessarily the object which owns this expression, for example a preview material compiling a material function's expressions.\n\x09 */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "The material that this expression is currently being compiled in.\nThis is not necessarily the object which owns this expression, for example a preview material compiling a material function's expressions." }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Material = { "Material", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, Material), Z_Construct_UClass_UMaterial_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Material_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Material_MetaData)) }; #if WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionGuid_MetaData[] = { { "Comment", "/** GUID to uniquely identify this node, to help the tutorials out */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "GUID to uniquely identify this node, to help the tutorials out" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionGuid = { "MaterialExpressionGuid", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, MaterialExpressionGuid), Z_Construct_UScriptStruct_FGuid, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionGuid_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionGuid_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_GraphNode_MetaData[] = { { "Comment", "/** Expression's Graph representation */" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, { "ToolTip", "Expression's Graph representation" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_GraphNode = { "GraphNode", nullptr, (EPropertyFlags)0x0010000800002000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, GraphNode), Z_Construct_UClass_UEdGraphNode_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_GraphNode_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_GraphNode_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorY_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorY = { "MaterialExpressionEditorY", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, MaterialExpressionEditorY), METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorY_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorY_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorX_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpression.h" }, }; #endif const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorX = { "MaterialExpressionEditorX", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpression, MaterialExpressionEditorX), METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorX_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorX_MetaData)) }; #endif // WITH_EDITORONLY_DATA const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UMaterialExpression_Statics::PropPointers[] = { #if WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Outputs, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Outputs_Inner, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MenuCategories, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MenuCategories_Inner, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputs, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowInputs, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShaderInputData, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCollapsed, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bHidePreviewWindow, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowMaskColorsOnPin, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bShowOutputNameOnPin, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bCommentBubbleVisible, #endif // WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bIsParameterExpression, #if WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bNeedToUpdatePreview, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_bRealtimePreview, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Desc, #endif // WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Function, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_Material, #if WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionGuid, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_GraphNode, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorY, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpression_Statics::NewProp_MaterialExpressionEditorX, #endif // WITH_EDITORONLY_DATA }; const FCppClassTypeInfoStatic Z_Construct_UClass_UMaterialExpression_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UMaterialExpression>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMaterialExpression_Statics::ClassParams = { &UMaterialExpression::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_UMaterialExpression_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::PropPointers), 0, 0x001000A1u, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpression_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpression_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UMaterialExpression() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMaterialExpression_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UMaterialExpression, 3610243218); template<> ENGINE_API UClass* StaticClass<UMaterialExpression>() { return UMaterialExpression::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UMaterialExpression(Z_Construct_UClass_UMaterialExpression, &UMaterialExpression::StaticClass, TEXT("/Script/Engine"), TEXT("UMaterialExpression"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UMaterialExpression); IMPLEMENT_FARCHIVE_SERIALIZER(UMaterialExpression) PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "west.ryan.k@gmail.com" ]
west.ryan.k@gmail.com
ed3c0dcb7b662917f3e506e0c8503948335a6c64
2a2ff2eab6a367da2f8a5e68e28406fd7a4b2a82
/include/golite/func.h
ec3e9ec5e90624cd95e454a9d6171ff7172a0ced
[]
no_license
amirbawab/GoLite
5daf5ed363300d9c0bdb3e46b4234b0424742856
8c00f3e4f52437e7cf5c81c35e8afbabce0d91d4
refs/heads/master
2020-03-14T18:49:54.639897
2018-05-01T19:44:12
2018-05-01T19:44:12
131,749,955
1
0
null
null
null
null
UTF-8
C++
false
false
2,254
h
#ifndef GOLITE_FUNC_H #define GOLITE_FUNC_H #include <golite/pointer.h> #include <golite/function.h> namespace golite { class Func : public Pointer { private: golite::TypeComponent* type_component_ = nullptr; golite::Function* function_ = nullptr; public: Func(Function* function, golite::TypeComponent* type_component) : function_(function), type_component_(type_component) {} /** * @see TypeComposite::getTypeComponent() */ golite::TypeComponent* getTypeComponent() { return type_component_; } /** * @see TypeComposite::toGoLite(int) */ std::string toGoLite(int indent); /** * @see TypeComponent::toGotLiteMin() */ std::string toGoLiteMin(); /** * @see TypeComposite::getLine() */ int getLine(); /** * @see TypeComposite::weedingPass() */ void weedingPass(); /** * @see TypeComposite::symbolTablePass() */ void symbolTablePass(SymbolTable* root); /** * @see TypeComposite::isCompatible() */ bool isCompatible(TypeComposite* type_composite); /** * @see TypeComposite::toPrettySymbol() */ std::string toPrettySymbol(); /** * @see TypeComposite::resolveChildren() */ std::vector<golite::TypeComposite*> resolveChildren(); /** * @see TypeComposite::isComparable() */ bool isComparable() { return false; } /** * @see TypeComposite::resolvesToComparable() */ bool resolvesToComparable() { return false; } /** * @see TypeComposite::isFunc() */ bool isFunc() { return true; } /** * Get function * @return function */ Function* getFunction() const { return function_; } /** * @see TypeComposite::toTypeScript() */ std::string toTypeScript(int indent); /** * @see TypeComposite::toTypeScriptInitializer() */ std::string toTypeScriptInitializer(int indent); }; } #endif
[ "amirbawab@gmail.com" ]
amirbawab@gmail.com
8929337dab1ba9e5da6374d86b4957cbb03444d3
f097c1db0c9f423ad44ca38c3485aef9a83ddeff
/algofunc.cpp
b183ea469aafde0c1d0427b71ed8cd669b62dda7
[]
no_license
alex-krav/intro-prog-lab2
3f6b17622d1d7f1c603cdf23c7cceedb8b7455d8
d95f1ffc3cd1b0394defab6e280d3e84237fb542
refs/heads/master
2022-09-16T01:17:06.464421
2020-06-03T07:29:38
2020-06-03T07:29:38
257,972,788
0
0
null
null
null
null
UTF-8
C++
false
false
1,299
cpp
#include "iofunc.h" #include <iostream> #include <algorithm> using namespace std; vector<kvPair> get_topN_grades(map<string, vector<int>> country_votes, int topNum, vector<int> grades) { map<string, int> country_grades, one_country_votes; // init grades for (const auto& pair : country_votes) { country_grades[pair.first] = 0; } for (int i = 0; i < country_votes.size(); ++i) { // get one country votes for (const auto& pair : country_votes) { one_country_votes[pair.first] = pair.second[i]; } // sort countries by votes in one column descending vector<kvPair> vec; copy(one_country_votes.begin(), one_country_votes.end(), back_inserter<vector<kvPair>>(vec)); sort(vec.begin(), vec.end(), [](const kvPair& l, const kvPair& r) { return l.second > r.second; }); // add grades to countries for (int j = 0; j < grades.size(); ++j) { country_grades[vec[j].first] += grades[j]; } } // sort countries by grades and return topNum vector<kvPair> vec; copy(country_grades.begin(), country_grades.end(), back_inserter<vector<kvPair>>(vec)); sort(vec.begin(), vec.end(), [](const kvPair& l, const kvPair& r) { if (l.second != r.second) return l.second > r.second; return l.first < r.first; }); vec.resize(topNum); return vec; }
[ "oakravchuk@luxoft.com" ]
oakravchuk@luxoft.com
3024c0af3b6aaba957d0f3990c2ac4230740f404
06c8fa8a045b8d015125adc8bb4ed3ff08f66005
/cbMakefileGen.cpp
695df31a94b83cd2644f65f22385c02a75b2f92d
[]
no_license
gongfuPanada/cbmakefilegen
3af2188283d3e3761c197b7b58ccfdf7752277e2
f84508a7b8e7d296be3b28dbfe3cc3c06f3eed58
refs/heads/master
2021-01-15T17:14:01.802024
2014-12-19T10:17:47
2014-12-19T10:17:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,975
cpp
#include <sdk.h> // Code::Blocks SDK #include <configurationpanel.h> #include "cbMakefileGen.h" #include <wx/menu.h> #include "Makefile.hpp" #include "cbmakefilecfg.h" #include <cbproject.h> #include <projectmanager.h> #include <logmanager.h> #include <configmanager.h> int MakefileGenId = wxNewId(); // Register the plugin with Code::Blocks. // We are using an anonymous namespace so we don't litter the global one. namespace { PluginRegistrant<cbMakefileGen> reg(_T("cbMakefileGen")); } // events handling BEGIN_EVENT_TABLE(cbMakefileGen, cbPlugin) // add any events you want to handle here EVT_MENU(MakefileGenId, cbMakefileGen::OnExecute) END_EVENT_TABLE() // constructor cbMakefileGen::cbMakefileGen() { // Make sure our resources are available. // In the generated boilerplate code we have no resources but when // we add some, it will be nice that this code is in place already ;) if (!Manager::LoadResource(_T("cbMakefileGen.zip"))) { NotifyMissingFile(_T("cbMakefileGen.zip")); } } // destructor cbMakefileGen::~cbMakefileGen() {} void cbMakefileGen::OnAttach() { // do whatever initialization you need for your plugin // NOTE: after this function, the inherited member variable // m_IsAttached will be TRUE... // You should check for it in other functions, because if it // is FALSE, it means that the application did *not* "load" // (see: does not need) this plugin... } void cbMakefileGen::OnRelease(bool appShutDown) { // do de-initialization for your plugin // if appShutDown is true, the plugin is unloaded because Code::Blocks is being shut down, // which means you must not use any of the SDK Managers // NOTE: after this function, the inherited member variable // m_IsAttached will be FALSE... } int cbMakefileGen::Configure() { //create and display the configuration dialog for your plugin cbConfigurationDialog dlg(Manager::Get()->GetAppWindow(), wxID_ANY, _("Makefile generator configure")); cbConfigurationPanel* panel = GetConfigurationPanel(&dlg); if (panel) { dlg.AttachConfigurationPanel(panel); PlaceWindow(&dlg); return dlg.ShowModal() == wxID_OK ? 0 : -1; } return -1; } void cbMakefileGen::BuildMenu(wxMenuBar* menuBar) { //The application is offering its menubar for your plugin, //to add any menu items you want... //Append any items you need in the menu... //NOTE: Be careful in here... The application's menubar is at your disposal. if (!IsAttached()) { return; } int idx = menuBar->FindMenu(_("Project")); if (idx != wxNOT_FOUND) { wxMenu* lMenu = menuBar->GetMenu(idx); if ( lMenu ) { lMenu->AppendSeparator(); lMenu->Append(MakefileGenId, _("Generate Makefile")); } } } void cbMakefileGen::BuildModuleMenu(const ModuleType type, wxMenu* menu, const FileTreeData* data) { //Some library module is ready to display a pop-up menu. //Check the parameter \"type\" and see which module it is //and append any items you need in the menu... //TIP: for consistency, add a separator as the first item... // NotImplemented(_T("cbMakefileGen::BuildModuleMenu()")); } void cbMakefileGen::OnExecute(wxCommandEvent &event) { // if not attached, exit if (!IsAttached()) return; wxString msg; cbProject* project = Manager::Get()->GetProjectManager()->GetActiveProject(); // if no project open, exit if (!project) { msg = _("You need to open a project\nbefore using the plugin!\n" "C::B MakefileGen could not complete the operation."); cbMessageBox(msg, _("Error"), wxICON_ERROR | wxOK, Manager::Get()->GetAppWindow()); Manager::Get()->GetLogManager()->DebugLog(msg); return; } ConfigManager* cfg = Manager::Get()->GetConfigManager(_T("cbMakefileGen")); m_Filename = cfg->Read(_T("/filename"),_T("Makefile.gen")); m_Overwrite = cfg->ReadBool(_T("/overwrite"),false); m_Silence = cfg->ReadBool(_T("/silence"),true); m_AllTargets = cfg->ReadBool(_T("/alltargets"),false); /* fix by oBFusCATed */ m_Filename.Replace(_T("$(proj_title)"), project->GetTitle()); cbMGMakefile lMakefile(project,m_Filename,m_Overwrite,m_Silence,m_AllTargets); if ( lMakefile.SaveMakefile() ) { msg = _("C::B MakefileGen save : "); msg += m_Filename; msg += _T("\n"); msg += _("Targets: "); msg += lMakefile.GetProceedTargets(); cbMessageBox(msg, _("Info"), wxICON_INFORMATION | wxOK, Manager::Get()->GetAppWindow()); } else { msg = _("C::B MakefileGen found errors, saves aborted."); cbMessageBox(msg, _("Error"), wxICON_EXCLAMATION | wxOK, Manager::Get()->GetAppWindow()); } } cbConfigurationPanel* cbMakefileGen::GetConfigurationPanel(wxWindow* parent) { return new cbmakefilecfg(parent); }
[ "kisoft@rambler.ru" ]
kisoft@rambler.ru
983ec5533d952193b4eb3eeadb6e720c0b47a420
d6258ae3c0fd9f36efdd859a2c93ab489da2aa9b
/fulldocset/add/codesnippet/CPP/p-system.windows.forms.f_56_1.cpp
2786f1080fdaa697df3fa1a8472c3a4a35fd85a0
[ "CC-BY-4.0", "MIT" ]
permissive
OpenLocalizationTestOrg/ECMA2YamlTestRepo2
ca4d3821767bba558336b2ef2d2a40aa100d67f6
9a577bbd8ead778fd4723fbdbce691e69b3b14d4
refs/heads/master
2020-05-26T22:12:47.034527
2017-03-07T07:07:15
2017-03-07T07:07:15
82,508,764
1
0
null
2017-02-28T02:14:26
2017-02-20T02:36:59
Visual Basic
UTF-8
C++
false
false
2,301
cpp
void Button1_Click( System::Object^ sender, System::EventArgs^ e ) { // Set FontMustExist to true, which causes message box error // if the user enters a font that does not exist. FontDialog1->FontMustExist = true; // Associate the method handling the Apply event with the event. FontDialog1->Apply += gcnew System::EventHandler( this, &Form1::FontDialog1_Apply ); // Set a minimum and maximum size to be // shown in the FontDialog. FontDialog1->MaxSize = 32; FontDialog1->MinSize = 18; // Show the Apply button in the dialog. FontDialog1->ShowApply = true; // Do not show effects such as Underline // and Bold. FontDialog1->ShowEffects = false; // Save the existing font. System::Drawing::Font^ oldFont = this->Font; //Show the dialog, and get the result System::Windows::Forms::DialogResult result = FontDialog1->ShowDialog(); // If the OK button in the Font dialog box is clicked, // set all the controls' fonts to the chosen font by calling // the FontDialog1_Apply method. if ( result == ::DialogResult::OK ) { FontDialog1_Apply( this->Button1, gcnew System::EventArgs ); } // If Cancel is clicked, set the font back to // the original font. else // If Cancel is clicked, set the font back to // the original font. if ( result == ::DialogResult::Cancel ) { this->Font = oldFont; System::Collections::IEnumerator^ myEnum = this->Controls->GetEnumerator(); while ( myEnum->MoveNext() ) { Control^ containedControl = safe_cast<Control^>(myEnum->Current); containedControl->Font = oldFont; } } } // Handle the Apply event by setting all controls' fonts to // the chosen font. void FontDialog1_Apply( Object^ sender, System::EventArgs^ e ) { this->Font = FontDialog1->Font; System::Collections::IEnumerator^ myEnum1 = this->Controls->GetEnumerator(); while ( myEnum1->MoveNext() ) { Control^ containedControl = safe_cast<Control^>(myEnum1->Current); containedControl->Font = FontDialog1->Font; } }
[ "tianzh@microsoft.com" ]
tianzh@microsoft.com
7ad1db0e6458e9cf38325f75bf6e96f7352f190a
570fc184f62d1cf8624ca2a5a7fc487af1452754
/parser/html/nsHtml5Highlighter.h
c27b6b606e4c076da89f8e5755bcc3697d9dc9fb
[]
no_license
roytam1/palemoon26
726424415a96fb36fe47d5d414a2cfafabecb3e6
43b0deedf05166f30d62bd666c040a3165a761a1
refs/heads/master
2023-09-03T15:25:23.800487
2018-08-25T16:35:59
2018-08-28T12:32:52
115,328,093
6
1
null
null
null
null
UTF-8
C++
false
false
10,657
h
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef nsHtml5Highlighter_h_ #define nsHtml5Highlighter_h_ #include "prtypes.h" #include "nsCOMPtr.h" #include "nsHtml5TreeOperation.h" #include "nsHtml5UTF16Buffer.h" #include "nsHtml5TreeOperation.h" #include "nsAHtml5TreeOpSink.h" #define NS_HTML5_HIGHLIGHTER_HANDLE_ARRAY_LENGTH 512 /** * A state machine for generating HTML for display in View Source based on * the transitions the tokenizer makes on the source being viewed. */ class nsHtml5Highlighter { public: /** * The constructor. * * @param aOpSink the sink for the tree ops generated by this highlighter */ nsHtml5Highlighter(nsAHtml5TreeOpSink* aOpSink); /** * The destructor. */ ~nsHtml5Highlighter(); /** * Starts the generated document. */ void Start(const nsAutoString& aTitle); /** * Report a tokenizer state transition. * * @param aState the state being transitioned to * @param aReconsume whether this is a reconsuming transition * @param aPos the tokenizer's current position into the buffer */ int32_t Transition(int32_t aState, bool aReconsume, int32_t aPos); /** * Report end of file. */ void End(); /** * Set the current buffer being tokenized */ void SetBuffer(nsHtml5UTF16Buffer* aBuffer); /** * Let go of the buffer being tokenized but first, flush text from it. * * @param aPos the first UTF-16 code unit not to flush */ void DropBuffer(int32_t aPos); /** * Flush the tree ops into the sink. * * @return true if there were ops to flush */ bool FlushOps(); /** * Linkify the current attribute value if the attribute name is one of * known URL attributes. (When executing tree ops, javascript: URLs will * not be linkified, though.) * * @param aName the name of the attribute * @param aValue the value of the attribute */ void MaybeLinkifyAttributeValue(nsHtml5AttributeName* aName, nsString* aValue); /** * Inform the highlighter that the tokenizer successfully completed a * named character reference. */ void CompletedNamedCharacterReference(); /** * Adds an error annotation to the node that's currently on top of * mStack. * * @param aMsgId the id of the message in the property file */ void AddErrorToCurrentNode(const char* aMsgId); /** * Adds an error annotation to the node that corresponds to the most * recently opened markup declaration/tag span, character reference or * run of text. * * @param aMsgId the id of the message in the property file */ void AddErrorToCurrentRun(const char* aMsgId); /** * Adds an error annotation to the node that corresponds to the most * recently opened markup declaration/tag span, character reference or * run of text with one atom to use when formatting the message. * * @param aMsgId the id of the message in the property file * @param aName the atom */ void AddErrorToCurrentRun(const char* aMsgId, nsIAtom* aName); /** * Adds an error annotation to the node that corresponds to the most * recently opened markup declaration/tag span, character reference or * run of text with two atoms to use when formatting the message. * * @param aMsgId the id of the message in the property file * @param aName the first atom * @param aOther the second atom */ void AddErrorToCurrentRun(const char* aMsgId, nsIAtom* aName, nsIAtom* aOther); /** * Adds an error annotation to the node that corresponds to the most * recent potentially character reference-starting ampersand. * * @param aMsgId the id of the message in the property file */ void AddErrorToCurrentAmpersand(const char* aMsgId); /** * Adds an error annotation to the node that corresponds to the most * recent potentially self-closing slash. * * @param aMsgId the id of the message in the property file */ void AddErrorToCurrentSlash(const char* aMsgId); /** * Enqueues a tree op for adding base to the urls with the view-source: * * @param aValue the base URL to add */ void AddBase(const nsString& aValue); private: /** * Starts a span with no class. */ void StartSpan(); /** * Starts a <span> and sets the class attribute on it. * * @param aClass the class to set (MUST be a static string that does not * need to be released!) */ void StartSpan(const PRUnichar* aClass); /** * End the current <span> or <a> in the highlighter output. */ void EndSpanOrA(); /** * Starts a wrapper around a run of characters. */ void StartCharacters(); /** * Ends a wrapper around a run of characters. */ void EndCharactersAndStartMarkupRun(); /** * Starts an <a>. */ void StartA(); /** * Flushes characters up to but not including the current one. */ void FlushChars(); /** * Flushes characters up to and including the current one. */ void FlushCurrent(); /** * Finishes highlighting a tag in the input data by closing the open * <span> and <a> elements in the highlighter output and then starts * another <span> for potentially highlighting characters potentially * appearing next. */ void FinishTag(); /** * Adds a class attribute to the current node. * * @param aClass the class to set (MUST be a static string that does not * need to be released!) */ void AddClass(const PRUnichar* aClass); /** * Allocates a handle for an element. * * See the documentation for nsHtml5TreeBuilder::AllocateContentHandle() * in nsHtml5TreeBuilderHSupplement.h. * * @return the handle */ nsIContent** AllocateContentHandle(); /** * Enqueues an element creation tree operation. * * @param aName the name of the element * @param aAttributes the attribute holder (ownership will be taken) or * nullptr for no attributes * @return the handle for the element that will be created */ nsIContent** CreateElement(nsIAtom* aName, nsHtml5HtmlAttributes* aAttributes); /** * Gets the handle for the current node. May be called only after the * root element has been set. * * @return the handle for the current node */ nsIContent** CurrentNode(); /** * Create an element and push it (its handle) on the stack. * * @param aName the name of the element * @param aAttributes the attribute holder (ownership will be taken) or * nullptr for no attributes */ void Push(nsIAtom* aName, nsHtml5HtmlAttributes* aAttributes); /** * Pops the current node off the stack. */ void Pop(); /** * Appends text content to the current node. * * @param aBuffer the buffer to copy from * @param aStart the index of the first code unit to copy * @param aLength the number of code units to copy */ void AppendCharacters(const PRUnichar* aBuffer, int32_t aStart, int32_t aLength); /** * Enqueues a tree op for adding an href attribute with the view-source: * URL scheme to the current node. * * @param aValue the (potentially relative) URL to link to */ void AddViewSourceHref(const nsString& aValue); /** * The state we are transitioning away from. */ int32_t mState; /** * The index of the first UTF-16 code unit in mBuffer that hasn't been * flushed yet. */ int32_t mCStart; /** * The position of the code unit in mBuffer that caused the current * transition. */ int32_t mPos; /** * The current line number. */ int32_t mLineNumber; /** * The number of inline elements open inside the <pre> excluding the * span potentially wrapping a run of characters. */ int32_t mInlinesOpen; /** * Whether there's a span wrapping a run of characters (excluding CDATA * section) open. */ bool mInCharacters; /** * The current buffer being tokenized. */ nsHtml5UTF16Buffer* mBuffer; /** * Whether to highlight syntax visibly initially. */ bool mSyntaxHighlight; /** * The outgoing tree op queue. */ nsTArray<nsHtml5TreeOperation> mOpQueue; /** * The tree op stage for the tree op executor. */ nsAHtml5TreeOpSink* mOpSink; /** * The most recently opened markup declaration/tag or run of characters. */ nsIContent** mCurrentRun; /** * The most recent ampersand in a place where character references were * allowed. */ nsIContent** mAmpersand; /** * The most recent slash that might become a self-closing slash. */ nsIContent** mSlash; /** * Memory for element handles. */ nsAutoArrayPtr<nsIContent*> mHandles; /** * Number of handles used in mHandles */ int32_t mHandlesUsed; /** * A holder for old contents of mHandles */ nsTArray<nsAutoArrayPtr<nsIContent*> > mOldHandles; /** * The element stack. */ nsTArray<nsIContent**> mStack; /** * The string "comment" */ static PRUnichar sComment[]; /** * The string "cdata" */ static PRUnichar sCdata[]; /** * The string "start-tag" */ static PRUnichar sStartTag[]; /** * The string "attribute-name" */ static PRUnichar sAttributeName[]; /** * The string "attribute-value" */ static PRUnichar sAttributeValue[]; /** * The string "end-tag" */ static PRUnichar sEndTag[]; /** * The string "doctype" */ static PRUnichar sDoctype[]; /** * The string "entity" */ static PRUnichar sEntity[]; /** * The string "pi" */ static PRUnichar sPi[]; /** * Whether base is already visited once. */ bool mSeenBase; }; #endif // nsHtml5Highlighter_h_
[ "roytam@gmail.com" ]
roytam@gmail.com
ac7f7edda72143abb39f122ce914cff21161ded2
6341a025f36812581ed759170747364d81efe4c2
/application/source/skill-system/primitives/AOE.h
8fe6c888fc07c2fa4bff23668caeb8ef54f0b4b0
[]
no_license
yhyu13/DigiPen-GAM541-GameProject
dcab68494d6636aee2a91d114baf712b419355fa
2ed81961482dd261181f4934832ac2da4b2f9f48
refs/heads/master
2023-03-14T21:58:33.034521
2021-03-22T02:14:28
2021-03-22T02:14:28
350,177,524
0
0
null
null
null
null
UTF-8
C++
false
false
741
h
/* Start Header ------------------------------------------------------- Copyright (C) 2020 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. Language: c++ 11 Platform: Windows 10 (X64) Project: GAM541 Author: Hang Yu (hang.yu@digipen.edu | 60001119) Creation date: 03/30/2020 - End Header ----------------------------*/ #pragma once #include "skill-system/BaseSkill.h" namespace gswy { class AOE : virtual public BaseSkill { public: AOE(); ~AOE(); const float GetAOEMultipler(); void SetAOEMultipler(float multiplier); void ApplyAOEMultipler(float multiplier); private: float m_multiplier; }; }
[ "yohan680919@gmail.com" ]
yohan680919@gmail.com
7327ca348f4c5752f5c3f61bcf7ce6a89e2d032a
b1af8bb863a6730e6e4e93129efbad89d33cf509
/SDK/SCUM_OxygenSaturationMonitor_parameters.hpp
fce20b3ce812c35c10868d7f12d945fffcd16263
[]
no_license
frankie-11/SCUM_SDK7.13.2020
b3bbd8fb9b6c03120b865a6254eca6a2389ea654
7b48bcf9e8088aa8917c07dd6756eac90e3f693a
refs/heads/master
2022-11-16T05:48:55.729087
2020-07-13T23:48:50
2020-07-13T23:48:50
279,433,512
0
1
null
null
null
null
UTF-8
C++
false
false
3,717
hpp
#pragma once // SCUM (4.24) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.AlarmControl struct UOxygenSaturationMonitor_C_AlarmControl_Params { int* alarmCode; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.DeactivateAlarm struct UOxygenSaturationMonitor_C_DeactivateAlarm_Params { }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.ActivateAlarm struct UOxygenSaturationMonitor_C_ActivateAlarm_Params { }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.CheckBloodOxygenationAlarm struct UOxygenSaturationMonitor_C_CheckBloodOxygenationAlarm_Params { float* oxygenationLevel; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int alarmCode; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.SetPrisonerAndLifeComponentToMonitor struct UOxygenSaturationMonitor_C_SetPrisonerAndLifeComponentToMonitor_Params { class APrisoner** prisonerToSet; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool Success; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.ProvideOxygenSaturationExtremes struct UOxygenSaturationMonitor_C_ProvideOxygenSaturationExtremes_Params { struct FText OxygenSaturationExtremes; // (Parm, OutParm) }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.GetHeartRateBPM struct UOxygenSaturationMonitor_C_GetHeartRateBPM_Params { struct FText ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.Construct struct UOxygenSaturationMonitor_C_Construct_Params { }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.Tick struct UOxygenSaturationMonitor_C_Tick_Params { struct FGeometry* MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) float* InDeltaTime; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.AlarmOnWindowContent struct UOxygenSaturationMonitor_C_AlarmOnWindowContent_Params { }; // Function OxygenSaturationMonitor.OxygenSaturationMonitor_C.ExecuteUbergraph_OxygenSaturationMonitor struct UOxygenSaturationMonitor_C_ExecuteUbergraph_OxygenSaturationMonitor_Params { int* EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "60810131+frankie-11@users.noreply.github.com" ]
60810131+frankie-11@users.noreply.github.com
fad65984cd448f695070cb6848ba0935887d5753
edfb38fa076edeb72b511d8c7a801f217ade83f4
/wwiv-svn/.svn/pristine/fa/fad65984cd448f695070cb6848ba0935887d5753.svn-base
de3ab4bd60f38e3518d937ae45c00c90c1c998a1
[]
no_license
insidenothing/wwiv
b06e3e71265f8fe7ffa8c0e6ab37b2135bcdcf05
93f311305d36c07b363853707f64f4c53e43e0d4
refs/heads/master
2020-04-04T01:29:00.664801
2016-11-18T05:00:07
2016-11-18T05:00:07
9,230,690
0
1
null
null
null
null
UTF-8
C++
false
false
26,715
/**************************************************************************/ /* */ /* WWIV Version 5.0x */ /* Copyright (C)1998-20014, WWIV Software Services */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, */ /* software distributed under the License is distributed on an */ /* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */ /* either express or implied. See the License for the specific */ /* language governing permissions and limitations under the License. */ /* */ /**************************************************************************/ #ifndef __INCLUDED_WUSER_H__ #define __INCLUDED_WUSER_H__ #include <sstream> #include <cstring> #include <string> #include "sdk/vardec.h" /** * User Class - Represents a User record */ class WUser { public: // Constants // USERREC.inact static const int userDeleted = 0x01; static const int userInactive = 0x02; // USERREC.exempt static const int exemptRatio = 0x01; static const int exemptTime = 0x02; static const int exemptPost = 0x04; static const int exemptAll = 0x08; static const int exemptAutoDelete = 0x10; // USERREC.restrict static const int restrictLogon = 0x0001; static const int restrictChat = 0x0002; static const int restrictValidate = 0x0004; static const int restrictAutomessage = 0x0008; static const int restrictAnony = 0x0010; static const int restrictPost = 0x0020; static const int restrictEmail = 0x0040; static const int restrictVote = 0x0080; static const int restrictMultiNodeChat = 0x0100; static const int restrictNet = 0x0200; static const int restrictUpload = 0x0400; // USERREC.sysstatus static const int ansi = 0x00000001; static const int color = 0x00000002; static const int music = 0x00000004; static const int pauseOnPage = 0x00000008; static const int expert = 0x00000010; static const int SMW = 0x00000020; static const int fullScreen = 0x00000040; static const int nscanFileSystem = 0x00000080; static const int extraColor = 0x00000100; static const int clearScreen = 0x00000200; static const int upperASCII = 0x00000400; static const int noTag = 0x00000800; static const int conference = 0x00001000; static const int noChat = 0x00002000; static const int noMsgs = 0x00004000; static const int menuSys = 0x00008000; // not used? static const int listPlus = 0x00010000; static const int autoQuote = 0x00020000; static const int twentyFourHourClock = 0x00040000; static const int msgPriority = 0x00080000; // not used? // // Data // public: struct userrec data; public: // // Constructors and Destructors // WUser(); ~WUser(); WUser(const WUser& w); WUser& operator=(const WUser& rhs); // // Member Functions // void FixUp(); // was function fix_user_rec void ZeroUserData(); // // Accessor Functions // const char *GetUserNameAndNumber(int nUserNumber) const; const char *GetUserNameNumberAndSystem(int nUserNumber, int nSystemNumber) const; // USERREC.inact void SetInactFlag(int nFlag) { data.inact |= nFlag; } void ToggleInactFlag(int nFlag) { data.inact ^= nFlag; } void ClearInactFlag(int nFlag) { data.inact &= ~nFlag; } bool IsUserDeleted() const { /* printf( "DEBUG: User %s is deleted!\r\n", data.name ); */ return (data.inact & WUser::userDeleted) != 0; } bool IsUserInactive() const { return (data.inact & WUser::userInactive) != 0; } // USERREC.sysstatus void SetStatusFlag(int nFlag) { data.sysstatus |= nFlag; } void ToggleStatusFlag(int nFlag) { data.sysstatus ^= nFlag; } void ClearStatusFlag(int nFlag) { data.sysstatus &= ~nFlag; } bool HasStatusFlag(int nFlag) const { return (data.sysstatus & nFlag) != 0; } long GetStatus() const { return static_cast<long>(data.sysstatus); } void SetStatus(long l) { data.sysstatus = static_cast<unsigned long>(l); } bool HasAnsi() const { return HasStatusFlag(WUser::ansi); } bool HasColor() const { return HasStatusFlag(WUser::color); } bool HasMusic() const { return HasStatusFlag(WUser::music); } bool HasPause() const { return HasStatusFlag(WUser::pauseOnPage); } bool IsExpert() const { return HasStatusFlag(WUser::expert); } bool HasShortMessage() const { return HasStatusFlag(WUser::SMW); } bool IsFullScreen() const { return HasStatusFlag(WUser::fullScreen); } bool IsNewScanFiles() const { return HasStatusFlag(WUser::nscanFileSystem); } bool IsUseExtraColor() const { return HasStatusFlag(WUser::extraColor); } bool IsUseClearScreen() const { return HasStatusFlag(WUser::clearScreen); } bool IsUseNoTagging() const { return HasStatusFlag(WUser::noTag); } bool IsUseConference() const { return HasStatusFlag(WUser::conference); } bool IsIgnoreChatRequests() const { return HasStatusFlag(WUser::noChat); } bool IsIgnoreNodeMessages() const { return HasStatusFlag(WUser::noMsgs); } bool IsUseListPlus() const { return HasStatusFlag(WUser::listPlus); } bool IsUseAutoQuote() const { return HasStatusFlag(WUser::autoQuote); } bool IsUse24HourClock() const { return HasStatusFlag(WUser::twentyFourHourClock); }; // USERREC.exempt void SetExemptFlag(int nFlag) { data.exempt |= nFlag; } void ToggleExemptFlag(int nFlag) { data.exempt ^= nFlag; } void ClearExemptFlag(int nFlag) { data.exempt &= ~nFlag; } bool HasExemptFlag(int nFlag) const { return (data.exempt & nFlag) != 0; } bool IsExemptRatio() { return HasExemptFlag(WUser::exemptRatio); } bool IsExemptTime() { return HasExemptFlag(WUser::exemptTime); } bool IsExemptPost() { return HasExemptFlag(WUser::exemptPost); } bool IsExemptAll() { return HasExemptFlag(WUser::exemptAll); } bool IsExemptAutoDelete() { return HasExemptFlag(WUser::exemptAutoDelete); } // USERREC.restrict void SetRestrictionFlag(int nFlag) { data.restrict |= nFlag; } void ToggleRestrictionFlag(int nFlag) { data.restrict ^= nFlag; } void ClearRestrictionFlag(int nFlag) { data.restrict &= ~nFlag; } bool HasRestrictionFlag(int nFlag) const { return (data.restrict & nFlag) != 0; } unsigned short GetRestriction() const { return data.restrict; } void SetRestriction(int n) { data.restrict = static_cast<unsigned short>(n); } bool IsRestrictionLogon() { return HasRestrictionFlag(WUser::restrictLogon); } bool IsRestrictionChat() { return HasRestrictionFlag(WUser::restrictChat); } bool IsRestrictionValidate() { return HasRestrictionFlag(WUser::restrictValidate); } bool IsRestrictionAutomessage() { return HasRestrictionFlag(WUser::restrictAutomessage); } bool IsRestrictionAnonymous() { return HasRestrictionFlag(WUser::restrictAnony); } bool IsRestrictionPost() { return HasRestrictionFlag(WUser::restrictPost); } bool IsRestrictionEmail() { return HasRestrictionFlag(WUser::restrictEmail); } bool IsRestrictionVote() { return HasRestrictionFlag(WUser::restrictVote); } bool IsRestrictionMultiNodeChat() { return HasRestrictionFlag(WUser::restrictMultiNodeChat); } bool IsRestrictionNet() { return HasRestrictionFlag(WUser::restrictNet); } bool IsRestrictionUpload() { return HasRestrictionFlag(WUser::restrictUpload); } void SetArFlag(int nFlag) { data.ar |= nFlag; } void ToggleArFlag(int nFlag) { data.ar ^= nFlag; } void ClearArFlag(int nFlag) { data.ar &= ~nFlag; } bool HasArFlag(int nFlag) const { return (data.ar & nFlag) != 0; } unsigned short GetAr() const { return data.ar; } void SetAr(int n) { data.ar = static_cast<unsigned short>(n); } void SetDarFlag(int nFlag) { data.dar |= nFlag; } void ToggleDarFlag(int nFlag) { data.dar ^= nFlag; } void ClearDarFlag(int nFlag) { data.dar &= ~nFlag; } bool HasDarFlag(int nFlag) const { return (data.dar & nFlag) != 0; } unsigned short GetDar() const { return data.dar; } void SetDar(int n) { data.dar = static_cast<unsigned short>(n); } const char *GetName() const { return reinterpret_cast<const char*>(data.name); } void SetName(const char *s) { strcpy(reinterpret_cast<char*>(data.name), s); } const char *GetRealName() const { return reinterpret_cast<const char*>(data.realname); } void SetRealName(const char *s) { strcpy(reinterpret_cast<char*>(data.realname), s); } const char *GetCallsign() const { return reinterpret_cast<const char*>(data.callsign); } void SetCallsign(const char *s) { strcpy(reinterpret_cast<char*>(data.callsign), s); } const char *GetVoicePhoneNumber() const { return reinterpret_cast<const char*>(data.phone); } void SetVoicePhoneNumber(const char *s) { strcpy(reinterpret_cast<char*>(data.phone), s); } const char *GetDataPhoneNumber() const { return reinterpret_cast<const char*>(data.dataphone); } void SetDataPhoneNumber(const char *s) { strcpy(reinterpret_cast<char*>(data.dataphone), s); } const char *GetStreet() const { return reinterpret_cast<const char*>(data.street); } void SetStreet(const char *s) { strcpy(reinterpret_cast<char*>(data.street), s); } const char *GetCity() const { return reinterpret_cast<const char*>(data.city); } void SetCity(const char *s) { strcpy(reinterpret_cast<char*>(data.city), s); } const char *GetState() const { return reinterpret_cast<const char*>(data.state); } void SetState(const char *s) { strcpy(reinterpret_cast<char*>(data.state), s); } const char *GetCountry() const { return reinterpret_cast<const char*>(data.country); } void SetCountry(const char *s) { strcpy(reinterpret_cast<char*>(data.country) , s); } const char *GetZipcode() const { return reinterpret_cast<const char*>(data.zipcode); } void SetZipcode(const char *s) { strcpy(reinterpret_cast<char*>(data.zipcode), s); } const char *GetPassword() const { return reinterpret_cast<const char*>(data.pw); } void SetPassword(const char *s) { strcpy(reinterpret_cast<char*>(data.pw), s); } const char *GetLastOn() const { return reinterpret_cast<const char*>(data.laston); } void SetLastOn(const char *s) { strcpy(reinterpret_cast<char*>(data.laston), s); } const char *GetFirstOn() const { return reinterpret_cast<const char*>(data.firston); } void SetFirstOn(const char *s) { strcpy(reinterpret_cast<char*>(data.firston), s); } const char *GetNote() const { return reinterpret_cast<const char*>(data.note); } void SetNote(const char *s) { strcpy(reinterpret_cast<char*>(data.note), s); } const char *GetMacro(int nLine) const { return reinterpret_cast<const char*>(data.macros[ nLine ]); } void SetMacro(int nLine, const char *s) { memset(&data.macros[ nLine ][0], 0, 80); strcpy(reinterpret_cast<char*>(data.macros[ nLine ]), s); } const char GetGender() const { if (data.sex == 'N') { // N means unknowN. NEWUSER sets it to N to prompt the // user again. return 'N'; } return data.sex == 'F' ? 'F' : 'M'; } void SetGender(const char c) { data.sex = static_cast<unsigned char>(c); } const char *GetEmailAddress() const { return data.email; } void SetEmailAddress(const char *s) { strcpy(reinterpret_cast<char*>(data.email), s); } const int GetAge() const { return data.age; } void SetAge(int n) { data.age = static_cast<unsigned char>(n); } const int GetComputerType() const { return data.comp_type; } void SetComputerType(int n) { data.comp_type = static_cast<char>(n); } const int GetDefaultProtocol() const { return data.defprot; } void SetDefaultProtocol(int n) { data.defprot = static_cast<unsigned char>(n); } const int GetDefaultEditor() const { return data.defed; } void SetDefaultEditor(int n) { data.defed = static_cast<unsigned char>(n); } const int GetScreenChars() const { return data.screenchars; } void SetScreenChars(int n) { data.screenchars = static_cast<unsigned char>(n); } const int GetScreenLines() const { return data.screenlines; } void SetScreenLines(int n) { data.screenlines = static_cast<unsigned char>(n); } const int GetNumExtended() const { return data.num_extended; } void SetNumExtended(int n) { data.num_extended = static_cast<unsigned char>(n); } const int GetOptionalVal() const { return data.optional_val; } void SetOptionalVal(int n) { data.optional_val = static_cast<unsigned char>(n); } const int GetSl() const { return data.sl; } void SetSl(int n) { data.sl = static_cast<unsigned char>(n); } const int GetDsl() const { return data.dsl; } void SetDsl(int n) { data.dsl = static_cast<unsigned char>(n); } const int GetExempt() const { return data.exempt; } void SetExempt(int n) { data.exempt = static_cast<unsigned char>(n); } const unsigned char GetColor(int nColor) const { return data.colors[ nColor ]; } void SetColor(int nColor, int n) { data.colors[ nColor ] = static_cast<unsigned char>(n); } const unsigned char GetBWColor(int nColor) const { return data.bwcolors[ nColor ]; } void SetBWColor(int nColor, int n) { data.bwcolors[ nColor ] = static_cast<unsigned char>(n); } const int GetVote(int nVote) const { return data.votes[ nVote ]; } void SetVote(int nVote, int n) { data.votes[ nVote ] = static_cast<unsigned char>(n); } const int GetNumIllegalLogons() const { return data.illegal; } void SetNumIllegalLogons(int n) { data.illegal = static_cast<unsigned char>(n); } const int GetNumMailWaiting() const { return data.waiting; } void SetNumMailWaiting(int n) { data.waiting = static_cast<unsigned char>(n); } const int GetTimesOnToday() const { return data.ontoday; } void SetTimesOnToday(int n) { data.ontoday = static_cast<unsigned char>(n); } const int GetBirthdayMonth() const { return data.month; } void SetBirthdayMonth(int n) { data.month = static_cast<unsigned char>(n); } const int GetBirthdayDay() const { return data.day; } void SetBirthdayDay(int n) { data.day = static_cast<unsigned char>(n); } const int GetBirthdayYear() const { return data.year + 1900; } const int GetBirthdayYearShort() const { return data.year; } void SetBirthdayYear(int n) { if(n == 0){ data.year = static_cast<unsigned char>(n); }else{ data.year = static_cast<unsigned char>(n-1900); } } const int GetLanguage() const { return data.language; } void SetLanguage(int n) { data.language = static_cast<unsigned char>(n); } const int GetCbv() const { return data.cbv; } void SetCbv(int n) { data.cbv = static_cast<unsigned char>(n); } const int GetHomeUserNumber() const { return data.homeuser; } void SetHomeUserNumber(int n) { data.homeuser = static_cast<unsigned short>(n); } const int GetHomeSystemNumber() const { return data.homesys; } void SetHomeSystemNumber(int n) { data.homesys = static_cast<unsigned short>(n); } const int GetForwardUserNumber() const { return data.forwardusr; } void SetForwardUserNumber(int n) { data.forwardusr = static_cast<unsigned short>(n); } const int GetForwardSystemNumber() const { return data.forwardsys; } void SetForwardSystemNumber(int n) { data.forwardsys = static_cast<unsigned short>(n); } const int GetForwardNetNumber() const { return data.net_num; } void SetForwardNetNumber(int n) { data.net_num = static_cast<unsigned short>(n); } const int GetNumMessagesPosted() const { return data.msgpost; } void SetNumMessagesPosted(int n) { data.msgpost = static_cast<unsigned short>(n); } const int GetNumEmailSent() const { return data.emailsent; } void SetNumEmailSent(int n) { data.emailsent = static_cast<unsigned short>(n); } const int GetNumFeedbackSent() const { return data.feedbacksent; } void SetNumFeedbackSent(int n) { data.feedbacksent = static_cast<unsigned short>(n); } const int GetNumFeedbackSentToday() const { return data.fsenttoday1; } void SetNumFeedbackSentToday(int n) { data.fsenttoday1 = static_cast<unsigned short>(n); } const int GetNumPostsToday() const { return data.posttoday; } void SetNumPostsToday(int n) { data.posttoday = static_cast<unsigned short>(n); } const int GetNumEmailSentToday() const { return data.etoday; } void SetNumEmailSentToday(int n) { data.etoday = static_cast<unsigned short>(n); } const int GetAssPoints() const { return data.ass_pts; } void SetAssPoints(int n) { data.ass_pts = static_cast<unsigned short>(n); } void IncrementAssPoints(int n) { data.ass_pts = data.ass_pts + static_cast<unsigned short>(n); } const int GetFilesUploaded() const { return data.uploaded; } void SetFilesUploaded(int n) { data.uploaded = static_cast<unsigned short>(n); } const int GetFilesDownloaded() const { return data.downloaded; } void SetFilesDownloaded(int n) { data.downloaded = static_cast<unsigned short>(n); } const int GetLastBaudRate() const { return data.lastrate; } void SetLastBaudRate(int n) { data.lastrate = static_cast<unsigned short>(n); } const int GetNumLogons() const { return data.logons; } void SetNumLogons(int n) { data.logons = static_cast<unsigned short>(n); } const int GetNumNetEmailSent() const { return data.emailnet; } void SetNumNetEmailSent(int n) { data.emailnet = static_cast<unsigned short>(n); } const int GetNumNetPosts() const { return data.postnet; } void SetNumNetPosts(int n) { data.postnet = static_cast<unsigned short>(n); } const int GetNumDeletedPosts() const { return data.deletedposts; } void SetNumDeletedPosts(int n) { data.deletedposts = static_cast<unsigned short>(n); } const int GetNumChainsRun() const { return data.chainsrun; } void SetNumChainsRun(int n) { data.chainsrun = static_cast<unsigned short>(n); } const int GetNumGFilesRead() const { return data.gfilesread; } void SetNumGFilesRead(int n) { data.gfilesread = static_cast<unsigned short>(n); } const int GetTimeBankMinutes() const { return data.banktime; } void SetTimeBankMinutes(int n) { data.banktime = static_cast<unsigned short>(n); } const int GetHomeNetNumber() const { return data.homenet; } void SetHomeNetNumber(int n) { data.homenet = static_cast<unsigned short>(n); } const int GetLastSubConf() const { return data.subconf; } void SetLastSubConf(int n) { data.subconf = static_cast<unsigned short>(n); } const int GetLastDirConf() const { return data.dirconf; } void SetLastDirConf(int n) { data.dirconf = static_cast<unsigned short>(n); } const int GetLastSubNum() const { return data.subnum; } void SetLastSubNum(int n) { data.subnum = static_cast<unsigned short>(n); } const int GetLastDirNum() const { return data.dirnum; } void SetLastDirNum(int n) { data.dirnum = static_cast<unsigned short>(n); } const unsigned long GetNumMessagesRead() const { return data.msgread; } void SetNumMessagesRead(unsigned long l) { data.msgread = l; } const unsigned long GetUploadK() const { return data.uk; } void SetUploadK(unsigned long l) { data.uk = l; } const unsigned long GetDownloadK() const { return data.dk; } void SetDownloadK(unsigned long l) { data.dk = l; } const unsigned long GetLastOnDateNumber() const { return data.daten; } void SetLastOnDateNumber(unsigned long l) { data.daten = l; } const unsigned long GetWWIVRegNumber() const { return data.wwiv_regnum; } void SetWWIVRegNumber(unsigned long l) { data.wwiv_regnum = l; } const unsigned long GetFilePoints() const { return data.filepoints; } void SetFilePoints(unsigned long l) { data.filepoints = l; } const unsigned long GetRegisteredDateNum() const { return data.registered; } void SetRegisteredDateNum(unsigned long l) { data.registered = l; } const unsigned long GetExpiresDateNum() const { return data.expires; } void SetExpiresDateNum(unsigned long l) { data.expires = l; } const unsigned long GetNewScanDateNumber() const { return data.datenscan; } void SetNewScanDateNumber(unsigned long l) { data.datenscan = l; } const float GetTimeOnToday() const { return data.timeontoday; } void SetTimeOnToday(float f) { data.timeontoday = f; } const float GetExtraTime() const { return data.extratime; } void SetExtraTime(float f) { data.extratime = f; } const float GetTimeOn() const { return data.timeon; } void SetTimeOn(float f) { data.timeon = f; } const float GetGold() const { return data.gold; } void SetGold(float f) { data.gold = f; } bool GetFullFileDescriptions() const { return data.full_desc ? true : false; } void SetFullFileDescriptions(bool b) { data.full_desc = b ? 1 : 0; } bool IsMailboxClosed() const { return (GetForwardUserNumber() == 65535) ? true : false; } void CloseMailbox() { SetForwardSystemNumber(0); SetForwardUserNumber(65535); } bool IsMailForwardedToInternet() const { return (GetForwardUserNumber() == 32767) ? true : false; } bool IsMailboxForwarded() const { return (GetForwardUserNumber() > 0 && GetForwardUserNumber() < 32767); } void SetForwardToInternet() { SetForwardSystemNumber(32767); } void ClearMailboxForward() { SetForwardSystemNumber(0); SetForwardUserNumber(0); } // // Private Methods // private: char *nam(int nUserNumber) const; char *nam1(int nUserNumber, int nSystemNumber) const; }; /** * */ class WUserManager { private: std::string m_dataDirectory; int m_nUserRecordLength; int m_nMaxNumberOfUsers; bool m_bUserWritesAllowed; bool m_bInitalized; public: WUserManager(); WUserManager(std::string dataDirectory, int nUserRecordLength, int nMaxNumberOfUsers); ~WUserManager(); int GetNumberOfUserRecords() const; bool ReadUserNoCache(WUser *pUser, int nUserNumber); bool ReadUser(WUser *pUser, int nUserNumber, bool bForceRead = false); bool WriteUserNoCache(WUser *pUser, int nUserNumber); bool WriteUser(WUser *pUser, int nUserNumber); int FindUser(std::string searchString); void InitializeUserManager(std::string dataDirectory, int nUserRecordLength, int nMaxNumberOfUsers); /** * Setting this to false will disable writing the userrecord to disk. This should ONLY be false when the * Global guest_user variable is true. */ void SetUserWritesAllowed(bool bUserWritesAllowed) { m_bUserWritesAllowed = bUserWritesAllowed; } bool IsUserWritesAllowed() { return m_bUserWritesAllowed; } }; #endif // __INCLUDED_PLATFORM_WUSER_H__
[ "ec2-user@nfs.mdwestserve.com" ]
ec2-user@nfs.mdwestserve.com
3d138f736d9f44fd457988f5c6fc36e428a37784
aa4669a80c56029423c8587d9eac3f69c6d5a1fd
/testproj/bin/android/obj/include/openfl/utils/Float32Array.h
67a1335aaaca862ea46ef9d50e6f56d72c43dda7
[]
no_license
shadowofsoul/testproj
aa9c04bfd72262f2aaaa5c1cf366ab2f5c5385ec
e31016cb0cedf7b966b166f99cfd41f36896ac1e
refs/heads/master
2021-01-01T18:54:42.559141
2014-02-08T00:09:25
2014-02-08T00:09:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,597
h
#ifndef INCLUDED_openfl_utils_Float32Array #define INCLUDED_openfl_utils_Float32Array #ifndef HXCPP_H #include <hxcpp.h> #endif #include <openfl/utils/ArrayBufferView.h> HX_DECLARE_CLASS2(flash,geom,Matrix3D) HX_DECLARE_CLASS2(openfl,utils,ArrayBufferView) HX_DECLARE_CLASS2(openfl,utils,Float32Array) HX_DECLARE_CLASS2(openfl,utils,IMemoryRange) namespace openfl{ namespace utils{ class HXCPP_CLASS_ATTRIBUTES Float32Array_obj : public ::openfl::utils::ArrayBufferView_obj{ public: typedef ::openfl::utils::ArrayBufferView_obj super; typedef Float32Array_obj OBJ_; Float32Array_obj(); Void __construct(Dynamic bufferOrArray,hx::Null< int > __o_start,Dynamic length); public: static hx::ObjectPtr< Float32Array_obj > __new(Dynamic bufferOrArray,hx::Null< int > __o_start,Dynamic length); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~Float32Array_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); ::String __ToString() const { return HX_CSTRING("Float32Array"); } typedef Float __array_access; virtual Void __set( int index,Float value); Dynamic __set_dyn(); virtual Float __get( int index); Dynamic __get_dyn(); int length; int BYTES_PER_ELEMENT; static ::openfl::utils::Float32Array fromMatrix( ::flash::geom::Matrix3D matrix); static Dynamic fromMatrix_dyn(); }; } // end namespace openfl } // end namespace utils #endif /* INCLUDED_openfl_utils_Float32Array */
[ "david@y-developments.com" ]
david@y-developments.com
670ef95934c79da933357bd21ce3e0b467051eca
44f00508be92f9bb6a36bca9552b75355b104c96
/lineDDA3/main.cpp
ef54084ada4727f37dcfc70fb0b47c0879fd30df
[]
no_license
mittrayash/Computer-Graphics-Programs
f4a832a5b546a0e30a232c84706af16dbf036c3a
8e931aedffa30458a5b711db18455c3ce26d54fb
refs/heads/master
2021-07-10T09:36:39.495440
2017-10-10T06:50:15
2017-10-10T06:50:15
106,378,570
2
0
null
null
null
null
UTF-8
C++
false
false
905
cpp
#include <stdio.h> #include <stdlib.h> #include <graphics.h> #include <conio.h> #define Round(x) ((int)(x+0.5)) int main() { float xIncrement, yIncrement, x, y, step; int dx, dy, i, x1, x2, y1, y2; int gDriver = DETECT, gmode, errorCode; initgraph(&gDriver, &gmode, "C:\\TC\\BGI"); errorCode = graphresult(); if(errorCode != 0){ printf("Graphic Error", grapherrormsg(errorCode)); exit(1); } printf("Enter x1, y1, x2, y2"); scanf("%d%d%d%d", &x1, &x2, &y1, &y2); dx = x2 - x1; dy = y2 - y1; if(dx>dy) step = dx; else step = dy; xIncrement = dx/step; yIncrement = dy/step; x = x1; y = y1; putpixel(Round(x), Round(y), RED); for(i=0; i<step; i++){ x += xIncrement; y += yIncrement; putpixel(Round(x), Round(y), RED); } getch(); closegraph(); return 0; }
[ "mittrayash@gmail.com" ]
mittrayash@gmail.com
bd413eb269619ecbd160f24feeeeceaef0df821f
78b45a21181a173caa0162ec290a65388ad5cbe6
/to1bitdialog.cpp
d2a3b805f0729778c939963f0d0053243835a501
[ "MIT" ]
permissive
rexpit/cpp-simpleimage
68555daa9390f00a636f2a124881cead80246069
cbefb18f6b1b947eade7b1621a7c6580e0cf8094
refs/heads/master
2020-05-29T23:18:05.425932
2017-01-12T02:40:48
2017-01-12T02:40:48
3,775,084
0
0
null
null
null
null
UTF-8
C++
false
false
517
cpp
#include "to1bitdialog.hpp" #include "ui_to1bitdialog.h" To1BitDialog::To1BitDialog(QWidget *parent) : QDialog(parent), ui(new Ui::To1BitDialog) { ui->setupUi(this); } To1BitDialog::~To1BitDialog() { delete ui; } To1BitDialog::WayTo1Bit To1BitDialog::getWayTo1Bit() const { return this->ui->radioButtonB->isChecked() ? WayThresholdMethod : this->ui->radioButtonE->isChecked() ? WayErrorDiffusionMethod : WayIllegal; } int To1BitDialog::getThreshold() const { return this->ui->spinBoxT->value(); }
[ "loxyplst+github@gmail.com" ]
loxyplst+github@gmail.com
a02853adb7eeea4ce2ecb53f3283e8132698cad2
08c49ab21b5a7b79487fc55f9f5425f0b09dc4f9
/DSAA3/Fig01_22.cpp
db9cd745f6d2480d860a86df1753af8b9bc0a4d0
[ "MIT" ]
permissive
crosslife/DSAA
f03a46781bd5a496944e00e92a31ed1f2f56623e
03472db6e61582187192073b6ea4649b6195222b
refs/heads/master
2021-03-12T20:45:18.195236
2013-11-06T08:10:49
2013-11-06T08:10:49
14,159,406
5
1
null
null
null
null
UTF-8
C++
false
false
855
cpp
#include <iostream> #include <vector> #include <string> #include <cstring> using namespace std; // Generic findMax, with a function object, Version #1. // Precondition: a.size( ) > 0. template <typename Object, typename Comparator> const Object & findMax( const vector<Object> & arr, Comparator cmp ) { int maxIndex = 0; for( int i = 1; i < arr.size( ); i++ ) if( cmp.isLessThan( arr[ maxIndex ], arr[ i ] ) ) maxIndex = i; return arr[ maxIndex ]; } class CaseInsensitiveCompare { public: bool isLessThan( const string & lhs, const string & rhs ) const { return stricmp( lhs.c_str( ), rhs.c_str( ) ) < 0; } }; int main( ) { vector<string> arr( 3 ); arr[ 0 ] = "ZEBRA"; arr[ 1 ] = "alligator"; arr[ 2 ] = "crocodile"; cout << findMax( arr, CaseInsensitiveCompare( ) ) << endl; return 0; }
[ "geziyang@foxmail.com" ]
geziyang@foxmail.com
3f9d54d30c506998fa1aec78e07c9c52f0e94fce
e6de827b14aa9e48e048f56d789f0ee07fdc19a4
/SW/Winscope/DotNet/ProgressDlg.cpp
0c23fe0584cee409cde9781d4cbf6636bfe0c262
[]
no_license
stfrha/winscope
2d93cd0917a8a6c28c541adc8a7ccae91f90c4c1
fafd9e02b934577fa6193a28662749b53e7a82c7
refs/heads/master
2023-07-12T21:49:47.208467
2021-08-23T20:52:09
2021-08-23T20:52:09
399,244,429
1
0
null
null
null
null
UTF-8
C++
false
false
990
cpp
// ProgressDlg.cpp : implementation file // #include "stdafx.h" #include "winscope.h" #include "ProgressDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CProgressDlg dialog CProgressDlg::CProgressDlg(CWnd* pParent /*=NULL*/) : CDialog(CProgressDlg::IDD, pParent) { //{{AFX_DATA_INIT(CProgressDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CProgressDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CProgressDlg) DDX_Control(pDX, IDC_PROGRESS, m_progress); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CProgressDlg, CDialog) //{{AFX_MSG_MAP(CProgressDlg) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CProgressDlg message handlers
[ "mail@fredrikhoffman.se" ]
mail@fredrikhoffman.se
532bef985679c980b77f239873f8ec6c6bc05f07
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/242/604/CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_calloc_43.cpp
dd003cca9f44a18249012799e61d01c047dca687
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
3,130
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_calloc_43.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-43.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: calloc Allocate data using calloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_calloc_43 { #ifndef OMITBAD void badSource(int64_t * &data) { /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (int64_t *)calloc(100, sizeof(int64_t)); if (data == NULL) {exit(-1);} } void bad() { int64_t * data; /* Initialize data*/ data = NULL; badSource(data); /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSource(int64_t * &data) { /* FIX: Allocate memory from the heap using new */ data = new int64_t; } static void goodG2B() { int64_t * data; /* Initialize data*/ data = NULL; goodG2BSource(data); /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } /* goodB2G() uses the BadSource with the GoodSink */ static void goodB2GSource(int64_t * &data) { /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (int64_t *)calloc(100, sizeof(int64_t)); if (data == NULL) {exit(-1);} } static void goodB2G() { int64_t * data; /* Initialize data*/ data = NULL; goodB2GSource(data); /* FIX: Deallocate the memory using free() */ free(data); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_calloc_43; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
fddee518fd81102ed6d85cdade350fdcb8e0b1c9
7b7291307cf15a055f36ba1725d799a6cbd7013c
/build-qt21_qtreewidget-Desktop_Qt_5_5_1_GCC_64bit-Debug/moc_dialog.cpp
6e76c73ff322097d8aa546cfa0c7f6f6e10043b2
[]
no_license
heqile/QT
6a243c89e24f64d1bf5f3ef021010cfb3ad1f3ef
10b9920ccfd3fef8ea507b364b0cbcba39fe97df
refs/heads/master
2021-01-10T10:42:54.256237
2016-02-18T23:04:12
2016-02-18T23:04:12
51,940,543
0
0
null
null
null
null
UTF-8
C++
false
false
3,273
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'dialog.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../qt21_qtreewidget/dialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'dialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_Dialog_t { QByteArrayData data[3]; char stringdata0[30]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Dialog_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Dialog_t qt_meta_stringdata_Dialog = { { QT_MOC_LITERAL(0, 0, 6), // "Dialog" QT_MOC_LITERAL(1, 7, 21), // "on_pushButton_clicked" QT_MOC_LITERAL(2, 29, 0) // "" }, "Dialog\0on_pushButton_clicked\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Dialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 19, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, 0 // eod }; void Dialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Dialog *_t = static_cast<Dialog *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_pushButton_clicked(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject Dialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_Dialog.data, qt_meta_data_Dialog, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *Dialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Dialog::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_Dialog.stringdata0)) return static_cast<void*>(const_cast< Dialog*>(this)); return QDialog::qt_metacast(_clname); } int Dialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
[ "mr.qile@gmail.com" ]
mr.qile@gmail.com
ac5aa5c88464d61b7f5d88c0d424be4f68c227c4
c1ff870879152fba2b54eddfb7591ec322eb3061
/plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/deps/v8/src/heap/worklist.h
bb3eae222845bd592b1ba469befe42daed4c2910
[ "LicenseRef-scancode-free-unknown", "MIT", "ISC", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "Artistic-2.0", "NAIST-2003", "BSD-3-Clause", "Zlib", "NTP", "LicenseRef-scancode-openssl", "ICU", "LicenseRef-scancode-unicode", "LicenseRef-scancode-unknown-license-reference", "bzip2...
permissive
MTASZTAKI/ApertusVR
1a9809fb7af81c3cd7fb732ed481ebe4ce66fefa
424ec5515ae08780542f33cc4841a8f9a96337b3
refs/heads/0.9
2022-12-11T20:03:42.926813
2019-10-11T09:29:45
2019-10-11T09:29:45
73,708,854
188
55
MIT
2022-12-11T08:53:21
2016-11-14T13:48:00
C++
UTF-8
C++
false
false
11,099
h
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_HEAP_WORKLIST_H_ #define V8_HEAP_WORKLIST_H_ #include <cstddef> #include <utility> #include "src/base/atomic-utils.h" #include "src/base/logging.h" #include "src/base/macros.h" #include "src/base/platform/mutex.h" #include "testing/gtest/include/gtest/gtest_prod.h" // nogncheck namespace v8 { namespace internal { // A concurrent worklist based on segments. Each tasks gets private // push and pop segments. Empty pop segments are swapped with their // corresponding push segments. Full push segments are published to a global // pool of segments and replaced with empty segments. // // Work stealing is best effort, i.e., there is no way to inform other tasks // of the need of items. template <typename EntryType, int SEGMENT_SIZE> class Worklist { public: class View { public: View(Worklist<EntryType, SEGMENT_SIZE>* worklist, int task_id) : worklist_(worklist), task_id_(task_id) {} // Pushes an entry onto the worklist. bool Push(EntryType entry) { return worklist_->Push(task_id_, entry); } // Pops an entry from the worklist. bool Pop(EntryType* entry) { return worklist_->Pop(task_id_, entry); } // Returns true if the local portion of the worklist is empty. bool IsLocalEmpty() { return worklist_->IsLocalEmpty(task_id_); } // Returns true if the worklist is empty. Can only be used from the main // thread without concurrent access. bool IsGlobalEmpty() { return worklist_->IsGlobalEmpty(); } bool IsGlobalPoolEmpty() { return worklist_->IsGlobalPoolEmpty(); } size_t LocalPushSegmentSize() { return worklist_->LocalPushSegmentSize(task_id_); } private: Worklist<EntryType, SEGMENT_SIZE>* worklist_; int task_id_; }; static const int kMaxNumTasks = 8; static const size_t kSegmentCapacity = SEGMENT_SIZE; Worklist() : Worklist(kMaxNumTasks) {} explicit Worklist(int num_tasks) : num_tasks_(num_tasks) { for (int i = 0; i < num_tasks_; i++) { private_push_segment(i) = NewSegment(); private_pop_segment(i) = NewSegment(); } } ~Worklist() { CHECK(IsGlobalEmpty()); for (int i = 0; i < num_tasks_; i++) { DCHECK_NOT_NULL(private_push_segment(i)); DCHECK_NOT_NULL(private_pop_segment(i)); delete private_push_segment(i); delete private_pop_segment(i); } } bool Push(int task_id, EntryType entry) { DCHECK_LT(task_id, num_tasks_); DCHECK_NOT_NULL(private_push_segment(task_id)); if (!private_push_segment(task_id)->Push(entry)) { PublishPushSegmentToGlobal(task_id); bool success = private_push_segment(task_id)->Push(entry); USE(success); DCHECK(success); } return true; } bool Pop(int task_id, EntryType* entry) { DCHECK_LT(task_id, num_tasks_); DCHECK_NOT_NULL(private_pop_segment(task_id)); if (!private_pop_segment(task_id)->Pop(entry)) { if (!private_push_segment(task_id)->IsEmpty()) { Segment* tmp = private_pop_segment(task_id); private_pop_segment(task_id) = private_push_segment(task_id); private_push_segment(task_id) = tmp; } else if (!StealPopSegmentFromGlobal(task_id)) { return false; } bool success = private_pop_segment(task_id)->Pop(entry); USE(success); DCHECK(success); } return true; } size_t LocalPushSegmentSize(int task_id) { return private_push_segment(task_id)->Size(); } bool IsLocalEmpty(int task_id) { return private_pop_segment(task_id)->IsEmpty() && private_push_segment(task_id)->IsEmpty(); } bool IsGlobalPoolEmpty() { return global_pool_.IsEmpty(); } bool IsGlobalEmpty() { for (int i = 0; i < num_tasks_; i++) { if (!IsLocalEmpty(i)) return false; } return global_pool_.IsEmpty(); } size_t LocalSize(int task_id) { return private_pop_segment(task_id)->Size() + private_push_segment(task_id)->Size(); } // Clears all segments. Frees the global segment pool. // // Assumes that no other tasks are running. void Clear() { for (int i = 0; i < num_tasks_; i++) { private_pop_segment(i)->Clear(); private_push_segment(i)->Clear(); } global_pool_.Clear(); } // Calls the specified callback on each element of the deques and replaces // the element with the result of the callback. // The signature of the callback is // bool Callback(EntryType old, EntryType* new). // If the callback returns |false| then the element is removed from the // worklist. Otherwise the |new| entry is updated. // // Assumes that no other tasks are running. template <typename Callback> void Update(Callback callback) { for (int i = 0; i < num_tasks_; i++) { private_pop_segment(i)->Update(callback); private_push_segment(i)->Update(callback); } global_pool_.Update(callback); } template <typename Callback> void IterateGlobalPool(Callback callback) { global_pool_.Iterate(callback); } void FlushToGlobal(int task_id) { PublishPushSegmentToGlobal(task_id); PublishPopSegmentToGlobal(task_id); } void MergeGlobalPool(Worklist* other) { auto pair = other->global_pool_.Extract(); global_pool_.MergeList(pair.first, pair.second); } private: FRIEND_TEST(WorkListTest, SegmentCreate); FRIEND_TEST(WorkListTest, SegmentPush); FRIEND_TEST(WorkListTest, SegmentPushPop); FRIEND_TEST(WorkListTest, SegmentIsEmpty); FRIEND_TEST(WorkListTest, SegmentIsFull); FRIEND_TEST(WorkListTest, SegmentClear); FRIEND_TEST(WorkListTest, SegmentFullPushFails); FRIEND_TEST(WorkListTest, SegmentEmptyPopFails); FRIEND_TEST(WorkListTest, SegmentUpdateFalse); FRIEND_TEST(WorkListTest, SegmentUpdate); class Segment { public: static const size_t kCapacity = kSegmentCapacity; Segment() : index_(0) {} bool Push(EntryType entry) { if (IsFull()) return false; entries_[index_++] = entry; return true; } bool Pop(EntryType* entry) { if (IsEmpty()) return false; *entry = entries_[--index_]; return true; } size_t Size() const { return index_; } bool IsEmpty() const { return index_ == 0; } bool IsFull() const { return index_ == kCapacity; } void Clear() { index_ = 0; } template <typename Callback> void Update(Callback callback) { size_t new_index = 0; for (size_t i = 0; i < index_; i++) { if (callback(entries_[i], &entries_[new_index])) { new_index++; } } index_ = new_index; } template <typename Callback> void Iterate(Callback callback) const { for (size_t i = 0; i < index_; i++) { callback(entries_[i]); } } Segment* next() const { return next_; } void set_next(Segment* segment) { next_ = segment; } private: Segment* next_; size_t index_; EntryType entries_[kCapacity]; }; struct PrivateSegmentHolder { Segment* private_push_segment; Segment* private_pop_segment; char cache_line_padding[64]; }; class GlobalPool { public: GlobalPool() : top_(nullptr) {} V8_INLINE void Push(Segment* segment) { base::LockGuard<base::Mutex> guard(&lock_); segment->set_next(top_); set_top(segment); } V8_INLINE bool Pop(Segment** segment) { base::LockGuard<base::Mutex> guard(&lock_); if (top_ != nullptr) { *segment = top_; set_top(top_->next()); return true; } return false; } V8_INLINE bool IsEmpty() { return base::AsAtomicPointer::Relaxed_Load(&top_) == nullptr; } void Clear() { base::LockGuard<base::Mutex> guard(&lock_); Segment* current = top_; while (current != nullptr) { Segment* tmp = current; current = current->next(); delete tmp; } set_top(nullptr); } // See Worklist::Update. template <typename Callback> void Update(Callback callback) { base::LockGuard<base::Mutex> guard(&lock_); Segment* prev = nullptr; Segment* current = top_; while (current != nullptr) { current->Update(callback); if (current->IsEmpty()) { if (prev == nullptr) { top_ = current->next(); } else { prev->set_next(current->next()); } Segment* tmp = current; current = current->next(); delete tmp; } else { prev = current; current = current->next(); } } } // See Worklist::Iterate. template <typename Callback> void Iterate(Callback callback) { base::LockGuard<base::Mutex> guard(&lock_); for (Segment* current = top_; current != nullptr; current = current->next()) { current->Iterate(callback); } } std::pair<Segment*, Segment*> Extract() { Segment* top = nullptr; { base::LockGuard<base::Mutex> guard(&lock_); if (top_ == nullptr) return std::make_pair(nullptr, nullptr); top = top_; set_top(nullptr); } Segment* end = top; while (end->next() != nullptr) end = end->next(); return std::make_pair(top, end); } void MergeList(Segment* start, Segment* end) { if (start == nullptr) return; { base::LockGuard<base::Mutex> guard(&lock_); end->set_next(top_); set_top(start); } } private: void set_top(Segment* segment) { base::AsAtomicPointer::Relaxed_Store(&top_, segment); } base::Mutex lock_; Segment* top_; }; V8_INLINE Segment*& private_push_segment(int task_id) { return private_segments_[task_id].private_push_segment; } V8_INLINE Segment*& private_pop_segment(int task_id) { return private_segments_[task_id].private_pop_segment; } V8_INLINE void PublishPushSegmentToGlobal(int task_id) { if (!private_push_segment(task_id)->IsEmpty()) { global_pool_.Push(private_push_segment(task_id)); private_push_segment(task_id) = NewSegment(); } } V8_INLINE void PublishPopSegmentToGlobal(int task_id) { if (!private_pop_segment(task_id)->IsEmpty()) { global_pool_.Push(private_pop_segment(task_id)); private_pop_segment(task_id) = NewSegment(); } } V8_INLINE bool StealPopSegmentFromGlobal(int task_id) { if (global_pool_.IsEmpty()) return false; Segment* new_segment = nullptr; if (global_pool_.Pop(&new_segment)) { delete private_pop_segment(task_id); private_pop_segment(task_id) = new_segment; return true; } return false; } V8_INLINE Segment* NewSegment() { // Bottleneck for filtering in crash dumps. return new Segment(); } PrivateSegmentHolder private_segments_[kMaxNumTasks]; GlobalPool global_pool_; int num_tasks_; }; } // namespace internal } // namespace v8 #endif // V8_HEAP_WORKLIST_H_
[ "peter.kovacs@sztaki.mta.hu" ]
peter.kovacs@sztaki.mta.hu
fc970430fc3a44301e7c54b259691aefd4ad5dbc
242215eb0c915c7992898108a2420cdae8bbe477
/PhysFrolic/Classes/EduUI.h
b4f45db33ab71b2a8dc55a18ba08b8f619e13ab9
[]
no_license
archylex/Frolic
077e5f60ce0f1e6b363e19f40d58b565196e6825
b71fc681cdf603fdebc13421b41b6e1cf9185abf
refs/heads/master
2021-02-18T23:53:20.059984
2020-03-05T20:13:08
2020-03-05T20:13:08
245,253,740
0
1
null
null
null
null
UTF-8
C++
false
false
1,136
h
#ifndef __EDU_UI_H__ #define __EDU_UI_H__ #include "cocos2d.h" #include "ui/CocosGUI.h" #include "FrolicUtils.h" using namespace std; using namespace cocos2d; using namespace ui; class EduUI: public Layer { public: EduUI(); void setFirstParamName(string _s); void setSecondParamName(string _s); void setFirstParamValue(float _s, string _m); void setSecondParamValue(float _s, string _m); void setAnswerPic(string _m); void horizontalLine(Vec2 _startPos, Vec2 _endPos, string _t); void verticalLine(Vec2 _startPos, Vec2 _endPos); void trajectoryLine(Vec2 _startPos, Vec2 _endPos, float _vel, float _angle); void angleLine(Vec2 _startPos); void eraseLines(); void showInfoVec(Vec2 _pl, Vec2 _np, float _vel, float _angle); void checkString(Ref *ref, TextFiledEventType type); void setLockStart(bool _m); private: Size visibleSize; Sprite *firstParamPic; Sprite *secondParamPic; Sprite *answerPic; Label *firstParamValue; Label *secondParamValue; TextField *tf; Vector<Sprite*> arrow_array; Vector<DrawNode*> rects; bool info_vec; bool lock_start; }; #endif // __!EDU_UI_H__
[ "archylex@protonmail.com" ]
archylex@protonmail.com
6b7170b9f3514b116288125a43f33550e3dbbf08
32207a681faea81fa12d9c5bdf7e6012df281885
/display.cpp
bd87c5cbe5546b9abd558f51223dd1566597da00
[]
no_license
rvictorr/POV_Display
eceffafcfcfe84ccd2be527eff9a7a5fbdb623aa
70ebbc60f96a52e20c373c58e1040bd0bb640c33
refs/heads/master
2020-05-09T09:38:10.511165
2019-05-21T15:17:32
2019-05-21T15:17:32
181,009,714
1
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
#include "display.h" uint16_t Display::delta = 0; uint16_t Display::degree = 0; uint32_t Display::startPos = 0; uint32_t Display::rotationStartMicros = 0; uint32_t Display::timeLost = 0; std::vector<SymbolString> Display::buffer = {}; uint8_t Display::bufferIndex = 0; // const std::array<uint8_t, 10> Display::leds = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2}; const std::array<uint8_t, 10> Display::leds = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; void ISRTimer() { Display::onTimerOverflow(); }
[ "victrusu@gmail.com" ]
victrusu@gmail.com
9b352222a1c110d38414b7186ad91d97edb8683d
3e8f16e18eb953456ca399192ea8c54c1a218376
/src/game_shared/vgui_checkbutton2.cpp
85d0336104f3584b84b6fdb5a731976490cecbd2
[]
no_license
maxvollmer/Half-Life-VR
6437ffb3f6b098c0387b70c6e674572d94c0f190
f05957aa919765a1f53e54f3727e2c64ac1ec65f
refs/heads/main
2023-05-14T02:29:24.136125
2023-05-07T19:48:18
2023-05-07T19:48:18
102,905,323
241
42
null
2023-05-07T19:48:19
2017-09-08T21:19:41
C++
UTF-8
C++
false
false
3,732
cpp
//========= Copyright � 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #include <stdarg.h> #include <stdio.h> #include "vgui_checkbutton2.h" #include "vgui_loadtga.h" #define EXTRA_X 5 using namespace vgui; CCheckButton2::CCheckButton2() : m_Label(""), m_pChecked(nullptr), m_pUnchecked(nullptr), m_pHandler(nullptr), m_CheckboxPanel(nullptr) { m_bOwnImages = false; m_bChecked = false; m_pChecked = m_pUnchecked = nullptr; m_bCheckboxLeft = true; m_Label.setParent(this); m_Label.setFgColor(255, 255, 255, 0); m_Label.setBgColor(0, 0, 0, 255); // background is not drawn and foreground is white m_Label.addInputSignal(this); m_CheckboxPanel.setParent(this); m_CheckboxPanel.addInputSignal(this); setPaintBackgroundEnabled(false); } CCheckButton2::~CCheckButton2() { DeleteImages(); } void CCheckButton2::SetImages(char const* pChecked, char const* pUnchecked) { DeleteImages(); m_pChecked = vgui_LoadTGA(pChecked); m_pUnchecked = vgui_LoadTGA(pUnchecked); m_bOwnImages = true; SetupControls(); } void CCheckButton2::SetImages(Image* pChecked, Image* pUnchecked) { DeleteImages(); m_pChecked = pChecked; m_pUnchecked = pUnchecked; m_bOwnImages = false; SetupControls(); } void CCheckButton2::DeleteImages() { if (m_bOwnImages) { delete m_pChecked; delete m_pUnchecked; } m_pChecked = nullptr; m_pUnchecked = nullptr; m_bOwnImages = false; SetupControls(); } void CCheckButton2::SetCheckboxLeft(bool bLeftAlign) { m_bCheckboxLeft = bLeftAlign; SetupControls(); } bool CCheckButton2::GetCheckboxLeft() { return m_bCheckboxLeft; } void CCheckButton2::SetText(char const* pText, ...) { char str[512]; va_list marker; va_start(marker, pText); _vsnprintf_s(str, sizeof(str), pText, marker); va_end(marker); m_Label.setText(str); SetupControls(); } void CCheckButton2::SetTextColor(int r, int g, int b, int a) { m_Label.setFgColor(r, g, b, a); repaint(); } void CCheckButton2::SetHandler(ICheckButton2Handler* pHandler) { m_pHandler = pHandler; } bool CCheckButton2::IsChecked() { return m_bChecked; } void CCheckButton2::SetChecked(bool bChecked) { m_bChecked = bChecked; SetupControls(); } void CCheckButton2::internalMousePressed(MouseCode code) { m_bChecked = !m_bChecked; if (m_pHandler) m_pHandler->StateChanged(this); SetupControls(); } void CCheckButton2::SetupControls() { // Initialize the checkbutton bitmap. Image* pBitmap = m_bChecked ? m_pChecked : m_pUnchecked; Panel* controls[2] = { &m_CheckboxPanel, &m_Label }; int controlSizes[2][2]; controlSizes[0][0] = controlSizes[0][1] = 0; if (pBitmap) pBitmap->getSize(controlSizes[0][0], controlSizes[0][1]); m_CheckboxPanel.setImage(pBitmap); m_CheckboxPanel.setSize(controlSizes[0][0], controlSizes[0][1]); // Get the label's size. m_Label.getSize(controlSizes[1][0], controlSizes[1][1]); m_Label.setContentAlignment(Label::a_west); // Position the controls. int iLeftControl = !m_bCheckboxLeft; int iBiggestY = controlSizes[0][1] > controlSizes[1][0] ? 0 : 1; controls[iLeftControl]->setPos(0, (controlSizes[iBiggestY][1] - controlSizes[iLeftControl][1]) / 2); controls[!iLeftControl]->setPos(controlSizes[iLeftControl][0] + EXTRA_X, (controlSizes[iBiggestY][1] - controlSizes[!iLeftControl][1]) / 2); // Fit this control to the sizes of the subcontrols. setSize(controlSizes[0][0] + controlSizes[1][0] + EXTRA_X, (controlSizes[0][1] > controlSizes[1][1]) ? controlSizes[0][1] : controlSizes[1][1]); repaint(); } void CCheckButton2::mousePressed(MouseCode code, Panel* panel) { internalMousePressed(code); }
[ "maxvollmer@users.noreply.github.com" ]
maxvollmer@users.noreply.github.com
8cf31726c88f0d10e4afbe90745f012bd7334b1a
874ccdc2260ac36cff42d26cbb82e15d067b134f
/src/Framework/Datas/Animation2DData.cpp
e6b4dd45f0262781dd5e11621549097142bfa13d
[ "MIT" ]
permissive
xcasadio/casaengine
ae0441d6d3fa7225fdbd8717b9e6f3dfc95ba16b
4d96abab857fdbcc0892f8807b0e455fae9a9ed6
refs/heads/master
2023-03-16T04:58:43.882766
2023-03-11T10:19:05
2023-03-11T10:19:05
40,560,096
0
0
null
2020-10-08T10:32:12
2015-08-11T19:08:08
C
UTF-8
C++
false
false
556
cpp
#include "Base.h" #include "Datas/Animation2DData.h" namespace CasaEngine { Animation2DData::Animation2DData() = default; Animation2DData::Animation2DData(const Animation2DData& rsh) { *this = rsh; } Animation2DData& Animation2DData::operator=(const Animation2DData& rsh) { for (auto& frame : rsh._frames) { _frames.push_back(frame); } AnimationData::operator=(rsh); return *this; } Animation2DData::~Animation2DData() = default; Animation2DData* Animation2DData::Copy() const { return new Animation2DData(*this); } }
[ "casadprod@hotmail.fr" ]
casadprod@hotmail.fr
6bdc72b0d2c0f7794ff64682993b0e1f2e802893
324d9d9dd344b482faab3b2368b8cfee4c14c33f
/include/R0CK3T/vendors/nlohmann/json.hpp
3f0b6e3e9f628f3e213c519886c57c2a84f6a139
[]
no_license
madureira/R0CK3T
9495716ccad03f0263e71e471f945245d79df801
9a49458f391340193e7eb86673e9f4b8264a1c13
refs/heads/master
2022-03-29T18:26:29.460983
2019-08-31T22:21:53
2019-08-31T22:21:53
105,956,287
7
1
null
null
null
null
UTF-8
C++
false
false
504,383
hpp
/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 2.1.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License <http://opensource.org/licenses/MIT>. Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>. 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 NLOHMANN_JSON_HPP #define NLOHMANN_JSON_HPP #include <algorithm> // all_of, copy, fill, find, for_each, generate_n, none_of, remove, reverse, transform #include <array> // array #include <cassert> // assert #include <ciso646> // and, not, or #include <clocale> // lconv, localeconv #include <cmath> // isfinite, labs, ldexp, signbit #include <cstddef> // nullptr_t, ptrdiff_t, size_t #include <cstdint> // int64_t, uint64_t #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull #include <cstring> // memcpy, strlen #include <forward_list> // forward_list #include <functional> // function, hash, less #include <initializer_list> // initializer_list #include <iomanip> // hex #include <iosfwd> // istream, ostream #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator #include <limits> // numeric_limits #include <locale> // locale #include <map> // map #include <memory> // addressof, allocator, allocator_traits, unique_ptr #include <numeric> // accumulate #include <sstream> // stringstream #include <string> // getline, stoi, string, to_string #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type #include <utility> // declval, forward, make_pair, move, pair, swap #include <valarray> // valarray #include <vector> // vector // exclude unsupported compilers #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif // disable float-equal warnings on GCC/clang #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // disable documentation warnings on clang #if defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdocumentation" #endif // allow for portable deprecation warnings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define JSON_DEPRECATED __declspec(deprecated) #else #define JSON_DEPRECATED #endif // allow to disable exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #else #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #endif // manual branch prediction #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_LIKELY(x) __builtin_expect(!!(x), 1) #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define JSON_LIKELY(x) x #define JSON_UNLIKELY(x) x #endif /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { template<typename = void, typename = void> struct adl_serializer; // forward declaration of basic_json (required to split the class) template<template<typename U, typename V, typename... Args> class ObjectType = std::map, template<typename U, typename... Args> class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template<typename U> class AllocatorType = std::allocator, template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer> class basic_json; // Ugly macros to avoid uglier copy-paste when specializing basic_json // This is only temporary and will be removed in 3.0 #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ template<template<typename, typename, typename...> class ObjectType, \ template<typename, typename...> class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template<typename> class AllocatorType, \ template<typename, typename = void> class JSONSerializer> #define NLOHMANN_BASIC_JSON_TPL \ basic_json<ObjectType, ArrayType, StringType, BooleanType, \ NumberIntegerType, NumberUnsignedType, NumberFloatType, \ AllocatorType, JSONSerializer> /*! @brief unnamed namespace with internal helper functions This namespace collects some functions that could not be defined inside the @ref basic_json class. @since version 2.1.0 */ namespace detail { //////////////// // exceptions // //////////////// /*! @brief general exception of the @ref basic_json class This class is an extension of `std::exception` objects with a member @a id for exception ids. It is used as the base class for all exceptions thrown by the @ref basic_json class. This class can hence be used as "wildcard" to catch exceptions. Subclasses: - @ref parse_error for exceptions indicating a parse error - @ref invalid_iterator for exceptions indicating errors with iterators - @ref type_error for exceptions indicating executing a member function with a wrong type - @ref out_of_range for exceptions indicating access out of the defined range - @ref other_error for exceptions indicating other library errors @internal @note To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor. @endinternal @liveexample{The following code shows how arbitrary library exceptions can be caught.,exception} @since version 3.0.0 */ class exception : public std::exception { public: /// returns the explanatory string const char* what() const noexcept override { return m.what(); } /// the id of the exception const int id; protected: exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} static std::string name(const std::string& ename, int id_) { return "[json.exception." + ename + "." + std::to_string(id_) + "] "; } private: /// an exception object as storage for error messages std::runtime_error m; }; /*! @brief exception indicating a parse error This excpetion is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Member @a byte holds the byte index of the last read character in the input file. Exceptions have ids 1xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number wihtout a leading `0`. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xf8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). @liveexample{The following code shows how a `parse_error` exception can be caught.,parse_error} @sa @ref exception for the base class of the library exceptions @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class parse_error : public exception { public: /*! @brief create a parse error exception @param[in] id_ the id of the exception @param[in] byte_ the byte index where the error occurred (or 0 if the position cannot be determined) @param[in] what_arg the explanatory string @return parse_error object */ static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) { std::string w = exception::name("parse_error", id_) + "parse error" + (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") + ": " + what_arg; return parse_error(id_, byte_, w.c_str()); } /*! @brief byte index of the parse error The byte index of the last read character in the input file. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). */ const std::size_t byte; private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} }; /*! @brief exception indicating errors with iterators This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. name / id | example message | description ----------------------------------- | --------------- | ------------------------- json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). @liveexample{The following code shows how an `invalid_iterator` exception can be caught.,invalid_iterator} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class invalid_iterator : public exception { public: static invalid_iterator create(int id_, const std::string& what_arg) { std::string w = exception::name("invalid_iterator", id_) + what_arg; return invalid_iterator(id_, w.c_str()); } private: invalid_iterator(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating executing a member function with a wrong type This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. name / id | example message | description ----------------------------- | --------------- | ------------------------- json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. @liveexample{The following code shows how a `type_error` exception can be caught.,type_error} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class type_error : public exception { public: static type_error create(int id_, const std::string& what_arg) { std::string w = exception::name("type_error", id_) + what_arg; return type_error(id_, w.c_str()); } private: type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating access out of the defined range This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. name / id | example message | description ------------------------------- | --------------- | ------------------------- json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. @liveexample{The following code shows how an `out_of_range` exception can be caught.,out_of_range} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class out_of_range : public exception { public: static out_of_range create(int id_, const std::string& what_arg) { std::string w = exception::name("out_of_range", id_) + what_arg; return out_of_range(id_, w.c_str()); } private: out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating other library errors This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. json.exception.other_error.502 | invalid object size for conversion | Some conversions to user-defined types impose constraints on the object size (e.g. std::pair) @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @liveexample{The following code shows how an `other_error` exception can be caught.,other_error} @since version 3.0.0 */ class other_error : public exception { public: static other_error create(int id_, const std::string& what_arg) { std::string w = exception::name("other_error", id_) + what_arg; return other_error(id_, w.c_str()); } private: other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /////////////////////////// // JSON type enumeration // /////////////////////////// /*! @brief the JSON type enumeration This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions @ref basic_json::is_null(), @ref basic_json::is_object(), @ref basic_json::is_array(), @ref basic_json::is_string(), @ref basic_json::is_boolean(), @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and @ref basic_json::is_structured() rely on it. @note There are three enumeration entries (number_integer, number_unsigned, and number_float), because the library distinguishes these three types for numbers: @ref basic_json::number_unsigned_t is used for unsigned integers, @ref basic_json::number_integer_t is used for signed integers, and @ref basic_json::number_float_t is used for floating-point numbers or to approximate integers which do not fit in the limits of their respective type. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON value with the default value for a given type @since version 1.0.0 */ enum class value_t : uint8_t { null, ///< null value object, ///< object (unordered set of name/value pairs) array, ///< array (ordered collection of values) string, ///< string value boolean, ///< boolean value number_integer, ///< number value (signed integer) number_unsigned, ///< number value (unsigned integer) number_float, ///< number value (floating-point) discarded ///< discarded by the the parser callback function }; /*! @brief comparison operator for JSON types Returns an ordering that is similar to Python: - order: null < boolean < number < object < array < string - furthermore, each type is not smaller than itself @since version 1.0.0 */ inline bool operator<(const value_t lhs, const value_t rhs) noexcept { static constexpr std::array<uint8_t, 8> order = {{ 0, // null 3, // object 4, // array 5, // string 1, // boolean 2, // integer 2, // unsigned 2, // float } }; // discarded values are not comparable return lhs != value_t::discarded and rhs != value_t::discarded and order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)]; } ///////////// // helpers // ///////////// template<typename> struct is_basic_json : std::false_type {}; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {}; // alias templates to reduce boilerplate template<bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type; template<typename T> using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type; // implementation of C++14 index_sequence and affiliates // source: https://stackoverflow.com/a/32223343 template<std::size_t... Ints> struct index_sequence { using type = index_sequence; using value_type = std::size_t; static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; template<class Sequence1, class Sequence2> struct merge_and_renumber; template<std::size_t... I1, std::size_t... I2> struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>> : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; template<std::size_t N> struct make_index_sequence : merge_and_renumber < typename make_index_sequence < N / 2 >::type, typename make_index_sequence < N - N / 2 >::type > {}; template<> struct make_index_sequence<0> : index_sequence<> { }; template<> struct make_index_sequence<1> : index_sequence<0> { }; template<typename... Ts> using index_sequence_for = make_index_sequence<sizeof...(Ts)>; /* Implementation of two C++17 constructs: conjunction, negation. This is needed to avoid evaluating all the traits in a condition For example: not std::is_same<void, T>::value and has_value_type<T>::value will not compile when T = void (on MSVC at least). Whereas conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will stop evaluating if negation<...>::value == false Please note that those constructs must be used with caution, since symbols can become very long quickly (which can slow down compilation and cause MSVC internal compiler errors). Only use it when you have to (see example ahead). */ template<class...> struct conjunction : std::true_type {}; template<class B1> struct conjunction<B1> : B1 {}; template<class B1, class... Bn> struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; template<class B> struct negation : std::integral_constant < bool, !B::value > {}; // dispatch utility (taken from ranges-v3) template<unsigned N> struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; ////////////////// // constructors // ////////////////// template<value_t> struct external_constructor; template<> struct external_constructor<value_t::boolean> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept { j.m_type = value_t::boolean; j.m_value = b; j.assert_invariant(); } }; template<> struct external_constructor<value_t::string> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) { j.m_type = value_t::string; j.m_value = s; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) { j.m_type = value_t::string; j.m_value = std::move(s); j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_float> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept { j.m_type = value_t::number_float; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_unsigned> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept { j.m_type = value_t::number_unsigned; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_integer> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept { j.m_type = value_t::number_integer; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::array> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) { j.m_type = value_t::array; j.m_value = arr; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { j.m_type = value_t::array; j.m_value = std::move(arr); j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleArrayType, enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleArrayType& arr) { using std::begin; using std::end; j.m_type = value_t::array; j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr)); j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, const std::vector<bool>& arr) { j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->reserve(arr.size()); for (bool x : arr) { j.m_value.array->push_back(x); } j.assert_invariant(); } template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> static void construct(BasicJsonType& j, const std::valarray<T>& arr) { j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->resize(arr.size()); std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); j.assert_invariant(); } }; template<> struct external_constructor<value_t::object> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) { j.m_type = value_t::object; j.m_value = obj; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { j.m_type = value_t::object; j.m_value = std::move(obj); j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleObjectType, enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleObjectType& obj) { using std::begin; using std::end; j.m_type = value_t::object; j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj)); j.assert_invariant(); } }; //////////////////////// // has_/is_ functions // //////////////////////// /*! @brief Helper to determine whether there's a key_type for T. This helper is used to tell associative containers apart from other containers such as sequence containers. For instance, `std::map` passes the test as it contains a `mapped_type`, whereas `std::vector` fails the test. @sa http://stackoverflow.com/a/7728728/266378 @since version 1.0.0, overworked in version 2.0.6 */ #define NLOHMANN_JSON_HAS_HELPER(type) \ template<typename T> struct has_##type { \ private: \ template<typename U, typename = typename U::type> \ static int detect(U &&); \ static void detect(...); \ public: \ static constexpr bool value = \ std::is_integral<decltype(detect(std::declval<T>()))>::value; \ } NLOHMANN_JSON_HAS_HELPER(mapped_type); NLOHMANN_JSON_HAS_HELPER(key_type); NLOHMANN_JSON_HAS_HELPER(value_type); NLOHMANN_JSON_HAS_HELPER(iterator); #undef NLOHMANN_JSON_HAS_HELPER template<bool B, class RealType, class CompatibleObjectType> struct is_compatible_object_type_impl : std::false_type {}; template<class RealType, class CompatibleObjectType> struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType> { static constexpr auto value = std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value; }; template<class BasicJsonType, class CompatibleObjectType> struct is_compatible_object_type { static auto constexpr value = is_compatible_object_type_impl < conjunction<negation<std::is_same<void, CompatibleObjectType>>, has_mapped_type<CompatibleObjectType>, has_key_type<CompatibleObjectType>>::value, typename BasicJsonType::object_t, CompatibleObjectType >::value; }; template<typename BasicJsonType, typename T> struct is_basic_json_nested_type { static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or std::is_same<T, typename BasicJsonType::const_iterator>::value or std::is_same<T, typename BasicJsonType::reverse_iterator>::value or std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value; }; template<class BasicJsonType, class CompatibleArrayType> struct is_compatible_array_type { static auto constexpr value = conjunction<negation<std::is_same<void, CompatibleArrayType>>, negation<is_compatible_object_type< BasicJsonType, CompatibleArrayType>>, negation<std::is_constructible<typename BasicJsonType::string_t, CompatibleArrayType>>, negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>, has_value_type<CompatibleArrayType>, has_iterator<CompatibleArrayType>>::value; }; template<bool, typename, typename> struct is_compatible_integer_type_impl : std::false_type {}; template<typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType> { // is there an assert somewhere on overflows? using RealLimits = std::numeric_limits<RealIntegerType>; using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>; static constexpr auto value = std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and CompatibleLimits::is_integer and RealLimits::is_signed == CompatibleLimits::is_signed; }; template<typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type { static constexpr auto value = is_compatible_integer_type_impl < std::is_integral<CompatibleNumberIntegerType>::value and not std::is_same<bool, CompatibleNumberIntegerType>::value, RealIntegerType, CompatibleNumberIntegerType > ::value; }; // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists template<typename BasicJsonType, typename T> struct has_from_json { private: // also check the return type of from_json template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json( std::declval<BasicJsonType>(), std::declval<T&>()))>::value>> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype( detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; // This trait checks if JSONSerializer<T>::from_json(json const&) exists // this overload is used for non-default-constructible user-defined-types template<typename BasicJsonType, typename T> struct has_non_default_from_json { private: template < typename U, typename = enable_if_t<std::is_same< T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype(detect( std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; // This trait checks if BasicJsonType::json_serializer<T>::to_json exists template<typename BasicJsonType, typename T> struct has_to_json { private: template<typename U, typename = decltype(uncvref_t<U>::to_json( std::declval<BasicJsonType&>(), std::declval<T>()))> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype(detect( std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; ///////////// // to_json // ///////////// template<typename BasicJsonType, typename T, enable_if_t< std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0> void to_json(BasicJsonType& j, T b) noexcept { external_constructor<value_t::boolean>::construct(j, b); } template<typename BasicJsonType, typename CompatibleString, enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleString& s) { external_constructor<value_t::string>::construct(j, s); } template <typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) { external_constructor<value_t::string>::construct(j, std::move(s)); } template<typename BasicJsonType, typename FloatType, enable_if_t<std::is_floating_point<FloatType>::value, int> = 0> void to_json(BasicJsonType& j, FloatType val) noexcept { external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val)); } template < typename BasicJsonType, typename CompatibleNumberUnsignedType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0 > void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept { external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val)); } template < typename BasicJsonType, typename CompatibleNumberIntegerType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0 > void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept { external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val)); } template<typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0> void to_json(BasicJsonType& j, EnumType e) noexcept { using underlying_type = typename std::underlying_type<EnumType>::type; external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e)); } template<typename BasicJsonType> void to_json(BasicJsonType& j, const std::vector<bool>& e) { external_constructor<value_t::array>::construct(j, e); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleArrayType& arr) { external_constructor<value_t::array>::construct(j, arr); } template <typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> void to_json(BasicJsonType& j, std::valarray<T> arr) { external_constructor<value_t::array>::construct(j, std::move(arr)); } template <typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { external_constructor<value_t::array>::construct(j, std::move(arr)); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0 > void to_json(BasicJsonType& j, const CompatibleObjectType& obj) { external_constructor<value_t::object>::construct(j, obj); } template <typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { external_constructor<value_t::object>::construct(j, std::move(obj)); } template<typename BasicJsonType, typename T, std::size_t N, enable_if_t<not std::is_constructible< typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0> void to_json(BasicJsonType& j, T (&arr)[N]) { external_constructor<value_t::array>::construct(j, arr); } template<typename BasicJsonType, typename... Args> void to_json(BasicJsonType& j, const std::pair<Args...>& p) { j = {p.first, p.second}; } template<typename BasicJsonType, typename Tuple, std::size_t... Idx> void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>) { j = {std::get<Idx>(t)...}; } template<typename BasicJsonType, typename... Args> void to_json(BasicJsonType& j, const std::tuple<Args...>& t) { to_json_tuple_impl(j, t, index_sequence_for<Args...> {}); } /////////////// // from_json // /////////////// // overloads for basic_json template parameters template<typename BasicJsonType, typename ArithmeticType, enable_if_t<std::is_arithmetic<ArithmeticType>::value and not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int> = 0> void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); } } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) { if (JSON_UNLIKELY(not j.is_boolean())) { JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()))); } b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) { if (JSON_UNLIKELY(not j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); } s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0> void from_json(const BasicJsonType& j, EnumType& e) { typename std::underlying_type<EnumType>::type val; get_arithmetic_value(j, val); e = static_cast<EnumType>(val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } arr = *j.template get_ptr<const typename BasicJsonType::array_t*>(); } // forward_list doesn't have an insert method template<typename BasicJsonType, typename T, typename Allocator, enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0> void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } std::transform(j.rbegin(), j.rend(), std::front_inserter(l), [](const BasicJsonType & i) { return i.template get<T>(); }); } // valarray doesn't have an insert method template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0> void from_json(const BasicJsonType& j, std::valarray<T>& l) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } l.resize(j.size()); std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l)); } template<typename BasicJsonType, typename CompatibleArrayType> void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/) { using std::end; std::transform(j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename CompatibleArrayType::value_type>(); }); } template<typename BasicJsonType, typename CompatibleArrayType> auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/) -> decltype( arr.reserve(std::declval<typename CompatibleArrayType::size_type>()), void()) { using std::end; arr.reserve(j.size()); std::transform(j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename CompatibleArrayType::value_type>(); }); } template<typename BasicJsonType, typename T, std::size_t N> void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get<T>(); } } template<typename BasicJsonType, typename CompatibleArrayType, enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0> void from_json(const BasicJsonType& j, CompatibleArrayType& arr) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } from_json_array_impl(j, arr, priority_tag<2> {}); } template<typename BasicJsonType, typename CompatibleObjectType, enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0> void from_json(const BasicJsonType& j, CompatibleObjectType& obj) { if (JSON_UNLIKELY(not j.is_object())) { JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()))); } auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>(); using value_type = typename CompatibleObjectType::value_type; std::transform( inner_object->begin(), inner_object->end(), std::inserter(obj, obj.begin()), [](typename BasicJsonType::object_t::value_type const & p) { return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>()); }); } // overload for arithmetic types, not chosen for basic_json template arguments // (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template<typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic<ArithmeticType>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int> = 0> void from_json(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } case value_t::boolean: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); } } template<typename BasicJsonType, typename A1, typename A2> void from_json(const BasicJsonType& j, std::pair<A1, A2>& p) { p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()}; } template<typename BasicJsonType, typename Tuple, std::size_t... Idx> void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>) { t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...); } template<typename BasicJsonType, typename... Args> void from_json(const BasicJsonType& j, std::tuple<Args...>& t) { from_json_tuple_impl(j, t, index_sequence_for<Args...> {}); } struct to_json_fn { private: template<typename BasicJsonType, typename T> auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val)))) -> decltype(to_json(j, std::forward<T>(val)), void()) { return to_json(j, std::forward<T>(val)); } template<typename BasicJsonType, typename T> void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept { static_assert(sizeof(BasicJsonType) == 0, "could not find to_json() method in T's namespace"); } public: template<typename BasicJsonType, typename T> void operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {}))) { return call(j, std::forward<T>(val), priority_tag<1> {}); } }; struct from_json_fn { private: template<typename BasicJsonType, typename T> auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const noexcept(noexcept(from_json(j, val))) -> decltype(from_json(j, val), void()) { return from_json(j, val); } template<typename BasicJsonType, typename T> void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept { static_assert(sizeof(BasicJsonType) == 0, "could not find from_json() method in T's namespace"); } public: template<typename BasicJsonType, typename T> void operator()(const BasicJsonType& j, T& val) const noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {}))) { return call(j, val, priority_tag<1> {}); } }; // taken from ranges-v3 template<typename T> struct static_const { static constexpr T value{}; }; template<typename T> constexpr T static_const<T>::value; //////////////////// // input adapters // //////////////////// /// abstract input adapter interface struct input_adapter_protocol { virtual int get_character() = 0; virtual std::string read(std::size_t offset, std::size_t length) = 0; virtual ~input_adapter_protocol() = default; }; /// a type to simplify interfaces using input_adapter_t = std::shared_ptr<input_adapter_protocol>; /// input adapter for cached stream input template<std::size_t BufferSize> class cached_input_stream_adapter : public input_adapter_protocol { public: explicit cached_input_stream_adapter(std::istream& i) : is(i), start_position(is.tellg()) { fill_buffer(); // skip byte order mark if (fill_size >= 3 and buffer[0] == '\xEF' and buffer[1] == '\xBB' and buffer[2] == '\xBF') { buffer_pos += 3; processed_chars += 3; } } ~cached_input_stream_adapter() override { // clear stream flags is.clear(); // We initially read a lot of characters into the buffer, and we may // not have processed all of them. Therefore, we need to "rewind" the // stream after the last processed char. is.seekg(start_position); is.ignore(static_cast<std::streamsize>(processed_chars)); // clear stream flags is.clear(); } int get_character() override { // check if refilling is necessary and possible if (buffer_pos == fill_size and not eof) { fill_buffer(); // check and remember that filling did not yield new input if (fill_size == 0) { eof = true; return std::char_traits<char>::eof(); } // the buffer is ready buffer_pos = 0; } ++processed_chars; assert(buffer_pos < buffer.size()); return buffer[buffer_pos++] & 0xFF; } std::string read(std::size_t offset, std::size_t length) override { // create buffer std::string result(length, '\0'); // save stream position const auto current_pos = is.tellg(); // save stream flags const auto flags = is.rdstate(); // clear stream flags is.clear(); // set stream position is.seekg(static_cast<std::streamoff>(offset)); // read bytes is.read(&result[0], static_cast<std::streamsize>(length)); // reset stream position is.seekg(current_pos); // reset stream flags is.setstate(flags); return result; } private: void fill_buffer() { // fill is.read(buffer.data(), static_cast<std::streamsize>(buffer.size())); // store number of bytes in the buffer fill_size = static_cast<size_t>(is.gcount()); } /// the associated input stream std::istream& is; /// chars returned via get_character() std::size_t processed_chars = 0; /// chars processed in the current buffer std::size_t buffer_pos = 0; /// whether stream reached eof bool eof = false; /// how many chars have been copied to the buffer by last (re)fill std::size_t fill_size = 0; /// position of the stream when we started const std::streampos start_position; /// internal buffer std::array<char, BufferSize> buffer{{}}; }; /// input adapter for buffer input class input_buffer_adapter : public input_adapter_protocol { public: input_buffer_adapter(const char* b, const std::size_t l) : cursor(b), limit(b + l), start(b) { // skip byte order mark if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF') { cursor += 3; } } // delete because of pointer members input_buffer_adapter(const input_buffer_adapter&) = delete; input_buffer_adapter& operator=(input_buffer_adapter&) = delete; int get_character() noexcept override { if (JSON_LIKELY(cursor < limit)) { return *(cursor++) & 0xFF; } return std::char_traits<char>::eof(); } std::string read(std::size_t offset, std::size_t length) override { // avoid reading too many characters const auto max_length = static_cast<size_t>(limit - start); return std::string(start + offset, (std::min)(length, max_length - offset)); } private: /// pointer to the current character const char* cursor; /// pointer past the last character const char* limit; /// pointer to the first character const char* start; }; class input_adapter { public: // native support /// input adapter for input stream input_adapter(std::istream& i) : ia(std::make_shared<cached_input_stream_adapter<16384>>(i)) {} /// input adapter for input stream input_adapter(std::istream&& i) : ia(std::make_shared<cached_input_stream_adapter<16384>>(i)) {} /// input adapter for buffer template<typename CharT, typename std::enable_if< std::is_pointer<CharT>::value and std::is_integral< typename std::remove_pointer<CharT>::type>::value and sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0> input_adapter(CharT b, std::size_t l) : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {} // derived support /// input adapter for string literal template<typename CharT, typename std::enable_if< std::is_pointer<CharT>::value and std::is_integral< typename std::remove_pointer<CharT>::type>::value and sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0> input_adapter(CharT b) : input_adapter(reinterpret_cast<const char*>(b), std::strlen(reinterpret_cast<const char*>(b))) {} /// input adapter for iterator range with contiguous storage template<class IteratorType, typename std::enable_if< std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value, int>::type = 0> input_adapter(IteratorType first, IteratorType last) { // assertion to check that the iterator range is indeed contiguous, // see http://stackoverflow.com/a/35008842/266378 for more discussion assert(std::accumulate( first, last, std::pair<bool, int>(true, 0), [&first](std::pair<bool, int> res, decltype(*first) val) { res.first &= (val == *(std::next(std::addressof(*first), res.second++))); return res; }).first); // assertion to check that each element is 1 byte long static_assert( sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1, "each element in the iterator range must have the size of 1 byte"); const auto len = static_cast<size_t>(std::distance(first, last)); if (JSON_LIKELY(len > 0)) { // there is at least one element: use the address of first ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len); } else { // the address of first cannot be used: use nullptr ia = std::make_shared<input_buffer_adapter>(nullptr, len); } } /// input adapter for array template<class T, std::size_t N> input_adapter(T (&array)[N]) : input_adapter(std::begin(array), std::end(array)) {} /// input adapter for contiguous container template < class ContiguousContainer, typename std::enable_if < not std::is_pointer<ContiguousContainer>::value and std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value, int >::type = 0 > input_adapter(const ContiguousContainer& c) : input_adapter(std::begin(c), std::end(c)) {} operator input_adapter_t() { return ia; } private: /// the actual adapter input_adapter_t ia = nullptr; }; ////////////////////// // lexer and parser // ////////////////////// /*! @brief lexical analysis This class organizes the lexical analysis during JSON deserialization. */ template<typename BasicJsonType> class lexer { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; public: /// token types for the parser enum class token_type { uninitialized, ///< indicating the scanner is uninitialized literal_true, ///< the `true` literal literal_false, ///< the `false` literal literal_null, ///< the `null` literal value_string, ///< a string -- use get_string() for actual value value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value value_integer, ///< a signed integer -- use get_number_integer() for actual value value_float, ///< an floating point number -- use get_number_float() for actual value begin_array, ///< the character for array begin `[` begin_object, ///< the character for object begin `{` end_array, ///< the character for array end `]` end_object, ///< the character for object end `}` name_separator, ///< the name separator `:` value_separator, ///< the value separator `,` parse_error, ///< indicating a parse error end_of_input, ///< indicating the end of the input buffer literal_or_value ///< a literal or the begin of a value (only for diagnostics) }; /// return name of values of type token_type (only used for errors) static const char* token_type_name(const token_type t) noexcept { switch (t) { case token_type::uninitialized: return "<uninitialized>"; case token_type::literal_true: return "true literal"; case token_type::literal_false: return "false literal"; case token_type::literal_null: return "null literal"; case token_type::value_string: return "string literal"; case lexer::token_type::value_unsigned: case lexer::token_type::value_integer: case lexer::token_type::value_float: return "number literal"; case token_type::begin_array: return "'['"; case token_type::begin_object: return "'{'"; case token_type::end_array: return "']'"; case token_type::end_object: return "'}'"; case token_type::name_separator: return "':'"; case token_type::value_separator: return "','"; case token_type::parse_error: return "<parse error>"; case token_type::end_of_input: return "end of input"; case token_type::literal_or_value: return "'[', '{', or a literal"; default: // catch non-enum values return "unknown token"; // LCOV_EXCL_LINE } } explicit lexer(detail::input_adapter_t adapter) : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {} // delete because of pointer members lexer(const lexer&) = delete; lexer& operator=(lexer&) = delete; private: ///////////////////// // locales ///////////////////// /// return the locale-dependent decimal point static char get_decimal_point() noexcept { const auto loc = localeconv(); assert(loc != nullptr); return (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0]; } ///////////////////// // scan functions ///////////////////// /*! @brief get codepoint from 4 hex characters following `\u` For input "\u c1 c2 c3 c4" the codepoint is: (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The conversion is done by subtracting the offset (0x30, 0x37, and 0x57) between the ASCII value of the character and the desired integer value. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or non-hex character) */ int get_codepoint() { // this function only makes sense after reading `\u` assert(current == 'u'); int codepoint = 0; const auto factors = { 12, 8, 4, 0 }; for (const auto factor : factors) { get(); if (current >= '0' and current <= '9') { codepoint += ((current - 0x30) << factor); } else if (current >= 'A' and current <= 'F') { codepoint += ((current - 0x37) << factor); } else if (current >= 'a' and current <= 'f') { codepoint += ((current - 0x57) << factor); } else { return -1; } } assert(0x0000 <= codepoint and codepoint <= 0xFFFF); return codepoint; } /*! @brief check if the next byte(s) are inside a given range Adds the current byte and, for each passed range, reads a new byte and checks if it is inside the range. If a violation was detected, set up an error message and return false. Otherwise, return true. @return true if and only if no range violation was detected */ bool next_byte_in_range(std::initializer_list<int> ranges) { assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6); add(current); for (auto range = ranges.begin(); range != ranges.end(); ++range) { get(); if (JSON_LIKELY(*range <= current and current <= *(++range))) { add(current); } else { error_message = "invalid string: ill-formed UTF-8 byte"; return false; } } return true; } /*! @brief scan a string literal This function scans a string according to Sect. 7 of RFC 7159. While scanning, bytes are escaped and copied into buffer yytext. Then the function returns successfully, yytext is null-terminated and yylen contains the number of bytes in the string. @return token_type::value_string if string could be successfully scanned, token_type::parse_error otherwise @note In case of errors, variable error_message contains a textual description. */ token_type scan_string() { // reset yytext (ignore opening quote) reset(); // we entered the function by reading an open quote assert(current == '\"'); while (true) { // get next character switch (get()) { // end of file while parsing string case std::char_traits<char>::eof(): { error_message = "invalid string: missing closing quote"; return token_type::parse_error; } // closing quote case '\"': { // terminate yytext add('\0'); --yylen; return token_type::value_string; } // escapes case '\\': { switch (get()) { // quotation mark case '\"': add('\"'); break; // reverse solidus case '\\': add('\\'); break; // solidus case '/': add('/'); break; // backspace case 'b': add('\b'); break; // form feed case 'f': add('\f'); break; // line feed case 'n': add('\n'); break; // carriage return case 'r': add('\r'); break; // tab case 't': add('\t'); break; // unicode escapes case 'u': { int codepoint; const int codepoint1 = get_codepoint(); if (JSON_UNLIKELY(codepoint1 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if code point is a high surrogate if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF) { // expect next \uxxxx entry if (JSON_LIKELY(get() == '\\' and get() == 'u')) { const int codepoint2 = get_codepoint(); if (JSON_UNLIKELY(codepoint2 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if codepoint2 is a low surrogate if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF)) { codepoint = // high surrogate occupies the most significant 22 bits (codepoint1 << 10) // low surrogate occupies the least significant 15 bits + codepoint2 // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00; } else { error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF)) { error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; return token_type::parse_error; } // only work with first code point codepoint = codepoint1; } // result of the above calculation yields a proper codepoint assert(0x00 <= codepoint and codepoint <= 0x10FFFF); // translate code point to bytes if (codepoint < 0x80) { // 1-byte characters: 0xxxxxxx (ASCII) add(codepoint); } else if (codepoint <= 0x7ff) { // 2-byte characters: 110xxxxx 10xxxxxx add(0xC0 | (codepoint >> 6)); add(0x80 | (codepoint & 0x3F)); } else if (codepoint <= 0xffff) { // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx add(0xE0 | (codepoint >> 12)); add(0x80 | ((codepoint >> 6) & 0x3F)); add(0x80 | (codepoint & 0x3F)); } else { // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx add(0xF0 | (codepoint >> 18)); add(0x80 | ((codepoint >> 12) & 0x3F)); add(0x80 | ((codepoint >> 6) & 0x3F)); add(0x80 | (codepoint & 0x3F)); } break; } // other characters after escape default: error_message = "invalid string: forbidden character after backslash"; return token_type::parse_error; } break; } // invalid control characters case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: { error_message = "invalid string: control character must be escaped"; return token_type::parse_error; } // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) case 0x20: case 0x21: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5a: case 0x5b: case 0x5d: case 0x5e: case 0x5f: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f: { add(current); break; } // U+0080..U+07FF: bytes C2..DF 80..BF case 0xc2: case 0xc3: case 0xc4: case 0xc5: case 0xc6: case 0xc7: case 0xc8: case 0xc9: case 0xca: case 0xcb: case 0xcc: case 0xcd: case 0xce: case 0xcf: case 0xd0: case 0xd1: case 0xd2: case 0xd3: case 0xd4: case 0xd5: case 0xd6: case 0xd7: case 0xd8: case 0xd9: case 0xda: case 0xdb: case 0xdc: case 0xdd: case 0xde: case 0xdf: { if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF}))) { return token_type::parse_error; } break; } // U+0800..U+0FFF: bytes E0 A0..BF 80..BF case 0xe0: { if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF case 0xe1: case 0xe2: case 0xe3: case 0xe4: case 0xe5: case 0xe6: case 0xe7: case 0xe8: case 0xe9: case 0xea: case 0xeb: case 0xec: case 0xee: case 0xef: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+D000..U+D7FF: bytes ED 80..9F 80..BF case 0xed: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF case 0xf0: { if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF case 0xf1: case 0xf2: case 0xf3: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF case 0xf4: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // remaining bytes (80..C1 and F5..FF) are ill-formed default: { error_message = "invalid string: ill-formed UTF-8 byte"; return token_type::parse_error; } } } } static void strtof(float& f, const char* str, char** endptr) noexcept { f = std::strtof(str, endptr); } static void strtof(double& f, const char* str, char** endptr) noexcept { f = std::strtod(str, endptr); } static void strtof(long double& f, const char* str, char** endptr) noexcept { f = std::strtold(str, endptr); } /*! @brief scan a number literal This function scans a string according to Sect. 6 of RFC 7159. The function is realized with a deterministic finite state machine derived from the grammar described in RFC 7159. Starting in state "init", the input is read and used to determined the next state. Only state "done" accepts the number. State "error" is a trap state to model errors. In the table below, "anything" means any character but the ones listed before. state | 0 | 1-9 | e E | + | - | . | anything ---------|----------|----------|----------|---------|---------|----------|----------- init | zero | any1 | [error] | [error] | minus | [error] | [error] minus | zero | any1 | [error] | [error] | [error] | [error] | [error] zero | done | done | exponent | done | done | decimal1 | done any1 | any1 | any1 | exponent | done | done | decimal1 | done decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error] decimal2 | decimal2 | decimal2 | exponent | done | done | done | done exponent | any2 | any2 | [error] | sign | sign | [error] | [error] sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] any2 | any2 | any2 | done | done | done | done | done The state machine is realized with one label per state (prefixed with "scan_number_") and `goto` statements between them. The state machine contains cycles, but any cycle can be left when EOF is read. Therefore, the function is guaranteed to terminate. During scanning, the read bytes are stored in yytext. This string is then converted to a signed integer, an unsigned integer, or a floating-point number. @return token_type::value_unsigned, token_type::value_integer, or token_type::value_float if number could be successfully scanned, token_type::parse_error otherwise @note The scanner is independent of the current locale. Internally, the locale's decimal point is used instead of `.` to work with the locale-dependent converters. */ token_type scan_number() { // reset yytext to store the number's bytes reset(); // the type of the parsed number; initially set to unsigned; will be // changed if minus sign, decimal point or exponent is read token_type number_type = token_type::value_unsigned; // state (init): we just found out we need to scan a number switch (current) { case '-': { add(current); goto scan_number_minus; } case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { // all other characters are rejected outside scan_number() assert(false); // LCOV_EXCL_LINE } } scan_number_minus: // state: we just parsed a leading minus sign number_type = token_type::value_integer; switch (get()) { case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { error_message = "invalid number; expected digit after '-'"; return token_type::parse_error; } } scan_number_zero: // state: we just parse a zero (maybe with a leading minus sign) switch (get()) { case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_any1: // state: we just parsed a number 0-9 (maybe with a leading minus sign) switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_decimal1: // state: we just parsed a decimal point number_type = token_type::value_float; switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } default: { error_message = "invalid number; expected digit after '.'"; return token_type::parse_error; } } scan_number_decimal2: // we just parsed at least one number after a decimal point switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_exponent: // we just parsed an exponent number_type = token_type::value_float; switch (get()) { case '+': case '-': { add(current); goto scan_number_sign; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected '+', '-', or digit after exponent"; return token_type::parse_error; } } scan_number_sign: // we just parsed an exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected digit after exponent sign"; return token_type::parse_error; } } scan_number_any2: // we just parsed a number after the exponent or exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: goto scan_number_done; } scan_number_done: // unget the character after the number (we only read it to know that // we are done scanning a number) --chars_read; next_unget = true; // terminate token add('\0'); --yylen; char* endptr = nullptr; errno = 0; // try to parse integers first and fall back to floats if (number_type == token_type::value_unsigned) { const auto x = std::strtoull(yytext.data(), &endptr, 10); // we checked the number format before assert(endptr == yytext.data() + yylen); if (errno == 0) { value_unsigned = static_cast<number_unsigned_t>(x); if (value_unsigned == x) { return token_type::value_unsigned; } } } else if (number_type == token_type::value_integer) { const auto x = std::strtoll(yytext.data(), &endptr, 10); // we checked the number format before assert(endptr == yytext.data() + yylen); if (errno == 0) { value_integer = static_cast<number_integer_t>(x); if (value_integer == x) { return token_type::value_integer; } } } // this code is reached if we parse a floating-point number or if an // integer conversion above failed strtof(value_float, yytext.data(), &endptr); // we checked the number format before assert(endptr == yytext.data() + yylen); return token_type::value_float; } /*! @param[in] literal_text the literal text to expect @param[in] length the length of the passed literal text @param[in] return_type the token type to return on success */ token_type scan_literal(const char* literal_text, const std::size_t length, token_type return_type) { assert(current == literal_text[0]); for (std::size_t i = 1; i < length; ++i) { if (JSON_UNLIKELY(get() != literal_text[i])) { error_message = "invalid literal"; return token_type::parse_error; } } return return_type; } ///////////////////// // input management ///////////////////// /// reset yytext void reset() noexcept { yylen = 0; start_pos = chars_read - 1; } /// get a character from the input int get() { ++chars_read; return next_unget ? (next_unget = false, current) : (current = ia->get_character()); } /// add a character to yytext void add(int c) { // resize yytext if necessary; this condition is deemed unlikely, // because we start with a 1024-byte buffer if (JSON_UNLIKELY((yylen + 1 > yytext.capacity()))) { yytext.resize(2 * yytext.capacity(), '\0'); } assert(yylen < yytext.size()); yytext[yylen++] = static_cast<char>(c); } public: ///////////////////// // value getters ///////////////////// /// return integer value constexpr number_integer_t get_number_integer() const noexcept { return value_integer; } /// return unsigned integer value constexpr number_unsigned_t get_number_unsigned() const noexcept { return value_unsigned; } /// return floating-point value constexpr number_float_t get_number_float() const noexcept { return value_float; } /// return string value const std::string get_string() { // yytext cannot be returned as char*, because it may contain a null // byte (parsed as "\u0000") return std::string(yytext.data(), yylen); } ///////////////////// // diagnostics ///////////////////// /// return position of last read token constexpr std::size_t get_position() const noexcept { return chars_read; } /// return the last read token (for errors only) std::string get_token_string() const { // get the raw byte sequence of the last token std::string s = ia->read(start_pos, chars_read - start_pos); // escape control characters std::string result; for (auto c : s) { if (c == '\0' or c == std::char_traits<char>::eof()) { // ignore EOF continue; } else if ('\x00' <= c and c <= '\x1f') { // escape control characters std::stringstream ss; ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(c) << ">"; result += ss.str(); } else { // add character as is result.push_back(c); } } return result; } /// return syntax error message constexpr const char* get_error_message() const noexcept { return error_message; } ///////////////////// // actual scanner ///////////////////// token_type scan() { // read next character and ignore whitespace do { get(); } while (current == ' ' or current == '\t' or current == '\n' or current == '\r'); switch (current) { // structural characters case '[': return token_type::begin_array; case ']': return token_type::end_array; case '{': return token_type::begin_object; case '}': return token_type::end_object; case ':': return token_type::name_separator; case ',': return token_type::value_separator; // literals case 't': return scan_literal("true", 4, token_type::literal_true); case 'f': return scan_literal("false", 5, token_type::literal_false); case 'n': return scan_literal("null", 4, token_type::literal_null); // string case '\"': return scan_string(); // number case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return scan_number(); // end of input (the null byte is needed when parsing from // string literals) case '\0': case std::char_traits<char>::eof(): return token_type::end_of_input; // error default: error_message = "invalid literal"; return token_type::parse_error; } } private: /// input adapter detail::input_adapter_t ia = nullptr; /// the current character int current = std::char_traits<char>::eof(); /// whether get() should return the last character again bool next_unget = false; /// the number of characters read std::size_t chars_read = 0; /// the start position of the current token std::size_t start_pos = 0; /// buffer for variable-length tokens (numbers, strings) std::vector<char> yytext = std::vector<char>(1024, '\0'); /// current index in yytext std::size_t yylen = 0; /// a description of occurred lexer errors const char* error_message = ""; // number values number_integer_t value_integer = 0; number_unsigned_t value_unsigned = 0; number_float_t value_float = 0; /// the decimal point const char decimal_point_char = '.'; }; /*! @brief syntax analysis This class implements a recursive decent parser. */ template<typename BasicJsonType> class parser { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using lexer_t = lexer<BasicJsonType>; using token_type = typename lexer_t::token_type; public: enum class parse_event_t : uint8_t { /// the parser read `{` and started to process a JSON object object_start, /// the parser read `}` and finished processing a JSON object object_end, /// the parser read `[` and started to process a JSON array array_start, /// the parser read `]` and finished processing a JSON array array_end, /// the parser read a key of a value in an object key, /// the parser finished reading a JSON value value }; using parser_callback_t = std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>; /// a parser reading from an input adapter explicit parser(detail::input_adapter_t adapter, const parser_callback_t cb = nullptr, const bool allow_exceptions_ = true) : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_) {} /*! @brief public parser interface @param[in] strict whether to expect the last token to be EOF @param[in,out] result parsed JSON value @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse(const bool strict, BasicJsonType& result) { // read first token get_token(); parse_internal(true, result); result.assert_invariant(); // in strict mode, input must be completely read if (strict) { get_token(); expect(token_type::end_of_input); } // in case of an error, return discarded value if (errored) { result = value_t::discarded; return; } // set top-level value to null if it was discarded by the callback // function if (result.is_discarded()) { result = nullptr; } } /*! @brief public accept interface @param[in] strict whether to expect the last token to be EOF @return whether the input is a proper JSON text */ bool accept(const bool strict = true) { // read first token get_token(); if (not accept_internal()) { return false; } // strict => last token must be EOF return not strict or (get_token() == token_type::end_of_input); } private: /*! @brief the actual parser @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse_internal(bool keep, BasicJsonType& result) { // never parse after a parse error was detected assert(not errored); // start with a discarded value if (not result.is_discarded()) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } switch (last_token) { case token_type::begin_object: { if (keep and (not callback or ((keep = callback(depth++, parse_event_t::object_start, result))))) { // explicitly set result to object to cope with {} result.m_type = value_t::object; result.m_value = value_t::object; } // read next token get_token(); // closing } -> we are done if (last_token == token_type::end_object) { if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } break; } // parse values std::string key; BasicJsonType value; while (true) { // store key if (not expect(token_type::value_string)) { return; } key = m_lexer.get_string(); bool keep_tag = false; if (keep) { if (callback) { BasicJsonType k(key); keep_tag = callback(depth, parse_event_t::key, k); } else { keep_tag = true; } } // parse separator (:) get_token(); if (not expect(token_type::name_separator)) { return; } // parse and add value get_token(); value.m_value.destroy(value.m_type); value.m_type = value_t::discarded; parse_internal(keep, value); if (JSON_UNLIKELY(errored)) { return; } if (keep and keep_tag and not value.is_discarded()) { result.m_value.object->emplace(std::move(key), std::move(value)); } // comma -> next value get_token(); if (last_token == token_type::value_separator) { get_token(); continue; } // closing } if (not expect(token_type::end_object)) { return; } break; } if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } break; } case token_type::begin_array: { if (keep and (not callback or ((keep = callback(depth++, parse_event_t::array_start, result))))) { // explicitly set result to object to cope with [] result.m_type = value_t::array; result.m_value = value_t::array; } // read next token get_token(); // closing ] -> we are done if (last_token == token_type::end_array) { if (callback and not callback(--depth, parse_event_t::array_end, result)) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } break; } // parse values BasicJsonType value; while (true) { // parse value value.m_value.destroy(value.m_type); value.m_type = value_t::discarded; parse_internal(keep, value); if (JSON_UNLIKELY(errored)) { return; } if (keep and not value.is_discarded()) { result.m_value.array->push_back(std::move(value)); } // comma -> next value get_token(); if (last_token == token_type::value_separator) { get_token(); continue; } // closing ] if (not expect(token_type::end_array)) { return; } break; } if (keep and callback and not callback(--depth, parse_event_t::array_end, result)) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } break; } case token_type::literal_null: { result.m_type = value_t::null; break; } case token_type::value_string: { result.m_type = value_t::string; result.m_value = m_lexer.get_string(); break; } case token_type::literal_true: { result.m_type = value_t::boolean; result.m_value = true; break; } case token_type::literal_false: { result.m_type = value_t::boolean; result.m_value = false; break; } case token_type::value_unsigned: { result.m_type = value_t::number_unsigned; result.m_value = m_lexer.get_number_unsigned(); break; } case token_type::value_integer: { result.m_type = value_t::number_integer; result.m_value = m_lexer.get_number_integer(); break; } case token_type::value_float: { result.m_type = value_t::number_float; result.m_value = m_lexer.get_number_float(); // throw in case of infinity or NAN if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float))) { if (allow_exceptions) { JSON_THROW(out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'")); } expect(token_type::uninitialized); } break; } case token_type::parse_error: { // using "uninitialized" to avoid "expected" message if (not expect(token_type::uninitialized)) { return; } break; // LCOV_EXCL_LINE } default: { // the last token was unexpected; we expected a value if (not expect(token_type::literal_or_value)) { return; } break; // LCOV_EXCL_LINE } } if (keep and callback and not callback(depth, parse_event_t::value, result)) { result.m_type = value_t::discarded; } } /*! @brief the acutal acceptor @invariant 1. The last token is not yet processed. Therefore, the caller of this function must make sure a token has been read. 2. When this function returns, the last token is processed. That is, the last read character was already considered. This invariant makes sure that no token needs to be "unput". */ bool accept_internal() { switch (last_token) { case token_type::begin_object: { // read next token get_token(); // closing } -> we are done if (last_token == token_type::end_object) { return true; } // parse values while (true) { // parse key if (last_token != token_type::value_string) { return false; } // parse separator (:) get_token(); if (last_token != token_type::name_separator) { return false; } // parse value get_token(); if (not accept_internal()) { return false; } // comma -> next value get_token(); if (last_token == token_type::value_separator) { get_token(); continue; } // closing } return (last_token == token_type::end_object); } } case token_type::begin_array: { // read next token get_token(); // closing ] -> we are done if (last_token == token_type::end_array) { return true; } // parse values while (true) { // parse value if (not accept_internal()) { return false; } // comma -> next value get_token(); if (last_token == token_type::value_separator) { get_token(); continue; } // closing ] return (last_token == token_type::end_array); } } case token_type::value_float: { // reject infinity or NAN return std::isfinite(m_lexer.get_number_float()); } case token_type::literal_false: case token_type::literal_null: case token_type::literal_true: case token_type::value_integer: case token_type::value_string: case token_type::value_unsigned: return true; default: // the last token was unexpected return false; } } /// get next token from lexer token_type get_token() { return (last_token = m_lexer.scan()); } /*! @throw parse_error.101 if expected token did not occur */ bool expect(token_type t) { if (JSON_UNLIKELY(t != last_token)) { errored = true; expected = t; if (allow_exceptions) { throw_exception(); } else { return false; } } return true; } [[noreturn]] void throw_exception() const { std::string error_msg = "syntax error - "; if (last_token == token_type::parse_error) { error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + m_lexer.get_token_string() + "'"; } else { error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); } if (expected != token_type::uninitialized) { error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); } JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg)); } private: /// current level of recursion int depth = 0; /// callback function const parser_callback_t callback = nullptr; /// the type of the last read token token_type last_token = token_type::uninitialized; /// the lexer lexer_t m_lexer; /// whether a syntax error occurred bool errored = false; /// possible reason for the syntax error token_type expected = token_type::uninitialized; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; /////////////// // iterators // /////////////// /*! @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t { public: using difference_type = std::ptrdiff_t; constexpr difference_type get_value() const noexcept { return m_it; } /// set iterator to a defined beginning void set_begin() noexcept { m_it = begin_value; } /// set iterator to a defined past the end void set_end() noexcept { m_it = end_value; } /// return whether the iterator can be dereferenced constexpr bool is_begin() const noexcept { return m_it == begin_value; } /// return whether the iterator is at end constexpr bool is_end() const noexcept { return m_it == end_value; } friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it == rhs.m_it; } friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it < rhs.m_it; } primitive_iterator_t operator+(difference_type i) { auto result = *this; result += i; return result; } friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it - rhs.m_it; } friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it) { return os << it.m_it; } primitive_iterator_t& operator++() { ++m_it; return *this; } primitive_iterator_t operator++(int) { auto result = *this; m_it++; return result; } primitive_iterator_t& operator--() { --m_it; return *this; } primitive_iterator_t operator--(int) { auto result = *this; m_it--; return result; } primitive_iterator_t& operator+=(difference_type n) { m_it += n; return *this; } primitive_iterator_t& operator-=(difference_type n) { m_it -= n; return *this; } private: static constexpr difference_type begin_value = 0; static constexpr difference_type end_value = begin_value + 1; /// iterator as signed integer type difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)(); }; /*! @brief an iterator value @note This structure could easily be a union, but MSVC currently does not allow unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. */ template<typename BasicJsonType> struct internal_iterator { /// iterator for JSON objects typename BasicJsonType::object_t::iterator object_iterator {}; /// iterator for JSON arrays typename BasicJsonType::array_t::iterator array_iterator {}; /// generic iterator for all other types primitive_iterator_t primitive_iterator {}; }; template<typename IteratorType> class iteration_proxy; /*! @brief a template for a random access iterator for the @ref basic_json class This class implements a both iterators (iterator and const_iterator) for the @ref basic_json class. @note An iterator is called *initialized* when a pointer to a JSON value has been set (e.g., by a constructor or a copy assignment). If the iterator is default-constructed, it is *uninitialized* and most methods are undefined. **The library uses assertions to detect calls on uninitialized iterators.** @requirement The class satisfies the following concept requirements: - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): The iterator that can be moved to point (forward and backward) to any element in constant time. @since version 1.0.0, simplified in version 2.0.9 */ template<typename BasicJsonType> class iter_impl : public std::iterator<std::random_access_iterator_tag, BasicJsonType> { /// allow basic_json to access private members friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>; friend BasicJsonType; friend iteration_proxy<iter_impl>; using object_t = typename BasicJsonType::object_t; using array_t = typename BasicJsonType::array_t; // make sure BasicJsonType is basic_json or const basic_json static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value, "iter_impl only accepts (const) basic_json"); public: /// the type of the values when the iterator is dereferenced using value_type = typename BasicJsonType::value_type; /// a type to represent differences between iterators using difference_type = typename BasicJsonType::difference_type; /// defines a pointer to the type iterated over (value_type) using pointer = typename std::conditional<std::is_const<BasicJsonType>::value, typename BasicJsonType::const_pointer, typename BasicJsonType::pointer>::type; /// defines a reference to the type iterated over (value_type) using reference = typename std::conditional<std::is_const<BasicJsonType>::value, typename BasicJsonType::const_reference, typename BasicJsonType::reference>::type; /// the category of the iterator using iterator_category = std::bidirectional_iterator_tag; /// default constructor iter_impl() = default; /*! @brief constructor for a given JSON instance @param[in] object pointer to a JSON object for this iterator @pre object != nullptr @post The iterator is initialized; i.e. `m_object != nullptr`. */ explicit iter_impl(pointer object) noexcept : m_object(object) { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = typename object_t::iterator(); break; } case value_t::array: { m_it.array_iterator = typename array_t::iterator(); break; } default: { m_it.primitive_iterator = primitive_iterator_t(); break; } } } /*! @note The conventional copy constructor and copy assignment are implicitly defined. Combined with the following converting constructor and assignment, they support: (1) copy from iterator to iterator, (2) copy from const iterator to const iterator, and (3) conversion from iterator to const iterator. However conversion from const iterator to iterator is not defined. */ /*! @brief converting constructor @param[in] other non-const iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in,out] other non-const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept { m_object = other.m_object; m_it = other.m_it; return *this; } private: /*! @brief set the iterator to the first value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_begin() noexcept { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->begin(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->begin(); break; } case value_t::null: { // set to end so begin()==end() is true: null is empty m_it.primitive_iterator.set_end(); break; } default: { m_it.primitive_iterator.set_begin(); break; } } } /*! @brief set the iterator past the last value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_end() noexcept { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->end(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->end(); break; } default: { m_it.primitive_iterator.set_end(); break; } } } public: /*! @brief return a reference to the value pointed to by the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator*() const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { assert(m_it.object_iterator != m_object->m_value.object->end()); return m_it.object_iterator->second; } case value_t::array: { assert(m_it.array_iterator != m_object->m_value.array->end()); return *m_it.array_iterator; } case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value")); default: { if (JSON_LIKELY(m_it.primitive_iterator.is_begin())) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief dereference the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ pointer operator->() const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { assert(m_it.object_iterator != m_object->m_value.object->end()); return &(m_it.object_iterator->second); } case value_t::array: { assert(m_it.array_iterator != m_object->m_value.array->end()); return &*m_it.array_iterator; } default: { if (JSON_LIKELY(m_it.primitive_iterator.is_begin())) { return m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief post-increment (it++) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator++(int) { auto result = *this; ++(*this); return result; } /*! @brief pre-increment (++it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator++() { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, 1); break; } case value_t::array: { std::advance(m_it.array_iterator, 1); break; } default: { ++m_it.primitive_iterator; break; } } return *this; } /*! @brief post-decrement (it--) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator--(int) { auto result = *this; --(*this); return result; } /*! @brief pre-decrement (--it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator--() { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, -1); break; } case value_t::array: { std::advance(m_it.array_iterator, -1); break; } default: { --m_it.primitive_iterator; break; } } return *this; } /*! @brief comparison: equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator==(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); } assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: return (m_it.object_iterator == other.m_it.object_iterator); case value_t::array: return (m_it.array_iterator == other.m_it.array_iterator); default: return (m_it.primitive_iterator == other.m_it.primitive_iterator); } } /*! @brief comparison: not equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator!=(const iter_impl& other) const { return not operator==(other); } /*! @brief comparison: smaller @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); } assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators")); case value_t::array: return (m_it.array_iterator < other.m_it.array_iterator); default: return (m_it.primitive_iterator < other.m_it.primitive_iterator); } } /*! @brief comparison: less than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<=(const iter_impl& other) const { return not other.operator < (*this); } /*! @brief comparison: greater than @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>(const iter_impl& other) const { return not operator<=(other); } /*! @brief comparison: greater than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>=(const iter_impl& other) const { return not operator<(other); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator+=(difference_type i) { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); case value_t::array: { std::advance(m_it.array_iterator, i); break; } default: { m_it.primitive_iterator += i; break; } } return *this; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator-=(difference_type i) { return operator+=(-i); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator+(difference_type i) const { auto result = *this; result += i; return result; } /*! @brief addition of distance and iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ friend iter_impl operator+(difference_type i, const iter_impl& it) { auto result = it; result += i; return result; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator-(difference_type i) const { auto result = *this; result -= i; return result; } /*! @brief return difference @pre The iterator is initialized; i.e. `m_object != nullptr`. */ difference_type operator-(const iter_impl& other) const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); case value_t::array: return m_it.array_iterator - other.m_it.array_iterator; default: return m_it.primitive_iterator - other.m_it.primitive_iterator; } } /*! @brief access to successor @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator[](difference_type n) const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators")); case value_t::array: return *std::next(m_it.array_iterator, n); case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value")); default: { if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n)) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief return the key of an object iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ typename object_t::key_type key() const { assert(m_object != nullptr); if (JSON_LIKELY(m_object->is_object())) { return m_it.object_iterator->first; } JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators")); } /*! @brief return the value of an iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference value() const { return operator*(); } private: /// associated JSON instance pointer m_object = nullptr; /// the actual iterator of the associated instance internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it = {}; }; /// proxy class for the iterator_wrapper functions template<typename IteratorType> class iteration_proxy { private: /// helper class for iteration class iteration_proxy_internal { private: /// the iterator IteratorType anchor; /// an index for arrays (used to create key names) std::size_t array_index = 0; public: explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {} /// dereference operator (needed for range-based for) iteration_proxy_internal& operator*() { return *this; } /// increment operator (needed for range-based for) iteration_proxy_internal& operator++() { ++anchor; ++array_index; return *this; } /// inequality operator (needed for range-based for) bool operator!=(const iteration_proxy_internal& o) const noexcept { return anchor != o.anchor; } /// return key of the iterator std::string key() const { assert(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: return std::to_string(array_index); // use key from the object case value_t::object: return anchor.key(); // use an empty key for all primitive types default: return ""; } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// the container to iterate typename IteratorType::reference container; public: /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) : container(cont) {} /// return iterator begin (needed for range-based for) iteration_proxy_internal begin() noexcept { return iteration_proxy_internal(container.begin()); } /// return iterator end (needed for range-based for) iteration_proxy_internal end() noexcept { return iteration_proxy_internal(container.end()); } }; /*! @brief a template for a reverse iterator class @tparam Base the base iterator type to reverse. Valid types are @ref iterator (to create @ref reverse_iterator) and @ref const_iterator (to create @ref const_reverse_iterator). @requirement The class satisfies the following concept requirements: - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): The iterator that can be moved to point (forward and backward) to any element in constant time. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator): It is possible to write to the pointed-to element (only if @a Base is @ref iterator). @since version 1.0.0 */ template<typename Base> class json_reverse_iterator : public std::reverse_iterator<Base> { public: using difference_type = std::ptrdiff_t; /// shortcut to the reverse iterator adaptor using base_iterator = std::reverse_iterator<Base>; /// the reference type for the pointed-to element using reference = typename Base::reference; /// create reverse iterator from iterator json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {} /// create reverse iterator from base class json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} /// post-increment (it++) json_reverse_iterator operator++(int) { return static_cast<json_reverse_iterator>(base_iterator::operator++(1)); } /// pre-increment (++it) json_reverse_iterator& operator++() { return static_cast<json_reverse_iterator&>(base_iterator::operator++()); } /// post-decrement (it--) json_reverse_iterator operator--(int) { return static_cast<json_reverse_iterator>(base_iterator::operator--(1)); } /// pre-decrement (--it) json_reverse_iterator& operator--() { return static_cast<json_reverse_iterator&>(base_iterator::operator--()); } /// add to iterator json_reverse_iterator& operator+=(difference_type i) { return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i)); } /// add to iterator json_reverse_iterator operator+(difference_type i) const { return static_cast<json_reverse_iterator>(base_iterator::operator+(i)); } /// subtract from iterator json_reverse_iterator operator-(difference_type i) const { return static_cast<json_reverse_iterator>(base_iterator::operator-(i)); } /// return difference difference_type operator-(const json_reverse_iterator& other) const { return base_iterator(*this) - base_iterator(other); } /// access to successor reference operator[](difference_type n) const { return *(this->operator+(n)); } /// return the key of an object iterator auto key() const -> decltype(std::declval<Base>().key()) { auto it = --this->base(); return it.key(); } /// return the value of an iterator reference value() const { auto it = --this->base(); return it.operator * (); } }; ///////////////////// // output adapters // ///////////////////// /// abstract output adapter interface template<typename CharType> struct output_adapter_protocol { virtual void write_character(CharType c) = 0; virtual void write_characters(const CharType* s, std::size_t length) = 0; virtual ~output_adapter_protocol() = default; }; /// a type to simplify interfaces template<typename CharType> using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>; /// output adapter for byte vectors template<typename CharType> class output_vector_adapter : public output_adapter_protocol<CharType> { public: explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {} void write_character(CharType c) override { v.push_back(c); } void write_characters(const CharType* s, std::size_t length) override { std::copy(s, s + length, std::back_inserter(v)); } private: std::vector<CharType>& v; }; /// output adapter for output streams template<typename CharType> class output_stream_adapter : public output_adapter_protocol<CharType> { public: explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {} void write_character(CharType c) override { stream.put(c); } void write_characters(const CharType* s, std::size_t length) override { stream.write(s, static_cast<std::streamsize>(length)); } private: std::basic_ostream<CharType>& stream; }; /// output adapter for basic_string template<typename CharType> class output_string_adapter : public output_adapter_protocol<CharType> { public: explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {} void write_character(CharType c) override { str.push_back(c); } void write_characters(const CharType* s, std::size_t length) override { str.append(s, length); } private: std::basic_string<CharType>& str; }; template<typename CharType> class output_adapter { public: output_adapter(std::vector<CharType>& vec) : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {} output_adapter(std::basic_ostream<CharType>& s) : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {} output_adapter(std::basic_string<CharType>& s) : oa(std::make_shared<output_string_adapter<CharType>>(s)) {} operator output_adapter_t<CharType>() { return oa; } private: output_adapter_t<CharType> oa = nullptr; }; ////////////////////////////// // binary reader and writer // ////////////////////////////// /*! @brief deserialization of CBOR and MessagePack values */ template<typename BasicJsonType> class binary_reader { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; public: /*! @brief create a binary reader @param[in] adapter input adapter to read from */ explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter)) { assert(ia); } /*! @brief create a JSON value from CBOR input @param[in] strict whether to expect the input to be consumed completed @return JSON value created from CBOR input @throw parse_error.110 if input ended unexpectedly or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported byte was read */ BasicJsonType parse_cbor(const bool strict) { const auto res = parse_cbor_internal(); if (strict) { get(); check_eof(true); } return res; } /*! @brief create a JSON value from MessagePack input @param[in] strict whether to expect the input to be consumed completed @return JSON value created from MessagePack input @throw parse_error.110 if input ended unexpectedly or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported byte was read */ BasicJsonType parse_msgpack(const bool strict) { const auto res = parse_msgpack_internal(); if (strict) { get(); check_eof(true); } return res; } /*! @brief determine system byte order @return true if and only if system's byte order is little endian @note from http://stackoverflow.com/a/1001328/266378 */ static constexpr bool little_endianess(int num = 1) noexcept { return (*reinterpret_cast<char*>(&num) == 1); } private: /*! @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead */ BasicJsonType parse_cbor_internal(const bool get_char = true) { switch (get_char ? get() : current) { // EOF case std::char_traits<char>::eof(): JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input")); // Integer 0x00..0x17 (0..23) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: return static_cast<number_unsigned_t>(current); case 0x18: // Unsigned integer (one-byte uint8_t follows) return get_number<uint8_t>(); case 0x19: // Unsigned integer (two-byte uint16_t follows) return get_number<uint16_t>(); case 0x1a: // Unsigned integer (four-byte uint32_t follows) return get_number<uint32_t>(); case 0x1b: // Unsigned integer (eight-byte uint64_t follows) return get_number<uint64_t>(); // Negative integer -1-0x00..-1-0x17 (-1..-24) case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: return static_cast<int8_t>(0x20 - 1 - current); case 0x38: // Negative integer (one-byte uint8_t follows) { // must be uint8_t ! return static_cast<number_integer_t>(-1) - get_number<uint8_t>(); } case 0x39: // Negative integer -1-n (two-byte uint16_t follows) { return static_cast<number_integer_t>(-1) - get_number<uint16_t>(); } case 0x3a: // Negative integer -1-n (four-byte uint32_t follows) { return static_cast<number_integer_t>(-1) - get_number<uint32_t>(); } case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows) { return static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(get_number<uint64_t>()); } // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: // UTF-8 string (one-byte uint8_t for n follows) case 0x79: // UTF-8 string (two-byte uint16_t for n follow) case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) case 0x7f: // UTF-8 string (indefinite length) { return get_cbor_string(); } // array (0x00..0x17 data items follow) case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: { return get_cbor_array(current & 0x1f); } case 0x98: // array (one-byte uint8_t for n follows) { return get_cbor_array(get_number<uint8_t>()); } case 0x99: // array (two-byte uint16_t for n follow) { return get_cbor_array(get_number<uint16_t>()); } case 0x9a: // array (four-byte uint32_t for n follow) { return get_cbor_array(get_number<uint32_t>()); } case 0x9b: // array (eight-byte uint64_t for n follow) { return get_cbor_array(get_number<uint64_t>()); } case 0x9f: // array (indefinite length) { BasicJsonType result = value_t::array; while (get() != 0xff) { result.push_back(parse_cbor_internal(false)); } return result; } // map (0x00..0x17 pairs of data items follow) case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7: { return get_cbor_object(current & 0x1f); } case 0xb8: // map (one-byte uint8_t for n follows) { return get_cbor_object(get_number<uint8_t>()); } case 0xb9: // map (two-byte uint16_t for n follow) { return get_cbor_object(get_number<uint16_t>()); } case 0xba: // map (four-byte uint32_t for n follow) { return get_cbor_object(get_number<uint32_t>()); } case 0xbb: // map (eight-byte uint64_t for n follow) { return get_cbor_object(get_number<uint64_t>()); } case 0xbf: // map (indefinite length) { BasicJsonType result = value_t::object; while (get() != 0xff) { auto key = get_cbor_string(); result[key] = parse_cbor_internal(); } return result; } case 0xf4: // false { return false; } case 0xf5: // true { return true; } case 0xf6: // null { return value_t::null; } case 0xf9: // Half-Precision Float (two-byte IEEE 754) { const int byte1 = get(); check_eof(); const int byte2 = get(); check_eof(); // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very // easy to include at least decoding support for them even // without such support. An example of a small decoder for // half-precision floating-point numbers in the C language // is shown in Fig. 3. const int half = (byte1 << 8) + byte2; const int exp = (half >> 10) & 0x1f; const int mant = half & 0x3ff; double val; if (exp == 0) { val = std::ldexp(mant, -24); } else if (exp != 31) { val = std::ldexp(mant + 1024, exp - 25); } else { val = (mant == 0) ? std::numeric_limits<double>::infinity() : std::numeric_limits<double>::quiet_NaN(); } return (half & 0x8000) != 0 ? -val : val; } case 0xfa: // Single-Precision Float (four-byte IEEE 754) { return get_number<float>(); } case 0xfb: // Double-Precision Float (eight-byte IEEE 754) { return get_number<double>(); } default: // anything else (0xFF is handled inside the other types) { std::stringstream ss; ss << std::setw(2) << std::setfill('0') << std::hex << current; JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str())); } } } BasicJsonType parse_msgpack_internal() { switch (get()) { // EOF case std::char_traits<char>::eof(): JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input")); // positive fixint case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5a: case 0x5b: case 0x5c: case 0x5d: case 0x5e: case 0x5f: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f: return static_cast<number_unsigned_t>(current); // fixmap case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f: { return get_msgpack_object(current & 0x0f); } // fixarray case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9a: case 0x9b: case 0x9c: case 0x9d: case 0x9e: case 0x9f: { return get_msgpack_array(current & 0x0f); } // fixstr case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7: case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbc: case 0xbd: case 0xbe: case 0xbf: return get_msgpack_string(); case 0xc0: // nil return value_t::null; case 0xc2: // false return false; case 0xc3: // true return true; case 0xca: // float 32 return get_number<float>(); case 0xcb: // float 64 return get_number<double>(); case 0xcc: // uint 8 return get_number<uint8_t>(); case 0xcd: // uint 16 return get_number<uint16_t>(); case 0xce: // uint 32 return get_number<uint32_t>(); case 0xcf: // uint 64 return get_number<uint64_t>(); case 0xd0: // int 8 return get_number<int8_t>(); case 0xd1: // int 16 return get_number<int16_t>(); case 0xd2: // int 32 return get_number<int32_t>(); case 0xd3: // int 64 return get_number<int64_t>(); case 0xd9: // str 8 case 0xda: // str 16 case 0xdb: // str 32 return get_msgpack_string(); case 0xdc: // array 16 { return get_msgpack_array(get_number<uint16_t>()); } case 0xdd: // array 32 { return get_msgpack_array(get_number<uint32_t>()); } case 0xde: // map 16 { return get_msgpack_object(get_number<uint16_t>()); } case 0xdf: // map 32 { return get_msgpack_object(get_number<uint32_t>()); } // positive fixint case 0xe0: case 0xe1: case 0xe2: case 0xe3: case 0xe4: case 0xe5: case 0xe6: case 0xe7: case 0xe8: case 0xe9: case 0xea: case 0xeb: case 0xec: case 0xed: case 0xee: case 0xef: case 0xf0: case 0xf1: case 0xf2: case 0xf3: case 0xf4: case 0xf5: case 0xf6: case 0xf7: case 0xf8: case 0xf9: case 0xfa: case 0xfb: case 0xfc: case 0xfd: case 0xfe: case 0xff: return static_cast<int8_t>(current); default: // anything else { std::stringstream ss; ss << std::setw(2) << std::setfill('0') << std::hex << current; JSON_THROW(parse_error::create(112, chars_read, "error reading MessagePack; last byte: 0x" + ss.str())); } } } /*! @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns `std::char_traits<char>::eof()` in that case. @return character read from the input */ int get() { ++chars_read; return (current = ia->get_character()); } /* @brief read a number from the input @tparam NumberType the type of the number @return number of type @a NumberType @note This function needs to respect the system's endianess, because bytes in CBOR and MessagePack are stored in network order (big endian) and therefore need reordering on little endian systems. @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes */ template<typename NumberType> NumberType get_number() { // step 1: read input into array with system's byte order std::array<uint8_t, sizeof(NumberType)> vec; for (std::size_t i = 0; i < sizeof(NumberType); ++i) { get(); check_eof(); // reverse byte order prior to conversion if necessary if (is_little_endian) { vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current); } else { vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE } } // step 2: convert array into number of type T and return NumberType result; std::memcpy(&result, vec.data(), sizeof(NumberType)); return result; } /*! @brief create a string by reading characters from the input @param[in] len number of bytes to read @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref check_eof() detects the end of the input before we run out of string memory. @return string created by reading @a len bytes @throw parse_error.110 if input has less than @a len bytes */ template<typename NumberType> std::string get_string(const NumberType len) { std::string result; std::generate_n(std::back_inserter(result), len, [this]() { get(); check_eof(); return current; }); return result; } /*! @brief reads a CBOR string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. Additionally, CBOR's strings with indefinite lengths are supported. @return string @throw parse_error.110 if input ended @throw parse_error.113 if an unexpected byte is read */ std::string get_cbor_string() { check_eof(); switch (current) { // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { return get_string(current & 0x1f); } case 0x78: // UTF-8 string (one-byte uint8_t for n follows) { return get_string(get_number<uint8_t>()); } case 0x79: // UTF-8 string (two-byte uint16_t for n follow) { return get_string(get_number<uint16_t>()); } case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) { return get_string(get_number<uint32_t>()); } case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) { return get_string(get_number<uint64_t>()); } case 0x7f: // UTF-8 string (indefinite length) { std::string result; while (get() != 0xff) { check_eof(); result.push_back(static_cast<char>(current)); } return result; } default: { std::stringstream ss; ss << std::setw(2) << std::setfill('0') << std::hex << current; JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str())); } } } template<typename NumberType> BasicJsonType get_cbor_array(const NumberType len) { BasicJsonType result = value_t::array; std::generate_n(std::back_inserter(*result.m_value.array), len, [this]() { return parse_cbor_internal(); }); return result; } template<typename NumberType> BasicJsonType get_cbor_object(const NumberType len) { BasicJsonType result = value_t::object; std::generate_n(std::inserter(*result.m_value.object, result.m_value.object->end()), len, [this]() { get(); auto key = get_cbor_string(); auto val = parse_cbor_internal(); return std::make_pair(std::move(key), std::move(val)); }); return result; } /*! @brief reads a MessagePack string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. @return string @throw parse_error.110 if input ended @throw parse_error.113 if an unexpected byte is read */ std::string get_msgpack_string() { check_eof(); switch (current) { // fixstr case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7: case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbc: case 0xbd: case 0xbe: case 0xbf: { return get_string(current & 0x1f); } case 0xd9: // str 8 { return get_string(get_number<uint8_t>()); } case 0xda: // str 16 { return get_string(get_number<uint16_t>()); } case 0xdb: // str 32 { return get_string(get_number<uint32_t>()); } default: { std::stringstream ss; ss << std::setw(2) << std::setfill('0') << std::hex << current; JSON_THROW(parse_error::create(113, chars_read, "expected a MessagePack string; last byte: 0x" + ss.str())); } } } template<typename NumberType> BasicJsonType get_msgpack_array(const NumberType len) { BasicJsonType result = value_t::array; std::generate_n(std::back_inserter(*result.m_value.array), len, [this]() { return parse_msgpack_internal(); }); return result; } template<typename NumberType> BasicJsonType get_msgpack_object(const NumberType len) { BasicJsonType result = value_t::object; std::generate_n(std::inserter(*result.m_value.object, result.m_value.object->end()), len, [this]() { get(); auto key = get_msgpack_string(); auto val = parse_msgpack_internal(); return std::make_pair(std::move(key), std::move(val)); }); return result; } /*! @brief check if input ended @throw parse_error.110 if input ended */ void check_eof(const bool expect_eof = false) const { if (expect_eof) { if (JSON_UNLIKELY(current != std::char_traits<char>::eof())) { JSON_THROW(parse_error::create(110, chars_read, "expected end of input")); } } else { if (JSON_UNLIKELY(current == std::char_traits<char>::eof())) { JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input")); } } } private: /// input adapter input_adapter_t ia = nullptr; /// the current character int current = std::char_traits<char>::eof(); /// the number of characters read std::size_t chars_read = 0; /// whether we can assume little endianess const bool is_little_endian = little_endianess(); }; /*! @brief serialization to CBOR and MessagePack values */ template<typename BasicJsonType, typename CharType> class binary_writer { public: /*! @brief create a binary writer @param[in] adapter output adapter to write to */ explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter) { assert(oa); } /*! @brief[in] j JSON value to serialize */ void write_cbor(const BasicJsonType& j) { switch (j.type()) { case value_t::null: { oa->write_character(static_cast<CharType>(0xf6)); break; } case value_t::boolean: { oa->write_character(j.m_value.boolean ? static_cast<CharType>(0xf5) : static_cast<CharType>(0xf4)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // CBOR does not differentiate between positive signed // integers and unsigned integers. Therefore, we used the // code from the value_t::number_unsigned case here. if (j.m_value.number_integer <= 0x17) { write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(static_cast<CharType>(0x18)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(static_cast<CharType>(0x19)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(static_cast<CharType>(0x1a)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else { oa->write_character(static_cast<CharType>(0x1b)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } } else { // The conversions below encode the sign in the first // byte, and the value is converted to a positive number. const auto positive_number = -1 - j.m_value.number_integer; if (j.m_value.number_integer >= -24) { write_number(static_cast<uint8_t>(0x20 + positive_number)); } else if (positive_number <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(static_cast<CharType>(0x38)); write_number(static_cast<uint8_t>(positive_number)); } else if (positive_number <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(static_cast<CharType>(0x39)); write_number(static_cast<uint16_t>(positive_number)); } else if (positive_number <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(static_cast<CharType>(0x3a)); write_number(static_cast<uint32_t>(positive_number)); } else { oa->write_character(static_cast<CharType>(0x3b)); write_number(static_cast<uint64_t>(positive_number)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= 0x17) { write_number(static_cast<uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(static_cast<CharType>(0x18)); write_number(static_cast<uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(static_cast<CharType>(0x19)); write_number(static_cast<uint16_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(static_cast<CharType>(0x1a)); write_number(static_cast<uint32_t>(j.m_value.number_unsigned)); } else { oa->write_character(static_cast<CharType>(0x1b)); write_number(static_cast<uint64_t>(j.m_value.number_unsigned)); } break; } case value_t::number_float: // Double-Precision Float { oa->write_character(static_cast<CharType>(0xfb)); write_number(j.m_value.number_float); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0x60 + N)); } else if (N <= 0xff) { oa->write_character(static_cast<CharType>(0x78)); write_number(static_cast<uint8_t>(N)); } else if (N <= 0xffff) { oa->write_character(static_cast<CharType>(0x79)); write_number(static_cast<uint16_t>(N)); } else if (N <= 0xffffffff) { oa->write_character(static_cast<CharType>(0x7a)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { oa->write_character(static_cast<CharType>(0x7b)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write the string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0x80 + N)); } else if (N <= 0xff) { oa->write_character(static_cast<CharType>(0x98)); write_number(static_cast<uint8_t>(N)); } else if (N <= 0xffff) { oa->write_character(static_cast<CharType>(0x99)); write_number(static_cast<uint16_t>(N)); } else if (N <= 0xffffffff) { oa->write_character(static_cast<CharType>(0x9a)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { oa->write_character(static_cast<CharType>(0x9b)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.array) { write_cbor(el); } break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0xa0 + N)); } else if (N <= 0xff) { oa->write_character(static_cast<CharType>(0xb8)); write_number(static_cast<uint8_t>(N)); } else if (N <= 0xffff) { oa->write_character(static_cast<CharType>(0xb9)); write_number(static_cast<uint16_t>(N)); } else if (N <= 0xffffffff) { oa->write_character(static_cast<CharType>(0xba)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { oa->write_character(static_cast<CharType>(0xbb)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.object) { write_cbor(el.first); write_cbor(el.second); } break; } default: break; } } /*! @brief[in] j JSON value to serialize */ void write_msgpack(const BasicJsonType& j) { switch (j.type()) { case value_t::null: // nil { oa->write_character(static_cast<CharType>(0xc0)); break; } case value_t::boolean: // true and false { oa->write_character(j.m_value.boolean ? static_cast<CharType>(0xc3) : static_cast<CharType>(0xc2)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // MessagePack does not differentiate between positive // signed integers and unsigned integers. Therefore, we used // the code from the value_t::number_unsigned case here. if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { // uint 8 oa->write_character(static_cast<CharType>(0xcc)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { // uint 16 oa->write_character(static_cast<CharType>(0xcd)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { // uint 32 oa->write_character(static_cast<CharType>(0xce)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)()) { // uint 64 oa->write_character(static_cast<CharType>(0xcf)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } } else { if (j.m_value.number_integer >= -32) { // negative fixnum write_number(static_cast<int8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)()) { // int 8 oa->write_character(static_cast<CharType>(0xd0)); write_number(static_cast<int8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)()) { // int 16 oa->write_character(static_cast<CharType>(0xd1)); write_number(static_cast<int16_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)()) { // int 32 oa->write_character(static_cast<CharType>(0xd2)); write_number(static_cast<int32_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)()) { // int 64 oa->write_character(static_cast<CharType>(0xd3)); write_number(static_cast<int64_t>(j.m_value.number_integer)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { // uint 8 oa->write_character(static_cast<CharType>(0xcc)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { // uint 16 oa->write_character(static_cast<CharType>(0xcd)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { // uint 32 oa->write_character(static_cast<CharType>(0xce)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)()) { // uint 64 oa->write_character(static_cast<CharType>(0xcf)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } break; } case value_t::number_float: // float 64 { oa->write_character(static_cast<CharType>(0xcb)); write_number(j.m_value.number_float); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 31) { // fixstr write_number(static_cast<uint8_t>(0xa0 | N)); } else if (N <= 255) { // str 8 oa->write_character(static_cast<CharType>(0xd9)); write_number(static_cast<uint8_t>(N)); } else if (N <= 65535) { // str 16 oa->write_character(static_cast<CharType>(0xda)); write_number(static_cast<uint16_t>(N)); } else if (N <= 4294967295) { // str 32 oa->write_character(static_cast<CharType>(0xdb)); write_number(static_cast<uint32_t>(N)); } // step 2: write the string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 15) { // fixarray write_number(static_cast<uint8_t>(0x90 | N)); } else if (N <= 0xffff) { // array 16 oa->write_character(static_cast<CharType>(0xdc)); write_number(static_cast<uint16_t>(N)); } else if (N <= 0xffffffff) { // array 32 oa->write_character(static_cast<CharType>(0xdd)); write_number(static_cast<uint32_t>(N)); } // step 2: write each element for (const auto& el : *j.m_value.array) { write_msgpack(el); } break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 15) { // fixmap write_number(static_cast<uint8_t>(0x80 | (N & 0xf))); } else if (N <= 65535) { // map 16 oa->write_character(static_cast<CharType>(0xde)); write_number(static_cast<uint16_t>(N)); } else if (N <= 4294967295) { // map 32 oa->write_character(static_cast<CharType>(0xdf)); write_number(static_cast<uint32_t>(N)); } // step 2: write each element for (const auto& el : *j.m_value.object) { write_msgpack(el.first); write_msgpack(el.second); } break; } default: break; } } private: /* @brief write a number to output input @param[in] n number of type @a NumberType @tparam NumberType the type of the number @note This function needs to respect the system's endianess, because bytes in CBOR and MessagePack are stored in network order (big endian) and therefore need reordering on little endian systems. */ template<typename NumberType> void write_number(NumberType n) { // step 1: write number to array of length NumberType std::array<CharType, sizeof(NumberType)> vec; std::memcpy(vec.data(), &n, sizeof(NumberType)); // step 2: write array to output (with possible reordering) if (is_little_endian) { // reverse byte order prior to conversion if necessary std::reverse(vec.begin(), vec.end()); } oa->write_characters(vec.data(), sizeof(NumberType)); } private: /// whether we can assume little endianess const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess(); /// the output output_adapter_t<CharType> oa = nullptr; }; /////////////////// // serialization // /////////////////// template<typename BasicJsonType> class serializer { using string_t = typename BasicJsonType::string_t; using number_float_t = typename BasicJsonType::number_float_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; public: /*! @param[in] s output stream to serialize to @param[in] ichar indentation character to use */ serializer(output_adapter_t<char> s, const char ichar) : o(std::move(s)), loc(std::localeconv()), thousands_sep(loc->thousands_sep == nullptr ? '\0' : loc->thousands_sep[0]), decimal_point(loc->decimal_point == nullptr ? '\0' : loc->decimal_point[0]), indent_char(ichar), indent_string(512, indent_char) {} // delete because of pointer members serializer(const serializer&) = delete; serializer& operator=(const serializer&) = delete; /*! @brief internal implementation of the serialization function This function is called by the public member function dump and organizes the serialization internally. The indentation level is propagated as additional parameter. In case of arrays and objects, the function is called recursively. - strings and object keys are escaped using `escape_string()` - integer numbers are converted implicitly via `operator<<` - floating-point numbers are converted to a string using `"%g"` format @param[in] val value to serialize @param[in] pretty_print whether the output shall be pretty-printed @param[in] indent_step the indent level @param[in] current_indent the current indent level (only used internally) */ void dump(const BasicJsonType& val, const bool pretty_print, const bool ensure_ascii, const unsigned int indent_step, const unsigned int current_indent = 0) { switch (val.m_type) { case value_t::object: { if (val.m_value.object->empty()) { o->write_characters("{}", 2); return; } if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element assert(i != val.m_value.object->cend()); assert(std::next(i) == val.m_value.object->cend()); o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_character('{'); // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element assert(i != val.m_value.object->cend()); assert(std::next(i) == val.m_value.object->cend()); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character('}'); } return; } case value_t::array: { if (val.m_value.array->empty()) { o->write_characters("[]", 2); return; } if (pretty_print) { o->write_characters("[\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { o->write_characters(indent_string.c_str(), new_indent); dump(*i, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element assert(not val.m_value.array->empty()); o->write_characters(indent_string.c_str(), new_indent); dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character(']'); } else { o->write_character('['); // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { dump(*i, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element assert(not val.m_value.array->empty()); dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); o->write_character(']'); } return; } case value_t::string: { o->write_character('\"'); dump_escaped(*val.m_value.string, ensure_ascii); o->write_character('\"'); return; } case value_t::boolean: { if (val.m_value.boolean) { o->write_characters("true", 4); } else { o->write_characters("false", 5); } return; } case value_t::number_integer: { dump_integer(val.m_value.number_integer); return; } case value_t::number_unsigned: { dump_integer(val.m_value.number_unsigned); return; } case value_t::number_float: { dump_float(val.m_value.number_float); return; } case value_t::discarded: { o->write_characters("<discarded>", 11); return; } case value_t::null: { o->write_characters("null", 4); return; } } } private: /*! @brief returns the number of expected bytes following in UTF-8 string @param[in] u the first byte of a UTF-8 string @return the number of expected bytes following */ static constexpr std::size_t bytes_following(const uint8_t u) { return ((u <= 127) ? 0 : ((192 <= u and u <= 223) ? 1 : ((224 <= u and u <= 239) ? 2 : ((240 <= u and u <= 247) ? 3 : std::string::npos)))); } /*! @brief calculates the extra space to escape a JSON string @param[in] s the string to escape @param[in] ensure_ascii whether to escape non-ASCII characters with \uXXXX sequences @return the number of characters required to escape string @a s @complexity Linear in the length of string @a s. */ static std::size_t extra_space(const string_t& s, const bool ensure_ascii) noexcept { std::size_t res = 0; for (std::size_t i = 0; i < s.size(); ++i) { switch (s[i]) { // control characters that can be escaped with a backslash case '"': case '\\': case '\b': case '\f': case '\n': case '\r': case '\t': { // from c (1 byte) to \x (2 bytes) res += 1; break; } // control characters that need \uxxxx escaping case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x0b: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: { // from c (1 byte) to \uxxxx (6 bytes) res += 5; break; } default: { if (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F)) { const auto bytes = bytes_following(static_cast<uint8_t>(s[i])); if (bytes == std::string::npos) { // invalid characters are treated as is, so no // additional space will be used break; } if (bytes == 3) { // codepoints that need 4 bytes (i.e., 3 additional // bytes) in UTF-8 need a surrogate pair when \u // escaping is used: from 4 bytes to \uxxxx\uxxxx // (12 bytes) res += (12 - bytes - 1); } else { // from x bytes to \uxxxx (6 bytes) res += (6 - bytes - 1); } // skip the additional bytes i += bytes; } break; } } } return res; } static void escape_codepoint(int codepoint, string_t& result, std::size_t& pos) { // expecting a proper codepoint assert(0x00 <= codepoint and codepoint <= 0x10FFFF); // the last written character was the backslash before the 'u' assert(result[pos] == '\\'); // write the 'u' result[++pos] = 'u'; // convert a number 0..15 to its hex representation (0..f) static const std::array<char, 16> hexify = { { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' } }; if (codepoint < 0x10000) { // codepoints U+0000..U+FFFF can be represented as \uxxxx. result[++pos] = hexify[(codepoint >> 12) & 0x0F]; result[++pos] = hexify[(codepoint >> 8) & 0x0F]; result[++pos] = hexify[(codepoint >> 4) & 0x0F]; result[++pos] = hexify[codepoint & 0x0F]; } else { // codepoints U+10000..U+10FFFF need a surrogate pair to be // represented as \uxxxx\uxxxx. // http://www.unicode.org/faq/utf_bom.html#utf16-4 codepoint -= 0x10000; const int high_surrogate = 0xD800 | ((codepoint >> 10) & 0x3FF); const int low_surrogate = 0xDC00 | (codepoint & 0x3FF); result[++pos] = hexify[(high_surrogate >> 12) & 0x0F]; result[++pos] = hexify[(high_surrogate >> 8) & 0x0F]; result[++pos] = hexify[(high_surrogate >> 4) & 0x0F]; result[++pos] = hexify[high_surrogate & 0x0F]; ++pos; // backslash is already in output result[++pos] = 'u'; result[++pos] = hexify[(low_surrogate >> 12) & 0x0F]; result[++pos] = hexify[(low_surrogate >> 8) & 0x0F]; result[++pos] = hexify[(low_surrogate >> 4) & 0x0F]; result[++pos] = hexify[low_surrogate & 0x0F]; } ++pos; } /*! @brief dump escaped string Escape a string by replacing certain special characters by a sequence of an escape character (backslash) and another character and other control characters by a sequence of "\u" followed by a four-digit hex representation. The escaped string is written to output stream @a o. @param[in] s the string to escape @param[in] ensure_ascii whether to escape non-ASCII characters with \uXXXX sequences @complexity Linear in the length of string @a s. */ void dump_escaped(const string_t& s, const bool ensure_ascii) const { const auto space = extra_space(s, ensure_ascii); if (space == 0) { o->write_characters(s.c_str(), s.size()); return; } // create a result string of necessary size string_t result(s.size() + space, '\\'); std::size_t pos = 0; for (std::size_t i = 0; i < s.size(); ++i) { switch (s[i]) { case '"': // quotation mark (0x22) { result[pos + 1] = '"'; pos += 2; break; } case '\\': // reverse solidus (0x5c) { // nothing to change pos += 2; break; } case '\b': // backspace (0x08) { result[pos + 1] = 'b'; pos += 2; break; } case '\f': // formfeed (0x0c) { result[pos + 1] = 'f'; pos += 2; break; } case '\n': // newline (0x0a) { result[pos + 1] = 'n'; pos += 2; break; } case '\r': // carriage return (0x0d) { result[pos + 1] = 'r'; pos += 2; break; } case '\t': // horizontal tab (0x09) { result[pos + 1] = 't'; pos += 2; break; } default: { // escape control characters (0x00..0x1F) or, if // ensure_ascii parameter is used, non-ASCII characters if ((0x00 <= s[i] and s[i] <= 0x1F) or (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F))) { const auto bytes = bytes_following(static_cast<uint8_t>(s[i])); if (bytes == std::string::npos) { // copy invalid character as is result[pos++] = s[i]; break; } // check that the additional bytes are present assert(i + bytes < s.size()); // to use \uxxxx escaping, we first need to caluclate // the codepoint from the UTF-8 bytes int codepoint = 0; assert(0 <= bytes and bytes <= 3); switch (bytes) { case 0: { codepoint = s[i] & 0xFF; break; } case 1: { codepoint = ((s[i] & 0x3F) << 6) + (s[i + 1] & 0x7F); break; } case 2: { codepoint = ((s[i] & 0x1F) << 12) + ((s[i + 1] & 0x7F) << 6) + (s[i + 2] & 0x7F); break; } case 3: { codepoint = ((s[i] & 0xF) << 18) + ((s[i + 1] & 0x7F) << 12) + ((s[i + 2] & 0x7F) << 6) + (s[i + 3] & 0x7F); break; } default: break; // LCOV_EXCL_LINE } escape_codepoint(codepoint, result, pos); i += bytes; } else { // all other characters are added as-is result[pos++] = s[i]; } break; } } } assert(pos == result.size()); o->write_characters(result.c_str(), result.size()); } /*! @brief dump an integer Dump a given integer to output stream @a o. Works internally with @a number_buffer. @param[in] x integer number (signed or unsigned) to dump @tparam NumberType either @a number_integer_t or @a number_unsigned_t */ template < typename NumberType, detail::enable_if_t<std::is_same<NumberType, number_unsigned_t>::value or std::is_same<NumberType, number_integer_t>::value, int> = 0 > void dump_integer(NumberType x) { // special case for "0" if (x == 0) { o->write_character('0'); return; } const bool is_negative = (x <= 0) and (x != 0); // see issue #755 std::size_t i = 0; while (x != 0) { // spare 1 byte for '\0' assert(i < number_buffer.size() - 1); const auto digit = std::labs(static_cast<long>(x % 10)); number_buffer[i++] = static_cast<char>('0' + digit); x /= 10; } if (is_negative) { // make sure there is capacity for the '-' assert(i < number_buffer.size() - 2); number_buffer[i++] = '-'; } std::reverse(number_buffer.begin(), number_buffer.begin() + i); o->write_characters(number_buffer.data(), i); } /*! @brief dump a floating-point number Dump a given floating-point number to output stream @a o. Works internally with @a number_buffer. @param[in] x floating-point number to dump */ void dump_float(number_float_t x) { // NaN / inf if (not std::isfinite(x) or std::isnan(x)) { o->write_characters("null", 4); return; } // get number of digits for a text -> float -> text round-trip static constexpr auto d = std::numeric_limits<number_float_t>::digits10; // the actual conversion std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x); // negative value indicates an error assert(len > 0); // check if buffer was large enough assert(static_cast<std::size_t>(len) < number_buffer.size()); // erase thousands separator if (thousands_sep != '\0') { const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); std::fill(end, number_buffer.end(), '\0'); assert((end - number_buffer.begin()) <= len); len = (end - number_buffer.begin()); } // convert decimal point to '.' if (decimal_point != '\0' and decimal_point != '.') { const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); if (dec_pos != number_buffer.end()) { *dec_pos = '.'; } } o->write_characters(number_buffer.data(), static_cast<std::size_t>(len)); // determine if need to append ".0" const bool value_is_int_like = std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, [](char c) { return (c == '.' or c == 'e'); }); if (value_is_int_like) { o->write_characters(".0", 2); } } private: /// the output of the serializer output_adapter_t<char> o = nullptr; /// a (hopefully) large enough character buffer std::array<char, 64> number_buffer{{}}; /// the locale const std::lconv* loc = nullptr; /// the locale's thousand separator character const char thousands_sep = '\0'; /// the locale's decimal point character const char decimal_point = '\0'; /// the indentation character const char indent_char; /// the indentation string string_t indent_string; }; template<typename BasicJsonType> class json_ref { public: using value_type = BasicJsonType; json_ref(value_type&& value) : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true) {} json_ref(const value_type& value) : value_ref(const_cast<value_type*>(&value)), is_rvalue(false) {} json_ref(std::initializer_list<json_ref> init) : owned_value(init), value_ref(&owned_value), is_rvalue(true) {} template <class... Args> json_ref(Args... args) : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true) {} // class should be movable only json_ref(json_ref&&) = default; json_ref(const json_ref&) = delete; json_ref& operator=(const json_ref&) = delete; value_type moved_or_copied() const { if (is_rvalue) { return std::move(*value_ref); } return *value_ref; } value_type const& operator*() const { return *static_cast<value_type const*>(value_ref); } value_type const* operator->() const { return static_cast<value_type const*>(value_ref); } private: mutable value_type owned_value = nullptr; value_type* value_ref = nullptr; const bool is_rvalue; }; } // namespace detail /// namespace to hold default `to_json` / `from_json` functions namespace { constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; } /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template<typename, typename> struct adl_serializer { /*! @brief convert a JSON value to any value type This function is usually called by the `get()` function of the @ref basic_json class (either explicit or via conversion operators). @param[in] j JSON value to read from @param[in,out] val value to write to */ template<typename BasicJsonType, typename ValueType> static void from_json(BasicJsonType&& j, ValueType& val) noexcept( noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val))) { ::nlohmann::from_json(std::forward<BasicJsonType>(j), val); } /*! @brief convert any value type to a JSON value This function is usually called by the constructors of the @ref basic_json class. @param[in,out] j JSON value to write to @param[in] val value to read from */ template<typename BasicJsonType, typename ValueType> static void to_json(BasicJsonType& j, ValueType&& val) noexcept( noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val)))) { ::nlohmann::to_json(j, std::forward<ValueType>(val)); } }; /*! @brief JSON Pointer A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions `at` and `operator[]`. Furthermore, JSON pointers are the base for JSON patches. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ class json_pointer { /// allow basic_json to access private members NLOHMANN_BASIC_JSON_TPL_DECLARATION friend class basic_json; public: /*! @brief create JSON pointer Create a JSON pointer according to the syntax described in [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). @param[in] s string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value @throw parse_error.107 if the given JSON pointer @a s is nonempty and does not begin with a slash (`/`); see example below @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is not followed by `0` (representing `~`) or `1` (representing `/`); see example below @liveexample{The example shows the construction several valid JSON pointers as well as the exceptional behavior.,json_pointer} @since version 2.0.0 */ explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {} /*! @brief return a string representation of the JSON pointer @invariant For each JSON pointer `ptr`, it holds: @code {.cpp} ptr == json_pointer(ptr.to_string()); @endcode @return a string representation of the JSON pointer @liveexample{The example shows the result of `to_string`., json_pointer__to_string} @since version 2.0.0 */ std::string to_string() const noexcept { return std::accumulate(reference_tokens.begin(), reference_tokens.end(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + escape(b); }); } /// @copydoc to_string() operator std::string() const { return to_string(); } private: /*! @brief remove and return last reference pointer @throw out_of_range.405 if JSON pointer has no parent */ std::string pop_back() { if (JSON_UNLIKELY(is_root())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } auto last = reference_tokens.back(); reference_tokens.pop_back(); return last; } /// return whether pointer points to the root document bool is_root() const { return reference_tokens.empty(); } json_pointer top() const { if (JSON_UNLIKELY(is_root())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } json_pointer result = *this; result.reference_tokens = {reference_tokens[0]}; return result; } /*! @brief create and return a reference to the pointed to value @complexity Linear in the number of reference tokens. @throw parse_error.109 if array index is not a number @throw type_error.313 if value cannot be unflattened */ NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const; /*! @brief return a reference to the pointed to value @note This version does not throw if a value is not present, but tries to create nested values instead. For instance, calling this function with pointer `"/this/that"` on a null value is equivalent to calling `operator[]("this").operator[]("that")` on that value, effectively changing the null value to an object. @param[in] ptr a JSON value @return reference to the JSON value pointed to by the JSON pointer @complexity Linear in the length of the JSON pointer. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved */ NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const; /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const; /*! @brief return a const reference to the pointed to value @param[in] ptr a JSON value @return const reference to the JSON value pointed to by the JSON pointer @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ NLOHMANN_BASIC_JSON_TPL_DECLARATION const NLOHMANN_BASIC_JSON_TPL& get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const; /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ NLOHMANN_BASIC_JSON_TPL_DECLARATION const NLOHMANN_BASIC_JSON_TPL& get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const; /*! @brief split the string input to reference tokens @note This function is only called by the json_pointer constructor. All exceptions below are documented there. @throw parse_error.107 if the pointer is not empty or begins with '/' @throw parse_error.108 if character '~' is not followed by '0' or '1' */ static std::vector<std::string> split(const std::string& reference_string) { std::vector<std::string> result; // special case: empty reference string -> no reference tokens if (reference_string.empty()) { return result; } // check if nonempty reference string begins with slash if (JSON_UNLIKELY(reference_string[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'")); } // extract the reference tokens: // - slash: position of the last read slash (or end of string) // - start: position after the previous slash for ( // search for the first slash after the first character std::size_t slash = reference_string.find_first_of('/', 1), // set the beginning of the first reference token start = 1; // we can stop if start == string::npos+1 = 0 start != 0; // set the beginning of the next reference token // (will eventually be 0 if slash == std::string::npos) start = slash + 1, // find next slash slash = reference_string.find_first_of('/', start)) { // use the text between the beginning of the reference token // (start) and the last slash (slash). auto reference_token = reference_string.substr(start, slash - start); // check reference tokens are properly escaped for (std::size_t pos = reference_token.find_first_of('~'); pos != std::string::npos; pos = reference_token.find_first_of('~', pos + 1)) { assert(reference_token[pos] == '~'); // ~ must be followed by 0 or 1 if (JSON_UNLIKELY(pos == reference_token.size() - 1 or (reference_token[pos + 1] != '0' and reference_token[pos + 1] != '1'))) { JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'")); } } // finally, store the reference token unescape(reference_token); result.push_back(reference_token); } return result; } /*! @brief replace all occurrences of a substring by another string @param[in,out] s the string to manipulate; changed so that all occurrences of @a f are replaced with @a t @param[in] f the substring to replace with @a t @param[in] t the string to replace @a f @pre The search string @a f must not be empty. **This precondition is enforced with an assertion.** @since version 2.0.0 */ static void replace_substring(std::string& s, const std::string& f, const std::string& t) { assert(not f.empty()); for (auto pos = s.find(f); // find first occurrence of f pos != std::string::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t, and pos = s.find(f, pos + t.size())) // find next occurrence of f {} } /// escape "~"" to "~0" and "/" to "~1" static std::string escape(std::string s) { replace_substring(s, "~", "~0"); replace_substring(s, "/", "~1"); return s; } /// unescape "~1" to tilde and "~0" to slash (order is important!) static void unescape(std::string& s) { replace_substring(s, "~1", "/"); replace_substring(s, "~0", "~"); } /*! @param[in] reference_string the reference string to the current value @param[in] value the value to consider @param[in,out] result the result object to insert values to @note Empty objects or arrays are flattened to `null`. */ NLOHMANN_BASIC_JSON_TPL_DECLARATION static void flatten(const std::string& reference_string, const NLOHMANN_BASIC_JSON_TPL& value, NLOHMANN_BASIC_JSON_TPL& result); /*! @param[in] value flattened JSON @return unflattened JSON @throw parse_error.109 if array index is not a number @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @throw type_error.313 if value cannot be unflattened */ NLOHMANN_BASIC_JSON_TPL_DECLARATION static NLOHMANN_BASIC_JSON_TPL unflatten(const NLOHMANN_BASIC_JSON_TPL& value); friend bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept; friend bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept; /// the reference tokens std::vector<std::string> reference_tokens; }; /*! @brief a class to store JSON values @tparam ObjectType type for JSON objects (`std::map` by default; will be used in @ref object_t) @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used in @ref array_t) @tparam StringType type for JSON strings and object keys (`std::string` by default; will be used in @ref string_t) @tparam BooleanType type for JSON booleans (`bool` by default; will be used in @ref boolean_t) @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by default; will be used in @ref number_integer_t) @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c `uint64_t` by default; will be used in @ref number_unsigned_t) @tparam NumberFloatType type for JSON floating-point numbers (`double` by default; will be used in @ref number_float_t) @tparam AllocatorType type of the allocator to use (`std::allocator` by default) @tparam JSONSerializer the serializer to resolve internal calls to `to_json()` and `from_json()` (@ref adl_serializer by default) @requirement The class satisfies the following concept requirements: - Basic - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible): JSON values can be default constructed. The result will be a JSON null value. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible): A JSON value can be constructed from an rvalue argument. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible): A JSON value can be copy-constructed from an lvalue expression. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable): A JSON value van be assigned from an rvalue argument. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable): A JSON value can be copy-assigned from an lvalue expression. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible): JSON values can be destructed. - Layout - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType): JSON values have [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout): All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes. - Library-wide - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable): JSON values can be compared with `==`, see @ref operator==(const_reference,const_reference). - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable): JSON values can be compared with `<`, see @ref operator<(const_reference,const_reference). - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable): Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function call @ref swap(). - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer): JSON values can be compared against `std::nullptr_t` objects which are used to model the `null` value. - Container - [Container](http://en.cppreference.com/w/cpp/concept/Container): JSON values can be used like STL containers and provide iterator access. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer); JSON values can be used like STL containers and provide reverse iterator access. @invariant The member variables @a m_value and @a m_type have the following relationship: - If `m_type == value_t::object`, then `m_value.object != nullptr`. - If `m_type == value_t::array`, then `m_value.array != nullptr`. - If `m_type == value_t::string`, then `m_value.string != nullptr`. The invariants are checked by member function assert_invariant(). @internal @note ObjectType trick from http://stackoverflow.com/a/9860911 @endinternal @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format](http://rfc7159.net/rfc7159) @since version 1.0.0 @nosubgrouping */ NLOHMANN_BASIC_JSON_TPL_DECLARATION class basic_json { private: template<detail::value_t> friend struct detail::external_constructor; friend ::nlohmann::json_pointer; friend ::nlohmann::detail::parser<basic_json>; friend ::nlohmann::detail::serializer<basic_json>; template<typename BasicJsonType> friend class ::nlohmann::detail::iter_impl; template<typename BasicJsonType, typename CharType> friend class ::nlohmann::detail::binary_writer; template<typename BasicJsonType> friend class ::nlohmann::detail::binary_reader; /// workaround type for MSVC using basic_json_t = NLOHMANN_BASIC_JSON_TPL; // convenience aliases for types residing in namespace detail; using lexer = ::nlohmann::detail::lexer<basic_json>; using parser = ::nlohmann::detail::parser<basic_json>; using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; template<typename BasicJsonType> using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>; template<typename BasicJsonType> using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>; template<typename Iterator> using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>; template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>; template<typename CharType> using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>; using binary_reader = ::nlohmann::detail::binary_reader<basic_json>; template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>; using serializer = ::nlohmann::detail::serializer<basic_json>; public: using value_t = detail::value_t; // forward declarations using json_pointer = ::nlohmann::json_pointer; template<typename T, typename SFINAE> using json_serializer = JSONSerializer<T, SFINAE>; using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>; //////////////// // exceptions // //////////////// /// @name exceptions /// Classes to implement user-defined exceptions. /// @{ /// @copydoc detail::exception using exception = detail::exception; /// @copydoc detail::parse_error using parse_error = detail::parse_error; /// @copydoc detail::invalid_iterator using invalid_iterator = detail::invalid_iterator; /// @copydoc detail::type_error using type_error = detail::type_error; /// @copydoc detail::out_of_range using out_of_range = detail::out_of_range; /// @copydoc detail::other_error using other_error = detail::other_error; /// @} ///////////////////// // container types // ///////////////////// /// @name container types /// The canonic container types to use @ref basic_json like any other STL /// container. /// @{ /// the type of elements in a basic_json container using value_type = basic_json; /// the type of an element reference using reference = value_type&; /// the type of an element const reference using const_reference = const value_type&; /// a type to represent differences between iterators using difference_type = std::ptrdiff_t; /// a type to represent container sizes using size_type = std::size_t; /// the allocator type using allocator_type = AllocatorType<basic_json>; /// the type of an element pointer using pointer = typename std::allocator_traits<allocator_type>::pointer; /// the type of an element const pointer using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer; /// an iterator for a basic_json container using iterator = iter_impl<basic_json>; /// a const iterator for a basic_json container using const_iterator = iter_impl<const basic_json>; /// a reverse iterator for a basic_json container using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>; /// a const reverse iterator for a basic_json container using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>; /// @} /*! @brief returns the allocator associated with the container */ static allocator_type get_allocator() { return allocator_type(); } /*! @brief returns version information on the library This function returns a JSON object with information about the library, including the version number and information on the platform and compiler. @return JSON object holding version information key | description ----------- | --------------- `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). `copyright` | The copyright line for the library as string. `name` | The name of the library as string. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. `url` | The URL of the project as string. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). @liveexample{The following code shows an example output of the `meta()` function.,meta} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @complexity Constant. @since 2.1.0 */ static basic_json meta() { basic_json result; result["copyright"] = "(C) 2013-2017 Niels Lohmann"; result["name"] = "JSON for Modern C++"; result["url"] = "https://github.com/nlohmann/json"; result["version"] = { {"string", "2.1.1"}, {"major", 2}, {"minor", 1}, {"patch", 1} }; #ifdef _WIN32 result["platform"] = "win32"; #elif defined __linux__ result["platform"] = "linux"; #elif defined __APPLE__ result["platform"] = "apple"; #elif defined __unix__ result["platform"] = "unix"; #else result["platform"] = "unknown"; #endif #if defined(__ICC) || defined(__INTEL_COMPILER) result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; #elif defined(__clang__) result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; #elif defined(__GNUC__) || defined(__GNUG__) result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; #elif defined(__HP_cc) || defined(__HP_aCC) result["compiler"] = "hp" #elif defined(__IBMCPP__) result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; #elif defined(_MSC_VER) result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; #elif defined(__PGI) result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; #elif defined(__SUNPRO_CC) result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; #else result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; #endif #ifdef __cplusplus result["compiler"]["c++"] = std::to_string(__cplusplus); #else result["compiler"]["c++"] = "unknown"; #endif return result; } /////////////////////////// // JSON value data types // /////////////////////////// /// @name JSON value data types /// The data types to store a JSON value. These types are derived from /// the template arguments passed to class @ref basic_json. /// @{ /*! @brief a type for an object [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: > An object is an unordered collection of zero or more name/value pairs, > where a name is a string and a value is a string, number, boolean, null, > object, or array. To store objects in C++, a type is defined by the template parameters described below. @tparam ObjectType the container to store objects (e.g., `std::map` or `std::unordered_map`) @tparam StringType the type of the keys or names (e.g., `std::string`). The comparison function `std::less<StringType>` is used to order elements inside the container. @tparam AllocatorType the allocator to use for objects (e.g., `std::allocator`) #### Default type With the default values for @a ObjectType (`std::map`), @a StringType (`std::string`), and @a AllocatorType (`std::allocator`), the default value for @a object_t is: @code {.cpp} std::map< std::string, // key_type basic_json, // value_type std::less<std::string>, // key_compare std::allocator<std::pair<const std::string, basic_json>> // allocator_type > @endcode #### Behavior The choice of @a object_t influences the behavior of the JSON class. With the default type, objects have the following behavior: - When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. - When the names within an object are not unique, later stored name/value pairs overwrite previously stored name/value pairs, leaving the used names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will be treated as equal and both stored as `{"key": 1}`. - Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see @ref dump) in this order. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored and serialized as `{"a": 2, "b": 1}`. - When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be treated as equal. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON object. #### Storage Objects are stored as pointers in a @ref basic_json type. That is, for any access to object values, a pointer of type `object_t*` must be dereferenced. @sa @ref array_t -- type for an array value @since version 1.0.0 @note The order name/value pairs are added to the object is *not* preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as `std::map` with `std::less` is used by default. Please note this behavior conforms to [RFC 7159](http://rfc7159.net/rfc7159), because any order implements the specified "unordered" nature of JSON objects. */ using object_t = ObjectType<StringType, basic_json, std::less<StringType>, AllocatorType<std::pair<const StringType, basic_json>>>; /*! @brief a type for an array [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: > An array is an ordered sequence of zero or more values. To store objects in C++, a type is defined by the template parameters explained below. @tparam ArrayType container type to store arrays (e.g., `std::vector` or `std::list`) @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) #### Default type With the default values for @a ArrayType (`std::vector`) and @a AllocatorType (`std::allocator`), the default value for @a array_t is: @code {.cpp} std::vector< basic_json, // value_type std::allocator<basic_json> // allocator_type > @endcode #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON array. #### Storage Arrays are stored as pointers in a @ref basic_json type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced. @sa @ref object_t -- type for an object value @since version 1.0.0 */ using array_t = ArrayType<basic_json, AllocatorType<basic_json>>; /*! @brief a type for a string [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: > A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization. @tparam StringType the container to store strings (e.g., `std::string`). Note this container is used for keys/names in objects, see @ref object_t. #### Default type With the default values for @a StringType (`std::string`), the default value for @a string_t is: @code {.cpp} std::string @endcode #### Encoding Strings are stored in UTF-8 encoding. Therefore, functions like `std::string::size()` or `std::string::length()` return the number of bytes in the string rather than the number of characters or glyphs. #### String comparison [RFC 7159](http://rfc7159.net/rfc7159) states: > Software implementations are typically required to test names of object > members for equality. Implementations that transform the textual > representation into sequences of Unicode code units and then perform the > comparison numerically, code unit by code unit, are interoperable in the > sense that implementations will agree in all cases on equality or > inequality of two strings. For example, implementations that compare > strings with escaped characters unconverted may incorrectly find that > `"a\\b"` and `"a\u005Cb"` are not equal. This implementation is interoperable as it does compare strings code unit by code unit. #### Storage String values are stored as pointers in a @ref basic_json type. That is, for any access to string values, a pointer of type `string_t*` must be dereferenced. @since version 1.0.0 */ using string_t = StringType; /*! @brief a type for a boolean [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a type which differentiates the two literals `true` and `false`. To store objects in C++, a type is defined by the template parameter @a BooleanType which chooses the type to use. #### Default type With the default values for @a BooleanType (`bool`), the default value for @a boolean_t is: @code {.cpp} bool @endcode #### Storage Boolean values are stored directly inside a @ref basic_json type. @since version 1.0.0 */ using boolean_t = BooleanType; /*! @brief a type for a number (integer) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter @a NumberIntegerType which chooses the type to use. #### Default type With the default values for @a NumberIntegerType (`int64_t`), the default value for @a number_integer_t is: @code {.cpp} int64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `9223372036854775807` (INT64_MAX) and the minimal integer number that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_unsigned_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_integer_t = NumberIntegerType; /*! @brief a type for a number (unsigned) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter @a NumberUnsignedType which chooses the type to use. #### Default type With the default values for @a NumberUnsignedType (`uint64_t`), the default value for @a number_unsigned_t is: @code {.cpp} uint64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `18446744073709551615` (UINT64_MAX) and the minimal integer number that can be stored is `0`. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_integer_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_integer_t -- type for number values (integer) @since version 2.0.0 */ using number_unsigned_t = NumberUnsignedType; /*! @brief a type for a number (floating-point) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store floating-point numbers in C++, a type is defined by the template parameter @a NumberFloatType which chooses the type to use. #### Default type With the default values for @a NumberFloatType (`double`), the default value for @a number_float_t is: @code {.cpp} double @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal `01.2` will be serialized to `1.2`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) states: > This specification allows implementations to set limits on the range and > precision of numbers accepted. Since software that implements IEEE > 754-2008 binary64 (double precision) numbers is generally available and > widely used, good interoperability can be achieved by implementations > that expect no more precision or range than these provide, in the sense > that implementations will approximate JSON numbers within the expected > precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally and be serialized to `null`. #### Storage Floating-point number values are stored directly inside a @ref basic_json type. @sa @ref number_integer_t -- type for number values (integer) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_float_t = NumberFloatType; /// @} private: /// helper for exception-safe object creation template<typename T, typename... Args> static T* create(Args&& ... args) { AllocatorType<T> alloc; auto deleter = [&](T * object) { alloc.deallocate(object, 1); }; std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter); alloc.construct(object.get(), std::forward<Args>(args)...); assert(object != nullptr); return object.release(); } //////////////////////// // JSON value storage // //////////////////////// /*! @brief a JSON value The actual storage for a JSON value of the @ref basic_json class. This union combines the different storage types for the JSON value types defined in @ref value_t. JSON type | value_t type | used type --------- | --------------- | ------------------------ object | object | pointer to @ref object_t array | array | pointer to @ref array_t string | string | pointer to @ref string_t boolean | boolean | @ref boolean_t number | number_integer | @ref number_integer_t number | number_unsigned | @ref number_unsigned_t number | number_float | @ref number_float_t null | null | *no value is stored* @note Variable-length types (objects, arrays, and strings) are stored as pointers. The size of the union should not exceed 64 bits if the default value types are used. @since version 1.0.0 */ union json_value { /// object (stored with pointer to save storage) object_t* object; /// array (stored with pointer to save storage) array_t* array; /// string (stored with pointer to save storage) string_t* string; /// boolean boolean_t boolean; /// number (integer) number_integer_t number_integer; /// number (unsigned integer) number_unsigned_t number_unsigned; /// number (floating-point) number_float_t number_float; /// default constructor (for null values) json_value() = default; /// constructor for booleans json_value(boolean_t v) noexcept : boolean(v) {} /// constructor for numbers (integer) json_value(number_integer_t v) noexcept : number_integer(v) {} /// constructor for numbers (unsigned) json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} /// constructor for numbers (floating-point) json_value(number_float_t v) noexcept : number_float(v) {} /// constructor for empty values of a given type json_value(value_t t) { switch (t) { case value_t::object: { object = create<object_t>(); break; } case value_t::array: { array = create<array_t>(); break; } case value_t::string: { string = create<string_t>(""); break; } case value_t::boolean: { boolean = boolean_t(false); break; } case value_t::number_integer: { number_integer = number_integer_t(0); break; } case value_t::number_unsigned: { number_unsigned = number_unsigned_t(0); break; } case value_t::number_float: { number_float = number_float_t(0.0); break; } case value_t::null: { break; } default: { if (JSON_UNLIKELY(t == value_t::null)) { JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE } break; } } } /// constructor for strings json_value(const string_t& value) { string = create<string_t>(value); } /// constructor for rvalue strings json_value(string_t&& value) { string = create<string_t>(std::move(value)); } /// constructor for objects json_value(const object_t& value) { object = create<object_t>(value); } /// constructor for rvalue objects json_value(object_t&& value) { object = create<object_t>(std::move(value)); } /// constructor for arrays json_value(const array_t& value) { array = create<array_t>(value); } /// constructor for rvalue arrays json_value(array_t&& value) { array = create<array_t>(std::move(value)); } void destroy(value_t t) { switch (t) { case value_t::object: { AllocatorType<object_t> alloc; alloc.destroy(object); alloc.deallocate(object, 1); break; } case value_t::array: { AllocatorType<array_t> alloc; alloc.destroy(array); alloc.deallocate(array, 1); break; } case value_t::string: { AllocatorType<string_t> alloc; alloc.destroy(string); alloc.deallocate(string, 1); break; } default: { break; } } } }; /*! @brief checks the class invariants This function asserts the class invariants. It needs to be called at the end of every constructor to make sure that created objects respect the invariant. Furthermore, it has to be called each time the type of a JSON value is changed, because the invariant expresses a relationship between @a m_type and @a m_value. */ void assert_invariant() const { assert(m_type != value_t::object or m_value.object != nullptr); assert(m_type != value_t::array or m_value.array != nullptr); assert(m_type != value_t::string or m_value.string != nullptr); } public: ////////////////////////// // JSON parser callback // ////////////////////////// using parse_event_t = typename parser::parse_event_t; /*! @brief per-element parser callback type With a parser callback function, the result of parsing a JSON text can be influenced. When passed to @ref parse(std::istream&, const parser_callback_t) or @ref parse(const CharT, const parser_callback_t), it is called on certain events (passed as @ref parse_event_t via parameter @a event) with a set recursion depth @a depth and context JSON value @a parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters @a depth, @a event, and @a parsed. parameter @a event | description | parameter @a depth | parameter @a parsed ------------------ | ----------- | ------------------ | ------------------- parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value @image html callback_events.png "Example when certain parse events are triggered" Discarding a value (i.e., returning `false`) has different effects depending on the context in which function was called: - Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read. - In case a value outside a structured type is skipped, it is replaced with `null`. This case happens if the top-level element is skipped. @param[in] depth the depth of the recursion during parsing @param[in] event an event of type parse_event_t indicating the context in the callback function has been called @param[in,out] parsed the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events @return Whether the JSON value which called the function during parsing should be kept (`true`) or not (`false`). In the latter case, it is either skipped completely or replaced by an empty discarded object. @sa @ref parse(std::istream&, parser_callback_t) or @ref parse(const CharT, const parser_callback_t) for examples @since version 1.0.0 */ using parser_callback_t = typename parser::parser_callback_t; ////////////////// // constructors // ////////////////// /// @name constructors and destructors /// Constructors of class @ref basic_json, copy/move constructor, copy /// assignment, static functions creating objects, and the destructor. /// @{ /*! @brief create an empty value with a given type Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type: Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` @param[in] v the type of the value to create @complexity Constant. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor for different @ref value_t values,basic_json__value_t} @sa @ref clear() -- restores the postcondition of this constructor @since version 1.0.0 */ basic_json(const value_t v) : m_type(v), m_value(v) { assert_invariant(); } /*! @brief create a null object Create a `null` JSON value. It either takes a null pointer as parameter (explicitly creating `null`) or no parameter (implicitly creating `null`). The passed null pointer itself is not read -- it is only used to choose the right constructor. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @liveexample{The following code shows the constructor with and without a null pointer parameter.,basic_json__nullptr_t} @since version 1.0.0 */ basic_json(std::nullptr_t = nullptr) noexcept : basic_json(value_t::null) { assert_invariant(); } /*! @brief create a JSON value This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method exsits. The constructor forwards the parameter @a val to that method (to `json_serializer<U>::to_json` method with `U = uncvref_t<CompatibleType>`, to be exact). Template type @a CompatibleType includes, but is not limited to, the following types: - **arrays**: @ref array_t and all kinds of compatible containers such as `std::vector`, `std::deque`, `std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`, and `std::unordered_multiset` with a `value_type` from which a @ref basic_json value can be constructed. - **objects**: @ref object_t and all kinds of compatible associative containers such as `std::map`, `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to @ref string_t and a `value_type` from which a @ref basic_json value can be constructed. - **strings**: @ref string_t, string literals, and all compatible string containers can be used. - **numbers**: @ref number_integer_t, @ref number_unsigned_t, @ref number_float_t, and all convertible number types such as `int`, `size_t`, `int64_t`, `float` or `double` can be used. - **boolean**: @ref boolean_t / `bool` can be used. See the examples below. @tparam CompatibleType a type such that: - @a CompatibleType is not derived from `std::istream`, - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move constructors), - @a CompatibleType is not a @ref basic_json nested type (e.g., @ref json_pointer, @ref iterator, etc ...) - @ref @ref json_serializer<U> has a `to_json(basic_json_t&, CompatibleType&&)` method @tparam U = `uncvref_t<CompatibleType>` @param[in] val the value to be forwarded to the respective constructor @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @exceptionsafety Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor with several compatible types.,basic_json__CompatibleType} @since version 2.1.0 */ template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>, detail::enable_if_t<not std::is_base_of<std::istream, U>::value and not std::is_same<U, basic_json_t>::value and not detail::is_basic_json_nested_type< basic_json_t, U>::value and detail::has_to_json<basic_json, U>::value, int> = 0> basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json( std::declval<basic_json_t&>(), std::forward<CompatibleType>(val)))) { JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val)); assert_invariant(); } /*! @brief create a container (array or object) from an initializer list Creates a JSON value of type array or object from the passed initializer list @a init. In case @a type_deduction is `true` (default), the type of the JSON value to be created is deducted from the initializer list @a init according to the following rules: 1. If the list is empty, an empty JSON object value `{}` is created. 2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values. 3. In all other cases, an array is created. The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows: 1. The empty initializer list is written as `{}` which is exactly an empty JSON object. 2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object. 3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe. With the rules described above, the following JSON values cannot be expressed by an initializer list: - the empty array (`[]`): use @ref array(initializer_list_t) with an empty initializer list in this case - arrays whose elements satisfy rule 2: use @ref array(initializer_list_t) with the same initializer list in this case @note When used without parentheses around an empty initializer list, @ref basic_json() is called instead of this function, yielding the JSON null value. @param[in] init initializer list with JSON values @param[in] type_deduction internal parameter; when set to `true`, the type of the JSON value is deducted from the initializer list @a init; when set to `false`, the type provided via @a manual_type is forced. This mode is used by the functions @ref array(initializer_list_t) and @ref object(initializer_list_t). @param[in] manual_type internal parameter; when @a type_deduction is set to `false`, the created JSON value will use the provided type (only @ref value_t::array and @ref value_t::object are valid); when @a type_deduction is set to `true`, this parameter has no effect @throw type_error.301 if @a type_deduction is `false`, @a manual_type is `value_t::object`, but @a init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If @a type_deduction would have be `true`, an array would have been created. See @ref object(initializer_list_t) for an example. @complexity Linear in the size of the initializer list @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows how JSON values are created from initializer lists.,basic_json__list_init_t} @sa @ref array(initializer_list_t) -- create a JSON array value from an initializer list @sa @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ basic_json(initializer_list_t init, bool type_deduction = true, value_t manual_type = value_t::array) { // check if each element is an array with two elements whose first // element is a string bool is_an_object = std::all_of(init.begin(), init.end(), [](const detail::json_ref<basic_json>& element_ref) { return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string()); }); // adjust type if type deduction is not wanted if (not type_deduction) { // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_an_object = false; } // if object is wanted but impossible, throw an exception if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object)) { JSON_THROW(type_error::create(301, "cannot create object from initializer list")); } } if (is_an_object) { // the initializer list is a list of pairs -> create object m_type = value_t::object; m_value = value_t::object; std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref) { auto element = element_ref.moved_or_copied(); m_value.object->emplace( std::move(*((*element.m_value.array)[0].m_value.string)), std::move((*element.m_value.array)[1])); }); } else { // the initializer list describes an array -> create array m_type = value_t::array; m_value.array = create<array_t>(init.begin(), init.end()); } assert_invariant(); } /*! @brief explicitly create an array from an initializer list Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the initializer list is empty, the empty array `[]` is created. @note This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (@ref basic_json(initializer_list_t, bool, value_t)). These cases are: 1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys 2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object @param[in] init initializer list with JSON values to create an array from (optional) @return JSON array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `array` function.,array} @sa @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ static basic_json array(initializer_list_t init = {}) { return basic_json(init, false, value_t::array); } /*! @brief explicitly create an object from an initializer list Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object `{}` is created. @note This function is only added for symmetry reasons. In contrast to the related function @ref array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list @a init can also be passed to the initializer list constructor @ref basic_json(initializer_list_t, bool, value_t). @param[in] init initializer list to create an object from (optional) @return JSON object value @throw type_error.301 if @a init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to @ref basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list @a init. See example below. @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `object` function.,object} @sa @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa @ref array(initializer_list_t) -- create a JSON array value from an initializer list @since version 1.0.0 */ static basic_json object(initializer_list_t init = {}) { return basic_json(init, false, value_t::object); } /*! @brief construct an array with count copies of given value Constructs a JSON array value by creating @a cnt copies of a passed value. In case @a cnt is `0`, an empty array is created. @param[in] cnt the number of JSON copies of @a val to create @param[in] val the JSON value to copy @post `std::distance(begin(),end()) == cnt` holds. @complexity Linear in @a cnt. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows examples for the @ref basic_json(size_type\, const basic_json&) constructor.,basic_json__size_type_basic_json} @since version 1.0.0 */ basic_json(size_type cnt, const basic_json& val) : m_type(value_t::array) { m_value.array = create<array_t>(cnt, val); assert_invariant(); } /*! @brief construct a JSON container given an iterator range Constructs the JSON value with the contents of the range `[first, last)`. The semantics depends on the different types a JSON value can have: - In case of a null type, invalid_iterator.206 is thrown. - In case of other primitive types (number, boolean, or string), @a first must be `begin()` and @a last must be `end()`. In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown. - In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or `std::map`; that is, a JSON array or object is constructed from the values in the range. @tparam InputIT an input iterator type (@ref iterator or @ref const_iterator) @param[in] first begin of the range to copy from (included) @param[in] last end of the range to copy from (excluded) @pre Iterators @a first and @a last must be initialized. **This precondition is enforced with an assertion (see warning).** If assertions are switched off, a violation of this precondition yields undefined behavior. @pre Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions below. A violation of this precondition yields undefined behavior. @warning A precondition is enforced with a runtime assertion that will result in calling `std::abort` if this precondition is not met. Assertions can be disabled by defining `NDEBUG` at compile time. See http://en.cppreference.com/w/cpp/error/assert for more information. @throw invalid_iterator.201 if iterators @a first and @a last are not compatible (i.e., do not belong to the same JSON value). In this case, the range `[first, last)` is undefined. @throw invalid_iterator.204 if iterators @a first and @a last belong to a primitive type (number, boolean, or string), but @a first does not point to the first element any more. In this case, the range `[first, last)` is undefined. See example code below. @throw invalid_iterator.206 if iterators @a first and @a last belong to a null value. In this case, the range `[first, last)` is undefined. @complexity Linear in distance between @a first and @a last. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows several ways to create JSON values by specifying a subrange with iterators.,basic_json__InputIt_InputIt} @since version 1.0.0 */ template<class InputIT, typename std::enable_if< std::is_same<InputIT, typename basic_json_t::iterator>::value or std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0> basic_json(InputIT first, InputIT last) { assert(first.m_object != nullptr); assert(last.m_object != nullptr); // make sure iterator fits the current value if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(201, "iterators are not compatible")); } // copy type from first iterator m_type = first.m_object->m_type; // check if iterator range is complete for primitive values switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range")); } break; } default: break; } switch (m_type) { case value_t::number_integer: { m_value.number_integer = first.m_object->m_value.number_integer; break; } case value_t::number_unsigned: { m_value.number_unsigned = first.m_object->m_value.number_unsigned; break; } case value_t::number_float: { m_value.number_float = first.m_object->m_value.number_float; break; } case value_t::boolean: { m_value.boolean = first.m_object->m_value.boolean; break; } case value_t::string: { m_value = *first.m_object->m_value.string; break; } case value_t::object: { m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()))); } assert_invariant(); } /////////////////////////////////////// // other constructors and destructor // /////////////////////////////////////// /// @private basic_json(const detail::json_ref<basic_json>& ref) : basic_json(ref.moved_or_copied()) {} /*! @brief copy constructor Creates a copy of a given JSON value. @param[in] other the JSON value to copy @post `*this == other` @complexity Linear in the size of @a other. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. - As postcondition, it holds: `other == basic_json(other)`. @liveexample{The following code shows an example for the copy constructor.,basic_json__basic_json} @since version 1.0.0 */ basic_json(const basic_json& other) : m_type(other.m_type) { // check of passed value is valid other.assert_invariant(); switch (m_type) { case value_t::object: { m_value = *other.m_value.object; break; } case value_t::array: { m_value = *other.m_value.array; break; } case value_t::string: { m_value = *other.m_value.string; break; } case value_t::boolean: { m_value = other.m_value.boolean; break; } case value_t::number_integer: { m_value = other.m_value.number_integer; break; } case value_t::number_unsigned: { m_value = other.m_value.number_unsigned; break; } case value_t::number_float: { m_value = other.m_value.number_float; break; } default: break; } assert_invariant(); } /*! @brief move constructor Move constructor. Constructs a JSON value with the contents of the given value @a other using move semantics. It "steals" the resources from @a other and leaves it as JSON null value. @param[in,out] other value to move to this object @post `*this` has the same value as @a other before the call. @post @a other is a JSON null value. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @requirement This function helps `basic_json` satisfying the [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible) requirements. @liveexample{The code below shows the move constructor explicitly called via std::move.,basic_json__moveconstructor} @since version 1.0.0 */ basic_json(basic_json&& other) noexcept : m_type(std::move(other.m_type)), m_value(std::move(other.m_value)) { // check that passed value is valid other.assert_invariant(); // invalidate payload other.m_type = value_t::null; other.m_value = {}; assert_invariant(); } /*! @brief copy assignment Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the `swap()` member function. @param[in] other value to copy from @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. @liveexample{The code below shows and example for the copy assignment. It creates a copy of value `a` which is then swapped with `b`. Finally\, the copy of `a` (which is the null value after the swap) is destroyed.,basic_json__copyassignment} @since version 1.0.0 */ reference& operator=(basic_json other) noexcept ( std::is_nothrow_move_constructible<value_t>::value and std::is_nothrow_move_assignable<value_t>::value and std::is_nothrow_move_constructible<json_value>::value and std::is_nothrow_move_assignable<json_value>::value ) { // check that passed value is valid other.assert_invariant(); using std::swap; swap(m_type, other.m_type); swap(m_value, other.m_value); assert_invariant(); return *this; } /*! @brief destructor Destroys the JSON value and frees all allocated memory. @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. - All stored elements are destroyed and all memory is freed. @since version 1.0.0 */ ~basic_json() { assert_invariant(); m_value.destroy(m_type); } /// @} public: /////////////////////// // object inspection // /////////////////////// /// @name object inspection /// Functions to inspect the type of a JSON value. /// @{ /*! @brief serialization Serialization function for JSON values. The function tries to mimic Python's `json.dumps()` function, and currently supports its @a indent and @a ensure_ascii parameters. @param[in] indent If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation. @param[in] indent_char The character to use for indentation if @a indent is greater than `0`. The default is ` ` (space). @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result consists of ASCII characters only. @return string containing the serialization of the JSON value @complexity Linear. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @liveexample{The following example shows the effect of different @a indent\, @a indent_char\, and @a ensure_ascii parameters to the result of the serialization.,dump} @see https://docs.python.org/2/library/json.html#json.dump @since version 1.0.0; indentation character @a indent_char and option @a ensure_ascii added in version 3.0.0 */ string_t dump(const int indent = -1, const char indent_char = ' ', const bool ensure_ascii = false) const { string_t result; serializer s(detail::output_adapter<char>(result), indent_char); if (indent >= 0) { s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent)); } else { s.dump(*this, false, ensure_ascii, 0); } return result; } /*! @brief return the type of the JSON value (explicit) Return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value Value type | return value ------------------------- | ------------------------- null | value_t::null boolean | value_t::boolean string | value_t::string number (integer) | value_t::number_integer number (unsigned integer) | value_t::number_unsigned number (foating-point) | value_t::number_float object | value_t::object array | value_t::array discarded | value_t::discarded @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `type()` for all JSON types.,type} @sa @ref operator value_t() -- return the type of the JSON value (implicit) @sa @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr value_t type() const noexcept { return m_type; } /*! @brief return whether type is primitive This function returns true if and only if the JSON type is primitive (string, number, boolean, or null). @return `true` if type is primitive (string, number, boolean, or null), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_primitive()` for all JSON types.,is_primitive} @sa @ref is_structured() -- returns whether JSON value is structured @sa @ref is_null() -- returns whether JSON value is `null` @sa @ref is_string() -- returns whether JSON value is a string @sa @ref is_boolean() -- returns whether JSON value is a boolean @sa @ref is_number() -- returns whether JSON value is a number @since version 1.0.0 */ constexpr bool is_primitive() const noexcept { return is_null() or is_string() or is_boolean() or is_number(); } /*! @brief return whether type is structured This function returns true if and only if the JSON type is structured (array or object). @return `true` if type is structured (array or object), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_structured()` for all JSON types.,is_structured} @sa @ref is_primitive() -- returns whether value is primitive @sa @ref is_array() -- returns whether value is an array @sa @ref is_object() -- returns whether value is an object @since version 1.0.0 */ constexpr bool is_structured() const noexcept { return is_array() or is_object(); } /*! @brief return whether value is null This function returns true if and only if the JSON value is null. @return `true` if type is null, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_null()` for all JSON types.,is_null} @since version 1.0.0 */ constexpr bool is_null() const noexcept { return (m_type == value_t::null); } /*! @brief return whether value is a boolean This function returns true if and only if the JSON value is a boolean. @return `true` if type is boolean, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_boolean()` for all JSON types.,is_boolean} @since version 1.0.0 */ constexpr bool is_boolean() const noexcept { return (m_type == value_t::boolean); } /*! @brief return whether value is a number This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values. @return `true` if type is number (regardless whether integer, unsigned integer or floating-type), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number()` for all JSON types.,is_number} @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number() const noexcept { return is_number_integer() or is_number_float(); } /*! @brief return whether value is an integer number This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values. @return `true` if type is an integer or unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_integer()` for all JSON types.,is_number_integer} @sa @ref is_number() -- check if value is a number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number_integer() const noexcept { return (m_type == value_t::number_integer or m_type == value_t::number_unsigned); } /*! @brief return whether value is an unsigned integer number This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values. @return `true` if type is an unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_unsigned()` for all JSON types.,is_number_unsigned} @sa @ref is_number() -- check if value is a number @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 2.0.0 */ constexpr bool is_number_unsigned() const noexcept { return (m_type == value_t::number_unsigned); } /*! @brief return whether value is a floating-point number This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values. @return `true` if type is a floating-point number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_float()` for all JSON types.,is_number_float} @sa @ref is_number() -- check if value is number @sa @ref is_number_integer() -- check if value is an integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @since version 1.0.0 */ constexpr bool is_number_float() const noexcept { return (m_type == value_t::number_float); } /*! @brief return whether value is an object This function returns true if and only if the JSON value is an object. @return `true` if type is object, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_object()` for all JSON types.,is_object} @since version 1.0.0 */ constexpr bool is_object() const noexcept { return (m_type == value_t::object); } /*! @brief return whether value is an array This function returns true if and only if the JSON value is an array. @return `true` if type is array, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_array()` for all JSON types.,is_array} @since version 1.0.0 */ constexpr bool is_array() const noexcept { return (m_type == value_t::array); } /*! @brief return whether value is a string This function returns true if and only if the JSON value is a string. @return `true` if type is string, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_string()` for all JSON types.,is_string} @since version 1.0.0 */ constexpr bool is_string() const noexcept { return (m_type == value_t::string); } /*! @brief return whether value is discarded This function returns true if and only if the JSON value was discarded during parsing with a callback function (see @ref parser_callback_t). @note This function will always be `false` for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases. @return `true` if type is discarded, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_discarded()` for all JSON types.,is_discarded} @since version 1.0.0 */ constexpr bool is_discarded() const noexcept { return (m_type == value_t::discarded); } /*! @brief return the type of the JSON value (implicit) Implicitly return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies the @ref value_t operator for all JSON types.,operator__value_t} @sa @ref type() -- return the type of the JSON value (explicit) @sa @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr operator value_t() const noexcept { return m_type; } /// @} private: ////////////////// // value access // ////////////////// /// get a boolean (explicit) boolean_t get_impl(boolean_t* /*unused*/) const { if (JSON_LIKELY(is_boolean())) { return m_value.boolean; } JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()))); } /// get a pointer to the value (object) object_t* get_impl_ptr(object_t* /*unused*/) noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (object) constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (array) array_t* get_impl_ptr(array_t* /*unused*/) noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (array) constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (string) string_t* get_impl_ptr(string_t* /*unused*/) noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (string) constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (boolean) boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (boolean) constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (integer number) number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (integer number) constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (unsigned number) number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (unsigned number) constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (floating-point number) number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (floating-point number) constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /*! @brief helper function to implement get_ref() This function helps to implement get_ref() without code duplication for const and non-const overloads @tparam ThisType will be deduced as `basic_json` or `const basic_json` @throw type_error.303 if ReferenceType does not match underlying value type of the current JSON */ template<typename ReferenceType, typename ThisType> static ReferenceType get_ref_impl(ThisType& obj) { // delegate the call to get_ptr<>() auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>(); if (JSON_LIKELY(ptr != nullptr)) { return *ptr; } JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()))); } public: /// @name value access /// Direct access to the stored value of a JSON value. /// @{ /*! @brief get special-case overload This overloads avoids a lot of template boilerplate, it can be seen as the identity method @tparam BasicJsonType == @ref basic_json @return a copy of *this @complexity Constant. @since version 2.1.0 */ template < typename BasicJsonType, detail::enable_if_t<std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value, int> = 0 > basic_json get() const { return *this; } /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer<ValueType> has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and - @ref json_serializer<ValueType> does not have a `from_json()` method of the form `ValueType from_json(const basic_json&)` @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,get__ValueType_const} @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t < not std::is_same<basic_json_t, ValueType>::value and detail::has_from_json<basic_json_t, ValueType>::value and not detail::has_non_default_from_json<basic_json_t, ValueType>::value, int > = 0 > ValueType get() const noexcept(noexcept( JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>()))) { // we cannot static_assert on ValueTypeCV being non-const, because // there is support for get<const basic_json_t>(), which is why we // still need the uncvref static_assert(not std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); static_assert(std::is_default_constructible<ValueType>::value, "types must be DefaultConstructible when used with get()"); ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; } /*! @brief get a value (explicit); special case Explicit type conversion between the JSON value and a compatible value which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} return JSONSerializer<ValueTypeCV>::from_json(*this); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json and - @ref json_serializer<ValueType> has a `from_json()` method of the form `ValueType from_json(const basic_json&)` @note If @ref json_serializer<ValueType> has both overloads of `from_json()`, this one is chosen. @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and detail::has_non_default_from_json<basic_json_t, ValueType>::value, int> = 0 > ValueType get() const noexcept(noexcept( JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>()))) { static_assert(not std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); return JSONSerializer<ValueTypeCV>::from_json(*this); } /*! @brief get a pointer value (explicit) Explicit pointer access to the internally stored JSON value. No copies are made. @warning The pointer becomes invalid if the underlying JSON object changes. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get__PointerType} @sa @ref get_ptr() for explicit pointer-member access @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> PointerType get() noexcept { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a pointer value (explicit) @copydoc get() */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> constexpr const PointerType get() const noexcept { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a pointer value (implicit) Implicit pointer access to the internally stored JSON value. No copies are made. @warning Writing data to the pointee of the result yields an undefined state. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. Enforced by a static assertion. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get_ptr} @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> PointerType get_ptr() noexcept { // get the type of the PointerType (remove pointer and const) using pointee_t = typename std::remove_const<typename std::remove_pointer<typename std::remove_const<PointerType>::type>::type>::type; // make sure the type matches the allowed types static_assert( std::is_same<object_t, pointee_t>::value or std::is_same<array_t, pointee_t>::value or std::is_same<string_t, pointee_t>::value or std::is_same<boolean_t, pointee_t>::value or std::is_same<number_integer_t, pointee_t>::value or std::is_same<number_unsigned_t, pointee_t>::value or std::is_same<number_float_t, pointee_t>::value , "incompatible pointer type"); // delegate the call to get_impl_ptr<>() return get_impl_ptr(static_cast<PointerType>(nullptr)); } /*! @brief get a pointer value (implicit) @copydoc get_ptr() */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value and std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0> constexpr const PointerType get_ptr() const noexcept { // get the type of the PointerType (remove pointer and const) using pointee_t = typename std::remove_const<typename std::remove_pointer<typename std::remove_const<PointerType>::type>::type>::type; // make sure the type matches the allowed types static_assert( std::is_same<object_t, pointee_t>::value or std::is_same<array_t, pointee_t>::value or std::is_same<string_t, pointee_t>::value or std::is_same<boolean_t, pointee_t>::value or std::is_same<number_integer_t, pointee_t>::value or std::is_same<number_unsigned_t, pointee_t>::value or std::is_same<number_float_t, pointee_t>::value , "incompatible pointer type"); // delegate the call to get_impl_ptr<>() const return get_impl_ptr(static_cast<PointerType>(nullptr)); } /*! @brief get a reference value (implicit) Implicit reference access to the internally stored JSON value. No copies are made. @warning Writing data to the referee of the result yields an undefined state. @tparam ReferenceType reference type; must be a reference to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or @ref number_float_t. Enforced by static assertion. @return reference to the internally stored JSON value if the requested reference type @a ReferenceType fits to the JSON value; throws type_error.303 otherwise @throw type_error.303 in case passed type @a ReferenceType is incompatible with the stored JSON value; see example below @complexity Constant. @liveexample{The example shows several calls to `get_ref()`.,get_ref} @since version 1.1.0 */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value, int>::type = 0> ReferenceType get_ref() { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a reference value (implicit) @copydoc get_ref() */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value and std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0> ReferenceType get_ref() const { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a value (implicit) Implicit type conversion between the JSON value and a compatible value. The call is realized by calling @ref get() const. @tparam ValueType non-pointer type compatible to the JSON value, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. The character type of @ref string_t as well as an initializer list of this type is excluded to avoid ambiguities as these types implicitly convert to `std::string`. @return copy of the JSON value, converted to type @a ValueType @throw type_error.302 in case passed type @a ValueType is incompatible to the JSON value type (e.g., the JSON value is of type boolean, but a string is requested); see example below @complexity Linear in the size of the JSON value. @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,operator__ValueType} @since version 1.0.0 */ template < typename ValueType, typename std::enable_if < not std::is_pointer<ValueType>::value and not std::is_same<ValueType, detail::json_ref<basic_json>>::value and not std::is_same<ValueType, typename string_t::value_type>::value #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value #endif #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_MSC_VER) && _MSC_VER >1900 && defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 and not std::is_same<ValueType, typename std::string_view>::value #endif , int >::type = 0 > operator ValueType() const { // delegate the call to get<>() const return get<ValueType>(); } /// @} //////////////////// // element access // //////////////////// /// @name element access /// Access to the JSON value. /// @{ /*! @brief access specified array element with bounds checking Returns a reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__size_type} */ reference at(size_type idx) { // at only works for arrays if (JSON_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified array element with bounds checking Returns a const reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__size_type_const} */ const_reference at(size_type idx) const { // at only works for arrays if (JSON_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified object element with bounds checking Returns a reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__object_t_key_type} */ reference at(const typename object_t::key_type& key) { // at only works for objects if (JSON_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified object element with bounds checking Returns a const reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return const reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__object_t_key_type_const} */ const_reference at(const typename object_t::key_type& key) const { // at only works for objects if (JSON_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified array element Returns a reference to the element at specified location @a idx. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), then the array is silently filled up with `null` values to make `idx` a valid reference to the last stored element. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array or null; in that cases, using the [] operator with an index makes no sense. @complexity Constant if @a idx is in the range of the array. Otherwise linear in `idx - size()`. @liveexample{The example below shows how array elements can be read and written using `[]` operator. Note the addition of `null` values.,operatorarray__size_type} @since version 1.0.0 */ reference operator[](size_type idx) { // implicitly convert null value to an empty array if (is_null()) { m_type = value_t::array; m_value.array = create<array_t>(); assert_invariant(); } // operator[] only works for arrays if (JSON_LIKELY(is_array())) { // fill up array with null values if given idx is outside range if (idx >= m_value.array->size()) { m_value.array->insert(m_value.array->end(), idx - m_value.array->size() + 1, basic_json()); } return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief access specified array element Returns a const reference to the element at specified location @a idx. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array; in that cases, using the [] operator with an index makes no sense. @complexity Constant. @liveexample{The example below shows how array elements can be read using the `[]` operator.,operatorarray__size_type_const} @since version 1.0.0 */ const_reference operator[](size_type idx) const { // const operator[] only works for arrays if (JSON_LIKELY(is_array())) { return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ reference operator[](const typename object_t::key_type& key) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } // operator[] only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->operator[](key); } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ const_reference operator[](const typename object_t::key_type& key) const { // const operator[] only works for objects if (JSON_LIKELY(is_object())) { assert(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> reference operator[](T* key) { // implicitly convert null to object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // at only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->operator[](key); } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> const_reference operator[](T* key) const { // at only works for objects if (JSON_LIKELY(is_object())) { assert(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief access specified object element with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(key); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const typename object_t::key_type&), this function does not throw if the given key @a key was not found. @note Unlike @ref operator[](const typename object_t::key_type& key), this function does not implicitly add an element to the position defined by @a key. This function is furthermore also applicable to const objects. @param[in] key key of the element to access @param[in] default_value the value to return if @a key is not found @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.306 if the JSON value is not an objec; in that cases, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @since version 1.0.0 */ template<class ValueType, typename std::enable_if< std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const { // at only works for objects if (JSON_LIKELY(is_object())) { // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { return *it; } return default_value; } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const */ string_t value(const typename object_t::key_type& key, const char* default_value) const { return value(key, string_t(default_value)); } /*! @brief access specified object element via JSON Pointer with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(ptr); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const json_pointer&), this function does not throw if the given key @a key was not found. @param[in] ptr a JSON pointer to the element to access @param[in] default_value the value to return if @a ptr found no value @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.306 if the JSON value is not an objec; in that cases, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value_ptr} @sa @ref operator[](const json_pointer&) for unchecked access by reference @since version 2.0.2 */ template<class ValueType, typename std::enable_if< std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const json_pointer& ptr, const ValueType& default_value) const { // at only works for objects if (JSON_LIKELY(is_object())) { // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this); } JSON_CATCH (out_of_range&) { return default_value; } } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const json_pointer&, ValueType) const */ string_t value(const json_pointer& ptr, const char* default_value) const { return value(ptr, string_t(default_value)); } /*! @brief access the first element Returns a reference to the first element in the container. For a JSON container `c`, the expression `c.front()` is equivalent to `*c.begin()`. @return In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, or boolean values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on `null` value @liveexample{The following code shows an example for `front()`.,front} @sa @ref back() -- access the last element @since version 1.0.0 */ reference front() { return *begin(); } /*! @copydoc basic_json::front() */ const_reference front() const { return *cbegin(); } /*! @brief access the last element Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to @code {.cpp} auto tmp = c.end(); --tmp; return *tmp; @endcode @return In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, or boolean values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on a `null` value. See example below. @liveexample{The following code shows an example for `back()`.,back} @sa @ref front() -- access the first element @since version 1.0.0 */ reference back() { auto tmp = end(); --tmp; return *tmp; } /*! @copydoc basic_json::back() */ const_reference back() const { auto tmp = cend(); --tmp; return *tmp; } /*! @brief remove element given an iterator Removes the element specified by iterator @a pos. The iterator @a pos must be valid and dereferenceable. Thus the `end()` iterator (which is valid, but is not dereferenceable) cannot be used as a value for @a pos. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] pos iterator to the element to remove @return Iterator following the last removed element. If the iterator @a pos refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"` @throw invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not `begin()`); example: `"iterator out of range"` @complexity The complexity depends on the type: - objects: amortized constant - arrays: linear in distance between @a pos and the end of the container - strings: linear in the length of the string - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType} @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template<class IteratorType, typename std::enable_if< std::is_same<IteratorType, typename basic_json_t::iterator>::value or std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type = 0> IteratorType erase(IteratorType pos) { // make sure iterator fits the current value if (JSON_UNLIKELY(this != pos.m_object)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin())) { JSON_THROW(invalid_iterator::create(205, "iterator out of range")); } if (is_string()) { AllocatorType<string_t> alloc; alloc.destroy(m_value.string); alloc.deallocate(m_value.string, 1); m_value.string = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } return result; } /*! @brief remove elements given an iterator range Removes the element specified by the range `[first; last)`. The iterator @a first does not need to be dereferenceable if `first == last`: erasing an empty range is a no-op. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] first iterator to the beginning of the range to remove @param[in] last iterator past the end of the range to remove @return Iterator following the last removed element. If the iterator @a second refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: `"iterators do not fit current value"` @throw invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if `first != begin()` and `last != end()`); example: `"iterators out of range"` @complexity The complexity depends on the type: - objects: `log(size()) + std::distance(first, last)` - arrays: linear in the distance between @a first and @a last, plus linear in the distance between @a last and end of the container - strings: linear in the length of the string - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType_IteratorType} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template<class IteratorType, typename std::enable_if< std::is_same<IteratorType, typename basic_json_t::iterator>::value or std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type = 0> IteratorType erase(IteratorType first, IteratorType last) { // make sure iterator fits the current value if (JSON_UNLIKELY(this != first.m_object or this != last.m_object)) { JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range")); } if (is_string()) { AllocatorType<string_t> alloc; alloc.destroy(m_value.string); alloc.deallocate(m_value.string, 1); m_value.string = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } return result; } /*! @brief remove element from a JSON object given a key Removes elements from a JSON object with the key value @a key. @param[in] key value of the elements to remove @return Number of elements removed. If @a ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @post References and iterators to the erased elements are invalidated. Other references and iterators are not affected. @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @complexity `log(size()) + count(key)` @liveexample{The example shows the effect of `erase()`.,erase__key_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ size_type erase(const typename object_t::key_type& key) { // this erase only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->erase(key); } JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } /*! @brief remove element from a JSON array given an index Removes element from a JSON array at the index @a idx. @param[in] idx index of the element to remove @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 is out of range"` @complexity Linear in distance between @a idx and the end of the container. @liveexample{The example shows the effect of `erase()`.,erase__size_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @since version 1.0.0 */ void erase(const size_type idx) { // this erase only works for arrays if (JSON_LIKELY(is_array())) { if (JSON_UNLIKELY(idx >= size())) { JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx)); } else { JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } } /// @} //////////// // lookup // //////////// /// @name lookup /// @{ /*! @brief find an element in a JSON object Finds an element in a JSON object with key equivalent to @a key. If the element is not found or the JSON value is not an object, end() is returned. @note This method always returns @ref end() when executed on a JSON type that is not an object. @param[in] key key value of the element to search for @return Iterator to an element with key equivalent to @a key. If no such element is found or the JSON value is not an object, past-the-end (see @ref end()) iterator is returned. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `find()` is used.,find__key_type} @since version 1.0.0 */ iterator find(typename object_t::key_type key) { auto result = end(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(key); } return result; } /*! @brief find an element in a JSON object @copydoc find(typename object_t::key_type) */ const_iterator find(typename object_t::key_type key) const { auto result = cend(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(key); } return result; } /*! @brief returns the number of occurrences of a key in a JSON object Returns the number of elements with key @a key. If ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @note This method always returns `0` when executed on a JSON type that is not an object. @param[in] key key value of the element to count @return Number of elements with key @a key. If the JSON value is not an object, the return value will be `0`. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `count()` is used.,count} @since version 1.0.0 */ size_type count(typename object_t::key_type key) const { // return 0 for all nonobject types return is_object() ? m_value.object->count(key) : 0; } /// @} /////////////// // iterators // /////////////// /// @name iterators /// @{ /*! @brief returns an iterator to the first element Returns an iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `begin()`.,begin} @sa @ref cbegin() -- returns a const iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ iterator begin() noexcept { iterator result(this); result.set_begin(); return result; } /*! @copydoc basic_json::cbegin() */ const_iterator begin() const noexcept { return cbegin(); } /*! @brief returns a const iterator to the first element Returns a const iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`. @liveexample{The following code shows an example for `cbegin()`.,cbegin} @sa @ref begin() -- returns an iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ const_iterator cbegin() const noexcept { const_iterator result(this); result.set_begin(); return result; } /*! @brief returns an iterator to one past the last element Returns an iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `end()`.,end} @sa @ref cend() -- returns a const iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ iterator end() noexcept { iterator result(this); result.set_end(); return result; } /*! @copydoc basic_json::cend() */ const_iterator end() const noexcept { return cend(); } /*! @brief returns a const iterator to one past the last element Returns a const iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).end()`. @liveexample{The following code shows an example for `cend()`.,cend} @sa @ref end() -- returns an iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ const_iterator cend() const noexcept { const_iterator result(this); result.set_end(); return result; } /*! @brief returns an iterator to the reverse-beginning Returns an iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(end())`. @liveexample{The following code shows an example for `rbegin()`.,rbegin} @sa @ref crbegin() -- returns a const reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } /*! @copydoc basic_json::crbegin() */ const_reverse_iterator rbegin() const noexcept { return crbegin(); } /*! @brief returns an iterator to the reverse-end Returns an iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(begin())`. @liveexample{The following code shows an example for `rend()`.,rend} @sa @ref crend() -- returns a const reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ reverse_iterator rend() noexcept { return reverse_iterator(begin()); } /*! @copydoc basic_json::crend() */ const_reverse_iterator rend() const noexcept { return crend(); } /*! @brief returns a const reverse iterator to the last element Returns a const iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`. @liveexample{The following code shows an example for `crbegin()`.,crbegin} @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /*! @brief returns a const reverse iterator to one before the first Returns a const reverse iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`. @liveexample{The following code shows an example for `crend()`.,crend} @sa @ref rend() -- returns a reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } public: /*! @brief wrapper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. @liveexample{The following code shows how the wrapper is used,iterator_wrapper} @note The name of this function is not yet final and may change in the future. */ static iteration_proxy<iterator> iterator_wrapper(reference cont) { return iteration_proxy<iterator>(cont); } /*! @copydoc iterator_wrapper(reference) */ static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont) { return iteration_proxy<const_iterator>(cont); } /// @} ////////////// // capacity // ////////////// /// @name capacity /// @{ /*! @brief checks whether the container is empty. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `true` boolean | `false` string | `false` number | `false` object | result of function `object_t::empty()` array | result of function `array_t::empty()` @liveexample{The following code uses `empty()` to check if a JSON object contains any elements.,empty} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `empty()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return whether a string stored as JSON value is empty - it returns whether the JSON container itself is empty which is false in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `begin() == end()`. @sa @ref size() -- returns the number of elements @since version 1.0.0 */ bool empty() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return true; } case value_t::array: { // delegate call to array_t::empty() return m_value.array->empty(); } case value_t::object: { // delegate call to object_t::empty() return m_value.object->empty(); } default: { // all other types are nonempty return false; } } } /*! @brief returns the number of elements Returns the number of elements in a JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` boolean | `1` string | `1` number | `1` object | result of function object_t::size() array | result of function array_t::size() @liveexample{The following code calls `size()` on the different value types.,size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their size() functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return the length of a string stored as JSON value - it returns the number of elements in the JSON value which is 1 in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `std::distance(begin(), end())`. @sa @ref empty() -- checks whether the container is empty @sa @ref max_size() -- returns the maximal number of elements @since version 1.0.0 */ size_type size() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return 0; } case value_t::array: { // delegate call to array_t::size() return m_value.array->size(); } case value_t::object: { // delegate call to object_t::size() return m_value.object->size(); } default: { // all other types have size 1 return 1; } } } /*! @brief returns the maximum possible number of elements Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. `std::distance(begin(), end())` for the JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` (same as `size()`) boolean | `1` (same as `size()`) string | `1` (same as `size()`) number | `1` (same as `size()`) object | result of function `object_t::max_size()` array | result of function `array_t::max_size()` @liveexample{The following code calls `max_size()` on the different value types. Note the output is implementation specific.,max_size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `max_size()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of returning `b.size()` where `b` is the largest possible JSON value. @sa @ref size() -- returns the number of elements @since version 1.0.0 */ size_type max_size() const noexcept { switch (m_type) { case value_t::array: { // delegate call to array_t::max_size() return m_value.array->max_size(); } case value_t::object: { // delegate call to object_t::max_size() return m_value.object->max_size(); } default: { // all other types have max_size() == size() return size(); } } } /// @} /////////////// // modifiers // /////////////// /// @name modifiers /// @{ /*! @brief clears the contents Clears the content of a JSON value and resets it to the default value as if @ref basic_json(value_t) would have been called with the current value type from @ref type(): Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` @post Has the same effect as calling @code {.cpp} *this = basic_json(type()); @endcode @liveexample{The example below shows the effect of `clear()` to different JSON types.,clear} @complexity Linear in the size of the JSON value. @iterators All iterators, pointers and references related to this container are invalidated. @exceptionsafety No-throw guarantee: this function never throws exceptions. @sa @ref basic_json(value_t) -- constructor that creates an object with the same value than calling `clear()` @since version 1.0.0 */ void clear() noexcept { switch (m_type) { case value_t::number_integer: { m_value.number_integer = 0; break; } case value_t::number_unsigned: { m_value.number_unsigned = 0; break; } case value_t::number_float: { m_value.number_float = 0.0; break; } case value_t::boolean: { m_value.boolean = false; break; } case value_t::string: { m_value.string->clear(); break; } case value_t::array: { m_value.array->clear(); break; } case value_t::object: { m_value.object->clear(); break; } default: break; } } /*! @brief add an object to an array Appends the given element @a val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending @a val. @param[in] val the value to add to the JSON array @throw type_error.308 when called on a type other than JSON array or null; example: `"cannot use push_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,push_back} @since version 1.0.0 */ void push_back(basic_json&& val) { // push_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (move semantics) m_value.array->push_back(std::move(val)); // invalidate object val.m_type = value_t::null; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(basic_json&& val) { push_back(std::move(val)); return *this; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ void push_back(const basic_json& val) { // push_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array m_value.array->push_back(val); } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(const basic_json& val) { push_back(val); return *this; } /*! @brief add an object to an object Inserts the given element @a val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting @a val. @param[in] val the value to add to the JSON object @throw type_error.308 when called on a type other than JSON object or null; example: `"cannot use push_back() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object.,push_back__object_t__value} @since version 1.0.0 */ void push_back(const typename object_t::value_type& val) { // push_back only works for null objects or objects if (JSON_UNLIKELY(not(is_null() or is_object()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array m_value.object->insert(val); } /*! @brief add an object to an object @copydoc push_back(const typename object_t::value_type&) */ reference operator+=(const typename object_t::value_type& val) { push_back(val); return *this; } /*! @brief add an object to an object This function allows to use `push_back` with an initializer list. In case 1. the current value is an object, 2. the initializer list @a init contains only two elements, and 3. the first element of @a init is a string, @a init is converted into an object element and added using @ref push_back(const typename object_t::value_type&). Otherwise, @a init is converted to a JSON value and added using @ref push_back(basic_json&&). @param[in] init an initializer list @complexity Linear in the size of the initializer list @a init. @note This function is required to resolve an ambiguous overload error, because pairs like `{"key", "value"}` can be both interpreted as `object_t::value_type` or `std::initializer_list<basic_json>`, see https://github.com/nlohmann/json/issues/235 for more information. @liveexample{The example shows how initializer lists are treated as objects when possible.,push_back__initializer_list} */ void push_back(initializer_list_t init) { if (is_object() and init.size() == 2 and (*init.begin())->is_string()) { basic_json&& key = init.begin()->moved_or_copied(); push_back(typename object_t::value_type( std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied())); } else { push_back(basic_json(init)); } } /*! @brief add an object to an object @copydoc push_back(initializer_list_t) */ reference operator+=(initializer_list_t init) { push_back(init); return *this; } /*! @brief add an object to an array Creates a JSON value from the passed parameters @a args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @throw type_error.311 when called on a type other than JSON array or null; example: `"cannot use emplace_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,emplace_back} @since version 2.0.8 */ template<class... Args> void emplace_back(Args&& ... args) { // emplace_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (perfect forwarding) m_value.array->emplace_back(std::forward<Args>(args)...); } /*! @brief add an object to an object if key does not exist Inserts a new element into a JSON object constructed in-place with the given @a args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @return a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place. @throw type_error.311 when called on a type other than JSON object or null; example: `"cannot use emplace() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.,emplace} @since version 2.0.8 */ template<class... Args> std::pair<iterator, bool> emplace(Args&& ... args) { // emplace only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_object()))) { JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()))); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array (perfect forwarding) auto res = m_value.object->emplace(std::forward<Args>(args)...); // create result iterator and set iterator to the result of emplace auto it = begin(); it.m_it.object_iterator = res.first; // return pair of iterator and boolean return {it, res.second}; } /*! @brief inserts element Inserts element @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] val element to insert @return iterator pointing to the inserted @a val. @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Constant plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert} @since version 1.0.0 */ iterator insert(const_iterator pos, const basic_json& val) { // insert only works for arrays if (JSON_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val); return result; } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } /*! @brief inserts element @copydoc insert(const_iterator, const basic_json&) */ iterator insert(const_iterator pos, basic_json&& val) { return insert(pos, val); } /*! @brief inserts elements Inserts @a cnt copies of @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] cnt number of copies of @a val to insert @param[in] val element to insert @return iterator pointing to the first element inserted, or @a pos if `cnt==0` @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Linear in @a cnt plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__count} @since version 1.0.0 */ iterator insert(const_iterator pos, size_type cnt, const basic_json& val) { // insert only works for arrays if (JSON_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); return result; } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } /*! @brief inserts elements Inserts elements from range `[first, last)` before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @throw invalid_iterator.211 if @a first or @a last are iterators into container for which insert is called; example: `"passed iterators may not belong to container"` @return iterator pointing to the first element inserted, or @a pos if `first==last` @complexity Linear in `std::distance(first, last)` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__range} @since version 1.0.0 */ iterator insert(const_iterator pos, const_iterator first, const_iterator last) { // insert only works for arrays if (JSON_UNLIKELY(not is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } if (JSON_UNLIKELY(first.m_object == this or last.m_object == this)) { JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert( pos.m_it.array_iterator, first.m_it.array_iterator, last.m_it.array_iterator); return result; } /*! @brief inserts elements Inserts elements from initializer list @a ilist before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] ilist initializer list to insert the values from @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @return iterator pointing to the first element inserted, or @a pos if `ilist` is empty @complexity Linear in `ilist.size()` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__ilist} @since version 1.0.0 */ iterator insert(const_iterator pos, initializer_list_t ilist) { // insert only works for arrays if (JSON_UNLIKELY(not is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end()); return result; } /*! @brief inserts elements Inserts elements from range `[first, last)`. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than objects; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number of elements to insert. @liveexample{The example shows how `insert()` is used.,insert__range_object} @since version 3.0.0 */ void insert(const_iterator first, const_iterator last) { // insert only works for objects if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } // passed iterators must belong to objects if (JSON_UNLIKELY(not first.m_object->is_object() or not last.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); } m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from JSON object @a j and overwrites existing keys. @param[in] j JSON object to read values from @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_reference j) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); } if (JSON_UNLIKELY(not j.is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()))); } for (auto it = j.begin(); it != j.end(); ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from from range `[first, last)` and overwrites existing keys. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used__range.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_iterator first, const_iterator last) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } // passed iterators must belong to objects if (JSON_UNLIKELY(not first.m_object->is_object() or not first.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); } for (auto it = first; it != last; ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief exchanges the values Exchanges the contents of the JSON value with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other JSON value to exchange the contents with @complexity Constant. @liveexample{The example below shows how JSON values can be swapped with `swap()`.,swap__reference} @since version 1.0.0 */ void swap(reference other) noexcept ( std::is_nothrow_move_constructible<value_t>::value and std::is_nothrow_move_assignable<value_t>::value and std::is_nothrow_move_constructible<json_value>::value and std::is_nothrow_move_assignable<json_value>::value ) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); assert_invariant(); } /*! @brief exchanges the values Exchanges the contents of a JSON array with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other array to exchange the contents with @throw type_error.310 when JSON value is not an array; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how arrays can be swapped with `swap()`.,swap__array_t} @since version 1.0.0 */ void swap(array_t& other) { // swap only works for arrays if (JSON_LIKELY(is_array())) { std::swap(*(m_value.array), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON object with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other object to exchange the contents with @throw type_error.310 when JSON value is not an object; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how objects can be swapped with `swap()`.,swap__object_t} @since version 1.0.0 */ void swap(object_t& other) { // swap only works for objects if (JSON_LIKELY(is_object())) { std::swap(*(m_value.object), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON string with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other string to exchange the contents with @throw type_error.310 when JSON value is not a string; example: `"cannot use swap() with boolean"` @complexity Constant. @liveexample{The example below shows how strings can be swapped with `swap()`.,swap__string_t} @since version 1.0.0 */ void swap(string_t& other) { // swap only works for strings if (JSON_LIKELY(is_string())) { std::swap(*(m_value.string), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /// @} public: ////////////////////////////////////////// // lexicographical comparison operators // ////////////////////////////////////////// /// @name lexicographical comparison operators /// @{ /*! @brief comparison: equal Compares two JSON values for equality according to the following rules: - Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same according to their respective `operator==`. - Integer and floating-point numbers are automatically converted before comparison. Note than two NaN values are always treated as unequal. - Two JSON null values are equal. @note Floating-point inside JSON values numbers are compared with `json::number_float_t::operator==` which is `double::operator==` by default. To compare floating-point while respecting an epsilon, an alternative [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39) could be used, for instance @code {.cpp} template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type> inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept { return std::abs(a - b) <= epsilon; } @endcode @note NaN values never compare equal to themselves or to other NaN values. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are equal @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__equal} @since version 1.0.0 */ friend bool operator==(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return (*lhs.m_value.array == *rhs.m_value.array); case value_t::object: return (*lhs.m_value.object == *rhs.m_value.object); case value_t::null: return true; case value_t::string: return (*lhs.m_value.string == *rhs.m_value.string); case value_t::boolean: return (lhs.m_value.boolean == rhs.m_value.boolean); case value_t::number_integer: return (lhs.m_value.number_integer == rhs.m_value.number_integer); case value_t::number_unsigned: return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned); case value_t::number_float: return (lhs.m_value.number_float == rhs.m_value.number_float); default: return false; } } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) { return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float); } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) { return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer)); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) { return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float); } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) { return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned)); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) { return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer); } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) { return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned)); } return false; } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept { return (lhs == basic_json(rhs)); } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) == rhs); } /*! @brief comparison: not equal Compares two JSON values for inequality by calculating `not (lhs == rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are not equal @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__notequal} @since version 1.0.0 */ friend bool operator!=(const_reference lhs, const_reference rhs) noexcept { return not (lhs == rhs); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs != basic_json(rhs)); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) != rhs); } /*! @brief comparison: less than Compares whether one JSON value @a lhs is less than another JSON value @a rhs according to the following rules: - If @a lhs and @a rhs have the same type, the values are compared using the default `<` operator. - Integer and floating-point numbers are automatically converted before comparison - In case @a lhs and @a rhs have different types, the values are ignored and the order of the types is considered, see @ref operator<(const value_t, const value_t). @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__less} @since version 1.0.0 */ friend bool operator<(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return (*lhs.m_value.array) < (*rhs.m_value.array); case value_t::object: return *lhs.m_value.object < *rhs.m_value.object; case value_t::null: return false; case value_t::string: return *lhs.m_value.string < *rhs.m_value.string; case value_t::boolean: return lhs.m_value.boolean < rhs.m_value.boolean; case value_t::number_integer: return lhs.m_value.number_integer < rhs.m_value.number_integer; case value_t::number_unsigned: return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; case value_t::number_float: return lhs.m_value.number_float < rhs.m_value.number_float; default: return false; } } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) { return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; } // We only reach this line if we cannot compare values. In that case, // we compare types. Note we have to call the operator explicitly, // because MSVC has problems otherwise. return operator<(lhs_type, rhs_type); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept { return (lhs < basic_json(rhs)); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) < rhs); } /*! @brief comparison: less than or equal Compares whether one JSON value @a lhs is less than or equal to another JSON value by calculating `not (rhs < lhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greater} @since version 1.0.0 */ friend bool operator<=(const_reference lhs, const_reference rhs) noexcept { return not (rhs < lhs); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs <= basic_json(rhs)); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) <= rhs); } /*! @brief comparison: greater than Compares whether one JSON value @a lhs is greater than another JSON value by calculating `not (lhs <= rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__lessequal} @since version 1.0.0 */ friend bool operator>(const_reference lhs, const_reference rhs) noexcept { return not (lhs <= rhs); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept { return (lhs > basic_json(rhs)); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) > rhs); } /*! @brief comparison: greater than or equal Compares whether one JSON value @a lhs is greater than or equal to another JSON value by calculating `not (lhs < rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greaterequal} @since version 1.0.0 */ friend bool operator>=(const_reference lhs, const_reference rhs) noexcept { return not (lhs < rhs); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs >= basic_json(rhs)); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) >= rhs); } /// @} /////////////////// // serialization // /////////////////// /// @name serialization /// @{ /*! @brief serialize to stream Serialize the given JSON value @a j to the output stream @a o. The JSON value will be serialized using the @ref dump member function. - The indentation of the output can be controlled with the member variable `width` of the output stream @a o. For instance, using the manipulator `std::setw(4)` on @a o sets the indentation level to `4` and the serialization result is the same as calling `dump(4)`. - The indentation characrer can be controlled with the member variable `fill` of the output stream @a o. For instance, the manipulator `std::setfill('\\t')` sets indentation to use a tab character rather than the default space character. @param[in,out] o stream to serialize to @param[in] j JSON value to serialize @return the stream @a o @complexity Linear. @liveexample{The example below shows the serialization with different parameters to `width` to adjust the indentation level.,operator_serialize} @since version 1.0.0; indentaction character added in version 3.0.0 */ friend std::ostream& operator<<(std::ostream& o, const basic_json& j) { // read width member and use it as indentation parameter if nonzero const bool pretty_print = (o.width() > 0); const auto indentation = (pretty_print ? o.width() : 0); // reset width to 0 for subsequent calls to this stream o.width(0); // do the actual serialization serializer s(detail::output_adapter<char>(o), o.fill()); s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation)); return o; } /*! @brief serialize to stream @deprecated This stream operator is deprecated and will be removed in a future version of the library. Please use @ref operator<<(std::ostream&, const basic_json&) instead; that is, replace calls like `j >> o;` with `o << j;`. @since version 1.0.0; deprecated since version 3.0.0 */ JSON_DEPRECATED friend std::ostream& operator>>(const basic_json& j, std::ostream& o) { return o << j; } /// @} ///////////////////// // deserialization // ///////////////////// /// @name deserialization /// @{ /*! @brief deserialize from a compatible input This function reads from a compatible input. Examples are: - an array of 1-byte values - strings with character/literal type with size of 1 byte - input streams - container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, `std::valarray`, and `std::initializer_list`. Furthermore, C-style arrays can be used with `std::begin()`/`std::end()`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @pre The container storage is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with a noncompliant container and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @param[in] i input to read from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an array.,parse__array__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__string__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__istream__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function reading from a contiguous container.,parse__contiguouscontainer__parser_callback_t} @since version 2.0.3 (contiguous containers) */ static basic_json parse(detail::input_adapter i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true) { basic_json result; parser(i, cb, allow_exceptions).parse(true, result); return result; } /*! @copydoc basic_json parse(detail::input_adapter, const parser_callback_t) */ static basic_json parse(detail::input_adapter& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true) { basic_json result; parser(i, cb, allow_exceptions).parse(true, result); return result; } static bool accept(detail::input_adapter i) { return parser(i).accept(true); } static bool accept(detail::input_adapter& i) { return parser(i).accept(true); } /*! @brief deserialize from an iterator range with contiguous storage This function reads from an iterator range of a container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, `std::valarray`, and `std::initializer_list`. Furthermore, C-style arrays can be used with `std::begin()`/`std::end()`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre The iterator range is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element in the range has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with noncompliant iterators and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @tparam IteratorType iterator of container with contiguous storage @param[in] first begin of the range to parse (included) @param[in] last end of the range to parse (excluded) @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an iterator range.,parse__iteratortype__parser_callback_t} @since version 2.0.3 */ template<class IteratorType, typename std::enable_if< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> static basic_json parse(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr, const bool allow_exceptions = true) { basic_json result; parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result); return result; } template<class IteratorType, typename std::enable_if< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> static bool accept(IteratorType first, IteratorType last) { return parser(detail::input_adapter(first, last)).accept(true); } /*! @brief deserialize from stream @deprecated This stream operator is deprecated and will be removed in a future version of the library. Please use @ref operator>>(std::istream&, basic_json&) instead; that is, replace calls like `j << i;` with `i >> j;`. @since version 1.0.0; deprecated since version 3.0.0 */ JSON_DEPRECATED friend std::istream& operator<<(basic_json& j, std::istream& i) { return operator>>(i, j); } /*! @brief deserialize from stream Deserializes an input stream to a JSON value. @param[in,out] i input stream to read a serialized JSON value from @param[in,out] j JSON value to write the deserialized input to @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below shows how a JSON value is constructed by reading a serialization from a stream.,operator_deserialize} @sa parse(std::istream&, const parser_callback_t) for a variant with a parser callback function to filter values while parsing @since version 1.0.0 */ friend std::istream& operator>>(std::istream& i, basic_json& j) { parser(detail::input_adapter(i)).parse(false, j); return i; } /// @} /////////////////////////// // convenience functions // /////////////////////////// /*! @brief return the type as string Returns the type name as string to be used in error messages - usually to indicate that a function was called on a wrong JSON type. @return a string representation of a the @a m_type member: Value type | return value ----------- | ------------- null | `"null"` boolean | `"boolean"` string | `"string"` number | `"number"` (for all number types) object | `"object"` array | `"array"` discarded | `"discarded"` @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Constant. @liveexample{The following code exemplifies `type_name()` for all JSON types.,type_name} @sa @ref type() -- return the type of the JSON value @sa @ref operator value_t() -- return the type of the JSON value (implicit) @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` since 3.0.0 */ const char* type_name() const noexcept { { switch (m_type) { case value_t::null: return "null"; case value_t::object: return "object"; case value_t::array: return "array"; case value_t::string: return "string"; case value_t::boolean: return "boolean"; case value_t::discarded: return "discarded"; default: return "number"; } } } private: ////////////////////// // member variables // ////////////////////// /// the type of the current element value_t m_type = value_t::null; /// the value of the current element json_value m_value = {}; ////////////////////////////////////////// // binary serialization/deserialization // ////////////////////////////////////////// /// @name binary serialization/deserialization support /// @{ public: /*! @brief create a CBOR serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049): JSON value type | value/range | CBOR type | first byte --------------- | ------------------------------------------ | ---------------------------------- | --------------- null | `null` | Null | 0xf6 boolean | `true` | True | 0xf5 boolean | `false` | False | 0xf4 number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3b number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3a number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 number_integer | -24..-1 | Negative integer | 0x20..0x37 number_integer | 0..23 | Integer | 0x00..0x17 number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b number_unsigned | 0..23 | Integer | 0x00..0x17 number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b number_float | *any value* | Double-Precision Float | 0xfb string | *length*: 0..23 | UTF-8 string | 0x60..0x77 string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7a string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7b array | *size*: 0..23 | array | 0x80..0x97 array | *size*: 23..255 | array (1 byte follow) | 0x98 array | *size*: 256..65535 | array (2 bytes follow) | 0x99 array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9a array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9b object | *size*: 0..23 | map | 0xa0..0xb7 object | *size*: 23..255 | map (1 byte follow) | 0xb8 object | *size*: 256..65535 | map (2 bytes follow) | 0xb9 object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xba object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xbb @note The mapping is **complete** in the sense that any JSON value type can be converted to a CBOR value. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @note The following CBOR types are not used in the conversion: - byte strings (0x40..0x5f) - UTF-8 strings terminated by "break" (0x7f) - arrays terminated by "break" (0x9f) - maps terminated by "break" (0xbf) - date/time (0xc0..0xc1) - bignum (0xc2..0xc3) - decimal fraction (0xc4) - bigfloat (0xc5) - tagged items (0xc6..0xd4, 0xd8..0xdb) - expected conversions (0xd5..0xd7) - simple values (0xe0..0xf3, 0xf8) - undefined (0xf7) - half and single-precision floats (0xf9-0xfa) - break (0xff) @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in CBOR format.,to_cbor} @sa http://cbor.io @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the analogous deserialization @sa @ref to_msgpack(const basic_json&) for the related MessagePack format @since version 2.0.9 */ static std::vector<uint8_t> to_cbor(const basic_json& j) { std::vector<uint8_t> result; to_cbor(j, result); return result; } static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_cbor(j); } static void to_cbor(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_cbor(j); } /*! @brief create a MessagePack serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type | value/range | MessagePack type | first byte --------------- | --------------------------------- | ---------------- | ---------- null | `null` | nil | 0xc0 boolean | `true` | true | 0xc3 boolean | `false` | false | 0xc2 number_integer | -9223372036854775808..-2147483649 | int64 | 0xd3 number_integer | -2147483648..-32769 | int32 | 0xd2 number_integer | -32768..-129 | int16 | 0xd1 number_integer | -128..-33 | int8 | 0xd0 number_integer | -32..-1 | negative fixint | 0xe0..0xff number_integer | 0..127 | positive fixint | 0x00..0x7f number_integer | 128..255 | uint 8 | 0xcc number_integer | 256..65535 | uint 16 | 0xcd number_integer | 65536..4294967295 | uint 32 | 0xce number_integer | 4294967296..18446744073709551615 | uint 64 | 0xcf number_unsigned | 0..127 | positive fixint | 0x00..0x7f number_unsigned | 128..255 | uint 8 | 0xcc number_unsigned | 256..65535 | uint 16 | 0xcd number_unsigned | 65536..4294967295 | uint 32 | 0xce number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xcf number_float | *any value* | float 64 | 0xcb string | *length*: 0..31 | fixstr | 0xa0..0xbf string | *length*: 32..255 | str 8 | 0xd9 string | *length*: 256..65535 | str 16 | 0xda string | *length*: 65536..4294967295 | str 32 | 0xdb array | *size*: 0..15 | fixarray | 0x90..0x9f array | *size*: 16..65535 | array 16 | 0xdc array | *size*: 65536..4294967295 | array 32 | 0xdd object | *size*: 0..15 | fix map | 0x80..0x8f object | *size*: 16..65535 | map 16 | 0xde object | *size*: 65536..4294967295 | map 32 | 0xdf @note The mapping is **complete** in the sense that any JSON value type can be converted to a MessagePack value. @note The following values can **not** be converted to a MessagePack value: - strings with more than 4294967295 bytes - arrays with more than 4294967295 elements - objects with more than 4294967295 elements @note The following MessagePack types are not used in the conversion: - bin 8 - bin 32 (0xc4..0xc6) - ext 8 - ext 32 (0xc7..0xc9) - float 32 (0xca) - fixext 1 - fixext 16 (0xd4..0xd8) @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in MessagePack format.,to_msgpack} @sa http://msgpack.org @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the analogous deserialization @sa @ref to_cbor(const basic_json& for the related CBOR format @since version 2.0.9 */ static std::vector<uint8_t> to_msgpack(const basic_json& j) { std::vector<uint8_t> result; to_msgpack(j, result); return result; } static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_msgpack(j); } static void to_msgpack(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_msgpack(j); } /*! @brief create a JSON value from an input in CBOR format Deserializes a given input @a i to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. The library maps CBOR types to JSON value types as follows: CBOR type | JSON value type | first byte ---------------------- | --------------- | ---------- Integer | number_unsigned | 0x00..0x17 Unsigned integer | number_unsigned | 0x18 Unsigned integer | number_unsigned | 0x19 Unsigned integer | number_unsigned | 0x1a Unsigned integer | number_unsigned | 0x1b Negative integer | number_integer | 0x20..0x37 Negative integer | number_integer | 0x38 Negative integer | number_integer | 0x39 Negative integer | number_integer | 0x3a Negative integer | number_integer | 0x3b Negative integer | number_integer | 0x40..0x57 UTF-8 string | string | 0x60..0x77 UTF-8 string | string | 0x78 UTF-8 string | string | 0x79 UTF-8 string | string | 0x7a UTF-8 string | string | 0x7b UTF-8 string | string | 0x7f array | array | 0x80..0x97 array | array | 0x98 array | array | 0x99 array | array | 0x9a array | array | 0x9b array | array | 0x9f map | object | 0xa0..0xb7 map | object | 0xb8 map | object | 0xb9 map | object | 0xba map | object | 0xbb map | object | 0xbf False | `false` | 0xf4 True | `true` | 0xf5 Nill | `null` | 0xf6 Half-Precision Float | number_float | 0xf9 Single-Precision Float | number_float | 0xfa Double-Precision Float | number_float | 0xfb @warning The mapping is **incomplete** in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors (parse_error.112): - byte strings (0x40..0x5f) - date/time (0xc0..0xc1) - bignum (0xc2..0xc3) - decimal fraction (0xc4) - bigfloat (0xc5) - tagged items (0xc6..0xd4, 0xd8..0xdb) - expected conversions (0xd5..0xd7) - simple values (0xe0..0xf3, 0xf8) - undefined (0xf7) @warning CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected (parse_error.113). @note Any CBOR output created @ref to_cbor can be successfully parsed by @ref from_cbor. @param[in] i an input in CBOR format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @return deserialized JSON value @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from CBOR were used in the given input @a v or if the input is not valid CBOR @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in CBOR format to a JSON value.,from_cbor} @sa http://cbor.io @sa @ref to_cbor(const basic_json&) for the analogous serialization @sa @ref from_msgpack(detail::input_adapter, const bool) for the related MessagePack format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0 */ static basic_json from_cbor(detail::input_adapter i, const bool strict = true) { return binary_reader(i).parse_cbor(strict); } /*! @copydoc from_cbor(detail::input_adapter, const bool) */ template<typename A1, typename A2, detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true) { return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict); } /*! @brief create a JSON value from an input in MessagePack format Deserializes a given input @a i to a JSON value using the MessagePack serialization format. The library maps MessagePack types to JSON value types as follows: MessagePack type | JSON value type | first byte ---------------- | --------------- | ---------- positive fixint | number_unsigned | 0x00..0x7f fixmap | object | 0x80..0x8f fixarray | array | 0x90..0x9f fixstr | string | 0xa0..0xbf nil | `null` | 0xc0 false | `false` | 0xc2 true | `true` | 0xc3 float 32 | number_float | 0xca float 64 | number_float | 0xcb uint 8 | number_unsigned | 0xcc uint 16 | number_unsigned | 0xcd uint 32 | number_unsigned | 0xce uint 64 | number_unsigned | 0xcf int 8 | number_integer | 0xd0 int 16 | number_integer | 0xd1 int 32 | number_integer | 0xd2 int 64 | number_integer | 0xd3 str 8 | string | 0xd9 str 16 | string | 0xda str 32 | string | 0xdb array 16 | array | 0xdc array 32 | array | 0xdd map 16 | object | 0xde map 32 | object | 0xdf negative fixint | number_integer | 0xe0-0xff @warning The mapping is **incomplete** in the sense that not all MessagePack types can be converted to a JSON value. The following MessagePack types are not supported and will yield parse errors: - bin 8 - bin 32 (0xc4..0xc6) - ext 8 - ext 32 (0xc7..0xc9) - fixext 1 - fixext 16 (0xd4..0xd8) @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @param[in] i an input in MessagePack format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from MessagePack were used in the given input @a i or if the input is not valid MessagePack @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in MessagePack format to a JSON value.,from_msgpack} @sa http://msgpack.org @sa @ref to_msgpack(const basic_json&) for the analogous serialization @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0 */ static basic_json from_msgpack(detail::input_adapter i, const bool strict = true) { return binary_reader(i).parse_msgpack(strict); } /*! @copydoc from_msgpack(detail::input_adapter, const bool) */ template<typename A1, typename A2, detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true) { return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict); } /// @} ////////////////////////// // JSON Pointer support // ////////////////////////// /// @name JSON Pointer functions /// @{ /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. Similar to @ref operator[](const typename object_t::key_type&), `null` values are created in arrays and objects if necessary. In particular: - If the JSON pointer points to an object key that does not exist, it is created an filled with a `null` value before a reference to it is returned. - If the JSON pointer points to an array index that does not exist, it is created an filled with a `null` value before a reference to it is returned. All indices between the current maximum and the given index are also filled with `null`. - The special value `-` is treated as a synonym for the index past the end. @param[in] ptr a JSON pointer @return reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer} @since version 2.0.0 */ reference operator[](const json_pointer& ptr) { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. The function does not change the JSON value; no `null` values are created. In particular, the the special value `-` yields an exception. @param[in] ptr JSON pointer to the desired element @return const reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} @since version 2.0.0 */ const_reference operator[](const json_pointer& ptr) const { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Returns a reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer} */ reference at(const json_pointer& ptr) { return ptr.get_checked(this); } /*! @brief access specified element via JSON Pointer Returns a const reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer_const} */ const_reference at(const json_pointer& ptr) const { return ptr.get_checked(this); } /*! @brief return flattened JSON value The function creates a JSON object whose keys are JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all primitive. The original JSON value can be restored using the @ref unflatten() function. @return an object that maps JSON pointers to primitive values @note Empty objects and arrays are flattened to `null` and will not be reconstructed correctly by the @ref unflatten() function. @complexity Linear in the size the JSON value. @liveexample{The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.,flatten} @sa @ref unflatten() for the reverse function @since version 2.0.0 */ basic_json flatten() const { basic_json result(value_t::object); json_pointer::flatten("", *this, result); return result; } /*! @brief unflatten a previously flattened JSON value The function restores the arbitrary nesting of a JSON value that has been flattened before using the @ref flatten() function. The JSON value must meet certain constraints: 1. The value must be an object. 2. The keys must be JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) 3. The mapped values must be primitive JSON types. @return the original JSON from a flattened version @note Empty objects and arrays are flattened by @ref flatten() to `null` values and can not unflattened to their original type. Apart from this example, for a JSON value `j`, the following is always true: `j == j.flatten().unflatten()`. @complexity Linear in the size the JSON value. @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @liveexample{The following code shows how a flattened JSON object is unflattened into the original nested JSON object.,unflatten} @sa @ref flatten() for the reverse function @since version 2.0.0 */ basic_json unflatten() const { return json_pointer::unflatten(*this); } /// @} ////////////////////////// // JSON Patch functions // ////////////////////////// /// @name JSON Patch functions /// @{ /*! @brief applies a JSON patch [JSON Patch](http://jsonpatch.com) defines a JSON document structure for expressing a sequence of operations to apply to a JSON) document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. @param[in] json_patch JSON patch document @return patched document @note The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value. @throw parse_error.104 if the JSON patch does not consist of an array of objects @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: `"operation add must have member path"` @throw out_of_range.401 if an array index is out of range. @throw out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: `"key baz not found"` @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", "move") @throw other_error.501 if "test" operation was unsuccessful @complexity Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected. @liveexample{The following code shows how a JSON patch is applied to a value.,patch} @sa @ref diff -- create a JSON patch by comparing two JSON values @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ basic_json patch(const basic_json& json_patch) const { // make a working copy to apply the patch to basic_json result = *this; // the valid JSON Patch operations enum class patch_operations {add, remove, replace, move, copy, test, invalid}; const auto get_op = [](const std::string & op) { if (op == "add") { return patch_operations::add; } if (op == "remove") { return patch_operations::remove; } if (op == "replace") { return patch_operations::replace; } if (op == "move") { return patch_operations::move; } if (op == "copy") { return patch_operations::copy; } if (op == "test") { return patch_operations::test; } return patch_operations::invalid; }; // wrapper for "add" operation; add value at ptr const auto operation_add = [&result](json_pointer & ptr, basic_json val) { // adding to the root of the target document means replacing it if (ptr.is_root()) { result = val; } else { // make sure the top element of the pointer exists json_pointer top_pointer = ptr.top(); if (top_pointer != ptr) { result.at(top_pointer); } // get reference to parent of JSON pointer ptr const auto last_path = ptr.pop_back(); basic_json& parent = result[ptr]; switch (parent.m_type) { case value_t::null: case value_t::object: { // use operator[] to add value parent[last_path] = val; break; } case value_t::array: { if (last_path == "-") { // special case: append to back parent.push_back(val); } else { const auto idx = std::stoi(last_path); if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size())) { // avoid undefined behavior JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } else { // default case: insert add offset parent.insert(parent.begin() + static_cast<difference_type>(idx), val); } } break; } default: { // if there exists a parent it cannot be primitive assert(false); // LCOV_EXCL_LINE } } } }; // wrapper for "remove" operation; remove value at ptr const auto operation_remove = [&result](json_pointer & ptr) { // get reference to parent of JSON pointer ptr const auto last_path = ptr.pop_back(); basic_json& parent = result.at(ptr); // remove child if (parent.is_object()) { // perform range check auto it = parent.find(last_path); if (JSON_LIKELY(it != parent.end())) { parent.erase(it); } else { JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found")); } } else if (parent.is_array()) { // note erase performs range check parent.erase(static_cast<size_type>(std::stoi(last_path))); } }; // type check: top level value must be an array if (JSON_UNLIKELY(not json_patch.is_array())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); } // iterate and apply the operations for (const auto& val : json_patch) { // wrapper to get a value for an operation const auto get_value = [&val](const std::string & op, const std::string & member, bool string_type) -> basic_json& { // find value auto it = val.m_value.object->find(member); // context-sensitive error message const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; // check if desired value is present if (JSON_UNLIKELY(it == val.m_value.object->end())) { JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'")); } // check if result is of type string if (JSON_UNLIKELY(string_type and not it->second.is_string())) { JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'")); } // no error: return value return it->second; }; // type check: every element of the array must be an object if (JSON_UNLIKELY(not val.is_object())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); } // collect mandatory members const std::string op = get_value("op", "op", true); const std::string path = get_value(op, "path", true); json_pointer ptr(path); switch (get_op(op)) { case patch_operations::add: { operation_add(ptr, get_value("add", "value", false)); break; } case patch_operations::remove: { operation_remove(ptr); break; } case patch_operations::replace: { // the "path" location must exist - use at() result.at(ptr) = get_value("replace", "value", false); break; } case patch_operations::move: { const std::string from_path = get_value("move", "from", true); json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The move operation is functionally identical to a // "remove" operation on the "from" location, followed // immediately by an "add" operation at the target // location with the value that was just removed. operation_remove(from_ptr); operation_add(ptr, v); break; } case patch_operations::copy: { const std::string from_path = get_value("copy", "from", true); const json_pointer from_ptr(from_path); // the "from" location must exist - use at() result[ptr] = result.at(from_ptr); break; } case patch_operations::test: { bool success = false; JSON_TRY { // check if "value" matches the one at "path" // the "path" location must exist - use at() success = (result.at(ptr) == get_value("test", "value", false)); } JSON_CATCH (out_of_range&) { // ignore out of range errors: success remains false } // throw an exception if test fails if (JSON_UNLIKELY(not success)) { JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump())); } break; } case patch_operations::invalid: { // op must be "add", "remove", "replace", "move", "copy", or // "test" JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid")); } } } return result; } /*! @brief creates a diff as a JSON patch Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can be changed into the value @a target by calling @ref patch function. @invariant For two JSON values @a source and @a target, the following code yields always `true`: @code {.cpp} source.patch(diff(source, target)) == target; @endcode @note Currently, only `remove`, `add`, and `replace` operations are generated. @param[in] source JSON value to compare from @param[in] target JSON value to compare against @param[in] path helper value to create JSON pointers @return a JSON patch to convert the @a source to @a target @complexity Linear in the lengths of @a source and @a target. @liveexample{The following code shows how a JSON patch is created as a diff for two JSON values.,diff} @sa @ref patch -- apply a JSON patch @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @since version 2.0.0 */ static basic_json diff(const basic_json& source, const basic_json& target, const std::string& path = "") { // the patch basic_json result(value_t::array); // if the values are the same, return empty patch if (source == target) { return result; } if (source.type() != target.type()) { // different types: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); } else { switch (source.type()) { case value_t::array: { // first pass: traverse common elements std::size_t i = 0; while (i < source.size() and i < target.size()) { // recursive call to compare array values at index i auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); ++i; } // i now reached the end of at least one array // in a second pass, traverse the remaining elements // remove my remaining elements const auto end_index = static_cast<difference_type>(result.size()); while (i < source.size()) { // add operations in reverse order to avoid invalid // indices result.insert(result.begin() + end_index, object( { {"op", "remove"}, {"path", path + "/" + std::to_string(i)} })); ++i; } // add other remaining elements while (i < target.size()) { result.push_back( { {"op", "add"}, {"path", path + "/" + std::to_string(i)}, {"value", target[i]} }); ++i; } break; } case value_t::object: { // first pass: traverse this object's elements for (auto it = source.begin(); it != source.end(); ++it) { // escape the key name to be used in a JSON patch const auto key = json_pointer::escape(it.key()); if (target.find(it.key()) != target.end()) { // recursive call to compare object values at key it auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); } else { // found a key that is not in o -> remove it result.push_back(object( { {"op", "remove"}, {"path", path + "/" + key} })); } } // second pass: traverse other object's elements for (auto it = target.begin(); it != target.end(); ++it) { if (source.find(it.key()) == source.end()) { // found a key that is not in this -> add it const auto key = json_pointer::escape(it.key()); result.push_back( { {"op", "add"}, {"path", path + "/" + key}, {"value", it.value()} }); } } break; } default: { // both primitive type: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); break; } } } return result; } /// @} }; ///////////// // presets // ///////////// /*! @brief default JSON class This type is the default specialization of the @ref basic_json class which uses the standard template types. @since version 1.0.0 */ using json = basic_json<>; ////////////////// // json_pointer // ////////////////// NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& json_pointer::get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; auto result = &j; // in case no reference tokens exist, return a reference to the JSON value // j which will be overwritten by a primitive value for (const auto& reference_token : reference_tokens) { switch (result->m_type) { case detail::value_t::null: { if (reference_token == "0") { // start a new array if reference token is 0 result = &result->operator[](0); } else { // start a new object otherwise result = &result->operator[](reference_token); } break; } case detail::value_t::object: { // create an entry in the object result = &result->operator[](reference_token); break; } case detail::value_t::array: { // create an entry in the array JSON_TRY { result = &result->operator[](static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } /* The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as single value; that is, with an empty list of reference tokens. */ default: JSON_THROW(detail::type_error::create(313, "invalid value to unflatten")); } } return *result; } NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& json_pointer::get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; for (const auto& reference_token : reference_tokens) { // convert null values to arrays or objects before continuing if (ptr->m_type == detail::value_t::null) { // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const char x) { return (x >= '0' and x <= '9'); }); // change value to array for numbers or "-" or to object otherwise *ptr = (nums or reference_token == "-") ? detail::value_t::array : detail::value_t::object; } switch (ptr->m_type) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } if (reference_token == "-") { // explicitly treat "-" as index beyond the end ptr = &ptr->operator[](ptr->m_value.array->size()); } else { // convert array index to number; unchecked access JSON_TRY { ptr = &ptr->operator[]( static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& json_pointer::get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // note: at performs range check JSON_TRY { ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } NLOHMANN_BASIC_JSON_TPL_DECLARATION const NLOHMANN_BASIC_JSON_TPL& json_pointer::get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" cannot be used for const access JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // use unchecked array access JSON_TRY { ptr = &ptr->operator[]( static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } NLOHMANN_BASIC_JSON_TPL_DECLARATION const NLOHMANN_BASIC_JSON_TPL& json_pointer::get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // note: at performs range check JSON_TRY { ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } NLOHMANN_BASIC_JSON_TPL_DECLARATION void json_pointer::flatten(const std::string& reference_string, const NLOHMANN_BASIC_JSON_TPL& value, NLOHMANN_BASIC_JSON_TPL& result) { switch (value.m_type) { case detail::value_t::array: { if (value.m_value.array->empty()) { // flatten empty array as null result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_value.array->size(); ++i) { flatten(reference_string + "/" + std::to_string(i), value.m_value.array->operator[](i), result); } } break; } case detail::value_t::object: { if (value.m_value.object->empty()) { // flatten empty object as null result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_value.object) { flatten(reference_string + "/" + escape(element.first), element.second, result); } } break; } default: { // add primitive value with its reference string result[reference_string] = value; break; } } } NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL json_pointer::unflatten(const NLOHMANN_BASIC_JSON_TPL& value) { if (JSON_UNLIKELY(not value.is_object())) { JSON_THROW(detail::type_error::create(314, "only objects can be unflattened")); } NLOHMANN_BASIC_JSON_TPL result; // iterate the JSON object values for (const auto& element : *value.m_value.object) { if (JSON_UNLIKELY(not element.second.is_primitive())) { JSON_THROW(detail::type_error::create(315, "values in object must be primitive")); } // assign value to reference pointed to by JSON pointer; Note that if // the JSON pointer is "" (i.e., points to the whole value), function // get_and_create returns a reference to result itself. An assignment // will then create a primitive value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } inline bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept { return (lhs.reference_tokens == rhs.reference_tokens); } inline bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept { return not (lhs == rhs); } } // namespace nlohmann /////////////////////// // nonmember support // /////////////////////// // specialization of std::swap, and std::hash namespace std { /*! @brief exchanges the values of two JSON objects @since version 1.0.0 */ template<> inline void swap(nlohmann::json& j1, nlohmann::json& j2) noexcept( is_nothrow_move_constructible<nlohmann::json>::value and is_nothrow_move_assignable<nlohmann::json>::value ) { j1.swap(j2); } /// hash value for JSON objects template<> struct hash<nlohmann::json> { /*! @brief return a hash value for a JSON object @since version 1.0.0 */ std::size_t operator()(const nlohmann::json& j) const { // a naive hashing via the string representation const auto& h = hash<nlohmann::json::string_t>(); return h(j.dump()); } }; /// specialization for std::less<value_t> /// @note: do not remove the space after '<', /// see https://github.com/nlohmann/json/pull/679 template<> struct less< ::nlohmann::detail::value_t> { /*! @brief compare two value_t enum values @since version 3.0.0 */ bool operator()(nlohmann::detail::value_t lhs, nlohmann::detail::value_t rhs) const noexcept { return nlohmann::detail::operator<(lhs, rhs); } }; } // namespace std /*! @brief user-defined string literal for JSON values This operator implements a user-defined string literal for JSON objects. It can be used by adding `"_json"` to a string literal and returns a JSON object if no parse error occurred. @param[in] s a string representation of a JSON object @param[in] n the length of string @a s @return a JSON object @since version 1.0.0 */ inline nlohmann::json operator "" _json(const char* s, std::size_t n) { return nlohmann::json::parse(s, s + n); } /*! @brief user-defined string literal for JSON pointer This operator implements a user-defined string literal for JSON Pointers. It can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer object if no parse error occurred. @param[in] s a string representation of a JSON Pointer @param[in] n the length of string @a s @return a JSON pointer object @since version 2.0.0 */ inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) { return nlohmann::json::json_pointer(std::string(s, n)); } // restore GCC/clang diagnostic settings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma GCC diagnostic pop #endif // clean up #undef JSON_CATCH #undef JSON_THROW #undef JSON_TRY #undef JSON_LIKELY #undef JSON_UNLIKELY #undef JSON_DEPRECATED #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION #undef NLOHMANN_BASIC_JSON_TPL #endif
[ "rafael.madureira.santos@gmail.com" ]
rafael.madureira.santos@gmail.com
364e14a489b3e887bf614e56bbe1283e700a1ec9
0500d134989e73782ad8c7f6d7e2873b3b3e8216
/cpp_d10_2019/ex01/AWeapon.cpp
be2dc131c1d1fbd0ce5f4873645fcf6dab675f8d
[]
no_license
alexis-riot/CPPool-Epitech
1d98a7b63eef9316b6de1ff54b6ee1a239df8c0d
956b84e26bebce2ec8c556b63ccd8579c1caac1b
refs/heads/master
2021-02-15T11:33:50.481050
2020-03-04T12:29:38
2020-03-04T12:29:38
244,894,656
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
/* ** EPITECH PROJECT, 2020 ** cpp_d10_2019 ** File description: ** AWeapon.cpp */ #include "AWeapon.hpp" AWeapon::AWeapon(const std::string &name, int apcost, int damage) : name(std::move(name)), apcost(apcost), damage(damage) { } AWeapon::~AWeapon() {} int AWeapon::getAPCost() const { return this->apcost; } int AWeapon::getDamage() const { return this->damage; } const std::string AWeapon::getName() const { return this->name; }
[ "riotalexis35@gmail.com" ]
riotalexis35@gmail.com
93a1b570fc95f981d47bffc4ba72fb9b3d3c57a8
88f3fe8a0fd64a36f4bba69aa8fd8e41a6feea64
/src/util/string/StrUtils.h
09ab1cc6fb69ac28d077b0bb999f240bab8d9a9b
[]
no_license
AltropInc/alt
0fa30bd2e5194d0b0e4832f8dce89177c4c00b62
831fc4e19d74364da03ba02cf9ac643afc0adaa3
refs/heads/master
2023-09-04T18:52:38.873358
2023-09-03T13:17:33
2023-09-03T13:17:33
249,748,618
0
0
null
null
null
null
UTF-8
C++
false
false
16,099
h
#pragma once //************************************************************************** // Copyright (c) 2020-present, Altrop Software Inc. and Contributors. // SPDX-License-Identifier: BSL-1.0 //************************************************************************** /** * @file StrUtils.h * @library alt_util * @brief string utility function */ #include "StrBuffer.h" #include <util/system/Platform.h> #include <util/numeric/Intrinsics.h> // for clz #include <stddef.h> #include <stdint.h> #include <type_traits> #include <string> #include <cstring> #include <vector> #include <ctype.h> //---------------------------------------------------------------------------- // string utils //---------------------------------------------------------------------------- namespace alt { template <int N> ALT_INLINE void strCpy (char* d, const char* s) { std::strncpy(d, s, N); } template <> ALT_INLINE void strCpy<1> (char* d, const char* s) { *d=*s; } template <> ALT_INLINE void strCpy<2> (char* d, const char* s) { *((int16_t*)d)=*((int16_t*)s); } template <> ALT_INLINE void strCpy<3> (char* d, const char* s) { strCpy<2>(d+4,s+4); *(d+4)=*(s+4); } template <> ALT_INLINE void strCpy<4> (char* d, const char* s) { *((int32_t*)d)=*((int32_t*)s); } template <> ALT_INLINE void strCpy<5> (char* d, const char* s) { strCpy<4>(d,s); *(d+4)=*(s+4); } template <> ALT_INLINE void strCpy<6> (char* d, const char* s) { strCpy<4>(d,s); strCpy<2>(d+4,s+4); } template <> ALT_INLINE void strCpy<7> (char* d, const char* s) { strCpy<4>(d,s); strCpy<3>(d+4,s+4); } template <> ALT_INLINE void strCpy<8> (char* d, const char* s) { *((int64_t*)d)=*((int64_t*)s); } template <> ALT_INLINE void strCpy<9> (char* d, const char* s) { strCpy<8>(d,s); *(d+8)=*(s+8); } template <> ALT_INLINE void strCpy<10> (char* d, const char* s) { strCpy<8>(d,s); strCpy<2>(d+8,s+8); } template <> ALT_INLINE void strCpy<11> (char* d, const char* s) { strCpy<8>(d,s); strCpy<3>(d+8,s+8); } template <> ALT_INLINE void strCpy<12> (char* d, const char* s) { strCpy<8>(d,s); strCpy<4>(d+8,s+8); } template <> ALT_INLINE void strCpy<13> (char* d, const char* s) { strCpy<8>(d,s); strCpy<5>(d+8,s+8); } template <> ALT_INLINE void strCpy<14> (char* d, const char* s) { strCpy<8>(d,s); strCpy<6>(d+8,s+8); } template <> ALT_INLINE void strCpy<15> (char* d, const char* s) { strCpy<8>(d,s); strCpy<7>(d+8,s+8); } template <> ALT_INLINE void strCpy<16> (char* d, const char* s) { strCpy<8>(d,s); strCpy<8>(d+8,s+8); } ALT_INLINE bool str2Equal (const char* x, const char* y) { return *((int16_t*)x)==*((int16_t*)y); } ALT_INLINE bool str3Equal (const char* x, const char* y) { return str2Equal(x,y) && *(x+2)==*(y+2); } ALT_INLINE bool str4Equal (const char* x, const char* y) { return *((int32_t*)x)==*((int32_t*)y); } ALT_INLINE bool str5Equal (const char* x, const char* y) { return str4Equal(x,y) && *(x+2)==*(y+2); } ALT_INLINE bool str6Equal (const char* x, const char* y) { return str4Equal(x,y) && str2Equal(x+4,y+4); } ALT_INLINE bool str7Equal (const char* x, const char* y) { return str4Equal(x,y) && str3Equal(x+4,y+4); } ALT_INLINE bool str8Equal (const char* x, const char* y) { return *((int64_t*)x)==*((int64_t*)y); } ALT_INLINE bool str9Equal (const char* x, const char* y) { return str8Equal(x,y) && *(x+8)==*(y+8); } ALT_INLINE bool str10Equal (const char* x, const char* y) { return str8Equal(x,y) && str2Equal(x+8,y+8); } template<int N> ALT_INLINE bool strEqual (const char* x, const char* y) { return std::strncmp(x,y,N)==0; } template<> ALT_INLINE bool strEqual<1> (const char* x, const char* y) { return *x==*y; } template<> ALT_INLINE bool strEqual<2> (const char* x, const char* y) { return *((int16_t*)x)==*((int16_t*)y); } template<> ALT_INLINE bool strEqual<3> (const char* x, const char* y) { return str2Equal(x,y) && *(x+2)==*(y+2); } template<> ALT_INLINE bool strEqual<4> (const char* x, const char* y) { return *((int32_t*)x)==*((int32_t*)y); } template<> ALT_INLINE bool strEqual<5> (const char* x, const char* y) { return str4Equal(x,y) && *(x+2)==*(y+2); } template<> ALT_INLINE bool strEqual<6> (const char* x, const char* y) { return str4Equal(x,y) && str2Equal(x+4,y+4); } template<> ALT_INLINE bool strEqual<7> (const char* x, const char* y) { return str4Equal(x,y) && str3Equal(x+4,y+4); } template<> ALT_INLINE bool strEqual<8> (const char* x, const char* y) { return *((int64_t*)x)==*((int64_t*)y); } template<> ALT_INLINE bool strEqual<9> (const char* x, const char* y) { return str8Equal(x,y) && *(x+8)==*(y+8); } template<> ALT_INLINE bool strEqual<10> (const char* x, const char* y) { return str8Equal(x,y) && str2Equal(x+8,y+8); } template<> ALT_INLINE bool strEqual<11> (const char* x, const char* y) { return str8Equal(x,y) && str3Equal(x+8,y+8); } template<> ALT_INLINE bool strEqual<12> (const char* x, const char* y) { return str8Equal(x,y) && str4Equal(x+8,y+8); } template<> ALT_INLINE bool strEqual<13> (const char* x, const char* y) { return str8Equal(x,y) && str5Equal(x+8,y+8); } template<> ALT_INLINE bool strEqual<14> (const char* x, const char* y) { return str8Equal(x,y) && str6Equal(x+8,y+8); } template<> ALT_INLINE bool strEqual<15> (const char* x, const char* y) { return str8Equal(x,y) && str7Equal(x+8,y+8); } template<> ALT_INLINE bool strEqual<16> (const char* x, const char* y) { return str8Equal(x,y) && str8Equal(x+8,y+8); } // Call these functions if you know the start buffer is already // aligned by 16. Otherwise, called the unaligned version const char* fastStrChrAligned(const char* s, char ch); size_t fastStrLenAligned(const char* s); uint64_t fastSumAligned(const uint8_t* bytes, int sz); // unaligned versions const char* fastStrChr(const char* s, char ch); size_t fastStrLen(const char* s); uint64_t fastSum(const uint8_t* bytes, int sz); /// \brief conver std::array<char,8> into 64-bit integer for template parameter /// usage to overcome the limit of template parameter not being a string constexpr static uint64_t strToNameId(std::array<char,8> name) { uint64_t res = 0; for (auto ch: name) { if (!ch) break; res = (res<<8) + uint8_t(ch); } return res; } /// \brief conver 64-bit integer into std::array<char,9> for template parameter /// usage to overcome the limit of template parameter not being a string constexpr std::array<char,9> strFromNameId(uint64_t id) { std::array<char,9> res {0}; int i = 0; int j = 0; for (; i<8; ++i) { char ch = char ((id & 0xFF00000000000000UL) >> 56); if (ch) res[j++] = ch; id <<= 8; } if (j<8) res[j] = 0; return res; } /// \brief Split a string into substrings with the given separator /// \param str The string to be slipt /// \param substrings The containder for the output of the split substrings /// \param length The length of the string to be split. When 0, the length is /// determined by scanning the null terminator of the string to be split /// \param separator The separater char to divide substrings /// \param terminator The terminator fo the string to be split /// \param skip_leading_sp Flag to indicating whether the leading spaces of the /// substring should be skipped /// \param skip_trailing_sp Flag to indicating whether the trailing spaces of the /// substring should be skipped /// \return the number of characters scanned in str size_t strSplit ( const char * str, std::vector<std::string>& substrings, size_t length = 0, char separator = ',', char terminator = '\0', bool skip_leading_sp = true, bool skip_trailing_sp = true); /// \brief split a quoted string into a list of substrings /// \param str the buffer contains quotes strings. The quote can be (), {}, [], or "". /// for example "{string1, string2, string2}", or "\"string1, string2, string2\"" /// \param substrings The containder for the output of the split substrings /// \param separator the separator in the string buffer between substrings /// \param skip_leading_sp when true, skip leading spaces in a substring /// \param skip_trailing_sp when true, skip trailing spaces in a substring /// \return the number of characters scanned in str size_t strSplitQuoted ( const char * str, std::vector<std::string>& substrings, char separator = ',', bool skip_leading_sp = true, bool skip_trailing_sp = true); /// \brief check if a character is for a decimal digit /// \param ch the character to check template <typename CHAR_T> ALT_INLINE bool isDigit (CHAR_T ch) { return ch>='0' && ch<='9'; }; /// \brief check if a character is for an oct digit /// \param ch the character to check template <typename CHAR_T> ALT_INLINE bool isOctDigit (CHAR_T ch) { return ch>='0' && ch<='7'; }; /// \brief check if a character is for a binary digit /// \param ch the character to check template <typename CHAR_T> ALT_INLINE bool isBinDigit (CHAR_T ch) { return ch=='0' || ch=='1'; }; /// \brief check if a character is for a hex digit /// \param ch the character to check template <typename CHAR_T> ALT_INLINE bool isHexDigit (CHAR_T ch) { return (ch>='0' && ch<='9') || (ch>='A' && ch<='F') || (ch>='a' && ch<='f'); }; /// \brief Get number of bytes of an UTF-8 encoded string by looking its first byte /// \param ch the first character byte of an UTF-8 encoded string ALT_INLINE size_t uCharBytes(char ch) { return clz(~(uint32_t(uint8_t(ch))<<24)); } constexpr char INVALID_HEX_DIGIT = 0X10; /// \brief convert a hex character (0~9, A~F, a~f) to integer (0~15) /// \param ch the hex character /// \return integer 0~15, or INVALID_HEX_DIGIT if oaram ch is not a hex character uint8_t hexDigit (char ch); /// \brief get the first character from an UTF8 string /// \param utf the UTF8 string /// \param wch the output of the scanned character, in 4-byte unicode /// \return the number of scanned bytes of the character size_t scanUTF8String(const char * utf8Char, alt_char_t& wch); /// \brief convert 4-byte unicode into an UTF8 string /// \param wch the 4-byte unicode /// \param utf8Char_buffer the UTF8 string buffer /// \param buffer_length the size of the TF8 string buffer /// \return number of converted bytes in utf8Char_buffer size_t wcharToUTF8(alt_char_t wch, char * utf8Char_buffer, size_t buffer_length); /// \brief convert 4-byte unicode string into an UTF8 string /// \param wch_str the 4-byte unicode string /// \param length number of unicode chars in the string /// \param utf8Char_buffer the UTF8 string buffer /// \param buffer_length the size of the TF8 string buffer /// \return number of converted bytes in utf8Char_buffer size_t wcharStrToUTF8(const alt_char_t *wch_str, size_t length, char * utf8Char_buffer, size_t buffer_length); /// \brief convert UFt8 string to 4-byte unicode string /// \param utf8_str points to a UTF8 encoded string, null terminated /// \return the u32 string in unicode std::u32string toU32String(const char * utf8_str); template <typename StrT> std::u32string toU32String(const StrT & utf8_str) { return toU32String(utf8_str.c_str()); } /// \brief tells if a UTF8 encoded string is a basic string bool isBasicString(const char * utf8_str); template <typename StrT> bool isBasicString(const StrT & utf8_str) { return isBasicString(utf8_str.c_str()); } /// \brief compare two UTF8 strings. /// \param str1 the first string to compare. /// \param str2 the second string to compare. /// \param case_sensitive when true, do the caseless comparison. /// \param number_as_whole when true and a number starts at the same position of /// two strings, the compare will use the number as whole instead of comparing /// digits individually. For instance, "item(12)" is greater than "item(3)" /// \note this does not support the case of comparsion involving multiple /// characters vs. single character such as between "ss" and “ß” in German. /// In these cases they are considered not equal. int strCmp (const char* str1, const char* str2, bool case_sensitive, bool number_as_whole); /// \brief Forward trim a c string pointer (skip ASCII white spaces only) /// \param cp pointer to a c string to trim. This cannot be nullptr /// \return pointer to the first non-whilespace character or the null therminator inline const char* strTrimForward(const char* cp) noexcept (false) { while (isspace(*cp)) ++cp; return cp; } /// \brief Backward trim a c string pointer (skip ASCII white spaces only) /// \param cp pointer to a c string to trim. This cannot be nullptr /// \param length length of the c string /// \return pointer to the position after the last first non whilespace character // or the begining of the string const char* strTrimBackward(const char* cp, size_t length) noexcept (false); /// \brief Backward trim a c string pointer (skip ASCII white spaces only) /// \param cp pointer to a c string to trim. This cannot be nullptr /// \return pointer to the position after the last first non whilespace character // or the begining of the string inline const char* strTrimBackward(const char* cp) noexcept (false) { return strTrimBackward(cp, strlen(cp)); } /// \brief Forward and Backward trim a c string pointer (skip ASCII white spaces only) /// \param str pointer to a c string to trim /// \param length length of the c string /// \param begin output param points to the beginning of the trimmed string /// \param end output param points to the end of the trimmed string inline void strTrim(const char* str, size_t length, const char*& begin, const char*& end) { if (str==nullptr || length==0) { begin = end = nullptr; return; } begin = str; end = str + length - 1; while (begin < end && isspace(*begin)) ++begin; while (begin < end && isspace(*end)) --end; if (begin==end && isspace(*begin)) { begin = end = nullptr; } } /// \brief Forward and Backward trim a string (skip ASCII white spaces only) /// \param str the input string for tirim /// \return the str being trimmed template <typename StrT> inline StrT strTrim(const StrT& str) { const char* begin; const char* end; strTrim(str.c_str(), str.length(), begin, end); return StrT(begin, size_t(end-begin)+1); } /// \brief Trim copy (remove leading and trailing spaces) for any string type /// that has methods c_str(), length(), and constructor(char*, size_t) /// \param str the source string to be trimmed /// \return string being trimmed template <typename StrT> inline StrT strTrimCpy(StrT const & str) { const char *startp, *endp; strTrim(str.c_str(), str.length(), startp, endp); if (startp && endp) { return StrT(startp, size_t(endp-startp+1)); } return StrT(); } /// \brief Trim copy (remove leading and trailing spaces) on c strings /// \param dest pointer to dest buffer for the trimmed string /// \param source pointer to source string to be trimmed inline void strTrimCpy(char* dest, const char* source) { const char *startp, *endp; strTrim(source, strlen(source), startp, endp); if (startp && endp) { strncmp(dest, startp, size_t(endp-startp+1)); } else { *dest = '\0'; } } /// \brief coverts unicode char into a formatted string with escape sequence /// \param wch the char value to be converted /// \param StrBuf the buffer to hold the convert result void uCharToFormattedString(alt_char_t wch, StrBuf& buffer); inline std::string uCharToFormattedString(alt_char_t wch) { char buffer[16]; StrBuf str_buf(buffer, 16); uCharToFormattedString(wch, str_buf); return std::string(buffer, str_buf.length()); } /// \brief coverts uft8 string into a formatted string with escape sequence /// \param u8_str the utf-8 string to be converted /// \param res the buffer to hold the converted result /// \param use_unicode_seq when true, utf-8 encoded sequence will be converted into /// unicode escape sequence if the character value is greater than 0x100. Otherwise, /// the output will keep the utf-8 encoded sequence void u8StrToFormattedString(const char* u8_str, std::string& res, bool use_unicode_seq); } // namespace alt
[ "lujunshang@gmail.com" ]
lujunshang@gmail.com
72b3441a96a62af23621a13f3658d4a68e55f662
7045bb4f95ada6e1669a3cd9520681b7e548c319
/Meijer/Platform-Core-Patch/Core/SCOTAPP/SMSelectFromListBase.cpp
e2a82d915ea130fe9a839c71e0b3c70d340bc7a5
[]
no_license
co185057/MeijerTESTSVN
0ffe207db43c8e881fdbad66c1c058e25fe451f5
3a3df97b2decc1a04e6efe7c8ab74eff5409f39f
refs/heads/master
2023-05-30T00:19:36.524059
2021-06-10T08:41:31
2021-06-10T08:41:31
375,576,064
0
0
null
null
null
null
UTF-8
C++
false
false
5,986
cpp
// // FILE: SMSelectFromListBase.cpp // // TITLE: Class implementation for Select From List state // // AUTHOR: Feng Zhang // ////////////////////////////////////////////////////////////////////////////////////////////////// #include <stdafx.h> // MS MFC always needed first #include <afxtempl.h> // MS MFC template header #include "Common.h" // Common includes #include "SMState.h" // Base state #include "SMSelectFromList.h" // This state #include "SMEnterQuantity.h" #define COMP_ID ID_SM // base state component #define T_ID _T("SelectFromList") IMPLEMENT_DYNCREATE(SMSelectFromListBase, CObject)// MFC Runtime class/object information //IMPLEMENT_STATE(SelectFromList) DEFINE_TIMESTAMP ////////////////////////////////////////// SMSelectFromListBase::SMSelectFromListBase() { IMPLEMENT_TIMESTAMP saMsgFuncPtr = PSProceduresBase::SecurityMessageNonmodal; } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::Initialize(void) { //Update RAP window with SCOT state UpdateStateName(ps.GetPSText(LTT_SELECTITEM, SCOT_LANGUAGE_PRIMARY)); // we need to go to look up first to reach this state setAnchorState(BES_SELECTFROMLIST); // TAR 164000 TellApplicationStateToSecurity(KEY_AC_SET_APP_STATE_BEGIN, _T("SelectFromList") ); // RFC 330050 if(co.fStateGraphicalSelectList) #ifndef NewUI //Not sure to remove this ps.SetCMFrame(PRODUCE_FRAME); else ps.SetCMFrame(SCROLL_FRAME); #endif if(!co.fStateGraphicalSelectList) ps.SetCMMascotImage(BMP_MASCOT_SELECTFROMLIST); ps.SetCMGobackButtonVisible(true); if(co.fStateGraphicalSelectList) ps.SetCMBackground(BMP_GRAPHICALSELECT); else ps.SetCMBackground(BMP_SELECTFROMLIST); ps.SetCMLeadthruText(LTT_SELECTITEM); ps.ShowCMFrame(); ps.DisplaySelectedItem(csLookupItemCode); DMSayPhrase(SELECTFROMLIST); ps.ShowWideList(); if(!co.fStateGraphicalSelectList) { ps.Message12(TXT_SELECTFROMLIST1, false); ps.ShowCMTotal(false ,true); ps.ShowCMTBText(csTBMessage2Scot); //thp } // allow the EchoInput() func to accept up to max digits ps.AllowInput(MAX_DIGITS_ITEMCODE,false,false); if(co.fStateGraphicalSelectList) ps.ShowVideoProduce(); else ps.ShowVideoSmall(); SetFocusToVideo(); // TAR #154963. SAWLDBScannerDisable(); // Disable the scanner return STATE_NULL; // stay in SelectFromList state } /////////////////////////////////////////// void SMSelectFromListBase::UnInitialize(void) { if(co.fStateGraphicalSelectList) ps.HideVideoProduce(); else ps.HideVideoSmall(); // BeginCodeWLDBSA11 //SAWLDBScannerDisable(); // Disable the scanner // EndCodeWLDBSA11 TellApplicationStateToSecurity(KEY_AC_SET_APP_STATE_END, _T("SelectFromList") ); // RFC 330050 } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::PSButton3(void)// start { return STATE_NULL; // stay in SelectFromList state } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::PSButton4(void)// cancel { return setAndCreateAnchorState(nSellState); //TAR#126112 return to last sell state instead of Scan and Bag LPM111599 } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::PSButtonGoBack(void)// cancel { // TAR 164000 - return createAnchorState(); //TAR# 137321 -- should return to Type Item Description screen return setAndCreateAnchorState(BES_LOOKUPITEM); // TAR 164000 } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::DMScanner(void)// scanned item { csItemSent = csDMLastBarCode; return TBItemSale(FALSE,0,true); } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::PSNumericKey(const long lKey) { PSEchoInput(lKey); return STATE_NULL; } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::PSEnterKey(void) // enter key pressed, sell this item { long lLen = ps.GetInput(csItemSent); if (lLen==0) { DMSayPhrase(KEYPADINVALID); return PSClearKey(); } DMSayPhrase(KEYPADVALID); // BeginCodeWLDBSA11 SAWLDBScannerDisable(); // Disable the scanner--Feng // EndCodeWLDBSA11 return TBItemSale(FALSE,0,false); } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::PSClearKey(void) { //PSClearInput(); long lKey=0x08; PSEchoInput(lKey); //Delete one character once--Feng return STATE_NULL; } /////////////////////////////////////////// //This is the new lookup --Feng SMStateBase *SMSelectFromListBase::PSListLookup(CString cItemCode) // list or lookup selection { // GetListWide returns an int, not a UINT and -1 means failure which is // completely lost if we cast the return to UINT ncr_barn int nSelect = ps.GetWideList(csItemSent); //Selected item //Feng csItemSent.TrimRight(); // Check for failure of nSelect also (<=) ncr_barn if (nSelect<=0 || csItemSent==_T("")) //fail in picking list { DMSayPhrase(PICKLISTINVALID); return STATE_NULL; } //double boink pd DMSayPhrase("PickListValid"); //Play a "PickListValid" wav file. --Feng if (VerifyQtyItem(csItemSent)) //Tar 143309 { io.Reset(); io.csOrigCode = csItemSent; // item code keyed io.csItemCode = csItemSent; // assumed to be the same SASendSCOTInput( UPC_MANUAL, csItemSent); RETURNSTATE(EnterQuantity) } return TBItemSale(FALSE,0,false); //Sell item } /////////////////////////////////////////// SMStateBase *SMSelectFromListBase::PSCancelKey(void)/// override where needed { DMSayPhrase(KEYPADVALID); return PSButton4(); // usually same as button 4 }
[ "co185057@ncr.com" ]
co185057@ncr.com
100e5f87be72ba49bca72c452a3e5d0fa0b3b9e5
8e6af5f82d6c35bd2e5233a03ccee3cf83fa6fb8
/jni/icon.cxx
4dc36bbf3c107b64c8b012ad0fc41054a021bbdc
[]
no_license
kay27/glukalo
e7cf23aa3d3153e0b00739336777a3a8793b1093
d5eb8376a893fb4af9586b0bdc30cdb2e65d0bf3
refs/heads/master
2021-01-21T04:47:19.412665
2016-06-01T21:56:29
2016-06-01T21:56:29
51,707,156
0
0
null
null
null
null
UTF-8
C++
false
false
1,316
cxx
#include "game.h" float Icon::vm = 1; void Icon::Init(const char * vs, const char * fs, float x_, float y_, float state_) { x = x_; y = y_; state = state_; prog = MyShader::CreateProgram(); MyShader::AttachVertexShader(prog, vs); MyShader::AttachFragmentShader(prog, fs); MyShader::LinkProgram(prog); glUseProgram(prog); vPos = glGetAttribLocation(prog, "vPos"); vTC = glGetAttribLocation(prog, "vTC"); vOffs = glGetUniformLocation(prog, "vOffs"); glEnableVertexAttribArray(vPos); glEnableVertexAttribArray(vTC); glVertexAttribPointer(vPos, 3, GL_FLOAT, false, sizeof(MyVertex), (void*)offsetof(MyVertex,pos)); glVertexAttribPointer(vTC, 2, GL_FLOAT, false, sizeof(MyVertex), (void*)offsetof(MyVertex,txtcrds)); glUseProgram(0); } void Icon::Init(const char * vs, const char * fs, float x_, float y_) { Init(vs, fs, x_, y_, 0); } void Icon::Move(float x_, float y_) { x = x_; y = y_; } void Icon::Render() { glUseProgram(prog); glUniform4f(vOffs, x, y, vm, state); glDrawArrays(GL_TRIANGLE_STRIP, 24, 4); } void Icon::Resize(float newMulValue) { vm = newMulValue; } int Icon::Tap(float tx, float ty) { return (tx>=x-ICON_SIZE/vm/2) && (tx<=x+ICON_SIZE/vm/2) && (ty>=y-ICON_SIZE/2) && (ty<=y+ICON_SIZE/2); }
[ "kay27@bk.ru" ]
kay27@bk.ru
ca3c0c3d037912a3fe28d610c79e2fd84551fe1d
af217731f0aa60e94b3713133239271c680f8806
/sources/Interpreter/lambda.hpp
da7edf2f5dae79d85a727df1d2bdf33953ecba00
[ "MIT" ]
permissive
dbanisimov/mipt-scheme-compiler
531a688fdc60980e12c705f00353c59aea80e29f
144062cdeff667bd950e12fa5c1c89e5947dc904
refs/heads/master
2021-01-19T21:40:10.802015
2014-05-28T01:08:24
2014-05-28T01:08:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
hpp
/** * @file:lambda.hpp * A declaration for classes creating storing and managing of lambda functions, * used in simulator to support user defined functions and macroses. */ /* * Copyright 2012 MIPT-COMPILER team */ #pragma once #include <vector> #include <iostream> #include "evaluator.hpp" #include "interpreter_dep.hpp" namespace interpreter { class Evaluator; namespace lambda { using std::vector; using parser::ast::SExprp; class Lambda { public: Lambda( vector<int> par, int rest_, SExprp body_, Activationp scope_, bool do_tail_rec_) :params( par), rest( rest_), body( body_), scope(scope_), do_tail_rec( do_tail_rec_) {} SExprp operator()( SExprp args, Evaluator* eva); private: vector<int> params; int rest; SExprp body; Activationp scope; bool do_tail_rec; void bindParams( SExprp args, Context* ctx); SExprp eval( Evaluator* eva); }; class LambdaManager { public: ~LambdaManager(); Lambda* makeLambda( SExprp args_and_body, Activationp scope, Evaluator* eva, bool do_tail_rec); private: vector<Lambda*> lambdas; }; }//namespace lambda }//namespace interpreter
[ "dbanisimov@gmail.com" ]
dbanisimov@gmail.com
b9e97ed48e0a1be573106e669070586ffb8d1f05
ecae991ebea4410ff718b68e166d1d92b6736be2
/limlog/include/limlog/Timestamp.h
5bc6fde9ad6a2fd0beb1034e2f7ff12b7d4a78c7
[]
no_license
looken/third-party
2f531b0c1c31fe12f98e8c4dce47dd966bf86409
dbfc73b3c86c73d1583e49828e45cbad0f30a0e9
refs/heads/main
2023-08-19T04:53:15.818091
2021-09-11T09:55:59
2021-09-11T09:55:59
405,335,521
0
0
null
null
null
null
UTF-8
C++
false
false
3,378
h
//===- Timestamp.h - Wrapper of Timestamp -----------------------*- C++ -*-===// // /// \file /// Provide related helper function of timestamp. // // Author: zxh(definezxh@163.com) // Date: 2019/12/17 20:21:54 //===----------------------------------------------------------------------===// #pragma once #include <algorithm> #include <iostream> #include <string> #ifdef __linux #include <sys/time.h> #else #include <chrono> #endif #include <stdint.h> namespace limlog { namespace detail { /// Wrapper of timestamp. class Timestamp { public: Timestamp() : timestamp_(0) {} Timestamp(uint64_t timestamp) : timestamp_(timestamp) {} /// Timestamp of current timestamp. static Timestamp now() { uint64_t timestamp = 0; #ifdef __linux // use gettimeofday(2) is 15% faster then std::chrono in linux. struct timeval tv; gettimeofday(&tv, NULL); timestamp = tv.tv_sec * kUSecPerSec + tv.tv_usec; #else timestamp = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::system_clock().now().time_since_epoch()) .count(); #endif return Timestamp(timestamp); } /// Parse format '2020-07-09-14:48:36.458074' to Timestamp. static Timestamp parse(const std::string &fmt) { if (fmt.length() == 0) return Timestamp(); struct tm st_tm; st_tm.tm_year = std::stoi(fmt.substr(0, 4)) - 1900; st_tm.tm_mon = std::stoi(fmt.substr(5, 6)) - 1; st_tm.tm_mday = std::stoi(fmt.substr(8, 9)); st_tm.tm_hour = std::stoi(fmt.substr(11, 12)); st_tm.tm_min = std::stoi(fmt.substr(14, 15)); st_tm.tm_sec = std::stoi(fmt.substr(17, 18)); uint32_t usec = std::stoi(fmt.substr(20, 25)); time_t t = static_cast<uint64_t>(mktime(&st_tm) * kUSecPerSec + usec); return Timestamp(t); } /// Current timestamp (us). /// e.g. 1594277460153980 uint64_t timestamp() const { return timestamp_; } int year() const { return toTm().tm_year + 1900; } int mon() const { return toTm().tm_mon + 1; } int mday() const { return toTm().tm_mday; } int hour() const { return toTm().tm_hour; } int min() const { return toTm().tm_min; } int sec() const { return toTm().tm_sec; } /// Format time with default fmt. /// e.g. 2020-07-09-14:48:36.458074 std::string format() const; /// Compare Timestamp. int64_t compare(const Timestamp &t) const { return static_cast<int64_t>(timestamp_ - t.timestamp()); } private: /// Convert to 'struct tm' struct tm toTm() const; uint64_t timestamp_; static const uint32_t kUSecPerSec = 1000000; }; std::string Timestamp::format() const { // reduce count of calling strftime by thread_local. static thread_local time_t t_second = 0; static thread_local char t_datetime[32]; // 2019-08-16-15:32:25 time_t nowsec = timestamp_ / kUSecPerSec; if (t_second != nowsec) { t_second = nowsec; struct tm st_time; localtime_r(&t_second, &st_time); strftime(t_datetime, sizeof(t_datetime), "%Y-%m-%d-%H:%M:%S", &st_time); } char f[40]; uint32_t micro = static_cast<uint32_t>(timestamp_ % kUSecPerSec); snprintf(f, sizeof(f), "%s.%06u", t_datetime, micro); return f; } struct tm Timestamp::toTm() const { time_t nowsec = timestamp_ / kUSecPerSec; struct tm st_time; localtime_r(&nowsec, &st_time); return st_time; } } // namespace detail } // namespace limlog
[ "18518007500@163.com" ]
18518007500@163.com
552c39afdc8c0aaf976f305f1496a839fc2f2db0
22754084ce6aa108a8a0e8ab29188741324580c9
/Adventure Game V.2/AdventureRooms.h
dfb9232853fb63321e434f49608690c0064c2718
[]
no_license
mcnugets/AdventureGame
4e60d6a0cc035c581e074dd6bc81dbb9ac3f6466
93841ca60df02ad01c76a5544d750b2c5f5ec00b
refs/heads/master
2023-05-07T09:24:12.146473
2018-07-06T17:00:00
2018-07-06T17:00:00
124,794,883
0
0
null
null
null
null
UTF-8
C++
false
false
600
h
#pragma once #include "Object.h" #include "MotionTableEntry.h" #include <vector> #include "Enemy.h" class AdventureRooms { private: int roomnum; int eventType; string nameoftheroom; bool isActive; bool eventHappened; public: AdventureRooms(int numb, string name, int eventNum); ~AdventureRooms(); string getName(); bool getActive(); void setActive(bool active); Enemy* enemy; vector<Object*> roomObjects; vector<MotionTableEntry*> motionTable; vector<string>roomDescription; vector<string>roomDescription2; bool getStatus(); void setStatus(bool status); int geteventype(); };
[ "sultanscarface@gmail.com" ]
sultanscarface@gmail.com
e7bf7c9201e72d6980a13d1bd404c2e8a39ea461
0b060f46d0d01cc4b35c417c78c1f9413952d5d0
/src/main.cpp
c0436e1f480e969960a6c2f0340617762ee16cf8
[ "MIT" ]
permissive
rbetik12/flex-compiler
72146a5ee6c592c9ff7bcdde4d9522ec8be66462
0eed37ff01da1f0da7ac337721e92bee72a2402d
refs/heads/master
2023-04-30T13:48:48.266297
2021-05-18T22:16:24
2021-05-18T22:16:24
368,225,858
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
#include <stdio.h> #include <cstdlib> extern int lineno; extern FILE* yyin; extern FILE* yyout; int yyparse(); void yyerror (char* str) { fprintf(stderr, "Syntax error at line %d\n", lineno); exit(1); } int main (int argc, char *argv[]) { if (argc < 2) { fputs("compiler <path to file>", stderr); exit(1); } int flag; yyin = fopen(argv[1], "r"); flag = yyparse(); fclose(yyin); return flag; }
[ "mr.prikota@gmail.com" ]
mr.prikota@gmail.com
114e00497df2af035189e97d3c66a18c2fe0d623
77aaeadcc4e0b756986f2433292b0fb15c64e366
/day 3/BLUETOOTH/bluetooth.ino
6c0e2eca3595a1491866ee777b029127287fad17
[]
no_license
Ashar77/Arduino-
ec0957059ec1e09c407a3fc1efa504e8ac54e625
e78c0f6320eeb8a47d01b8ff41d0d1bc0e6668a7
refs/heads/master
2021-02-04T00:57:39.508351
2020-02-28T02:45:48
2020-02-28T02:45:48
243,591,109
0
0
null
null
null
null
UTF-8
C++
false
false
348
ino
String value ; void setup() { Serial.begin(9600); pinMode(8,OUTPUT); } void loop() { while (Serial.available()) { delay(3); char c = Serial.read(); value += c; } if (value.length() > 0) { Serial.println(value);} if (value=="on1") { digitalWrite(8,HIGH);} if (value=="off1") { digitalWrite(8,LOW);} value = ""; }
[ "Asharmehmood360@gmail.com" ]
Asharmehmood360@gmail.com
a4d17c4f71023bd039af63969f7dbb8752951a78
636394fc4967123179dd2dc935f437e735c6d38a
/export/windows/obj/include/flixel/system/debug/watch/WatchEntryData.h
d37996fbb2805d359c88d251530672ef3ab0b5b9
[ "MIT" ]
permissive
arturspon/zombie-killer
865e6ef3bdb47408f9bfea9016f61bf19b2559c7
07848c5006916e9079537a3d703ffe3740afaa5a
refs/heads/master
2021-07-18T16:44:26.556092
2019-05-04T13:56:08
2019-05-04T13:56:08
181,805,463
0
1
MIT
2021-07-16T23:18:46
2019-04-17T02:50:10
C++
UTF-8
C++
false
true
1,473
h
// Generated by Haxe 4.0.0-rc.2+77068e10c #ifndef INCLUDED_flixel_system_debug_watch_WatchEntryData #define INCLUDED_flixel_system_debug_watch_WatchEntryData #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS4(flixel,_hx_system,debug,watch,WatchEntryData) HX_DECLARE_CLASS1(hscript,Expr) namespace flixel{ namespace _hx_system{ namespace debug{ namespace watch{ class WatchEntryData_obj : public hx::EnumBase_obj { typedef hx::EnumBase_obj super; typedef WatchEntryData_obj OBJ_; public: WatchEntryData_obj() {}; HX_DO_ENUM_RTTI; static void __boot(); static void __register(); static bool __GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp); ::String GetEnumName( ) const { return HX_("flixel.system.debug.watch.WatchEntryData",54,23,6d,a5); } ::String __ToString() const { return HX_("WatchEntryData.",01,e4,e7,77) + _hx_tag; } static ::flixel::_hx_system::debug::watch::WatchEntryData EXPRESSION(::String expression, ::hscript::Expr parsedExpr); static ::Dynamic EXPRESSION_dyn(); static ::flixel::_hx_system::debug::watch::WatchEntryData FIELD( ::Dynamic object,::String field); static ::Dynamic FIELD_dyn(); static ::flixel::_hx_system::debug::watch::WatchEntryData QUICK(::String value); static ::Dynamic QUICK_dyn(); }; } // end namespace flixel } // end namespace system } // end namespace debug } // end namespace watch #endif /* INCLUDED_flixel_system_debug_watch_WatchEntryData */
[ "artursponchi@gmail.com" ]
artursponchi@gmail.com
d1661bb33543e6bd22dcfc7f1a7f289de813f5f8
1cc17e9f4c3b6fba21aef3af5e900c80cfa98051
/chrome/browser/web_resource/promo_resource_service_unittest.cc
670756ed47d6ba5e67db4162d625356aba35ad0d
[ "BSD-3-Clause" ]
permissive
sharpglasses/BitPop
2643a39b76ab71d1a2ed5b9840217b0e9817be06
1fae4ecfb965e163f6ce154b3988b3181678742a
refs/heads/master
2021-01-21T16:04:02.854428
2013-03-22T02:12:27
2013-03-22T02:12:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,289
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/json/json_reader.h" #include "base/message_loop.h" #include "base/string_number_conversions.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/web_resource/notification_promo.h" #include "chrome/browser/web_resource/promo_resource_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_pref_service.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "net/url_request/test_url_fetcher_factory.h" #include "testing/gtest/include/gtest/gtest.h" class PromoResourceServiceTest : public testing::Test { public: PromoResourceServiceTest() : local_state_(static_cast<TestingBrowserProcess*>(g_browser_process)), web_resource_service_(new PromoResourceService(&profile_)) { } protected: TestingProfile profile_; ScopedTestingLocalState local_state_; scoped_refptr<PromoResourceService> web_resource_service_; MessageLoop loop_; }; class NotificationPromoTest { public: explicit NotificationPromoTest(Profile* profile) : profile_(profile), prefs_(profile->GetPrefs()), notification_promo_(profile), received_notification_(false), start_(0.0), end_(0.0), num_groups_(0), initial_segment_(0), increment_(1), time_slice_(0), max_group_(0), max_views_(0), closed_(false), gplus_required_(false) { } void Init(const std::string& json, const std::string& promo_text, #if defined(OS_ANDROID) const std::string& promo_text_long, const std::string& promo_action_type, const std::string& promo_action_arg0, const std::string& promo_action_arg1, #endif // defined(OS_ANDROID) double start, double end, int num_groups, int initial_segment, int increment, int time_slice, int max_group, int max_views, bool gplus_required) { Value* value(base::JSONReader::Read(json)); ASSERT_TRUE(value); DictionaryValue* dict = NULL; value->GetAsDictionary(&dict); ASSERT_TRUE(dict); test_json_.reset(dict); promo_type_ = #if !defined(OS_ANDROID) NotificationPromo::NTP_NOTIFICATION_PROMO; #else NotificationPromo::MOBILE_NTP_SYNC_PROMO; #endif promo_text_ = promo_text; #if defined(OS_ANDROID) promo_text_long_ = promo_text_long; promo_action_type_ = promo_action_type; promo_action_args_.push_back(promo_action_arg0); promo_action_args_.push_back(promo_action_arg1); #endif // defined(OS_ANDROID) start_ = start; end_ = end; num_groups_ = num_groups; initial_segment_ = initial_segment; increment_ = increment; time_slice_ = time_slice; max_group_ = max_group; max_views_ = max_views; gplus_required_ = gplus_required; closed_ = false; received_notification_ = false; } void InitPromoFromJson(bool should_receive_notification) { notification_promo_.InitFromJson(*test_json_, promo_type_); EXPECT_EQ(should_receive_notification, notification_promo_.new_notification()); // Test the fields. TestNotification(); } void TestNotification() { // Check values. EXPECT_EQ(notification_promo_.promo_text_, promo_text_); #if defined(OS_ANDROID) EXPECT_EQ(notification_promo_.promo_text_long_, promo_text_long_); EXPECT_EQ(notification_promo_.promo_action_type_, promo_action_type_); EXPECT_TRUE(notification_promo_.promo_action_args_.get() != NULL); EXPECT_EQ(std::size_t(2), promo_action_args_.size()); EXPECT_EQ(notification_promo_.promo_action_args_->GetSize(), promo_action_args_.size()); for (std::size_t i = 0; i < promo_action_args_.size(); ++i) { std::string value; EXPECT_TRUE(notification_promo_.promo_action_args_->GetString(i, &value)); EXPECT_EQ(value, promo_action_args_[i]); } #endif // defined(OS_ANDROID) EXPECT_EQ(notification_promo_.start_, start_); EXPECT_EQ(notification_promo_.end_, end_); EXPECT_EQ(notification_promo_.num_groups_, num_groups_); EXPECT_EQ(notification_promo_.initial_segment_, initial_segment_); EXPECT_EQ(notification_promo_.increment_, increment_); EXPECT_EQ(notification_promo_.time_slice_, time_slice_); EXPECT_EQ(notification_promo_.max_group_, max_group_); EXPECT_EQ(notification_promo_.max_views_, max_views_); EXPECT_EQ(notification_promo_.closed_, closed_); // Check group within bounds. EXPECT_GE(notification_promo_.group_, 0); EXPECT_LT(notification_promo_.group_, num_groups_); // Views should be 0 for now. EXPECT_EQ(notification_promo_.views_, 0); EXPECT_EQ(notification_promo_.gplus_required_, gplus_required_); } // Create a new NotificationPromo from prefs and compare to current // notification. void TestInitFromPrefs() { NotificationPromo prefs_notification_promo(profile_); prefs_notification_promo.InitFromPrefs(promo_type_); EXPECT_EQ(notification_promo_.prefs_, prefs_notification_promo.prefs_); EXPECT_EQ(notification_promo_.promo_text_, prefs_notification_promo.promo_text_); #if defined(OS_ANDROID) EXPECT_EQ(notification_promo_.promo_text_long_, prefs_notification_promo.promo_text_long_); EXPECT_EQ(notification_promo_.promo_action_type_, prefs_notification_promo.promo_action_type_); EXPECT_TRUE(prefs_notification_promo.promo_action_args_.get() != NULL); EXPECT_EQ(notification_promo_.promo_action_args_->GetSize(), prefs_notification_promo.promo_action_args_->GetSize()); for (std::size_t i = 0; i < notification_promo_.promo_action_args_->GetSize(); ++i) { std::string promo_value; std::string prefs_value; EXPECT_TRUE( notification_promo_.promo_action_args_->GetString(i, &promo_value)); EXPECT_TRUE( prefs_notification_promo.promo_action_args_->GetString( i, &prefs_value)); EXPECT_EQ(promo_value, prefs_value); } #endif // defined(OS_ANDROID) EXPECT_EQ(notification_promo_.start_, prefs_notification_promo.start_); EXPECT_EQ(notification_promo_.end_, prefs_notification_promo.end_); EXPECT_EQ(notification_promo_.num_groups_, prefs_notification_promo.num_groups_); EXPECT_EQ(notification_promo_.initial_segment_, prefs_notification_promo.initial_segment_); EXPECT_EQ(notification_promo_.increment_, prefs_notification_promo.increment_); EXPECT_EQ(notification_promo_.time_slice_, prefs_notification_promo.time_slice_); EXPECT_EQ(notification_promo_.max_group_, prefs_notification_promo.max_group_); EXPECT_EQ(notification_promo_.max_views_, prefs_notification_promo.max_views_); EXPECT_EQ(notification_promo_.group_, prefs_notification_promo.group_); EXPECT_EQ(notification_promo_.views_, prefs_notification_promo.views_); EXPECT_EQ(notification_promo_.closed_, prefs_notification_promo.closed_); EXPECT_EQ(notification_promo_.gplus_required_, prefs_notification_promo.gplus_required_); } void TestGroup() { // Test out of range groups. const int incr = num_groups_ / 20; for (int i = max_group_; i < num_groups_; i += incr) { notification_promo_.group_ = i; EXPECT_FALSE(notification_promo_.CanShow()); } // Test in-range groups. for (int i = 0; i < max_group_; i += incr) { notification_promo_.group_ = i; EXPECT_TRUE(notification_promo_.CanShow()); } // When max_group_ is 0, all groups pass. notification_promo_.max_group_ = 0; for (int i = 0; i < num_groups_; i += incr) { notification_promo_.group_ = i; EXPECT_TRUE(notification_promo_.CanShow()); } notification_promo_.WritePrefs(); } void TestViews() { notification_promo_.views_ = notification_promo_.max_views_ - 2; notification_promo_.WritePrefs(); NotificationPromo::HandleViewed(profile_, promo_type_); NotificationPromo new_promo(profile_); new_promo.InitFromPrefs(promo_type_); EXPECT_EQ(new_promo.max_views_ - 1, new_promo.views_); EXPECT_TRUE(new_promo.CanShow()); NotificationPromo::HandleViewed(profile_, promo_type_); new_promo.InitFromPrefs(promo_type_); EXPECT_EQ(new_promo.max_views_, new_promo.views_); EXPECT_FALSE(new_promo.CanShow()); // Test out of range views. for (int i = max_views_; i < max_views_ * 2; ++i) { new_promo.views_ = i; EXPECT_FALSE(new_promo.CanShow()); } // Test in range views. for (int i = 0; i < max_views_; ++i) { new_promo.views_ = i; EXPECT_TRUE(new_promo.CanShow()); } new_promo.WritePrefs(); } void TestClosed() { NotificationPromo new_promo(profile_); new_promo.InitFromPrefs(promo_type_); EXPECT_FALSE(new_promo.closed_); EXPECT_TRUE(new_promo.CanShow()); NotificationPromo::HandleClosed(profile_, promo_type_); new_promo.InitFromPrefs(promo_type_); EXPECT_TRUE(new_promo.closed_); EXPECT_FALSE(new_promo.CanShow()); new_promo.closed_ = false; EXPECT_TRUE(new_promo.CanShow()); new_promo.WritePrefs(); } void TestPromoText() { notification_promo_.promo_text_.clear(); EXPECT_FALSE(notification_promo_.CanShow()); notification_promo_.promo_text_ = promo_text_; EXPECT_TRUE(notification_promo_.CanShow()); } void TestTime() { const double now = base::Time::Now().ToDoubleT(); const double qhour = 15 * 60; notification_promo_.group_ = 0; // For simplicity. notification_promo_.start_ = now - qhour; notification_promo_.end_ = now + qhour; EXPECT_TRUE(notification_promo_.CanShow()); // Start time has not arrived. notification_promo_.start_ = now + qhour; notification_promo_.end_ = now + qhour; EXPECT_FALSE(notification_promo_.CanShow()); // End time has past. notification_promo_.start_ = now - qhour; notification_promo_.end_ = now - qhour; EXPECT_FALSE(notification_promo_.CanShow()); notification_promo_.start_ = start_; notification_promo_.end_ = end_; EXPECT_TRUE(notification_promo_.CanShow()); } void TestIncrement() { const double now = base::Time::Now().ToDoubleT(); const double slice = 60; notification_promo_.num_groups_ = 18; notification_promo_.initial_segment_ = 5; notification_promo_.increment_ = 3; notification_promo_.time_slice_ = slice; notification_promo_.start_ = now - 1; notification_promo_.end_ = now + slice; // Test initial segment. notification_promo_.group_ = 4; EXPECT_TRUE(notification_promo_.CanShow()); notification_promo_.group_ = 5; EXPECT_FALSE(notification_promo_.CanShow()); // Test first increment. notification_promo_.start_ -= slice; notification_promo_.group_ = 7; EXPECT_TRUE(notification_promo_.CanShow()); notification_promo_.group_ = 8; EXPECT_FALSE(notification_promo_.CanShow()); // Test second increment. notification_promo_.start_ -= slice; notification_promo_.group_ = 10; EXPECT_TRUE(notification_promo_.CanShow()); notification_promo_.group_ = 11; EXPECT_FALSE(notification_promo_.CanShow()); // Test penultimate increment. notification_promo_.start_ -= 2 * slice; notification_promo_.group_ = 16; EXPECT_TRUE(notification_promo_.CanShow()); notification_promo_.group_ = 17; EXPECT_FALSE(notification_promo_.CanShow()); // Test last increment. notification_promo_.start_ -= slice; EXPECT_TRUE(notification_promo_.CanShow()); } void TestGplus() { notification_promo_.gplus_required_ = true; // Test G+ required. notification_promo_.prefs_->SetBoolean(prefs::kIsGooglePlusUser, true); EXPECT_TRUE(notification_promo_.CanShow()); notification_promo_.prefs_->SetBoolean(prefs::kIsGooglePlusUser, false); EXPECT_FALSE(notification_promo_.CanShow()); notification_promo_.gplus_required_ = false; // Test G+ not required. notification_promo_.prefs_->SetBoolean(prefs::kIsGooglePlusUser, true); EXPECT_TRUE(notification_promo_.CanShow()); notification_promo_.prefs_->SetBoolean(prefs::kIsGooglePlusUser, false); EXPECT_TRUE(notification_promo_.CanShow()); } private: Profile* profile_; PrefService* prefs_; NotificationPromo notification_promo_; bool received_notification_; scoped_ptr<DictionaryValue> test_json_; NotificationPromo::PromoType promo_type_; std::string promo_text_; #if defined(OS_ANDROID) std::string promo_text_long_; std::string promo_action_type_; std::vector<std::string> promo_action_args_; #endif // defined(OS_ANDROID) double start_; double end_; int num_groups_; int initial_segment_; int increment_; int time_slice_; int max_group_; int max_views_; bool closed_; bool gplus_required_; }; TEST_F(PromoResourceServiceTest, NotificationPromoTest) { // Check that prefs are set correctly. PrefService* prefs = profile_.GetPrefs(); ASSERT_TRUE(prefs != NULL); NotificationPromoTest promo_test(&profile_); // Set up start and end dates and promo line in a Dictionary as if parsed // from the service. #if !defined(OS_ANDROID) promo_test.Init("{" " \"ntp_notification_promo\": [" " {" " \"date\":" " [" " {" " \"start\":\"15 Jan 2012 10:50:85 PST\"," " \"end\":\"7 Jan 2013 5:40:75 PST\"" " }" " ]," " \"strings\":" " {" " \"NTP4_HOW_DO_YOU_FEEL_ABOUT_CHROME\":" " \"What do you think of Chrome?\"" " }," " \"grouping\":" " {" " \"buckets\":1000," " \"segment\":200," " \"increment\":100," " \"increment_frequency\":3600," " \"increment_max\":400" " }," " \"payload\":" " {" " \"days_active\":7," " \"install_age_days\":21," " \"gplus_required\":false" " }," " \"max_views\":30" " }" " ]" "}", "What do you think of Chrome?", 1326653485, // unix epoch for 15 Jan 2012 10:50:85 PST. 1357566075, // unix epoch for 7 Jan 2013 5:40:75 PST. 1000, 200, 100, 3600, 400, 30, false); #else promo_test.Init( "{" " \"mobile_ntp_sync_promo\": [" " {" " \"date\":" " [" " {" " \"start\":\"15 Jan 2012 10:50:85 PST\"," " \"end\":\"7 Jan 2013 5:40:75 PST\"" " }" " ]," " \"strings\":" " {" " \"MOBILE_PROMO_CHROME_SHORT_TEXT\":" " \"Like Chrome? Go http://www.google.com/chrome/\"," " \"MOBILE_PROMO_CHROME_LONG_TEXT\":" " \"It\'s simple. Go http://www.google.com/chrome/\"," " \"MOBILE_PROMO_EMAIL_BODY\":\"This is the body.\"," " \"XXX_VALUE\":\"XXX value\"" " }," " \"grouping\":" " {" " \"buckets\":1000," " \"segment\":200," " \"increment\":100," " \"increment_frequency\":3600," " \"increment_max\":400" " }," " \"payload\":" " {" " \"payload_format_version\":3," " \"gplus_required\":false," " \"promo_message_long\":" " \"MOBILE_PROMO_CHROME_LONG_TEXT\"," " \"promo_message_short\":" " \"MOBILE_PROMO_CHROME_SHORT_TEXT\"," " \"promo_action_type\":\"ACTION_EMAIL\"," " \"promo_action_args\":[\"MOBILE_PROMO_EMAIL_BODY\",\"XXX\"]," " \"XXX\":\"XXX_VALUE\"" " }," " \"max_views\":30" " }" " ]" "}", "Like Chrome? Go http://www.google.com/chrome/", "It\'s simple. Go http://www.google.com/chrome/", "ACTION_EMAIL", "This is the body.", "XXX value", 1326653485, // unix epoch for 15 Jan 2012 10:50:85 PST. 1357566075, // unix epoch for 7 Jan 2013 5:40:75 PST. 1000, 200, 100, 3600, 400, 30, false); #endif // !defined(OS_ANDROID) promo_test.InitPromoFromJson(true); // Second time should not trigger a notification. promo_test.InitPromoFromJson(false); promo_test.TestInitFromPrefs(); // Test various conditions of CanShow. // TestGroup Has the side effect of setting us to a passing group. promo_test.TestGroup(); promo_test.TestViews(); promo_test.TestClosed(); promo_test.TestPromoText(); promo_test.TestTime(); promo_test.TestIncrement(); promo_test.TestGplus(); } TEST_F(PromoResourceServiceTest, PromoServerURLTest) { GURL promo_server_url = NotificationPromo::PromoServerURL(); EXPECT_FALSE(promo_server_url.is_empty()); EXPECT_TRUE(promo_server_url.SchemeIs("https")); // TODO(achuith): Test this better. }
[ "vgachkaylo@crystalnix.com" ]
vgachkaylo@crystalnix.com
efca1ff2721452d9ff4155a52f83293f537abf13
7b6469d1508f0a67bfe4ca6350357c2c8ffa875a
/Practical 0 - Abstract Factory/Abstract Factory/Character.h
5451416990136cf072df39d612e7e876414e658b
[]
no_license
KDaryl/Games-Engineering
785784efe18bfeaee0e9c77fa87a9e45e8b87dc3
24b6bac0e7727ee235678702a791ade956b8271a
refs/heads/master
2020-03-29T02:33:10.114707
2019-03-27T19:08:16
2019-03-27T19:08:16
149,442,486
0
0
null
null
null
null
UTF-8
C++
false
false
152
h
#pragma once #include <iostream> using namespace std; class Character { public: Character() {}; virtual ~Character() {}; virtual void draw() = 0; };
[ "c00207452@itcarlow.ie" ]
c00207452@itcarlow.ie
0d4c5b320dbc9f169c26f82970673f70af2f6b61
f98404805d5e8de2d0fdb8af1aae18f9d9632e41
/include/notneeded/DAMICDetectorInnerLead.cc
7abe3dc7ab89647e2603167825cfa895a39eee12
[]
no_license
leftcross/neutron_yield
93557333e2ef44926f93839d7ae2ca0f54618807
be13438c64c4b9e1e03eaba4e4ce4c05b3aba50e
refs/heads/master
2020-03-21T03:34:31.403578
2018-06-20T17:08:12
2018-06-20T17:08:12
138,061,743
0
0
null
null
null
null
UTF-8
C++
false
false
5,365
cc
#include "DAMICDetectorInnerLead.hh" #include "G4Material.hh" #include "G4NistManager.hh" #include "G4VSolid.hh" #include "G4Box.hh" #include "G4Tubs.hh" #include "G4Trap.hh" #include "G4Trd.hh" #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" #include "G4GeometryManager.hh" #include "G4PhysicalVolumeStore.hh" #include "G4LogicalVolumeStore.hh" #include "G4SolidStore.hh" #include "G4RunManager.hh" #include "G4UnionSolid.hh" #include "G4SubtractionSolid.hh" #include "G4ThreeVector.hh" #include "G4RotationMatrix.hh" #include "G4MultiUnion.hh" #include "G4Transform3D.hh" #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include <cmath> G4LogicalVolume* GetConstructionAncientLead1() { G4double cylRin = 15.748*mm; G4double cylRout = 91.948*mm; G4double cylH = 25.4*mm; G4double angle0 = 0; G4double angle180 = M_PI; G4Tubs* cylLead = new G4Tubs("CylLead", cylRin, cylRout, cylH/2, angle0, angle180); G4Material* Lead = G4Material::GetMaterial("G4_Pb"); G4LogicalVolume * ancientLead1 = new G4LogicalVolume(cylLead, LeadMat,"AncientLead1"); return ancientLead1; } G4LogicalVolume* GetConstructionAncientLead2() { G4double cylRin = 15.748*mm; G4double cylRout = 91.948*mm; G4double cylH = 25.4*mm; G4double angle0 = 0; G4double angle180 = M_PI; G4double rmBoxX = 6.223*mm; G4double rmBoxY = 31.75*mm; G4double rmBoxZ = 25.4*mm; G4Tubs* cylLead = new G4Tubs("CylLead", cylRin, cylRout, cylH/2, angle0, angle180); G4Box * rmBox = new G4Box ("rmBox", rmBoxX, rmBoxY/2, rmBoxZ); G4RotationMatrix * rotBox = new G4RotationMatrix; rotBox->rotateZ(M_PI/4); G4double rmBoxVecX = cylRout * cos(M_PI/4); G4double rmBoxVecY = cylRout * sin(M_PI/4); G4ThreeVector rmBoxVec = G4ThreeVector(rmBoxVecX, rmBoxVecY, 0); G4Transform3D rmBoxTr = G4Transform3D(*rotBox, rmBoxVec); G4SubtractionSolid* ancientLead2Final = new G4SubtractionSolid("AncientLead2Final", cylLead, rmBox, rmBoxTr); G4Material* Lead = G4Material::GetMaterial("G4_Pb"); G4LogicalVolume * ancientLead2 = new G4LogicalVolume(ancientLead2Final, Lead,"AncientLead2"); return ancientLead2; } G4LogicalVolume* GetConstructionBoxMountingPlate() { G4double rmCylROut = 127/2*mm; G4double rmCylRIn = 28.575/2*mm; G4double rmCylH = 6.35*mm; G4double cylRIn = 28.575/2*mm; G4double cylROut = 185.166/2*mm; G4double cylH = 9.652*mm; G4double rmBoxX = 9.525*mm; G4double rmBoxY = 30.48*mm; G4double rmBoxZ = 9.652*mm; G4double angle0 = 0; G4double angle360 = 2*M_PI+1; G4Tubs* rmCyl = new G4Tubs("RmCyl", 0, rmCylROut, rmCylH, angle0, angle360); G4Tubs* cyl = new G4Tubs("Cyl", cylRIn, cylROut, cylH/2, angle0, angle360); G4Box* rmBox = new G4Box("RmBox", rmBoxX, rmBoxY/2, rmBoxZ); G4RotationMatrix *rot0 = new G4RotationMatrix; G4double rmCylZ = cylH/2; G4double rmBoxXVec = cylROut; G4ThreeVector rmCylVec = G4ThreeVector(0,0,rmCylZ); G4ThreeVector rmBoxVec = G4ThreeVector(rmBoxXVec,0,0); G4Transform3D rmCylTr = G4Transform3D(*rot0, rmCylVec); G4Transform3D rmBoxTr = G4Transform3D(*rot0, rmBoxVec); G4SubtractionSolid* boxMountPlate = new G4SubtractionSolid("BoxMountPlate", cyl, rmCyl, rmCylTr); G4SubtractionSolid* boxMountPlateFinal = new G4SubtractionSolid("BoxMountPlateFinal", boxMountPlate, rmBox, rmBoxTr); G4Material* Copper = G4Material::GetMaterial("G4_Cu"); G4LogicalVolume * boxMountingPlate = new G4LogicalVolume(boxMountPlateFinal, Copper,"BoxMountingPlate"); return boxMountingPlate; } G4LogicalVolume* GetConstructionGoodLead() { G4double cylRIn = 31.75/2*mm; G4double cylROut = 184.15/2*mm; G4double cylH = 50.8*mm; G4double rmBoxX = 9.525*mm; G4double rmBoxY = 30.48*mm; G4double rmBoxZ = 50.8*mm; G4double angle0 = 0; G4double angle360 = M_PI*2+1; G4Tubs * cylGood = new G4Tubs("CylGood", cylRIn, cylROut, cylH/2, angle0, angle360); G4Box* rmBoxGood = new G4Box("RmBoxGood", rmBoxX, rmBoxY/2, rmBoxZ); G4RotationMatrix * rot0 = new G4RotationMatrix; G4double rmBoxXVec = -cylROut; G4ThreeVector rmBoxVec = G4ThreeVector(rmBoxXVec, 0, 0); G4Transform3D rmBoxTr = G4Transform3D(*rot0, rmBoxVec); G4SubtractionSolid * goodLeadFinal = new G4SubtractionSolid("GoodLeadFinal", cylGood, rmBoxGood, rmBoxTr); G4Material* Lead = G4Material::GetMaterial("G4_Pb"); G4LogicalVolume * goodLead = new G4LogicalVolume(goodLeadFinal, LeadMat,"GoodLead"); return goodLead; } G4LogicalVolume* GetConstructionSpacerPlate() { G4double cylRIn = 28.575/2*mm; G4double cylROut = 189.23/2*mm; G4double cylH = 3.048*mm; G4double rmBoxX = 9.525*mm; G4double rmBoxY = 30.48*mm; G4double rmBoxZ = 3.048*mm; G4double angle0 = 0; G4double angle360 = M_PI*2+1; G4Tubs * cylGood = new G4Tubs("CylGood", cylRIn, cylROut, cylH/2, angle0, angle360); G4Box* rmBoxGood = new G4Box("RmBoxGood", rmBoxX, rmBoxY/2, rmBoxZ); G4RotationMatrix * rot0 = new G4RotationMatrix; G4double rmBoxXVec = -cylROut; G4ThreeVector rmBoxVec = G4ThreeVector(rmBoxXVec, 0, 0); G4Transform3D rmBoxTr = G4Transform3D(*rot0, rmBoxVec); G4SubtractionSolid * spacerPlateFinal = new G4SubtractionSolid("SpacerPlateFinal", cylGood, rmBoxGood, rmBoxTr); G4Material* Copper = G4Material::GetMaterial("G4_Cu"); G4LogicalVolume * spacerPlate = new G4LogicalVolume(spacerPlateFinal, Copper,"SpacerPlate"); return spacerPlate; }
[ "shobhit@uchicago.edu" ]
shobhit@uchicago.edu
f9ad1ff006505eeb86fb4e0bf4be502a63af9ab9
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE36_Absolute_Path_Traversal/s03/CWE36_Absolute_Path_Traversal__wchar_t_console_open_18.cpp
253eabd9dacfcfdf88adf0ca8701b3da14ece5a9
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
3,822
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__wchar_t_console_open_18.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-18.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: console Read input from the console * GoodSource: Full path and file name * Sink: open * BadSink : Open the file named in data using open() * Flow Variant: 18 Control flow: goto statements * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #define OPEN _wopen #define CLOSE _close #else #include <unistd.h> #define OPEN open #define CLOSE close #endif namespace CWE36_Absolute_Path_Traversal__wchar_t_console_open_18 { #ifndef OMITBAD void bad() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; goto source; source: { /* Read input from the console */ size_t dataLen = wcslen(data); /* if there is room in data, read into it from the console */ if (FILENAME_MAX-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgetws() */ dataLen = wcslen(data); if (dataLen > 0 && data[dataLen-1] == L'\n') { data[dataLen-1] = L'\0'; } } else { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } } } { int fileDesc; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); if (fileDesc != -1) { CLOSE(fileDesc); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */ static void goodG2B() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; goto source; source: #ifdef _WIN32 /* FIX: Use a fixed, full path and file name */ wcscat(data, L"c:\\temp\\file.txt"); #else /* FIX: Use a fixed, full path and file name */ wcscat(data, L"/tmp/file.txt"); #endif { int fileDesc; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); if (fileDesc != -1) { CLOSE(fileDesc); } } } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE36_Absolute_Path_Traversal__wchar_t_console_open_18; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
defda5c418e375136897f409b270775c37a15478
230764d82733fac64c3e0eae1ce0a4030965dc4a
/third_party/gst-plugins-base/tests/examples/gl/gtk/filtervideooverlay/main.cpp
6850a7da28c6d78d04bd2da64ceb13275247100d
[ "LGPL-2.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-3-Clause" ]
permissive
isabella232/aistreams
478f6ae94189aecdfd9a9cc19742bcb4b4e20bcc
209f4385425405676a581a749bb915e257dbc1c1
refs/heads/master
2023-03-06T14:49:27.864415
2020-09-25T19:48:04
2020-09-25T19:48:04
298,772,653
0
0
Apache-2.0
2021-02-23T10:11:29
2020-09-26T08:40:34
null
UTF-8
C++
false
false
10,107
cpp
/* * GStreamer * Copyright (C) 2008-2009 Julien Isorce <julien.isorce@gmail.com> * * 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., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/gst.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include "../gstgtk.h" #ifdef HAVE_X11 #include <X11/Xlib.h> #endif static GstBusSyncReply create_window (GstBus* bus, GstMessage* message, GtkWidget* widget) { GtkAllocation allocation; if (gst_gtk_handle_need_context (bus, message, NULL)) return GST_BUS_DROP; // ignore anything but 'prepare-window-handle' element messages if (GST_MESSAGE_TYPE (message) != GST_MESSAGE_ELEMENT) return GST_BUS_PASS; if (!gst_is_video_overlay_prepare_window_handle_message (message)) return GST_BUS_PASS; g_print ("setting window handle %p\n", widget); gst_video_overlay_set_gtk_window (GST_VIDEO_OVERLAY (GST_MESSAGE_SRC (message)), widget); gtk_widget_get_allocation (widget, &allocation); gst_video_overlay_set_render_rectangle (GST_VIDEO_OVERLAY (GST_MESSAGE_SRC (message)), allocation.x, allocation.y, allocation.width, allocation.height); gst_message_unref (message); return GST_BUS_DROP; } static gboolean resize_cb (GtkWidget * widget, GdkEvent * event, gpointer sink) { GtkAllocation allocation; gtk_widget_get_allocation (widget, &allocation); gst_video_overlay_set_render_rectangle (GST_VIDEO_OVERLAY (sink), allocation.x, allocation.y, allocation.width, allocation.height); return G_SOURCE_CONTINUE; } static void end_stream_cb(GstBus* bus, GstMessage* message, GstElement* pipeline) { GError *error = NULL; gchar *details; switch (GST_MESSAGE_TYPE (message)) { case GST_MESSAGE_ERROR: gst_message_parse_error (message, &error, &details); g_print("Error %s\n", error->message); g_print("Details %s\n", details); /* fallthrough */ case GST_MESSAGE_EOS: g_print("End of stream\n"); gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref(pipeline); gtk_main_quit(); break; case GST_MESSAGE_WARNING: gst_message_parse_warning (message, &error, &details); g_print("Warning %s\n", error->message); g_print("Details %s\n", details); break; default: break; } } static gboolean expose_cb(GtkWidget* widget, cairo_t *cr, GstElement* videosink) { gst_video_overlay_expose (GST_VIDEO_OVERLAY (videosink)); return FALSE; } static void destroy_cb(GtkWidget* widget, GdkEvent* event, GstElement* pipeline) { g_print("Close\n"); gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref(pipeline); gtk_main_quit(); } static void button_state_null_cb(GtkWidget* widget, GstElement* pipeline) { gst_element_set_state (pipeline, GST_STATE_NULL); g_print ("GST_STATE_NULL\n"); } static void button_state_ready_cb(GtkWidget* widget, GstElement* pipeline) { gst_element_set_state (pipeline, GST_STATE_READY); g_print ("GST_STATE_READY\n"); } static void button_state_paused_cb(GtkWidget* widget, GstElement* pipeline) { gst_element_set_state (pipeline, GST_STATE_PAUSED); g_print ("GST_STATE_PAUSED\n"); } static void button_state_playing_cb(GtkWidget* widget, GstElement* pipeline) { gst_element_set_state (pipeline, GST_STATE_PLAYING); g_print ("GST_STATE_PLAYING\n"); } static gchar* slider_fps_cb (GtkScale* scale, gdouble value, GstElement* pipeline) { //change the video frame rate dynamically return g_strdup_printf ("video framerate: %0.*g", gtk_scale_get_digits (scale), value); } gint main (gint argc, gchar *argv[]) { #ifdef HAVE_X11 XInitThreads (); #endif gtk_init (&argc, &argv); gst_init (&argc, &argv); GstElement* pipeline = gst_pipeline_new ("pipeline"); //window that contains an area where the video is drawn GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_widget_set_size_request (window, 640, 480); gtk_window_move (GTK_WINDOW (window), 300, 10); gtk_window_set_title (GTK_WINDOW (window), "glimagesink implement the gstvideooverlay interface"); GdkGeometry geometry; geometry.min_width = 1; geometry.min_height = 1; geometry.max_width = -1; geometry.max_height = -1; gtk_window_set_geometry_hints (GTK_WINDOW (window), window, &geometry, GDK_HINT_MIN_SIZE); //window to control the states GtkWidget* window_control = gtk_window_new (GTK_WINDOW_TOPLEVEL); geometry.min_width = 1; geometry.min_height = 1; geometry.max_width = -1; geometry.max_height = -1; gtk_window_set_geometry_hints (GTK_WINDOW (window_control), window_control, &geometry, GDK_HINT_MIN_SIZE); gtk_window_set_resizable (GTK_WINDOW (window_control), FALSE); gtk_window_move (GTK_WINDOW (window_control), 10, 10); GtkWidget* grid = gtk_grid_new (); gtk_container_add (GTK_CONTAINER (window_control), grid); //control state null GtkWidget* button_state_null = gtk_button_new_with_label ("GST_STATE_NULL"); g_signal_connect (G_OBJECT (button_state_null), "clicked", G_CALLBACK (button_state_null_cb), pipeline); gtk_grid_attach (GTK_GRID (grid), button_state_null, 0, 1, 1, 1); gtk_widget_show (button_state_null); //control state ready GtkWidget* button_state_ready = gtk_button_new_with_label ("GST_STATE_READY"); g_signal_connect (G_OBJECT (button_state_ready), "clicked", G_CALLBACK (button_state_ready_cb), pipeline); gtk_grid_attach (GTK_GRID (grid), button_state_ready, 0, 2, 1, 1); gtk_widget_show (button_state_ready); //control state paused GtkWidget* button_state_paused = gtk_button_new_with_label ("GST_STATE_PAUSED"); g_signal_connect (G_OBJECT (button_state_paused), "clicked", G_CALLBACK (button_state_paused_cb), pipeline); gtk_grid_attach (GTK_GRID (grid), button_state_paused, 0, 3, 1, 1); gtk_widget_show (button_state_paused); //control state playing GtkWidget* button_state_playing = gtk_button_new_with_label ("GST_STATE_PLAYING"); g_signal_connect (G_OBJECT (button_state_playing), "clicked", G_CALLBACK (button_state_playing_cb), pipeline); gtk_grid_attach (GTK_GRID (grid), button_state_playing, 0, 4, 1, 1); gtk_widget_show (button_state_playing); //change framerate GtkWidget* slider_fps = gtk_scale_new_with_range (GTK_ORIENTATION_VERTICAL, 1, 30, 2); g_signal_connect (G_OBJECT (slider_fps), "format-value", G_CALLBACK (slider_fps_cb), pipeline); gtk_grid_attach (GTK_GRID (grid), slider_fps, 1, 0, 1, 5); gtk_widget_show (slider_fps); gtk_widget_show (grid); gtk_widget_show (window_control); //configure the pipeline g_signal_connect(G_OBJECT(window), "delete-event", G_CALLBACK(destroy_cb), pipeline); GstElement* videosrc = gst_element_factory_make ("videotestsrc", "videotestsrc"); GstElement* upload = gst_element_factory_make ("glupload", "glupload"); GstElement* glfiltercube = gst_element_factory_make ("glfiltercube", "glfiltercube"); GstElement* videosink = gst_element_factory_make ("glimagesink", "glimagesink"); GstCaps *caps = gst_caps_new_simple("video/x-raw", "width", G_TYPE_INT, 640, "height", G_TYPE_INT, 480, "framerate", GST_TYPE_FRACTION, 25, 1, "format", G_TYPE_STRING, "RGBA", NULL) ; gst_bin_add_many (GST_BIN (pipeline), videosrc, upload, glfiltercube, videosink, NULL); gboolean link_ok = gst_element_link_filtered(videosrc, upload, caps) ; gst_caps_unref(caps) ; if(!link_ok) { g_warning("Failed to link videosrc to glfiltercube!\n") ; return -1; } if(!gst_element_link_many(upload, glfiltercube, videosink, NULL)) { g_warning("Failed to link glfiltercube to videosink!\n") ; return -1; } //area where the video is drawn GtkWidget* area = gtk_drawing_area_new(); gtk_widget_set_redraw_on_allocate (area, TRUE); gtk_container_add (GTK_CONTAINER (window), area); gtk_widget_realize(area); //set window id on this event GstBus* bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); gst_bus_set_sync_handler (bus, (GstBusSyncHandler) create_window, area, NULL); gst_bus_add_signal_watch (bus); g_signal_connect(bus, "message::error", G_CALLBACK(end_stream_cb), pipeline); g_signal_connect(bus, "message::warning", G_CALLBACK(end_stream_cb), pipeline); g_signal_connect(bus, "message::eos", G_CALLBACK(end_stream_cb), pipeline); gst_object_unref (bus); //needed when being in GST_STATE_READY, GST_STATE_PAUSED //or resizing/obscuring the window g_signal_connect(area, "draw", G_CALLBACK(expose_cb), videosink); g_signal_connect(area, "configure-event", G_CALLBACK(resize_cb), videosink); //start GstStateChangeReturn ret = gst_element_set_state (pipeline, GST_STATE_PLAYING); if (ret == GST_STATE_CHANGE_FAILURE) { g_print ("Failed to start up pipeline!\n"); return -1; } gtk_widget_show_all (window); gtk_main(); return 0; }
[ "dschao@google.com" ]
dschao@google.com
b456b7da8a9f1a15a5bbe3b32d337ef42d3d3463
81409142eb929541875ff524e1a8fd4a6ee23f5b
/Logger.h
efdd34e1825821dff1b4b689f63e891a9e7665bc
[]
no_license
HodongMan/server-prac
c5fd040e1dbff46972e6aa46dc03cd343c250ca0
59bff534721d4d51b8f6b77eac9b3e62b95ccfb8
refs/heads/master
2020-04-29T01:27:41.781941
2019-09-02T16:02:46
2019-09-02T16:02:46
175,730,906
0
0
null
null
null
null
UTF-8
C++
false
false
1,487
h
#pragma once #include "TypeBackend.h" #include "HybridArray.h" #include "Backend.h" class Logger { public: void addBackend( Backend* backend ) noexcept; void log( const LogLevel level, const char* file, const int line, const char* format, ... ) noexcept; void setLevel( const LogLevel level ) noexcept; const LogLevel getLevel( void ) const noexcept; static Logger* getSlot( const unsigned int slot ) noexcept; private: Logger( void ); static Logger* m_slots[SLOT_COUNT]; HybridArray<Backend*, SLOT_COUNT> m_backends; LogLevel m_level; }; #define LOG_GENERAL( slot, level, file, line, format, ... ) \ do { \ if( ( level <= Logger::getSlot( slot )->getLevel() ) \ Logger::getSlot( slot )->log( level, file, line, format, __VA_ARGS__ ); \ }while( 0 ) #define LOG_FATAL( format, ... ) LOG_GENERAL( 0, LogLevel::LOG_LEVEL_FATAL, __FILE__, __LINE__, format, __VA_ARGS__ ) #define LOG_ERROR( format, ... ) LOG_GENERAL( 0, LogLevel::LOG_LEVEL_ERROR, __FILE__, __LINE__, format, __VA_ARGS__ ) #define LOG_DEBUG( format, ... ) LOG_GENERAL( 0, LogLevel::LOG_LEVEL_DEBUG, __FILE__, __LINE__, format, __VA_ARGS__ ) #define LOG_DEBUGPOS() LOG_GENERAL( 0, LogLevel::LOG_LEVEL_DEBUG, __FILE__, __LINE__, "" ) #define LOG_INFO( format, ... ) LOG_GENERAL( 0, LogLevel::LOG_LEVEL_INFO, __FILE__, __LINE__, format, __VA_ARGS__ ) #define LOG_SQL( format, ... ) LOG_GENERAL( 1, LogLevel::LOG_LEVEL_INFO, __FILE__, __LINE__, format, __VA_ARGS__ )
[ "jhd9206@gmail.com" ]
jhd9206@gmail.com
6fec942955ede69d5143719f86035c02a1b93f00
c5193e72c108d144856e1cc5050131e5a1c3f88b
/Chapter4/4_19.cc
a3d203daca6667204ddc36a83d83b70caacaa7c4
[]
no_license
mviseu/Cpp_primer
0fbad7d2671c5906e62119c930a18a839928aa77
35ec142bd959e8596be03701e5d43e01276710a1
refs/heads/master
2021-01-18T23:21:45.715093
2018-08-25T12:12:33
2018-08-25T12:12:33
87,107,097
2
0
null
null
null
null
UTF-8
C++
false
false
1,068
cc
#include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; int main() { vector<int> vec{2,1,3}; int *ptr = &vec[0]; int ival = 0; /* The order of evaluation here is clear because we are dealing with logical && operator Checks the left hand FIRST Check if not null if not null -> increment ptr return *(old ptr rvalue) */ if(ptr != 0 && *ptr++ ) { cout << "ptr is not null" << endl; } /*This first increments ival and returns old ival rvalue if old ival is non zero the && continues new ival is evaluated and if non zero is true. if zero, is false. */ if(ival++ && ival) { cout << "Both old ival and new ival are non zeroes" << endl; } /*Order of evaluation is NOT clear vec[ival++] <= vec[ival]; will it evaluate ival++ first or ival first? If it evaluates ival++ first then this means: vec[ival] <= vec[ival + 1] Which makes sense. If it evaluates ival first then this means: vec[ival] <= vec[ival] Which will always be true if ival is within index range -> does not make sense */ return 0; }
[ "mariaviseu@gmail.com" ]
mariaviseu@gmail.com
502ad702b09419b27bf3a0c3c3117407378426bc
e27d9e460c374473e692f58013ca692934347ef1
/drafts/quickSpectrogram_2/libraries/liblsl/external/lslboost/serialization/string.hpp
c09eb76cde4dd910c2c521e7a82267a6c6312e4d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thoughtworksarts/Dual_Brains
84a0edf69d95299021daf4af9311aed5724a2e84
a7a6586b91a280950693b427d8269bd68bf8a7ab
refs/heads/master
2021-09-18T15:50:51.397078
2018-07-16T23:20:18
2018-07-16T23:20:18
119,759,649
3
0
null
2018-07-16T23:14:34
2018-02-01T00:09:16
HTML
UTF-8
C++
false
false
2,792
hpp
#ifndef BOOST_SERIALIZATION_STRING_HPP #define BOOST_SERIALIZATION_STRING_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // serialization/string.hpp: // serialization for stl string templates // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.lslboost.org/LICENSE_1_0.txt) // See http://www.lslboost.org for updates, documentation, and revision history. #include <string> #include <lslboost/config.hpp> #include <lslboost/serialization/level.hpp> BOOST_CLASS_IMPLEMENTATION(std::string, lslboost::serialization::primitive_type) #ifndef BOOST_NO_STD_WSTRING BOOST_CLASS_IMPLEMENTATION(std::wstring, lslboost::serialization::primitive_type) #endif // left over from a previous incarnation - strings are now always primitive types #if 0 #include <string> #include <lslboost/serialization/collections_save_imp.hpp> #include <lslboost/serialization/collections_load_imp.hpp> #include <lslboost/serialization/split_free.hpp> namespace lslboost { namespace serialization { // basic_string - general case template<class Archive, class U, class Allocator> inline void save( Archive & ar, const std::basic_string<U, Allocator> &t, const unsigned int file_version ){ lslboost::serialization::stl::save_collection< Archive, std::basic_string<U, Allocator> >(ar, t); } template<class Archive, class U, class Allocator> inline void load( Archive & ar, std::basic_string<U, Allocator> &t, const unsigned int file_version ){ lslboost::serialization::stl::load_collection< Archive, std::basic_string<U, Allocator>, lslboost::serialization::stl::archive_input_seq< Archive, std::basic_string<U, Allocator> >, lslboost::serialization::stl::reserve_imp< std::basic_string<U, Allocator> > >(ar, t); } // split non-intrusive serialization function member into separate // non intrusive save/load member functions template<class Archive, class U, class Allocator> inline void serialize( Archive & ar, std::basic_string<U, Allocator> & t, const unsigned int file_version ){ lslboost::serialization::split_free(ar, t, file_version); } } // serialization } // namespace lslboost #include <lslboost/serialization/collection_traits.hpp> BOOST_SERIALIZATION_COLLECTION_TRAITS(std::vector) #endif #endif // BOOST_SERIALIZATION_STRING_HPP
[ "gabriel.ibagon@gmail.com" ]
gabriel.ibagon@gmail.com
920ce11f16f7a1dc618295e498066c66c3e3997b
731350bb9eab8e95e805e4a291114aea74626700
/keygenerator/tests/tests.cpp
bcfab6920e548eabd5e85afc75e807986ee2989e
[]
no_license
OlegGibadulin/PasteSlash
98c10fe78696d9912d64c8e7ff9527552343d513
d093587e371600d33466895669b2fafbc4176073
refs/heads/master
2022-12-14T18:07:29.077240
2020-09-03T19:11:14
2020-09-03T19:11:14
254,921,532
0
0
null
2020-09-03T19:11:15
2020-04-11T17:39:27
null
UTF-8
C++
false
false
230
cpp
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "../inc/KeyGenerator.h" TEST(GeneratorKeyTest,NotEmptyReturnKey) { KeyGeneratorClass generator; std::string key = generator.ReturnKey(); ASSERT_NE(key,""); }
[ "alexbutol@yandex.ru" ]
alexbutol@yandex.ru
66ab07229dcbc0311b8af67876ae8afeaf4907ba
8242d218808b8cc5734a27ec50dbf1a7a7a4987a
/Intermediate/Build/Win64/Netshoot/Inc/Engine/MaterialExpressionCurveAtlasRowParameter.gen.cpp
74c19a20af8ab6818b28e81274e709965f4da22a
[]
no_license
whyhhr/homework2
a2e75b494a962eab4fb0a740f83dc8dc27f8f6ee
9808107fcc983c998d8601920aba26f96762918c
refs/heads/main
2023-08-29T08:14:39.581638
2021-10-22T16:47:11
2021-10-22T16:47:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,487
cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "Engine/Classes/Materials/MaterialExpressionCurveAtlasRowParameter.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeMaterialExpressionCurveAtlasRowParameter() {} // Cross Module References ENGINE_API UClass* Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter(); ENGINE_API UClass* Z_Construct_UClass_UMaterialExpressionScalarParameter(); UPackage* Z_Construct_UPackage__Script_Engine(); ENGINE_API UClass* Z_Construct_UClass_UCurveLinearColor_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UCurveLinearColorAtlas_NoRegister(); ENGINE_API UScriptStruct* Z_Construct_UScriptStruct_FExpressionInput(); // End Cross Module References void UMaterialExpressionCurveAtlasRowParameter::StaticRegisterNativesUMaterialExpressionCurveAtlasRowParameter() { } UClass* Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_NoRegister() { return UMaterialExpressionCurveAtlasRowParameter::StaticClass(); } struct Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Curve_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Curve; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Atlas_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Atlas; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_InputTime_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_InputTime; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UMaterialExpressionScalarParameter, (UObject* (*)())Z_Construct_UPackage__Script_Engine, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::Class_MetaDataParams[] = { { "HideCategories", "Object MaterialExpressionScalarParameter Object Object Object" }, { "IncludePath", "Materials/MaterialExpressionCurveAtlasRowParameter.h" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpressionCurveAtlasRowParameter.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Curve_MetaData[] = { { "Category", "MaterialExpressionCurveAtlasRowParameter" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpressionCurveAtlasRowParameter.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Curve = { "Curve", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpressionCurveAtlasRowParameter, Curve), Z_Construct_UClass_UCurveLinearColor_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Curve_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Curve_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Atlas_MetaData[] = { { "Category", "MaterialExpressionCurveAtlasRowParameter" }, { "ModuleRelativePath", "Classes/Materials/MaterialExpressionCurveAtlasRowParameter.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Atlas = { "Atlas", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpressionCurveAtlasRowParameter, Atlas), Z_Construct_UClass_UCurveLinearColorAtlas_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Atlas_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Atlas_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_InputTime_MetaData[] = { { "ModuleRelativePath", "Classes/Materials/MaterialExpressionCurveAtlasRowParameter.h" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_InputTime = { "InputTime", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMaterialExpressionCurveAtlasRowParameter, InputTime), Z_Construct_UScriptStruct_FExpressionInput, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_InputTime_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_InputTime_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Curve, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_Atlas, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::NewProp_InputTime, }; const FCppClassTypeInfoStatic Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UMaterialExpressionCurveAtlasRowParameter>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::ClassParams = { &UMaterialExpressionCurveAtlasRowParameter::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::PropPointers), 0, 0x000820A0u, METADATA_PARAMS(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UMaterialExpressionCurveAtlasRowParameter, 3434918729); template<> ENGINE_API UClass* StaticClass<UMaterialExpressionCurveAtlasRowParameter>() { return UMaterialExpressionCurveAtlasRowParameter::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UMaterialExpressionCurveAtlasRowParameter(Z_Construct_UClass_UMaterialExpressionCurveAtlasRowParameter, &UMaterialExpressionCurveAtlasRowParameter::StaticClass, TEXT("/Script/Engine"), TEXT("UMaterialExpressionCurveAtlasRowParameter"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UMaterialExpressionCurveAtlasRowParameter); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "49893309+whyhhr@users.noreply.github.com" ]
49893309+whyhhr@users.noreply.github.com
1103281d9675027636542b447e2b56bda197847f
d25df6b3378827e6fe8d8b00566d11b67f0f17d6
/src/mem_mgr.h
389a372fced6c7aab44d43bb46b469f6408caf7b
[]
no_license
jc4ever21/ps3emu
297d234086ac46f02ce67a6b12f02238bf1be427
36f073e75bb1b0e36a72f339dbd783998cd710d8
refs/heads/master
2020-12-28T20:54:23.932140
2012-01-09T06:33:01
2012-01-09T06:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,511
h
static const int reserve_granularity = 1024*1024; bool mm_reserve(void*addr) { if ((uint64_t)addr%reserve_granularity) xcept("attempt to reserve unaligned address %p",addr); void*a = VirtualAlloc(addr,reserve_granularity,MEM_RESERVE,PAGE_READWRITE); if (a&&a!=addr) xcept("VirtualAlloc(%p,MEM_RESERVE) returned unexpected value %p",addr,a); return a?true:false; } void mm_reserve_area(void*addr,size_t size) { if ((uint64_t)addr%reserve_granularity) xcept("attempt to reserve unaligned address %p",addr); for (uintptr_t a=(uintptr_t)addr;a<(uintptr_t)addr+size;a+=reserve_granularity) { if (!mm_reserve((void*)a)) xcept("failed to reserve %p; last error %d",(void*)a,GetLastError()); } } void mm_release(void*addr) { if ((uint64_t)addr%reserve_granularity) xcept("attempt to release unaligned address %p",addr); if (!VirtualFree(addr,0,MEM_RELEASE)) xcept("VirtualFree(%p,0,MEM_RELEASE) failed; last error %d",addr,GetLastError()); } void mm_release_area(void*addr,size_t size) { for (size_t a=(size_t)addr;a<(size_t)addr+size;a+=1024*1024) { mm_release((void*)a); } } void mm_commit(void*addr,size_t size) { //dbgf("commit %p + %#x\n",addr,size); if (!VirtualAlloc(addr,size,MEM_COMMIT,PAGE_READWRITE)) { xcept("VirtualAlloc(%p,%d,MEM_COMMIT) failed; last error %d",addr,size,GetLastError()); } } void mm_decommit(void*addr,size_t size) { //dbgf("decommit %p + %#x\n",addr,size); if (!VirtualFree(addr,size,MEM_DECOMMIT)) xcept("VirtualFree(%p,%d,MEM_DECOMMIT) failed; last error %d",addr,size,GetLastError()); } struct mem_mgr { struct region; typedef basic_rbtree_node<region> region_node; struct region: region_node { uint32_t begin,end; }; struct region_cmp { bool operator()(const region*a,const region*b) const { return a->begin<b->begin; } }; struct region_map { typedef boost::intrusive::rbtree_algorithms<region> algo; region header; uint32_t total_range_size; region_map() : total_range_size(0) { algo::init_header(&header); } ~region_map() { while (!algo::unique(&header)) { region*n = algo::unlink_leftmost_without_rebalance(&header); delete n; } } region*begin() { return algo::begin_node(&header); } region*end() { return &header; } region*next(region*i) { return algo::next_node(i); } uint32_t size() { return total_range_size; } region*try_merge_range(uint32_t begin,uint32_t end) { auto insert_hint = &header; // This compare function is compatible only because it is guaranteed there are no adjacent regions for (auto i = algo::lower_bound(&header,begin,[](const region*a,uint32_t begin) {return a->end<begin;});i!=&header && i->begin<=end;i=algo::next_node(i)) { region&r = *i; if (begin<r.end&&end>r.begin) xcept("overlapping addresses [%#x,%#x) [%#x,%#x)",begin,end,r.begin,r.end); if (begin==i->end) { i = algo::next_node(i); if (i!=&header&&end>i->begin) xcept("overlapping addresses [%#x,%#x) [%#x,%#x)",begin,end,i->begin,i->end); total_range_size += end-r.end; r.end = end; return 0; } else if (i->begin==end) { total_range_size += r.begin-begin; r.begin = begin; return 0; } if (r.begin>begin && !insert_hint) insert_hint = i; } return insert_hint; } void add_range(uint32_t begin,uint32_t end) { auto insert_hint = try_merge_range(begin,end); if (!insert_hint) return; region&nr = *new region(); nr.begin = begin; nr.end = end; algo::insert_equal(&header,insert_hint,&nr,region_cmp()); total_range_size += end-begin; } void add_region(region&r) { auto insert_hint = try_merge_range(r.begin,r.end); if (!insert_hint) { delete &r; return; } else { algo::insert_equal(&header,insert_hint,&r,region_cmp()); total_range_size += r.end-r.begin; } } bool try_extract(uint32_t begin,uint32_t end) { for (auto i = algo::lower_bound(&header,begin,[](const region*a,uint32_t begin) {return a->end<=begin;});i!=&header&&i->begin<end;i=algo::next_node(i)) { if (end>i->end) continue; region&r = *i; if (r.begin==begin&&r.end==end) { algo::erase(&header,&r); delete &r; } else if (r.begin==begin) { r.begin = end; } else if (r.end==end) { r.end = begin; } else { region&nr = *new region(); nr.begin = end; nr.end = r.end; r.end = begin; algo::insert_equal(&header,algo::next_node(i),&nr,region_cmp()); } total_range_size -= end-begin; return true; } return false; } void extract(uint32_t begin,uint32_t end) { if (!try_extract(begin,end)) xcept("failed to extract range [%#x,%#x)",begin,end); } }; uint32_t max_avail_size; mem_mgr() : max_avail_size(0) {} ~mem_mgr() {} region_map avail_address_map; boost::mutex avail_address_map_mutex; void add_address_range(uint32_t begin,uint32_t end) { boost::unique_lock<boost::mutex> l(avail_address_map_mutex); avail_address_map.add_range(begin,end); uint32_t s = avail_address_map.size(); if (s>max_avail_size) max_avail_size=s; } void dump_avail_address_map() { boost::unique_lock<boost::mutex> l(avail_address_map_mutex); dbgf("Available address map ::\n"); for (auto i=avail_address_map.begin();i!=avail_address_map.end();i=avail_address_map.next(i)) { region&r = *i; uint32_t size = r.end-r.begin; if (size&0xfffff) dbgf(" [%#x,%#x) - %dM + %dK\n",r.begin,r.end,size/0x100000,size/0x400&0x3ff); else dbgf(" [%#x,%#x) - %dM\n",r.begin,r.end,size/0x100000); } uint32_t total = avail_address_map.size(); if (total&0xfffff) dbgf("Total size: %dM + %dK\n",total/0x100000,total/0x400&0x3ff); else dbgf("Total size: %dM\n",total/0x100000); } // alignment must be a power of 2 uint32_t get_address(uint32_t alignment,uint32_t size,uint32_t min_addr=0,uint32_t max_addr=-1) { //dbgf("get_address alignment %u size %u\n",alignment,size); //dump_avail_address_map(); uint32_t mask = ~(alignment-1); if ((alignment&mask)!=alignment) xcept("get_address alignment is not a power of 2"); boost::unique_lock<boost::mutex> l(avail_address_map_mutex); for (auto i=avail_address_map.begin();i!=avail_address_map.end();i=avail_address_map.next(i)) { region&r = *i; uint32_t b = ((r.begin-1)&mask)+alignment; uint32_t e = b+size; if (e<b) break; if (b<min_addr || e>max_addr) continue; if (e<=r.end) { avail_address_map.extract(b,e); return b; } } return 0; } bool try_extract(uint32_t begin,uint32_t end) { return avail_address_map.try_extract(begin,end); } struct allocated_block { uint32_t begin, end; allocated_block(uint32_t begin,uint32_t end) : begin(begin), end(end) {} bool operator==(const allocated_block&o) const { return o.begin==begin; } operator size_t() const { return begin/0x10000; } }; std::unordered_set<allocated_block> allocated_block_set; boost::mutex allocate_mutex; // alignment must be a multiple of 65536 uint32_t allocate(uint32_t alignment,uint32_t size) { size = (size-1&~0xffff)+0x10000; if (alignment&0xffff) xcept("alignment&0xffff"); uint32_t addr = get_address(alignment,size); if (!addr) return 0; // Apparently, Windows doesn't like commits across multiple reserves // (returns 487, invalid address). Can't find anything about this in // the documentation. uint32_t a=(addr-1&-reserve_granularity)+reserve_granularity; if (a>addr+size) a=addr+size; if (a-addr) mm_commit((void*)addr,a-addr); for (;a+reserve_granularity<addr+size;a+=reserve_granularity) { mm_commit((void*)a,reserve_granularity); } if (addr+size-a) mm_commit((void*)a,addr+size-a); boost::unique_lock<boost::mutex> l(allocate_mutex); allocated_block_set.insert(allocated_block(addr,addr+size)); return addr; } bool free(uint32_t addr) { uint32_t size; { boost::unique_lock<boost::mutex> l(allocate_mutex); auto i = allocated_block_set.find(allocated_block(addr,0)); if (i==allocated_block_set.end()) return false; allocated_block_set.erase(i); size=i->end-i->begin; } // Same goes when decommitting. uint32_t a=(addr-1&-reserve_granularity)+reserve_granularity; if (a>addr+size) a=addr+size; if (a-addr) mm_decommit((void*)addr,a-addr); for (;a+reserve_granularity<addr+size;a+=reserve_granularity) { mm_decommit((void*)a,reserve_granularity); } if (addr+size-a) mm_decommit((void*)a,addr+size-a); add_address_range(addr,addr+size); return true; } static const uint32_t max_reserve = -1; void find_addresses(uint32_t begin,uint32_t end) { // TODO: Make it skip already reserved addresses begin = (begin-1&-reserve_granularity) + reserve_granularity; if (!begin) begin = reserve_granularity; for (uint32_t addr=begin;addr<end;) { if (avail_address_map.size()>=max_reserve) break; if (mm_reserve((void*)addr)) { add_address_range(addr,addr+reserve_granularity); } addr += reserve_granularity; } } uint32_t avail_size() { return avail_address_map.size(); } uint32_t total_size() { return max_avail_size; } }; mem_mgr user_mem_mgr; void*mm_alloc(size_t size) { return (void*)user_mem_mgr.allocate(0x10000,size); } void mm_free(void*addr) { if (!user_mem_mgr.free((uint32_t)addr)) xcept("user_mem_mgr.free(%p) failed",addr); } void mm_find_addresses() { static bool si_valid=false; static SYSTEM_INFO si; if (!si_valid) { GetSystemInfo(&si); si_valid = true; } uint32_t g = (uint32_t)si.dwAllocationGranularity; uint32_t p = (uint32_t)si.dwPageSize; if (reserve_granularity%g) xcept("Reserve granularity (%d) is not a multiple of the allocation granularity (%d)",reserve_granularity,g); user_mem_mgr.find_addresses(0,0x80000000); user_mem_mgr.dump_avail_address_map(); } void mm_setup() { SYSTEM_INFO si; GetSystemInfo(&si); uint32_t g = (uint32_t)si.dwAllocationGranularity; uint32_t p = (uint32_t)si.dwPageSize; dbgf("Page Size: %d\n",si.dwPageSize); dbgf("Min address: %p\n",si.lpMinimumApplicationAddress); dbgf("Max address: %p\n",si.lpMaximumApplicationAddress); dbgf("Allocation granularity: %d\n",si.dwAllocationGranularity); if (0x100000%p) xcept("Page size (%d) is not a multiple of 1M",si.dwPageSize); mm_find_addresses(); } struct mm_setuper { mm_setuper() { mm_setup(); } } mm_setuper; template<typename T> struct mm_allocator { typedef T value_type; typedef T*pointer; typedef T&reference; typedef const T*const_pointer; typedef const T&const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; mm_allocator() {} template<typename U> mm_allocator(const mm_allocator<U>&) {} pointer address(reference x) const {return &x;} const_pointer address(const_reference x) const {return &x;} pointer allocate(size_type n,void*hint=0) { pointer r = (pointer)mm_alloc(sizeof(T)*n); if (!r) xcept("mm_allocator::allocate failed"); return r; } void deallocate(pointer p,size_type n) { mm_free(p); } size_t max_size() const { return (size_t)-1/sizeof(T); } void construct(pointer p,const_reference val) { new (p) T(val); } void destroy(pointer p) { p->~T(); } template<typename T> struct rebind { typedef mm_allocator<T> other; }; };
[ "tsc.moo@gmail.com@fe98964a-3680-33c8-1987-c395d0cee68b" ]
tsc.moo@gmail.com@fe98964a-3680-33c8-1987-c395d0cee68b
b0c7b145d7fc79a1258f04eef88a3b0579478a61
116954475f2b0d90fc088ade84fe9be5986dd7f3
/OSGWidgets/ClearIrrelevantPoints.cpp
0f3da3b676c340ab68b5c4034b20c21dd32a82b8
[]
no_license
ColleyLi/RobotPathGeneration
36df5a7704c9cba3caa2acb93660d333a879b504
32aa59368b99084461be49027a498bda34410b2a
refs/heads/master
2023-03-18T23:59:29.737585
2019-10-08T02:46:25
2019-10-08T02:46:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,472
cpp
// // Created by zhihui on 8/5/19. // #include <iostream> #include <QObject> #include <QThread> #include <QMessageBox> #include "ClearIrrelevantPoints.h" ClearIrrelevantPoints::~ClearIrrelevantPoints() { std::cout<<"~ClearIrrelevantPoints"<<std::endl; } void ClearIrrelevantPoints::clearIrrelevantPointsSlot(osg::ref_ptr<osg::Switch> rootnode, osg::ref_ptr<osgViewer::View> mainview, bool isactive) { this->mainView = mainview; this->rootNode = rootnode; clearPointsEvents = new ClearPointsEvents(rootNode); std::cout << "ClearIrrelevantPoints thread: " << QThread::currentThreadId() << std::endl; std::cout << "ClearIrrelevantPoints :success" << std::endl; if (rootNode == nullptr) { std::cout << "get failed" << std::endl; } else{ std::cout<<"isActive: "<<isactive<<std::endl; mainview->setEventQueue(new osgGA::EventQueue); if(isactive) { std::cout<<"addEvent success"<<std::endl; mainView->addEventHandler(clearPointsEvents); } } } void ClearIrrelevantPoints::removeEvent() { if (rootNode == nullptr) { std::cout << "get failed" << std::endl; } else { std::cout << "remove clearPointsEvents success" << std::endl; mainView->removeEventHandler(clearPointsEvents); } } void ClearIrrelevantPoints::PolygonclearIrrelevantPointsSlot(osg::ref_ptr<osg::Switch> rootnode, osg::ref_ptr<osgViewer::View> mainview, bool isactive) { this->mainView = mainview; this->rootNode = rootnode; polygonClearPointsEvents = new PolygonClearPointsEvents(rootNode); std::cout << "PolygonClearPointsEvents thread: " << QThread::currentThreadId() << std::endl; std::cout << "PolygonClearPointsEvents :success" << std::endl; if (rootNode == nullptr) { std::cout << "get failed" << std::endl; } else{ std::cout<<"isActive: "<<isactive<<std::endl; mainview->setEventQueue(new osgGA::EventQueue); if(isactive) { std::cout<<"addEvent success"<<std::endl; mainView->addEventHandler(polygonClearPointsEvents); } } } void ClearIrrelevantPoints::removePolygonEvent() { if (rootNode == nullptr) { std::cout << "get failed" << std::endl; } else { std::cout << "remove polygonClearPointsEvents success" << std::endl; mainView->removeEventHandler(polygonClearPointsEvents); } }
[ "1401605907@qq.com" ]
1401605907@qq.com
a580552345249386ab84436199048b24f289c7c1
8e1334bd97b8fe92ada1c9ca00beb342c52ba122
/code blocks/fake.c
1a2fdcd077deeac84e3624b7f222c30a6ddf01ce
[]
no_license
chetan-anand/codechef
39922197ec2d61da44106fa38f2414b3fcec72e1
03c4da7684aa8e129e05dc9509e1e3b5e9cc213a
refs/heads/master
2020-04-16T07:59:08.735276
2014-03-04T20:48:45
2014-03-04T20:48:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
567
c
#include<stdio.h> int main() { int n,i,j,first,last; long long int a[100001]={1,0,2,3,7}; //scanf("%d",&n); n=5; /*for(i=0;i<n;i++) { scanf("%lld",&a[i]); }*/ for(first=0;first<=n-4;++first) { for(last=first+3;last<=n-1;last++) { for(i=first+1;i<=last-2;++i) { for(j=i+1;j<=last-1;++j) { if((a[first]^a[i]^a[j]^a[last])==0){printf("Yes");return 0;} } } } } printf("No"); return 0; }
[ "chetan.iitg@gmail.com" ]
chetan.iitg@gmail.com
315890cbc7ff820b2cde11f86fdcb2fdd371175d
b76d3f6e3fe5429021007431acbf683319183e42
/TestSVN/TestSVN/TestSVN.cpp
53c402f6caf010816c1b3954a5a52b9212699899
[]
no_license
AlexandrPuryshev/cfparser
82a520f7d15188decbb68ff3a8f125cbee8454c3
3d81fa67dab2b34035cac78380b246c2abb1bd65
refs/heads/master
2021-01-13T00:49:23.110243
2008-10-27T20:58:46
2008-10-27T20:58:46
47,927,807
0
0
null
null
null
null
UTF-8
C++
false
false
162
cpp
// TestSVN.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; }
[ "alexey.maggot@bef8c1c5-3d53-0410-ba26-178f7c86328d" ]
alexey.maggot@bef8c1c5-3d53-0410-ba26-178f7c86328d
cbf40dab11544a2b9a81297e82c73731f733fcf4
9d0cc5bdaa0de82eadc0f9a0839db0fdb3aeeab8
/mexEVP_Encrypt.cpp
cbd3e073cb9d4943e91116e5c29e61a888c0470b
[]
no_license
agabrielson/MatlabOpenSSL
328fbd1d0567bb88bfec68462d928866febcfecd
22c75f8fddae9e4df1fb0324e7bbc64ae9348201
refs/heads/master
2020-03-16T13:09:12.947295
2018-05-09T20:54:35
2018-05-09T20:54:35
132,682,495
0
0
null
null
null
null
UTF-8
C++
false
false
4,519
cpp
/* mexEVP_Decrypt.cpp * Examples: * reference readme.txt * * Notes: * Lots - reference readme.txt * * To Build: * Reference buildMex * * Author: * Anthony Gabrielson * agabrielson@me.com * 3/26/2010 * * Modifications: * 3/29/2010 Added a bit more documentation * */ #include "mex.h" #include "EVPIO.hpp" #include "matlabIO.hpp" #include <openssl/evp.h> #include <string> #include <stdlib.h> void encrypt(data &data2Enc, data &encData, char key[], char iv[], string cipher); void help(); template<class Type> int getData( const mxArray **prhs, Type data[], size_t elem_len ); /* * mexFunction: Matlab entry function into this C code * Inputs: * int nlhs: Number of left hand arguments (output) * mxArray *plhs[]: The left hand arguments (output) * int nrhs: Number of right hand arguments (inputs) * const mxArray *prhs[]: The right hand arguments (inputs) * * Notes: * (Left) goes_out = foo(goes_in); (Right) */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { char key[EVP_MAX_KEY_LENGTH] = "this's my key"; char iv[EVP_MAX_IV_LENGTH] = "my iv"; string cmd, keyStr, ivStr, cipher; data data2Enc, encData; data2Enc.elem = 0; encData.elem = 0; for (int inputProc = 0; inputProc < nrhs; ) { getStr( &prhs[inputProc++], cmd ); if (cmd == "data") { getData( &prhs[inputProc++], data2Enc ); } else if(cmd == "key") { memset(key,0,EVP_MAX_KEY_LENGTH); getData( &prhs[inputProc++], key, EVP_MAX_KEY_LENGTH ); } else if(cmd == "iv") { memset(iv,0,EVP_MAX_IV_LENGTH); getData( &prhs[inputProc++], iv, EVP_MAX_IV_LENGTH ); } else if(cmd == "cipher") { getStr( &prhs[inputProc++], cipher ); } else { mexPrintf("Input Confusion: %s\n",cmd.c_str()); mexErrMsgTxt( cmd.c_str() ); } } if(data2Enc.elem == 0){ help(); mexPrintf("Data not set...\n"); return; } //Encrypt the data encrypt(data2Enc, encData, key, iv, cipher); //Send the encrypted data back to Matlab. sendType(&plhs[0], encData.mem, encData.elem, 1); } void encrypt(data &data2Enc, data &encData, char key[], char iv[], string cipher) { OpenSSL_add_all_algorithms(); //EVP_get_cipherbyname will not work with out this const EVP_CIPHER *cipher_type; //For cipher choice cipher_type = EVP_get_cipherbyname(cipher.c_str()); if( cipher_type == NULL ){ if(cipher.length() != 0) mexPrintf("Defaulting to: EVP_aes_128_cbc()\n"); cipher_type = EVP_aes_128_cbc(); //Default to AES is there is a problem } EVP_CIPHER_CTX ctx; EVP_EncryptInit(&ctx, cipher_type, (const unsigned char *) key, (const unsigned char *) iv); //Need to allocate the encrypted memory int in_len = data2Enc.elem; int malloc_len = in_len+(EVP_CIPHER_CTX_block_size(&ctx)*2); //I'm feeling lazy... encData.mem = static_cast<uint8*>(mxCalloc(malloc_len, sizeof(char))); int out_len = 0, update, final; EVP_EncryptUpdate(&ctx, (unsigned char *) encData.mem, &update, (const unsigned char *) data2Enc.mem, in_len); //Block through the mem to be encrypted EVP_EncryptFinal(&ctx, (unsigned char *) (encData.mem+update), &final); //Finish any remaining encryption and throw a pad on out_len = update + final; encData.elem = out_len; return; } void help() { mexPrintf("mexEVP_Encrypt:\n"); mexPrintf("data: What data would you like to encrypt? This is the only required option...\n"); mexPrintf("key: what key would you like the data it be encrypted with?\n"); mexPrintf("IV: The intialization vector used to speed some algorithms up\n"); mexPrintf("Supported Ciphers: (Reference OpenSSL documentation for current & complete list)\n"); mexPrintf("\tCurrently Defaults to: aes-128-cbc\n"); mexPrintf("\tAES: aes-128-ecb, aes-128-cbc, aes-192-ecb, aes-192-cbc, aes-256-ecb, aes-256-cbc\n"); mexPrintf("\tBlowfish: bf-ecb, bf-cbc, bf-cfb, bf-ofb\n"); mexPrintf("\tCast: cast-ecb, cast-cbc, cast-cfb, cast-ofb\n"); mexPrintf("\tDES: des-ecb, des-cbc, des-cfb, des-ofb\n"); mexPrintf("\tDESX: desx\n"); mexPrintf("\t3DES: des-ede3, des-ede3-cbc, des-ede3-cfb, des-ede3-ofb, des-ede, des-ede-cbc, des-ede-cfb, des-ede-ofb\n"); mexPrintf("\tIDEA: idea-ecb, idea-cbc, idea-cfb, idea-ofb\n"); }
[ "agabriel2@gmail.com" ]
agabriel2@gmail.com
717a22ef4c65fe9981111cf34bccdad86c5ce02e
9e45d4890174faddc173b28bf9db4ef4e8b47a52
/src/widgets/Ads.cpp
36025ad343cf69baf3af7649bf5ec26d414d2ebe
[]
no_license
VladSnow/smartRTU
59e02f78114762598cfcceef5dfc46940e656729
7bb431daee81b4ea80e7237e0e807896c5061cd4
refs/heads/master
2021-08-26T08:36:34.564104
2017-11-22T15:33:16
2017-11-22T15:33:16
109,303,519
0
0
null
2017-11-02T18:28:31
2017-11-02T18:28:31
null
UTF-8
C++
false
false
136
cpp
#include "Ads.h" bool Ads::Load(const char * jsonFile) {} Ads::Ads() {} Ads::~Ads() {} bool Ads::update() {} void Ads::render() {}
[ "rtudf@inbox.lv" ]
rtudf@inbox.lv
363ab6d857abcf50d61a804f16393c95d9f64e76
7e62f0928681aaaecae7daf360bdd9166299b000
/external/DirectXShaderCompiler/external/SPIRV-Tools/source/opt/loop_utils.h
4a311f74c8fd8a6476322b05b3a26d5417ff1003
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yuri410/rpg
949b001bd0aec47e2a046421da0ff2a1db62ce34
266282ed8cfc7cd82e8c853f6f01706903c24628
refs/heads/master
2020-08-03T09:39:42.253100
2020-06-16T15:38:03
2020-06-16T15:38:03
211,698,323
0
0
null
null
null
null
UTF-8
C++
false
false
7,015
h
// Copyright (c) 2018 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SOURCE_OPT_LOOP_UTILS_H_ #define SOURCE_OPT_LOOP_UTILS_H_ #include <list> #include <memory> #include <unordered_map> #include <vector> #include "source/opt/ir_context.h" #include "source/opt/loop_descriptor.h" namespace spvtools { namespace opt { // Class to gather some metrics about a Region Of Interest (ROI). // So far it counts the number of instructions in a ROI (excluding debug // and label instructions) per basic block and in total. struct CodeMetrics { void Analyze(const Loop& loop); // The number of instructions per basic block in the ROI. std::unordered_map<uint32_t, size_t> block_sizes_; // Number of instruction in the ROI. size_t roi_size_; }; // LoopUtils is used to encapsulte loop optimizations and from the passes which // use them. Any pass which needs a loop optimization should do it through this // or through a pass which is using this. class LoopUtils { public: // Holds a auxiliary results of the loop cloning procedure. struct LoopCloningResult { using ValueMapTy = std::unordered_map<uint32_t, uint32_t>; using BlockMapTy = std::unordered_map<uint32_t, BasicBlock*>; using PtrMap = std::unordered_map<Instruction*, Instruction*>; PtrMap ptr_map_; // Mapping between the original loop ids and the new one. ValueMapTy value_map_; // Mapping between original loop blocks to the cloned one. BlockMapTy old_to_new_bb_; // Mapping between the cloned loop blocks to original one. BlockMapTy new_to_old_bb_; // List of cloned basic block. std::vector<std::unique_ptr<BasicBlock>> cloned_bb_; }; LoopUtils(IRContext* context, Loop* loop) : context_(context), loop_desc_( context->GetLoopDescriptor(loop->GetHeaderBlock()->GetParent())), loop_(loop), function_(*loop_->GetHeaderBlock()->GetParent()) {} // The converts the current loop to loop closed SSA form. // In the loop closed SSA, all loop exiting values go through a dedicated Phi // instruction. For instance: // // for (...) { // A1 = ... // if (...) // A2 = ... // A = phi A1, A2 // } // ... = op A ... // // Becomes // // for (...) { // A1 = ... // if (...) // A2 = ... // A = phi A1, A2 // } // C = phi A // ... = op C ... // // This makes some loop transformations (such as loop unswitch) simpler // (removes the needs to take care of exiting variables). void MakeLoopClosedSSA(); // Create dedicate exit basic block. This ensure all exit basic blocks has the // loop as sole predecessors. // By construction, structured control flow already has a dedicated exit // block. // Preserves: CFG, def/use and instruction to block mapping. void CreateLoopDedicatedExits(); // Clone |loop_| and remap its instructions. Newly created blocks // will be added to the |cloning_result.cloned_bb_| list, correctly ordered to // be inserted into a function. // It is assumed that |ordered_loop_blocks| is compatible with the result of // |Loop::ComputeLoopStructuredOrder|. If the preheader and merge block are in // the list they will also be cloned. If not, the resulting loop will share // them with the original loop. // The function preserves the def/use, cfg and instr to block analyses. // The cloned loop nest will be added to the loop descriptor and will have // ownership. Loop* CloneLoop(LoopCloningResult* cloning_result, const std::vector<BasicBlock*>& ordered_loop_blocks) const; // Clone |loop_| and remap its instructions, as above. Overload to compute // loop block ordering within method rather than taking in as parameter. Loop* CloneLoop(LoopCloningResult* cloning_result) const; // Clone the |loop_| and make the new loop branch to the second loop on exit. Loop* CloneAndAttachLoopToHeader(LoopCloningResult* cloning_result); // Perfom a partial unroll of |loop| by given |factor|. This will copy the // body of the loop |factor| times. So a |factor| of one would give a new loop // with the original body plus one unrolled copy body. bool PartiallyUnroll(size_t factor); // Fully unroll |loop|. bool FullyUnroll(); // This function validates that |loop| meets the assumptions made by the // implementation of the loop unroller. As the implementation accommodates // more types of loops this function can reduce its checks. // // The conditions checked to ensure the loop can be unrolled are as follows: // 1. That the loop is in structured order. // 2. That the continue block is a branch to the header. // 3. That the only phi used in the loop is the induction variable. // TODO(stephen@codeplay.com): This is a temporary mesure, after the loop is // converted into LCSAA form and has a single entry and exit we can rewrite // the other phis. // 4. That this is an inner most loop, or that loops contained within this // loop have already been fully unrolled. // 5. That each instruction in the loop is only used within the loop. // (Related to the above phi condition). bool CanPerformUnroll(); // Maintains the loop descriptor object after the unroll functions have been // called, otherwise the analysis should be invalidated. void Finalize(); // Returns the context associate to |loop_|. IRContext* GetContext() { return context_; } // Returns the loop descriptor owning |loop_|. LoopDescriptor* GetLoopDescriptor() { return loop_desc_; } // Returns the loop on which the object operates on. Loop* GetLoop() const { return loop_; } // Returns the function that |loop_| belong to. Function* GetFunction() const { return &function_; } private: IRContext* context_; LoopDescriptor* loop_desc_; Loop* loop_; Function& function_; // Populates the loop nest of |new_loop| according to |loop_| nest. void PopulateLoopNest(Loop* new_loop, const LoopCloningResult& cloning_result) const; // Populates |new_loop| descriptor according to |old_loop|'s one. void PopulateLoopDesc(Loop* new_loop, Loop* old_loop, const LoopCloningResult& cloning_result) const; }; } // namespace opt } // namespace spvtools #endif // SOURCE_OPT_LOOP_UTILS_H_
[ "yuri410@users.noreply.github.com" ]
yuri410@users.noreply.github.com
a9849a013fc4f648bf547a081b69257efd450498
215ce8f43785f46c1fe141f27c966d592679ee54
/Plugins/Profiler/Profiler.cpp
2211e6134dfb973e5c663774ca85a8e597e37b01
[]
no_license
borzacchiello/S2E_plugins
6f0c893918f749596618f1e27152e1ef2bdc48a9
d8036599f58d3379eb61f87f1de81178f894a517
refs/heads/master
2020-04-12T10:25:22.792885
2019-12-12T14:29:53
2019-12-12T14:29:53
162,429,213
1
3
null
null
null
null
UTF-8
C++
false
false
6,414
cpp
// // Created by luca on 02/10/19. // #include <s2e/cpu.h> #include <s2e/opcodes.h> #include <s2e/ConfigFile.h> #include <s2e/S2E.h> #include <s2e/S2EExecutor.h> #include <klee/util/ExprTemplates.h> #include <s2e/Utils.h> #include <iostream> #include <fstream> #include "Profiler.h" #include "monitor_inst.h" #define DEBUG_PRINT(inst) if (debug) {inst} namespace s2e { namespace plugins { using namespace llvm; S2E_DEFINE_PLUGIN(Profiler, "Profiler plugin", "Profiler",); void Profiler::initialize() { debug = s2e()->getConfig()->getBool(getConfigKey() + ".debug"); timerdata_path = s2e()->getConfig()->getString(getConfigKey() + ".timer_path"); init_count(); } void Profiler::handleOpcodeInvocation(S2EExecutionState *state, uint64_t guestDataPtr, uint64_t guestDataSize) { ProfilerGuestCommand command; if (guestDataSize != sizeof(command)) { getWarningsStream(state) << "mismatched S2E_HOOK_PLUGIN_COMMAND size\n"; exit(-1); } if (!state->mem()->read(guestDataPtr, &command, guestDataSize)) { getWarningsStream(state) << "could not read transmitted data\n"; exit(-1); } switch (command.cmd) { case NOTIFY_INIT: { DEBUG_PRINT ( std::ostringstream message; message << "NOTIFY_INIT received" << "\n"; getInfoStream(state) << message.str(); ) } break; case NOTIFY_START_TIMER: { clock_gettime(CLOCK_MONOTONIC, &timer_begin); DEBUG_PRINT ( std::ostringstream message; message << "NOTIFY_START_TIMER received." << "\n"; getInfoStream(state) << message.str(); ) start_count(); } break; case NOTIFY_END_TIMER: { struct timespec timer_end; clock_gettime(CLOCK_MONOTONIC, &timer_end); stop_count(); unsigned long long perf_count; read_count(&perf_count); std::ofstream timer_file; timer_file.open (timerdata_path, std::ios_base::app); timer_file << timespecDiff(&timer_end, &timer_begin) << ";" << perf_count << "\n"; timer_file.close(); DEBUG_PRINT ( std::ostringstream message; message << "NOTIFY_END_TIMER received. \n\tElapsed time: " << timespecDiff(&timer_end, &timer_begin) << "\n\t" << "Executed instructions (perf): " << perf_count << "\n"; getInfoStream(state) << message.str(); ) } break; case NOTIFY_FORCE_LLVM: { assert(false && "deprecated"); unsigned long long buff = command.forceLLVMData.buffer; unsigned long long data = command.forceLLVMData.data; unsigned long size = command.forceLLVMData.size; DEBUG_PRINT ( std::ostringstream message; message << "NOTIFY_FORCE_LLVM received data: \n" << "\t buff: " << std::hex << buff << "\n" << "\t data: " << std::hex << data << "\n" << "\t size: " << size << "\n"; getInfoStream(state) << message.str(); ) std::vector<uint8_t> concreteData; for (unsigned i = 0; i < size; ++i) { uint8_t byte = 0; if (!state->mem()->read<uint8_t>(data + i, &byte, VirtualAddress, false)) { getWarningsStream(state) << "FORCE_LLVM_BUFFER Can not concretize/read symbolic value at " << hexval(data + i) << ". System state not modified\n"; return; } concreteData.push_back(byte); } std::vector<klee::ref<klee::Expr>> symb; symb = state->createConcolicArray("FORCE_LLVM_BUFFER", size, concreteData, 0); for (unsigned i = 0; i < size; ++i) { if (!state->mem()->write(buff + i, symb[i], VirtualAddress)) { getWarningsStream(state) << "FORCE_LLVM_BUFFER Can not insert symbolic value at " << hexval(buff + i) << ": can not write to memory\n"; } state->addConstraint(E_EQ(symb[i], E_CONST(concreteData[i], klee::Expr::Int8))); } DEBUG_PRINT ( std::ostringstream message; message << "NOTIFY_FORCE_LLVM completed. Fake symbolic array at " << std::hex << buff << " injected" << "\n"; getInfoStream(state) << message.str(); ) } default: { getWarningsStream(state) << "unknown command\n"; } break; } } int64_t Profiler::timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); } void Profiler::killState(S2EExecutionState *state, std::string mex) { std::ostringstream os; os << "The state was terminated by Profiler plugin\n" << " Message: " << mex << "\n"; s2e()->getExecutor()->terminateStateEarly(*state, os.str()); } } // namespace plugins } // namespace s2e
[ "lucaborza@gmail.com" ]
lucaborza@gmail.com
736d9fed779c87d40cc6e001edf05bb4d5f0c01e
c5f9df9a1a4891c53ed8b08de4d4791734fcc9a2
/04栈和递归/递归实现简单迷宫(文件版)/实现简单迷宫/createFile.hpp
12cba83238a2b01d920e31df1e56b23518ce82a8
[]
no_license
happyxiaotao/-DayDayUp
e11c56dcc38597068766f15f3ce3b0b73725c039
0848b1e92f1ae0d735f102a665585ab532b6896f
refs/heads/master
2021-01-01T04:41:36.893023
2017-09-14T14:30:08
2017-09-14T14:30:08
97,222,931
0
1
null
null
null
null
GB18030
C++
false
false
2,958
hpp
/* 功能:实现创建关卡文件 */ #include <fstream> //文件名 char* file[3] = {"maze1.txt", "maze2.txt", "maze3.txt"}; //共有三关(1,2两关都有出口,3关没有出口) const int MAX_ROW_1 = 10; const int MAX_COL_1 = 10; char mapArr_1[MAX_ROW_1][MAX_COL_1] = { { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 }, { 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 1, 1, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 } }; //关卡2地图 const int MAX_ROW_2 = 10; const int MAX_COL_2 = 20; char mapArr_2[MAX_ROW_2][MAX_COL_2] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 1, 0, 0, 0, 0, 1 ,1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 1, 0, 0, 0, 0, 1 ,0, 0, 1, 1, 1, 0, 0, 1, 0, 0 }, { 0, 1, 0, 0, 1, 0, 0, 0, 0, 1 ,0, 0, 1, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ,0, 0, 1, 0, 1, 0, 0, 1, 1, 1 }, { 0, 0, 1, 1, 1, 0, 0, 0, 1, 1 ,0, 0, 1, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 ,0, 0, 1, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0 ,0, 0, 1, 0, 1, 1, 1, 1, 1, 0 }, { 0, 0, 0, 1, 1, 1, 1, 0, 1, 1 ,1, 1, 1, 0, 1, 1, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; //关卡3地图 const int MAX_ROW_3 = 10; const int MAX_COL_3 = 20; char mapArr_3[MAX_ROW_3][MAX_COL_3] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 1, 0, 0, 0, 0, 1 ,1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 1, 0, 0, 0, 0, 1 ,0, 0, 1, 1, 1, 0, 0, 1, 0, 0 }, { 0, 1, 0, 0, 1, 0, 0, 0, 0, 1 ,0, 0, 1, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ,0, 0, 1, 0, 1, 0, 0, 1, 1, 0 }, { 0, 0, 1, 1, 1, 0, 0, 0, 1, 1 ,0, 0, 1, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 ,0, 0, 1, 0, 1, 0, 0, 1, 0, 0 }, { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0 ,0, 0, 1, 0, 1, 1, 1, 1, 1, 0 }, { 0, 0, 0, 1, 1, 1, 1, 0, 1, 1 ,1, 1, 1, 0, 1, 1, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; //给文件写入内容 void WriteFile(const char* fileName, char* map, int max_row, int max_col) { // 1.打开文件 ofstream ofs(fileName, ofstream::out); if (!ofs) { cerr << "write"<<fileName<< "error!" << endl; exit(1); } // 2.写入文件 //写入二位数组行列数 ofs.put(max_row); ofs.put(max_col); ofs.put('\n'); //写入内容 for (int i = 0; i < max_row; ++i) { for (int j = 0; j < max_col; ++j) ofs.put(map[i*max_col+j]); ofs.put('\n'); } //关闭文件 ofs.close(); } void loadFile() { //写入文件maze_1.txt中 WriteFile(file[0], &mapArr_1[0][0], MAX_ROW_1, MAX_COL_1); //写入文件maze_2.txt中 WriteFile(file[1], &mapArr_2[0][0], MAX_ROW_2, MAX_COL_2); //写入文件maze_2.txt中 WriteFile(file[2], &mapArr_3[0][0], MAX_ROW_3, MAX_COL_3); }
[ "1550637676@qq.com" ]
1550637676@qq.com
1df364bac4ab9e1529607b7a27620f2b66a9ce2b
5beded726fe9d57f3e1d98500f2fae5fb18caaaa
/thermophile/thermophile.ino
7be3104c581af6573d42c39519b4846f2e72ad12
[]
no_license
drewperry/IoTsensors
59a795814d6461d72211876375f03ebad69bec98
f800075269620dc220bf8f0a3c119662c0efad89
refs/heads/master
2022-04-14T07:07:26.536582
2020-04-12T20:10:56
2020-04-12T20:10:56
255,161,044
0
0
null
null
null
null
UTF-8
C++
false
false
2,436
ino
/*************************************************** This is an example for the TMP006 Contact-less Infrared Thermopile Sensor Designed specifically to work with the Adafruit TMP006 Breakout ----> https://www.adafruit.com/products/1296 These displays use I2C to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution ****************************************************/ #include <Wire.h> #include <Adafruit_Sensor.h> #include "Adafruit_TMP006.h" // Connect VCC to +3V (its a quieter supply than the 5V supply on an Arduino // Gnd -> Gnd // SCL connects to the I2C clock pin. On newer boards this is labeled with SCL // otherwise, on the Uno, this is A5 on the Mega it is 21 and on the Leonardo/Micro digital 3 // SDA connects to the I2C data pin. On newer boards this is labeled with SDA // otherwise, on the Uno, this is A4 on the Mega it is 20 and on the Leonardo/Micro digital 2 Adafruit_TMP006 tmp006; //Adafruit_TMP006 tmp006(0x41); // start with a diferent i2c address! void setup() { Serial.begin(9600); Serial.println("Adafruit TMP006 example"); // you can also use tmp006.begin(TMP006_CFG_1SAMPLE) or 2SAMPLE/4SAMPLE/8SAMPLE to have // lower precision, higher rate sampling. default is TMP006_CFG_16SAMPLE which takes // 4 seconds per reading (16 samples) if (! tmp006.begin()) { Serial.println("No sensor found"); while (1); } Serial.println("Send s to enter sleep mode, or w to wake up. Measurements are not updated while asleep!"); } void loop() { // Check for sleep/wake command. while (Serial.available() > 0) { char c = Serial.read(); if (c == 'w') { Serial.println("Waking up!"); tmp006.wake(); } else if (c == 's') { Serial.println("Going to sleep!"); tmp006.sleep(); } } // Grab temperature measurements and print them. float objt = tmp006.readObjTempC(); Serial.print("Object Temperature: "); Serial.print(objt); Serial.println("*C"); float diet = tmp006.readDieTempC(); Serial.print("Die Temperature: "); Serial.print(diet); Serial.println("*C"); delay(4000); // 4 seconds per reading for 16 samples per reading }
[ "andrewperry@vt.edu" ]
andrewperry@vt.edu
28f49c417b008f07a5c4f47f1e50580688152aa1
dbc81819c6463b81c40aee5e9c6c99be1d743f15
/services/catalog/entry_unittest.cc
e5dba1b4380a0d8c8f60bad94f5ee8e8c419655a
[ "BSD-3-Clause" ]
permissive
processnotproduct/WebARonARCore
a465795f91418428104a6ceb6c404bdf0f600f84
d412066287a181961f0caa7b080bea55f3f40e2f
refs/heads/master
2023-02-26T04:54:42.074849
2017-08-25T21:27:51
2017-08-25T21:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,778
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/catalog/entry.h" #include "base/files/file_path.h" #include "base/json/json_file_value_serializer.h" #include "base/macros.h" #include "base/path_service.h" #include "base/values.h" #include "build/build_config.h" #include "services/service_manager/public/cpp/interface_provider_spec.h" #include "services/service_manager/public/interfaces/interface_provider_spec.mojom.h" #include "testing/gtest/include/gtest/gtest.h" namespace catalog { class EntryTest : public testing::Test { public: EntryTest() {} ~EntryTest() override {} protected: std::unique_ptr<Entry> ReadEntry(const std::string& manifest, std::unique_ptr<base::Value>* out_value) { std::unique_ptr<base::Value> value = ReadManifest(manifest); base::DictionaryValue* dictionary = nullptr; CHECK(value->GetAsDictionary(&dictionary)); if (out_value) *out_value = std::move(value); return Entry::Deserialize(*dictionary); } std::unique_ptr<base::Value> ReadManifest(const std::string& manifest) { base::FilePath manifest_path; PathService::Get(base::DIR_SOURCE_ROOT, &manifest_path); manifest_path = manifest_path.AppendASCII("services/catalog/test_data/" + manifest); JSONFileValueDeserializer deserializer(manifest_path); int error = 0; std::string message; // TODO(beng): probably want to do more detailed error checking. This should // be done when figuring out if to unblock connection // completion. return deserializer.Deserialize(&error, &message); } private: void SetUp() override {} void TearDown() override {} DISALLOW_COPY_AND_ASSIGN(EntryTest); }; TEST_F(EntryTest, Simple) { std::unique_ptr<Entry> entry = ReadEntry("simple", nullptr); EXPECT_EQ("foo", entry->name()); EXPECT_EQ("Foo", entry->display_name()); } TEST_F(EntryTest, Instance) { std::unique_ptr<Entry> entry = ReadEntry("instance", nullptr); EXPECT_EQ("foo", entry->name()); EXPECT_EQ("Foo", entry->display_name()); } TEST_F(EntryTest, ConnectionSpec) { std::unique_ptr<Entry> entry = ReadEntry("connection_spec", nullptr); EXPECT_EQ("foo", entry->name()); EXPECT_EQ("Foo", entry->display_name()); service_manager::InterfaceProviderSpec spec; service_manager::CapabilitySet capabilities; capabilities.insert("bar:bar"); spec.requires["bar"] = capabilities; service_manager::InterfaceProviderSpecMap specs; specs[service_manager::mojom::kServiceManager_ConnectorSpec] = spec; EXPECT_EQ(specs, entry->interface_provider_specs()); } TEST_F(EntryTest, RequiredFiles) { std::unique_ptr<Entry> entry = ReadEntry("required_files", nullptr); EXPECT_EQ("foo", entry->name()); EXPECT_EQ("Foo", entry->display_name()); auto required_files = entry->required_file_paths(); EXPECT_EQ(2U, required_files.size()); auto iter = required_files.find("all_platforms"); ASSERT_NE(required_files.end(), iter); bool checked_platform_specific_file = false; #if defined(OS_WIN) EXPECT_EQ(base::FilePath(L"/all/platforms/windows"), iter->second); iter = required_files.find("windows_only"); ASSERT_NE(required_files.end(), iter); EXPECT_EQ(base::FilePath(L"/windows/only"), iter->second); checked_platform_specific_file = true; #elif defined(OS_FUCHSIA) EXPECT_EQ(base::FilePath("/all/platforms/fuchsia"), iter->second); iter = required_files.find("fuchsia_only"); ASSERT_NE(required_files.end(), iter); EXPECT_EQ(base::FilePath("/fuchsia/only"), iter->second); checked_platform_specific_file = true; #elif defined(OS_LINUX) EXPECT_EQ(base::FilePath("/all/platforms/linux"), iter->second); iter = required_files.find("linux_only"); ASSERT_NE(required_files.end(), iter); EXPECT_EQ(base::FilePath("/linux/only"), iter->second); checked_platform_specific_file = true; #elif defined(OS_MACOSX) EXPECT_EQ(base::FilePath("/all/platforms/macosx"), iter->second); iter = required_files.find("macosx_only"); ASSERT_NE(required_files.end(), iter); EXPECT_EQ(base::FilePath("/macosx/only"), iter->second); checked_platform_specific_file = true; #elif defined(OS_ANDROID) EXPECT_EQ(base::FilePath("/all/platforms/android"), iter->second); iter = required_files.find("android_only"); ASSERT_NE(required_files.end(), iter); EXPECT_EQ(base::FilePath("/android/only"), iter->second); checked_platform_specific_file = true; #endif EXPECT_TRUE(checked_platform_specific_file); } TEST_F(EntryTest, Malformed) { std::unique_ptr<base::Value> value = ReadManifest("malformed"); EXPECT_FALSE(value.get()); } } // namespace catalog
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f166671bdccae82122ce61faed2c1a6cc9027c5f
11f37c2af971187824419ed3cb751a252f6d8a19
/DKP/2013/CrackingTheSafe/main.cpp
b1c68819f89c862e0a7a84894abe4cf7fd152778
[]
no_license
devos50/programmingchallenges
c1fd97062bf85d0999d91cbf51b30a56b628972e
004e64337b1c140023f520aef15781640e108842
refs/heads/master
2020-06-07T07:30:10.246738
2015-01-19T18:29:10
2015-01-19T18:29:10
29,485,114
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
cpp
#include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; bool can = false; double eval(double a, double b, int op) { if(op == 0) return a + b; else if(op == 1) return a - b; else if(op == 2) return a * b; else if(op == 3) return a / b; return 0; } void rec(vector<double> vec) { // for(vector<double>::iterator it = vec.begin(); it != vec.end(); it++) cout << *it << " "; // cout << endl; // cout << "vec size: " << vec.size() << endl; if(vec.size() == 1) { // cout << "VALUE: " << vec[0] << endl; if(abs(vec[0] - 24.0) < 0.0001) { can = true; } return; } // chose two indices and take an operator for(int i = 0; i < vec.size() - 1; i++) { for(int j = 0; j < 4; j++) { if(j == 3 && vec[i+1] == 0) continue; vector<double> newvec; for(int k = 0; k < i; k++) newvec.push_back(vec[k]); newvec.push_back(eval(vec[i], vec[i+1], j)); for(int k = i + 2; k < vec.size(); k++) newvec.push_back(vec[k]); rec(newvec); } } } void solve() { can = false; double a, b, c, d; cin >> a >> b >> c >> d; // cout << a << " " << b << " " << c << " " << d << endl; vector<double> vec; vec.push_back(a); vec.push_back(b); vec.push_back(c); vec.push_back(d); sort(vec.begin(), vec.end()); do { rec(vec); } while(next_permutation(vec.begin(), vec.end())); if(can) cout << "YES" << endl; else cout << "NO" << endl; } int main(int argc, char *argv[]) { int t; cin >> t; while(t--) solve(); }
[ "mdmartijndevos@gmail.com" ]
mdmartijndevos@gmail.com
fd6fd92ef55af7b09675de3d2122049a0343d985
c2aa1ea6ec509a457a21b82d24243f69101f5e56
/pathtracer/src/integrators/photonmapping.h
c0b45a8df1aac9da867e0b3b3c5bf2bebc8182e7
[]
no_license
AgentLee/PathTracer
96647ab7ccb19dee30ccb582d0817e3de4f086e2
104c4de02f5ef7ad4663a59b1ceececda6215b53
refs/heads/master
2021-06-16T15:27:31.648587
2017-10-26T12:25:37
2017-10-26T12:25:37
101,907,807
0
0
null
null
null
null
UTF-8
C++
false
false
971
h
#pragma once #include "integrator.h" class Photon { public: // Constructors Photon() {} Photon(Point3f pos, Vector3f dir, float pow, Color3f col) : position(pos), direction(dir), flux(pow), color(col) {} ~Photon() {} // Member variables Point3f position; Vector3f direction; float flux; Color3f color; }; class PhotonMapping : public Integrator { public: PhotonMapping(Bounds2i bounds, Scene* s, std::shared_ptr<Sampler> sampler, int recursionLimit) : Integrator(bounds, s, sampler, recursionLimit) {} // Evaluate the energy transmitted along the ray back to // its origin using multiple importance sampling virtual Color3f Li(const Ray& ray, const Scene& scene, std::shared_ptr<Sampler> sampler, int depth, Color3f compoundEnergy) const; // Member variables std::vector<Photon> directPhotonMap; std::vector<Photon> indirectPhotonMap; std::vector<Photon> causticsPhotonMap; };
[ "agentlee927@gmail.com" ]
agentlee927@gmail.com
386dca3afdad44e930de417aac221dc534833a0f
db25d2ec853fa414fd6c7a9390fc2e358a31d0ca
/20150508/Rectangle.h
69ddb17f69a38d2915891ddd61558f165e15a35e
[]
no_license
pandada8/LearnC-CPP
f6c50df4abba9947ac5bc1738c2cad7c8c27bb56
3681eb07179530750c0b140df2b20fea7a57cbec
refs/heads/master
2016-09-06T02:26:50.925878
2015-06-20T10:13:06
2015-06-20T10:13:06
32,436,753
0
0
null
null
null
null
UTF-8
C++
false
false
311
h
// // Created by pan on 5/8/15. // #ifndef CANDCPP_RECTANGLE_H #define CANDCPP_RECTANGLE_H #include "Paintable.h" class Rectangle : public Paintable { public: Rectangle(int x, int y, int w, int h) : Paintable(x, y), w(w), h(h){}; void draw(); private: int w, h; }; #endif //CANDCPP_RECTANGLE_H
[ "pandada8@gmail.com" ]
pandada8@gmail.com
20161fc21325c4df01a535579fd0a7f21dc53692
b6ce9b399dfdf0f5e7a11d69ac077f462ccbec63
/include/game/Items/Weapon.h
ed5f723807e75e8456836f29478faae230741f5a
[]
no_license
AsTeFu/Roguelike
6db30abd80b01ee61bf02d005c4385bab985b02d
221241f8a645c92a864d1bc967c845565a31dfdc
refs/heads/master
2020-07-11T10:05:29.219942
2019-09-18T19:15:34
2019-09-18T19:15:34
202,659,470
1
0
null
null
null
null
UTF-8
C++
false
false
846
h
// // Created by AsTeFu on 31.08.2019. // #ifndef INCLUDE_GAME_ITEMS_WEAPON_H_ #define INCLUDE_GAME_ITEMS_WEAPON_H_ #include <string> #include "game/Items/InventoryItem.h" class Weapon : public InventoryItem { public: int damage; int chanceCritical; Weapon(const std::string& name, Rarity rarity, int cost, int damage, int chanceCritical) : InventoryItem(name, rarity, cost), damage(damage), chanceCritical(chanceCritical) {} void printItem(int x, int y) const override; int printItemExtended(int x, int y) const override; void equipItem(Entity* player, ChestComponent* chestComponent, int indexItem) override; void takeItem(Entity* player) override; void addItemToInventory(InventoryComponent* inventory) override; void equipItem(Entity* player, int indexItem) override; }; #endif // INCLUDE_GAME_ITEMS_WEAPON_H_
[ "astefuapps@gmail.com" ]
astefuapps@gmail.com
e6454de8605927c2a6d602a264627eaa40298c8c
7f6d2df4f97ee88d8614881b5fa0e30d51617e61
/居安/第三章知识总结/第三章知识总结代码/example3_14.cpp
404510ed94e7fc125ccfc923c8539c3f2ccf25c7
[]
no_license
tsingke/Homework_Turing
79d36b18692ec48b1b65cfb83fc21abf87fd53b0
aa077a2ca830cdf14f4a0fd55e61822a4f99f01d
refs/heads/master
2021-10-10T02:03:53.951212
2019-01-06T07:44:20
2019-01-06T07:44:20
148,451,853
15
25
null
2018-10-17T15:20:24
2018-09-12T09:01:50
C++
GB18030
C++
false
false
295
cpp
// Li3_14.cpp文件: 包含Date4.h文件,主函数中定义Date类的对象数组,注意其定义、初始化及访问 #include"Date4.h" int main() { Date array[3]={ Date(2011,5,1), Date(2011,10,1) }; for(int i=0; i<3; i++) array[i].Display( ); system("Pause"); return 0; }
[ "912616832@qq.com" ]
912616832@qq.com
d4a2d89f0a24c97ff110b08d4e0564b881642791
b6e2bb10d45ea945b7b67df5d3d4938d86dcbf63
/Implements/Sorting/MergeSort.cpp
c4461bd6cdc28f88f44f96ab507f8b01e1756e16
[]
no_license
ahnyeji/C_Algorithm
42195cb53cda97470cc7a3d934dd427857ca4de5
89c28f7fc790afd2ca076b3c772761f3ceb8d167
refs/heads/main
2023-06-16T17:19:36.322517
2021-07-17T17:33:10
2021-07-17T17:33:10
333,251,827
0
0
null
null
null
null
UTF-8
C++
false
false
1,373
cpp
#include <iostream> #include <vector> using namespace std; template<typename T> // Combine vector<T> merge(vector<T> left, vector<T> right){ int llen = left.size(); int l = 0; int rlen = right.size(); int r = 0; vector<T> merged; while(l < llen && r < rlen){ if(left[l] <= right[r]){ merged.push_back(left[l]); l++; } else{ merged.push_back(right[r]); r++; } } while(l < llen){ merged.push_back(left[l++]); } while(r < rlen){ merged.push_back(right[r++]); } return merged; } template<typename T> vector<T> mergeSort(vector<T> inp){ int len = inp.size(); if(len < 2) return inp; // len 0 or 1 : cannot divide -> return // Divide int mid = len / 2; vector<T> left; vector<T> right; for(int i = 0; i < mid; i++){ left.push_back(inp[i]); } for(int i = mid; i < len; i++){ right.push_back(inp[i]); } // Conquer & Combine inp = merge(mergeSort(left), mergeSort(right)); return inp; } int main(){ int N; cin >> N; vector<int> toSort; for(int i = 0; i < N; i++){ int c; cin >> c; toSort.push_back(c); } toSort = mergeSort(toSort); for(int i = 0; i < N; i++){ cout << toSort[i] << " "; } }
[ "yejian1218@naver.com" ]
yejian1218@naver.com
34a2eca66f91b11ac25919d3eb1565288ed29493
ab2d13f1680170c1556d5d9271b851a537860449
/C++lec01/demo2.cpp
564b9a9312f12dde794752d5fec9adb4a9063674
[ "MIT" ]
permissive
7418520/ACMProgramming
93802c97fab4c835e9894eb30d203db72b523016
3a94506a061900bb7c659c15993241c5c6be9864
refs/heads/master
2020-03-11T09:35:56.868245
2017-10-26T02:29:26
2017-10-26T02:29:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
#include<iostream> using namespace std; struct node { int x; inline int operator +(node &a) const { return x+a.x; } }; int main() { node a,b; a.x=b.x=5; cout<<a+b<<endl; return 0; }
[ "1658751131@qq.com" ]
1658751131@qq.com
74db81d3d9c8ad859e8665a4aa801f5fa7b41fd6
27bb5ed9eb1011c581cdb76d96979a7a9acd63ba
/aws-cpp-sdk-organizations/source/model/ListRootsRequest.cpp
ea5b26d0466dc1bcdc489d21987cfe455bca399f
[ "Apache-2.0", "JSON", "MIT" ]
permissive
exoscale/aws-sdk-cpp
5394055f0876a0dafe3c49bf8e804d3ddf3ccc54
0876431920136cf638e1748d504d604c909bb596
refs/heads/master
2023-08-25T11:55:20.271984
2017-05-05T17:32:25
2017-05-05T17:32:25
90,744,509
0
0
null
2017-05-09T12:43:30
2017-05-09T12:43:30
null
UTF-8
C++
false
false
1,489
cpp
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/organizations/model/ListRootsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Organizations::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; ListRootsRequest::ListRootsRequest() : m_nextTokenHasBeenSet(false), m_maxResults(0), m_maxResultsHasBeenSet(false) { } Aws::String ListRootsRequest::SerializePayload() const { JsonValue payload; if(m_nextTokenHasBeenSet) { payload.WithString("NextToken", m_nextToken); } if(m_maxResultsHasBeenSet) { payload.WithInteger("MaxResults", m_maxResults); } return payload.WriteReadable(); } Aws::Http::HeaderValueCollection ListRootsRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSOrganizationsV20161128.ListRoots")); return headers; }
[ "henso@amazon.com" ]
henso@amazon.com
326b01bf404d7743c5c5da2ba4d9db3f47e6fc1a
79dd503a760429f0ad9f267ab16de7451ce1764b
/src/broker.hxx
ec7fe4c5f48a23ea24b5a49b6908dc311dc74d9f
[]
no_license
GunioRobot/Http-Simple-Server
20c174eb06f31f023c76d55df936c6b9a83c3fea
1d9ea23fe2d43b1f78d58cbdcf0b8c76e459a749
refs/heads/master
2020-04-06T03:44:54.636439
2011-02-21T21:31:18
2011-02-21T21:31:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
579
hxx
/* LICENSE resumo curto: você pode fazer o que quiser com o código desde que cite o autor. author: Kayo Hamid */ /* BROKER.HXX categoria: interface. info: usado pelo LOGGER para finalizar a aplicacao quando o LOGGER receber alguma mensagem de falha. sera responsavel por requisitar informacoes necessarias para efetuar um restart no servidor. Caso o servidor falhe em seguida pelo mesmo erro, broker vai conseguir identificar isso, para a aplicacao e dar informacoes ao administrador. */ class broker { public: broker(); ~broker(); private: protected: };
[ "jayrmotta@gmail.com" ]
jayrmotta@gmail.com
eef1b824b8e0aba1de584694c65dda19e20227b7
a4527a5510628a49ecf3ce89461d9d89aa7de2ad
/Codechef/codechef.cpp
36a2ad2f6b14dd58b7d3853d239bdf5b0d82ba13
[ "MIT" ]
permissive
ujjwalgulecha/Coding
66ecc42bdb632619b3811e312bc9564edbfb1b84
d04c19d8f673749a00c85cd5e8935960fb7e8b16
refs/heads/master
2020-12-24T13:17:11.907400
2017-02-05T21:57:43
2017-02-05T21:57:43
32,799,802
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
cpp
<<<<<<< HEAD #include<iostream> #include<algorithm> using namespace std; int main() { int n,j=0,t,i,l=0,count,s,w[100],max[100]; cin>>n; while(n--) { count=0; cin>>t; for(i=0;i<t;i++) cin>>w[i]; for(i=0;i<t;i++) cin>>max[i]; sort(w,w+t); sort(max,max+t); for(i=0;i<t;i++) { for(j=0;j<t;j++) { if(w[i]<=max[j]) { count++; max[j]=0; break; } } } cout<<count<<endl; } return 0; } ======= #include<iostream> #include<algorithm> using namespace std; int main() { int n,j=0,t,i,l=0,count,s,w[100],max[100]; cin>>n; while(n--) { count=0; cin>>t; for(i=0;i<t;i++) cin>>w[i]; for(i=0;i<t;i++) cin>>max[i]; sort(w,w+t); sort(max,max+t); for(i=0;i<t;i++) { for(j=0;j<t;j++) { if(w[i]<=max[j]) { count++; max[j]=0; break; } } } cout<<count<<endl; } return 0; } >>>>>>> efd4245fe427ffeefe49c72470b81a015d8dcf82
[ "ujjwal.gulecha@gmail.com" ]
ujjwal.gulecha@gmail.com
bfec6170a1c1b14f2f107c6cfca572b0795cc7c0
30efafd0aeaba4dee203404bd285144508ba340f
/[Dorb]Operation_Kerberos_ACE3.Altis/ui/menu.h
7358ad8ec3272ba20c028f165aaba5ae763d901e
[]
no_license
kitoma/Operation_Kerberos
1df2d865e524928751395f6bd46aeb7466052929
7f47a791b36916671b85f99af7d761f0366ef9f8
refs/heads/master
2020-12-24T20:10:04.833387
2015-08-08T09:28:23
2015-08-08T09:28:23
40,403,746
0
0
null
2015-08-08T13:30:32
2015-08-08T13:30:31
SQF
UTF-8
C++
false
false
48,112
h
#define teleport_start 470470 // vehiclespawn = 600100 // CRATE = 600200 // Task_force = 700200 class dorb_veh_spawn { idd = 600100; name = "spawndialog"; movingEnable = 0; enableSimulation = 1; fadein = 0; fadeout = 0; duration = 1000000; objects[] = {}; onLoad = "uiNamespace setVariable ['dorb_spawnMenu', _this select 0]; ['dorb_spawnMenu', true] call dorb_fnc_disp_blur;"; onUnload = " ['dorb_spawnMenu', false] call dorb_fnc_disp_blur;"; controlsBackground[] = { spawn_CenterBackground, spawn_RightBackground }; controls[] = { spawn_HeaderBackground, spawn_Fahrzeug, spawn_bttn_moveIn, spawn_Fahrzeug_pic, spawn_bttn_spawn, spawn_listbox }; class spawn_CenterBackground: dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_x(0)+_get_screen_h(0.2); w = _get_screen_w(0.46); h = _get_screen_h(0.5); text = ""; colorBackground[] = UI_CL_BODY; }; class spawn_RightBackground: spawn_CenterBackground { x = _get_screen_x(0)+_get_screen_w(0.565); y = _get_screen_x(0)+_get_screen_h(0.305); w = _get_screen_w(0.235); h = _get_screen_h(0.395); }; class spawn_Fahrzeug : spawn_RightBackground { idc = 600103; y = _get_screen_y(0)+_get_screen_h(0.2); h = _get_screen_h(0.1); sizeEx = _get_screen_h(0.027); colorText[] = UI_CL_TEXT_DARK; colorBackground[]=UI_CL_HEADER2; text = ""; }; class spawn_Fahrzeug_pic : dorb_gui_pictureBase { idc = 600104; x = _get_screen_x(0)+_get_screen_w(0.598125); y = _get_screen_x(0)+_get_screen_h(0.315); w = _get_screen_w(0.16875); h = _get_screen_h(0.225); colorText[] = UI_CL_CTRL_GRAU3; colorBackground[]=UI_CL_BODY; text = "data\icon\icon_heli.paa"; }; class spawn_HeaderBackground: spawn_CenterBackground { idc = 600101; y = _get_screen_y(0)+_get_screen_h(0.1); w = _get_screen_w(0.7); h = _get_screen_h(0.09); text = ""; colorText[] = UI_CL_HEADER_TEXT; colorBackground[] = UI_CL_HEADER; }; class spawn_listbox : dorb_gui_listboxN { idc = 600102; x = _get_screen_x(0)+_get_screen_w(0.115); y = _get_screen_y(0)+_get_screen_h(0.215); w = _get_screen_w(0.43); h = _get_screen_h(0.46); rowHeight = _get_screen_h(0.035); sizeEx = _get_screen_h(0.025); columns[] = {0.0,_get_screen_w(0.08),_get_screen_w(0.14),0.0}; onLBSelChanged = "_this spawn dorb_fnc_ui_spawn_select;"; default = true; }; class spawn_bttn_moveIn : dorb_gui_button { idc = 600105; x = _get_screen_x(0)+_get_screen_w(0.58); y = _get_screen_y(0)+_get_screen_h(0.55); w = _get_screen_w(0.205); h = _get_screen_h(0.06); style = ST_CENTER; sizeEx = _get_screen_h(0.03); text = "$STR_DORB_SPAWN_DRIVER"; colorBackground[] = UI_CL_BTN6_foc; colorBackgroundActive[] = UI_CL_BTN6_foc; colorShadow[] = UI_CL_BTN6; colorFocused[] = UI_CL_BTN6_foc; default = false; shadow = 1; onMouseEnter = ""; onMouseExit = ""; action = "[""driver""]call dorb_fnc_ui_spawn_create;"; }; class spawn_bttn_spawn : spawn_bttn_moveIn { idc = 600106; y = _get_screen_y(0)+_get_screen_h(0.615); text = "$STR_DORB_SPAWN_EMPTY"; colorBackground[] = UI_CL_BTN2_foc; colorBackgroundActive[] = UI_CL_BTN2_foc; colorShadow[] = UI_CL_BTN2; colorFocused[] = UI_CL_BTN2_foc; onSetFocus = ""; action = "[]call dorb_fnc_ui_spawn_create;"; }; }; #define TELEPORT_SPALTE1 _get_screen_x(0)+_get_screen_w(0.14) #define TELEPORT_SPALTE2 _get_screen_x(0)+_get_screen_w(0.36) #define TELEPORT_SPALTE3 _get_screen_x(0)+_get_screen_w(0.58) #define TELEPORT_REIHE1 _get_screen_y(0)+_get_screen_h(0.25) #define TELEPORT_REIHE2 _get_screen_y(0)+_get_screen_h(0.4) #define TELEPORT_REIHE3 _get_screen_y(0)+_get_screen_h(0.55) class dorb_teleporter { idd = 600300; name = "Teleporter"; movingEnable = 0; enableSimulation = 1; fadein = 0; fadeout = 0; duration = 1000000; objects[] = {}; onLoad = "uiNamespace setVariable ['dorb_teleportMenu', _this select 0]; ['dorb_teleportMenu', true] call dorb_fnc_disp_blur; [] spawn dorb_fnc_ui_teleport_onLoad"; onUnload = " ['dorb_teleportMenu', false] call dorb_fnc_disp_blur;"; controlsBackground[] = { teleport_CenterBackground, teleport_HeaderBackground }; controls[] = { teleport_bttn1, teleport_bttn2, teleport_bttn3, teleport_bttn4, teleport_bttn5, teleport_bttn6, teleport_bttn7 }; class teleport_CenterBackground: dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_x(0)+_get_screen_h(0.2); w = _get_screen_w(0.7); h = _get_screen_h(0.5); text = ""; colorBackground[] = UI_CL_BODY; }; class teleport_HeaderBackground: teleport_CenterBackground { y = _get_screen_y(0)+_get_screen_h(0.1); w = _get_screen_w(0.7); h = _get_screen_h(0.09); text = "Teleporter"; colorText[] = UI_CL_HEADER_TEXT; colorBackground[] = UI_CL_HEADER; }; class teleport_bttn1 : dorb_gui_button { idc = 600301; x = TELEPORT_SPALTE1; y = TELEPORT_REIHE1; w = _get_screen_w(0.17); h = _get_screen_h(0.08); sizeEx = _get_screen_h(0.04); text = ""; colorBackground[] = UI_CL_BTN1; colorBackgroundActive[] = UI_CL_BTN1_foc; colorFocused[] = UI_CL_BTN1; colorText[] = UI_CL_TEXT_DARK; }; class teleport_bttn2 : teleport_bttn1 { idc = 600302; y = TELEPORT_REIHE2; text = ""; colorBackground[] = UI_CL_BTN2; colorBackgroundActive[] = UI_CL_BTN2_foc; colorFocused[] = UI_CL_BTN2; colorText[] = UI_CL_TEXT; }; class teleport_bttn3 : teleport_bttn1 { idc = 600303; x = TELEPORT_SPALTE2; y = TELEPORT_REIHE1; text = ""; colorBackground[] = UI_CL_BTN3; colorBackgroundActive[] = UI_CL_BTN3_foc; colorFocused[] = UI_CL_BTN3; colorText[] = UI_CL_TEXT_DARK; }; class teleport_bttn4 : teleport_bttn3 { idc = 600304; y = TELEPORT_REIHE2; text = ""; colorBackground[] = UI_CL_BTN4; colorBackgroundActive[] = UI_CL_BTN4_foc; colorFocused[] = UI_CL_BTN4; colorText[] = UI_CL_TEXT; }; class teleport_bttn5 : teleport_bttn1 { idc = 600305; x = TELEPORT_SPALTE3; y = TELEPORT_REIHE1; text = ""; colorBackground[] = UI_CL_BTN5; colorBackgroundActive[] = UI_CL_BTN5_foc; colorFocused[] = UI_CL_BTN5; colorText[] = UI_CL_TEXT; }; class teleport_bttn6 : teleport_bttn5 { idc = 600306; y = TELEPORT_REIHE2; text = ""; colorBackground[] = UI_CL_BTN6; colorBackgroundActive[] = UI_CL_BTN6_foc; colorFocused[] = UI_CL_BTN6; colorText[] = UI_CL_TEXT; }; class teleport_bttn7 : teleport_bttn1 { idc = 600307; y = TELEPORT_REIHE3; x = _get_screen_x(0)+_get_screen_w(0.28); w = _get_screen_w(0.34); text = ""; colorBackground[] = UI_CL_BTN7; colorBackgroundActive[] = UI_CL_BTN7_foc; colorFocused[] = UI_CL_BTN7; colorText[] = UI_CL_TEXT; }; }; class dorb_teleport { idd = 470470; name = "teleport_tafel"; movingEnable = 0; enableSimulation = 1; fadein = 0; fadeout = 0; duration = 1000000; objects[] = {}; onLoad = ""; onUnload = ""; controlsBackground[] = { dorb_teleport_body, dorb_teleport_header }; controls[] = { dorb_teleport_base_btn //dorb_teleport_base_pic, //dorb_teleport_tank_btn, //dorb_teleport_tank_pic, //dorb_teleport_heli_btn, //dorb_teleport_heli_pic, //dorb_teleport_drone_btn, //dorb_teleport_drone_pic, //dorb_teleport_harbour_btn, //dorb_teleport_harbour_pic, //dorb_teleport_logistik_btn, //dorb_teleport_logistik_pic }; class dorb_teleport_body : dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.2); y = _get_screen_x(0)+_get_screen_h(0.2); w = _get_screen_w(0.6); h = _get_screen_h(0.49); text = ""; colorBackground[] = UI_CL_BODY; }; class dorb_teleport_header : dorb_teleport_body { idc = -1; y = _get_screen_y(0)+_get_screen_h(0.1); h = _get_screen_h(0.09); text = "Teleport"; colorText[] = UI_CL_HEADER_TEXT; colorBackground[] = UI_CL_HEADER; }; class dorb_teleport_base_btn : dorb_gui_button { idc = 470471; x = _get_screen_x(0)+_get_screen_w(0.22); y = _get_screen_y(0)+_get_screen_h(0.22); w = _get_screen_w(0.136); h = _get_screen_h(0.17); style = ST_PICTURE; sizeEx = _get_screen_h(0.17); text = "A3\ui_f\data\gui\cfg\Hints\gear_ca.paa"; colorBackground[] = UI_CL_BTN2_foc; colorShadow[] = UI_CL_BTN2; colorBackgroundActive[] = {1,0,1,1}; colorText[] = {1,0,0,1}; shadow = 0; colorBorder[] = {0,1,0,1}; colorFocused[] = {0,1,1,1}; //onMouseEnter = "[""enter"", _this select 0] call basis_fnc_teleport_logic;"; //onMouseExit = "[""exit"", _this select 0] call basis_fnc_teleport_logic;"; //onButtonClick = "[""click"", _this select 0] call basis_fnc_teleport_logic;"; // animTextureNormal = "#(argb,8,8,3)color(0,0,0,0)"; //animTextureDisabled = "#(argb,8,8,3)color(0,0,0,0)"; //animTextureOver = "#(argb,8,8,3)color(0,0,0,0)"; //animTextureFocused = "#(argb,8,8,3)color(0,0,0,0)"; //animTexturePressed = "#(argb,8,8,3)color(0,0,0,0)"; //animTextureDefault = "#(argb,8,8,3)color(0,0,0,0)"; //textureNoShortcut = "#(argb,8,8,3)color(0,0,0,0)"; }; class dorb_teleport_base_pic: dorb_gui_pictureBase { idc = 470472; x = _get_screen_x(0)+_get_screen_w(0.24); y = _get_screen_y(0)+_get_screen_h(0.25); w = _get_screen_w(0.136); h = _get_screen_h(0.17); colorText[] = UI_CL_TEXT; text = "basis\data\icon\icon_base.paa"; }; ///// class dorb_teleport_tank_btn : dorb_teleport_base_btn { idc = 470473; y = _get_screen_y(0)+_get_screen_h(0.47); colorBackground[] = UI_CL_BTN3_foc; colorShadow[] = UI_CL_BTN3; }; class dorb_teleport_tank_pic : dorb_teleport_base_pic { idc = 470474; y = _get_screen_y(0)+_get_screen_h(0.47); text = "basis\data\icon\icon_tank.paa"; colorText[] = UI_CL_TEXT_DARK; }; ///// class dorb_teleport_heli_btn : dorb_teleport_base_btn { idc = 470475; x = _get_screen_x(0)+_get_screen_w(0.4); y = _get_screen_y(0)+_get_screen_h(0.22); colorBackground[] = UI_CL_BTN6_foc; colorShadow[] = UI_CL_BTN6; }; class dorb_teleport_heli_pic : dorb_teleport_base_pic { idc = 470476; x = _get_screen_x(0)+_get_screen_w(0.4); y = _get_screen_y(0)+_get_screen_h(0.22); text = "basis\data\icon\icon_heli.paa"; }; ///// class dorb_teleport_drone_btn : dorb_teleport_heli_btn { idc = 470477; y = _get_screen_y(0)+_get_screen_h(0.47); colorBackground[] = UI_CL_BTN5_foc; colorShadow[] = UI_CL_BTN5; }; class dorb_teleport_drone_pic : dorb_teleport_heli_pic { idc = 470478; y = _get_screen_y(0)+_get_screen_h(0.47); text = "basis\data\icon\icon_drone.paa"; }; ///// class dorb_teleport_harbour_btn : dorb_teleport_base_btn { idc = 470479; x = _get_screen_x(0)+_get_screen_w(0.58); y = _get_screen_y(0)+_get_screen_h(0.22); colorBackground[] = UI_CL_BTN4_foc; colorShadow[] = UI_CL_BTN4; }; class dorb_teleport_harbour_pic : dorb_teleport_base_pic { idc = 470480; x = _get_screen_x(0)+_get_screen_w(0.58); y = _get_screen_y(0)+_get_screen_h(0.22); text = "basis\data\icon\icon_harbour.paa"; }; ///// class dorb_teleport_logistik_btn : dorb_teleport_harbour_btn { idc = 470481; y = _get_screen_y(0)+_get_screen_h(0.47); colorBackground[] = UI_CL_BTN7_foc; colorShadow[] = UI_CL_BTN7; }; class dorb_teleport_logistik_pic : dorb_teleport_harbour_pic { idc = 470482; y = _get_screen_y(0)+_get_screen_h(0.47); text = "basis\data\icon\icon_logistik.paa"; }; }; #define CRATE_SPALTE1 _get_screen_x(0)+_get_screen_w(0.11) #define CRATE_SPALTE2 _get_screen_x(0)+_get_screen_w(0.14988) #define CRATE_REIHE1 _get_screen_y(0)+_get_screen_h(0.21) #define CRATE_REIHE2 _get_screen_y(0)+_get_screen_h(0.2615) #define CRATE_REIHE3 _get_screen_y(0)+_get_screen_h(0.313) #define CRATE_REIHE4 _get_screen_y(0)+_get_screen_h(0.3645) #define CRATE_REIHE5 _get_screen_y(0)+_get_screen_h(0.416) #define CRATE_REIHE6 _get_screen_y(0)+_get_screen_h(0.4675) #define CRATE_REIHE7 _get_screen_y(0)+_get_screen_h(0.519) #define CRATE_REIHE8 _get_screen_y(0)+_get_screen_h(0.5705) #define CRATE_REIHE9 _get_screen_y(0)+_get_screen_h(0.622) #define CRATE_REIHE10 _get_screen_y(0)+_get_screen_h(0.6735) #define CRATE_BTTN_W _get_screen_w(0.03488) #define CRATE_BTTN_H _get_screen_h(0.0465) class dorb_crate_alt { idd = 600200; name = "Kisten-Füller"; /// von Dorbedo - wer das Ding nutzen will: Fragen! movingEnable = 0; enableSimulation = 1; fadein = 0; fadeout = 0; duration = 1000000; objects[] = {}; onLoad = "uiNamespace setVariable ['dorb_crateMenu', _this select 0]; ['dorb_crateMenu', true] call dorb_fnc_disp_blur; [] spawn dorb_fnc_ui_crate_OnLoad;"; onUnload = " ['dorb_crateMenu', false] call dorb_fnc_disp_blur;"; controlsBackground[] = { crate_CenterBackground, crate_RightCenterBackground, crate_HeaderBackground, crate_BottemLeftBackground, crate_BottemRightBackground, crate_ListBackground }; controls[] = { crate_combo_box, crate_progessbar, crate_listbox, crate_list_button_add, crate_list_button_sub, crate_spawn, crate_clear, crate_button1, crate_button2, crate_button3, crate_button4, crate_button5, crate_button6, crate_button7, crate_button8, crate_button9, crate_button10, crate_button11, crate_button12, crate_button13, crate_button14, crate_button15, crate_button16, crate_button17, crate_button18, crate_button19, //crate_button20, crate_backgroung_pic1, crate_backgroung_pic2, crate_backgroung_pic3, crate_backgroung_pic4, crate_backgroung_pic5, crate_backgroung_pic6, crate_backgroung_pic7, crate_backgroung_pic8, crate_backgroung_pic9, crate_backgroung_pic10, crate_backgroung_pic11, crate_backgroung_pic12, crate_backgroung_pic13, crate_backgroung_pic14, crate_backgroung_pic15, crate_backgroung_pic16, crate_backgroung_pic17, crate_backgroung_pic18, crate_backgroung_pic19, //crate_backgroung_pic20, crate_pic1, crate_pic2, crate_pic3, crate_pic4, crate_pic5, crate_pic6, crate_pic7, crate_pic8, crate_pic9, crate_pic10, crate_pic11, crate_pic12, crate_pic13, crate_pic14, crate_pic15, crate_pic16, crate_pic17, crate_pic18, crate_pic19//, //crate_pic20 }; class crate_CenterBackground: dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_y(0)+_get_screen_h(0.2); w = _get_screen_w(0.09476); h = _get_screen_h(0.53); text = ""; colorBackground[] = UI_CL_BODY; colorText[] = UI_CL_BODY_TEXT; }; class crate_RightCenterBackground: crate_CenterBackground { x = _get_screen_x(0)+_get_screen_w(0.19976); w = _get_screen_w(0.70024); }; class crate_BottemLeftBackground: dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_y(0)+_get_screen_h(0.74); w = _get_screen_w(0.395); h = _get_screen_h(0.16); text = ""; colorBackground[] = UI_CL_BODY; colorText[] = UI_CL_BODY_TEXT; }; class crate_BottemRightBackground: dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.505); y = _get_screen_y(0)+_get_screen_h(0.74); w = _get_screen_w(0.395); h = _get_screen_h(0.16); text = ""; colorBackground[] = UI_CL_BODY; colorText[] = UI_CL_BODY_TEXT; }; class crate_HeaderBackground: crate_CenterBackground { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_y(0)+_get_screen_h(0.1); w = _get_screen_w(0.8); h = _get_screen_h(0.09); text = "$STR_DORB_CRATE_HEADER"; colorText[] = UI_CL_HEADER_TEXT; colorBackground[] = UI_CL_HEADER; }; class crate_spawn : dorb_gui_button { idc = 600206; x = _get_screen_x(0)+_get_screen_w(0.525); y = _get_screen_y(0)+_get_screen_h(0.755); w = _get_screen_w(0.14); h = _get_screen_h(0.06); text = "$STR_DORB_CRATE_SPAWN"; sizeEx = _get_screen_h(0.03); colorBackground[] = UI_CL_BTN2_foc; colorBackgroundActive[] = UI_CL_BTN2_foc; colorShadow[] = UI_CL_BTN2; colorFocused[] = UI_CL_BTN2_foc; action = "[true]call dorb_fnc_ui_crate_spawn;false"; }; class crate_clear : crate_spawn { idc = 600207; x = _get_screen_x(0)+_get_screen_w(0.725); text = "$STR_DORB_CRATE_CLEAR"; action = "DORB_CRATE_CURRENT=[[],[],[],[],[],[]];DORB_CRATE_CURRENT_BOXID=0;[]call dorb_fnc_ui_crate_OnLoad;false"; }; class crate_list_button_add : crate_spawn { idc = 1000; text = "+"; borderSize = 0; colorShadow[] = {0,0,0,0}; action = "[true]call dorb_fnc_crate_add;false"; }; class crate_list_button_sub : crate_list_button_add { idc = 1001; text = "-"; action = "[false]call dorb_fnc_crate_add;false"; }; class crate_ListBackground: crate_CenterBackground { x = _get_screen_x(0)+_get_screen_w(0.20976); y = _get_screen_y(0)+_get_screen_h(0.21); w = _get_screen_w(0.68024); h = _get_screen_h(0.51); colorText[] = UI_CL_HEADER_TEXT; colorBackground[] = UI_CL_CTRL_GRAU2; }; class crate_listbox : dorb_gui_listboxN { idc = 600201; access = 2; x = _get_screen_x(0)+_get_screen_w(0.21976); y = _get_screen_y(0)+_get_screen_h(0.22); w = _get_screen_w(0.66024); h = _get_screen_h(0.49); rowHeight = _get_screen_h(0.035); sizeEx = _get_screen_h(0.022); columns[] = {_get_screen_w(0.027),_get_screen_w(0.09),_get_screen_w(0.15),_get_screen_w(0.55)}; //colorText[] = UI_CL_BODY_TEXT; //colorBackground[] = {0.5, 0.5, 0, 1}; //shadow = 1; // color[] = {0.5, 0.5, 0, 1}; // colorScrollbar[] = {0.8, 0.8, 0.8, 1}; //colorSelect[] = {0.8, 0.8, 0.8, 1}; //colorSelect2[] = {0.8, 0.8, 0.8, 1}; //colorSelectBackground[] = {0, 0, 0, 1}; //colorSelectBackground2[] = {0.8784, 0.8471, 0.651, 1}; drawSideArrows = 1; // 1 to draw buttons linked by idcLeft and idcRight on both sides of selected line. They are resized to line height idcLeft = 1001; // Left button IDC idcRight = 1000; //onCanDestroy = "systemChat str ['onCanDestroy',_this]; true"; //onDestroy = "systemChat str ['onDestroy',_this]; false"; //onSetFocus = "systemChat str ['onSetFocus',_this]; false"; //onKillFocus = "systemChat str ['onKillFocus',_this]; false"; //onKeyDown = "systemChat str ['onKeyDown',_this]; false"; //onKeyUp = "systemChat str ['onKeyUp',_this]; false"; //onMouseButtonDown = "systemChat str ['onMouseButtonDown',_this]; false"; //onMouseButtonUp = "systemChat str ['onMouseButtonUp',_this]; false"; //onMouseButtonClick = "systemChat str ['onMouseButtonClick',_this]; false"; //onMouseButtonDblClick = "systemChat str ['onMouseButtonDblClick',_this]; false"; //onMouseZChanged = "systemChat str ['onMouseZChanged',_this]; false"; //onMouseMoving = ""; //onMouseHolding = ""; //onLBSelChanged = "systemChat str ['onLBSelChanged',_this]; false"; //onLBDblClick = "systemChat str ['onLBDblClick',_this]; false"; }; class crate_combo_box : dorb_gui_combo { idc = 600205; x = _get_screen_x(0)+_get_screen_w(0.11); y = _get_screen_y(0)+_get_screen_h(0.85); w = _get_screen_w(0.375); h = _get_screen_h(0.03); sizeEx = _get_screen_h(0.025); rowHeight = _get_screen_h(0.025); wholeHeight = _get_screen_h(0.2); onLBSelChanged = "DORB_CRATE_CURRENT_BOXID=(_this select 1);['changebox',_config] call dorb_fnc_ui_crate_mass;;false"; }; class crate_progessbar : dorb_gui_loadingbarBase { idc = 600204; x = _get_screen_x(0)+_get_screen_w(0.11); y = _get_screen_y(0)+_get_screen_h(0.78); w = _get_screen_w(0.375); h = _get_screen_h(0.03); }; class crate_button1 : dorb_gui_button { idc = 600211; x = CRATE_SPALTE1; y = CRATE_REIHE1; w = CRATE_BTTN_W; h = CRATE_BTTN_H; shadow = 0; colorBackground[] = {0.6,0.6,0.6,0}; colorBackgroundActive[] = {0.6,0.6,0.6,0}; colorFocused[] = {0.6,0.6,0.6,0}; colorBackgroundDisabled[] = {0.6,0.6,0.6,0}; colorShadow[] = {0,0,0,0}; colorBorder[] = {0,0,0,0}; toolTip = "$STR_DORB_CRATE_BTTN_1"; }; class crate_backgroung_pic1 : dorb_gui_backgroundBase { idc = 600251; x = CRATE_SPALTE1; y = CRATE_REIHE1; w = CRATE_BTTN_W; h = CRATE_BTTN_H; colorText[] = UI_CL_CTRL_GRAU1; colorBackground[] = UI_CL_CTRL_GRAU4; text = ""; }; class crate_pic1 : dorb_gui_pictureBase { idc = 600231; x = CRATE_SPALTE1; y = CRATE_REIHE1; w = CRATE_BTTN_W; h = CRATE_BTTN_H; colorText[] = UI_CL_CTRL_GRAU1; colorBackground[] = UI_CL_CTRL_GRAU1; shadow = 0; text = "\A3\ui_f\data\IGUI\Cfg\MPTable\total_ca.paa"; }; class crate_button2 : crate_button1 { idc = 600212; x = CRATE_SPALTE2; y = CRATE_REIHE1; toolTip = "$STR_DORB_CRATE_BTTN_2"; }; class crate_backgroung_pic2 : crate_backgroung_pic1 { idc = 600252; x = CRATE_SPALTE2; y = CRATE_REIHE1; colorText[] = UI_CL_CTRL_GRAU1; colorBackground[] = UI_CL_CTRL_GRAU1; text = ""; }; class crate_pic2 : crate_pic1 { idc = 600232; x = CRATE_SPALTE2; y = CRATE_REIHE1; colorText[] = UI_CL_CTRL_GRAU4; colorBackground[] = UI_CL_CTRL_GRAU1; //text = "\A3\ui_f\data\gui\Rsc\RscDisplayArsenal\primaryweapon_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\rifle_ca.paa"; }; class crate_button3 : crate_button1 { idc = 600213; x = CRATE_SPALTE1; y = CRATE_REIHE2; toolTip = "$STR_DORB_CRATE_BTTN_3"; }; class crate_backgroung_pic3 : crate_backgroung_pic2 { idc = 600253; x = CRATE_SPALTE1; y = CRATE_REIHE2; text = ""; }; class crate_pic3 : crate_pic2 { idc = 600233; x = CRATE_SPALTE1; y = CRATE_REIHE2; //text = "\A3\ui_f\data\gui\Rsc\RscDisplayArsenal\handgun_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\rifles_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\automatic_ca.paa"; }; class crate_button4 : crate_button1 { idc = 600214; x = CRATE_SPALTE2; y = CRATE_REIHE2; toolTip = "$STR_DORB_CRATE_BTTN_4"; }; class crate_backgroung_pic4 : crate_backgroung_pic2 { idc = 600254; x = CRATE_SPALTE2; y = CRATE_REIHE2; text = ""; }; class crate_pic4 : crate_pic2 { idc = 600234; x = CRATE_SPALTE2; y = CRATE_REIHE2; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\secondaryweapon_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\shotguns_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\sniper_ca.paa"; }; class crate_button5 : crate_button1 { idc = 600215; x = CRATE_SPALTE1; y = CRATE_REIHE3; toolTip = "$STR_DORB_CRATE_BTTN_5"; }; class crate_backgroung_pic5 : crate_backgroung_pic2 { idc = 600255; x = CRATE_SPALTE1; y = CRATE_REIHE3; text = ""; }; class crate_pic5 : crate_pic2 { idc = 600235; x = CRATE_SPALTE1; y = CRATE_REIHE3; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\itemoptic_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\sniper_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\shotguns_ca.paa"; }; class crate_button6 : crate_button1 { idc = 600216; x = CRATE_SPALTE2; y = CRATE_REIHE3; toolTip = "$STR_DORB_CRATE_BTTN_6"; }; class crate_backgroung_pic6 : crate_backgroung_pic2 { idc = 600256; x = CRATE_SPALTE2; y = CRATE_REIHE3; text = ""; }; class crate_pic6 : crate_pic2 { idc = 600236; x = CRATE_SPALTE2; y = CRATE_REIHE3; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\itemmuzzle_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\ranged_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\launcher_ca.paa"; }; class crate_button7 : crate_button1 { idc = 600217; x = CRATE_SPALTE1; y = CRATE_REIHE4; toolTip = "$STR_DORB_CRATE_BTTN_7"; }; class crate_backgroung_pic7 : crate_backgroung_pic2 { idc = 600257; x = CRATE_SPALTE1; y = CRATE_REIHE4; text = ""; }; class crate_pic7 : crate_pic2 { idc = 600237; x = CRATE_SPALTE1; y = CRATE_REIHE4; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\itemacc_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\launcher_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\handgun_ca.paa"; }; class crate_button8 : crate_button1 { idc = 600218; x = CRATE_SPALTE2; y = CRATE_REIHE4; toolTip = "$STR_DORB_CRATE_BTTN_8"; }; class crate_backgroung_pic8 : crate_backgroung_pic2 { idc = 600258; x = CRATE_SPALTE2; y = CRATE_REIHE4; text = ""; }; class crate_pic8 : crate_pic2 { idc = 600238; x = CRATE_SPALTE2; y = CRATE_REIHE4; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\cargomag_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\automatic_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\optics_ca.paa"; }; class crate_button9 : crate_button1 { idc = 600219; x = CRATE_SPALTE1; y = CRATE_REIHE5; toolTip = "$STR_DORB_CRATE_BTTN_9"; }; class crate_backgroung_pic9 : crate_backgroung_pic2 { idc = 600259; x = CRATE_SPALTE1; y = CRATE_REIHE5; text = ""; }; class crate_pic9 : crate_pic2 { idc = 600239; x = CRATE_SPALTE1; y = CRATE_REIHE5; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\cargoput_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\handgun_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\grenades_ca.paa"; }; class crate_button10 : crate_button1 { idc = 600220; x = CRATE_SPALTE2; y = CRATE_REIHE5; toolTip = "$STR_DORB_CRATE_BTTN_10"; }; class crate_backgroung_pic10 : crate_backgroung_pic2 { idc = 6002560; x = CRATE_SPALTE2; y = CRATE_REIHE5; text = ""; }; class crate_pic10 : crate_pic2 { idc = 600240; x = CRATE_SPALTE2; y = CRATE_REIHE5; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\cargothrow_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\grenades_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\ieds_ca.paa"; }; class crate_button11 : crate_button1 { idc = 600221; x = CRATE_SPALTE1; y = CRATE_REIHE6; toolTip = "$STR_DORB_CRATE_BTTN_11"; }; class crate_backgroung_pic11 : crate_backgroung_pic2 { idc = 600261; x = CRATE_SPALTE1; y = CRATE_REIHE6; text = ""; }; class crate_pic11 : crate_pic2 { idc = 600241; x = CRATE_SPALTE1; y = CRATE_REIHE6; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\gps_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\ammotype_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\gear_ca.paa"; }; class crate_button12 : crate_button1 { idc = 600222; x = CRATE_SPALTE2; y = CRATE_REIHE6; toolTip = "$STR_DORB_CRATE_BTTN_12"; }; class crate_backgroung_pic12 : crate_backgroung_pic1 { idc = 600262; x = CRATE_SPALTE2; y = CRATE_REIHE6; text = ""; }; class crate_pic12 : crate_pic1 { idc = 600242; x = CRATE_SPALTE2; y = CRATE_REIHE6; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\cargomisc_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\muzzles_ca.paa"; text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\vest_ca.paa"; }; class crate_button13 : crate_button1 { idc = 600223; x = CRATE_SPALTE1; y = CRATE_REIHE7; toolTip = "$STR_DORB_CRATE_BTTN_13"; }; class crate_backgroung_pic13 : crate_backgroung_pic1 { idc = 600263; x = CRATE_SPALTE1; y = CRATE_REIHE7; text = ""; }; class crate_pic13 : crate_pic1 { idc = 600243; x = CRATE_SPALTE1; y = CRATE_REIHE7; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\nvgs_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\pointer_ca.paa"; text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\uniform_ca.paa"; }; class crate_button14 : crate_button1 { idc = 600224; x = CRATE_SPALTE2; y = CRATE_REIHE7; toolTip = "$STR_DORB_CRATE_BTTN_14"; }; class crate_backgroung_pic14 : crate_backgroung_pic1 { idc = 600264; x = CRATE_SPALTE2; y = CRATE_REIHE7; text = ""; }; class crate_pic14 : crate_pic1 { idc = 600244; x = CRATE_SPALTE2; y = CRATE_REIHE7; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\binoculars_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\pointers_ca.paa"; text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\headgear_ca.paa"; }; class crate_button15 : crate_button1 { idc = 600225; x = CRATE_SPALTE1; y = CRATE_REIHE8; toolTip = "$STR_DORB_CRATE_BTTN_15"; }; class crate_backgroung_pic15 : crate_backgroung_pic1 { idc = 600265; x = CRATE_SPALTE1; y = CRATE_REIHE8; text = ""; }; class crate_pic15 : crate_pic1 { idc = 600245; x = CRATE_SPALTE1; y = CRATE_REIHE8; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\goggles_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\ieds_ca.paa"; text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\radio_ca.paa"; }; class crate_button16 : crate_button1 { idc = 600226; x = CRATE_SPALTE2; y = CRATE_REIHE8; toolTip = "$STR_DORB_CRATE_BTTN_16"; }; class crate_backgroung_pic16 : crate_backgroung_pic2 { idc = 600266; x = CRATE_SPALTE2; y = CRATE_REIHE8; text = ""; }; class crate_pic16 : crate_pic2 { idc = 600246; x = CRATE_SPALTE2; y = CRATE_REIHE8; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\radio_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\map_ca.paa"; }; class crate_button17 : crate_button1 { idc = 600227; x = CRATE_SPALTE1; y = CRATE_REIHE9; toolTip = "$STR_DORB_CRATE_BTTN_17"; }; class crate_backgroung_pic17 : crate_backgroung_pic2 { idc = 600267; x = CRATE_SPALTE1; y = CRATE_REIHE9; text = ""; }; class crate_pic17 : crate_pic2 { idc = 600247; x = CRATE_SPALTE1; y = CRATE_REIHE9; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\uniform_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\injury_ca.paa"; }; class crate_button18 : crate_button1 { idc = 600228; x = CRATE_SPALTE2; y = CRATE_REIHE9; toolTip = "$STR_DORB_CRATE_BTTN_18"; }; class crate_backgroung_pic18 : crate_backgroung_pic2 { idc = 600268; x = CRATE_SPALTE2; y = CRATE_REIHE9; text = ""; }; class crate_pic18 : crate_pic2 { idc = 600248; x = CRATE_SPALTE2; y = CRATE_REIHE9; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\headgear_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\slots_ca.paa"; }; class crate_button19 : crate_button1 { idc = 600229; x = CRATE_SPALTE1; y = CRATE_REIHE10; toolTip = "$STR_DORB_CRATE_BTTN_19"; }; class crate_backgroung_pic19 : crate_backgroung_pic2 { idc = 600269; x = CRATE_SPALTE1; y = CRATE_REIHE10; text = ""; }; class crate_pic19 : crate_pic2 { idc = 600249; x = CRATE_SPALTE1; y = CRATE_REIHE10; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\vest_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\actionmenu_ca.paa"; }; class crate_button20 : crate_button1 { idc = 600230; x = CRATE_SPALTE2; y = CRATE_REIHE10; toolTip = "$STR_DORB_CRATE_BTTN_20"; }; class crate_backgroung_pic20 : crate_backgroung_pic2 { idc = 600270; x = CRATE_SPALTE2; y = CRATE_REIHE10; text = ""; }; class crate_pic20 : crate_pic2 { idc = 600250; x = CRATE_SPALTE2; y = CRATE_REIHE10; //text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\backpack_ca.paa"; //text = "A3\ui_f\data\gui\cfg\Hints\gear_ca.paa"; text = "A3\ui_f\data\gui\cfg\Hints\actionmenu_ca.paa"; }; }; class dorb_tfr { idd = 700200; name = "Task Force Tool"; // createDialog "dorb_tfr"; movingEnable = 0; enableSimulation = 1; fadein = 0; fadeout = 0; duration = 1000000; objects[] = {}; onLoad = "uiNamespace setVariable ['dorb_tfrMenu', _this select 0]; ['dorb_tfrMenu', true] call dorb_fnc_disp_blur;"; onUnload = " ['dorb_tfrMenu', false] call dorb_fnc_disp_blur; ['DORB_TFR_onOpenEH', 'onEachFrame'] call BIS_fnc_removeStackedEventHandler;"; controlsBackground[] = { dorb_tfr_body, dorb_tfr_body2, dorb_tfr_body3, dorb_tfr_header, dorb_tfr_frequenzen, dorb_tfr_SR_name, dorb_tfr_LR_name, //dorb_tfr_DD_name dorb_tfr_SR_name2, dorb_tfr_LR_name2, //dorb_tfr_DD_name2 dorb_tfr_frequenzen_neu, dorb_tfr_bodyLB }; controls[] = { dorb_tfr_list, dorb_tfr_SR_edit, dorb_tfr_LR_edit, //dorb_tfr_DD_edit, dorb_tfr_SR_disp, dorb_tfr_LR_disp, //dorb_tfr_DD_disp, dorb_tfr_take, dorb_tfr_set }; class dorb_tfr_body : dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_x(0)+_get_screen_h(0.2); w = _get_screen_w(0.5); h = _get_screen_h(0.52); text = ""; colorBackground[] = UI_CL_BODY; colorText[] = UI_CL_BODY_TEXT; }; class dorb_tfr_body2 : dorb_tfr_body { x = _get_screen_x(0)+_get_screen_w(0.605); y = _get_screen_x(0)+_get_screen_h(0.2625); w = _get_screen_w(0.295); h = _get_screen_h(0.1975); }; class dorb_tfr_body3 : dorb_tfr_body2 { y = _get_screen_x(0)+_get_screen_h(0.5275); h = _get_screen_h(0.1925); }; class dorb_tfr_bodyLB : dorb_tfr_body { x = _get_screen_x(0)+_get_screen_w(0.12); y = _get_screen_x(0)+_get_screen_h(0.22); w = _get_screen_w(0.46); h = _get_screen_h(0.48); colorBackground[] = UI_CL_CTRL_GRAU1; }; class dorb_tfr_header : dorb_tfr_body { idc = -1; y = _get_screen_y(0)+_get_screen_h(0.1); h = _get_screen_h(0.09); w = _get_screen_w(0.8); text = "$STR_DORB_TFR_HEADER"; colorText[] = UI_CL_HEADER_TEXT; colorBackground[] = UI_CL_HEADER; }; class dorb_tfr_frequenzen : dorb_tfr_body { x = _get_screen_x(0)+_get_screen_w(0.605); y = _get_screen_x(0)+_get_screen_h(0.2); w = _get_screen_w(0.295); h = _get_screen_h(0.06); sizeEx = _get_screen_h(0.035); text = "$STR_DORB_TFR_FREQ_SQUAD"; colorBackground[]=UI_CL_HEADER2; }; class dorb_tfr_frequenzen_neu : dorb_tfr_frequenzen { y = _get_screen_x(0)+_get_screen_h(0.465); text = "$STR_DORB_TFR_FREQ_NEW"; }; class dorb_tfr_SR_name : dorb_tfr_body { x = _get_screen_x(0)+_get_screen_w(0.62); y = _get_screen_x(0)+_get_screen_h(0.28); w = _get_screen_w(0.03); h = _get_screen_h(0.04); sizeEx = _get_screen_h(0.035); text = "SR:"; }; class dorb_tfr_LR_name : dorb_tfr_SR_name { y = _get_screen_x(0)+_get_screen_h(0.34125); text = "LR:"; }; class dorb_tfr_DD_name : dorb_tfr_SR_name { y = _get_screen_x(0)+_get_screen_h(0.4025); text = "DD"; }; class dorb_tfr_SR_name2 : dorb_tfr_SR_name { y = _get_screen_x(0)+_get_screen_h(0.545); text = "SR"; }; class dorb_tfr_LR_name2 : dorb_tfr_SR_name { y = _get_screen_x(0)+_get_screen_h(0.60375); text = "LR:"; }; class dorb_tfr_DD_name2 : dorb_tfr_SR_name { y = _get_screen_x(0)+_get_screen_h(0.6625); text = "DD"; }; class dorb_tfr_SR_disp : dorb_tfr_body { idc = 700202; x = _get_screen_x(0)+_get_screen_w(0.66); y = _get_screen_x(0)+_get_screen_h(0.28); w = _get_screen_w(0.07); h = _get_screen_h(0.04); sizeEx = _get_screen_h(0.035); text = ""; }; class dorb_tfr_LR_disp : dorb_tfr_SR_disp { idc = 700203; y = _get_screen_x(0)+_get_screen_h(0.34125); text = ""; }; class dorb_tfr_DD_disp : dorb_tfr_SR_disp { idc = 700204; y = _get_screen_x(0)+_get_screen_h(0.4025); text = ""; }; class dorb_tfr_SR_edit : dorb_gui_editBase { idc = 700205; x = _get_screen_x(0)+_get_screen_w(0.66); y = _get_screen_x(0)+_get_screen_h(0.545); w = _get_screen_w(0.07); h = _get_screen_h(0.038); sizeEx = _get_screen_h(0.035); textcolor[] = UI_CL_BODY_TEXT; text = ""; }; class dorb_tfr_LR_edit : dorb_tfr_SR_edit { idc = 700206; y = _get_screen_x(0)+_get_screen_h(0.60375); text = ""; }; class dorb_tfr_DD_edit : dorb_tfr_SR_edit { idc = 700207; y = _get_screen_x(0)+_get_screen_h(0.6625); text = ""; }; class dorb_tfr_list : dorb_gui_listboxN { idc = 700201; access = 2; x = _get_screen_x(0)+_get_screen_w(0.12); y = _get_screen_x(0)+_get_screen_h(0.22); w = _get_screen_w(0.46); h = _get_screen_h(0.48); rowHeight = _get_screen_h(0.035); sizeEx = _get_screen_h(0.025); columns[] = {0.0,_get_screen_w(0.42),_get_screen_w(0.5)}; }; class dorb_tfr_take : dorb_gui_button { idc = 700208; x = _get_screen_x(0)+_get_screen_w(0.77); y = _get_screen_x(0)+_get_screen_h(0.32125); w = _get_screen_w(0.11); h = _get_screen_h(0.08); text = "$STR_DORB_TFR_TAKE"; toolTip = "$STR_DORB_TFR_TAKE_TOOLTIP"; sizeEx = _get_screen_h(0.03); colorBackground[] = UI_CL_CTRL_WEINROT1; colorBackgroundActive[] = UI_CL_CTRL_WEINROT2; colorFocused[] = UI_CL_CTRL_WEINROT1; action = "[]call dorb_fnc_ui_tfr_setFreq;"; }; class dorb_tfr_set : dorb_tfr_take { idc = 700209; y = _get_screen_x(0)+_get_screen_h(0.58375); text = "$STR_DORB_TFR_SET"; toolTip = "$STR_DORB_TFR_SET_TOOLTIP"; action = "[]call dorb_fnc_ui_tfr_setGroup;"; }; }; class dorb_crate { idd = 600200; name = "Kisten-Füller"; /// von Dorbedo - wer das Ding nutzen will: Fragen! movingEnable = 0; enableSimulation = 1; fadein = 0; fadeout = 0; duration = 1000000; objects[] = {}; onLoad = "uiNamespace setVariable ['dorb_crateMenu', _this select 0]; ['dorb_crateMenu', true] call dorb_fnc_disp_blur; [] spawn dorb_fnc_ui_crate_OnLoad;"; onUnload = " ['dorb_crateMenu', false] call dorb_fnc_disp_blur;"; controlsBackground[] = { crate_CenterBackground, crate_RightCenterBackground, crate_HeaderBackground, crate_BottemLeftBackground, crate_BottemRightBackground, crate_ListBackground }; controls[] = { crate_combo_box, crate_progessbar, crate_listbox, crate_list_button_add, crate_list_button_sub, crate_spawn, crate_clear, crate_button1, crate_button2, crate_button3, crate_button4, crate_button5, crate_button6, crate_button7, crate_button8, crate_button9, crate_button10, crate_button11, crate_button12, crate_button13, crate_button14, crate_button15, crate_button16, crate_button17, crate_button18, crate_button19, }; class crate_CenterBackground: dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_y(0)+_get_screen_h(0.2); w = _get_screen_w(0.118); h = _get_screen_h(0.53); text = ""; colorBackground[] = UI_CL_BODY; colorText[] = UI_CL_BODY_TEXT; }; class crate_RightCenterBackground: crate_CenterBackground { x = _get_screen_x(0)+_get_screen_w(0.223); w = _get_screen_w(0.677); }; class crate_BottemLeftBackground: dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_y(0)+_get_screen_h(0.74); w = _get_screen_w(0.395); h = _get_screen_h(0.16); text = ""; colorBackground[] = UI_CL_BODY; colorText[] = UI_CL_BODY_TEXT; }; class crate_BottemRightBackground: dorb_gui_backgroundBase { x = _get_screen_x(0)+_get_screen_w(0.505); y = _get_screen_y(0)+_get_screen_h(0.74); w = _get_screen_w(0.395); h = _get_screen_h(0.16); text = ""; colorBackground[] = UI_CL_BODY; colorText[] = UI_CL_BODY_TEXT; }; class crate_HeaderBackground: crate_CenterBackground { x = _get_screen_x(0)+_get_screen_w(0.1); y = _get_screen_y(0)+_get_screen_h(0.1); w = _get_screen_w(0.8); h = _get_screen_h(0.09); text = "$STR_DORB_CRATE_HEADER"; colorText[] = UI_CL_HEADER_TEXT; colorBackground[] = UI_CL_HEADER; }; class crate_spawn : dorb_gui_button { idc = 600206; x = _get_screen_x(0)+_get_screen_w(0.525); y = _get_screen_y(0)+_get_screen_h(0.755); w = _get_screen_w(0.14); h = _get_screen_h(0.06); text = "$STR_DORB_CRATE_SPAWN"; sizeEx = _get_screen_h(0.03); colorBackground[] = UI_CL_BTN2_foc; colorBackgroundActive[] = UI_CL_BTN2_foc; colorShadow[] = UI_CL_BTN2; colorFocused[] = UI_CL_BTN2_foc; action = "[true]call dorb_fnc_ui_crate_spawn;false"; }; class crate_clear : crate_spawn { idc = 600207; x = _get_screen_x(0)+_get_screen_w(0.725); text = "$STR_DORB_CRATE_CLEAR"; action = "DORB_CRATE_CURRENT=[[],[],[],[],[],[]];DORB_CRATE_CURRENT_BOXID=0;[]call dorb_fnc_ui_crate_OnLoad;false"; }; class crate_list_button_add : crate_spawn { idc = 1000; text = "+"; borderSize = 0; colorShadow[] = {0,0,0,0}; action = "[true]call dorb_fnc_ui_crate_add;false"; }; class crate_list_button_sub : crate_list_button_add { idc = 1001; text = "-"; action = "[false]call dorb_fnc_ui_crate_add;false"; }; class crate_ListBackground: crate_CenterBackground { x = _get_screen_x(0)+_get_screen_w(0.233); y = _get_screen_y(0)+_get_screen_h(0.21); w = _get_screen_w(0.657); h = _get_screen_h(0.51); colorText[] = UI_CL_HEADER_TEXT; colorBackground[] = UI_CL_CTRL_GRAU2; }; class crate_listbox : dorb_gui_listboxN { idc = 600201; access = 2; x = _get_screen_x(0)+_get_screen_w(0.243); y = _get_screen_y(0)+_get_screen_h(0.22); w = _get_screen_w(0.637); h = _get_screen_h(0.49); rowHeight = _get_screen_h(0.035); sizeEx = _get_screen_h(0.022); columns[] = {_get_screen_w(0.027),_get_screen_w(0.09),_get_screen_w(0.15),_get_screen_w(0.55)}; //colorText[] = UI_CL_BODY_TEXT; //colorBackground[] = {0.5, 0.5, 0, 1}; //shadow = 1; // color[] = {0.5, 0.5, 0, 1}; // colorScrollbar[] = {0.8, 0.8, 0.8, 1}; //colorSelect[] = {0.8, 0.8, 0.8, 1}; //colorSelect2[] = {0.8, 0.8, 0.8, 1}; //colorSelectBackground[] = {0, 0, 0, 1}; //colorSelectBackground2[] = {0.8784, 0.8471, 0.651, 1}; drawSideArrows = 1; // 1 to draw buttons linked by idcLeft and idcRight on both sides of selected line. They are resized to line height idcLeft = 1001; // Left button IDC idcRight = 1000; //onCanDestroy = "systemChat str ['onCanDestroy',_this]; true"; //onDestroy = "systemChat str ['onDestroy',_this]; false"; //onSetFocus = "systemChat str ['onSetFocus',_this]; false"; //onKillFocus = "systemChat str ['onKillFocus',_this]; false"; //onKeyDown = "systemChat str ['onKeyDown',_this]; false"; //onKeyUp = "systemChat str ['onKeyUp',_this]; false"; //onMouseButtonDown = "systemChat str ['onMouseButtonDown',_this]; false"; //onMouseButtonUp = "systemChat str ['onMouseButtonUp',_this]; false"; //onMouseButtonClick = "systemChat str ['onMouseButtonClick',_this]; false"; //onMouseButtonDblClick = "systemChat str ['onMouseButtonDblClick',_this]; false"; //onMouseZChanged = "systemChat str ['onMouseZChanged',_this]; false"; //onMouseMoving = ""; //onMouseHolding = ""; //onLBSelChanged = "systemChat str ['onLBSelChanged',_this]; false"; //onLBDblClick = "systemChat str ['onLBDblClick',_this]; false"; }; class crate_combo_box : dorb_gui_combo { idc = 600205; x = _get_screen_x(0)+_get_screen_w(0.11); y = _get_screen_y(0)+_get_screen_h(0.85); w = _get_screen_w(0.375); h = _get_screen_h(0.03); sizeEx = _get_screen_h(0.025); rowHeight = _get_screen_h(0.025); wholeHeight = _get_screen_h(0.2); onLBSelChanged = "DORB_CRATE_CURRENT_BOXID=(_this select 1);['changebox',_config] call dorb_fnc_ui_crate_mass;;false"; }; class crate_progessbar : dorb_gui_loadingbarBase { idc = 600204; x = _get_screen_x(0)+_get_screen_w(0.11); y = _get_screen_y(0)+_get_screen_h(0.78); w = _get_screen_w(0.375); h = _get_screen_h(0.03); }; #define CRATE_SPALTE1 _get_screen_x(0)+_get_screen_w(0.11) #define CRATE_SPALTE2 _get_screen_x(0)+_get_screen_w(0.1615) #define CRATE_REIHE1 _get_screen_y(0)+_get_screen_h(0.21) #define CRATE_REIHE2 _get_screen_y(0)+_get_screen_h(0.2615) #define CRATE_REIHE3 _get_screen_y(0)+_get_screen_h(0.313) #define CRATE_REIHE4 _get_screen_y(0)+_get_screen_h(0.3645) #define CRATE_REIHE5 _get_screen_y(0)+_get_screen_h(0.416) #define CRATE_REIHE6 _get_screen_y(0)+_get_screen_h(0.4675) #define CRATE_REIHE7 _get_screen_y(0)+_get_screen_h(0.519) #define CRATE_REIHE8 _get_screen_y(0)+_get_screen_h(0.5705) #define CRATE_REIHE9 _get_screen_y(0)+_get_screen_h(0.622) #define CRATE_REIHE10 _get_screen_y(0)+_get_screen_h(0.6735) #define CRATE_BTTN_W _get_screen_w(0.0465) //_get_screen_w(0.03488) #define CRATE_BTTN_H _get_screen_h(0.0465) class crate_button1 : dorb_gui_button { idc = 600211; x = CRATE_SPALTE1; y = CRATE_REIHE1; w = CRATE_BTTN_W; h = CRATE_BTTN_H; shadow = 0; //_get_screen_h(0.0465) // _get_screen_w(0.03488) sizeEx = CRATE_BTTN_W + _get_screen_w(0.004); color[] = {0, 1, 0, 1}; //seems nothing to change, but define to avaoid errors colorBackground[] = UI_CL_CTRL_GRAU4; colorBackgroundActive[] = UI_CL_CTRL_GRAU2; colorFocused[] = UI_CL_CTRL_GRAU3; colorText[] = UI_CL_CTRL_GRAU1; colorTextSelect[] = UI_CL_CTRL_GRAU4; colorShadow[] = UI_CL_CTRL_GRAU4; colorBorder[] = UI_CL_CTRL_GRAU4; colorDisabled[] = {0.1, 0.1, 0.1, 0.4}; colorBackgroundDisabled[] = {0, 0, 0, 0.2}; offsetX = 0; offsetY = 0; toolTip = "$STR_DORB_CRATE_BTTN_1"; style = ST_PICTURE; text = "\A3\ui_f\data\IGUI\Cfg\MPTable\total_ca.paa"; }; class crate_button2 : crate_button1 { idc = 600212; x = CRATE_SPALTE2; y = CRATE_REIHE1; default=false; colorBackground[] = UI_CL_CTRL_GRAU1; colorBackgroundActive[] = UI_CL_CTRL_GRAU3; colorFocused[] = UI_CL_CTRL_GRAU2; colorText[] = UI_CL_CTRL_GRAU4; colorTextSelect[] = UI_CL_CTRL_GRAU1; toolTip = "$STR_DORB_CRATE_BTTN_2"; text = "A3\ui_f\data\gui\cfg\Hints\rifle_ca.paa"; }; class crate_button3 : crate_button2 { idc = 600213; x = CRATE_SPALTE1; y = CRATE_REIHE2; toolTip = "$STR_DORB_CRATE_BTTN_3"; text = "A3\ui_f\data\gui\cfg\Hints\automatic_ca.paa"; }; class crate_button4 : crate_button2 { idc = 600214; x = CRATE_SPALTE2; y = CRATE_REIHE2; toolTip = "$STR_DORB_CRATE_BTTN_4"; text = "A3\ui_f\data\gui\cfg\Hints\sniper_ca.paa"; }; class crate_button5 : crate_button2 { idc = 600215; x = CRATE_SPALTE1; y = CRATE_REIHE3; toolTip = "$STR_DORB_CRATE_BTTN_5"; text = "A3\ui_f\data\gui\cfg\Hints\shotguns_ca.paa"; }; class crate_button6 : crate_button2 { idc = 600216; x = CRATE_SPALTE2; y = CRATE_REIHE3; toolTip = "$STR_DORB_CRATE_BTTN_6"; text = "A3\ui_f\data\gui\cfg\Hints\launcher_ca.paa"; }; class crate_button7 : crate_button2 { idc = 600217; x = CRATE_SPALTE1; y = CRATE_REIHE4; toolTip = "$STR_DORB_CRATE_BTTN_7"; text = "A3\ui_f\data\gui\cfg\Hints\handgun_ca.paa"; }; class crate_button8 : crate_button2 { idc = 600218; x = CRATE_SPALTE2; y = CRATE_REIHE4; toolTip = "$STR_DORB_CRATE_BTTN_8"; text = "A3\ui_f\data\gui\cfg\Hints\optics_ca.paa"; }; class crate_button9 : crate_button2 { idc = 600219; x = CRATE_SPALTE1; y = CRATE_REIHE5; toolTip = "$STR_DORB_CRATE_BTTN_9"; text = "A3\ui_f\data\gui\cfg\Hints\grenades_ca.paa"; }; class crate_button10 : crate_button2 { idc = 600220; x = CRATE_SPALTE2; y = CRATE_REIHE5; toolTip = "$STR_DORB_CRATE_BTTN_10"; text = "A3\ui_f\data\gui\cfg\Hints\ieds_ca.paa"; }; class crate_button11 : crate_button2 { idc = 600221; x = CRATE_SPALTE1; y = CRATE_REIHE6; toolTip = "$STR_DORB_CRATE_BTTN_11"; text = "A3\ui_f\data\gui\cfg\Hints\gear_ca.paa"; }; class crate_button12 : crate_button1 { idc = 600222; default=false; x = CRATE_SPALTE2; y = CRATE_REIHE6; toolTip = "$STR_DORB_CRATE_BTTN_12"; text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\vest_ca.paa"; }; class crate_button13 : crate_button1 { idc = 600223; default=false; x = CRATE_SPALTE1; y = CRATE_REIHE7; toolTip = "$STR_DORB_CRATE_BTTN_13"; text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\uniform_ca.paa"; }; class crate_button14 : crate_button1 { idc = 600224; default=false; x = CRATE_SPALTE2; y = CRATE_REIHE7; toolTip = "$STR_DORB_CRATE_BTTN_14"; text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\headgear_ca.paa"; }; class crate_button15 : crate_button1 { idc = 600225; default=false; x = CRATE_SPALTE1; y = CRATE_REIHE8; toolTip = "$STR_DORB_CRATE_BTTN_15"; text = "A3\ui_f\data\gui\Rsc\RscDisplayArsenal\radio_ca.paa"; }; class crate_button16 : crate_button2 { idc = 600226; x = CRATE_SPALTE2; y = CRATE_REIHE8; toolTip = "$STR_DORB_CRATE_BTTN_16"; text = "A3\ui_f\data\gui\cfg\Hints\map_ca.paa"; }; class crate_button17 : crate_button2 { idc = 600227; x = CRATE_SPALTE1; y = CRATE_REIHE9; toolTip = "$STR_DORB_CRATE_BTTN_17"; text = "A3\ui_f\data\gui\cfg\Hints\injury_ca.paa"; }; class crate_button18 : crate_button2 { idc = 600228; x = CRATE_SPALTE2; y = CRATE_REIHE9; toolTip = "$STR_DORB_CRATE_BTTN_18"; text = "A3\ui_f\data\gui\cfg\Hints\slots_ca.paa"; }; class crate_button19 : crate_button2 { idc = 600229; x = CRATE_SPALTE1; y = CRATE_REIHE10; toolTip = "$STR_DORB_CRATE_BTTN_19"; text = "A3\ui_f\data\gui\cfg\Hints\actionmenu_ca.paa"; }; class crate_button20 : crate_button2 { idc = 600230; x = CRATE_SPALTE2; y = CRATE_REIHE10; toolTip = "$STR_DORB_CRATE_BTTN_20"; text = "A3\ui_f\data\gui\cfg\Hints\actionmenu_ca.paa"; }; };
[ "Dorbedo@t-online.de" ]
Dorbedo@t-online.de
32e195b1b1c4c1f8abbb46b6516b7d241430fe52
395d1860e82bc75ccc04b91c4b9a8fa46276d9bb
/Source/Vision/Runtime/Common/VisMobileExitDialog.inl
069ee8b601d38382ad8a42057b64e8b6d235dafb
[]
no_license
Hakhyun-Kim/projectanarchy
28ba7370050000a12e4305faa11d5deb77c330a1
ccea719afcb03967a68a169730b59e8a8a6c45f8
refs/heads/master
2021-06-03T04:41:22.814866
2013-11-07T07:21:03
2013-11-07T07:21:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,196
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ V_IMPLEMENT_SERIAL(VisMobileExitDialog, VDialog, 0, &VGUIManager::GUIModule()); void VisMobileExitDialog::OnInitDialog() { // center the GUI SetPosition( Vision::Video.GetXRes()*0.5f - GetSize().x*0.5f, Vision::Video.GetYRes()*0.5f - GetSize().y*0.5f); m_iExitId = VGUIManager::GetID("ID_EXIT"); m_iCancelId = VGUIManager::GetID("ID_CANCEL"); m_bExitTriggered = false; } void VisMobileExitDialog::OnItemClicked(VMenuEventDataObject *pEvent) { VDialog::OnItemClicked(pEvent); int iID = pEvent->m_pItem->GetID(); if (iID == m_iExitId) { m_bExitTriggered = true; } else if (iID == m_iCancelId) { CloseDialog(); } } void VisMobileExitDialog::OnSetFocus(bool bStatus) { // Refuse to unfocus if dialog is visible. if (bStatus || !IsVisible()) VDialog::OnSetFocus(bStatus); } void VisMobileExitDialog::CloseDialog() { GetContext()->CloseDialog(this); SetVisible(false); if (GetContext()->m_OpenDialogs.Count() == 0) GetContext()->SetActivate(false); m_bExitTriggered = false; } /* * Havok SDK - Base file, BUILD(#20131019) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from salesteam@havok.com. * */
[ "joel.van.eenwyk@havok.com" ]
joel.van.eenwyk@havok.com
4f79cd1ab3cf18ad4d0d54fdcfbb6ba8a27e570d
990936108fcc03323e3cae1f4b8780be289f7559
/gfx/skia/src/core/SkBitmapHeap.cpp
936951cc8e532ec7b9c1165d2edeb43158462497
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
FilipinOTech/Pale-Moon
3740473f308b35f818e2d14ddab69b552a8b8763
0f978fa3c10b371a965f19e5b6533b924be27128
refs/heads/master
2021-01-16T19:40:21.735594
2014-07-09T21:20:24
2014-07-09T21:20:24
21,687,812
9
0
null
null
null
null
UTF-8
C++
false
false
13,867
cpp
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmapHeap.h" #include "SkBitmap.h" #include "SkFlattenableBuffers.h" #include "SkTSearch.h" SK_DEFINE_INST_COUNT(SkBitmapHeapReader) SK_DEFINE_INST_COUNT(SkBitmapHeap::ExternalStorage) SkBitmapHeapEntry::SkBitmapHeapEntry() : fSlot(-1) , fRefCount(0) , fBytesAllocated(0) { } SkBitmapHeapEntry::~SkBitmapHeapEntry() { SkASSERT(0 == fRefCount); } void SkBitmapHeapEntry::addReferences(int count) { if (0 == fRefCount) { // If there are no current owners then the heap manager // will be the only one able to modify it, so it does not // need to be an atomic operation. fRefCount = count; } else { sk_atomic_add(&fRefCount, count); } } /////////////////////////////////////////////////////////////////////////////// int SkBitmapHeap::LookupEntry::Compare(const SkBitmapHeap::LookupEntry *a, const SkBitmapHeap::LookupEntry *b) { if (a->fGenerationId < b->fGenerationId) { return -1; } else if (a->fGenerationId > b->fGenerationId) { return 1; } else if (a->fPixelOffset < b->fPixelOffset) { return -1; } else if (a->fPixelOffset > b->fPixelOffset) { return 1; } else if (a->fWidth < b->fWidth) { return -1; } else if (a->fWidth > b->fWidth) { return 1; } else if (a->fHeight < b->fHeight) { return -1; } else if (a->fHeight > b->fHeight) { return 1; } return 0; } /////////////////////////////////////////////////////////////////////////////// SkBitmapHeap::SkBitmapHeap(int32_t preferredSize, int32_t ownerCount) : INHERITED() , fExternalStorage(NULL) , fMostRecentlyUsed(NULL) , fLeastRecentlyUsed(NULL) , fPreferredCount(preferredSize) , fOwnerCount(ownerCount) , fBytesAllocated(0) , fDeferAddingOwners(false) { } SkBitmapHeap::SkBitmapHeap(ExternalStorage* storage, int32_t preferredSize) : INHERITED() , fExternalStorage(storage) , fMostRecentlyUsed(NULL) , fLeastRecentlyUsed(NULL) , fPreferredCount(preferredSize) , fOwnerCount(IGNORE_OWNERS) , fBytesAllocated(0) , fDeferAddingOwners(false) { SkSafeRef(storage); } SkBitmapHeap::~SkBitmapHeap() { SkDEBUGCODE( for (int i = 0; i < fStorage.count(); i++) { bool unused = false; for (int j = 0; j < fUnusedSlots.count(); j++) { if (fUnusedSlots[j] == fStorage[i]->fSlot) { unused = true; break; } } if (!unused) { fBytesAllocated -= fStorage[i]->fBytesAllocated; } } fBytesAllocated -= (fStorage.count() * sizeof(SkBitmapHeapEntry)); ) SkASSERT(0 == fBytesAllocated); fStorage.deleteAll(); SkSafeUnref(fExternalStorage); fLookupTable.deleteAll(); } SkTRefArray<SkBitmap>* SkBitmapHeap::extractBitmaps() const { const int size = fStorage.count(); SkTRefArray<SkBitmap>* array = NULL; if (size > 0) { array = SkTRefArray<SkBitmap>::Create(size); for (int i = 0; i < size; i++) { // make a shallow copy of the bitmap array->writableAt(i) = fStorage[i]->fBitmap; } } return array; } void SkBitmapHeap::removeFromLRU(SkBitmapHeap::LookupEntry* entry) { if (fMostRecentlyUsed == entry) { fMostRecentlyUsed = entry->fLessRecentlyUsed; if (NULL == fMostRecentlyUsed) { SkASSERT(fLeastRecentlyUsed == entry); fLeastRecentlyUsed = NULL; } else { fMostRecentlyUsed->fMoreRecentlyUsed = NULL; } } else { // Remove entry from its prior place, and make sure to cover the hole. if (fLeastRecentlyUsed == entry) { SkASSERT(entry->fMoreRecentlyUsed != NULL); fLeastRecentlyUsed = entry->fMoreRecentlyUsed; } // Since we have already considered the case where entry is the most recently used, it must // have a more recently used at this point. SkASSERT(entry->fMoreRecentlyUsed != NULL); entry->fMoreRecentlyUsed->fLessRecentlyUsed = entry->fLessRecentlyUsed; if (entry->fLessRecentlyUsed != NULL) { SkASSERT(fLeastRecentlyUsed != entry); entry->fLessRecentlyUsed->fMoreRecentlyUsed = entry->fMoreRecentlyUsed; } } entry->fMoreRecentlyUsed = NULL; } void SkBitmapHeap::appendToLRU(SkBitmapHeap::LookupEntry* entry) { if (fMostRecentlyUsed != NULL) { SkASSERT(NULL == fMostRecentlyUsed->fMoreRecentlyUsed); fMostRecentlyUsed->fMoreRecentlyUsed = entry; entry->fLessRecentlyUsed = fMostRecentlyUsed; } fMostRecentlyUsed = entry; if (NULL == fLeastRecentlyUsed) { fLeastRecentlyUsed = entry; } } // iterate through our LRU cache and try to find an entry to evict SkBitmapHeap::LookupEntry* SkBitmapHeap::findEntryToReplace(const SkBitmap& replacement) { SkASSERT(fPreferredCount != UNLIMITED_SIZE); SkASSERT(fStorage.count() >= fPreferredCount); SkBitmapHeap::LookupEntry* iter = fLeastRecentlyUsed; while (iter != NULL) { SkBitmapHeapEntry* heapEntry = fStorage[iter->fStorageSlot]; if (heapEntry->fRefCount > 0) { // If the least recently used bitmap has not been unreferenced // by its owner, then according to our LRU specifications a more // recently used one can not have used all its references yet either. return NULL; } if (replacement.getGenerationID() == iter->fGenerationId) { // Do not replace a bitmap with a new one using the same // pixel ref. Instead look for a different one that will // potentially free up more space. iter = iter->fMoreRecentlyUsed; } else { return iter; } } return NULL; } size_t SkBitmapHeap::freeMemoryIfPossible(size_t bytesToFree) { if (UNLIMITED_SIZE == fPreferredCount) { return 0; } LookupEntry* iter = fLeastRecentlyUsed; size_t origBytesAllocated = fBytesAllocated; // Purge starting from LRU until a non-evictable bitmap is found or until // everything is evicted. while (iter != NULL) { SkBitmapHeapEntry* heapEntry = fStorage[iter->fStorageSlot]; if (heapEntry->fRefCount > 0) { break; } LookupEntry* next = iter->fMoreRecentlyUsed; this->removeEntryFromLookupTable(iter); // Free the pixel memory. removeEntryFromLookupTable already reduced // fBytesAllocated properly. heapEntry->fBitmap.reset(); // Add to list of unused slots which can be reused in the future. fUnusedSlots.push(heapEntry->fSlot); iter = next; if (origBytesAllocated - fBytesAllocated >= bytesToFree) { break; } } if (fLeastRecentlyUsed != iter) { // There was at least one eviction. fLeastRecentlyUsed = iter; if (NULL == fLeastRecentlyUsed) { // Everything was evicted fMostRecentlyUsed = NULL; fBytesAllocated -= (fStorage.count() * sizeof(SkBitmapHeapEntry)); fStorage.deleteAll(); fUnusedSlots.reset(); SkASSERT(0 == fBytesAllocated); } else { fLeastRecentlyUsed->fLessRecentlyUsed = NULL; } } return origBytesAllocated - fBytesAllocated; } int SkBitmapHeap::findInLookupTable(const LookupEntry& indexEntry, SkBitmapHeapEntry** entry) { int index = SkTSearch<const LookupEntry>((const LookupEntry**)fLookupTable.begin(), fLookupTable.count(), &indexEntry, sizeof(void*), LookupEntry::Compare); if (index < 0) { // insert ourselves into the bitmapIndex index = ~index; *fLookupTable.insert(index) = SkNEW_ARGS(LookupEntry, (indexEntry)); } else if (entry != NULL) { // populate the entry if needed *entry = fStorage[fLookupTable[index]->fStorageSlot]; } return index; } bool SkBitmapHeap::copyBitmap(const SkBitmap& originalBitmap, SkBitmap& copiedBitmap) { SkASSERT(!fExternalStorage); // If the bitmap is mutable, we need to do a deep copy, since the // caller may modify it afterwards. if (originalBitmap.isImmutable()) { copiedBitmap = originalBitmap; // TODO if we have the pixel ref in the heap we could pass it here to avoid a potential deep copy // else if (sharedPixelRef != NULL) { // copiedBitmap = orig; // copiedBitmap.setPixelRef(sharedPixelRef, originalBitmap.pixelRefOffset()); } else if (originalBitmap.empty()) { copiedBitmap.reset(); } else if (!originalBitmap.deepCopyTo(&copiedBitmap, originalBitmap.getConfig())) { return false; } copiedBitmap.setImmutable(); return true; } int SkBitmapHeap::removeEntryFromLookupTable(LookupEntry* entry) { // remove the bitmap index for the deleted entry SkDEBUGCODE(int count = fLookupTable.count();) int index = this->findInLookupTable(*entry, NULL); // Verify that findInLookupTable found an existing entry rather than adding // a new entry to the lookup table. SkASSERT(count == fLookupTable.count()); fBytesAllocated -= fStorage[entry->fStorageSlot]->fBytesAllocated; SkDELETE(fLookupTable[index]); fLookupTable.remove(index); return index; } int32_t SkBitmapHeap::insert(const SkBitmap& originalBitmap) { SkBitmapHeapEntry* entry = NULL; int searchIndex = this->findInLookupTable(LookupEntry(originalBitmap), &entry); if (entry) { // Already had a copy of the bitmap in the heap. if (fOwnerCount != IGNORE_OWNERS) { if (fDeferAddingOwners) { *fDeferredEntries.append() = entry->fSlot; } else { entry->addReferences(fOwnerCount); } } if (fPreferredCount != UNLIMITED_SIZE) { LookupEntry* lookupEntry = fLookupTable[searchIndex]; if (lookupEntry != fMostRecentlyUsed) { this->removeFromLRU(lookupEntry); this->appendToLRU(lookupEntry); } } return entry->fSlot; } // decide if we need to evict an existing heap entry or create a new one if (fPreferredCount != UNLIMITED_SIZE && fStorage.count() >= fPreferredCount) { // iterate through our LRU cache and try to find an entry to evict LookupEntry* lookupEntry = this->findEntryToReplace(originalBitmap); if (lookupEntry != NULL) { // we found an entry to evict entry = fStorage[lookupEntry->fStorageSlot]; // Remove it from the LRU. The new entry will be added to the LRU later. this->removeFromLRU(lookupEntry); int index = this->removeEntryFromLookupTable(lookupEntry); // update the current search index now that we have removed one if (index < searchIndex) { searchIndex--; } } } // if we didn't have an entry yet we need to create one if (!entry) { if (fPreferredCount != UNLIMITED_SIZE && fUnusedSlots.count() > 0) { int slot; fUnusedSlots.pop(&slot); entry = fStorage[slot]; } else { entry = SkNEW(SkBitmapHeapEntry); fStorage.append(1, &entry); entry->fSlot = fStorage.count() - 1; fBytesAllocated += sizeof(SkBitmapHeapEntry); } } // create a copy of the bitmap bool copySucceeded; if (fExternalStorage) { copySucceeded = fExternalStorage->insert(originalBitmap, entry->fSlot); } else { copySucceeded = copyBitmap(originalBitmap, entry->fBitmap); } // if the copy failed then we must abort if (!copySucceeded) { // delete the index SkDELETE(fLookupTable[searchIndex]); fLookupTable.remove(searchIndex); // If entry is the last slot in storage, it is safe to delete it. if (fStorage.count() - 1 == entry->fSlot) { // free the slot fStorage.remove(entry->fSlot); fBytesAllocated -= sizeof(SkBitmapHeapEntry); SkDELETE(entry); } else { fUnusedSlots.push(entry->fSlot); } return INVALID_SLOT; } // update the index with the appropriate slot in the heap fLookupTable[searchIndex]->fStorageSlot = entry->fSlot; // compute the space taken by this entry // TODO if there is a shared pixel ref don't count it // If the SkBitmap does not share an SkPixelRef with an SkBitmap already // in the SharedHeap, also include the size of its pixels. entry->fBytesAllocated += originalBitmap.getSize(); // add the bytes from this entry to the total count fBytesAllocated += entry->fBytesAllocated; if (fOwnerCount != IGNORE_OWNERS) { entry->addReferences(fOwnerCount); } if (fPreferredCount != UNLIMITED_SIZE) { this->appendToLRU(fLookupTable[searchIndex]); } return entry->fSlot; } void SkBitmapHeap::deferAddingOwners() { fDeferAddingOwners = true; } void SkBitmapHeap::endAddingOwnersDeferral(bool add) { if (add) { for (int i = 0; i < fDeferredEntries.count(); i++) { SkASSERT(fOwnerCount != IGNORE_OWNERS); SkBitmapHeapEntry* heapEntry = this->getEntry(fDeferredEntries[i]); SkASSERT(heapEntry != NULL); heapEntry->addReferences(fOwnerCount); } } fDeferAddingOwners = false; fDeferredEntries.reset(); }
[ "mcwerewolf@gmail.com" ]
mcwerewolf@gmail.com
1dbc88052b8bceb70c15a7bacb491db8a809b1e3
f13ef18abfb61d983040f83249bd19c6f55c29c9
/tools/Vitis-AI-Library/centerpoint/src/preprocess.hpp
5a92e0e8e500c8876429ddd6dd3d0b6e1820b3eb
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
AEW2015/Vitis-AI
5487b6474924e57dbdf54f66517d1c604fc2c480
84798c76e6ebb93300bf384cb56397f214676330
refs/heads/master
2023-06-24T11:02:20.049076
2021-07-27T05:41:52
2021-07-27T05:41:52
390,221,916
1
0
Apache-2.0
2021-07-28T05:12:07
2021-07-28T05:12:06
null
UTF-8
C++
false
false
3,555
hpp
/* * Copyright 2019 Xilinx 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. */ #pragma once #include <string> #include <vector> #include <utility> #include <cassert> #include <initializer_list> #include <vitis/ai/profiling.hpp> using namespace std; namespace vitis { namespace ai { namespace centerpoint{ constexpr uint32_t MAX_POINTS_NUM = 40; constexpr uint32_t MAX_VOXELS_NUM = 20000; template<typename T> struct DataContainer { std::vector<uint32_t> shape; std::vector<T> data; std::vector<uint64_t> stride; explicit DataContainer(const std::vector<uint32_t>& data_shape, const T& val) : shape{data_shape}, stride(data_shape.size()) { long long size = 1; // e.g data_shape = {3, 4, 5} // stride = {20, 5, 1} for (auto i = 0u; i < data_shape.size(); ++i) { stride[data_shape.size() - 1 - i] = size; size *= data_shape[data_shape.size() - 1 - i]; } data.assign(size, val); } DataContainer(const DataContainer& other) = default; DataContainer(DataContainer&& other) = default; DataContainer& operator = (const DataContainer& other){ this->shape = other.shape; this->data = other.data; this->stride = other.stride; return *this; } DataContainer& operator = (DataContainer&& other){ this->shape = std::move(other.shape); this->data = std::move(other.data); this->stride = std::move(other.stride); return *this; } virtual ~DataContainer() = default; T& at(std::initializer_list<int32_t> l) { assert(l.size() == shape.size()); auto pos = 0llu; auto it = l.begin(); for (uint32_t i = 0u; i < stride.size(); ++i, ++it) { pos += stride[i] * (*it); } assert(pos < data.size()); return data[pos]; } const T& at(std::initializer_list<int32_t> l) const { assert(l.size() == shape.size()); auto pos = 0llu; auto it = l.begin(); for (uint32_t i = 0u; i < stride.size(); ++i, ++it) { pos += stride[i] * (*it); } assert(pos < data.size()); return data[pos]; } }; typedef struct { int voxel_num; DataContainer<float> voxels; DataContainer<int> num_points; // points number of every voxel DataContainer<int> coors; } VoxelizeResult; typedef struct { int voxel_num; vector<float> voxels; vector<int> num_points; // points number of every voxel vector<int> coors; } VoxelizeResult2; // note: need input tensor size std::vector<int> preprocess(const DataContainer<float> &points, int8_t *input_tensor_ptr, float input_tensor_scale); std::vector<int> preprocess2(const vector<float> &points, int8_t *input_tensor_ptr, float input_tensor_scale); //std::vector<int> preprocess3(const vector<float> &points, int8_t *input_tensor_ptr, float input_tensor_scale); std::vector<int> preprocess3(const vector<float> &points, int dim, const std::vector<float> &input_mean, const std::vector<float> &input_scale, int8_t *input_tensor_ptr); } // end of pointpillars_nuscenes }}
[ "hanxue.lee@xilinx.com" ]
hanxue.lee@xilinx.com
45ee6cae3efd20ec747c141de45e4a8990f31b32
5a7bb63506c49bdcdca0db093adab8d09389b403
/Final_Project/Wraith.h
be775a1eeeecc4b207950f11291677abd09ebf22
[]
no_license
AleousNB/Cis-17A-Final-Project
e3e029e50237fb10d6ed1a2ff29f4d2f66bd54a8
e6f980b86a69984d041db5b1ce0e355c8719b6ad
refs/heads/master
2021-01-25T06:30:51.215720
2017-06-09T04:17:49
2017-06-09T04:17:49
93,588,939
0
0
null
null
null
null
UTF-8
C++
false
false
173
h
#pragma once #include "Creature.h" class Wraith: virtual public Creature { protected: int _mana; public: Wraith(std::string name); ~Wraith(); std::string Attack(); };
[ "AleousNB@yahoo.com" ]
AleousNB@yahoo.com
ca19cd91999116de6f5d74a12a7fd647e5ac50ed
206658cb2387b5caa6de563fc62576842250cda7
/FridgeController.h
d4d3ec0583882fc554b2111a0fc9da6668c07cd1
[]
no_license
bensacola/FridgeControlServer
abe8f8fe29f49c04b0817fac31eca018b7e8fb7a
2551853458f2dfa269981582e17816fb82da4870
refs/heads/master
2022-01-22T03:11:19.781578
2019-08-22T15:09:46
2019-08-22T15:09:46
119,896,739
0
0
null
null
null
null
UTF-8
C++
false
false
6,435
h
#ifndef FRIDGECONTROL_H_ #define FRIDGECONTROL_H_ #include <Wire.h> #include <SPI.h> //#include <Adafruit_Sensor.h> //#include <Adafruit_BMP280.h> #include <DallasTemperature.h> #include <EEPROM.h> enum FridgeControllerErrors { NoError = 0, TemperatureSensorNotFound }; class FridgeConfig { public: FridgeConfig() { IntranetOnly = false; CheckInterval = 1000 * 60 * 5; TemperatureSensorPin = 0; RelayPin = 0; MaxTemperature = 55; MinTemperature = 40; } int CheckInterval; bool IntranetOnly; int TemperatureSensorPin; int RelayPin; int MaxTemperature; int MinTemperature; }; class FridgeControls { public: FridgeControls() : FridgeControls(0, 0) {} FridgeControls(int _tempPin, int _relayPin) { SetTemperaturePin(_relayPin); SetRelayPin(_relayPin); RelayOnTime = 0; RelayOffTime = 0; } void SetTemperaturePin(int _pin) { if (TemperaturePin != _pin) { TemperaturePin = _pin; if (TemperaturePin > 0) { pinMode(TemperaturePin, INPUT); } InitTemperatureSensor(); } } int GetTemperaturePin() { return TemperaturePin; } bool IsRelayOn() { return RelayOn; } void SetRelayPin(int _pin) { RelayPin = _pin; if (RelayPin > 0) { pinMode(RelayPin, OUTPUT); } } int GetRelayPin() { return RelayPin; } bool TurnRelayOn(bool _on = true) { if (RelayPin > 0) { digitalWrite(RelayPin, _on == true ? HIGH : LOW); RelayOn = _on; RelayOnTime = millis(); RelayOffTime = millis(); } } long GetRelayOnTime() { return RelayOnTime > 0 ? millis() - RelayOnTime : 0; } long GetRelayOffTime() { return RelayOffTime > 0 ? millis() - RelayOffTime : 0; } float GetTemperature() { return Temperature; } int RefreshTemps() { //read temperatures if (!TemperatureSensorPresent) { return FridgeControllerErrors::TemperatureSensorNotFound; } sensors->requestTemperatures(); Temperature = DallasTemperature::toFahrenheit(sensors->getTempC(TemperatureSensorAddress)); } void Begin() { InitTemperatureSensor(); } private: int RelayPin; bool RelayOn; long RelayOnTime; long RelayOffTime; int TemperaturePin; bool TemperatureSensorPresent; float Temperature; OneWire *oneWire; DallasTemperature *sensors = NULL; DeviceAddress TemperatureSensorAddress; int TemperatureSensorResolution; int InitTemperatureSensor() { if (sensors != NULL) { delete sensors; sensors = NULL; } if (oneWire != NULL) { delete oneWire; oneWire = NULL; } oneWire = new OneWire(GetTemperaturePin()); sensors = new DallasTemperature(oneWire); sensors->begin(); int deviceCount = sensors->getDeviceCount(); if (!deviceCount || !sensors->getAddress(TemperatureSensorAddress, 0)) { TemperatureSensorPresent = false; return FridgeControllerErrors::TemperatureSensorNotFound; } TemperatureSensorPresent = true; sensors->setResolution(TemperatureSensorAddress, TemperatureSensorResolution); sensors->begin(); } }; class FridgeController { public: FridgeController() : FridgeController(0, 0,50,55) {} FridgeController(int _tempPin, int _relayPin, int _minTemp, int _maxTemp) { LastRefreshTime = 0; IgnoreErrors = false; Controls.SetTemperaturePin(_tempPin); Controls.SetRelayPin(_relayPin); Config.MinTemperature = _minTemp; Config.MaxTemperature = _maxTemp; } ~FridgeController() {} bool IgnoreErrors; FridgeConfig Config; FridgeControls Controls; void Begin() { if (IsSavedConfigValid()) { Serial.println("Saved config is valid. loading from EEPROM"); yield(); LoadConfig(); yield(); } else { Serial.println("Saved config is not valid"); } Controls.Begin(); } int Refresh() { if (millis() > (Config.CheckInterval + LastRefreshTime)) { return RefreshInternal(); } return FridgeControllerErrors::NoError; } void WriteConfig() { Serial.println("WriteConfig"); SaveConfigValidationMark(); EEPROM.begin(eepromSize); EEPROM.put(eepromConfigOffset + 1, Config); EEPROM.commit(); EEPROM.end(); Serial.println("SaveConfig Complete"); UpdateControlsConfig(); } void PrintConfig() { Serial.println("Temperature Pin" + String(Config.TemperatureSensorPin)); Serial.println("Relay Pin" + String(Config.RelayPin)); Serial.println("MinTemperature " + String(Config.MinTemperature)); Serial.println("MaxTemperature " + String(Config.MaxTemperature)); Serial.println("CheckInterval " + String(Config.CheckInterval)); Serial.println("IntranetOnly " + String(Config.IntranetOnly)); } void UpdateControlsConfig() { Controls.SetTemperaturePin(Config.TemperatureSensorPin); Controls.SetRelayPin(Config.RelayPin); } private: long LastRefreshTime; int RefreshInternal() { Serial.println("\n*** Refresh Internal ***"); LastRefreshTime = millis(); //read temperatures Serial.println("Refresh Temps"); int error = Controls.RefreshTemps(); if (error > 0 && IgnoreErrors != true) { return error; } yield(); float temperature = Controls.GetTemperature(); Serial.println("Temperature = " + String(temperature)); //Check if we need to change relay state Serial.println("Checking Relay"); if (temperature >= Config.MaxTemperature) { Serial.println("Max Temperature Exceeded"); //if (!Controls.IsRelayOn()) { Serial.println("Turning ON"); Controls.TurnRelayOn(true); //} Serial.println("ON"); } else if (temperature < Config.MinTemperature) { //if (Controls.IsRelayOn()) { Serial.println("Turning OFF"); Controls.TurnRelayOn(false); //} Serial.println("OFF"); } yield(); Serial.println("*** Refresh Internal Complete ***"); return FridgeControllerErrors::NoError; } const char eepromConfigValidationMark = 'g'; int eepromConfigOffset = 32; const int eepromSize = 256; void SaveConfigValidationMark() { Serial.println("SaveConfigValidationMark"); EEPROM.begin(eepromSize); EEPROM.put(eepromConfigOffset, eepromConfigValidationMark); EEPROM.commit(); EEPROM.end(); Serial.println("SaveConfigValidationMark Complete"); } bool IsSavedConfigValid() { EEPROM.begin(eepromSize); char c; EEPROM.get(eepromConfigOffset, c); EEPROM.end(); if (c == eepromConfigValidationMark) { return true; } return false; } void LoadConfig() { Serial.println("LoadConfig"); EEPROM.begin(eepromSize); EEPROM.get(eepromConfigOffset + 1, Config); EEPROM.end(); Serial.println("LoadConfig Complete"); } }; #endif
[ "bensacola@gmail.com" ]
bensacola@gmail.com
db0b194cc001465d5e3c26b039a56b23149e46a1
40f26fac97de561ad384ae938bc6ac0c38830ba5
/classes/cs352/interface/src/deletetaskdialog.h
29615b337c9376a5ef73d25ac1bdd256dae00269
[]
no_license
dysbulic/tip
9b2b192844c7ccda22ddfbb180a37c825bf72128
2efcbf19461110ac09cb337263a8fabecdf58c25
refs/heads/master
2023-06-24T12:55:31.689806
2023-06-14T03:27:09
2023-06-14T03:27:09
530,573
1
3
null
2023-03-05T10:46:17
2010-02-22T18:29:32
HTML
UTF-8
C++
false
false
733
h
#ifndef __DELETE_TASK_DIALOG__ #define __DELETE_TASK_DIALOG__ #include <QDialog> #include <QLabel> #include <QListWidget> #include <QPushButton> #include <vector> class SharedData; class DeleteTaskDialog : public QDialog{ Q_OBJECT public: DeleteTaskDialog(SharedData * pSharedData, long robotId, std::vector<long> * pIdList); ~DeleteTaskDialog() {} protected: void PopulateTaskList(long robotId); private Q_SLOTS: void DeleteTask(); private: SharedData * m_pSharedData; std::vector<long> * m_pIdList; QLabel * m_pRobotNameLabel; QListWidget * m_pWaypointList; QPushButton * m_pDeleteButton; QPushButton * m_pDoneButton; QPushButton * m_pCancelButton; }; #endif
[ "will@dhappy.org" ]
will@dhappy.org
00605fd2acb59dd7543c5cbf71c27c05f036f721
211f01b13e9165bde8e3a87128ed3fe74113b536
/C++/문제_10282번.cpp
d6e3d244fa1c6dc6570e83bbe1a628f398ceb6cf
[]
no_license
portfolioExpert/BackJoon
9ee9d631322443e856d7d5a14f8f7379a32f9e05
e38c7a1ac9f5e9ddc5d84ae9135791fc7c701e52
refs/heads/master
2023-08-03T10:21:41.119294
2023-07-24T22:33:17
2023-07-24T22:33:17
223,161,598
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
cpp
//문제 10282번 해킹 -> 다익스트라 //마지막으로 감염된 컴퓨터를 못찾아서 계속 틀림 #include <vector> #include <queue> int n, d, c; int dp[10001]; void dijkstra(int go, vector<pair<int,int>>v[]){ priority_queue<pair<int,int>>pq; pq.push({0, go}); dp[go] = 0; while(!pq.empty()){ int gogo = pq.top().second; int cost = -pq.top().first; pq.pop(); for(int i = 0;i<v[gogo].size();i++){ int next = v[gogo][i].first; int nextcost = cost + v[gogo][i].second; if(dp[next] > nextcost){ dp[next] = nextcost; pq.push({-nextcost, next}); } } } } int main(){ cin.tie(NULL); ios_base::sync_with_stdio(false); cout.tie(NULL); int t; cin >> t; while(t--){ cin >> n >> d >> c; fill_n(dp, n+1, 987654321); vector<pair<int,int>>v[10001]; for(int i = 0;i<d;i++){ int a, b, s; cin >> a >> b >> s; v[b].push_back({a,s}); } dijkstra(c, v); int cnt = 0, value = 0; for(int i = 1;i<=n;i++){ if(dp[i] != 987654321){ cnt++; if(dp[i] > value) value = dp[i]; } } cout << cnt << " " << value << "\n"; } }
[ "gus7518@naver.com" ]
gus7518@naver.com
e8347f7b55e71199c3908af0b5144a6d6f738d9d
df68b54d10cdca09d5a42ade5a18e54c41c4f142
/headers/player.h
2517d4cf5a43f7fab5f561be0178aecd0a91440c
[]
no_license
kaspersoreide/kinematics
aa2d12a3305185ded7581e771afce34d710cd080
dfd3e72c4de7a3e037f35690c0c53631a814f7d1
refs/heads/main
2023-07-18T14:03:27.087077
2021-09-06T01:05:03
2021-09-06T01:05:03
403,364,677
2
0
null
null
null
null
UTF-8
C++
false
false
188
h
#pragma once #include "object.h" #define PLAYER_HEIGHT 1.8f class Player : public Object { public: void move(); bool mov[6], rot[6]; void jump(); Player(); ~Player(); };
[ "kasper.soreide@gmail.com" ]
kasper.soreide@gmail.com
ad88cf176c09e74a38cd14062de3e0e552b82b0a
9f8096cde6b7a608b91b7308767f132a312a55f2
/cpucounters.cpp
c4c58981341d8e326ab9650b48e6fd510d720b4c
[ "BSD-3-Clause" ]
permissive
hirenp/pcm
352fc1e76f35e65cadd13a2879dd08c7366fb707
a92d704dff4f638855ff4672a0ba8ed780f211dc
refs/heads/master
2016-09-06T05:43:51.249693
2014-03-21T15:18:10
2014-03-21T15:18:10
17,987,175
1
1
null
null
null
null
UTF-8
C++
false
false
129,275
cpp
/* Copyright (c) 2009-2013, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // written by Roman Dementiev // Otto Bruggeman // Thomas Willhalm // Pat Fay // Austen Ott // Jim Harris (FreeBSD) //#define PCM_TEST_FALLBACK_TO_ATOM #include <assert.h> #include <stdarg.h> #include <stdio.h> #ifdef INTELPCM_EXPORTS // Intelpcm.h includes cpucounters.h #include "Intelpcm.dll\Intelpcm.h" #else #include "cpucounters.h" #endif #include "msr.h" #include "pci.h" #include "types.h" #include "utils.h" #ifdef _MSC_VER #include <intrin.h> #include <windows.h> #include <tchar.h> #include "winring0/OlsApiInit.h" #else #include <pthread.h> #include <errno.h> #include <sys/time.h> #endif #include <string.h> #include <limits> #include <map> #ifdef __APPLE__ #include <sys/types.h> #include <sys/sysctl.h> #include <sys/sem.h> // convertUnknownToInt is used in the safe sysctl call to convert an unkown size to an int int convertUnknownToInt(size_t size, char* value); #endif #if defined (__FreeBSD__) #include <sys/types.h> #include <sys/sysctl.h> #include <sys/sem.h> #include <sys/ioccom.h> #include <sys/cpuctl.h> #include <machine/cpufunc.h> #endif // FreeBSD is much more restrictive about names for semaphores #if defined (__FreeBSD__) #define PCM_INSTANCE_LOCK_SEMAPHORE_NAME "/Intel_PCM_inst_lock" #define PCM_NUM_INSTANCES_SEMAPHORE_NAME "/Intel_num_PCM_inst" #else #define PCM_INSTANCE_LOCK_SEMAPHORE_NAME "Intel(r) PCM inst lock" #define PCM_NUM_INSTANCES_SEMAPHORE_NAME "Num Intel(r) PCM insts" #endif #ifdef _MSC_VER HMODULE hOpenLibSys = NULL; bool PCM::initWinRing0Lib() { const BOOL result = InitOpenLibSys(&hOpenLibSys); if(result == FALSE) hOpenLibSys = NULL; return result==TRUE; } class SystemWideLock { HANDLE globalMutex; public: SystemWideLock() { globalMutex = CreateMutex(NULL, FALSE, L"Global\\Intel(r) Performance Counter Monitor instance create/destroy lock"); // lock WaitForSingleObject(globalMutex, INFINITE); } ~SystemWideLock() { // unlock ReleaseMutex(globalMutex); } }; #else // Linux or Apple class SystemWideLock { const char * globalSemaphoreName; sem_t * globalSemaphore; public: SystemWideLock() : globalSemaphoreName(PCM_INSTANCE_LOCK_SEMAPHORE_NAME) { umask(0); while (1) { //sem_unlink(globalSemaphoreName); // temporary globalSemaphore = sem_open(globalSemaphoreName, O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1); if (SEM_FAILED == globalSemaphore) { if (EACCES == errno) { std::cout << "PCM Error, do not have permissions to open semaphores in /dev/shm/. Waiting one second and retrying..." << std::endl; sleep(1); } } else { /* if (sem_post(globalSemaphore)) { perror("sem_post error"); } */ break; // success } } if (sem_wait(globalSemaphore)) { perror("sem_wait error"); } } ~SystemWideLock() { if (sem_post(globalSemaphore)) { perror("sem_post error"); } } }; #endif // end of _MSC_VER else PCM * PCM::instance = NULL; int bitCount(uint64 n) { int count = 0; while (n) { count += (int)(n & 0x00000001); n >>= 1; } return count; } PCM * PCM::getInstance() { // no lock here if (instance) return instance; SystemWideLock lock; if (instance) return instance; return instance = new PCM(); } uint32 build_bit_ui(int beg, int end) { uint32 myll = 0; if (end == 31) { myll = (uint32)(-1); } else { myll = (1 << (end + 1)) - 1; } myll = myll >> beg; return myll; } uint32 extract_bits_ui(uint32 myin, uint32 beg, uint32 end) { uint32 myll = 0; uint32 beg1, end1; // Let the user reverse the order of beg & end. if (beg <= end) { beg1 = beg; end1 = end; } else { beg1 = end; end1 = beg; } myll = myin >> beg1; myll = myll & build_bit_ui(beg1, end1); return myll; } uint64 build_bit(uint32 beg, uint32 end) { uint64 myll = 0; if (end == 63) { myll = (uint64)(-1); } else { myll = (1LL << (end + 1)) - 1; } myll = myll >> beg; return myll; } uint64 extract_bits(uint64 myin, uint32 beg, uint32 end) { uint64 myll = 0; uint32 beg1, end1; // Let the user reverse the order of beg & end. if (beg <= end) { beg1 = beg; end1 = end; } else { beg1 = end; end1 = beg; } myll = myin >> beg1; myll = myll & build_bit(beg1, end1); return myll; } uint64 PCM::extractCoreGenCounterValue(uint64 val) { if(core_gen_counter_width) return extract_bits(val, 0, core_gen_counter_width-1); return val; } uint64 PCM::extractCoreFixedCounterValue(uint64 val) { if(core_fixed_counter_width) return extract_bits(val, 0, core_fixed_counter_width-1); return val; } uint64 PCM::extractUncoreGenCounterValue(uint64 val) { if(uncore_gen_counter_width) return extract_bits(val, 0, uncore_gen_counter_width-1); return val; } uint64 PCM::extractUncoreFixedCounterValue(uint64 val) { if(uncore_fixed_counter_width) return extract_bits(val, 0, uncore_fixed_counter_width-1); return val; } int32 extractThermalHeadroom(uint64 val) { if(val & (1ULL<<31ULL)) { // valid reading return (int32)extract_bits(val,16,22); } // invalid reading return PCM_INVALID_THERMAL_HEADROOM; } uint64 get_frequency_from_cpuid(); union PCM_CPUID_INFO { int array[4]; struct { int eax,ebx,ecx,edx; } reg ; }; void pcm_cpuid(int leaf, PCM_CPUID_INFO & info) { #ifdef _MSC_VER // version for Windows __cpuid(info.array, leaf); #else __asm__ __volatile__ ("cpuid" : \ "=a" (info.reg.eax), "=b" (info.reg.ebx), "=c" (info.reg.ecx), "=d" (info.reg.edx) : "a" (leaf)); #endif } PCM::PCM() : UnsupportedMessage("Error: unsupported processor. Only Intel(R) processors are supported (Atom(R) and microarchitecture codename Nehalem, Westmere, Sandy Bridge and Ivy Bridge)."), cpu_family(-1), cpu_model(-1), original_cpu_model(-1), threads_per_core(0), num_cores(0), num_sockets(0), core_gen_counter_num_max(0), core_gen_counter_num_used(0), // 0 means no core gen counters used core_gen_counter_width(0), core_fixed_counter_num_max(0), core_fixed_counter_num_used(0), core_fixed_counter_width(0), uncore_gen_counter_num_max(8), uncore_gen_counter_num_used(0), uncore_gen_counter_width(48), uncore_fixed_counter_num_max(1), uncore_fixed_counter_num_used(0), uncore_fixed_counter_width(48), perfmon_version(0), perfmon_config_anythread(1), nominal_frequency(0), qpi_speed(0), pkgThermalSpecPower(-1), pkgMinimumPower(-1), pkgMaximumPower(-1), MSR(NULL), server_pcicfg_uncore(NULL), clientBW(NULL), clientImcReads(NULL), clientImcWrites(NULL), disable_JKT_workaround(false), coreCStateMsr(NULL), pkgCStateMsr(NULL), mode(INVALID_MODE), canUsePerf(false) { char buffer[1024]; PCM_CPUID_INFO cpuinfo; int max_cpuid; pcm_cpuid(0, cpuinfo); memset(buffer, 0, 1024); ((int *)buffer)[0] = cpuinfo.array[1]; ((int *)buffer)[1] = cpuinfo.array[3]; ((int *)buffer)[2] = cpuinfo.array[2]; if (strncmp(buffer, "GenuineIntel", 4 * 3) != 0) { std::cout << UnsupportedMessage << std::endl; return; } max_cpuid = cpuinfo.array[0]; pcm_cpuid(1, cpuinfo); cpu_family = (((cpuinfo.array[0]) >> 8) & 0xf) | ((cpuinfo.array[0] & 0xf00000) >> 16); cpu_model = original_cpu_model = (((cpuinfo.array[0]) & 0xf0) >> 4) | ((cpuinfo.array[0] & 0xf0000) >> 12); if (max_cpuid >= 0xa) { // get counter related info pcm_cpuid(0xa, cpuinfo); perfmon_version = extract_bits_ui(cpuinfo.array[0], 0, 7); core_gen_counter_num_max = extract_bits_ui(cpuinfo.array[0], 8, 15); core_gen_counter_width = extract_bits_ui(cpuinfo.array[0], 16, 23); if (perfmon_version > 1) { core_fixed_counter_num_max = extract_bits_ui(cpuinfo.array[3], 0, 4); core_fixed_counter_width = extract_bits_ui(cpuinfo.array[3], 5, 12); } } if (cpu_family != 6) { std::cout << UnsupportedMessage << " CPU Family: " << cpu_family << std::endl; return; } if(!checkModel()) return; #define PCM_PARAM_PROTECT(...) __VA_ARGS__ #define PCM_CSTATE_ARRAY(array_ , val ) \ { \ static uint64 tmp[] = val; \ PCM_COMPILE_ASSERT( sizeof(tmp)/sizeof(uint64) == MAX_C_STATE + 1); \ array_ = tmp; \ break; \ } // fill package C state array switch(original_cpu_model) { case ATOM: case ATOM_2: case ATOM_CENTERTON: case ATOM_AVOTON: case ATOM_BAYTRAIL: PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x3F8, 0, 0x3F9, 0, 0x3FA, 0, 0, 0, 0 }) ); case NEHALEM_EP: case NEHALEM: case CLARKDALE: case WESTMERE_EP: case NEHALEM_EX: case WESTMERE_EX: PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0, 0, 0}) ); case SANDY_BRIDGE: case JAKETOWN: case IVY_BRIDGE: case IVYTOWN: PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0, 0, 0}) ); case HASWELL: case HASWELL_2: PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0, 0, 0}) ); case HASWELL_ULT: PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0x630, 0x631, 0x632}) ); default: std::cout << "PCM error: package C-states support array is not initialized. Package C-states metrics will not be shown." << std::endl; PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) ); }; // fill core C state array switch(original_cpu_model) { case ATOM: case ATOM_2: case ATOM_CENTERTON: PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) ); case NEHALEM_EP: case NEHALEM: case CLARKDALE: case WESTMERE_EP: case NEHALEM_EX: case WESTMERE_EX: PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0x3FC, 0, 0, 0x3FD, 0, 0, 0, 0}) ); case SANDY_BRIDGE: case JAKETOWN: case IVY_BRIDGE: case IVYTOWN: case HASWELL: case HASWELL_2: case HASWELL_ULT: case ATOM_BAYTRAIL: case ATOM_AVOTON: PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0x3FC, 0, 0, 0x3FD, 0x3FE, 0, 0, 0}) ); default: std::cout << "PCM error: core C-states support array is not initialized. Core C-states metrics will not be shown." << std::endl; PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) ); }; #ifdef _MSC_VER // version for Windows #ifdef COMPILE_FOR_WINDOWS_7 DWORD GroupStart[5]; // at most 4 groups on Windows 7 GroupStart[0] = 0; GroupStart[1] = GetActiveProcessorCount(0); GroupStart[2] = GroupStart[1] + GetActiveProcessorCount(1); GroupStart[3] = GroupStart[2] + GetActiveProcessorCount(2); GroupStart[4] = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS); if (GroupStart[3] + GetActiveProcessorCount(3) != GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)) { std::cout << "Error in processor group size counting (1)" << std::endl; std::cout << "Make sure your binary is compiled for 64-bit: using 'x64' platform configuration." << std::endl; return; } char * slpi = new char[sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)]; DWORD len = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX); DWORD res = GetLogicalProcessorInformationEx(RelationAll, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi, &len); while (res == FALSE) { delete[] slpi; if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { slpi = new char[len]; res = GetLogicalProcessorInformationEx(RelationAll, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi, &len); } else { std::cout << "Error in Windows function 'GetLogicalProcessorInformationEx': " << GetLastError() << std::endl; return; } } char * base_slpi = slpi; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pi = NULL; for ( ; slpi < base_slpi + len; slpi += pi->Size) { pi = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi; if (pi->Relationship == RelationProcessorCore) { threads_per_core = (pi->Processor.Flags == LTP_PC_SMT) ? 2 : 1; // std::cout << "thr per core: "<< threads_per_core << std::endl; num_cores += threads_per_core; } } if (num_cores != GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)) { std::cout << "Error in processor group size counting: " << num_cores << "!=" << GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) << std::endl; std::cout << "Make sure your binary is compiled for 64-bit: using 'x64' platform configuration." << std::endl; return; } topology.resize(num_cores); slpi = base_slpi; pi = NULL; for ( ; slpi < base_slpi + len; slpi += pi->Size) { pi = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi; if (pi->Relationship == RelationNumaNode) { ++num_sockets; for (unsigned int c = 0; c < (unsigned int)num_cores; ++c) { // std::cout << "c:"<<c<<" GroupStart[slpi->NumaNode.GroupMask.Group]: "<<GroupStart[slpi->NumaNode.GroupMask.Group]<<std::endl; if (c < GroupStart[pi->NumaNode.GroupMask.Group] || c >= GroupStart[(pi->NumaNode.GroupMask.Group) + 1]) { //std::cout <<"core "<<c<<" is not in group "<< slpi->NumaNode.GroupMask.Group << std::endl; continue; } if ((1LL << (c - GroupStart[pi->NumaNode.GroupMask.Group])) & pi->NumaNode.GroupMask.Mask) { topology[c].core_id = c; topology[c].os_id = c; topology[c].socket = pi->NumaNode.NodeNumber; // std::cout << "Core "<< c <<" is in NUMA node "<< topology[c].socket << " and belongs to processor group " << slpi->NumaNode.GroupMask.Group <<std::endl; } } } } delete[] base_slpi; #else // windows, not windows 7 int32 size = 1; SYSTEM_LOGICAL_PROCESSOR_INFORMATION * slpi = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[size]; DWORD len = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); DWORD res = GetLogicalProcessorInformation(slpi, &len); while (res == FALSE) { delete[] slpi; if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { size = (int32) len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); slpi = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[size]; res = GetLogicalProcessorInformation(slpi, &len); } else { std::cout << "Error in Windows function 'GetLogicalProcessorInformation': " << GetLastError() << std::endl; return; } } for (i = 0; i < size; ++i) { if (slpi[i].Relationship == RelationProcessorCore) { //std::cout << "Physical core found, mask: "<<slpi[i].ProcessorMask<< std::endl; threads_per_core = bitCount(slpi[i].ProcessorMask); num_cores += threads_per_core; } } topology.resize(num_cores); for (i = 0; i < size; ++i) { if (slpi[i].Relationship == RelationNumaNode) { //std::cout << "NUMA node "<<slpi[i].NumaNode.NodeNumber<<" cores: "<<slpi[i].ProcessorMask<< std::endl; ++num_sockets; for (int c = 0; c < num_cores; ++c) { if ((1LL << c) & slpi[i].ProcessorMask) { topology[c].core_id = c; topology[c].os_id = c; topology[c].socket = slpi[i].NumaNode.NodeNumber; //std::cout << "Core "<< c <<" is in NUMA node "<< topology[c].socket << std::endl; } } } } delete[] slpi; #endif // end of COMPILE_FOR_WINDOWS_7 #else // for Linux and Mac OS TopologyEntry entry; typedef std::map<uint32, uint32> socketIdMap_type; socketIdMap_type socketIdMap; #ifdef __linux__ // open /proc/cpuinfo FILE * f_cpuinfo = fopen("/proc/cpuinfo", "r"); if (!f_cpuinfo) { std::cout << "Can not open /proc/cpuinfo file." << std::endl; return; } while (0 != fgets(buffer, 1024, f_cpuinfo)) { if (strncmp(buffer, "processor", sizeof("processor") - 1) == 0) { if (entry.os_id >= 0) { topology.push_back(entry); if (entry.socket == 0 && entry.core_id == 0) ++threads_per_core; } sscanf(buffer, "processor\t: %d", &entry.os_id); //std::cout << "os_core_id: "<<entry.os_id<< std::endl; continue; } if (strncmp(buffer, "physical id", sizeof("physical id") - 1) == 0) { sscanf(buffer, "physical id\t: %d", &entry.socket); //std::cout << "physical id: "<<entry.socket<< std::endl; socketIdMap[entry.socket] = 0; continue; } if (strncmp(buffer, "core id", sizeof("core id") - 1) == 0) { sscanf(buffer, "core id\t: %d", &entry.core_id); //std::cout << "core id: "<<entry.core_id<< std::endl; continue; } } if (entry.os_id >= 0) { topology.push_back(entry); if (entry.socket == 0 && entry.core_id == 0) ++threads_per_core; } fclose(f_cpuinfo); #elif defined(__FreeBSD__) size_t size = sizeof(num_cores); cpuctl_cpuid_args_t cpuid_args; int fd, apic_ids_per_package, apic_ids_per_core; if(0 != sysctlbyname("kern.smp.cpus", &num_cores, &size, NULL, 0)) { std::cout << "Unable to get kern.smp.cpus from sysctl." << std::endl; return; } do_cpuid(1, cpuid_args.data); apic_ids_per_package = (cpuid_args.data[1] & 0x00FF0000) >> 16; cpuid_count(0xb, 0x0, cpuid_args.data); if ((cpuid_args.data[2] & 0xFF00) == 0x100) apic_ids_per_core = cpuid_args.data[1] & 0xFFFF; else apic_ids_per_core = 1; for (i = 0; i < num_cores; i++) { char cpuctl_name[64]; int apic_id; sprintf(cpuctl_name, "/dev/cpuctl%d", i); fd = ::open(cpuctl_name, O_RDWR); cpuid_args.level = 0xb; ::ioctl(fd, CPUCTL_CPUID, &cpuid_args); apic_id = cpuid_args.data[3]; entry.os_id = i; entry.socket = apic_id / apic_ids_per_package; entry.core_id = (apic_id % apic_ids_per_package) / apic_ids_per_core; if (entry.socket == 0 && entry.core_id == 0) ++threads_per_core; topology.push_back(entry); socketIdMap[entry.socket] = 0; } #else // Getting processor info for Mac OS #define SAFE_SYSCTLBYNAME(message, ret_value) \ { \ size_t size; \ char *pParam; \ if(0 != sysctlbyname(message, NULL, &size, NULL, 0)) \ { \ std::cout << "Unable to determine size of " << message << " sysctl return type." << std::endl; \ return; \ } \ if(NULL == (pParam = (char *)malloc(size))) \ { \ std::cout << "Unable to allocate memory for " << message << std::endl; \ return; \ } \ if(0 != sysctlbyname(message, (void*)pParam, &size, NULL, 0)) \ { \ std::cout << "Unable to get " << message << " from sysctl." << std::endl; \ return; \ } \ ret_value = convertUnknownToInt(size, pParam); \ free(pParam); \ } // End SAFE_SYSCTLBYNAME // Using OSXs sysctl to get the number of CPUs right away SAFE_SYSCTLBYNAME("hw.logicalcpu", num_cores) #undef SAFE_SYSCTLBYNAME // The OSX version needs the MSR handle earlier so that it can build the CPU topology. // This topology functionality should potentially go into a different KEXT MSR = new MsrHandle *[num_cores]; for(int i = 0; i < num_cores; i++) { MSR[i] = new MsrHandle(i); } TopologyEntry *entries = new TopologyEntry[num_cores]; MSR[0]->buildTopology(num_cores, entries); for(int i = 0; i < num_cores; i++){ socketIdMap[entries[i].socket] = 0; if(entries[i].os_id >= 0) { if(entries[i].core_id == 0 && entries[i].socket == 0) ++threads_per_core; topology.push_back(entries[i]); } } delete entries; // End of OSX specific code #endif // end of ifndef __APPLE__ num_cores = topology.size(); num_sockets = (std::max)(socketIdMap.size(), (size_t)1); socketIdMap_type::iterator s = socketIdMap.begin(); for (uint sid = 0; s != socketIdMap.end(); ++s) { s->second = sid++; } for (int i = 0; i < num_cores; ++i) { topology[i].socket = socketIdMap[topology[i].socket]; } #if 0 std::cout << "Number of socket ids: " << socketIdMap.size() << "\n"; std::cout << "Topology:\nsocket os_id core_id\n"; for (int i = 0; i < num_cores; ++i) { std::cout << topology[i].socket << " " << topology[i].os_id << " " << topology[i].core_id << std::endl; } #endif #endif //end of ifdef _MSC_VER std::cout << "Number of physical cores: " << (num_cores/threads_per_core) << std::endl; std::cout << "Number of logical cores: " << num_cores << std::endl; std::cout << "Threads (logical cores) per physical core: " << threads_per_core << std::endl; std::cout << "Num sockets: " << num_sockets << std::endl; std::cout << "Core PMU (perfmon) version: " << perfmon_version << std::endl; std::cout << "Number of core PMU generic (programmable) counters: " << core_gen_counter_num_max << std::endl; std::cout << "Width of generic (programmable) counters: " << core_gen_counter_width << " bits" << std::endl; if (perfmon_version > 1) { std::cout << "Number of core PMU fixed counters: " << core_fixed_counter_num_max << std::endl; std::cout << "Width of fixed counters: " << core_fixed_counter_width << " bits" << std::endl; } socketRefCore.resize(num_sockets); int32 i = 0; #ifndef __APPLE__ MSR = new MsrHandle *[num_cores]; try { for (i = 0; i < num_cores; ++i) { MSR[i] = new MsrHandle(i); socketRefCore[topology[i].socket] = i; } } catch (...) { // failed for (int j = 0; j < i; j++) delete MSR[j]; delete[] MSR; MSR = NULL; std::cerr << "Can not access CPUs Model Specific Registers (MSRs)." << std::endl; #ifdef _MSC_VER std::cerr << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program." << std::endl; #elif defined(__linux__) std::cerr << "Try to execute 'modprobe msr' as root user and then" << std::endl; std::cerr << "you also must have read and write permissions for /dev/cpu/*/msr devices (/dev/msr* for Android). The 'chown' command can help." << std::endl; #elif defined(__FreeBSD__) std::cerr << "Ensure cpuctl module is loaded and that you have read and write" << std::endl; std::cerr << "permissions for /dev/cpuctl* devices (the 'chown' command can help)." << std::endl; #endif } #else for(i = 0; i < num_cores; ++i) { socketRefCore[topology[i].socket] = i; } #endif if (MSR) { uint64 freq = 0; MSR[0]->read(PLATFORM_INFO_ADDR, &freq); const uint64 bus_freq = ( cpu_model == SANDY_BRIDGE || cpu_model == JAKETOWN || cpu_model == IVYTOWN || cpu_model == IVY_BRIDGE || cpu_model == HASWELL || original_cpu_model == ATOM_AVOTON ) ? (100000000ULL) : (133333333ULL); nominal_frequency = ((freq >> 8) & 255) * bus_freq; if(!nominal_frequency) nominal_frequency = get_frequency_from_cpuid(); if(!nominal_frequency) { std::cout << "Error: Can not detect core frequency." << std::endl; destroyMSR(); return; } std::cout << "Nominal core frequency: " << nominal_frequency << " Hz" << std::endl; } if(packageEnergyMetricsAvailable() && MSR) { uint64 rapl_power_unit = 0; MSR[0]->read(MSR_RAPL_POWER_UNIT,&rapl_power_unit); uint64 energy_status_unit = extract_bits(rapl_power_unit,8,12); joulesPerEnergyUnit = 1./double(1ULL<<energy_status_unit); // (1/2)^energy_status_unit //std::cout << "MSR_RAPL_POWER_UNIT: "<<energy_status_unit<<"; Joules/unit "<< joulesPerEnergyUnit << std::endl; uint64 power_unit = extract_bits(rapl_power_unit,0,3); double wattsPerPowerUnit = 1./double(1ULL<<power_unit); uint64 package_power_info = 0; MSR[0]->read(MSR_PKG_POWER_INFO,&package_power_info); pkgThermalSpecPower = (uint32) (double(extract_bits(package_power_info, 0, 14))*wattsPerPowerUnit); pkgMinimumPower = (uint32) (double(extract_bits(package_power_info, 16, 30))*wattsPerPowerUnit); pkgMaximumPower = (uint32) (double(extract_bits(package_power_info, 32, 46))*wattsPerPowerUnit); std::cout << "Package thermal spec power: "<< pkgThermalSpecPower << " Watt; "; std::cout << "Package minimum power: "<< pkgMinimumPower << " Watt; "; std::cout << "Package maximum power: "<< pkgMaximumPower << " Watt; " << std::endl; if(snb_energy_status.empty()) for (i = 0; i < num_sockets; ++i) snb_energy_status.push_back(new CounterWidthExtender(new CounterWidthExtender::MsrHandleCounter(MSR[socketRefCore[i]],MSR_PKG_ENERGY_STATUS)) ); if(dramEnergyMetricsAvailable() && jkt_dram_energy_status.empty()) for (i = 0; i < num_sockets; ++i) jkt_dram_energy_status.push_back(new CounterWidthExtender(new CounterWidthExtender::MsrHandleCounter(MSR[socketRefCore[i]],MSR_DRAM_ENERGY_STATUS))); } if (hasPCICFGUncore() && MSR != NULL) { server_pcicfg_uncore = new ServerPCICFGUncore *[num_sockets]; try { for (i = 0; i < num_sockets; ++i) { server_pcicfg_uncore[i] = new ServerPCICFGUncore(i, this); } } catch (...) { // failed for (int j = 0; j < i; j++) delete server_pcicfg_uncore[j]; delete[] server_pcicfg_uncore; server_pcicfg_uncore = NULL; std::cerr << "Can not access Jaketown/Ivytown PCI configuration space. Access to uncore counters (memory and QPI bandwidth) is disabled." << std::endl; #ifdef _MSC_VER std::cerr << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program." << std::endl; #else //std::cerr << "you must have read and write permissions for /proc/bus/pci/7f/10.* and /proc/bus/pci/ff/10.* devices (the 'chown' command can help)." << std::endl; //std::cerr << "you must have read and write permissions for /dev/mem device (the 'chown' command can help)."<< std::endl; //std::cerr << "you must have read permission for /sys/firmware/acpi/tables/MCFG device (the 'chmod' command can help)."<< std::endl; std::cerr << "You must be root to access these Jaketown/Ivytown counters in PCM. " << std::endl; #endif } } else if((cpu_model == SANDY_BRIDGE || cpu_model == IVY_BRIDGE || cpu_model == HASWELL) && MSR != NULL) { // initialize memory bandwidth counting try { clientBW = new ClientBW(); clientImcReads = new CounterWidthExtender(new CounterWidthExtender::ClientImcReadsCounter(clientBW)); clientImcWrites = new CounterWidthExtender(new CounterWidthExtender::ClientImcWritesCounter(clientBW)); } catch(...) { std::cerr << "Can not read memory controller counter information from PCI configuration space. Access to memory bandwidth counters is not possible." << std::endl; #ifdef _MSC_VER // TODO: add message here #endif #ifdef __linux__ std::cerr << "You must be root to access these SandyBridge/IvyBridge/Haswell counters in PCM. " << std::endl; #endif } } PCU_MSR_PMON_BOX_CTL_ADDR = JKTIVT_PCU_MSR_PMON_BOX_CTL_ADDR; PCU_MSR_PMON_CTRX_ADDR[0] = JKTIVT_PCU_MSR_PMON_CTR0_ADDR; PCU_MSR_PMON_CTRX_ADDR[1] = JKTIVT_PCU_MSR_PMON_CTR1_ADDR; PCU_MSR_PMON_CTRX_ADDR[2] = JKTIVT_PCU_MSR_PMON_CTR2_ADDR; PCU_MSR_PMON_CTRX_ADDR[3] = JKTIVT_PCU_MSR_PMON_CTR3_ADDR; #ifdef PCM_USE_PERF canUsePerf = true; std::vector<int> dummy(PERF_MAX_COUNTERS, -1); perfEventHandle.resize(num_cores, dummy); #endif } void PCM::enableJKTWorkaround(bool enable) { if(disable_JKT_workaround) return; std::cout << "Using PCM on your system might have a performance impact as per http://software.intel.com/en-us/articles/performance-impact-when-sampling-certain-llc-events-on-snb-ep-with-vtune" << std::endl; std::cout << "You can avoid the performance impact by using the option --noJKTWA, however the cache metrics might be wrong then." << std::endl; if(MSR) { for(int32 i = 0; i < num_cores; ++i) { uint64 val64 = 0; MSR[i]->read(0x39C, &val64); if(enable) val64 |= 1ULL; else val64 &= (~1ULL); MSR[i]->write(0x39C, val64); } } if(server_pcicfg_uncore) { for (int32 i = 0; i < num_sockets; ++i) { if(server_pcicfg_uncore[i]) server_pcicfg_uncore[i]->enableJKTWorkaround(enable); } } } bool PCM::isCPUModelSupported(int model_) { return ( model_ == NEHALEM_EP || model_ == NEHALEM_EX || model_ == WESTMERE_EP || model_ == WESTMERE_EX || model_ == ATOM || model_ == CLARKDALE || model_ == SANDY_BRIDGE || model_ == JAKETOWN || model_ == IVY_BRIDGE || model_ == HASWELL || model_ == IVYTOWN ); } bool PCM::checkModel() { if (cpu_model == NEHALEM) cpu_model = NEHALEM_EP; if (cpu_model == ATOM_2 || cpu_model == ATOM_CENTERTON || cpu_model == ATOM_BAYTRAIL || cpu_model == ATOM_AVOTON) cpu_model = ATOM; if (cpu_model == HASWELL_ULT || cpu_model == HASWELL_2) cpu_model = HASWELL; if(!isCPUModelSupported(cpu_model)) { std::cout << UnsupportedMessage << " CPU model number: " << cpu_model << " Brand: \"" << getCPUBrandString().c_str() <<"\""<< std::endl; /* FOR TESTING PURPOSES ONLY */ #ifdef PCM_TEST_FALLBACK_TO_ATOM std::cout << "Fall back to ATOM functionality." << std::endl; cpu_model = ATOM; return true; #endif return false; } return true; } void PCM::destroyMSR() { if (MSR) { for (int i = 0; i < num_cores; ++i) if (MSR[i]) delete MSR[i]; delete[] MSR; MSR = NULL; } } PCM::~PCM() { SystemWideLock lock; if (instance) { destroyMSR(); if (server_pcicfg_uncore) { for (int i = 0; i < num_sockets; ++i) if (server_pcicfg_uncore[i]) delete server_pcicfg_uncore[i]; delete[] server_pcicfg_uncore; } for (uint32 i = 0; i < snb_energy_status.size(); ++i) { delete snb_energy_status[i]; } for (uint32 i = 0; i < jkt_dram_energy_status.size(); ++i) delete jkt_dram_energy_status[i]; instance = NULL; if(clientImcReads) delete clientImcReads; clientImcReads = NULL; if(clientImcWrites) delete clientImcWrites; clientImcWrites = NULL; if(clientBW) delete clientBW; clientBW = NULL; } } bool PCM::good() { return MSR != NULL; } class TemporalThreadAffinity // speedup trick for Linux { #ifdef __linux__ cpu_set_t old_affinity; TemporalThreadAffinity(); // forbiden public: TemporalThreadAffinity(uint32 core_id) { pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &old_affinity); cpu_set_t new_affinity; CPU_ZERO(&new_affinity); CPU_SET(core_id, &new_affinity); pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &new_affinity); } ~TemporalThreadAffinity() { pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &old_affinity); } #else // not implemented for windows or os x TemporalThreadAffinity(); // forbiden public: TemporalThreadAffinity(uint32) { } #endif }; #ifdef PCM_USE_PERF perf_event_attr PCM_init_perf_event_attr() { perf_event_attr e; bzero(&e,sizeof(perf_event_attr)); e.type = -1; // must be set up later e.size = sizeof(e); e.config = -1; // must be set up later e.sample_period = 0; e.sample_type = 0; e.read_format = PERF_FORMAT_GROUP; /* PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID | PERF_FORMAT_GROUP ; */ e.disabled = 0; e.inherit = 0; e.pinned = 1; e.exclusive = 0; e.exclude_user = 0; e.exclude_kernel = 0; e.exclude_hv = 0; e.exclude_idle = 0; e.mmap = 0; e.comm = 0; e.freq = 0; e.inherit_stat = 0; e.enable_on_exec = 0; e.task = 0; e.watermark = 0; e.wakeup_events = 0; return e; } #endif PCM::ErrorCode PCM::program(PCM::ProgramMode mode_, void * parameter_) { SystemWideLock lock; if (!MSR) return PCM::MSRAccessDenied; ExtendedCustomCoreEventDescription * pExtDesc = (ExtendedCustomCoreEventDescription *)parameter_; #ifdef PCM_USE_PERF std::cout << "Trying to use Linux perf events..." << std::endl; if(PERF_COUNT_HW_MAX <= PCM_PERF_COUNT_HW_REF_CPU_CYCLES) { canUsePerf = false; std::cout << "Can not use Linux perf because your Linux kernel does not support PERF_COUNT_HW_REF_CPU_CYCLES event. Falling-back to direct PMU programming." << std::endl; } if(EXT_CUSTOM_CORE_EVENTS == mode_ && pExtDesc && pExtDesc->fixedCfg) { canUsePerf = false; std::cout << "Can not use Linux perf because non-standard fixed counter configuration requested. Falling-back to direct PMU programming." << std::endl; } if(EXT_CUSTOM_CORE_EVENTS == mode_ && pExtDesc && (pExtDesc->OffcoreResponseMsrValue[0] || pExtDesc->OffcoreResponseMsrValue[1])) { canUsePerf = false; std::cout << "Can not use Linux perf because OffcoreResponse counter usage requested. Falling-back to direct PMU programming." << std::endl; } #endif //std::cout << "Checking for other instances of PCM..." << std::endl; #ifdef _MSC_VER #if 1 numInstancesSemaphore = CreateSemaphore(NULL, 0, 1 << 20, L"Global\\Number of running Intel Processor Counter Monitor instances"); if (!numInstancesSemaphore) { std::cout << "Error in Windows function 'CreateSemaphore': " << GetLastError() << std::endl; return PCM::UnknownError; } LONG prevValue = 0; if (!ReleaseSemaphore(numInstancesSemaphore, 1, &prevValue)) { std::cout << "Error in Windows function 'ReleaseSemaphore': " << GetLastError() << std::endl; return PCM::UnknownError; } if (prevValue > 0) // already programmed since another instance exists { std::cout << "Number of PCM instances: " << (prevValue + 1) << std::endl; if (hasPCICFGUncore() && server_pcicfg_uncore && server_pcicfg_uncore[0] && qpi_speed==0) qpi_speed = server_pcicfg_uncore[0]->computeQPISpeed(); reportQPISpeed(); return PCM::Success; } #endif #else // if linux or apple numInstancesSemaphore = sem_open(PCM_NUM_INSTANCES_SEMAPHORE_NAME, O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 0); if (SEM_FAILED == numInstancesSemaphore) { if (EACCES == errno) std::cout << "PCM Error, do not have permissions to open semaphores in /dev/shm/. Clean up them." << std::endl; return PCM::UnknownError; } #ifndef __APPLE__ sem_post(numInstancesSemaphore); int curValue = 0; sem_getvalue(numInstancesSemaphore, &curValue); #else //if it is apple uint32 curValue = PCM::incrementNumInstances(); sem_post(numInstancesSemaphore); #endif // end ifndef __APPLE__ if (curValue > 1) // already programmed since another instance exists { std::cout << "Number of PCM instances: " << curValue << std::endl; if (hasPCICFGUncore() && server_pcicfg_uncore && server_pcicfg_uncore[0] && qpi_speed==0) qpi_speed = server_pcicfg_uncore[0]->computeQPISpeed(); reportQPISpeed(); if(!canUsePerf) return PCM::Success; } #endif // end ifdef _MSC_VER #ifdef PCM_USE_PERF /* numInst>1 && canUsePerf==false -> not reachable, already PMU programmed in another PCM instance numInst>1 && canUsePerf==true -> perf programmed in different PCM, is not allowed numInst<=1 && canUsePerf==false -> we are first, perf cannot be used, *check* if PMU busy numInst<=1 && canUsePerf==true -> we are first, perf will be used, *dont check*, this is now perf business */ if(curValue > 1 && (canUsePerf == true)) { std::cout << "Running several clients using the same counters is not posible with Linux perf. Recompile PCM without Linux Perf support to allow such usage. " << std::endl; decrementInstanceSemaphore(); return PCM::UnknownError; } if((curValue <= 1) && (canUsePerf == false)) #endif if (PMUinUse()) { decrementInstanceSemaphore(); return PCM::PMUBusy; } mode = mode_; // copy custom event descriptions if (mode == CUSTOM_CORE_EVENTS) { if (!parameter_) { std::cout << "PCM Internal Error: data structure for custom event not initialized" << std::endl; return PCM::UnknownError; } CustomCoreEventDescription * pDesc = (CustomCoreEventDescription *)parameter_; coreEventDesc[0] = pDesc[0]; coreEventDesc[1] = pDesc[1]; if (cpu_model != ATOM) { coreEventDesc[2] = pDesc[2]; coreEventDesc[3] = pDesc[3]; core_gen_counter_num_used = 4; } else core_gen_counter_num_used = 2; } else { if (cpu_model == ATOM) { coreEventDesc[0].event_number = ARCH_LLC_MISS_EVTNR; coreEventDesc[0].umask_value = ARCH_LLC_MISS_UMASK; coreEventDesc[1].event_number = ARCH_LLC_REFERENCE_EVTNR; coreEventDesc[1].umask_value = ARCH_LLC_REFERENCE_UMASK; core_gen_counter_num_used = 2; } else if ( SANDY_BRIDGE == cpu_model || JAKETOWN == cpu_model || IVYTOWN == cpu_model || IVY_BRIDGE == cpu_model || HASWELL == cpu_model ) { coreEventDesc[0].event_number = ARCH_LLC_MISS_EVTNR; coreEventDesc[0].umask_value = ARCH_LLC_MISS_UMASK; coreEventDesc[1].event_number = MEM_LOAD_UOPS_LLC_HIT_RETIRED_XSNP_NONE_EVTNR; coreEventDesc[1].umask_value = MEM_LOAD_UOPS_LLC_HIT_RETIRED_XSNP_NONE_UMASK; coreEventDesc[2].event_number = MEM_LOAD_UOPS_LLC_HIT_RETIRED_XSNP_EVTNR; coreEventDesc[2].umask_value = MEM_LOAD_UOPS_LLC_HIT_RETIRED_XSNP_UMASK; coreEventDesc[3].event_number = MEM_LOAD_UOPS_RETIRED_L2_HIT_EVTNR; coreEventDesc[3].umask_value = MEM_LOAD_UOPS_RETIRED_L2_HIT_UMASK; core_gen_counter_num_used = 4; } else { // Nehalem or Westmere if( NEHALEM_EP == cpu_model || WESTMERE_EP == cpu_model || CLARKDALE == cpu_model ) { coreEventDesc[0].event_number = MEM_LOAD_RETIRED_L3_MISS_EVTNR; coreEventDesc[0].umask_value = MEM_LOAD_RETIRED_L3_MISS_UMASK; } else { coreEventDesc[0].event_number = ARCH_LLC_MISS_EVTNR; coreEventDesc[0].umask_value = ARCH_LLC_MISS_UMASK; } coreEventDesc[1].event_number = MEM_LOAD_RETIRED_L3_UNSHAREDHIT_EVTNR; coreEventDesc[1].umask_value = MEM_LOAD_RETIRED_L3_UNSHAREDHIT_UMASK; coreEventDesc[2].event_number = MEM_LOAD_RETIRED_L2_HITM_EVTNR; coreEventDesc[2].umask_value = MEM_LOAD_RETIRED_L2_HITM_UMASK; coreEventDesc[3].event_number = MEM_LOAD_RETIRED_L2_HIT_EVTNR; coreEventDesc[3].umask_value = MEM_LOAD_RETIRED_L2_HIT_UMASK; core_gen_counter_num_used = 4; } } core_fixed_counter_num_used = 3; if(EXT_CUSTOM_CORE_EVENTS == mode_ && pExtDesc && pExtDesc->gpCounterCfg) { core_gen_counter_num_used = (std::min)(core_gen_counter_num_used,pExtDesc->nGPCounters); } if(cpu_model == JAKETOWN) { bool enableWA = false; for(uint32 i = 0; i< core_gen_counter_num_used; ++i) { if(coreEventDesc[i].event_number == MEM_LOAD_UOPS_LLC_HIT_RETIRED_XSNP_EVTNR) enableWA = true; } enableJKTWorkaround(enableWA); // this has a performance penalty on memory access } // Version for linux/windows for (int i = 0; i < num_cores; ++i) { // program core counters TemporalThreadAffinity tempThreadAffinity(i); // speedup trick for Linux FixedEventControlRegister ctrl_reg; #ifdef PCM_USE_PERF int leader_counter = -1; perf_event_attr e = PCM_init_perf_event_attr(); if(canUsePerf) { e.type = PERF_TYPE_HARDWARE; e.config = (((long long unsigned)PERF_TYPE_HARDWARE)<<(64ULL-8ULL)) + PERF_COUNT_HW_INSTRUCTIONS; if((perfEventHandle[i][PERF_INST_RETIRED_ANY_POS] = syscall(SYS_perf_event_open, &e, -1, i /* core id */, leader_counter /* group leader */ ,0 )) <= 0) { std::cout <<"Linux Perf: Error on programming INST_RETIRED_ANY: "<<strerror(errno)<< std::endl; decrementInstanceSemaphore(); return PCM::UnknownError; } leader_counter = perfEventHandle[i][PERF_INST_RETIRED_ANY_POS]; e.pinned = 0; // all following counter are not leaders, thus need not be pinned explicitly e.config = (((long long unsigned)PERF_TYPE_HARDWARE)<<(64ULL-8ULL)) + PERF_COUNT_HW_CPU_CYCLES; if( (perfEventHandle[i][PERF_CPU_CLK_UNHALTED_THREAD_POS] = syscall(SYS_perf_event_open, &e, -1, i /* core id */, leader_counter /* group leader */ ,0 )) <= 0) { std::cout <<"Linux Perf: Error on programming CPU_CLK_UNHALTED_THREAD: "<<strerror(errno)<< std::endl; decrementInstanceSemaphore(); return PCM::UnknownError; } e.config = (((long long unsigned)PERF_TYPE_HARDWARE)<<(64ULL-8ULL)) + PCM_PERF_COUNT_HW_REF_CPU_CYCLES; if((perfEventHandle[i][PERF_CPU_CLK_UNHALTED_REF_POS] = syscall(SYS_perf_event_open, &e, -1, i /* core id */, leader_counter /* group leader */ ,0 )) <= 0) { std::cout <<"Linux Perf: Error on programming CPU_CLK_UNHALTED_REF: "<<strerror(errno)<< std::endl; decrementInstanceSemaphore(); return PCM::UnknownError; } } else #endif { // disable counters while programming MSR[i]->write(IA32_CR_PERF_GLOBAL_CTRL, 0); MSR[i]->read(IA32_CR_FIXED_CTR_CTRL, &ctrl_reg.value); if(EXT_CUSTOM_CORE_EVENTS == mode_ && pExtDesc && pExtDesc->fixedCfg) { ctrl_reg = *(pExtDesc->fixedCfg); } else { ctrl_reg.fields.os0 = 1; ctrl_reg.fields.usr0 = 1; ctrl_reg.fields.any_thread0 = 0; ctrl_reg.fields.enable_pmi0 = 0; ctrl_reg.fields.os1 = 1; ctrl_reg.fields.usr1 = 1; ctrl_reg.fields.any_thread1 = 0; ctrl_reg.fields.enable_pmi1 = 0; ctrl_reg.fields.os2 = 1; ctrl_reg.fields.usr2 = 1; ctrl_reg.fields.any_thread2 = 0; ctrl_reg.fields.enable_pmi2 = 0; } MSR[i]->write(IA32_CR_FIXED_CTR_CTRL, ctrl_reg.value); } if(EXT_CUSTOM_CORE_EVENTS == mode_ && pExtDesc) { if(pExtDesc->OffcoreResponseMsrValue[0]) MSR[i]->write(MSR_OFFCORE_RSP0, pExtDesc->OffcoreResponseMsrValue[0]); if(pExtDesc->OffcoreResponseMsrValue[1]) MSR[i]->write(MSR_OFFCORE_RSP1, pExtDesc->OffcoreResponseMsrValue[1]); } EventSelectRegister event_select_reg; for (uint32 j = 0; j < core_gen_counter_num_used; ++j) { if(EXT_CUSTOM_CORE_EVENTS == mode_ && pExtDesc && pExtDesc->gpCounterCfg) { event_select_reg = pExtDesc->gpCounterCfg[j]; } else { MSR[i]->read(IA32_PERFEVTSEL0_ADDR + j, &event_select_reg.value); // read-only also safe for perf event_select_reg.fields.event_select = coreEventDesc[j].event_number; event_select_reg.fields.umask = coreEventDesc[j].umask_value; event_select_reg.fields.usr = 1; event_select_reg.fields.os = 1; event_select_reg.fields.edge = 0; event_select_reg.fields.pin_control = 0; event_select_reg.fields.apic_int = 0; event_select_reg.fields.any_thread = 0; event_select_reg.fields.enable = 1; event_select_reg.fields.invert = 0; event_select_reg.fields.cmask = 0; event_select_reg.fields.in_tx = 0; event_select_reg.fields.in_txcp = 0; } #ifdef PCM_USE_PERF if(canUsePerf) { e.type = PERF_TYPE_RAW; e.config = (1ULL<<63ULL) + (((long long unsigned)PERF_TYPE_RAW)<<(64ULL-8ULL)) + event_select_reg.value; if((perfEventHandle[i][PERF_GEN_EVENT_0_POS + j] = syscall(SYS_perf_event_open, &e, -1, i /* core id */, leader_counter /* group leader */ ,0 )) <= 0) { std::cout <<"Linux Perf: Error on programming generic event #"<< i <<" error: "<<strerror(errno)<< std::endl; decrementInstanceSemaphore(); return PCM::UnknownError; } } else #endif { MSR[i]->write(IA32_PMC0 + j, 0); MSR[i]->write(IA32_PERFEVTSEL0_ADDR + j, event_select_reg.value); } } if(!canUsePerf) { // start counting, enable all (4 programmable + 3 fixed) counters uint64 value = (1ULL << 0) + (1ULL << 1) + (1ULL << 2) + (1ULL << 3) + (1ULL << 32) + (1ULL << 33) + (1ULL << 34); if (cpu_model == ATOM) // Atom has only 2 programmable counters value = (1ULL << 0) + (1ULL << 1) + (1ULL << 32) + (1ULL << 33) + (1ULL << 34); MSR[i]->write(IA32_CR_PERF_GLOBAL_CTRL, value); } // program uncore counters if (cpu_model == NEHALEM_EP || cpu_model == WESTMERE_EP || cpu_model == CLARKDALE) { programNehalemEPUncore(i); } else if (hasBecktonUncore()) { programBecktonUncore(i); } } if(canUsePerf) { std::cout << "Successfully programmed on-core PMU using Linux perf"<<std::endl; } if (hasPCICFGUncore() && server_pcicfg_uncore) { for (int i = 0; i < num_sockets; ++i) { server_pcicfg_uncore[i]->program(); if(i==0 && qpi_speed==0) qpi_speed = server_pcicfg_uncore[i]->computeQPISpeed(); } } reportQPISpeed(); return PCM::Success; } void PCM::reportQPISpeed() const { if(qpi_speed) { std::cout.precision(1); std::cout << std::fixed; std::cout << "Max QPI link speed: " << qpi_speed / (1e9) << " GBytes/second (" << qpi_speed / (2e9) << " GT/second)" << std::endl; } } void PCM::programNehalemEPUncore(int32 core) { #define CPUCNT_INIT_THE_REST_OF_EVTCNT \ unc_event_select_reg.fields.occ_ctr_rst = 1; \ unc_event_select_reg.fields.edge = 0; \ unc_event_select_reg.fields.enable_pmi = 0; \ unc_event_select_reg.fields.enable = 1; \ unc_event_select_reg.fields.invert = 0; \ unc_event_select_reg.fields.cmask = 0; uncore_gen_counter_num_used = 8; UncoreEventSelectRegister unc_event_select_reg; MSR[core]->read(MSR_UNCORE_PERFEVTSEL0_ADDR, &unc_event_select_reg.value); unc_event_select_reg.fields.event_select = UNC_QMC_WRITES_FULL_ANY_EVTNR; unc_event_select_reg.fields.umask = UNC_QMC_WRITES_FULL_ANY_UMASK; CPUCNT_INIT_THE_REST_OF_EVTCNT MSR[core]->write(MSR_UNCORE_PERFEVTSEL0_ADDR, unc_event_select_reg.value); MSR[core]->read(MSR_UNCORE_PERFEVTSEL1_ADDR, &unc_event_select_reg.value); unc_event_select_reg.fields.event_select = UNC_QMC_NORMAL_READS_ANY_EVTNR; unc_event_select_reg.fields.umask = UNC_QMC_NORMAL_READS_ANY_UMASK; CPUCNT_INIT_THE_REST_OF_EVTCNT MSR[core]->write(MSR_UNCORE_PERFEVTSEL1_ADDR, unc_event_select_reg.value); MSR[core]->read(MSR_UNCORE_PERFEVTSEL2_ADDR, &unc_event_select_reg.value); unc_event_select_reg.fields.event_select = UNC_QHL_REQUESTS_EVTNR; unc_event_select_reg.fields.umask = UNC_QHL_REQUESTS_IOH_READS_UMASK; CPUCNT_INIT_THE_REST_OF_EVTCNT MSR[core]->write(MSR_UNCORE_PERFEVTSEL2_ADDR, unc_event_select_reg.value); MSR[core]->read(MSR_UNCORE_PERFEVTSEL3_ADDR, &unc_event_select_reg.value); unc_event_select_reg.fields.event_select = UNC_QHL_REQUESTS_EVTNR; unc_event_select_reg.fields.umask = UNC_QHL_REQUESTS_IOH_WRITES_UMASK; CPUCNT_INIT_THE_REST_OF_EVTCNT MSR[core]->write(MSR_UNCORE_PERFEVTSEL3_ADDR, unc_event_select_reg.value); MSR[core]->read(MSR_UNCORE_PERFEVTSEL4_ADDR, &unc_event_select_reg.value); unc_event_select_reg.fields.event_select = UNC_QHL_REQUESTS_EVTNR; unc_event_select_reg.fields.umask = UNC_QHL_REQUESTS_REMOTE_READS_UMASK; CPUCNT_INIT_THE_REST_OF_EVTCNT MSR[core]->write(MSR_UNCORE_PERFEVTSEL4_ADDR, unc_event_select_reg.value); MSR[core]->read(MSR_UNCORE_PERFEVTSEL5_ADDR, &unc_event_select_reg.value); unc_event_select_reg.fields.event_select = UNC_QHL_REQUESTS_EVTNR; unc_event_select_reg.fields.umask = UNC_QHL_REQUESTS_REMOTE_WRITES_UMASK; CPUCNT_INIT_THE_REST_OF_EVTCNT MSR[core]->write(MSR_UNCORE_PERFEVTSEL5_ADDR, unc_event_select_reg.value); MSR[core]->read(MSR_UNCORE_PERFEVTSEL6_ADDR, &unc_event_select_reg.value); unc_event_select_reg.fields.event_select = UNC_QHL_REQUESTS_EVTNR; unc_event_select_reg.fields.umask = UNC_QHL_REQUESTS_LOCAL_READS_UMASK; CPUCNT_INIT_THE_REST_OF_EVTCNT MSR[core]->write(MSR_UNCORE_PERFEVTSEL6_ADDR, unc_event_select_reg.value); MSR[core]->read(MSR_UNCORE_PERFEVTSEL7_ADDR, &unc_event_select_reg.value); unc_event_select_reg.fields.event_select = UNC_QHL_REQUESTS_EVTNR; unc_event_select_reg.fields.umask = UNC_QHL_REQUESTS_LOCAL_WRITES_UMASK; CPUCNT_INIT_THE_REST_OF_EVTCNT MSR[core]->write(MSR_UNCORE_PERFEVTSEL7_ADDR, unc_event_select_reg.value); #undef CPUCNT_INIT_THE_REST_OF_EVTCNT // start uncore counting uint64 value = 255 + (1ULL << 32); // enable all counters MSR[core]->write(MSR_UNCORE_PERF_GLOBAL_CTRL_ADDR, value); // synchronise counters MSR[core]->write(MSR_UNCORE_PMC0, 0); MSR[core]->write(MSR_UNCORE_PMC1, 0); MSR[core]->write(MSR_UNCORE_PMC2, 0); MSR[core]->write(MSR_UNCORE_PMC3, 0); MSR[core]->write(MSR_UNCORE_PMC4, 0); MSR[core]->write(MSR_UNCORE_PMC5, 0); MSR[core]->write(MSR_UNCORE_PMC6, 0); MSR[core]->write(MSR_UNCORE_PMC7, 0); } void PCM::programBecktonUncore(int32 core) { // program Beckton uncore if (core == 0) computeQPISpeedBeckton(core); uint64 value = 1 << 29ULL; // reset all counters MSR[core]->write(U_MSR_PMON_GLOBAL_CTL, value); BecktonUncorePMUZDPCTLFVCRegister FVCreg; FVCreg.value = 0; if (cpu_model == NEHALEM_EX) { FVCreg.fields.bcmd = 0; // rd_bcmd FVCreg.fields.resp = 0; // ack_resp FVCreg.fields.evnt0 = 5; // bcmd_match FVCreg.fields.evnt1 = 6; // resp_match FVCreg.fields.pbox_init_err = 0; } else { FVCreg.fields_wsm.bcmd = 0; // rd_bcmd FVCreg.fields_wsm.resp = 0; // ack_resp FVCreg.fields_wsm.evnt0 = 5; // bcmd_match FVCreg.fields_wsm.evnt1 = 6; // resp_match FVCreg.fields_wsm.pbox_init_err = 0; } MSR[core]->write(MB0_MSR_PMU_ZDP_CTL_FVC, FVCreg.value); MSR[core]->write(MB1_MSR_PMU_ZDP_CTL_FVC, FVCreg.value); BecktonUncorePMUCNTCTLRegister CNTCTLreg; CNTCTLreg.value = 0; CNTCTLreg.fields.en = 1; CNTCTLreg.fields.pmi_en = 0; CNTCTLreg.fields.count_mode = 0; CNTCTLreg.fields.storage_mode = 0; CNTCTLreg.fields.wrap_mode = 1; CNTCTLreg.fields.flag_mode = 0; CNTCTLreg.fields.inc_sel = 0x0d; // FVC_EV0 MSR[core]->write(MB0_MSR_PMU_CNT_CTL_0, CNTCTLreg.value); MSR[core]->write(MB1_MSR_PMU_CNT_CTL_0, CNTCTLreg.value); CNTCTLreg.fields.inc_sel = 0x0e; // FVC_EV1 MSR[core]->write(MB0_MSR_PMU_CNT_CTL_1, CNTCTLreg.value); MSR[core]->write(MB1_MSR_PMU_CNT_CTL_1, CNTCTLreg.value); value = 1 + ((0x0C) << 1ULL); // enable bit + (event select IMT_INSERTS_WR) MSR[core]->write(BB0_MSR_PERF_CNT_CTL_1, value); MSR[core]->write(BB1_MSR_PERF_CNT_CTL_1, value); MSR[core]->write(MB0_MSR_PERF_GLOBAL_CTL, 3); // enable two counters MSR[core]->write(MB1_MSR_PERF_GLOBAL_CTL, 3); // enable two counters MSR[core]->write(BB0_MSR_PERF_GLOBAL_CTL, 2); // enable second counter MSR[core]->write(BB1_MSR_PERF_GLOBAL_CTL, 2); // enable second counter // program R-Box to monitor QPI traffic // enable counting on all counters on the left side (port 0-3) MSR[core]->write(R_MSR_PMON_GLOBAL_CTL_7_0, 255); // ... on the right side (port 4-7) MSR[core]->write(R_MSR_PMON_GLOBAL_CTL_15_8, 255); // pick the event value = (1 << 7ULL) + (1 << 6ULL) + (1 << 2ULL); // count any (incoming) data responses MSR[core]->write(R_MSR_PORT0_IPERF_CFG0, value); MSR[core]->write(R_MSR_PORT1_IPERF_CFG0, value); MSR[core]->write(R_MSR_PORT4_IPERF_CFG0, value); MSR[core]->write(R_MSR_PORT5_IPERF_CFG0, value); // pick the event value = (1ULL << 30ULL); // count null idle flits sent MSR[core]->write(R_MSR_PORT0_IPERF_CFG1, value); MSR[core]->write(R_MSR_PORT1_IPERF_CFG1, value); MSR[core]->write(R_MSR_PORT4_IPERF_CFG1, value); MSR[core]->write(R_MSR_PORT5_IPERF_CFG1, value); // choose counter 0 to monitor R_MSR_PORT0_IPERF_CFG0 MSR[core]->write(R_MSR_PMON_CTL0, 1 + 2 * (0)); // choose counter 1 to monitor R_MSR_PORT1_IPERF_CFG0 MSR[core]->write(R_MSR_PMON_CTL1, 1 + 2 * (6)); // choose counter 8 to monitor R_MSR_PORT4_IPERF_CFG0 MSR[core]->write(R_MSR_PMON_CTL8, 1 + 2 * (0)); // choose counter 9 to monitor R_MSR_PORT5_IPERF_CFG0 MSR[core]->write(R_MSR_PMON_CTL9, 1 + 2 * (6)); // choose counter 2 to monitor R_MSR_PORT0_IPERF_CFG1 MSR[core]->write(R_MSR_PMON_CTL2, 1 + 2 * (1)); // choose counter 3 to monitor R_MSR_PORT1_IPERF_CFG1 MSR[core]->write(R_MSR_PMON_CTL3, 1 + 2 * (7)); // choose counter 10 to monitor R_MSR_PORT4_IPERF_CFG1 MSR[core]->write(R_MSR_PMON_CTL10, 1 + 2 * (1)); // choose counter 11 to monitor R_MSR_PORT5_IPERF_CFG1 MSR[core]->write(R_MSR_PMON_CTL11, 1 + 2 * (7)); // enable uncore TSC counter (fixed one) MSR[core]->write(W_MSR_PMON_GLOBAL_CTL, 1ULL << 31ULL); MSR[core]->write(W_MSR_PMON_FIXED_CTR_CTL, 1ULL); value = (1 << 28ULL) + 1; // enable all counters MSR[core]->write(U_MSR_PMON_GLOBAL_CTL, value); } uint64 RDTSC(); void PCM::computeNominalFrequency() { const int ref_core = 0; uint64 before = 0, after = 0; MSR[ref_core]->read(IA32_TIME_STAMP_COUNTER, &before); // sleep fo 100 ms #ifdef _MSC_VER Sleep(1000); #else usleep(1000*1000); #endif MSR[ref_core]->read(IA32_TIME_STAMP_COUNTER, &after); nominal_frequency = after-before; } std::string PCM::getCPUBrandString() { char buffer[sizeof(int)*4*3+1]; PCM_CPUID_INFO * info = (PCM_CPUID_INFO *) buffer; pcm_cpuid(0x80000002, *info); ++info; pcm_cpuid(0x80000003, *info); ++info; pcm_cpuid(0x80000004, *info); buffer[sizeof(int)*4*3] = 0; std::string result(buffer); while(result[0]==' ') result.erase(0,1); size_t i = std::string::npos; while((i=result.find(" "))!=std::string::npos) result.replace(i,2," "); // remove duplicate spaces return result; } uint64 get_frequency_from_cpuid() // from Pat Fay (Intel) { double speed=0; std::string brand = PCM::getCPUBrandString(); if(brand.length() > 0) { size_t unitsg = brand.find("GHz"); if(unitsg != std::string::npos) { size_t atsign = brand.rfind(' ', unitsg); if(atsign != std::string::npos) { std::istringstream(brand.substr(atsign)) >> speed; speed *= 1000; } } else { size_t unitsg = brand.find("MHz"); if(unitsg != std::string::npos) { size_t atsign = brand.rfind(' ', unitsg); if(atsign != std::string::npos) { std::istringstream(brand.substr(atsign)) >> speed; } } } } return (uint64)speed * 1000ULL * 1000ULL; } void PCM::computeQPISpeedBeckton(int core_nr) { uint64 startFlits = 0; // reset all counters MSR[core_nr]->write(U_MSR_PMON_GLOBAL_CTL, 1 << 29ULL); // enable counting on all counters on the left side (port 0-3) MSR[core_nr]->write(R_MSR_PMON_GLOBAL_CTL_7_0, 255); // disable on the right side (port 4-7) MSR[core_nr]->write(R_MSR_PMON_GLOBAL_CTL_15_8, 0); // count flits sent MSR[core_nr]->write(R_MSR_PORT0_IPERF_CFG0, 1ULL << 31ULL); // choose counter 0 to monitor R_MSR_PORT0_IPERF_CFG0 MSR[core_nr]->write(R_MSR_PMON_CTL0, 1 + 2 * (0)); // enable all counters MSR[core_nr]->write(U_MSR_PMON_GLOBAL_CTL, (1 << 28ULL) + 1); MSR[core_nr]->read(R_MSR_PMON_CTR0, &startFlits); const uint64 timerGranularity = 1000000ULL; // mks uint64 startTSC = getTickCount(timerGranularity, core_nr); uint64 endTSC; do { endTSC = getTickCount(timerGranularity, core_nr); } while (endTSC - startTSC < 200000ULL); // spin for 200 ms uint64 endFlits = 0; MSR[core_nr]->read(R_MSR_PMON_CTR0, &endFlits); qpi_speed = (endFlits - startFlits) * 8ULL * timerGranularity / (endTSC - startTSC); } bool PCM::PMUinUse() { // follow the "Performance Monitoring Unit Sharing Guide" by P. Irelan and Sh. Kuo for (int i = 0; i < num_cores; ++i) { //std::cout << "Core "<<i<<" exemine registers"<< std::endl; uint64 value; MSR[i]->read(IA32_CR_PERF_GLOBAL_CTRL, &value); // std::cout << "Core "<<i<<" IA32_CR_PERF_GLOBAL_CTRL is "<< std::hex << value << std::dec << std::endl; EventSelectRegister event_select_reg; event_select_reg.value = 0xFFFFFFFFFFFFFFFF; for (uint32 j = 0; j < core_gen_counter_num_max; ++j) { MSR[i]->read(IA32_PERFEVTSEL0_ADDR + j, &event_select_reg.value); if (event_select_reg.fields.event_select != 0 || event_select_reg.fields.apic_int != 0) { std::cout << "WARNING: Core "<<i<<" IA32_PERFEVTSEL0_ADDR are not zeroed "<< event_select_reg.value << std::endl; return true; } } FixedEventControlRegister ctrl_reg; ctrl_reg.value = 0xffffffffffffffff; MSR[i]->read(IA32_CR_FIXED_CTR_CTRL, &ctrl_reg.value); // Check if someone has installed pmi handler on counter overflow. // If so, that agent might potentially need to change counter value // for the "sample after"-mode messing up PCM measurements if(ctrl_reg.fields.enable_pmi0 || ctrl_reg.fields.enable_pmi1 || ctrl_reg.fields.enable_pmi2) { std::cout << "WARNING: Core "<<i<<" fixed ctrl:"<< ctrl_reg.value << std::endl; return true; } // either os=0,usr=0 (not running) or os=1,usr=1 (fits PCM modus) are ok, other combinations are not if(ctrl_reg.fields.os0 != ctrl_reg.fields.usr0 || ctrl_reg.fields.os1 != ctrl_reg.fields.usr1 || ctrl_reg.fields.os2 != ctrl_reg.fields.usr2) { std::cout << "WARNING: Core "<<i<<" fixed ctrl:"<< ctrl_reg.value << std::endl; return true; } } return false; } const char * PCM::getUArchCodename() { switch(cpu_model) { case NEHALEM_EP: case NEHALEM: return "Nehalem/Nehalem-EP"; case ATOM: return "Atom(tm)"; case CLARKDALE: return "Westmere/Clarkdale"; case WESTMERE_EP: return "Westmere-EP"; case NEHALEM_EX: return "Nehalem-EX"; case WESTMERE_EX: return "Westmere-EX"; case SANDY_BRIDGE: return "Sandy Bridge"; case JAKETOWN: return "Sandy Bridge-EP/Jaketown"; case IVYTOWN: return "Ivy Bridge-EP/EN/EX/Ivytown"; case IVY_BRIDGE: return "Ivy Bridge"; case HASWELL: return "Haswell"; } return "unknown"; } void PCM::cleanupPMU() { #ifdef PCM_USE_PERF if(canUsePerf) { for (int i = 0; i < num_cores; ++i) for(int c = 0; c < PERF_MAX_COUNTERS; ++c) ::close(perfEventHandle[i][c]); return; } #endif // follow the "Performance Monitoring Unit Sharing Guide" by P. Irelan and Sh. Kuo for (int i = 0; i < num_cores; ++i) { // disable generic counters and continue free running counting for fixed counters MSR[i]->write(IA32_CR_PERF_GLOBAL_CTRL, (1ULL << 32) + (1ULL << 33) + (1ULL << 34)); for (uint32 j = 0; j < core_gen_counter_num_max; ++j) { MSR[i]->write(IA32_PERFEVTSEL0_ADDR + j, 0); } } if(cpu_model == JAKETOWN) enableJKTWorkaround(false); } void PCM::resetPMU() { for (int i = 0; i < num_cores; ++i) { // disable all counters MSR[i]->write(IA32_CR_PERF_GLOBAL_CTRL, 0); for (uint32 j = 0; j < core_gen_counter_num_max; ++j) { MSR[i]->write(IA32_PERFEVTSEL0_ADDR + j, 0); } FixedEventControlRegister ctrl_reg; ctrl_reg.value = 0xffffffffffffffff; MSR[i]->read(IA32_CR_FIXED_CTR_CTRL, &ctrl_reg.value); if ((ctrl_reg.fields.os0 || ctrl_reg.fields.usr0 || ctrl_reg.fields.enable_pmi0 || ctrl_reg.fields.os1 || ctrl_reg.fields.usr1 || ctrl_reg.fields.enable_pmi1 || ctrl_reg.fields.os2 || ctrl_reg.fields.usr2 || ctrl_reg.fields.enable_pmi2) != 0) MSR[i]->write(IA32_CR_FIXED_CTR_CTRL, 0); } } void PCM::cleanup() { SystemWideLock lock; if (!MSR) return; std::cout << "Cleaning up" << std::endl; if (decrementInstanceSemaphore()) cleanupPMU(); } #ifdef __APPLE__ uint32 PCM::getNumInstances() { return MSR[0]->getNumInstances(); } uint32 PCM::incrementNumInstances() { return MSR[0]->incrementNumInstances(); } uint32 PCM::decrementNumInstances() { return MSR[0]->decrementNumInstances();; } int convertUnknownToInt(size_t size, char* value){ if(sizeof(int) == size) { return *(int*)value; } else if(sizeof(long) == size) { return *(long *)value; } else if(sizeof(long long) == size) { return *(long long *)value; } else { // In this case, we don't know what it is so we guess int return *(int *)value; } } #endif bool PCM::decrementInstanceSemaphore() { bool isLastInstance = false; #ifdef _MSC_VER WaitForSingleObject(numInstancesSemaphore, 0); DWORD res = WaitForSingleObject(numInstancesSemaphore, 0); if (res == WAIT_TIMEOUT) { // I have the last instance of monitor isLastInstance = true; CloseHandle(numInstancesSemaphore); } else if (res == WAIT_OBJECT_0) { ReleaseSemaphore(numInstancesSemaphore, 1, NULL); // std::cout << "Someone else is running monitor instance, no cleanup needed"<< std::endl; } else { // unknown error std::cout << "ERROR: Bad semaphore. Performed cleanup twice?" << std::endl; } #elif __APPLE__ sem_wait(numInstancesSemaphore); uint32 oldValue = PCM::getNumInstances(); sem_post(numInstancesSemaphore); if(oldValue == 0) { // see same case for linux return false; } sem_wait(numInstancesSemaphore); uint32 currValue = PCM::decrementNumInstances(); sem_post(numInstancesSemaphore); if(currValue == 0){ isLastInstance = true; } #else // if linux int oldValue = -1; sem_getvalue(numInstancesSemaphore, &oldValue); if(oldValue == 0) { // the current value is already zero, somewhere the semaphore has been already decremented (and thus the clean up has been done if needed) // that means logically we are do not own the last instance anymore, thus returning false return false; } sem_wait(numInstancesSemaphore); int curValue = -1; sem_getvalue(numInstancesSemaphore, &curValue); if (curValue == 0) { // I have the last instance of monitor isLastInstance = true; // std::cout << "I am the last one"<< std::endl; } #endif // end ifdef _MSC_VER return isLastInstance; } uint64 PCM::getTickCount(uint64 multiplier, uint32 core) { return (multiplier * getInvariantTSC(CoreCounterState(), getCoreCounterState(core))) / getNominalFrequency(); } uint64 RDTSC() { uint64 result = 0; #ifdef _MSC_VER // Windows #if _MSC_VER>= 1600 result = __rdtsc(); #endif #else // Linux uint32 high = 0, low = 0; asm volatile("rdtsc" : "=a" (low), "=d" (high)); result = low + (uint64(high)<<32ULL); #endif return result; } uint64 RDTSCP() { uint64 result = 0; #ifdef _MSC_VER // Windows #if _MSC_VER>= 1600 unsigned int Aux; result = __rdtscp(&Aux); #endif #else // Linux and OS X uint32 high = 0, low = 0; asm volatile ( "rdtscp\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t": "=r" (high), "=r" (low) :: "%rax", "%rcx", "%rdx"); result = low + (uint64(high)<<32ULL); #endif return result; } uint64 PCM::getTickCountRDTSCP(uint64 multiplier) { return (multiplier*RDTSCP())/getNominalFrequency(); } SystemCounterState getSystemCounterState() { PCM * inst = PCM::getInstance(); SystemCounterState result; if (inst) result = inst->getSystemCounterState(); return result; } SocketCounterState getSocketCounterState(uint32 socket) { PCM * inst = PCM::getInstance(); SocketCounterState result; if (inst) result = inst->getSocketCounterState(socket); return result; } CoreCounterState getCoreCounterState(uint32 core) { PCM * inst = PCM::getInstance(); CoreCounterState result; if (inst) result = inst->getCoreCounterState(core); return result; } #ifdef PCM_USE_PERF void PCM::readPerfData(uint32 core, std::vector<uint64> & outData) { uint64 data[1 + PERF_MAX_COUNTERS]; const int32 bytes2read = sizeof(uint64)*(1 + core_fixed_counter_num_used + core_gen_counter_num_used); int result = ::read(perfEventHandle[core][PERF_GROUP_LEADER_COUNTER], data, bytes2read ); // data layout: nr counters; counter 0, counter 1, counter 2,... if(result != bytes2read) { std::cout << "Error while reading perf data. Result is "<< result << std::endl; std::cout << "Check if you run other competing Linux perf clients." << std::endl; } else if(data[0] != core_fixed_counter_num_used + core_gen_counter_num_used) { std::cout << "Number of counters read from perf is wrong. Elements read: "<< data[0] << std::endl; } else { // copy all counters, they start from position 1 in data std::copy((data + 1), (data + 1) + data[0], outData.begin()); } } #endif void BasicCounterState::readAndAggregate(MsrHandle * msr) { uint64 cInstRetiredAny = 0, cCpuClkUnhaltedThread = 0, cCpuClkUnhaltedRef = 0; uint64 cL3Miss = 0; uint64 cL3UnsharedHit = 0; uint64 cL2HitM = 0; uint64 cL2Hit = 0; uint64 cInvariantTSC = 0; uint64 cCStateResidency[PCM::MAX_C_STATE + 1]; memset(&(cCStateResidency[0]), 0, sizeof(cCStateResidency)); uint64 thermStatus = 0; TemporalThreadAffinity tempThreadAffinity(msr->getCoreId()); // speedup trick for Linux PCM * m = PCM::getInstance(); uint32 cpu_model = m->getCPUModel(); // reading core PMU counters #ifdef PCM_USE_PERF if(m->canUsePerf) { std::vector<uint64> perfData(PERF_MAX_COUNTERS, 0ULL); m->readPerfData(msr->getCoreId(), perfData); cInstRetiredAny = perfData[PCM::PERF_INST_RETIRED_ANY_POS]; cCpuClkUnhaltedThread = perfData[PCM::PERF_CPU_CLK_UNHALTED_THREAD_POS]; cCpuClkUnhaltedRef = perfData[PCM::PERF_CPU_CLK_UNHALTED_REF_POS]; cL3Miss = perfData[PCM::PERF_GEN_EVENT_0_POS]; cL3UnsharedHit = perfData[PCM::PERF_GEN_EVENT_1_POS]; cL2HitM = perfData[PCM::PERF_GEN_EVENT_2_POS]; cL2Hit = perfData[PCM::PERF_GEN_EVENT_3_POS]; } else #endif { msr->read(INST_RETIRED_ANY_ADDR, &cInstRetiredAny); msr->read(CPU_CLK_UNHALTED_THREAD_ADDR, &cCpuClkUnhaltedThread); msr->read(CPU_CLK_UNHALTED_REF_ADDR, &cCpuClkUnhaltedRef); switch (cpu_model) { case PCM::WESTMERE_EP: case PCM::NEHALEM_EP: case PCM::NEHALEM_EX: case PCM::WESTMERE_EX: case PCM::CLARKDALE: case PCM::SANDY_BRIDGE: case PCM::JAKETOWN: case PCM::IVYTOWN: case PCM::IVY_BRIDGE: case PCM::HASWELL: msr->read(IA32_PMC0, &cL3Miss); msr->read(IA32_PMC1, &cL3UnsharedHit); msr->read(IA32_PMC2, &cL2HitM); msr->read(IA32_PMC3, &cL2Hit); break; case PCM::ATOM: msr->read(IA32_PMC0, &cL3Miss); // for Atom mapped to ArchLLCMiss field msr->read(IA32_PMC1, &cL3UnsharedHit); // for Atom mapped to ArchLLCRef field break; } } if(cpu_model != PCM::ATOM || m->getOriginalCPUModel() == PCM::ATOM_AVOTON) msr->read(IA32_TIME_STAMP_COUNTER, &cInvariantTSC); else { #ifdef _MSC_VER cInvariantTSC = ((uint64)(GetTickCount()/1000))*m->getNominalFrequency(); #else struct timeval tp; gettimeofday(&tp, NULL); cInvariantTSC = (double(tp.tv_sec) + tp.tv_usec / 1000000.)*m->getNominalFrequency(); #endif } // reading core C state counters for(int i=0; i <= PCM::MAX_C_STATE ;++i) if(m->coreCStateMsr && m->coreCStateMsr[i]) msr->read(m->coreCStateMsr[i], &(cCStateResidency[i])); // reading temperature msr->read(MSR_IA32_THERM_STATUS, &thermStatus); InstRetiredAny += m->extractCoreFixedCounterValue(cInstRetiredAny); CpuClkUnhaltedThread += m->extractCoreFixedCounterValue(cCpuClkUnhaltedThread); CpuClkUnhaltedRef += m->extractCoreFixedCounterValue(cCpuClkUnhaltedRef); L3Miss += m->extractCoreGenCounterValue(cL3Miss); L3UnsharedHit += m->extractCoreGenCounterValue(cL3UnsharedHit); L2HitM += m->extractCoreGenCounterValue(cL2HitM); L2Hit += m->extractCoreGenCounterValue(cL2Hit); InvariantTSC += cInvariantTSC; for(int i=0; i <= PCM::MAX_C_STATE ;++i) CStateResidency[i] += cCStateResidency[i]; ThermalHeadroom = extractThermalHeadroom(thermStatus); } PCM::ErrorCode PCM::programServerUncorePowerMetrics(int mc_profile, int pcu_profile, int * freq_bands) { if(MSR == NULL || server_pcicfg_uncore == NULL) return PCM::MSRAccessDenied; uint32 PCUCntConf[4] = {0,0,0,0}; PCUCntConf[0] = PCU_MSR_PMON_CTL_EVENT(0); // clock ticks switch(pcu_profile) { case 0: PCUCntConf[1] = PCU_MSR_PMON_CTL_EVENT(0xB); // FREQ_BAND0_CYCLES PCUCntConf[2] = PCU_MSR_PMON_CTL_EVENT(0xC); // FREQ_BAND1_CYCLES PCUCntConf[3] = PCU_MSR_PMON_CTL_EVENT(0xD); // FREQ_BAND2_CYCLES break; case 1: PCUCntConf[1] = PCU_MSR_PMON_CTL_EVENT(0x80) + PCU_MSR_PMON_CTL_OCC_SEL(1); // POWER_STATE_OCCUPANCY.C0 using CLOCKTICKS + 8th-bit PCUCntConf[2] = PCU_MSR_PMON_CTL_EVENT(0x80) + PCU_MSR_PMON_CTL_OCC_SEL(2); // POWER_STATE_OCCUPANCY.C3 using CLOCKTICKS + 8th-bit PCUCntConf[3] = PCU_MSR_PMON_CTL_EVENT(0x80) + PCU_MSR_PMON_CTL_OCC_SEL(3); // POWER_STATE_OCCUPANCY.C6 using CLOCKTICKS + 8th-bit break; case 2: PCUCntConf[1] = PCU_MSR_PMON_CTL_EVENT(0x09); // PROCHOT_INTERNAL_CYCLES PCUCntConf[2] = PCU_MSR_PMON_CTL_EVENT(0x0A); // PROCHOT_EXTERNAL_CYCLES PCUCntConf[3] = PCU_MSR_PMON_CTL_EVENT(0x04); // Thermal frequency limit cycles: FREQ_MAX_LIMIT_THERMAL_CYCLES break; case 3: PCUCntConf[1] = PCU_MSR_PMON_CTL_EVENT(0x04); // Thermal frequency limit cycles: FREQ_MAX_LIMIT_THERMAL_CYCLES PCUCntConf[2] = PCU_MSR_PMON_CTL_EVENT(0x05); // Power frequency limit cycles: FREQ_MAX_POWER_CYCLES PCUCntConf[3] = PCU_MSR_PMON_CTL_EVENT(0x07); // Clipped frequency limit cycles: FREQ_MAX_CURRENT_CYCLES break; case 4: PCUCntConf[1] = PCU_MSR_PMON_CTL_EVENT(0x06); // OS frequency limit cycles: FREQ_MAX_OS_CYCLES PCUCntConf[2] = PCU_MSR_PMON_CTL_EVENT(0x05); // Power frequency limit cycles: FREQ_MAX_POWER_CYCLES PCUCntConf[3] = PCU_MSR_PMON_CTL_EVENT(0x07); // Clipped frequency limit cycles: FREQ_MAX_CURRENT_CYCLES break; case 5: if(JAKETOWN == cpu_model) { PCUCntConf[1] = PCU_MSR_PMON_CTL_EVENT(0) + PCU_MSR_PMON_CTL_EXTRA_SEL + PCU_MSR_PMON_CTL_EDGE_DET ; // number of frequency transitions PCUCntConf[2] = PCU_MSR_PMON_CTL_EVENT(0) + PCU_MSR_PMON_CTL_EXTRA_SEL ; // cycles spent changing frequency } else if (IVYTOWN == cpu_model ) { PCUCntConf[1] = PCU_MSR_PMON_CTL_EVENT(0x60) + PCU_MSR_PMON_CTL_EDGE_DET ; // number of frequency transitions PCUCntConf[2] = PCU_MSR_PMON_CTL_EVENT(0x60) ; // cycles spent changing frequency } else { std::cout << "ERROR: no frequency transition events defined for CPU model "<< cpu_model << std::endl; } break; } uint32 PCU_MSR_PMON_BOX_FILTER_ADDR, PCU_MSR_PMON_CTLX_ADDR[4]; PCU_MSR_PMON_BOX_FILTER_ADDR = JKTIVT_PCU_MSR_PMON_BOX_FILTER_ADDR; PCU_MSR_PMON_CTLX_ADDR[0] = JKTIVT_PCU_MSR_PMON_CTL0_ADDR; PCU_MSR_PMON_CTLX_ADDR[1] = JKTIVT_PCU_MSR_PMON_CTL1_ADDR; PCU_MSR_PMON_CTLX_ADDR[2] = JKTIVT_PCU_MSR_PMON_CTL2_ADDR; PCU_MSR_PMON_CTLX_ADDR[3] = JKTIVT_PCU_MSR_PMON_CTL3_ADDR; for (int i = 0; (i < num_sockets) && server_pcicfg_uncore && MSR; ++i) { server_pcicfg_uncore[i]->program_power_metrics(mc_profile); uint32 refCore = socketRefCore[i]; TemporalThreadAffinity tempThreadAffinity(refCore); // speedup trick for Linux // freeze enable MSR[refCore]->write(PCU_MSR_PMON_BOX_CTL_ADDR, PCU_MSR_PMON_BOX_CTL_FRZ_EN); // freeze MSR[refCore]->write(PCU_MSR_PMON_BOX_CTL_ADDR, PCU_MSR_PMON_BOX_CTL_FRZ_EN + PCU_MSR_PMON_BOX_CTL_FRZ); uint64 val = 0; MSR[refCore]->read(PCU_MSR_PMON_BOX_CTL_ADDR,&val); if ((val & UNCORE_PMON_BOX_CTL_VALID_BITS_MASK) != (PCU_MSR_PMON_BOX_CTL_FRZ_EN + PCU_MSR_PMON_BOX_CTL_FRZ)) std::cout << "ERROR: PCU counter programming seems not to work. PCU_MSR_PMON_BOX_CTL=0x" << std::hex << val << " needs to be =0x"<< (PCU_MSR_PMON_BOX_CTL_FRZ_EN + PCU_MSR_PMON_BOX_CTL_FRZ) << std::endl; if(freq_bands == NULL) MSR[refCore]->write(PCU_MSR_PMON_BOX_FILTER_ADDR, PCU_MSR_PMON_BOX_FILTER_BAND_0(10) + // 1000 MHz PCU_MSR_PMON_BOX_FILTER_BAND_1(20) + // 2000 MHz PCU_MSR_PMON_BOX_FILTER_BAND_2(30) // 3000 MHz ); else MSR[refCore]->write(PCU_MSR_PMON_BOX_FILTER_ADDR, PCU_MSR_PMON_BOX_FILTER_BAND_0(freq_bands[0]) + PCU_MSR_PMON_BOX_FILTER_BAND_1(freq_bands[1]) + PCU_MSR_PMON_BOX_FILTER_BAND_2(freq_bands[2]) ); for(int ctr = 0; ctr < 4; ++ctr) { MSR[refCore]->write(PCU_MSR_PMON_CTLX_ADDR[ctr], PCU_MSR_PMON_CTL_EN); MSR[refCore]->write(PCU_MSR_PMON_CTLX_ADDR[ctr], PCU_MSR_PMON_CTL_EN + PCUCntConf[ctr]); } // reset counter values MSR[refCore]->write(PCU_MSR_PMON_BOX_CTL_ADDR, PCU_MSR_PMON_BOX_CTL_FRZ_EN + PCU_MSR_PMON_BOX_CTL_FRZ + PCU_MSR_PMON_BOX_CTL_RST_COUNTERS); // unfreeze counters MSR[refCore]->write(PCU_MSR_PMON_BOX_CTL_ADDR, PCU_MSR_PMON_BOX_CTL_FRZ_EN); } return PCM::Success; } void PCM::freezeServerUncoreCounters() { for (int i = 0; (i < num_sockets) && server_pcicfg_uncore && MSR; ++i) { server_pcicfg_uncore[i]->freezeCounters(); MSR[socketRefCore[i]]->write(PCU_MSR_PMON_BOX_CTL_ADDR, PCU_MSR_PMON_BOX_CTL_FRZ_EN + PCU_MSR_PMON_BOX_CTL_FRZ); } } void PCM::unfreezeServerUncoreCounters() { for (int i = 0; (i < num_sockets) && server_pcicfg_uncore && MSR; ++i) { server_pcicfg_uncore[i]->unfreezeCounters(); MSR[socketRefCore[i]]->write(PCU_MSR_PMON_BOX_CTL_ADDR, PCU_MSR_PMON_BOX_CTL_FRZ_EN); } } void UncoreCounterState::readAndAggregate(MsrHandle * msr) { TemporalThreadAffinity tempThreadAffinity(msr->getCoreId()); // speedup trick for Linux // reading package C state counters uint64 cCStateResidency[PCM::MAX_C_STATE + 1]; memset(&(cCStateResidency[0]), 0, sizeof(cCStateResidency)); PCM * m = PCM::getInstance(); for(int i=0; i <= PCM::MAX_C_STATE ;++i) if(m->pkgCStateMsr && m->pkgCStateMsr[i]) msr->read(m->pkgCStateMsr[i], &(cCStateResidency[i])); if (this!=NULL) { // to make security check happy for(int i=0; i <= PCM::MAX_C_STATE ;++i) CStateResidency[i] += cCStateResidency[i]; } } SystemCounterState PCM::getSystemCounterState() { SystemCounterState result; if (MSR) { // read core and uncore counter state for (int32 core = 0; core < num_cores; ++core) result.readAndAggregate(MSR[core]); for (int32 s=0; s < num_sockets; s++) { readAndAggregateUncoreMCCounters(s, result); readAndAggregateEnergyCounters(s, result); } readQPICounters(result); result.ThermalHeadroom = PCM_INVALID_THERMAL_HEADROOM; // not available for system } return result; } template <class CounterStateType> void PCM::readAndAggregateUncoreMCCounters(const uint32 socket, CounterStateType & result) { if (hasPCICFGUncore()) { if (server_pcicfg_uncore) { result.UncMCNormalReads += server_pcicfg_uncore[socket]->getImcReads(); result.UncMCFullWrites += server_pcicfg_uncore[socket]->getImcWrites(); } } else if(clientBW && socket == 0) { result.UncMCNormalReads += clientImcReads->read(); result.UncMCFullWrites += clientImcWrites->read(); } else { MsrHandle * msr = MSR[socketRefCore[socket]]; TemporalThreadAffinity tempThreadAffinity(socketRefCore[socket]); // speedup trick for Linux switch (cpu_model) { case PCM::WESTMERE_EP: case PCM::NEHALEM_EP: { uint64 cUncMCFullWrites = 0; uint64 cUncMCNormalReads = 0; msr->read(MSR_UNCORE_PMC0, &cUncMCFullWrites); msr->read(MSR_UNCORE_PMC1, &cUncMCNormalReads); result.UncMCFullWrites += extractUncoreGenCounterValue(cUncMCFullWrites); result.UncMCNormalReads += extractUncoreGenCounterValue(cUncMCNormalReads); } break; case PCM::NEHALEM_EX: case PCM::WESTMERE_EX: { uint64 cUncMCNormalReads = 0; msr->read(MB0_MSR_PMU_CNT_0, &cUncMCNormalReads); result.UncMCNormalReads += extractUncoreGenCounterValue(cUncMCNormalReads); msr->read(MB1_MSR_PMU_CNT_0, &cUncMCNormalReads); result.UncMCNormalReads += extractUncoreGenCounterValue(cUncMCNormalReads); uint64 cUncMCFullWrites = 0; // really good approximation of msr->read(BB0_MSR_PERF_CNT_1, &cUncMCFullWrites); result.UncMCFullWrites += extractUncoreGenCounterValue(cUncMCFullWrites); msr->read(BB1_MSR_PERF_CNT_1, &cUncMCFullWrites); result.UncMCFullWrites += extractUncoreGenCounterValue(cUncMCFullWrites); } break; default:; } } } template <class CounterStateType> void PCM::readAndAggregateEnergyCounters(const uint32 socket, CounterStateType & result) { if(socket < snb_energy_status.size()) result.PackageEnergyStatus += snb_energy_status[socket]->read(); if(socket < jkt_dram_energy_status.size()) result.DRAMEnergyStatus += jkt_dram_energy_status[socket]->read(); } void PCM::readQPICounters(SystemCounterState & result) { // read QPI counters std::vector<bool> SocketProcessed(num_sockets, false); if (cpu_model == PCM::NEHALEM_EX || cpu_model == PCM::WESTMERE_EX) { for (int32 core = 0; core < num_cores; ++core) { uint32 s = topology[core].socket; if (!SocketProcessed[s]) { TemporalThreadAffinity tempThreadAffinity(core); // speedup trick for Linux // incoming data responses from QPI link 0 MSR[core]->read(R_MSR_PMON_CTR1, &(result.incomingQPIPackets[s][0])); // incoming data responses from QPI link 1 (yes, from CTR0) MSR[core]->read(R_MSR_PMON_CTR0, &(result.incomingQPIPackets[s][1])); // incoming data responses from QPI link 2 MSR[core]->read(R_MSR_PMON_CTR8, &(result.incomingQPIPackets[s][2])); // incoming data responses from QPI link 3 MSR[core]->read(R_MSR_PMON_CTR9, &(result.incomingQPIPackets[s][3])); // outgoing idle flits from QPI link 0 MSR[core]->read(R_MSR_PMON_CTR3, &(result.outgoingQPIIdleFlits[s][0])); // outgoing idle flits from QPI link 1 (yes, from CTR0) MSR[core]->read(R_MSR_PMON_CTR2, &(result.outgoingQPIIdleFlits[s][1])); // outgoing idle flits from QPI link 2 MSR[core]->read(R_MSR_PMON_CTR10, &(result.outgoingQPIIdleFlits[s][2])); // outgoing idle flits from QPI link 3 MSR[core]->read(R_MSR_PMON_CTR11, &(result.outgoingQPIIdleFlits[s][3])); if (core == 0) MSR[core]->read(W_MSR_PMON_FIXED_CTR, &(result.uncoreTSC)); SocketProcessed[s] = true; } } } else if ((cpu_model == PCM::NEHALEM_EP || cpu_model == PCM::WESTMERE_EP)) { if (num_sockets == 2) { uint32 SCore[2] = { 0, 0 }; uint64 Total_Reads[2] = { 0, 0 }; uint64 Total_Writes[2] = { 0, 0 }; uint64 IOH_Reads[2] = { 0, 0 }; uint64 IOH_Writes[2] = { 0, 0 }; uint64 Remote_Reads[2] = { 0, 0 }; uint64 Remote_Writes[2] = { 0, 0 }; uint64 Local_Reads[2] = { 0, 0 }; uint64 Local_Writes[2] = { 0, 0 }; while (topology[SCore[0]].socket != 0) ++(SCore[0]); while (topology[SCore[1]].socket != 1) ++(SCore[1]); for (int s = 0; s < 2; ++s) { TemporalThreadAffinity tempThreadAffinity(SCore[s]); // speedup trick for Linux MSR[SCore[s]]->read(MSR_UNCORE_PMC0, &Total_Writes[s]); MSR[SCore[s]]->read(MSR_UNCORE_PMC1, &Total_Reads[s]); MSR[SCore[s]]->read(MSR_UNCORE_PMC2, &IOH_Reads[s]); MSR[SCore[s]]->read(MSR_UNCORE_PMC3, &IOH_Writes[s]); MSR[SCore[s]]->read(MSR_UNCORE_PMC4, &Remote_Reads[s]); MSR[SCore[s]]->read(MSR_UNCORE_PMC5, &Remote_Writes[s]); MSR[SCore[s]]->read(MSR_UNCORE_PMC6, &Local_Reads[s]); MSR[SCore[s]]->read(MSR_UNCORE_PMC7, &Local_Writes[s]); } #if 1 // compute Remote_Reads differently for (int s = 0; s < 2; ++s) { uint64 total = Total_Writes[s] + Total_Reads[s]; uint64 rem = IOH_Reads[s] + IOH_Writes[s] + Local_Reads[s] + Local_Writes[s] + Remote_Writes[s]; Remote_Reads[s] = (total > rem) ? (total - rem) : 0; } #endif // only an estimation (lower bound) - does not count NT stores correctly result.incomingQPIPackets[0][0] = Remote_Reads[1] + Remote_Writes[0]; result.incomingQPIPackets[0][1] = IOH_Reads[0]; result.incomingQPIPackets[1][0] = Remote_Reads[0] + Remote_Writes[1]; result.incomingQPIPackets[1][1] = IOH_Reads[1]; } else { // for a single socket systems no information is available result.incomingQPIPackets[0][0] = 0; } } else if (hasPCICFGUncore()) { if (server_pcicfg_uncore) for (int32 s = 0; (s < num_sockets); ++s) for (uint32 port = 0; port < getQPILinksPerSocket(); ++port) { result.incomingQPIPackets[s][port] = server_pcicfg_uncore[s]->getIncomingDataFlits(port) / 8; result.outgoingQPIDataNonDataFlits[s][port] = server_pcicfg_uncore[s]->getOutgoingDataNonDataFlits(port); } } // end of reading QPI counters } template <class CounterStateType> void PCM::readPackageThermalHeadroom(const uint32 socket, CounterStateType & result) { if(packageThermalMetricsAvailable()) { uint64 val = 0; MSR[socketRefCore[socket]]->read(MSR_PACKAGE_THERM_STATUS,&val); result.ThermalHeadroom = extractThermalHeadroom(val); } else result.ThermalHeadroom = PCM_INVALID_THERMAL_HEADROOM; // not available } SocketCounterState PCM::getSocketCounterState(uint32 socket) { SocketCounterState result; if (MSR) { // reading core and uncore counter states for (int32 core = 0; core < num_cores; ++core) if (topology[core].socket == int32(socket)) result.readAndAggregate(MSR[core]); readAndAggregateUncoreMCCounters(socket, result); readAndAggregateEnergyCounters(socket, result); readPackageThermalHeadroom(socket, result); } return result; } void PCM::getAllCounterStates(SystemCounterState & systemState, std::vector<SocketCounterState> & socketStates, std::vector<CoreCounterState> & coreStates) { // clear and zero-initialize all inputs systemState = SystemCounterState(); socketStates.clear(); socketStates.resize(num_sockets); coreStates.clear(); coreStates.resize(num_cores); for (int32 core = 0; core < num_cores; ++core) { // read core counters coreStates[core].readAndAggregate(MSR[core]); socketStates[topology[core].socket].UncoreCounterState::readAndAggregate(MSR[core]); // read package C state counters } for (int32 s=0; s < num_sockets; ++s) { readAndAggregateUncoreMCCounters(s, socketStates[s]); readAndAggregateEnergyCounters(s, socketStates[s]); readPackageThermalHeadroom(s, socketStates[s]); } readQPICounters(systemState); for (int32 core = 0; core < num_cores; ++core) { // aggregate core counters into sockets socketStates[topology[core].socket].accumulateCoreState(coreStates[core]); } for (int32 s = 0; s < num_sockets; ++s) { // aggregate core counters from sockets into system state and // aggregate socket uncore iMC, energy and package C state counters into system systemState.accumulateSocketState(socketStates[s]); } } CoreCounterState PCM::getCoreCounterState(uint32 core) { CoreCounterState result; if (MSR) result.readAndAggregate(MSR[core]); return result; } uint32 PCM::getNumCores() { return num_cores; } uint32 PCM::getNumSockets() { return num_sockets; } uint32 PCM::getThreadsPerCore() { return threads_per_core; } bool PCM::getSMT() { return threads_per_core > 1; } uint64 PCM::getNominalFrequency() { return nominal_frequency; } ServerUncorePowerState PCM::getServerUncorePowerState(uint32 socket) { ServerUncorePowerState result; if(server_pcicfg_uncore && server_pcicfg_uncore[socket]) { for(uint32 port=0;port < server_pcicfg_uncore[socket]->getNumQPIPorts();++port) { result.QPIClocks[port] = server_pcicfg_uncore[socket]->getQPIClocks(port); result.QPIL0pTxCycles[port] = server_pcicfg_uncore[socket]->getQPIL0pTxCycles(port); result.QPIL1Cycles[port] = server_pcicfg_uncore[socket]->getQPIL1Cycles(port); } for(uint32 channel=0;channel<server_pcicfg_uncore[socket]->getNumMCChannels();++channel) { result.DRAMClocks[channel] = server_pcicfg_uncore[socket]->getDRAMClocks(channel); for(uint32 cnt=0;cnt<4;++cnt) result.MCCounter[channel][cnt] = server_pcicfg_uncore[socket]->getMCCounter(channel,cnt); } } if(MSR) { uint32 refCore = socketRefCore[socket]; TemporalThreadAffinity tempThreadAffinity(refCore); for(int i=0; i<4; ++i) MSR[refCore]->read(PCU_MSR_PMON_CTRX_ADDR[i],&(result.PCUCounter[i])); // std::cout<< "values read: " << result.PCUCounter[0]<<" "<<result.PCUCounter[1] << " " << result.PCUCounter[2] << " " << result.PCUCounter[3] << std::endl; uint64 val=0; //MSR[refCore]->read(MSR_PKG_ENERGY_STATUS,&val); //std::cout << "Energy status: "<< val << std::endl; MSR[refCore]->read(MSR_PACKAGE_THERM_STATUS,&val); result.PackageThermalHeadroom = extractThermalHeadroom(val); } if(socket < snb_energy_status.size()) result.PackageEnergyStatus = snb_energy_status[socket]->read(); if(socket < jkt_dram_energy_status.size()) result.DRAMEnergyStatus = jkt_dram_energy_status[socket]->read(); return result; } #ifndef _MSC_VER void print_mcfg(const char * path) { int mcfg_handle = ::open(path, O_RDONLY); if (mcfg_handle < 0) throw std::exception(); MCFGHeader header; ::read(mcfg_handle, (void *)&header, sizeof(MCFGHeader)); const unsigned segments = header.nrecords(); header.print(); std::cout << "Segments: "<<segments<<std::endl; for(unsigned int i=0; i<segments;++i) { MCFGRecord record; ::read(mcfg_handle, (void *)&record, sizeof(MCFGRecord)); std::cout << "Segment " <<std::dec << i<< " "; record.print(); } ::close(mcfg_handle); } #endif static const uint32 IMC_DEV_IDS[] = { 0x03cb0, 0x03cb1, 0x03cb4, 0x03cb5, 0x0EB4, 0x0EB5, 0x0EB0, 0x0EB1, 0x0EF4, 0x0EF5, 0x0EF0, 0x0EF1 }; std::vector<uint32> ServerPCICFGUncore::socket2bus; void ServerPCICFGUncore::initSocket2Bus() { if(!socket2bus.empty()) return; for (uint32 bus = 0; bus < 256; bus++) { uint32 value = 0; try { PciHandleM h(0, bus, MCX_CHY_REGISTER_DEV_ADDR[0][0], MCX_CHY_REGISTER_FUNC_ADDR[0][0]); h.read32(0, &value); } catch(...) { // reached invalid bus return; } const uint32 vendor_id = value & 0xffff; const uint32 device_id = (value >> 16) & 0xffff; if (vendor_id != 0x8086) continue; for(uint32 i = 0; i< sizeof(IMC_DEV_IDS)/sizeof(IMC_DEV_IDS[0]) ; ++i) { // match if(IMC_DEV_IDS[i] == device_id) { // std::cout << "DEBUG: found bus "<<std::hex << bus << std::dec << std::endl; socket2bus.push_back(bus); break; } } } } int getBusFromSocket(const uint32 socket) { int cur_bus = 0; uint32 cur_socket = 0; // std::cout << "socket: "<< socket << std::endl; while(cur_socket <= socket) { // std::cout << "reading from bus 0x"<< std::hex << cur_bus << std::dec << " "; PciHandleM h(0, cur_bus, 5, 0); uint32 cpubusno = 0; h.read32(0x108, &cpubusno); // CPUBUSNO register cur_bus = (cpubusno >> 8)& 0x0ff; // std::cout << "socket: "<< cur_socket<< std::hex << " cpubusno: 0x"<< std::hex << cpubusno << " "<<cur_bus<< std::dec << std::endl; if(socket == cur_socket) return cur_bus; ++cur_socket; ++cur_bus; if(cur_bus > 0x0ff) return -1; } return -1; } PciHandleM * ServerPCICFGUncore::createIntelPerfMonDevice(uint32 groupnr_, uint32 bus_, uint32 dev_, uint32 func_, bool checkVendor) { if (PciHandleM::exists(bus_, dev_, func_)) { PciHandleM * handle = new PciHandleM(groupnr_, bus_, dev_, func_); if(!checkVendor) return handle; uint32 vendor_id = 0; handle->read32(PCM_PCI_VENDOR_ID_OFFSET,&vendor_id); vendor_id &= 0x0ffff; if(vendor_id == PCM_INTEL_PCI_VENDOR_ID) return handle; delete handle; } return NULL; } ServerPCICFGUncore::ServerPCICFGUncore(uint32 socket_, PCM * pcm) : bus(-1) , groupnr(0) , imcHandles(NULL) , num_imc_channels(0) , qpiLLHandles(NULL) , num_qpi_ports(0) , qpi_speed(0) , num_imc(0) { #define PCM_PCICFG_MC_INIT(controller, channel, arch) \ MCX_CHY_REGISTER_DEV_ADDR[controller][channel] = arch##_MC##controller##_CH##channel##_REGISTER_DEV_ADDR; \ MCX_CHY_REGISTER_FUNC_ADDR[controller][channel] = arch##_MC##controller##_CH##channel##_REGISTER_FUNC_ADDR; PCM_PCICFG_MC_INIT(0, 0, JKTIVT) PCM_PCICFG_MC_INIT(0, 1, JKTIVT) PCM_PCICFG_MC_INIT(0, 2, JKTIVT) PCM_PCICFG_MC_INIT(0, 3, JKTIVT) PCM_PCICFG_MC_INIT(1, 0, JKTIVT) PCM_PCICFG_MC_INIT(1, 1, JKTIVT) PCM_PCICFG_MC_INIT(1, 2, JKTIVT) PCM_PCICFG_MC_INIT(1, 3, JKTIVT) #undef PCM_PCICFG_MC_INIT initSocket2Bus(); const uint32 total_sockets_ = pcm->getNumSockets(); const uint32 cpu_model = pcm->getCPUModel(); if(total_sockets_ == socket2bus.size()) { bus = socket2bus[socket_]; } else if(total_sockets_ <= 4) { bus = getBusFromSocket(socket_); if(bus < 0) { std::cerr << "Cannot find bus for socket "<< socket_ <<" on system with "<< total_sockets_ << " sockets."<< std::endl; throw std::exception(); } } else if ((total_sockets_ > 4) && (cpu_model == PCM::JAKETOWN || cpu_model == PCM::IVYTOWN)) // for SGI UV2 { // if(socket_ == 0) print_mcfg("/sys/firmware/acpi/tables/MCFG"); groupnr = socket_ + 0x1000; bus = 0x3f; } else { std::cout << "Error: A system with "<< total_sockets_ <<" sockets is detected. Only 2- and 4-socket systems are supported."<< std::endl; throw std::exception(); } imcHandles = new PciHandleM *[8]; { #define PCM_PCICFG_SETUP_MC_HANDLE(controller,channel) \ { \ PciHandleM * handle = createIntelPerfMonDevice(groupnr, bus, \ MCX_CHY_REGISTER_DEV_ADDR[controller][channel], MCX_CHY_REGISTER_FUNC_ADDR[controller][channel], true); \ if(handle) imcHandles[num_imc_channels++] = handle; \ } PCM_PCICFG_SETUP_MC_HANDLE(0,0) PCM_PCICFG_SETUP_MC_HANDLE(0,1) PCM_PCICFG_SETUP_MC_HANDLE(0,2) PCM_PCICFG_SETUP_MC_HANDLE(0,3) if(num_imc_channels > 0) ++num_imc; // at least one memory controller const uint32 num_imc_channels1 = num_imc_channels; PCM_PCICFG_SETUP_MC_HANDLE(1,0) PCM_PCICFG_SETUP_MC_HANDLE(1,1) PCM_PCICFG_SETUP_MC_HANDLE(1,2) PCM_PCICFG_SETUP_MC_HANDLE(1,3) if(num_imc_channels > num_imc_channels1 ) ++num_imc; // another memory controller found #undef PCM_PCICFG_SETUP_MC_HANDLE } if (num_imc_channels == 0) { delete [] imcHandles; imcHandles = NULL; std::cerr << "PCM error: no memory controllers found." << std::endl; throw std::exception(); } if (num_imc_channels < 3) { std::cout << "Intel PCM: warning only " << num_imc_channels << " memory channels detected, must be >= 3." << std::endl; } if (total_sockets_ == 1) { /* * For single socket systems, do not worry at all about QPI ports. This * eliminates QPI LL programming error messages on single socket systems * with BIOS that hides QPI performance counting PCI functions. It also * eliminates register programming that is not needed since no QPI traffic * is possible with single socket systems. */ num_qpi_ports = 0; return; } #ifdef PCM_NOQPI num_qpi_ports = 0; return; #else qpiLLHandles = new PciHandleM *[3]; for(uint32 i=0; i<3; ++i) qpiLLHandles[i] = NULL; uint32 QPI_PORTX_REGISTER_DEV_ADDR[3]; uint32 QPI_PORTX_REGISTER_FUNC_ADDR[3]; #define PCM_PCICFG_QPI_INIT(port, arch) \ QPI_PORTX_REGISTER_DEV_ADDR[port] = arch##_QPI_PORT##port##_REGISTER_DEV_ADDR; \ QPI_PORTX_REGISTER_FUNC_ADDR[port] = arch##_QPI_PORT##port##_REGISTER_FUNC_ADDR; PCM_PCICFG_QPI_INIT(0, JKTIVT); PCM_PCICFG_QPI_INIT(1, JKTIVT); PCM_PCICFG_QPI_INIT(2, JKTIVT); #undef PCM_PCICFG_QPI_INIT try { { PciHandleM * handle = createIntelPerfMonDevice(groupnr, bus, QPI_PORTX_REGISTER_DEV_ADDR[0], QPI_PORTX_REGISTER_FUNC_ADDR[0], false); if (handle) qpiLLHandles[num_qpi_ports++] = handle; else std::cout << "ERROR: QPI LL monitoring device ("<< groupnr<<":"<<bus<<":"<< QPI_PORTX_REGISTER_DEV_ADDR[0] <<":"<< QPI_PORTX_REGISTER_FUNC_ADDR[0] << ") is missing. The QPI statistics will be incomplete or missing."<< std::endl; } { PciHandleM * handle = createIntelPerfMonDevice(groupnr, bus, QPI_PORTX_REGISTER_DEV_ADDR[1], QPI_PORTX_REGISTER_FUNC_ADDR[1], false); if (handle) qpiLLHandles[num_qpi_ports++] = handle; else std::cout << "ERROR: QPI LL monitoring device ("<< groupnr<<":"<<bus<<":"<< QPI_PORTX_REGISTER_DEV_ADDR[1] <<":"<< QPI_PORTX_REGISTER_FUNC_ADDR[1] << ") is missing. The QPI statistics will be incomplete or missing."<< std::endl; } { PciHandleM * handle = createIntelPerfMonDevice(groupnr, bus, QPI_PORTX_REGISTER_DEV_ADDR[2], QPI_PORTX_REGISTER_FUNC_ADDR[2], true); if (handle) qpiLLHandles[num_qpi_ports++] = handle; } } catch (...) { std::cerr << "PCM Error: can not create QPI LL handles." <<std::endl; for(uint32 i=0; i<num_qpi_ports; ++i) if (qpiLLHandles[i]) delete qpiLLHandles[i]; delete[] qpiLLHandles; qpiLLHandles = NULL; throw std::exception(); } #endif std::cout << "Socket "<<socket_<<": "<< num_imc<<" memory controllers detected with total number of "<< num_imc_channels <<" channels. "<< num_qpi_ports<< " QPI ports detected."<<std::endl; } ServerPCICFGUncore::~ServerPCICFGUncore() { if (imcHandles) { for (uint32 i = 0; i < num_imc_channels; ++i) if (imcHandles[i]) delete imcHandles[i]; delete[] imcHandles; imcHandles = NULL; } if (qpiLLHandles) { for(uint32 i=0; i<num_qpi_ports; ++i) if (qpiLLHandles[i]) delete qpiLLHandles[i]; delete[] qpiLLHandles; qpiLLHandles = NULL; } } void ServerPCICFGUncore::program() { for (uint32 i = 0; i < num_imc_channels; ++i) { // imc PMU // freeze enable imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN); // freeze imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN + MC_CH_PCI_PMON_BOX_CTL_FRZ); uint32 val = 0; imcHandles[i]->read32(MC_CH_PCI_PMON_BOX_CTL_ADDR, &val); if ((val & UNCORE_PMON_BOX_CTL_VALID_BITS_MASK) != (MC_CH_PCI_PMON_BOX_CTL_FRZ_EN + MC_CH_PCI_PMON_BOX_CTL_FRZ)) { std::cout << "ERROR: IMC counter programming seems not to work. MC_CH" << i << "_PCI_PMON_BOX_CTL=0x" << std::hex << val << std::endl; std::cout << " Please see BIOS options to enable the export of performance monitoring devices." << std::endl; } // enable counter 0 imcHandles[i]->write32(MC_CH_PCI_PMON_CTL0_ADDR, MC_CH_PCI_PMON_CTL_EN); // monitor reads on counter 0: CAS_COUNT.RD imcHandles[i]->write32(MC_CH_PCI_PMON_CTL0_ADDR, MC_CH_PCI_PMON_CTL_EN + MC_CH_PCI_PMON_CTL_EVENT(0x04) + MC_CH_PCI_PMON_CTL_UMASK(3)); // enable counter 1 imcHandles[i]->write32(MC_CH_PCI_PMON_CTL1_ADDR, MC_CH_PCI_PMON_CTL_EN); // monitor writes on counter 1: CAS_COUNT.WR imcHandles[i]->write32(MC_CH_PCI_PMON_CTL1_ADDR, MC_CH_PCI_PMON_CTL_EN + MC_CH_PCI_PMON_CTL_EVENT(0x04) + MC_CH_PCI_PMON_CTL_UMASK(12)); // enable counter 2 imcHandles[i]->write32(MC_CH_PCI_PMON_CTL2_ADDR, MC_CH_PCI_PMON_CTL_EN); // monitor partial writes on counter 2: CAS_COUNT.RD_UNDERFILL imcHandles[i]->write32(MC_CH_PCI_PMON_CTL2_ADDR, MC_CH_PCI_PMON_CTL_EN + MC_CH_PCI_PMON_CTL_EVENT(0x04) + MC_CH_PCI_PMON_CTL_UMASK(2)); // enable fixed counter (DRAM clocks) imcHandles[i]->write32(MC_CH_PCI_PMON_FIXED_CTL_ADDR, MC_CH_PCI_PMON_FIXED_CTL_EN); // reset it imcHandles[i]->write32(MC_CH_PCI_PMON_FIXED_CTL_ADDR, MC_CH_PCI_PMON_FIXED_CTL_EN + MC_CH_PCI_PMON_FIXED_CTL_RST); // reset counters values imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN + MC_CH_PCI_PMON_BOX_CTL_FRZ + MC_CH_PCI_PMON_BOX_CTL_RST_COUNTERS); // unfreeze counters imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN); } for (uint32 i = 0; i < num_qpi_ports; ++i) { // QPI LL PMU uint32 val = 0; // freeze enable qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN); // freeze qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN + Q_P_PCI_PMON_BOX_CTL_RST_FRZ); val = 0; qpiLLHandles[i]->read32(Q_P_PCI_PMON_BOX_CTL_ADDR, &val); if ((val & UNCORE_PMON_BOX_CTL_VALID_BITS_MASK) != (Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN + Q_P_PCI_PMON_BOX_CTL_RST_FRZ)) { std::cout << "ERROR: QPI LL counter programming seems not to work. Q_P" << i << "_PCI_PMON_BOX_CTL=0x" << std::hex << val << std::endl; std::cout << " Please see BIOS options to enable the export of performance monitoring devices (devices 8 and 9: function 2)." << std::endl; } // enable counter 0 qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL0_ADDR, Q_P_PCI_PMON_CTL_EN); // monitor DRS data received on counter 0: RxL_FLITS_G1.DRS_DATA qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL0_ADDR, Q_P_PCI_PMON_CTL_EN + Q_P_PCI_PMON_CTL_EVENT(0x02) + Q_P_PCI_PMON_CTL_EVENT_EXT + Q_P_PCI_PMON_CTL_UMASK(8)); // enable counter 1 qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL1_ADDR, Q_P_PCI_PMON_CTL_EN); // monitor NCB data received on counter 1: RxL_FLITS_G2.NCB_DATA qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL1_ADDR, Q_P_PCI_PMON_CTL_EN + Q_P_PCI_PMON_CTL_EVENT(0x03) + Q_P_PCI_PMON_CTL_EVENT_EXT + Q_P_PCI_PMON_CTL_UMASK(4)); // enable counter 2 qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL2_ADDR, Q_P_PCI_PMON_CTL_EN); // monitor outgoing data+nondata flits on counter 2: TxL_FLITS_G0.DATA + TxL_FLITS_G0.NON_DATA qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL2_ADDR, Q_P_PCI_PMON_CTL_EN + Q_P_PCI_PMON_CTL_EVENT(0x00) + Q_P_PCI_PMON_CTL_UMASK(6)); // enable counter 3 qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL3_ADDR, Q_P_PCI_PMON_CTL_EN); // monitor QPI clocks qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL3_ADDR, Q_P_PCI_PMON_CTL_EN + Q_P_PCI_PMON_CTL_EVENT(0x14)); // QPI clocks (CLOCKTICKS) // reset counters values qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN + Q_P_PCI_PMON_BOX_CTL_RST_FRZ + Q_P_PCI_PMON_BOX_CTL_RST_COUNTERS); // unfreeze counters qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN); } } uint64 ServerPCICFGUncore::getImcReads() { uint64 result = 0; for (uint32 i = 0; i < num_imc_channels; ++i) { uint64 value = 0; imcHandles[i]->read64(MC_CH_PCI_PMON_CTR0_ADDR, &value); result += value; } return result; } uint64 ServerPCICFGUncore::getImcWrites() { uint64 result = 0; for (uint32 i = 0; i < num_imc_channels; ++i) { uint64 value = 0; imcHandles[i]->read64(MC_CH_PCI_PMON_CTR1_ADDR, &value); result += value; } return result; } uint64 ServerPCICFGUncore::getIncomingDataFlits(uint32 port) { uint64 drs = 0, ncb = 0; if (port >= num_qpi_ports) return 0; qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR0_ADDR, &drs); qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR1_ADDR, &ncb); return drs + ncb; } uint64 ServerPCICFGUncore::getOutgoingDataNonDataFlits(uint32 port) { return getQPILLCounter(port,2); } void ServerPCICFGUncore::program_power_metrics(int mc_profile) { for (uint32 i = 0; i < num_qpi_ports; ++i) { // QPI LL PMU uint32 val = 0; // freeze enable qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN); // freeze qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN + Q_P_PCI_PMON_BOX_CTL_RST_FRZ); val = 0; qpiLLHandles[i]->read32(Q_P_PCI_PMON_BOX_CTL_ADDR, &val); if ((val & UNCORE_PMON_BOX_CTL_VALID_BITS_MASK) != (Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN + Q_P_PCI_PMON_BOX_CTL_RST_FRZ)) { std::cout << "ERROR: QPI LL counter programming seems not to work. Q_P" << i << "_PCI_PMON_BOX_CTL=0x" << std::hex << val << std::endl; std::cout << " Please see BIOS options to enable the export of performance monitoring devices." << std::endl; } qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL3_ADDR, Q_P_PCI_PMON_CTL_EN); qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL3_ADDR, Q_P_PCI_PMON_CTL_EN + Q_P_PCI_PMON_CTL_EVENT(0x14)); // QPI clocks (CLOCKTICKS) qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL0_ADDR, Q_P_PCI_PMON_CTL_EN); qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL0_ADDR, Q_P_PCI_PMON_CTL_EN + Q_P_PCI_PMON_CTL_EVENT(0x0D)); // L0p Tx Cycles (TxL0P_POWER_CYCLES) qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL2_ADDR, Q_P_PCI_PMON_CTL_EN); qpiLLHandles[i]->write32(Q_P_PCI_PMON_CTL2_ADDR, Q_P_PCI_PMON_CTL_EN + Q_P_PCI_PMON_CTL_EVENT(0x12)); // L1 Cycles (L1_POWER_CYCLES) // reset counters values qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN + Q_P_PCI_PMON_BOX_CTL_RST_FRZ + Q_P_PCI_PMON_BOX_CTL_RST_COUNTERS); // unfreeze counters qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN); } uint32 MCCntConfig[4] = {0,0,0,0}; switch(mc_profile) { case 0: // POWER_CKE_CYCLES.RANK0 and POWER_CKE_CYCLES.RANK1 MCCntConfig[0] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(1) + MC_CH_PCI_PMON_CTL_INVERT + MC_CH_PCI_PMON_CTL_THRESH(1); MCCntConfig[1] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(1) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; MCCntConfig[2] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(2) + MC_CH_PCI_PMON_CTL_INVERT + MC_CH_PCI_PMON_CTL_THRESH(1); MCCntConfig[3] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(2) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; break; case 1: // POWER_CKE_CYCLES.RANK2 and POWER_CKE_CYCLES.RANK3 MCCntConfig[0] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(4) + MC_CH_PCI_PMON_CTL_INVERT + MC_CH_PCI_PMON_CTL_THRESH(1); MCCntConfig[1] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(4) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; MCCntConfig[2] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(8) + MC_CH_PCI_PMON_CTL_INVERT + MC_CH_PCI_PMON_CTL_THRESH(1); MCCntConfig[3] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(8) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; break; case 2: // POWER_CKE_CYCLES.RANK4 and POWER_CKE_CYCLES.RANK5 MCCntConfig[0] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(0x10) + MC_CH_PCI_PMON_CTL_INVERT + MC_CH_PCI_PMON_CTL_THRESH(1); MCCntConfig[1] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(0x10) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; MCCntConfig[2] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(0x20) + MC_CH_PCI_PMON_CTL_INVERT + MC_CH_PCI_PMON_CTL_THRESH(1); MCCntConfig[3] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(0x20) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; break; case 3: // POWER_CKE_CYCLES.RANK6 and POWER_CKE_CYCLES.RANK7 MCCntConfig[0] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(0x40) + MC_CH_PCI_PMON_CTL_INVERT + MC_CH_PCI_PMON_CTL_THRESH(1); MCCntConfig[1] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(0x40) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; MCCntConfig[2] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(0x80) + MC_CH_PCI_PMON_CTL_INVERT + MC_CH_PCI_PMON_CTL_THRESH(1); MCCntConfig[3] = MC_CH_PCI_PMON_CTL_EVENT(0x83) + MC_CH_PCI_PMON_CTL_UMASK(0x80) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; break; case 4: // POWER_SELF_REFRESH MCCntConfig[0] = MC_CH_PCI_PMON_CTL_EVENT(0x43); MCCntConfig[1] = MC_CH_PCI_PMON_CTL_EVENT(0x43) + MC_CH_PCI_PMON_CTL_THRESH(1) + MC_CH_PCI_PMON_CTL_EDGE_DET; break; } for (uint32 i = 0; i < num_imc_channels; ++i) { // imc PMU // freeze enable imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN); // freeze imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN + MC_CH_PCI_PMON_BOX_CTL_FRZ); uint32 val = 0; imcHandles[i]->read32(MC_CH_PCI_PMON_BOX_CTL_ADDR, &val); if ((val & UNCORE_PMON_BOX_CTL_VALID_BITS_MASK) != (MC_CH_PCI_PMON_BOX_CTL_FRZ_EN + MC_CH_PCI_PMON_BOX_CTL_FRZ)) { std::cout << "ERROR: IMC counter programming seems not to work. MC_CH" << i << "_PCI_PMON_BOX_CTL=0x" << std::hex << val << std::endl; std::cout << " Please see BIOS options to enable the export of performance monitoring devices." << std::endl; } // enable fixed counter (DRAM clocks) imcHandles[i]->write32(MC_CH_PCI_PMON_FIXED_CTL_ADDR, MC_CH_PCI_PMON_FIXED_CTL_EN); // reset it imcHandles[i]->write32(MC_CH_PCI_PMON_FIXED_CTL_ADDR, MC_CH_PCI_PMON_FIXED_CTL_EN + MC_CH_PCI_PMON_FIXED_CTL_RST); imcHandles[i]->write32(MC_CH_PCI_PMON_CTL0_ADDR, MC_CH_PCI_PMON_CTL_EN); imcHandles[i]->write32(MC_CH_PCI_PMON_CTL0_ADDR, MC_CH_PCI_PMON_CTL_EN + MCCntConfig[0]); imcHandles[i]->write32(MC_CH_PCI_PMON_CTL1_ADDR, MC_CH_PCI_PMON_CTL_EN); imcHandles[i]->write32(MC_CH_PCI_PMON_CTL1_ADDR, MC_CH_PCI_PMON_CTL_EN + MCCntConfig[1]); imcHandles[i]->write32(MC_CH_PCI_PMON_CTL2_ADDR, MC_CH_PCI_PMON_CTL_EN); imcHandles[i]->write32(MC_CH_PCI_PMON_CTL2_ADDR, MC_CH_PCI_PMON_CTL_EN + MCCntConfig[2]); imcHandles[i]->write32(MC_CH_PCI_PMON_CTL3_ADDR, MC_CH_PCI_PMON_CTL_EN); imcHandles[i]->write32(MC_CH_PCI_PMON_CTL3_ADDR, MC_CH_PCI_PMON_CTL_EN + MCCntConfig[3]); // reset counters values imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN + MC_CH_PCI_PMON_BOX_CTL_FRZ + MC_CH_PCI_PMON_BOX_CTL_RST_COUNTERS); // unfreeze counters imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN); } } void ServerPCICFGUncore::freezeCounters() { for (uint32 i = 0; i < num_qpi_ports; ++i) { qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN + Q_P_PCI_PMON_BOX_CTL_RST_FRZ); } for (uint32 i = 0; i < num_imc_channels; ++i) { imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN + MC_CH_PCI_PMON_BOX_CTL_FRZ); } } void ServerPCICFGUncore::unfreezeCounters() { for (uint32 i = 0; i < num_qpi_ports; ++i) { qpiLLHandles[i]->write32(Q_P_PCI_PMON_BOX_CTL_ADDR, Q_P_PCI_PMON_BOX_CTL_RST_FRZ_EN); } for (uint32 i = 0; i < num_imc_channels; ++i) { imcHandles[i]->write32(MC_CH_PCI_PMON_BOX_CTL_ADDR, MC_CH_PCI_PMON_BOX_CTL_FRZ_EN); } } uint64 ServerPCICFGUncore::getQPIClocks(uint32 port) { uint64 res = 0; if (port >= num_qpi_ports) return 0; qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR3_ADDR, &res); return res; } uint64 ServerPCICFGUncore::getQPIL0pTxCycles(uint32 port) { uint64 res = 0; if (port >= num_qpi_ports) return 0; qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR0_ADDR, &res); return res; } uint64 ServerPCICFGUncore::getQPIL1Cycles(uint32 port) { uint64 res = 0; if (port >= num_qpi_ports) return 0; qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR2_ADDR, &res); return res; } uint64 ServerPCICFGUncore::getDRAMClocks(uint32 channel) { uint64 result = 0; if(channel < num_imc_channels) imcHandles[channel]->read64(MC_CH_PCI_PMON_FIXED_CTR_ADDR, &result); return result; } uint64 ServerPCICFGUncore::getMCCounter(uint32 channel, uint32 counter) { uint64 result = 0; if(channel < num_imc_channels) { switch(counter) { case 0: imcHandles[channel]->read64(MC_CH_PCI_PMON_CTR0_ADDR, &result); break; case 1: imcHandles[channel]->read64(MC_CH_PCI_PMON_CTR1_ADDR, &result); break; case 2: imcHandles[channel]->read64(MC_CH_PCI_PMON_CTR2_ADDR, &result); break; case 3: imcHandles[channel]->read64(MC_CH_PCI_PMON_CTR3_ADDR, &result); break; } } return result; } uint64 ServerPCICFGUncore::getQPILLCounter(uint32 port, uint32 counter) { uint64 result = 0; if(port < num_qpi_ports) { switch(counter) { case 0: qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR0_ADDR, &result); break; case 1: qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR1_ADDR, &result); break; case 2: qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR2_ADDR, &result); break; case 3: qpiLLHandles[port]->read64(Q_P_PCI_PMON_CTR3_ADDR, &result); break; } } return result; } void ServerPCICFGUncore::enableJKTWorkaround(bool enable) { { PciHandleM reg(groupnr,bus,14,0); uint32 value = 0; reg.read32(0x84, &value); if(enable) value |= 2; else value &= (~2); reg.write32(0x84, value); } { PciHandleM reg(groupnr,bus,8,0); uint32 value = 0; reg.read32(0x80, &value); if(enable) value |= 2; else value &= (~2); reg.write32(0x80, value); } { PciHandleM reg(groupnr,bus,9,0); uint32 value = 0; reg.read32(0x80, &value); if(enable) value |= 2; else value &= (~2); reg.write32(0x80, value); } } uint64 ServerPCICFGUncore::computeQPISpeed() { if(qpi_speed) return qpi_speed; PciHandleM reg(groupnr,bus,QPI_PORT0_MISC_REGISTER_DEV_ADDR,QPI_PORT0_MISC_REGISTER_FUNC_ADDR); uint32 value = 0; reg.read32(QPI_RATE_STATUS_ADDR, &value); value &= 7; // extract lower 3 bits if(value) qpi_speed = (4000000000ULL + ((uint64)value)*800000000ULL)*2ULL; if(qpi_speed) return qpi_speed; std::cout << "Warning: QPI_RATE_STATUS register is not available. Computing QPI speed using a measurement loop." << std::endl; // compute qpi speed const uint32 core_nr = 0; const uint32 port_nr = 0; const uint64 timerGranularity = 1000000ULL; // mks PCM * pcm = PCM::getInstance(); uint64 startClocks = getQPIClocks(port_nr); uint64 startTSC = pcm->getTickCount(timerGranularity, core_nr); uint64 endTSC; do { endTSC = pcm->getTickCount(timerGranularity, core_nr); } while (endTSC - startTSC < 200000ULL); // spin for 200 ms uint64 endClocks = getQPIClocks(port_nr); qpi_speed = ((std::max)((endClocks - startClocks) * 16ULL * timerGranularity / (endTSC - startTSC),0ULL)); return qpi_speed; } #ifdef _MSC_VER DWORD WINAPI WatchDogProc(LPVOID state) #else void * WatchDogProc(void * state) #endif { CounterWidthExtender * ext = (CounterWidthExtender * ) state; while(1) { #ifdef _MSC_VER Sleep(10000); #else sleep(10); #endif /* uint64 dummy = */ ext->read(); } return NULL; } uint32 PCM::CX_MSR_PMON_CTRY(uint32 Cbo, uint32 Ctr) const { if(JAKETOWN == cpu_model || IVYTOWN == cpu_model) { return JKT_C0_MSR_PMON_CTR0 + ((JKTIVT_CBO_MSR_STEP)*Cbo) + Ctr; } return 0; } uint32 PCM::CX_MSR_PMON_BOX_FILTER(uint32 Cbo) const { if(JAKETOWN == cpu_model || IVYTOWN == cpu_model) { return JKT_C0_MSR_PMON_BOX_FILTER + ((JKTIVT_CBO_MSR_STEP)*Cbo); } return 0; } uint32 PCM::CX_MSR_PMON_BOX_FILTER1(uint32 Cbo) const { if(IVYTOWN == cpu_model) { return IVT_C0_MSR_PMON_BOX_FILTER1 + ((JKTIVT_CBO_MSR_STEP)*Cbo); } return 0; } uint32 PCM::CX_MSR_PMON_CTLY(uint32 Cbo, uint32 Ctl) const { if(JAKETOWN == cpu_model || IVYTOWN == cpu_model) { return JKT_C0_MSR_PMON_CTL0 + ((JKTIVT_CBO_MSR_STEP)*Cbo) + Ctl; } return 0; } uint32 PCM::CX_MSR_PMON_BOX_CTL(uint32 Cbo) const { if(JAKETOWN == cpu_model || IVYTOWN == cpu_model) { return JKT_C0_MSR_PMON_BOX_CTL + ((JKTIVT_CBO_MSR_STEP)*Cbo); } return 0; } uint32 PCM::getMaxNumOfCBoxes() const { if(1) { /* * There is one CBox per physical core. This calculation will get us * the number of physical cores per socket which is the expected * value to be returned. */ return num_cores / num_sockets / threads_per_core; } return 0; } void PCM::programCboOpcodeFilter(const uint32 opc, const uint32 cbo, MsrHandle * msr) { if(JAKETOWN == cpu_model) { msr->write(CX_MSR_PMON_BOX_FILTER(cbo), JKT_CBO_MSR_PMON_BOX_FILTER_OPC(opc)); } else if(IVYTOWN == cpu_model) { msr->write(CX_MSR_PMON_BOX_FILTER1(cbo), IVT_CBO_MSR_PMON_BOX_FILTER1_OPC(opc)); } } void PCM::programPCIeCounters(const PCM::PCIeEventCode event_) { for (int32 i = 0; (i < num_sockets) && MSR; ++i) { uint32 refCore = socketRefCore[i]; TemporalThreadAffinity tempThreadAffinity(refCore); // speedup trick for Linux for(uint32 cbo = 0; cbo < getMaxNumOfCBoxes(); ++cbo) { // freeze enable MSR[refCore]->write(CX_MSR_PMON_BOX_CTL(cbo), CBO_MSR_PMON_BOX_CTL_FRZ_EN); // freeze MSR[refCore]->write(CX_MSR_PMON_BOX_CTL(cbo), CBO_MSR_PMON_BOX_CTL_FRZ_EN + CBO_MSR_PMON_BOX_CTL_FRZ); uint64 val = 0; MSR[refCore]->read(CX_MSR_PMON_BOX_CTL(cbo), &val); if ((val & UNCORE_PMON_BOX_CTL_VALID_BITS_MASK) != (CBO_MSR_PMON_BOX_CTL_FRZ_EN + CBO_MSR_PMON_BOX_CTL_FRZ)) { std::cout << "ERROR: CBO counter programming seems not to work. "; std::cout << "C" << std::dec << cbo << "_MSR_PMON_BOX_CTL=0x" << std::hex << val << std::endl; } programCboOpcodeFilter(event_, cbo, MSR[refCore]); MSR[refCore]->write(CX_MSR_PMON_CTLY(cbo, 0), CBO_MSR_PMON_CTL_EN); // TOR_INSERTS.OPCODE event MSR[refCore]->write(CX_MSR_PMON_CTLY(cbo, 0), CBO_MSR_PMON_CTL_EN + CBO_MSR_PMON_CTL_EVENT(0x35) + CBO_MSR_PMON_CTL_UMASK(1)); // reset counter values MSR[refCore]->write(CX_MSR_PMON_BOX_CTL(cbo), CBO_MSR_PMON_BOX_CTL_FRZ_EN + CBO_MSR_PMON_BOX_CTL_FRZ + CBO_MSR_PMON_BOX_CTL_RST_COUNTERS); // unfreeze counters MSR[refCore]->write(CX_MSR_PMON_BOX_CTL(cbo), CBO_MSR_PMON_BOX_CTL_FRZ_EN); } } } PCIeCounterState PCM::getPCIeCounterState(const uint32 socket_) { PCIeCounterState result; uint32 refCore = socketRefCore[socket_]; TemporalThreadAffinity tempThreadAffinity(refCore); // speedup trick for Linux for(uint32 cbo=0; cbo < getMaxNumOfCBoxes(); ++cbo) { uint64 ctrVal = 0; MSR[refCore]->read(CX_MSR_PMON_CTRY(cbo, 0), &ctrVal); result.data += ctrVal; } return result; }
[ "hiren.panchasara@gmail.com" ]
hiren.panchasara@gmail.com
3211219f6d7ccd69cf08a526748e152d574e42aa
5dd2818fd4499b5e4c79d6f51625092a4e8daa92
/runtime/vm/compiler/backend/compile_type.h
9aa145d6a5a0b79aeb622e84063c765bfa8025ec
[ "BSD-3-Clause", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
marcustanx/sdk
af95bedd5b505bb7066c6d7fbd8874638b75f282
96a8282cd9039d18eeeb066e3c629e19efa5028f
refs/heads/master
2020-12-06T02:31:25.190209
2020-01-07T07:52:32
2020-01-07T07:52:32
232,301,551
1
0
BSD-3-Clause
2020-01-07T10:33:59
2020-01-07T10:33:58
null
UTF-8
C++
false
false
8,532
h
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #ifndef RUNTIME_VM_COMPILER_BACKEND_COMPILE_TYPE_H_ #define RUNTIME_VM_COMPILER_BACKEND_COMPILE_TYPE_H_ #include "vm/allocation.h" #include "vm/class_id.h" #include "vm/compiler/runtime_api.h" namespace dart { class AbstractType; class BufferFormatter; class Definition; class FlowGraphSerializer; class SExpression; class SExpList; enum class NNBDMode; template <typename T> class GrowableArray; // CompileType describes type of a value produced by a definition. // // It captures the following properties: // - whether the value can potentially be null or if it is definitely not // null; // - concrete class id of the value or kDynamicCid if unknown statically; // - abstract super type of the value, concrete type of the value in runtime // is guaranteed to be sub type of this type. // // Values of CompileType form a lattice with a None type as a bottom and a // nullable Dynamic type as a top element. Method Union provides a join // operation for the lattice. class CompileType : public ZoneAllocated { public: static const bool kNullable = true; static const bool kNonNullable = false; // TODO(regis): Should CompileType take an NNBDMode? CompileType(bool is_nullable, intptr_t cid, const AbstractType* type) : is_nullable_(is_nullable), cid_(cid), type_(type) {} CompileType(const CompileType& other) : ZoneAllocated(), is_nullable_(other.is_nullable_), cid_(other.cid_), type_(other.type_) {} CompileType& operator=(const CompileType& other) { // This intentionally does not change the owner of this type. is_nullable_ = other.is_nullable_; cid_ = other.cid_; type_ = other.type_; return *this; } bool is_nullable() const { return is_nullable_; } // Return type such that concrete value's type in runtime is guaranteed to // be subtype of it. const AbstractType* ToAbstractType(); // Return class id such that it is either kDynamicCid or in runtime // value is guaranteed to have an equal class id. intptr_t ToCid(); // Return class id such that it is either kDynamicCid or in runtime // value is guaranteed to be either null or have an equal class id. intptr_t ToNullableCid(); // Return true if the value is guaranteed to be not-null or is known to be // always null. bool HasDecidableNullability(); // Return true if the value is known to be always null. bool IsNull(); // Return true if this type is a subtype of the given type. bool IsSubtypeOf(NNBDMode mode, const AbstractType& other); // Return true if value of this type is assignable to a location of the // given type. bool IsAssignableTo(NNBDMode mode, const AbstractType& type) { bool is_instance; return CanComputeIsInstanceOf(mode, type, kNullable, &is_instance) && is_instance; } // Create a new CompileType representing given combination of class id and // abstract type. The pair is assumed to be coherent. static CompileType Create(intptr_t cid, const AbstractType& type); // Return the non-nullable version of this type. CompileType CopyNonNullable() { if (IsNull()) { // Represent a non-nullable null type (typically arising for // unreachable values) as None. return None(); } return CompileType(kNonNullable, cid_, type_); } static CompileType CreateNullable(bool is_nullable, intptr_t cid) { return CompileType(is_nullable, cid, nullptr); } // Create a new CompileType representing given abstract type. By default // values as assumed to be nullable. static CompileType FromAbstractType(const AbstractType& type, bool is_nullable = kNullable); // Create a new CompileType representing a value with the given class id. // Resulting CompileType is nullable only if cid is kDynamicCid or kNullCid. static CompileType FromCid(intptr_t cid); // Create None CompileType. It is the bottom of the lattice and is used to // represent type of the phi that was not yet inferred. static CompileType None() { return CompileType(kNullable, kIllegalCid, nullptr); } // Create Dynamic CompileType. It is the top of the lattice and is used to // represent unknown type. static CompileType Dynamic(); static CompileType Null(); // Create non-nullable Bool type. static CompileType Bool(); // Create non-nullable Int type. static CompileType Int(); // Create non-nullable 32-bit Int type (arch dependent). static CompileType Int32(); // Create nullable Int type. static CompileType NullableInt(); // Create non-nullable Smi type. static CompileType Smi(); // Create nullable Smi type. static CompileType NullableSmi() { return CreateNullable(kNullable, kSmiCid); } // Create nullable Mint type. static CompileType NullableMint() { return CreateNullable(kNullable, kMintCid); } // Create non-nullable Double type. static CompileType Double(); // Create nullable Double type. static CompileType NullableDouble(); // Create non-nullable String type. static CompileType String(); // Perform a join operation over the type lattice. void Union(CompileType* other); // Refine old type with newly inferred type (it could be more or less // specific, or even unrelated to an old type in case of unreachable code). // May return 'old_type', 'new_type' or create a new CompileType instance. static CompileType* ComputeRefinedType(CompileType* old_type, CompileType* new_type); // Return true if this and other types are the same. bool IsEqualTo(CompileType* other) { return (is_nullable_ == other->is_nullable_) && (ToNullableCid() == other->ToNullableCid()) && (compiler::IsEqualType(*ToAbstractType(), *other->ToAbstractType())); } bool IsNone() const { return (cid_ == kIllegalCid) && (type_ == nullptr); } // Return true if value of this type is a non-nullable int. bool IsInt() { return !is_nullable() && IsNullableInt(); } // Return true if value of this type is a non-nullable double. bool IsDouble() { return !is_nullable() && IsNullableDouble(); } // Return true if value of this type is either int or null. bool IsNullableInt() { if (cid_ == kSmiCid || cid_ == kMintCid) { return true; } if (cid_ == kIllegalCid || cid_ == kDynamicCid) { return type_ != nullptr && (compiler::IsIntType(*type_) || compiler::IsSmiType(*type_)); } return false; } // Returns true if value of this type is either Smi or null. bool IsNullableSmi() { if (cid_ == kSmiCid) { return true; } if (cid_ == kIllegalCid || cid_ == kDynamicCid) { return type_ != nullptr && compiler::IsSmiType(*type_); } return false; } // Return true if value of this type is either double or null. bool IsNullableDouble() { if (cid_ == kDoubleCid) { return true; } if ((cid_ == kIllegalCid) || (cid_ == kDynamicCid)) { return type_ != nullptr && compiler::IsDoubleType(*type_); } return false; } bool Specialize(GrowableArray<intptr_t>* class_ids); void PrintTo(BufferFormatter* f) const; SExpression* ToSExpression(FlowGraphSerializer* s) const; void AddExtraInfoToSExpression(SExpList* sexp, FlowGraphSerializer* s) const; const char* ToCString() const; // CompileType object might be unowned or owned by a definition. // Owned CompileType objects can change during type propagation when // [RecomputeType] is called on the owner. We keep track of which // definition owns [CompileType] to prevent situations where // owned [CompileType] is cached as a reaching type in a [Value] which // is no longer connected to the original owning definition. // See [Value::SetReachingType]. void set_owner(Definition* owner) { owner_ = owner; } Definition* owner() const { return owner_; } private: bool CanComputeIsInstanceOf(NNBDMode mode, const AbstractType& type, bool is_nullable, bool* is_instance); bool is_nullable_; classid_t cid_; const AbstractType* type_; Definition* owner_ = nullptr; }; } // namespace dart #endif // RUNTIME_VM_COMPILER_BACKEND_COMPILE_TYPE_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
4bea5ad68e2869f3a62302bb3b81b76311ff96d2
f06d9b671187f13eaa27b1ea272d11a9588ac546
/《剑指offer》/52-正则表达式/main.cpp
2ae168384b479cca19bfc37526ae375471ad9914
[]
no_license
Rani-Zz/skill-tutorials
49eb3d18d69e2d92b7b34b4c5d8a3db21a4b9749
da50fa072fab2bf49cca6c534472b26bd182ae33
refs/heads/master
2020-05-01T07:57:26.497704
2019-09-11T02:58:57
2019-09-11T02:58:57
177,365,049
0
0
null
null
null
null
GB18030
C++
false
false
1,837
cpp
class Solution { public: /** *1)如果两个都为空 为true *2)如果字符串不空,模式为空,false(反过来就不一定了,模式如果为*那也是匹配的) *3)字符串空模式不空,匹配成功的话就是模式为‘.’,只有这一种情况 * 都不为空,开始匹配第一个字符,但是第二个字符是不是'*'会影响第一个字符的匹配 * 所以分两种情况: * a)第二个字符不为‘*’,则第一个字符相同或是模式为‘.’且str不空则匹配成功否则失败,匹配成功继续下一位 * b)第二个字符为‘*’,因为‘*’前面的字符可以出现0次或者多次,所以再分情况: i)匹配0次,也就是当前不等,那么模式跳过‘*’即后移两位继续匹配,str不变 ii)只匹配1次,也就是当前相等,那依旧跳过‘*’ 或者匹配多次,str后移1位,模式不变 *思路还待补充 *因为*str == *pattern时有两种情况:匹配0个字符和匹配一次及以上,如ab和a*ab就只需要匹配零个。*str != *pattern只有一种情况,就只能匹配0个字符 */ bool match(char* str, char* pattern) { if(*str=='\0'&&*pattern=='\0') return true; if(*str!='\0'&&*pattern=='\0') return false; if(*(pattern+1)!='*') { if(*str==*pattern||(*pattern=='.'&&*str!='\0')) return match(str+1,pattern+1); else return false; }else{ if(*str==*pattern||(*str != '\0' && *pattern == '.')) return match(str,pattern+2)||match(str+1,pattern); else return match(str,pattern+2); } } };
[ "850150293@qq.com" ]
850150293@qq.com
c235bf48f037270530e64f971bbc0b4c693cec2c
dde362ba02ee1c1a99e598c0f975e5661ae583d3
/myexp.h
dbaa40f7b55bb7a941fb168d9302244c207ec49a
[ "MIT" ]
permissive
PawellKowalski/repo158335
62f960aa4e6a485345ba1487086949cee8aa2574
55df855fc2cc3b7abc3714ee246243bcd42c6c7e
refs/heads/main
2023-02-18T19:12:22.508279
2021-01-17T20:47:20
2021-01-17T20:47:20
330,396,204
0
0
null
null
null
null
UTF-8
C++
false
false
202
h
class MyExp { public MyExp(); public MyExp(double x); public MyExp(const MyExp &obj); public ~MyExp(); public double value(); public void setX(double); public double getX(); private double mX; }
[ "158335@stud.prz.edu.pl" ]
158335@stud.prz.edu.pl
387060b885460de36e19e4d128c5d0bc87b6b5fc
81c66c9c0b78f8e9c698dcbb8507ec2922efc8b7
/src/domains/srcgc/kernel/SRCGCRecursiveScheduler.cc
40cbb92e599601d66113e7ba6edbd1c990ef47f6
[ "MIT-Modern-Variant" ]
permissive
Argonnite/ptolemy
3394f95d3f58e0170995f926bd69052e6e8909f2
581de3a48a9b4229ee8c1948afbf66640568e1e6
refs/heads/master
2021-01-13T00:53:43.646959
2015-10-21T20:49:36
2015-10-21T20:49:36
44,703,423
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,891
cc
/* -*-C++-*- * ################################################################### * SRCGC - Synchronous/Reactive C code generation for Ptolemy * * FILE: "SRCGCRecursiveScheduler.cc" * created: 9/03/98 16:41:11 * last update: 13/05/98 9:21:45 * Author: Vincent Legrand, Mathilde Roger, Frédéric Boulanger * E-mail: Frederic.Boulanger@supelec.fr * mail: Supélec - Service Informatique * Plateau de Moulon, F-91192 Gif-sur-Yvette cedex * www: http://wwwsi.supelec.fr/ * * Thomson: Xavier Warzee <XAVIER.W.X.WARZEE@tco.thomson.fr> * * Copyright (c) 1998 Supélec & Thomson-CSF Optronique. * All rights reserved. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in all * copies of this software. * * IN NO EVENT SHALL SUPELEC OR THOMSON-CSF OPTRONIQUE BE LIABLE TO ANY PARTY * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF * SUPELEC OR THOMSON-CSF OPTRONIQUE HAS BEEN ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * SUPELEC AND THOMSON-CSF OPTRONIQUE SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND SUPELEC OR THOMSON-CSF * OPTRONIQUE HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, * ENHANCEMENTS, OR MODIFICATIONS. * * See header file for further information * ################################################################### */ static const char file_id[] = "SRCGCRecursiveScheduler.cc"; #ifdef __GNUG__ #pragma implementation #endif #include "SRCGCStar.h" #include "SRCGCRecursiveScheduler.h" #include "SRRecSchedule.h" #include "GalIter.h" #include "Galaxy.h" extern const char SRCGCdomainName[]; // Return the name of the SRCGC domain const char* SRCGCRecursiveScheduler::domain() const { return SRCGCdomainName; } // Execute the galaxy for an instant // // @Description Call initializeInstant() on each star, and then for // each cluster, call run() on each star in the cluster, repeating the // cluster as many times as necessary. Call tick() on each star. void SRCGCRecursiveScheduler::compileRun() { GalStarIter nextStar( *galaxy() ); Star *s; // Run the schedule if ( schedule ) { schedule->runSchedule(); } // Finish the instant by calling each star's tick() method nextStar.reset(); while ( ( s = nextStar++ ) != 0 ) { ((SRCGCStar *) s)->tick(); // Only SR and SRCGC stars have a tick() method. } }
[ "dermalin3k@hotmail.com" ]
dermalin3k@hotmail.com
0410d3d58ad7d0a76a57a9ad4ec00c6bc6e2890d
b5db4d5e38ba006aa38d4d5bb66681d253679235
/D3Digger/_Include/common/bytes.h
2c0b4554212162a94b108f1ef2c0f26b1cdb44aa
[]
no_license
vasily-knk/D3Digger
f3088cd21440e1d4f80f20b3333bf8fc175d8571
0e3296a7a73bfaf4d1261a451177a3ea2f807d3b
refs/heads/master
2021-07-12T02:54:58.686339
2016-11-08T09:22:20
2016-11-08T09:22:20
18,885,229
1
0
null
null
null
null
UTF-8
C++
false
false
5,561
h
#pragma once namespace bytes { typedef vector<char> bytes_t; typedef shared_ptr<bytes_t> bytes_ptr; typedef shared_ptr<const bytes_t> bytes_const_ptr; typedef int32_t size_type; inline bytes_ptr make() { return make_shared<bytes_t>(); } namespace inner { inline void reserve_additional(bytes_ptr bytes, size_t size) { bytes->reserve(bytes->size() + size); } inline bytes_ptr make(size_t size) { return make_shared<bytes_t>(size); } template<typename T> void put(const T &data, bytes_ptr bytes, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value>::type* = nullptr) { const size_t offset = bytes->size(); bytes->resize(offset + sizeof(T)); *reinterpret_cast<T*>(&bytes->at(offset)) = data; } template<typename T> void put_array(T const *p, size_t num, bytes_ptr bytes, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value>::type* = nullptr) { size_t offset = bytes->size(); size_t size = num * sizeof(T); bytes->resize(offset + size); memcpy(&bytes->at(offset), p, size); } inline void append(bytes_ptr dst, bytes_const_ptr src) { reserve_additional(dst, src->size()); std::copy(src->begin(), src->end(), std::back_inserter(*dst)); } struct getter { struct error : std::runtime_error { error(string message) : std::runtime_error(message) { } }; getter(bytes_ptr bytes, bool allowLeft = false) : bytes_(bytes) , offset_(0) , allowLeft_(allowLeft) { } ~getter() { Assert(allowLeft_ || left() == 0); } size_t left() const { Assert(offset_ <= bytes_->size()); return bytes_->size() - offset_; } template<typename T> void get(T &data, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value>::type* = nullptr) { if (offset_ + sizeof(T) > bytes_->size()) throw error("Not enough bytes"); data = *reinterpret_cast<T*>(&bytes_->at(offset_)); offset_ += sizeof(T); } template<typename T> void get_array(T *p, size_t num, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value>::type* = nullptr) { size_t size = sizeof(T) * num; if (offset_ + size > bytes_->size()) throw error("Not enough bytes"); memcpy(p, &bytes_->at(offset_), size); offset_ += size; } private: bytes_ptr bytes_; size_t offset_; bool allowLeft_; }; } // namespace struct read_proc { read_proc(bytes_ptr bytes) : g_(bytes) {} template<typename T> void operator()(T const &dst, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value>::type* = nullptr) { g_.get(const_cast<T&>(dst)); } template<typename T> void array(T *const ptr, size_t size, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value>::type* = nullptr) { typedef std::remove_const<T>::type nonconst_type; nonconst_type* conv_ptr = const_cast<nonconst_type*>(ptr); g_.get_array<nonconst_type>(conv_ptr, size); } template<typename T> void operator()(T const &dst, typename std::enable_if<!std::is_arithmetic<T>::value && !std::is_enum<T>::value>::type* = nullptr) { refl::process(*this, dst); } template<typename T> void array(T *const ptr, size_t size, typename std::enable_if<!std::is_arithmetic<T>::value && !std::is_enum<T>::value>::type* = nullptr) { T* dst = const_cast<T*>(ptr); for (size_t i = 0; i < size; ++i) this->operator()(dst[i]); } template<typename T, size_t N> void operator()(T const(&arr)[N]) { array(arr, N); } template<typename T> T operator()() { T res; this->operator()(res); return res; } private: inner::getter g_; }; struct write_proc { write_proc(bytes_ptr bytes) : bytes_(bytes) {} template<typename T> void operator()(T const &src, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value>::type* = nullptr) { inner::put(src, bytes_); } template<typename T> void array(T *const ptr, size_t size, typename std::enable_if<std::is_arithmetic<T>::value || std::is_enum<T>::value>::type* = nullptr) { inner::put_array(ptr, size, bytes_); } template<typename T> void array(T *const ptr, size_t size, typename std::enable_if<!std::is_arithmetic<T>::value && !std::is_enum<T>::value>::type* = nullptr) { for (size_t i = 0; i < size; ++i) this->operator()(ptr[i]); } template<typename T, size_t N> void operator()(T const(&arr)[N]) { array(arr, N); } template<typename T> void operator()(T const &src, typename std::enable_if<!std::is_arithmetic<T>::value && !std::is_enum<T>::value>::type* = nullptr) { refl::process(*this, src); } private: bytes_ptr bytes_; }; } typedef bytes::bytes_t Bytes; typedef bytes::bytes_ptr BytesPtr; typedef bytes::bytes_const_ptr BytesConstPtr;
[ "vasily.knk@gmail.com" ]
vasily.knk@gmail.com
8f2bed338378070cbdb1847512119b2703e63049
d5926e2c62d43a14c3180ee7756b4bf93f0c1286
/src/dxvk/dxvk_event.h
325e1cea84542a09391cfeb7858fe4e6833314f5
[ "LicenseRef-scancode-warranty-disclaimer", "Zlib" ]
permissive
steemandlinux/dxvk
fea58bf9e64fe2f743b51a2b8831ea152297d6f3
858107278faedba71d81258e0b2441b5789ad7d5
refs/heads/master
2021-01-24T04:29:10.003476
2018-02-23T08:01:10
2018-02-25T06:48:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,213
h
#pragma once #include <mutex> #include "dxvk_include.h" namespace dxvk { /** * \brief Event status */ enum class DxvkEventStatus { Reset = 0, Signaled = 1, }; /** * \brief Event * * A CPU-side fence that will be signaled after * all previous Vulkan commands recorded to a * command buffer have finished executing. */ class DxvkEvent : public RcObject { public: DxvkEvent(); ~DxvkEvent(); /** * \brief Resets the event * \returns New revision ID */ uint32_t reset(); /** * \brief Signals the event * \param [in] revision The revision ID */ void signal(uint32_t revision); /** * \brief Queries event status * \returns Current event status */ DxvkEventStatus getStatus(); private: std::mutex m_mutex; DxvkEventStatus m_status = DxvkEventStatus::Reset; uint32_t m_revision = 0; }; /** * \brief Event revision * * Stores the event object and the * version ID for event operations. */ struct DxvkEventRevision { Rc<DxvkEvent> event; uint32_t revision; }; }
[ "philip.rebohle@tu-dortmund.de" ]
philip.rebohle@tu-dortmund.de
a19bc3f8b8a0ac4fc10261699b0e14ff5f3c03a5
f5acd38efe9f28e14a3e77cf60f938000a6660ab
/clients/cpp-qt5/generated/client/OAIPipelineActivityartifacts.h
44b771642f22c74be6abc4cb4ec2303f07d534e7
[ "MIT" ]
permissive
rahulyhg/swaggy-jenkins
3fc9377c8cf8643d6b4ffe4a6aceb49315afdb8e
21326779f8814a07153acaf5af15ffbbd593c48b
refs/heads/master
2020-05-04T16:14:43.369417
2019-01-27T06:27:32
2019-01-27T06:27:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,467
h
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * OpenAPI spec version: 1.0.0 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIPipelineActivityartifacts.h * * */ #ifndef OAIPipelineActivityartifacts_H_ #define OAIPipelineActivityartifacts_H_ #include <QJsonObject> #include <QString> #include "OAIObject.h" namespace OpenAPI { class OAIPipelineActivityartifacts: public OAIObject { public: OAIPipelineActivityartifacts(); OAIPipelineActivityartifacts(QString json); ~OAIPipelineActivityartifacts(); void init(); void cleanup(); QString asJson () override; QJsonObject asJsonObject() override; void fromJsonObject(QJsonObject json) override; OAIPipelineActivityartifacts* fromJson(QString jsonString) override; QString* getName(); void setName(QString* name); qint32 getSize(); void setSize(qint32 size); QString* getUrl(); void setUrl(QString* url); QString* getClass(); void setClass(QString* _class); virtual bool isSet() override; private: QString* name; bool m_name_isSet; qint32 size; bool m_size_isSet; QString* url; bool m_url_isSet; QString* _class; bool m__class_isSet; }; } #endif /* OAIPipelineActivityartifacts_H_ */
[ "cliffano@gmail.com" ]
cliffano@gmail.com
d73ef64d42aa583a8d296dd091e496b341b3d8e8
9eda9581cf81d6ce8b0c009a3925ab125b844fce
/src/plugins/displayGraphic2D/displaygraphic2dhelp.cpp
ee978ee8e50e2473a27b92ae94a1beb6124a624e
[]
no_license
XavierBerger/gpsbook
a33641a95e0020afd5eb54c69aa445fc7a2ca484
81b04c1741d6e568607472111bbbef2f1d72fc59
refs/heads/master
2021-01-18T22:31:26.692232
2016-05-06T19:19:19
2016-05-06T19:19:19
32,142,962
0
0
null
null
null
null
UTF-8
C++
false
false
2,068
cpp
/**************************************************************************** ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the GNU General Public License ** as published by the Free Software Foundation; either version 2 ** of the License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, ** Boston, MA 02110-1301, USA. ** ** --- ** Copyright (c) 2010, gpsbook-team ** ****************************************************************************/ #include "displaygraphic2dhelp.h" #include "ui_displaygraphic2dhelp.h" /*------------------------------------------------------------------------------* *------------------------------------------------------------------------------*/ DisplayGraphic2DHelp::DisplayGraphic2DHelp(QWidget *parent) : QTextBrowser(parent), ui(new Ui::DisplayGraphic2DHelp) { ui->setupUi(this); } //DisplayGraphic2DHelp::DisplayGraphic2DHelp /*------------------------------------------------------------------------------* *------------------------------------------------------------------------------*/ DisplayGraphic2DHelp::~DisplayGraphic2DHelp() { delete ui; } //DisplayGraphic2DHelp::~DisplayGraphic2DHelp /*------------------------------------------------------------------------------* *------------------------------------------------------------------------------*/ void DisplayGraphic2DHelp::changeEvent(QEvent *e) { QFrame::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } //DisplayGraphic2DHelp::changeEvent
[ "gpxbook@c08623ad-424c-67e4-2eed-d735b91391dd" ]
gpxbook@c08623ad-424c-67e4-2eed-d735b91391dd
bc0f32e0c47dea7a228a6bfda016914e4f51c5c8
d79abe05f07e79e6b491fd4d09bdeaae9b208131
/src/day02/day2.cpp
ed5cce25b79bad01ad148a5d03e521598274df5e
[]
no_license
biggysmith/advent_of_code_2019
8ee4c03b9daabace075d1e46e5356503b531ad5c
bffd7dcb9ca917fc8ce131385efd861d419ceedc
refs/heads/master
2023-02-15T05:58:19.918820
2021-01-06T02:08:27
2021-01-06T02:08:27
321,802,311
1
0
null
null
null
null
UTF-8
C++
false
false
1,412
cpp
#include <vector> #include <numeric> #include <algorithm> #include <iostream> #include <fstream> #include <sstream> std::vector<int> parse_input(const std::string& file){ std::vector<int> input; std::ifstream file_stream(file); std::string line; std::getline(file_stream, line); std::stringstream ss(line); std::string number_str; while(std::getline(ss, number_str, ',')){ input.push_back(std::stoi(number_str)); } return input; } void main() { auto input = parse_input("../src/day02/day2_input.txt"); auto run = [&](int noun,int verb){ auto prog = input; prog[1] = noun; prog[2] = verb; int i = 0; while (prog[i] != 99) { if (prog[i] == 1) { prog[prog[i+3]] = prog[prog[i+1]] + prog[prog[i+2]]; }else if (prog[i] == 2) { prog[prog[i+3]] = prog[prog[i+1]] * prog[prog[i+2]]; }else { return -1; } i += 4; } return prog[0]; }; std::cout << "part1: " << run(12,2) << std::endl; for(int noun=0; noun<100; ++noun){ for(int verb=0; verb<100; ++verb){ if(run(noun,verb) == 19690720){ std::cout << "part2: " << 100 << " * " << noun << " + " << verb << " = " << 100*noun+verb << std::endl; return; } } } }
[ "ssmith@tmvse.com" ]
ssmith@tmvse.com
d94da1c35e679522dfba366cbe80e91a8d927e12
94dcc118f9492896d6781e5a3f59867eddfbc78a
/llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp
6aea79fe5a38a28fed4db4a5386f708d92375d8c
[ "NCSA", "Apache-2.0" ]
permissive
vusec/safeinit
43fd500b5a832cce2bd87696988b64a718a5d764
8425bc49497684fe16e0063190dec8c3c58dc81a
refs/heads/master
2021-07-07T11:46:25.138899
2021-05-05T10:40:52
2021-05-05T10:40:52
76,794,423
22
5
null
null
null
null
UTF-8
C++
false
false
10,744
cpp
//===-------- LoopDataPrefetch.cpp - Loop Data Prefetching Pass -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a Loop Data Prefetching Pass. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "loop-data-prefetch" #include "llvm/Transforms/Scalar.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/CodeMetrics.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" #include "llvm/Analysis/ScalarEvolutionExpander.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/CFG.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Transforms/Utils/ValueMapper.h" using namespace llvm; // By default, we limit this to creating 16 PHIs (which is a little over half // of the allocatable register set). static cl::opt<bool> PrefetchWrites("loop-prefetch-writes", cl::Hidden, cl::init(false), cl::desc("Prefetch write addresses")); static cl::opt<unsigned> PrefetchDistance("prefetch-distance", cl::desc("Number of instructions to prefetch ahead"), cl::Hidden); static cl::opt<unsigned> MinPrefetchStride("min-prefetch-stride", cl::desc("Min stride to add prefetches"), cl::Hidden); static cl::opt<unsigned> MaxPrefetchIterationsAhead( "max-prefetch-iters-ahead", cl::desc("Max number of iterations to prefetch ahead"), cl::Hidden); STATISTIC(NumPrefetches, "Number of prefetches inserted"); namespace llvm { void initializeLoopDataPrefetchPass(PassRegistry&); } namespace { class LoopDataPrefetch : public FunctionPass { public: static char ID; // Pass ID, replacement for typeid LoopDataPrefetch() : FunctionPass(ID) { initializeLoopDataPrefetchPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<AssumptionCacheTracker>(); AU.addPreserved<DominatorTreeWrapperPass>(); AU.addRequired<LoopInfoWrapperPass>(); AU.addPreserved<LoopInfoWrapperPass>(); AU.addRequired<ScalarEvolutionWrapperPass>(); // FIXME: For some reason, preserving SE here breaks LSR (even if // this pass changes nothing). // AU.addPreserved<ScalarEvolutionWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>(); } bool runOnFunction(Function &F) override; private: bool runOnLoop(Loop *L); /// \brief Check if the the stride of the accesses is large enough to /// warrant a prefetch. bool isStrideLargeEnough(const SCEVAddRecExpr *AR); unsigned getMinPrefetchStride() { if (MinPrefetchStride.getNumOccurrences() > 0) return MinPrefetchStride; return TTI->getMinPrefetchStride(); } unsigned getPrefetchDistance() { if (PrefetchDistance.getNumOccurrences() > 0) return PrefetchDistance; return TTI->getPrefetchDistance(); } unsigned getMaxPrefetchIterationsAhead() { if (MaxPrefetchIterationsAhead.getNumOccurrences() > 0) return MaxPrefetchIterationsAhead; return TTI->getMaxPrefetchIterationsAhead(); } AssumptionCache *AC; LoopInfo *LI; ScalarEvolution *SE; const TargetTransformInfo *TTI; const DataLayout *DL; }; } char LoopDataPrefetch::ID = 0; INITIALIZE_PASS_BEGIN(LoopDataPrefetch, "loop-data-prefetch", "Loop Data Prefetch", false, false) INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) INITIALIZE_PASS_END(LoopDataPrefetch, "loop-data-prefetch", "Loop Data Prefetch", false, false) FunctionPass *llvm::createLoopDataPrefetchPass() { return new LoopDataPrefetch(); } bool LoopDataPrefetch::isStrideLargeEnough(const SCEVAddRecExpr *AR) { unsigned TargetMinStride = getMinPrefetchStride(); // No need to check if any stride goes. if (TargetMinStride <= 1) return true; const auto *ConstStride = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)); // If MinStride is set, don't prefetch unless we can ensure that stride is // larger. if (!ConstStride) return false; unsigned AbsStride = std::abs(ConstStride->getAPInt().getSExtValue()); return TargetMinStride <= AbsStride; } bool LoopDataPrefetch::runOnFunction(Function &F) { if (skipFunction(F)) return false; LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); DL = &F.getParent()->getDataLayout(); AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); // If PrefetchDistance is not set, don't run the pass. This gives an // opportunity for targets to run this pass for selected subtargets only // (whose TTI sets PrefetchDistance). if (getPrefetchDistance() == 0) return false; assert(TTI->getCacheLineSize() && "Cache line size is not set for target"); bool MadeChange = false; for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I) for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L) MadeChange |= runOnLoop(*L); return MadeChange; } bool LoopDataPrefetch::runOnLoop(Loop *L) { bool MadeChange = false; // Only prefetch in the inner-most loop if (!L->empty()) return MadeChange; SmallPtrSet<const Value *, 32> EphValues; CodeMetrics::collectEphemeralValues(L, AC, EphValues); // Calculate the number of iterations ahead to prefetch CodeMetrics Metrics; for (Loop::block_iterator I = L->block_begin(), IE = L->block_end(); I != IE; ++I) { // If the loop already has prefetches, then assume that the user knows // what he or she is doing and don't add any more. for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) if (CallInst *CI = dyn_cast<CallInst>(J)) if (Function *F = CI->getCalledFunction()) if (F->getIntrinsicID() == Intrinsic::prefetch) return MadeChange; Metrics.analyzeBasicBlock(*I, *TTI, EphValues); } unsigned LoopSize = Metrics.NumInsts; if (!LoopSize) LoopSize = 1; unsigned ItersAhead = getPrefetchDistance() / LoopSize; if (!ItersAhead) ItersAhead = 1; if (ItersAhead > getMaxPrefetchIterationsAhead()) return MadeChange; Function *F = L->getHeader()->getParent(); DEBUG(dbgs() << "Prefetching " << ItersAhead << " iterations ahead (loop size: " << LoopSize << ") in " << F->getName() << ": " << *L); SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads; for (Loop::block_iterator I = L->block_begin(), IE = L->block_end(); I != IE; ++I) { for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { Value *PtrValue; Instruction *MemI; if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) { MemI = LMemI; PtrValue = LMemI->getPointerOperand(); } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) { if (!PrefetchWrites) continue; MemI = SMemI; PtrValue = SMemI->getPointerOperand(); } else continue; unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace(); if (PtrAddrSpace) continue; if (L->isLoopInvariant(PtrValue)) continue; const SCEV *LSCEV = SE->getSCEV(PtrValue); const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV); if (!LSCEVAddRec) continue; // Check if the the stride of the accesses is large enough to warrant a // prefetch. if (!isStrideLargeEnough(LSCEVAddRec)) continue; // We don't want to double prefetch individual cache lines. If this load // is known to be within one cache line of some other load that has // already been prefetched, then don't prefetch this one as well. bool DupPref = false; for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end(); K != KE; ++K) { const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second); if (const SCEVConstant *ConstPtrDiff = dyn_cast<SCEVConstant>(PtrDiff)) { int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue()); if (PD < (int64_t) TTI->getCacheLineSize()) { DupPref = true; break; } } } if (DupPref) continue; const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr( SE->getConstant(LSCEVAddRec->getType(), ItersAhead), LSCEVAddRec->getStepRecurrence(*SE))); if (!isSafeToExpand(NextLSCEV, *SE)) continue; PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec)); Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace); SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr"); Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI); IRBuilder<> Builder(MemI); Module *M = (*I)->getParent()->getParent(); Type *I32 = Type::getInt32Ty((*I)->getContext()); Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch); Builder.CreateCall( PrefetchFunc, {PrefPtrValue, ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1), ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)}); ++NumPrefetches; DEBUG(dbgs() << " Access: " << *PtrValue << ", SCEV: " << *LSCEV << "\n"); emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, MemI->getDebugLoc(), "prefetched memory access"); MadeChange = true; } } return MadeChange; }
[ "fuzzie@fuzzie.org" ]
fuzzie@fuzzie.org
4de3a1315e4f20071548e9151e8d2bc25239d7bd
5f68034bffeb6ccec7e06e6222c698b1c564b23f
/42_1_ReverseWordsInSentence/main.cpp
a4e4b339265659fb593881b40684d1255bf3a3e6
[]
no_license
Howard725/offer
98194ebb32c1a840330fd2a9ddc512db3583a7a1
3a9fe795773681cdb29034fab6a2e9bf2b4ca0f7
refs/heads/master
2016-08-12T21:29:10.723817
2016-05-10T02:40:13
2016-05-10T02:40:13
52,920,071
1
0
null
null
null
null
UTF-8
C++
false
false
1,256
cpp
#include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; void reverseString( char *start, char *end ) { if ( NULL == start || NULL == end ) return; char temp; while ( start < end ) { temp = *start; *start = *end; *end = temp; start++; end--; } } void reverseWordsInSentence( char *sentence ) { if ( NULL == sentence ) return; //初始化两个指针 char *start = sentence, *end = sentence; while ( *end != '\0' ) end++; //反转整个字符串 reverseString( start, --end ); //循环遍历,同时寻找单词进行反转 start = end = sentence; while ( *start != '\0' ) { if ( *start == ' ' ) { start++; end++; } else if ( *end == ' ' || *end == '\0' ) { reverseString( start, --end ); end++; start = end; } else { end++; } } } int main() { cout << "Hello, World!" << endl; char input[100]; while ( gets(input ) ) { reverseWordsInSentence( input ); cout << input << endl; } system("PAUSE"); return 0; }
[ "wangren725@163.com" ]
wangren725@163.com
8bb183147385c4aeb31792c3776ae05d0fe86b1b
e521b57eb5d414b28c9e152e6c0921e8ab77ad43
/Test/tool.cpp
906ed30377919c25429dd4273af712ba27004403
[ "Apache-2.0" ]
permissive
zhaojunchen/PEViewPlus
90658d2e3c25a16e21c287970e563eaef32c41cb
ba36236bb6b2f88d1f326188f81203edb37cdfd9
refs/heads/master
2022-12-28T12:53:09.072123
2020-09-23T02:56:18
2020-09-23T02:56:18
259,530,475
2
1
null
null
null
null
UTF-8
C++
false
false
844
cpp
#ifndef TOOL_CPP #define TOOL_CPP #include <QDebug> #include <QString> /** * debug __LINE__ 出现错误的行号 * */ void error(QString msg, int line = 0) { if (line != 0) { qCritical() << "LINE " << line << " ERROR:" << msg << endl; } else { qCritical() << "ERROR:" << msg << endl; } } void report(QString msg, int line = 0) { if (line != 0) { qDebug() << "LINE " << line << " ERROR:" << msg << endl; } else { qDebug() << "Message: " << msg << endl; } } /** 输入指针 输入大小 * 输出指针内容的byte! * */ void show(void *src, int size) { char *p = (char *)src; for (int i = 0; i < size; i++) { if (i % 16 == 0) { qDebug() << endl; } qDebug("%02x ", (unsigned char)*p); p++; } } #endif // ifndef TOOL_CPP
[ "41560016+zhaojunchen@users.noreply.github.com" ]
41560016+zhaojunchen@users.noreply.github.com
80f769bcf9fb53be488d82b3af72b5503b62fbf1
a090af918e3ec59140027dbddd54aa4ca1c73910
/codeforces/262_B.cpp
8dea6e62da408b2704a77b85cf081d08f381a4e8
[]
no_license
nitesh-147/Programming-Problem-Solution
b739e2a3c9cfeb2141baf1d34e43eac0435ecb2a
df7d53e0863954ddf358539d23266b28d5504212
refs/heads/master
2023-03-16T00:37:10.236317
2019-11-28T18:11:33
2019-11-28T18:11:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
cpp
#include <bits/stdc++.h> #define LL long long #define MX 100009 #define clr(aa, bb) memset(aa, bb, sizeof aa) #define MD 1000000007 #define N 1000007 #define check_bit(a,b) (a & (1<<b)) #define set_bit(a,b) (a | (1<<b)) #define PB push_back #define FOR(aa,nn) for(aa=0; aa<nn; aa++) #define vi vector<int> #define vll vector<long long> using namespace std; LL digit(LL x) { int sum = 0; while(x) { sum += x%10; x = x / 10; } return sum; } int main() { // FILE * fin, * fout, *fp; // fp=fopen("out.txt", "w"); int i, j; int t; int x1, x2, y1, y2; LL n, m, c, b, a; cin>>a>>b>>c; vector<LL>V; V.clear(); for(LL i = 1; i <= 81; i++) { LL x = round(pow((double)i, (double)a )) * b + c; LL dig = digit(x); // cout<<i<<" "<<x<<" "<<dig<<endl; if(dig == i && x > 0 && x < 1000000000) { V.PB(x); } } sort(V.begin(), V.end()); cout<<V.size()<<endl; for(i = 0; i < V.size(); i++) cout<<V[i]<<" "; return 0; } /* 7 3 5 5 5 5 5 5 1 3 4 4 5 2 6 3 1 */
[ "milonju01@gmail.com" ]
milonju01@gmail.com
92d706982c9ec7439f9a905e269d6f27bc3e27be
fac52aacf1a7145d46f420bb2991528676e3be3f
/SDK/Night_Vision_Helmet_Down_07_classes.h
f8d480f22ef18eaec099f4997006939def219449
[]
no_license
zH4x-SDK/zSCUM-SDK
2342afd6ee54f4f0b14b0a0e9e3920d75bdb4fed
711376eb272b220521fec36d84ca78fc11d4802a
refs/heads/main
2023-07-15T16:02:22.649492
2021-08-27T13:44:21
2021-08-27T13:44:21
400,522,163
2
0
null
null
null
null
UTF-8
C++
false
false
688
h
#pragma once // Name: SCUM, Version: 4.20.3 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Night_Vision_Helmet_Down_07.Night_Vision_Helmet_Down_07_C // 0x0000 (0x0928 - 0x0928) class ANight_Vision_Helmet_Down_07_C : public AClothesItem { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Night_Vision_Helmet_Down_07.Night_Vision_Helmet_Down_07_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com