text
stringlengths
5
1.04M
#pragma GCC optimize("O3") #define TASK "" #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx") #define __USE_MINGW_ANSI_STDIO 0 #include<bits/stdc++.h> using namespace std; #define PI acos(-1) #define pb push_back #define fi first #define se second #define sz(a) (int)(a).size() #define all(c) (c).begin(), (c).end() #define TIMESTAMP fprintf(stderr, "Execution time: %.3lf s.\n", (double)clock()/CLOCKS_PER_SEC) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<ll> vll; typedef pair <int, int> pii; typedef vector <vi> vvi; typedef vector <pii> vpii; typedef vector <string> vs; const int MAXN = 1e5 + 9; const int MOD = (int)(1e9 + 7); const int INF = 100500; int di[] = {0, 1, 0, -1}; int dj[] = {1, 0, -1, 0}; int n, m; int aa[MAXN]; unordered_set <int> tt[4 * MAXN]; void build(int v, int l, int r) { if(l == r - 1) { tt[v].insert(aa[l]); return; } int m = (l + r) / 2; build(v * 2 + 1, l, m); build(v * 2 + 2, m, r); for(auto x : tt[v * 2 + 1]) tt[v].insert(x); for(auto x : tt[v * 2 + 2]) tt[v].insert(x); } bool query(int v, int l, int r, int ql, int qr, int x) { if(ql >= r || qr <= l) return 0; if(ql <= l && qr >= r) return bool(tt[v].count(x)); int m = (l + r) / 2; bool a = query(v * 2 + 1, l, m, ql, qr, x); bool b = query(v * 2 + 2, m, r, ql, qr, x); return max(a, b); } void input() { cin >> n; for(int i = 0; i < n; i++) cin >> aa[i]; build(0, 0, n); cin >> m; for(int i = 0; i < m; i++) { int l, r, x; cin >> l >> r >> x; cout << query(0, 0, n, l - 1, r, x); } } void solve() { } int main() { ios_base::sync_with_stdio(0); cin.tie(0); #ifdef LOCAL freopen("xxx.in", "r", stdin); freopen("xxx.out", "w", stdout); #else //freopen(TASK".in", "r", stdin); //freopen(TASK".out", "w", stdout); #endif input(); solve(); return 0; }
/** * @cond ___LICENSE___ * * Copyright (c) 2016-2018 Zefiros Software. * * 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. * * @endcond */ #define INSECURE_CURL #include "slacking/slacking.hpp" #include <fstream> int main() { try { auto &slack = slack::create("xxx-xxx"); // where "xxx-xxx" is your Slack API token slack.chat.channel = "#general"; slack.chat.postMessage("Hello there!"); // will send the message "Hello there!" in the channel #general { // You can also use the generic post slack approach. Parameters (except the token) will not be taken into account. // Everything from the Web Slack API is possible here! slack::post( "chat.postMessage", { {"text", "Slacking is awesome!" }, {"channel", "#general" }, {"username", "peach" }, {"icon_emoji", ":princess:" } } ); } { // You can also use the generic post with a a Json approach. auto json = R"({ "text": "Slacking is awesome!", "channel" : "#general", "username": "peach", "icon_emoji": ":princess:" })"_json; slack::post("chat.postMessage", json); } } catch (const std::runtime_error &e) { if (std::string(e.what()) != std::string("curl_easy_perform() failed SSL peer certificate or SSH remote key was not OK")) { throw e; } } return 0; }
//===-- X86RegisterInfo.cpp - X86 Register Information --------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the X86 implementation of the TargetRegisterInfo class. // This file is responsible for the frame pointer elimination optimization // on X86. // //===----------------------------------------------------------------------===// #include "X86RegisterInfo.h" #include "X86FrameLowering.h" #include "X86MachineFunctionInfo.h" #include "X86Subtarget.h" #include "llvm/ADT/BitVector.h" #include "llvm/ADT/STLExtras.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetFrameLowering.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/Type.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; #define GET_REGINFO_TARGET_DESC #include "X86GenRegisterInfo.inc" static cl::opt<bool> EnableBasePointer("x86-use-base-pointer", cl::Hidden, cl::init(true), cl::desc("Enable use of a base pointer for complex stack frames")); X86RegisterInfo::X86RegisterInfo(const Triple &TT) : X86GenRegisterInfo((TT.isArch64Bit() ? X86::RIP : X86::EIP), X86_MC::getDwarfRegFlavour(TT, false), X86_MC::getDwarfRegFlavour(TT, true), (TT.isArch64Bit() ? X86::RIP : X86::EIP)) { X86_MC::initLLVMToSEHAndCVRegMapping(this); // Cache some information. Is64Bit = TT.isArch64Bit(); IsWin64 = Is64Bit && TT.isOSWindows(); // Use a callee-saved register as the base pointer. These registers must // not conflict with any ABI requirements. For example, in 32-bit mode PIC // requires GOT in the EBX register before function calls via PLT GOT pointer. if (Is64Bit) { SlotSize = 8; // This matches the simplified 32-bit pointer code in the data layout // computation. // FIXME: Should use the data layout? bool Use64BitReg = TT.getEnvironment() != Triple::GNUX32; StackPtr = Use64BitReg ? X86::RSP : X86::ESP; FramePtr = Use64BitReg ? X86::RBP : X86::EBP; BasePtr = Use64BitReg ? X86::RBX : X86::EBX; } else { SlotSize = 4; StackPtr = X86::ESP; FramePtr = X86::EBP; BasePtr = X86::ESI; } } bool X86RegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const { // ExecutionDomainFix, BreakFalseDeps and PostRAScheduler require liveness. return true; } int X86RegisterInfo::getSEHRegNum(unsigned i) const { return getEncodingValue(i); } const TargetRegisterClass * X86RegisterInfo::getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const { // The sub_8bit sub-register index is more constrained in 32-bit mode. // It behaves just like the sub_8bit_hi index. if (!Is64Bit && Idx == X86::sub_8bit) Idx = X86::sub_8bit_hi; // Forward to TableGen's default version. return X86GenRegisterInfo::getSubClassWithSubReg(RC, Idx); } const TargetRegisterClass * X86RegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A, const TargetRegisterClass *B, unsigned SubIdx) const { // The sub_8bit sub-register index is more constrained in 32-bit mode. if (!Is64Bit && SubIdx == X86::sub_8bit) { A = X86GenRegisterInfo::getSubClassWithSubReg(A, X86::sub_8bit_hi); if (!A) return nullptr; } return X86GenRegisterInfo::getMatchingSuperRegClass(A, B, SubIdx); } const TargetRegisterClass * X86RegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC, const MachineFunction &MF) const { // Don't allow super-classes of GR8_NOREX. This class is only used after // extracting sub_8bit_hi sub-registers. The H sub-registers cannot be copied // to the full GR8 register class in 64-bit mode, so we cannot allow the // reigster class inflation. // // The GR8_NOREX class is always used in a way that won't be constrained to a // sub-class, so sub-classes like GR8_ABCD_L are allowed to expand to the // full GR8 class. if (RC == &X86::GR8_NOREXRegClass) return RC; const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>(); const TargetRegisterClass *Super = RC; TargetRegisterClass::sc_iterator I = RC->getSuperClasses(); do { switch (Super->getID()) { case X86::FR32RegClassID: case X86::FR64RegClassID: // If AVX-512 isn't supported we should only inflate to these classes. if (!Subtarget.hasAVX512() && getRegSizeInBits(*Super) == getRegSizeInBits(*RC)) return Super; break; case X86::VR128RegClassID: case X86::VR256RegClassID: // If VLX isn't supported we should only inflate to these classes. if (!Subtarget.hasVLX() && getRegSizeInBits(*Super) == getRegSizeInBits(*RC)) return Super; break; case X86::VR128XRegClassID: case X86::VR256XRegClassID: // If VLX isn't support we shouldn't inflate to these classes. if (Subtarget.hasVLX() && getRegSizeInBits(*Super) == getRegSizeInBits(*RC)) return Super; break; case X86::FR32XRegClassID: case X86::FR64XRegClassID: // If AVX-512 isn't support we shouldn't inflate to these classes. if (Subtarget.hasAVX512() && getRegSizeInBits(*Super) == getRegSizeInBits(*RC)) return Super; break; case X86::GR8RegClassID: case X86::GR16RegClassID: case X86::GR32RegClassID: case X86::GR64RegClassID: case X86::RFP32RegClassID: case X86::RFP64RegClassID: case X86::RFP80RegClassID: case X86::VR512_0_15RegClassID: case X86::VR512RegClassID: // Don't return a super-class that would shrink the spill size. // That can happen with the vector and float classes. if (getRegSizeInBits(*Super) == getRegSizeInBits(*RC)) return Super; } Super = *I++; } while (Super); return RC; } const TargetRegisterClass * X86RegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind) const { const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>(); switch (Kind) { default: llvm_unreachable("Unexpected Kind in getPointerRegClass!"); case 0: // Normal GPRs. if (Subtarget.isTarget64BitLP64()) return &X86::GR64RegClass; // If the target is 64bit but we have been told to use 32bit addresses, // we can still use 64-bit register as long as we know the high bits // are zeros. // Reflect that in the returned register class. if (Is64Bit) { // When the target also allows 64-bit frame pointer and we do have a // frame, this is fine to use it for the address accesses as well. const X86FrameLowering *TFI = getFrameLowering(MF); return TFI->hasFP(MF) && TFI->Uses64BitFramePtr ? &X86::LOW32_ADDR_ACCESS_RBPRegClass : &X86::LOW32_ADDR_ACCESSRegClass; } return &X86::GR32RegClass; case 1: // Normal GPRs except the stack pointer (for encoding reasons). if (Subtarget.isTarget64BitLP64()) return &X86::GR64_NOSPRegClass; // NOSP does not contain RIP, so no special case here. return &X86::GR32_NOSPRegClass; case 2: // NOREX GPRs. if (Subtarget.isTarget64BitLP64()) return &X86::GR64_NOREXRegClass; return &X86::GR32_NOREXRegClass; case 3: // NOREX GPRs except the stack pointer (for encoding reasons). if (Subtarget.isTarget64BitLP64()) return &X86::GR64_NOREX_NOSPRegClass; // NOSP does not contain RIP, so no special case here. return &X86::GR32_NOREX_NOSPRegClass; case 4: // Available for tailcall (not callee-saved GPRs). return getGPRsForTailCall(MF); } } bool X86RegisterInfo::shouldRewriteCopySrc(const TargetRegisterClass *DefRC, unsigned DefSubReg, const TargetRegisterClass *SrcRC, unsigned SrcSubReg) const { // Prevent rewriting a copy where the destination size is larger than the // input size. See PR41619. // FIXME: Should this be factored into the base implementation somehow. if (DefRC->hasSuperClassEq(&X86::GR64RegClass) && DefSubReg == 0 && SrcRC->hasSuperClassEq(&X86::GR64RegClass) && SrcSubReg == X86::sub_32bit) return false; return TargetRegisterInfo::shouldRewriteCopySrc(DefRC, DefSubReg, SrcRC, SrcSubReg); } const TargetRegisterClass * X86RegisterInfo::getGPRsForTailCall(const MachineFunction &MF) const { const Function &F = MF.getFunction(); if (IsWin64 || (F.getCallingConv() == CallingConv::Win64)) return &X86::GR64_TCW64RegClass; else if (Is64Bit) return &X86::GR64_TCRegClass; bool hasHipeCC = (F.getCallingConv() == CallingConv::HiPE); if (hasHipeCC) return &X86::GR32RegClass; return &X86::GR32_TCRegClass; } const TargetRegisterClass * X86RegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const { if (RC == &X86::CCRRegClass) { if (Is64Bit) return &X86::GR64RegClass; else return &X86::GR32RegClass; } return RC; } unsigned X86RegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC, MachineFunction &MF) const { const X86FrameLowering *TFI = getFrameLowering(MF); unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0; switch (RC->getID()) { default: return 0; case X86::GR32RegClassID: return 4 - FPDiff; case X86::GR64RegClassID: return 12 - FPDiff; case X86::VR128RegClassID: return Is64Bit ? 10 : 4; case X86::VR64RegClassID: return 4; } } const MCPhysReg * X86RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { assert(MF && "MachineFunction required"); const X86Subtarget &Subtarget = MF->getSubtarget<X86Subtarget>(); const Function &F = MF->getFunction(); bool HasSSE = Subtarget.hasSSE1(); bool HasAVX = Subtarget.hasAVX(); bool HasAVX512 = Subtarget.hasAVX512(); bool CallsEHReturn = MF->callsEHReturn(); CallingConv::ID CC = F.getCallingConv(); // If attribute NoCallerSavedRegisters exists then we set X86_INTR calling // convention because it has the CSR list. if (MF->getFunction().hasFnAttribute("no_caller_saved_registers")) CC = CallingConv::X86_INTR; switch (CC) { case CallingConv::GHC: case CallingConv::HiPE: return CSR_NoRegs_SaveList; case CallingConv::AnyReg: if (HasAVX) return CSR_64_AllRegs_AVX_SaveList; return CSR_64_AllRegs_SaveList; case CallingConv::PreserveMost: return CSR_64_RT_MostRegs_SaveList; case CallingConv::PreserveAll: if (HasAVX) return CSR_64_RT_AllRegs_AVX_SaveList; return CSR_64_RT_AllRegs_SaveList; case CallingConv::CXX_FAST_TLS: if (Is64Bit) return MF->getInfo<X86MachineFunctionInfo>()->isSplitCSR() ? CSR_64_CXX_TLS_Darwin_PE_SaveList : CSR_64_TLS_Darwin_SaveList; break; case CallingConv::Intel_OCL_BI: { if (HasAVX512 && IsWin64) return CSR_Win64_Intel_OCL_BI_AVX512_SaveList; if (HasAVX512 && Is64Bit) return CSR_64_Intel_OCL_BI_AVX512_SaveList; if (HasAVX && IsWin64) return CSR_Win64_Intel_OCL_BI_AVX_SaveList; if (HasAVX && Is64Bit) return CSR_64_Intel_OCL_BI_AVX_SaveList; if (!HasAVX && !IsWin64 && Is64Bit) return CSR_64_Intel_OCL_BI_SaveList; break; } case CallingConv::HHVM: return CSR_64_HHVM_SaveList; case CallingConv::X86_RegCall: if (Is64Bit) { if (IsWin64) { return (HasSSE ? CSR_Win64_RegCall_SaveList : CSR_Win64_RegCall_NoSSE_SaveList); } else { return (HasSSE ? CSR_SysV64_RegCall_SaveList : CSR_SysV64_RegCall_NoSSE_SaveList); } } else { return (HasSSE ? CSR_32_RegCall_SaveList : CSR_32_RegCall_NoSSE_SaveList); } case CallingConv::Cold: if (Is64Bit) return CSR_64_MostRegs_SaveList; break; case CallingConv::Win64: if (!HasSSE) return CSR_Win64_NoSSE_SaveList; return CSR_Win64_SaveList; case CallingConv::X86_64_SysV: if (CallsEHReturn) return CSR_64EHRet_SaveList; return CSR_64_SaveList; case CallingConv::X86_INTR: if (Is64Bit) { if (HasAVX512) return CSR_64_AllRegs_AVX512_SaveList; if (HasAVX) return CSR_64_AllRegs_AVX_SaveList; if (HasSSE) return CSR_64_AllRegs_SaveList; return CSR_64_AllRegs_NoSSE_SaveList; } else { if (HasAVX512) return CSR_32_AllRegs_AVX512_SaveList; if (HasAVX) return CSR_32_AllRegs_AVX_SaveList; if (HasSSE) return CSR_32_AllRegs_SSE_SaveList; return CSR_32_AllRegs_SaveList; } default: break; } if (Is64Bit) { bool IsSwiftCC = Subtarget.getTargetLowering()->supportSwiftError() && F.getAttributes().hasAttrSomewhere(Attribute::SwiftError); if (IsSwiftCC) return IsWin64 ? CSR_Win64_SwiftError_SaveList : CSR_64_SwiftError_SaveList; if (IsWin64) return HasSSE ? CSR_Win64_SaveList : CSR_Win64_NoSSE_SaveList; if (CallsEHReturn) return CSR_64EHRet_SaveList; return CSR_64_SaveList; } return CallsEHReturn ? CSR_32EHRet_SaveList : CSR_32_SaveList; } const MCPhysReg *X86RegisterInfo::getCalleeSavedRegsViaCopy( const MachineFunction *MF) const { assert(MF && "Invalid MachineFunction pointer."); if (MF->getFunction().getCallingConv() == CallingConv::CXX_FAST_TLS && MF->getInfo<X86MachineFunctionInfo>()->isSplitCSR()) return CSR_64_CXX_TLS_Darwin_ViaCopy_SaveList; return nullptr; } const uint32_t * X86RegisterInfo::getCallPreservedMask(const MachineFunction &MF, CallingConv::ID CC) const { const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>(); bool HasSSE = Subtarget.hasSSE1(); bool HasAVX = Subtarget.hasAVX(); bool HasAVX512 = Subtarget.hasAVX512(); switch (CC) { case CallingConv::GHC: case CallingConv::HiPE: return CSR_NoRegs_RegMask; case CallingConv::AnyReg: if (HasAVX) return CSR_64_AllRegs_AVX_RegMask; return CSR_64_AllRegs_RegMask; case CallingConv::PreserveMost: return CSR_64_RT_MostRegs_RegMask; case CallingConv::PreserveAll: if (HasAVX) return CSR_64_RT_AllRegs_AVX_RegMask; return CSR_64_RT_AllRegs_RegMask; case CallingConv::CXX_FAST_TLS: if (Is64Bit) return CSR_64_TLS_Darwin_RegMask; break; case CallingConv::Intel_OCL_BI: { if (HasAVX512 && IsWin64) return CSR_Win64_Intel_OCL_BI_AVX512_RegMask; if (HasAVX512 && Is64Bit) return CSR_64_Intel_OCL_BI_AVX512_RegMask; if (HasAVX && IsWin64) return CSR_Win64_Intel_OCL_BI_AVX_RegMask; if (HasAVX && Is64Bit) return CSR_64_Intel_OCL_BI_AVX_RegMask; if (!HasAVX && !IsWin64 && Is64Bit) return CSR_64_Intel_OCL_BI_RegMask; break; } case CallingConv::HHVM: return CSR_64_HHVM_RegMask; case CallingConv::X86_RegCall: if (Is64Bit) { if (IsWin64) { return (HasSSE ? CSR_Win64_RegCall_RegMask : CSR_Win64_RegCall_NoSSE_RegMask); } else { return (HasSSE ? CSR_SysV64_RegCall_RegMask : CSR_SysV64_RegCall_NoSSE_RegMask); } } else { return (HasSSE ? CSR_32_RegCall_RegMask : CSR_32_RegCall_NoSSE_RegMask); } case CallingConv::Cold: if (Is64Bit) return CSR_64_MostRegs_RegMask; break; case CallingConv::Win64: return CSR_Win64_RegMask; case CallingConv::X86_64_SysV: return CSR_64_RegMask; case CallingConv::X86_INTR: if (Is64Bit) { if (HasAVX512) return CSR_64_AllRegs_AVX512_RegMask; if (HasAVX) return CSR_64_AllRegs_AVX_RegMask; if (HasSSE) return CSR_64_AllRegs_RegMask; return CSR_64_AllRegs_NoSSE_RegMask; } else { if (HasAVX512) return CSR_32_AllRegs_AVX512_RegMask; if (HasAVX) return CSR_32_AllRegs_AVX_RegMask; if (HasSSE) return CSR_32_AllRegs_SSE_RegMask; return CSR_32_AllRegs_RegMask; } default: break; } // Unlike getCalleeSavedRegs(), we don't have MMI so we can't check // callsEHReturn(). if (Is64Bit) { const Function &F = MF.getFunction(); bool IsSwiftCC = Subtarget.getTargetLowering()->supportSwiftError() && F.getAttributes().hasAttrSomewhere(Attribute::SwiftError); if (IsSwiftCC) return IsWin64 ? CSR_Win64_SwiftError_RegMask : CSR_64_SwiftError_RegMask; return IsWin64 ? CSR_Win64_RegMask : CSR_64_RegMask; } return CSR_32_RegMask; } const uint32_t* X86RegisterInfo::getNoPreservedMask() const { return CSR_NoRegs_RegMask; } const uint32_t *X86RegisterInfo::getDarwinTLSCallPreservedMask() const { return CSR_64_TLS_Darwin_RegMask; } BitVector X86RegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); const X86FrameLowering *TFI = getFrameLowering(MF); // Set the floating point control register as reserved. Reserved.set(X86::FPCW); // Set the stack-pointer register and its aliases as reserved. for (MCSubRegIterator I(X86::RSP, this, /*IncludeSelf=*/true); I.isValid(); ++I) Reserved.set(*I); // Set the Shadow Stack Pointer as reserved. Reserved.set(X86::SSP); // Set the instruction pointer register and its aliases as reserved. for (MCSubRegIterator I(X86::RIP, this, /*IncludeSelf=*/true); I.isValid(); ++I) Reserved.set(*I); // Set the frame-pointer register and its aliases as reserved if needed. if (TFI->hasFP(MF)) { for (MCSubRegIterator I(X86::RBP, this, /*IncludeSelf=*/true); I.isValid(); ++I) Reserved.set(*I); } // Set the base-pointer register and its aliases as reserved if needed. if (hasBasePointer(MF)) { CallingConv::ID CC = MF.getFunction().getCallingConv(); const uint32_t *RegMask = getCallPreservedMask(MF, CC); if (MachineOperand::clobbersPhysReg(RegMask, getBaseRegister())) report_fatal_error( "Stack realignment in presence of dynamic allocas is not supported with" "this calling convention."); Register BasePtr = getX86SubSuperRegister(getBaseRegister(), 64); for (MCSubRegIterator I(BasePtr, this, /*IncludeSelf=*/true); I.isValid(); ++I) Reserved.set(*I); } // Mark the segment registers as reserved. Reserved.set(X86::CS); Reserved.set(X86::SS); Reserved.set(X86::DS); Reserved.set(X86::ES); Reserved.set(X86::FS); Reserved.set(X86::GS); // Mark the floating point stack registers as reserved. for (unsigned n = 0; n != 8; ++n) Reserved.set(X86::ST0 + n); // Reserve the registers that only exist in 64-bit mode. if (!Is64Bit) { // These 8-bit registers are part of the x86-64 extension even though their // super-registers are old 32-bits. Reserved.set(X86::SIL); Reserved.set(X86::DIL); Reserved.set(X86::BPL); Reserved.set(X86::SPL); Reserved.set(X86::SIH); Reserved.set(X86::DIH); Reserved.set(X86::BPH); Reserved.set(X86::SPH); for (unsigned n = 0; n != 8; ++n) { // R8, R9, ... for (MCRegAliasIterator AI(X86::R8 + n, this, true); AI.isValid(); ++AI) Reserved.set(*AI); // XMM8, XMM9, ... for (MCRegAliasIterator AI(X86::XMM8 + n, this, true); AI.isValid(); ++AI) Reserved.set(*AI); } } if (!Is64Bit || !MF.getSubtarget<X86Subtarget>().hasAVX512()) { for (unsigned n = 16; n != 32; ++n) { for (MCRegAliasIterator AI(X86::XMM0 + n, this, true); AI.isValid(); ++AI) Reserved.set(*AI); } } assert(checkAllSuperRegsMarked(Reserved, {X86::SIL, X86::DIL, X86::BPL, X86::SPL, X86::SIH, X86::DIH, X86::BPH, X86::SPH})); return Reserved; } void X86RegisterInfo::adjustStackMapLiveOutMask(uint32_t *Mask) const { // Check if the EFLAGS register is marked as live-out. This shouldn't happen, // because the calling convention defines the EFLAGS register as NOT // preserved. // // Unfortunatelly the EFLAGS show up as live-out after branch folding. Adding // an assert to track this and clear the register afterwards to avoid // unnecessary crashes during release builds. assert(!(Mask[X86::EFLAGS / 32] & (1U << (X86::EFLAGS % 32))) && "EFLAGS are not live-out from a patchpoint."); // Also clean other registers that don't need preserving (IP). for (auto Reg : {X86::EFLAGS, X86::RIP, X86::EIP, X86::IP}) Mask[Reg / 32] &= ~(1U << (Reg % 32)); } //===----------------------------------------------------------------------===// // Stack Frame Processing methods //===----------------------------------------------------------------------===// static bool CantUseSP(const MachineFrameInfo &MFI) { return MFI.hasVarSizedObjects() || MFI.hasOpaqueSPAdjustment(); } bool X86RegisterInfo::hasBasePointer(const MachineFunction &MF) const { const MachineFrameInfo &MFI = MF.getFrameInfo(); if (!EnableBasePointer) return false; // When we need stack realignment, we can't address the stack from the frame // pointer. When we have dynamic allocas or stack-adjusting inline asm, we // can't address variables from the stack pointer. MS inline asm can // reference locals while also adjusting the stack pointer. When we can't // use both the SP and the FP, we need a separate base pointer register. bool CantUseFP = needsStackRealignment(MF); return CantUseFP && CantUseSP(MFI); } bool X86RegisterInfo::canRealignStack(const MachineFunction &MF) const { if (!TargetRegisterInfo::canRealignStack(MF)) return false; const MachineFrameInfo &MFI = MF.getFrameInfo(); const MachineRegisterInfo *MRI = &MF.getRegInfo(); // Stack realignment requires a frame pointer. If we already started // register allocation with frame pointer elimination, it is too late now. if (!MRI->canReserveReg(FramePtr)) return false; // If a base pointer is necessary. Check that it isn't too late to reserve // it. if (CantUseSP(MFI)) return MRI->canReserveReg(BasePtr); return true; } bool X86RegisterInfo::hasReservedSpillSlot(const MachineFunction &MF, unsigned Reg, int &FrameIdx) const { // Since X86 defines assignCalleeSavedSpillSlots which always return true // this function neither used nor tested. llvm_unreachable("Unused function on X86. Otherwise need a test case."); } // tryOptimizeLEAtoMOV - helper function that tries to replace a LEA instruction // of the form 'lea (%esp), %ebx' --> 'mov %esp, %ebx'. // TODO: In this case we should be really trying first to entirely eliminate // this instruction which is a plain copy. static bool tryOptimizeLEAtoMOV(MachineBasicBlock::iterator II) { MachineInstr &MI = *II; unsigned Opc = II->getOpcode(); // Check if this is a LEA of the form 'lea (%esp), %ebx' if ((Opc != X86::LEA32r && Opc != X86::LEA64r && Opc != X86::LEA64_32r) || MI.getOperand(2).getImm() != 1 || MI.getOperand(3).getReg() != X86::NoRegister || MI.getOperand(4).getImm() != 0 || MI.getOperand(5).getReg() != X86::NoRegister) return false; Register BasePtr = MI.getOperand(1).getReg(); // In X32 mode, ensure the base-pointer is a 32-bit operand, so the LEA will // be replaced with a 32-bit operand MOV which will zero extend the upper // 32-bits of the super register. if (Opc == X86::LEA64_32r) BasePtr = getX86SubSuperRegister(BasePtr, 32); Register NewDestReg = MI.getOperand(0).getReg(); const X86InstrInfo *TII = MI.getParent()->getParent()->getSubtarget<X86Subtarget>().getInstrInfo(); TII->copyPhysReg(*MI.getParent(), II, MI.getDebugLoc(), NewDestReg, BasePtr, MI.getOperand(1).isKill()); MI.eraseFromParent(); return true; } static bool isFuncletReturnInstr(MachineInstr &MI) { switch (MI.getOpcode()) { case X86::CATCHRET: case X86::CLEANUPRET: return true; default: return false; } llvm_unreachable("impossible"); } void X86RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, unsigned FIOperandNum, RegScavenger *RS) const { MachineInstr &MI = *II; MachineBasicBlock &MBB = *MI.getParent(); MachineFunction &MF = *MBB.getParent(); MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator(); bool IsEHFuncletEpilogue = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI); const X86FrameLowering *TFI = getFrameLowering(MF); int FrameIndex = MI.getOperand(FIOperandNum).getIndex(); // Determine base register and offset. int FIOffset; unsigned BasePtr; if (MI.isReturn()) { assert((!needsStackRealignment(MF) || MF.getFrameInfo().isFixedObjectIndex(FrameIndex)) && "Return instruction can only reference SP relative frame objects"); FIOffset = TFI->getFrameIndexReferenceSP(MF, FrameIndex, BasePtr, 0); } else if (TFI->Is64Bit && (MBB.isEHFuncletEntry() || IsEHFuncletEpilogue)) { FIOffset = TFI->getWin64EHFrameIndexRef(MF, FrameIndex, BasePtr); } else { FIOffset = TFI->getFrameIndexReference(MF, FrameIndex, BasePtr); } // LOCAL_ESCAPE uses a single offset, with no register. It only works in the // simple FP case, and doesn't work with stack realignment. On 32-bit, the // offset is from the traditional base pointer location. On 64-bit, the // offset is from the SP at the end of the prologue, not the FP location. This // matches the behavior of llvm.frameaddress. unsigned Opc = MI.getOpcode(); if (Opc == TargetOpcode::LOCAL_ESCAPE) { MachineOperand &FI = MI.getOperand(FIOperandNum); FI.ChangeToImmediate(FIOffset); return; } // For LEA64_32r when BasePtr is 32-bits (X32) we can use full-size 64-bit // register as source operand, semantic is the same and destination is // 32-bits. It saves one byte per lea in code since 0x67 prefix is avoided. // Don't change BasePtr since it is used later for stack adjustment. Register MachineBasePtr = BasePtr; if (Opc == X86::LEA64_32r && X86::GR32RegClass.contains(BasePtr)) MachineBasePtr = getX86SubSuperRegister(BasePtr, 64); // This must be part of a four operand memory reference. Replace the // FrameIndex with base register. Add an offset to the offset. MI.getOperand(FIOperandNum).ChangeToRegister(MachineBasePtr, false); if (BasePtr == StackPtr) FIOffset += SPAdj; // The frame index format for stackmaps and patchpoints is different from the // X86 format. It only has a FI and an offset. if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) { assert(BasePtr == FramePtr && "Expected the FP as base register"); int64_t Offset = MI.getOperand(FIOperandNum + 1).getImm() + FIOffset; MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); return; } if (MI.getOperand(FIOperandNum+3).isImm()) { // Offset is a 32-bit integer. int Imm = (int)(MI.getOperand(FIOperandNum + 3).getImm()); int Offset = FIOffset + Imm; assert((!Is64Bit || isInt<32>((long long)FIOffset + Imm)) && "Requesting 64-bit offset in 32-bit immediate!"); if (Offset != 0 || !tryOptimizeLEAtoMOV(II)) MI.getOperand(FIOperandNum + 3).ChangeToImmediate(Offset); } else { // Offset is symbolic. This is extremely rare. uint64_t Offset = FIOffset + (uint64_t)MI.getOperand(FIOperandNum+3).getOffset(); MI.getOperand(FIOperandNum + 3).setOffset(Offset); } } Register X86RegisterInfo::getFrameRegister(const MachineFunction &MF) const { const X86FrameLowering *TFI = getFrameLowering(MF); return TFI->hasFP(MF) ? FramePtr : StackPtr; } unsigned X86RegisterInfo::getPtrSizedFrameRegister(const MachineFunction &MF) const { const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>(); Register FrameReg = getFrameRegister(MF); if (Subtarget.isTarget64BitILP32()) FrameReg = getX86SubSuperRegister(FrameReg, 32); return FrameReg; } unsigned X86RegisterInfo::getPtrSizedStackRegister(const MachineFunction &MF) const { const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>(); Register StackReg = getStackRegister(); if (Subtarget.isTarget64BitILP32()) StackReg = getX86SubSuperRegister(StackReg, 32); return StackReg; }
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/cryptauth/fake_authenticator.h" #include <utility> namespace cryptauth { FakeAuthenticator::FakeAuthenticator() {} FakeAuthenticator::~FakeAuthenticator() {} void FakeAuthenticator::Authenticate( const Authenticator::AuthenticationCallback& callback) { last_callback_ = callback; } } // namespace cryptauth
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrDrawPathBatch.h" static void pre_translate_transform_values(const float* xforms, GrPathRendering::PathTransformType type, int count, SkScalar x, SkScalar y, float* dst); SkString GrDrawPathBatch::dumpInfo() const { SkString string; string.printf("PATH: 0x%p", fPath.get()); return string; } void GrDrawPathBatch::onDraw(GrBatchFlushState* state) { GrProgramDesc desc; SkAutoTUnref<GrPathProcessor> pathProc(GrPathProcessor::Create(this->color(), this->overrides(), this->viewMatrix())); state->gpu()->buildProgramDesc(&desc, *pathProc, *this->pipeline()); GrPathRendering::DrawPathArgs args(pathProc, this->pipeline(), &desc, &this->stencilSettings()); state->gpu()->pathRendering()->drawPath(args, fPath.get()); } SkString GrDrawPathRangeBatch::dumpInfo() const { SkString string; string.printf("RANGE: 0x%p COUNTS: [", fPathRange.get()); for (DrawList::Iter iter(fDraws); iter.get(); iter.next()) { string.appendf("%d, ", iter.get()->fInstanceData->count()); } string.remove(string.size() - 2, 2); string.append("]"); return string; } GrDrawPathRangeBatch::GrDrawPathRangeBatch(const SkMatrix& viewMatrix, SkScalar scale, SkScalar x, SkScalar y, GrColor color, GrPathRendering::FillType fill, GrPathRange* range, const InstanceData* instanceData, const SkRect& bounds) : INHERITED(ClassID(), viewMatrix, color, fill) , fPathRange(range) , fTotalPathCount(instanceData->count()) , fScale(scale) { fDraws.addToHead()->set(instanceData, x, y); fBounds = bounds; } bool GrDrawPathRangeBatch::onCombineIfPossible(GrBatch* t, const GrCaps& caps) { GrDrawPathRangeBatch* that = t->cast<GrDrawPathRangeBatch>(); if (this->fPathRange.get() != that->fPathRange.get() || this->transformType() != that->transformType() || this->fScale != that->fScale || this->color() != that->color() || !this->viewMatrix().cheapEqualTo(that->viewMatrix())) { return false; } if (!GrPipeline::AreEqual(*this->pipeline(), *that->pipeline(), false)) { return false; } switch (fDraws.head()->fInstanceData->transformType()) { case GrPathRendering::kNone_PathTransformType: if (this->fDraws.head()->fX != that->fDraws.head()->fX || this->fDraws.head()->fY != that->fDraws.head()->fY) { return false; } break; case GrPathRendering::kTranslateX_PathTransformType: if (this->fDraws.head()->fY != that->fDraws.head()->fY) { return false; } break; case GrPathRendering::kTranslateY_PathTransformType: if (this->fDraws.head()->fX != that->fDraws.head()->fX) { return false; } break; default: break; } // TODO: Check some other things here. (winding, opaque, pathProc color, vm, ...) // Try to combine this call with the previous DrawPaths. We do this by stenciling all the // paths together and then covering them in a single pass. This is not equivalent to two // separate draw calls, so we can only do it if there is no blending (no overlap would also // work). Note that it's also possible for overlapping paths to cancel each other's winding // numbers, and we only partially account for this by not allowing even/odd paths to be // combined. (Glyphs in the same font tend to wind the same direction so it works out OK.) if (GrPathRendering::kWinding_FillType != this->fillType() || this->stencilSettings() != that->stencilSettings() || this->overrides().willColorBlendWithDst()) { return false; } SkASSERT(!that->overrides().willColorBlendWithDst()); fTotalPathCount += that->fTotalPathCount; while (Draw* head = that->fDraws.head()) { Draw* draw = fDraws.addToTail(); draw->fInstanceData.reset(head->fInstanceData.detach()); draw->fX = head->fX; draw->fY = head->fY; that->fDraws.popHead(); } return true; } void GrDrawPathRangeBatch::onDraw(GrBatchFlushState* state) { const Draw& head = *fDraws.head(); SkMatrix drawMatrix(this->viewMatrix()); drawMatrix.preScale(fScale, fScale); drawMatrix.preTranslate(head.fX, head.fY); SkMatrix localMatrix; localMatrix.setScale(fScale, fScale); localMatrix.preTranslate(head.fX, head.fY); SkAutoTUnref<GrPathProcessor> pathProc(GrPathProcessor::Create(this->color(), this->overrides(), drawMatrix, localMatrix)); GrProgramDesc desc; state->gpu()->buildProgramDesc(&desc, *pathProc, *this->pipeline()); GrPathRendering::DrawPathArgs args(pathProc, this->pipeline(), &desc, &this->stencilSettings()); if (fDraws.count() == 1) { const InstanceData& instances = *head.fInstanceData; state->gpu()->pathRendering()->drawPaths(args, fPathRange.get(), instances.indices(), GrPathRange::kU16_PathIndexType, instances.transformValues(), instances.transformType(), instances.count()); } else { int floatsPerTransform = GrPathRendering::PathTransformSize(this->transformType()); #if defined(GOOGLE3) //Stack frame size is limited in GOOGLE3. SkAutoSTMalloc<512, float> transformStorage(floatsPerTransform * fTotalPathCount); SkAutoSTMalloc<256, uint16_t> indexStorage(fTotalPathCount); #else SkAutoSTMalloc<4096, float> transformStorage(floatsPerTransform * fTotalPathCount); SkAutoSTMalloc<2048, uint16_t> indexStorage(fTotalPathCount); #endif int idx = 0; for (DrawList::Iter iter(fDraws); iter.get(); iter.next()) { const Draw& draw = *iter.get(); const InstanceData& instances = *draw.fInstanceData; memcpy(&indexStorage[idx], instances.indices(), instances.count() * sizeof(uint16_t)); pre_translate_transform_values(instances.transformValues(), this->transformType(), instances.count(), draw.fX - head.fX, draw.fY - head.fY, &transformStorage[floatsPerTransform * idx]); idx += instances.count(); // TODO: Support mismatched transform types if we start using more types other than 2D. SkASSERT(instances.transformType() == this->transformType()); } SkASSERT(idx == fTotalPathCount); state->gpu()->pathRendering()->drawPaths(args, fPathRange.get(), indexStorage, GrPathRange::kU16_PathIndexType, transformStorage, this->transformType(), fTotalPathCount); } } inline void pre_translate_transform_values(const float* xforms, GrPathRendering::PathTransformType type, int count, SkScalar x, SkScalar y, float* dst) { if (0 == x && 0 == y) { memcpy(dst, xforms, count * GrPathRendering::PathTransformSize(type) * sizeof(float)); return; } switch (type) { case GrPathRendering::kNone_PathTransformType: SkFAIL("Cannot pre-translate kNone_PathTransformType."); break; case GrPathRendering::kTranslateX_PathTransformType: SkASSERT(0 == y); for (int i = 0; i < count; i++) { dst[i] = xforms[i] + x; } break; case GrPathRendering::kTranslateY_PathTransformType: SkASSERT(0 == x); for (int i = 0; i < count; i++) { dst[i] = xforms[i] + y; } break; case GrPathRendering::kTranslate_PathTransformType: for (int i = 0; i < 2 * count; i += 2) { dst[i] = xforms[i] + x; dst[i + 1] = xforms[i + 1] + y; } break; case GrPathRendering::kAffine_PathTransformType: for (int i = 0; i < 6 * count; i += 6) { dst[i] = xforms[i]; dst[i + 1] = xforms[i + 1]; dst[i + 2] = xforms[i] * x + xforms[i + 1] * y + xforms[i + 2]; dst[i + 3] = xforms[i + 3]; dst[i + 4] = xforms[i + 4]; dst[i + 5] = xforms[i + 3] * x + xforms[i + 4] * y + xforms[i + 5]; } break; default: SkFAIL("Unknown transform type."); break; } }
#include "CondCore/Utilities/interface/PayloadInspectorModule.h" #include "CondCore/Utilities/interface/PayloadInspector.h" #include "CondCore/CondDB/interface/Time.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "CondCore/EcalPlugins/plugins/EcalDrawUtils.h" // the data format of the condition to be inspected #include "CondFormats/EcalObjects/interface/EcalDCUTemperatures.h" #include "TH2F.h" // a 2-D histogram with four bytes per cell (float) #include "TCanvas.h" #include "TLine.h" #include "TStyle.h" #include "TLatex.h" //write mathematical equations. #include "TPave.h" #include "TPaveStats.h" #include <string> #include <fstream> namespace { /******************************************************* 2d plot of Ecal DCU Temperatures of 1 IOV *******************************************************/ class EcalDCUTemperaturesPlot : public cond::payloadInspector::PlotImage<EcalDCUTemperatures> { public: EcalDCUTemperaturesPlot() : cond::payloadInspector::PlotImage<EcalDCUTemperatures>("Ecal DCU Temperatures - map ") { setSingleIov(true); } bool fill(const std::vector<std::tuple<cond::Time_t, cond::Hash> >& iovs) override { auto iov = iovs.front(); std::shared_ptr<EcalDCUTemperatures> payload = fetchPayload(std::get<1>(iov)); unsigned int run = std::get<0>(iov); TH2F* align; int NbRows; if (payload.get()) { EcalDCUTemperatures::EcalDCUTemperatureMap map = (*payload).getMap(); NbRows = map.size(); align = new TH2F("Ecal DCU Temperatures", "Key DCUTemperature", 2, 0, 2, NbRows, 0, NbRows); double row = NbRows - 0.5; for (EcalDCUTemperatures::EcalDCUTemperatureMap::const_iterator it = map.begin(); it != map.end(); it++) { uint32_t mapKey = it->first; float val = it->second; align->Fill(0.5, row, mapKey); align->Fill(1.5, row, val); row--; } } else return false; gStyle->SetPalette(1); gStyle->SetOptStat(0); TCanvas canvas("CC map", "CC map", 1000, 1000); TLatex t1; t1.SetNDC(); t1.SetTextAlign(26); t1.SetTextSize(0.05); t1.SetTextColor(2); t1.DrawLatex(0.5, 0.96, Form("Ecal DCU Temperatures, IOV %i", run)); TPad* pad = new TPad("pad", "pad", 0.0, 0.0, 1.0, 0.94); pad->Draw(); pad->cd(); align->Draw("TEXT"); drawTable(NbRows, 2); align->GetXaxis()->SetTickLength(0.); align->GetXaxis()->SetLabelSize(0.); align->GetYaxis()->SetTickLength(0.); align->GetYaxis()->SetLabelSize(0.); std::string ImageName(m_imageFileName); canvas.SaveAs(ImageName.c_str()); return true; } }; } // namespace // Register the classes as boost python plugin PAYLOAD_INSPECTOR_MODULE(EcalDCUTemperatures) { PAYLOAD_INSPECTOR_CLASS(EcalDCUTemperaturesPlot); }
/****************************************************************** * * Copyright 2015 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #include "request_model_builder.h" #include "resource_model_schema_builder.h" #include "logger.h" #include "Raml.h" #define TAG "REQ_MODEL_BUILDER" static std::string getRequestType(RAML::ActionType actionType) { switch (actionType) { case RAML::ActionType::GET: return "GET"; case RAML::ActionType::PUT: return "PUT"; case RAML::ActionType::POST: return "POST"; case RAML::ActionType::DELETE: return "DELETE"; } return ""; // This code should never reach } std::unordered_map<std::string, RequestModelSP> RequestModelBuilder::build( const std::shared_ptr<RAML::Raml> &raml, const std::string &uri) { std::unordered_map<std::string, RequestModelSP> requestModels; if (!raml) { OIC_LOG(ERROR, TAG, "Raml pointer is null!"); return requestModels; } for (auto &resource : raml->getResources()) { // Pick the resource based on the resource uri. if (std::string::npos == uri.find((resource.second)->getResourceUri())) continue; // Construct Request and Response Model from RAML::Action for (auto &action : (resource.second)->getActions()) { RequestModelSP requestModel = createRequestModel(action.second); if (requestModel) { requestModels[requestModel->getType()] = requestModel; } } break; } return requestModels; } std::unordered_map<std::string, RequestModelSP> RequestModelBuilder::build( const std::shared_ptr<RAML::RamlResource> &resource) { std::unordered_map<std::string, RequestModelSP> requestModels; if (!resource) { OIC_LOG(ERROR, TAG, "Resource pointer is null!"); return requestModels; } // Construct Request and Response Model from RAML::Action for (auto &action : resource->getActions()) { RequestModelSP requestModel = createRequestModel(action.second); if (requestModel) { requestModels[requestModel->getType()] = requestModel; } } return requestModels; } RequestModelSP RequestModelBuilder::createRequestModel(const RAML::ActionPtr &action) { // Validate the action type. Only GET, PUT, POST and DELETE are supported. RAML::ActionType actionType = action->getType(); if (actionType != RAML::ActionType::GET && actionType != RAML::ActionType::PUT && actionType != RAML::ActionType::POST && actionType != RAML::ActionType::DELETE) { OIC_LOG(ERROR, TAG, "Request model is of unknown type!"); return nullptr; } RequestModelSP requestModel(new RequestModel(getRequestType(actionType))); // Get the allowed query parameters of the request for (auto &qpEntry : action->getQueryParameters()) { for (auto &value : (qpEntry.second)->getEnumeration()) { requestModel->addQueryParam(qpEntry.first, value); } } // Set the request body schema RAML::RequestResponseBodyPtr requestBody = action->getRequestBody("application/json"); requestModel->setRequestBodyModel(createRepSchema(requestBody)); // Corresponsing responses for this request for (auto &responseEntry : action->getResponses()) { std::string codeStr = responseEntry.first; int code = boost::lexical_cast<int>(codeStr); ResponseModelSP responseModel = createResponseModel(code, responseEntry.second); if (nullptr != responseModel) { requestModel->setResponseModel(code, responseModel); } } return requestModel; } ResponseModelSP RequestModelBuilder::createResponseModel(int code, const RAML::ResponsePtr &response) { ResponseModelSP responseModel(new ResponseModel(code)); RAML::RequestResponseBodyPtr responseBody = response->getResponseBody("application/json"); responseModel->setResponseBodyModel(createRepSchema(responseBody)); return responseModel; } std::shared_ptr<SimulatorResourceModelSchema> RequestModelBuilder::createRepSchema( const RAML::RequestResponseBodyPtr &responseBody) { if (!responseBody) { OIC_LOG(ERROR, TAG, "Response body is null!"); return nullptr; } return ResourceModelSchemaBuilder(responseBody).build(); }
/* $Id: RemoteUSBBackend.cpp $ */ /** @file * * VirtualBox Remote USB backend */ /* * Copyright (C) 2006-2014 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #define LOG_GROUP LOG_GROUP_USB_REMOTE #include "ConsoleImpl.h" #include "ConsoleVRDPServer.h" #include "RemoteUSBBackend.h" #include "RemoteUSBDeviceImpl.h" #include <VBox/RemoteDesktop/VRDE.h> #include <VBox/vrdpusb.h> #include <VBox/err.h> #include <VBox/log.h> #include <VBox/vusb.h> #include <iprt/time.h> /** @page pg_vrdb_usb Async Remote USB * * * USB backend functions are called in EMT so care must be taken to prevent * delays in the functions execution. * * Among 11 backend functions 10 just return a success indicator. * * Such a function usually will check pending error code and if everything is ok, * submit asynchronous RDP request and return success immediately. * * On actual completion of each request, the status will be saved as * pending, so in case of an error all further functions will fail with * device disconnected condition. * @todo May be a device disconnect notification for console is required? * * The only remaining function that needs special processing is * the reap_urb. It has a timeout parameter. * Normally, the timeout is 0, as result of polling from VUSB frame timer. * It is ok for async processing, the backend will periodically reap urbs from client. * And already reaped URBs from client will be returned for the call. * Exceptions: * 1) during device initialization, when obtaining device descriptions * the timeout is -1, and the request is expected to be processed synchronously. * It looks like only 3 URBs with some information are retrieved that way. * Probably, one can return this information in DEVICE_LIST together with the * device description and when such request are submitted, just return * the prefetched data. * 2) during suspend timeout is non zero (10 or less milliseconds), * and URB's are reaped for about 1 second. But here network delays * will not affect the timeout, so it is ok. * * * @subsection sub_vrdb_usb_dad Device attaching/detaching * * Devices are attached when client is connected or when a new device is connected to client. * Devices are detached when client is disconnected (all devices) or a device is disconnected * the client side. * * The backend polls the client for list of attached USB devices from RemoteUSBThread. * */ /* Queued URB submitted to VRDP client. */ typedef struct _REMOTEUSBQURB { struct _REMOTEUSBQURB *next; struct _REMOTEUSBQURB *prev; PREMOTEUSBDEVICE pDevice; /* Device, the URB is queued for. */ uint32_t u32Handle; /* The handle of the URB. Generated by the Remote USB backend. */ void *pvData; /* Pointer to URB data allocated by VUSB. */ void *pvURB; /* Pointer to URB known to VUSB. */ uint32_t u32Len; /* Data length returned by the VRDP client. */ uint32_t u32Err; /* URB error code returned by the VRDP client. */ bool fCompleted; /* The URB has been returned back by VRDP client. */ bool fInput; /* This URB receives data from the client. */ uint32_t u32TransferredLen; /* For VRDE_USB_DIRECTION_OUT URBs = bytes written. * For VRDE_USB_DIRECTION_IN URBs = bytes received. */ } REMOTEUSBQURB; /* Remote USB device instance data. */ typedef struct _REMOTEUSBDEVICE { struct _REMOTEUSBDEVICE *prev; struct _REMOTEUSBDEVICE *next; RemoteUSBBackend *pOwner; VRDEUSBDEVID id; /* The remote identifier, assigned by client. */ uint32_t u32ClientId; /* The identifier of the remote client. */ REMOTEUSBQURB *pHeadQURBs; /* List of URBs queued for the device. */ REMOTEUSBQURB *pTailQURBs; volatile uint32_t hURB; /* Source for URB's handles. */ bool fFailed; /* True if an operation has failed for the device. */ RTCRITSECT critsect; /* Protects the queued urb list. */ volatile bool fWokenUp; /* Flag whther the reaper was woken up. */ } REMOTEUSBDEVICE; static void requestDevice(REMOTEUSBDEVICE *pDevice) { int rc = RTCritSectEnter(&pDevice->critsect); AssertRC(rc); } static void releaseDevice(REMOTEUSBDEVICE *pDevice) { RTCritSectLeave(&pDevice->critsect); } static REMOTEUSBQURB *qurbAlloc(PREMOTEUSBDEVICE pDevice) { /* @todo reuse URBs. */ REMOTEUSBQURB *pQURB = (REMOTEUSBQURB *)RTMemAllocZ (sizeof (REMOTEUSBQURB)); if (pQURB) { pQURB->pDevice = pDevice; } return pQURB; } static void qurbFree (REMOTEUSBQURB *pQURB) { RTMemFree (pQURB); return; } /* Called by VRDP server when the client responds to a request on USB channel. */ DECLCALLBACK(int) USBClientResponseCallback(void *pv, uint32_t u32ClientId, uint8_t code, const void *pvRet, uint32_t cbRet) { int rc = VINF_SUCCESS; LogFlow(("USBClientResponseCallback: id = %d, pv = %p, code = %d, pvRet = %p, cbRet = %d\n", u32ClientId, pv, code, pvRet, cbRet)); RemoteUSBBackend *pThis = (RemoteUSBBackend *)pv; switch (code) { case VRDE_USB_REQ_DEVICE_LIST: { rc = pThis->saveDeviceList(pvRet, cbRet); } break; case VRDE_USB_REQ_NEGOTIATE: { if (pvRet && cbRet >= sizeof(VRDEUSBREQNEGOTIATERET)) { VRDEUSBREQNEGOTIATERET *pret = (VRDEUSBREQNEGOTIATERET *)pvRet; rc = pThis->negotiateResponse(pret, cbRet); } else { Log(("USBClientResponseCallback: WARNING: not enough data in response: pv = %p, cb = %d, expected %d.\n", pvRet, cbRet, sizeof(VRDEUSBREQNEGOTIATERET))); rc = VERR_INVALID_PARAMETER; } } break; case VRDE_USB_REQ_REAP_URB: { rc = pThis->reapURB(pvRet, cbRet); LogFlow(("USBClientResponseCallback: reap URB, rc = %Rrc.\n", rc)); } break; case VRDE_USB_REQ_QUEUE_URB: case VRDE_USB_REQ_CLOSE: case VRDE_USB_REQ_CANCEL_URB: { /* Do nothing, actually this should not happen. */ Log(("USBClientResponseCallback: WARNING: response to a request %d is not expected!!!\n", code)); } break; case VRDE_USB_REQ_OPEN: case VRDE_USB_REQ_RESET: case VRDE_USB_REQ_SET_CONFIG: case VRDE_USB_REQ_CLAIM_INTERFACE: case VRDE_USB_REQ_RELEASE_INTERFACE: case VRDE_USB_REQ_INTERFACE_SETTING: case VRDE_USB_REQ_CLEAR_HALTED_EP: { /* * Device specific responses with status codes. */ if (pvRet && cbRet >= sizeof(VRDEUSBREQRETHDR)) { VRDEUSBREQRETHDR *pret = (VRDEUSBREQRETHDR *)pvRet; if (pret->status != VRDE_USB_STATUS_SUCCESS) { REMOTEUSBDEVICE *pDevice = pThis->deviceFromId(pret->id); if (!pDevice) { Log(("USBClientResponseCallback: WARNING: invalid device id %08X.\n", pret->id)); rc = VERR_INVALID_PARAMETER; } else { Log(("USBClientResponseCallback: WARNING: the operation failed, status %d\n", pret->status)); pDevice->fFailed = true; } } } else { Log(("USBClientResponseCallback: WARNING: not enough data in response: pv = %p, cb = %d, expected %d.\n", pvRet, cbRet, sizeof(VRDEUSBREQRETHDR))); } } break; default: { Log(("USBClientResponseCallback: WARNING: invalid code %d\n", code)); } break; } return rc; } /* * Backend entry points. */ static DECLCALLBACK(int) iface_Open(PREMOTEUSBBACKEND pInstance, const char *pszAddress, size_t cbAddress, PREMOTEUSBDEVICE *ppDevice) { int rc = VINF_SUCCESS; RemoteUSBBackend *pThis = (RemoteUSBBackend *)pInstance; REMOTEUSBDEVICE *pDevice = (REMOTEUSBDEVICE *)RTMemAllocZ(sizeof(REMOTEUSBDEVICE)); if (!pDevice) { rc = VERR_NO_MEMORY; } else { /* Parse given address string to find the device identifier. * The format is "REMOTEUSB0xAAAABBBB&0xCCCCDDDD", where AAAABBBB is hex device identifier * and CCCCDDDD is hex client id. */ if (strncmp(pszAddress, REMOTE_USB_BACKEND_PREFIX_S, REMOTE_USB_BACKEND_PREFIX_LEN) != 0) { AssertFailed(); rc = VERR_INVALID_PARAMETER; } else { /* Initialize the device structure. */ pDevice->pOwner = pThis; pDevice->fWokenUp = false; rc = RTCritSectInit(&pDevice->critsect); AssertRC(rc); if (RT_SUCCESS(rc)) { pDevice->id = RTStrToUInt32(&pszAddress[REMOTE_USB_BACKEND_PREFIX_LEN]); size_t l = strlen(pszAddress); if (l >= REMOTE_USB_BACKEND_PREFIX_LEN + strlen("0x12345678&0x87654321")) { const char *p = &pszAddress[REMOTE_USB_BACKEND_PREFIX_LEN + strlen("0x12345678")]; if (*p == '&') { pDevice->u32ClientId = RTStrToUInt32(p + 1); } else { AssertFailed(); rc = VERR_INVALID_PARAMETER; } } else { AssertFailed(); rc = VERR_INVALID_PARAMETER; } if (RT_SUCCESS(rc)) { VRDE_USB_REQ_OPEN_PARM parm; parm.code = VRDE_USB_REQ_OPEN; parm.id = pDevice->id; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); } } } } if (RT_SUCCESS(rc)) { *ppDevice = pDevice; pThis->addDevice(pDevice); } else { RTMemFree(pDevice); } return rc; } static DECLCALLBACK(void) iface_Close(PREMOTEUSBDEVICE pDevice) { RemoteUSBBackend *pThis = pDevice->pOwner; VRDE_USB_REQ_CLOSE_PARM parm; parm.code = VRDE_USB_REQ_CLOSE; parm.id = pDevice->id; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); pThis->removeDevice(pDevice); if (RTCritSectIsInitialized(&pDevice->critsect)) { RTCritSectDelete(&pDevice->critsect); } RTMemFree(pDevice); return; } static DECLCALLBACK(int) iface_Reset(PREMOTEUSBDEVICE pDevice) { RemoteUSBBackend *pThis = pDevice->pOwner; if (pDevice->fFailed) { return VERR_VUSB_DEVICE_NOT_ATTACHED; } VRDE_USB_REQ_RESET_PARM parm; parm.code = VRDE_USB_REQ_RESET; parm.id = pDevice->id; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); return VINF_SUCCESS; } static DECLCALLBACK(int) iface_SetConfig(PREMOTEUSBDEVICE pDevice, uint8_t u8Cfg) { RemoteUSBBackend *pThis = pDevice->pOwner; if (pDevice->fFailed) { return VERR_VUSB_DEVICE_NOT_ATTACHED; } VRDE_USB_REQ_SET_CONFIG_PARM parm; parm.code = VRDE_USB_REQ_SET_CONFIG; parm.id = pDevice->id; parm.configuration = u8Cfg; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); return VINF_SUCCESS; } static DECLCALLBACK(int) iface_ClaimInterface(PREMOTEUSBDEVICE pDevice, uint8_t u8Ifnum) { RemoteUSBBackend *pThis = pDevice->pOwner; if (pDevice->fFailed) { return VERR_VUSB_DEVICE_NOT_ATTACHED; } VRDE_USB_REQ_CLAIM_INTERFACE_PARM parm; parm.code = VRDE_USB_REQ_CLAIM_INTERFACE; parm.id = pDevice->id; parm.iface = u8Ifnum; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); return VINF_SUCCESS; } static DECLCALLBACK(int) iface_ReleaseInterface(PREMOTEUSBDEVICE pDevice, uint8_t u8Ifnum) { RemoteUSBBackend *pThis = pDevice->pOwner; if (pDevice->fFailed) { return VERR_VUSB_DEVICE_NOT_ATTACHED; } VRDE_USB_REQ_RELEASE_INTERFACE_PARM parm; parm.code = VRDE_USB_REQ_RELEASE_INTERFACE; parm.id = pDevice->id; parm.iface = u8Ifnum; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); return VINF_SUCCESS; } static DECLCALLBACK(int) iface_InterfaceSetting(PREMOTEUSBDEVICE pDevice, uint8_t u8Ifnum, uint8_t u8Setting) { RemoteUSBBackend *pThis = pDevice->pOwner; if (pDevice->fFailed) { return VERR_VUSB_DEVICE_NOT_ATTACHED; } VRDE_USB_REQ_INTERFACE_SETTING_PARM parm; parm.code = VRDE_USB_REQ_INTERFACE_SETTING; parm.id = pDevice->id; parm.iface = u8Ifnum; parm.setting = u8Setting; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); return VINF_SUCCESS; } static DECLCALLBACK(int) iface_ClearHaltedEP(PREMOTEUSBDEVICE pDevice, uint8_t u8Ep) { RemoteUSBBackend *pThis = pDevice->pOwner; if (pDevice->fFailed) { return VERR_VUSB_DEVICE_NOT_ATTACHED; } VRDE_USB_REQ_CLEAR_HALTED_EP_PARM parm; parm.code = VRDE_USB_REQ_CLEAR_HALTED_EP; parm.id = pDevice->id; parm.ep = u8Ep; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); return VINF_SUCCESS; } static DECLCALLBACK(void) iface_CancelURB(PREMOTEUSBDEVICE pDevice, PREMOTEUSBQURB pRemoteURB) { RemoteUSBBackend *pThis = pDevice->pOwner; VRDE_USB_REQ_CANCEL_URB_PARM parm; parm.code = VRDE_USB_REQ_CANCEL_URB; parm.id = pDevice->id; parm.handle = pRemoteURB->u32Handle; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); requestDevice(pDevice); /* Remove this urb from the queue. It is safe because if * client will return the URB, it will be just ignored * in reapURB. */ if (pRemoteURB->prev) { pRemoteURB->prev->next = pRemoteURB->next; } else { pDevice->pHeadQURBs = pRemoteURB->next; } if (pRemoteURB->next) { pRemoteURB->next->prev = pRemoteURB->prev; } else { pDevice->pTailQURBs = pRemoteURB->prev; } qurbFree(pRemoteURB); releaseDevice(pDevice); return; } static DECLCALLBACK(int) iface_QueueURB(PREMOTEUSBDEVICE pDevice, uint8_t u8Type, uint8_t u8Ep, uint8_t u8Direction, uint32_t u32Len, void *pvData, void *pvURB, PREMOTEUSBQURB *ppRemoteURB) { int rc = VINF_SUCCESS; #ifdef DEBUG_sunlover LogFlow(("RemoteUSBBackend::iface_QueueURB: u8Type = %d, u8Ep = %d, u8Direction = %d, data\n%.*Rhxd\n", u8Type, u8Ep, u8Direction, u32Len, pvData)); #endif /* DEBUG_sunlover */ if (pDevice->fFailed) { return VERR_VUSB_DEVICE_NOT_ATTACHED; } RemoteUSBBackend *pThis = pDevice->pOwner; VRDE_USB_REQ_QUEUE_URB_PARM parm; uint32_t u32Handle = 0; uint32_t u32DataLen = 0; REMOTEUSBQURB *qurb = qurbAlloc(pDevice); if (qurb == NULL) { rc = VERR_NO_MEMORY; goto l_leave; } /* * Compute length of data which need to be transferred to the client. */ switch(u8Direction) { case VUSB_DIRECTION_IN: { if (u8Type == VUSBXFERTYPE_MSG) { u32DataLen = 8; /* 8 byte header. */ // u32DataLen = u32Len; // @todo do messages need all information? } } break; case VUSB_DIRECTION_OUT: { u32DataLen = u32Len; } break; default: { AssertFailed(); rc = VERR_INVALID_PARAMETER; goto l_leave; } } parm.code = VRDE_USB_REQ_QUEUE_URB; parm.id = pDevice->id; u32Handle = pDevice->hURB++; if (u32Handle == 0) { u32Handle = pDevice->hURB++; } LogFlow(("RemoteUSBBackend::iface_QueueURB: handle = %d\n", u32Handle)); parm.handle = u32Handle; switch(u8Type) { case VUSBXFERTYPE_CTRL: parm.type = VRDE_USB_TRANSFER_TYPE_CTRL; break; case VUSBXFERTYPE_ISOC: parm.type = VRDE_USB_TRANSFER_TYPE_ISOC; break; case VUSBXFERTYPE_BULK: parm.type = VRDE_USB_TRANSFER_TYPE_BULK; break; case VUSBXFERTYPE_INTR: parm.type = VRDE_USB_TRANSFER_TYPE_INTR; break; case VUSBXFERTYPE_MSG: parm.type = VRDE_USB_TRANSFER_TYPE_MSG; break; default: AssertFailed(); rc = VERR_INVALID_PARAMETER; goto l_leave; } parm.ep = u8Ep; switch(u8Direction) { case VUSB_DIRECTION_SETUP: AssertFailed(); parm.direction = VRDE_USB_DIRECTION_SETUP; break; case VUSB_DIRECTION_IN: parm.direction = VRDE_USB_DIRECTION_IN; break; case VUSB_DIRECTION_OUT: parm.direction = VRDE_USB_DIRECTION_OUT; break; default: AssertFailed(); rc = VERR_INVALID_PARAMETER; goto l_leave; } parm.urblen = u32Len; parm.datalen = u32DataLen; if (u32DataLen) { parm.data = pvData; } requestDevice (pDevice); /* Add at tail of queued urb list. */ qurb->next = NULL; qurb->prev = pDevice->pTailQURBs; qurb->u32Err = VRDE_USB_XFER_OK; qurb->u32Len = u32Len; qurb->pvData = pvData; qurb->pvURB = pvURB; qurb->u32Handle = u32Handle; qurb->fCompleted = false; qurb->fInput = (u8Direction == VUSB_DIRECTION_IN); qurb->u32TransferredLen = 0; if (pDevice->pTailQURBs) { Assert(pDevice->pTailQURBs->next == NULL); pDevice->pTailQURBs->next = qurb; } else { /* This is the first URB to be added. */ Assert(pDevice->pHeadQURBs == NULL); pDevice->pHeadQURBs = qurb; } pDevice->pTailQURBs = qurb; releaseDevice(pDevice); *ppRemoteURB = qurb; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); l_leave: if (RT_FAILURE(rc)) { qurbFree(qurb); } return rc; } /* The function checks the URB queue for completed URBs. Also if the client * has requested URB polling, the function will send URB poll requests. */ static DECLCALLBACK(int) iface_ReapURB(PREMOTEUSBDEVICE pDevice, uint32_t u32Millies, void **ppvURB, uint32_t *pu32Len, uint32_t *pu32Err) { int rc = VINF_SUCCESS; LogFlow(("RemoteUSBBackend::iface_ReapURB %d ms\n", u32Millies)); if (pDevice->fFailed) { return VERR_VUSB_DEVICE_NOT_ATTACHED; } RemoteUSBBackend *pThis = pDevice->pOwner; /* Wait for transaction completion. */ uint64_t u64StartTime = RTTimeMilliTS(); if (pThis->pollingEnabledURB()) { VRDE_USB_REQ_REAP_URB_PARM parm; parm.code = VRDE_USB_REQ_REAP_URB; pThis->VRDPServer()->SendUSBRequest(pDevice->u32ClientId, &parm, sizeof(parm)); } REMOTEUSBQURB *qurb = NULL; for (;;) { uint32_t u32ClientId; if (ASMAtomicXchgBool(&pDevice->fWokenUp, false)) break; /* Scan queued URBs, look for completed. */ requestDevice(pDevice); u32ClientId = pDevice->u32ClientId; qurb = pDevice->pHeadQURBs; while (qurb) { if (qurb->fCompleted) { /* Remove this completed urb from the queue. */ if (qurb->prev) { qurb->prev->next = qurb->next; } else { pDevice->pHeadQURBs = qurb->next; } if (qurb->next) { qurb->next->prev = qurb->prev; } else { pDevice->pTailQURBs = qurb->prev; } qurb->next = NULL; qurb->prev = NULL; break; } qurb = qurb->next; } releaseDevice(pDevice); if ( qurb || !pDevice->pHeadQURBs || u32Millies == 0 || pDevice->fFailed || (RTTimeMilliTS() - u64StartTime >= (uint64_t)u32Millies)) { /* Got an URB or do not have to wait for an URB. */ break; } LogFlow(("RemoteUSBBackend::iface_ReapURB iteration.\n")); RTThreadSleep(10); if (pThis->pollingEnabledURB()) { VRDE_USB_REQ_REAP_URB_PARM parm; parm.code = VRDE_USB_REQ_REAP_URB; pThis->VRDPServer()->SendUSBRequest(u32ClientId, &parm, sizeof(parm)); } } LogFlow(("RemoteUSBBackend::iface_ReapURB completed in %lld ms, qurb = %p\n", RTTimeMilliTS () - u64StartTime, qurb)); if (!qurb) { *ppvURB = NULL; *pu32Len = 0; *pu32Err = VUSBSTATUS_OK; } else { *ppvURB = qurb->pvURB; *pu32Len = qurb->u32Len; *pu32Err = qurb->u32Err; #ifdef LOG_ENABLED Log(("URB len = %d, data = %p\n", qurb->u32Len, qurb->pvURB)); if (qurb->u32Len) { Log(("Received URB content:\n%.*Rhxd\n", qurb->u32Len, qurb->pvData)); } #endif qurbFree(qurb); } return rc; } static DECLCALLBACK(int) iface_Wakeup(PREMOTEUSBDEVICE pDevice) { ASMAtomicXchgBool(&pDevice->fWokenUp, true); return VINF_SUCCESS; } void RemoteUSBBackend::AddRef(void) { cRefs++; } void RemoteUSBBackend::Release(void) { cRefs--; if (cRefs <= 0) { delete this; } } void RemoteUSBBackend::PollRemoteDevices(void) { if ( mfWillBeDeleted && menmPollRemoteDevicesStatus != PollRemoteDevicesStatus_Dereferenced) { /* Unmount all remote USB devices. */ mConsole->i_processRemoteUSBDevices(mu32ClientId, NULL, 0, false); menmPollRemoteDevicesStatus = PollRemoteDevicesStatus_Dereferenced; Release(); return; } switch(menmPollRemoteDevicesStatus) { case PollRemoteDevicesStatus_Negotiate: { VRDEUSBREQNEGOTIATEPARM parm; parm.code = VRDE_USB_REQ_NEGOTIATE; parm.version = VRDE_USB_VERSION; /* VRDE_USB_VERSION_3: support VRDE_USB_REQ_DEVICE_LIST_EXT_RET. */ parm.flags = VRDE_USB_SERVER_CAPS_PORT_VERSION; mServer->SendUSBRequest(mu32ClientId, &parm, sizeof(parm)); /* Reference the object. When the client disconnects and * the backend is about to be deleted, the method must be called * to disconnect the USB devices (as stated above). */ AddRef(); /* Goto the disabled state. When a response will be received * the state will be changed to the SendRequest. */ menmPollRemoteDevicesStatus = PollRemoteDevicesStatus_WaitNegotiateResponse; } break; case PollRemoteDevicesStatus_WaitNegotiateResponse: { LogFlow(("USB::PollRemoteDevices: WaitNegotiateResponse\n")); /* Do nothing. */ } break; case PollRemoteDevicesStatus_SendRequest: { LogFlow(("USB::PollRemoteDevices: SendRequest\n")); /* Send a request for device list. */ VRDE_USB_REQ_DEVICE_LIST_PARM parm; parm.code = VRDE_USB_REQ_DEVICE_LIST; mServer->SendUSBRequest(mu32ClientId, &parm, sizeof(parm)); menmPollRemoteDevicesStatus = PollRemoteDevicesStatus_WaitResponse; } break; case PollRemoteDevicesStatus_WaitResponse: { LogFlow(("USB::PollRemoteDevices: WaitResponse\n")); if (mfHasDeviceList) { mConsole->i_processRemoteUSBDevices(mu32ClientId, (VRDEUSBDEVICEDESC *)mpvDeviceList, mcbDeviceList, mfDescExt); LogFlow(("USB::PollRemoteDevices: WaitResponse after process\n")); menmPollRemoteDevicesStatus = PollRemoteDevicesStatus_SendRequest; mfHasDeviceList = false; } } break; case PollRemoteDevicesStatus_Dereferenced: { LogFlow(("USB::PollRemoteDevices: Dereferenced\n")); /* Do nothing. */ } break; default: { AssertFailed(); } break; } } void RemoteUSBBackend::NotifyDelete(void) { mfWillBeDeleted = true; } /* * The backend maintains a list of UUIDs of devices * which are managed by the backend. */ bool RemoteUSBBackend::addUUID(const Guid *pUuid) { unsigned i; for (i = 0; i < RT_ELEMENTS(aGuids); i++) { if (aGuids[i].isZero()) { aGuids[i] = *pUuid; return true; } } return false; } bool RemoteUSBBackend::findUUID(const Guid *pUuid) { unsigned i; for (i = 0; i < RT_ELEMENTS(aGuids); i++) { if (aGuids[i] == *pUuid) { return true; } } return false; } void RemoteUSBBackend::removeUUID(const Guid *pUuid) { unsigned i; for (i = 0; i < RT_ELEMENTS(aGuids); i++) { if (aGuids[i] == *pUuid) { aGuids[i].clear(); break; } } } RemoteUSBBackend::RemoteUSBBackend(Console *console, ConsoleVRDPServer *server, uint32_t u32ClientId) : mConsole(console), mServer(server), cRefs(0), mu32ClientId(u32ClientId), mfHasDeviceList(false), mpvDeviceList(NULL), mcbDeviceList(0), menmPollRemoteDevicesStatus(PollRemoteDevicesStatus_Negotiate), mfPollURB(true), mpDevices(NULL), mfWillBeDeleted(false), mClientVersion(0), /* VRDE_USB_VERSION_2: the client version. */ mfDescExt(false) /* VRDE_USB_VERSION_3: VRDE_USB_REQ_DEVICE_LIST_EXT_RET. */ { Assert(console); Assert(server); int rc = RTCritSectInit(&mCritsect); if (RT_FAILURE(rc)) { AssertFailed(); RT_ZERO(mCritsect); } mCallback.pInstance = (PREMOTEUSBBACKEND)this; mCallback.pfnOpen = iface_Open; mCallback.pfnClose = iface_Close; mCallback.pfnReset = iface_Reset; mCallback.pfnSetConfig = iface_SetConfig; mCallback.pfnClaimInterface = iface_ClaimInterface; mCallback.pfnReleaseInterface = iface_ReleaseInterface; mCallback.pfnInterfaceSetting = iface_InterfaceSetting; mCallback.pfnQueueURB = iface_QueueURB; mCallback.pfnReapURB = iface_ReapURB; mCallback.pfnClearHaltedEP = iface_ClearHaltedEP; mCallback.pfnCancelURB = iface_CancelURB; mCallback.pfnWakeup = iface_Wakeup; } RemoteUSBBackend::~RemoteUSBBackend() { Assert(cRefs == 0); if (RTCritSectIsInitialized(&mCritsect)) { RTCritSectDelete(&mCritsect); } RTMemFree(mpvDeviceList); mServer->usbBackendRemoveFromList(this); } int RemoteUSBBackend::negotiateResponse(const VRDEUSBREQNEGOTIATERET *pret, uint32_t cbRet) { int rc = VINF_SUCCESS; Log(("RemoteUSBBackend::negotiateResponse: flags = %02X.\n", pret->flags)); LogRel(("Remote USB: Received negotiate response. Flags 0x%02X.\n", pret->flags)); if (pret->flags & VRDE_USB_CAPS_FLAG_POLL) { Log(("RemoteUSBBackend::negotiateResponse: client requested URB polling.\n")); mfPollURB = true; } else { mfPollURB = false; } /* VRDE_USB_VERSION_2: check the client version. */ if (pret->flags & VRDE_USB_CAPS2_FLAG_VERSION) { /* This could be a client version > 1. */ if (cbRet >= sizeof(VRDEUSBREQNEGOTIATERET_2)) { VRDEUSBREQNEGOTIATERET_2 *pret2 = (VRDEUSBREQNEGOTIATERET_2 *)pret; if (pret2->u32Version <= VRDE_USB_VERSION) { /* This is OK. The client wants a version supported by the server. */ mClientVersion = pret2->u32Version; } else { LogRel(("VRDP: ERROR: unsupported remote USB protocol client version %d.\n", pret2->u32Version)); rc = VERR_NOT_SUPPORTED; } } else { LogRel(("VRDP: ERROR: invalid remote USB negotiate request packet size %d.\n", cbRet)); rc = VERR_NOT_SUPPORTED; } } else { /* This is a client version 1. */ mClientVersion = VRDE_USB_VERSION_1; } if (RT_SUCCESS(rc)) { LogRel(("VRDP: remote USB protocol version %d.\n", mClientVersion)); /* VRDE_USB_VERSION_3: check the client capabilities: VRDE_USB_CLIENT_CAPS_*. */ if (mClientVersion == VRDE_USB_VERSION_3) { if (cbRet >= sizeof(VRDEUSBREQNEGOTIATERET_3)) { VRDEUSBREQNEGOTIATERET_3 *pret3 = (VRDEUSBREQNEGOTIATERET_3 *)pret; mfDescExt = (pret3->u32Flags & VRDE_USB_CLIENT_CAPS_PORT_VERSION) != 0; } else { LogRel(("VRDP: ERROR: invalid remote USB negotiate request packet size %d.\n", cbRet)); rc = VERR_NOT_SUPPORTED; } } menmPollRemoteDevicesStatus = PollRemoteDevicesStatus_SendRequest; } return rc; } int RemoteUSBBackend::saveDeviceList(const void *pvList, uint32_t cbList) { Log(("RemoteUSBBackend::saveDeviceList: pvList = %p, cbList = %d\n", pvList, cbList)); if (!mfHasDeviceList) { RTMemFree(mpvDeviceList); mpvDeviceList = NULL; mcbDeviceList = cbList; if (cbList > 0) { mpvDeviceList = RTMemAlloc(cbList); memcpy(mpvDeviceList, pvList, cbList); } mfHasDeviceList = true; } return VINF_SUCCESS; } void RemoteUSBBackend::request(void) { int rc = RTCritSectEnter(&mCritsect); AssertRC(rc); } void RemoteUSBBackend::release(void) { RTCritSectLeave(&mCritsect); } PREMOTEUSBDEVICE RemoteUSBBackend::deviceFromId(VRDEUSBDEVID id) { request(); REMOTEUSBDEVICE *pDevice = mpDevices; while (pDevice && pDevice->id != id) { pDevice = pDevice->next; } release(); return pDevice; } void RemoteUSBBackend::addDevice(PREMOTEUSBDEVICE pDevice) { request(); pDevice->next = mpDevices; if (mpDevices) { mpDevices->prev = pDevice; } mpDevices = pDevice; release(); } void RemoteUSBBackend::removeDevice(PREMOTEUSBDEVICE pDevice) { request(); if (pDevice->prev) { pDevice->prev->next = pDevice->next; } else { mpDevices = pDevice->next; } if (pDevice->next) { pDevice->next->prev = pDevice->prev; } release(); } int RemoteUSBBackend::reapURB(const void *pvBody, uint32_t cbBody) { int rc = VINF_SUCCESS; LogFlow(("RemoteUSBBackend::reapURB: pvBody = %p, cbBody = %d\n", pvBody, cbBody)); VRDEUSBREQREAPURBBODY *pBody = (VRDEUSBREQREAPURBBODY *)pvBody; while (cbBody >= sizeof(VRDEUSBREQREAPURBBODY)) { Log(("RemoteUSBBackend::reapURB: id = %d, flags = %02X, error = %d, handle %d, len = %d.\n", pBody->id, pBody->flags, pBody->error, pBody->handle, pBody->len)); uint8_t fu8ReapValidFlags; if (mClientVersion == VRDE_USB_VERSION_1 || mClientVersion == VRDE_USB_VERSION_2) { fu8ReapValidFlags = VRDE_USB_REAP_VALID_FLAGS; } else { fu8ReapValidFlags = VRDE_USB_REAP_VALID_FLAGS_3; } /* Verify client's data. */ if ( (pBody->flags & ~fu8ReapValidFlags) != 0 || sizeof(VRDEUSBREQREAPURBBODY) > cbBody || pBody->handle == 0) { LogFlow(("RemoteUSBBackend::reapURB: WARNING: invalid reply data. Skipping the reply.\n")); rc = VERR_INVALID_PARAMETER; break; } PREMOTEUSBDEVICE pDevice = deviceFromId(pBody->id); if (!pDevice) { LogFlow(("RemoteUSBBackend::reapURB: WARNING: invalid device id. Skipping the reply.\n")); rc = VERR_INVALID_PARAMETER; break; } uint32_t cbBodyData = 0; /* Data contained in the URB body structure for input URBs. */ requestDevice(pDevice); /* Search the queued URB for given handle. */ REMOTEUSBQURB *qurb = pDevice->pHeadQURBs; while (qurb && qurb->u32Handle != pBody->handle) { LogFlow(("RemoteUSBBackend::reapURB: searching: %p handle = %d.\n", qurb, qurb->u32Handle)); qurb = qurb->next; } if (!qurb) { LogFlow(("RemoteUSBBackend::reapURB: Queued URB not found, probably already canceled. Skipping the URB.\n")); } else { LogFlow(("RemoteUSBBackend::reapURB: qurb = %p\n", qurb)); /* Update the URB error field. */ if (mClientVersion == VRDE_USB_VERSION_1) { switch(pBody->error) { case VRDE_USB_XFER_OK: qurb->u32Err = VUSBSTATUS_OK; break; case VRDE_USB_XFER_STALL: qurb->u32Err = VUSBSTATUS_STALL; break; case VRDE_USB_XFER_DNR: qurb->u32Err = VUSBSTATUS_DNR; break; case VRDE_USB_XFER_CRC: qurb->u32Err = VUSBSTATUS_CRC; break; default: Log(("RemoteUSBBackend::reapURB: Invalid error %d\n", pBody->error)); qurb->u32Err = VUSBSTATUS_DNR; break; } } else if ( mClientVersion == VRDE_USB_VERSION_2 || mClientVersion == VRDE_USB_VERSION_3) { switch(pBody->error) { case VRDE_USB_XFER_OK: qurb->u32Err = VUSBSTATUS_OK; break; case VRDE_USB_XFER_STALL: qurb->u32Err = VUSBSTATUS_STALL; break; case VRDE_USB_XFER_DNR: qurb->u32Err = VUSBSTATUS_DNR; break; case VRDE_USB_XFER_CRC: qurb->u32Err = VUSBSTATUS_CRC; break; case VRDE_USB_XFER_DO: qurb->u32Err = VUSBSTATUS_DATA_OVERRUN; break; case VRDE_USB_XFER_DU: qurb->u32Err = VUSBSTATUS_DATA_UNDERRUN; break; /* Unmapped errors. */ case VRDE_USB_XFER_BS: case VRDE_USB_XFER_DTM: case VRDE_USB_XFER_PCF: case VRDE_USB_XFER_UPID: case VRDE_USB_XFER_BO: case VRDE_USB_XFER_BU: case VRDE_USB_XFER_ERR: default: Log(("RemoteUSBBackend::reapURB: Invalid error %d\n", pBody->error)); qurb->u32Err = VUSBSTATUS_DNR; break; } } else { qurb->u32Err = VUSBSTATUS_DNR; } /* Get the URB data. */ bool fURBCompleted = true; if (qurb->fInput) { cbBodyData = pBody->len; /* VRDE_USB_DIRECTION_IN URBs include some data. */ } if ( qurb->u32Err == VUSBSTATUS_OK && qurb->fInput) { LogFlow(("RemoteUSBBackend::reapURB: copying data %d bytes\n", pBody->len)); uint32_t u32DataLen = qurb->u32TransferredLen + pBody->len; if (u32DataLen > qurb->u32Len) { /* Received more data than expected for this URB. If there more fragments follow, * they will be discarded because the URB handle will not be valid anymore. */ qurb->u32Err = VUSBSTATUS_DNR; } else { memcpy ((uint8_t *)qurb->pvData + qurb->u32TransferredLen, &pBody[1], pBody->len); } if ( qurb->u32Err == VUSBSTATUS_OK && (pBody->flags & VRDE_USB_REAP_FLAG_FRAGMENT) != 0) { /* If the client sends fragmented packets, accumulate the URB data. */ fURBCompleted = false; } } qurb->u32TransferredLen += pBody->len; /* Update the value for all URBs. */ if (fURBCompleted) { /* Move the URB near the head of URB list, so that iface_ReapURB can * find it faster. Note that the order of completion must be preserved! */ if (qurb->prev) { /* The URB is not in the head. Unlink it from its current position. */ qurb->prev->next = qurb->next; if (qurb->next) { qurb->next->prev = qurb->prev; } else { pDevice->pTailQURBs = qurb->prev; } /* And insert it to its new place. */ if (pDevice->pHeadQURBs->fCompleted) { /* At least one other completed URB; insert after the * last completed URB. */ REMOTEUSBQURB *prev_qurb = pDevice->pHeadQURBs; while (prev_qurb->next && prev_qurb->next->fCompleted) prev_qurb = prev_qurb->next; qurb->next = prev_qurb->next; qurb->prev = prev_qurb; if (prev_qurb->next) prev_qurb->next->prev = qurb; else pDevice->pTailQURBs = qurb; prev_qurb->next = qurb; } else { /* No other completed URBs; insert at head. */ qurb->next = pDevice->pHeadQURBs; qurb->prev = NULL; pDevice->pHeadQURBs->prev = qurb; pDevice->pHeadQURBs = qurb; } } qurb->u32Len = qurb->u32TransferredLen; /* Update the final length. */ qurb->fCompleted = true; } } releaseDevice (pDevice); if (pBody->flags & VRDE_USB_REAP_FLAG_LAST) { break; } /* There is probably a further URB body. */ uint32_t cbBodySize = sizeof (VRDEUSBREQREAPURBBODY) + cbBodyData; if (cbBodySize > cbBody) { rc = VERR_INVALID_PARAMETER; break; } pBody = (VRDEUSBREQREAPURBBODY *)((uint8_t *)pBody + cbBodySize); cbBody -= cbBodySize; } LogFlow(("RemoteUSBBackend::reapURB: returns %Rrc\n", rc)); return rc; } /* vi: set tabstop=4 shiftwidth=4 expandtab: */
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("BlackBitcoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
//===--- ParseStmt.cpp - Swift Language Parser for Statements -------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Statement Parsing and AST Building // //===----------------------------------------------------------------------===// #include "swift/AST/ASTWalker.h" #include "swift/AST/Attr.h" #include "swift/AST/Decl.h" #include "swift/Basic/Defer.h" #include "swift/Basic/Version.h" #include "swift/Parse/CodeCompletionCallbacks.h" #include "swift/Parse/Lexer.h" #include "swift/Parse/Parser.h" #include "swift/Parse/SyntaxParsingContext.h" #include "swift/Subsystems.h" #include "swift/Syntax/TokenSyntax.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/SaveAndRestore.h" using namespace swift; using namespace swift::syntax; /// isStartOfStmt - Return true if the current token starts a statement. /// bool Parser::isStartOfStmt() { // This needs to be kept in sync with `Parser::parseStmt()`. If a new token // kind is accepted here as start of statement, it should also be handled in // `Parser::parseStmt()`. switch (Tok.getKind()) { default: return false; case tok::kw_return: case tok::kw_throw: case tok::kw_defer: case tok::kw_if: case tok::kw_guard: case tok::kw_while: case tok::kw_do: case tok::kw_repeat: case tok::kw_for: case tok::kw_break: case tok::kw_continue: case tok::kw_fallthrough: case tok::kw_switch: case tok::kw_case: case tok::kw_default: case tok::kw_yield: case tok::pound_assert: case tok::pound_if: case tok::pound_warning: case tok::pound_error: case tok::pound_sourceLocation: return true; case tok::pound_line: // #line at the start of a line is a directive, when within, it is an expr. return Tok.isAtStartOfLine(); case tok::kw_try: { // "try" cannot actually start any statements, but we parse it there for // better recovery. Parser::BacktrackingScope backtrack(*this); consumeToken(tok::kw_try); return isStartOfStmt(); } case tok::identifier: { // "identifier ':' for/while/do/switch" is a label on a loop/switch. if (!peekToken().is(tok::colon)) { // "yield" in the right context begins a yield statement. if (isContextualYieldKeyword()) { return true; } return false; } // To disambiguate other cases of "identifier :", which might be part of a // question colon expression or something else, we look ahead to the second // token. Parser::BacktrackingScope backtrack(*this); consumeToken(tok::identifier); consumeToken(tok::colon); // For better recovery, we just accept a label on any statement. We reject // putting a label on something inappropriate in parseStmt(). return isStartOfStmt(); } case tok::at_sign: { // Might be a statement or case attribute. The only one of these we have // right now is `@unknown default`, so hardcode a check for an attribute // without any parens. if (!peekToken().is(tok::identifier)) return false; Parser::BacktrackingScope backtrack(*this); consumeToken(tok::at_sign); consumeToken(tok::identifier); return isStartOfStmt(); } } } ParserStatus Parser::parseExprOrStmt(ASTNode &Result) { if (Tok.is(tok::semi)) { SyntaxParsingContext ErrorCtxt(SyntaxContext, SyntaxContextKind::Stmt); diagnose(Tok, diag::illegal_semi_stmt) .fixItRemove(SourceRange(Tok.getLoc())); consumeToken(); return makeParserError(); } if (Tok.is(tok::pound) && Tok.isAtStartOfLine() && peekToken().is(tok::code_complete)) { SyntaxParsingContext CCCtxt(SyntaxContext, SyntaxContextKind::Decl); consumeToken(); if (CodeCompletion) CodeCompletion->completeAfterPoundDirective(); consumeToken(tok::code_complete); return makeParserCodeCompletionStatus(); } if (isStartOfStmt()) { ParserResult<Stmt> Res = parseStmt(); if (Res.isNonNull()) Result = Res.get(); return Res; } // Note that we're parsing a statement. StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(), StructureMarkerKind::Statement); if (CodeCompletion) CodeCompletion->setExprBeginning(getParserPosition()); if (Tok.is(tok::code_complete)) { auto *CCE = new (Context) CodeCompletionExpr(Tok.getLoc()); Result = CCE; if (CodeCompletion) CodeCompletion->completeStmtOrExpr(CCE); SyntaxParsingContext ErrorCtxt(SyntaxContext, SyntaxContextKind::Stmt); consumeToken(tok::code_complete); return makeParserCodeCompletionStatus(); } ParserResult<Expr> ResultExpr = parseExpr(diag::expected_expr); if (ResultExpr.isNonNull()) { Result = ResultExpr.get(); } else if (!ResultExpr.hasCodeCompletion()) { // If we've consumed any tokens at all, build an error expression // covering the consumed range. SourceLoc startLoc = StructureMarkers.back().Loc; if (startLoc != Tok.getLoc()) { Result = new (Context) ErrorExpr(SourceRange(startLoc, PreviousLoc)); } } if (ResultExpr.hasCodeCompletion() && CodeCompletion) { CodeCompletion->completeExpr(); } return ResultExpr; } /// Returns whether the parser's current position is the start of a switch case, /// given that we're in the middle of a switch already. static bool isAtStartOfSwitchCase(Parser &parser, bool needsToBacktrack = true) { Optional<Parser::BacktrackingScope> backtrack; // Check for and consume attributes. The only valid attribute is `@unknown` // but that's a semantic restriction. while (parser.Tok.is(tok::at_sign)) { if (!parser.peekToken().is(tok::identifier)) return false; if (needsToBacktrack && !backtrack) backtrack.emplace(parser); parser.consumeToken(tok::at_sign); parser.consumeIdentifier(); if (parser.Tok.is(tok::l_paren)) parser.skipSingle(); } return parser.Tok.isAny(tok::kw_case, tok::kw_default); } bool Parser::isTerminatorForBraceItemListKind(BraceItemListKind Kind, ArrayRef<ASTNode> ParsedDecls) { switch (Kind) { case BraceItemListKind::Brace: return false; case BraceItemListKind::Case: { if (Tok.is(tok::pound_if)) { // Backtracking scopes are expensive, so avoid setting one up if possible. Parser::BacktrackingScope Backtrack(*this); // '#if' here could be to guard 'case:' or statements in cases. // If the next non-directive line starts with 'case' or 'default', it is // for 'case's. do { consumeToken(); // just find the end of the line skipUntilTokenOrEndOfLine(tok::NUM_TOKENS); } while (Tok.isAny(tok::pound_if, tok::pound_elseif, tok::pound_else)); return isAtStartOfSwitchCase(*this, /*needsToBacktrack*/false); } return isAtStartOfSwitchCase(*this); } case BraceItemListKind::TopLevelCode: // When parsing the top level executable code for a module, if we parsed // some executable code, then we're done. We want to process (name bind, // type check, etc) decls one at a time to make sure that there are not // forward type references, etc. There is an outer loop around the parser // that will reinvoke the parser at the top level on each statement until // EOF. In contrast, it is ok to have forward references between classes, // functions, etc. for (auto I : ParsedDecls) { if (isa<TopLevelCodeDecl>(I.get<Decl*>())) // Only bail out if the next token is at the start of a line. If we // don't, then we may accidentally allow things like "a = 1 b = 4". // FIXME: This is really dubious. This will reject some things, but // allow other things we don't want. if (Tok.isAtStartOfLine()) return true; } return false; case BraceItemListKind::TopLevelLibrary: return false; case BraceItemListKind::ActiveConditionalBlock: case BraceItemListKind::InactiveConditionalBlock: return Tok.isNot(tok::pound_else) && Tok.isNot(tok::pound_endif) && Tok.isNot(tok::pound_elseif); } llvm_unreachable("Unhandled BraceItemListKind in switch."); } void Parser::consumeTopLevelDecl(ParserPosition BeginParserPosition, TopLevelCodeDecl *TLCD) { SyntaxParsingContext Discarding(SyntaxContext); Discarding.disable(); SourceLoc EndLoc = PreviousLoc; backtrackToPosition(BeginParserPosition); SourceLoc BeginLoc = Tok.getLoc(); State->setCodeCompletionDelayedDeclState( PersistentParserState::CodeCompletionDelayedDeclKind::TopLevelCodeDecl, PD_Default, TLCD, {BeginLoc, EndLoc}, BeginParserPosition.PreviousLoc); // Skip the rest of the file to prevent the parser from constructing the AST // for it. Forward references are not allowed at the top level. while (!Tok.is(tok::eof)) consumeToken(); } /// brace-item: /// decl /// expr /// stmt /// stmt: /// ';' /// stmt-assign /// stmt-if /// stmt-guard /// stmt-for-c-style /// stmt-for-each /// stmt-switch /// stmt-control-transfer /// stmt-control-transfer: /// stmt-return /// stmt-break /// stmt-continue /// stmt-fallthrough /// stmt-assign: /// expr '=' expr ParserStatus Parser::parseBraceItems(SmallVectorImpl<ASTNode> &Entries, BraceItemListKind Kind, BraceItemListKind ConditionalBlockKind) { bool isRootCtx = SyntaxContext->isRoot(); SyntaxParsingContext ItemListContext(SyntaxContext, SyntaxKind::CodeBlockItemList); if (isRootCtx) { ItemListContext.setTransparent(); } bool IsTopLevel = (Kind == BraceItemListKind::TopLevelCode) || (Kind == BraceItemListKind::TopLevelLibrary); bool isActiveConditionalBlock = ConditionalBlockKind == BraceItemListKind::ActiveConditionalBlock; bool isConditionalBlock = isActiveConditionalBlock || ConditionalBlockKind == BraceItemListKind::InactiveConditionalBlock; // If we're not parsing an active #if block, form a new lexical scope. Optional<Scope> initScope; if (!isActiveConditionalBlock) { auto scopeKind = IsTopLevel ? ScopeKind::TopLevel : ScopeKind::Brace; initScope.emplace(this, scopeKind, ConditionalBlockKind == BraceItemListKind::InactiveConditionalBlock); } ParserStatus BraceItemsStatus; bool PreviousHadSemi = true; while ((IsTopLevel || Tok.isNot(tok::r_brace)) && Tok.isNot(tok::pound_endif) && Tok.isNot(tok::pound_elseif) && Tok.isNot(tok::pound_else) && Tok.isNot(tok::eof) && Tok.isNot(tok::kw_sil) && Tok.isNot(tok::kw_sil_scope) && Tok.isNot(tok::kw_sil_stage) && Tok.isNot(tok::kw_sil_vtable) && Tok.isNot(tok::kw_sil_global) && Tok.isNot(tok::kw_sil_witness_table) && Tok.isNot(tok::kw_sil_default_witness_table) && Tok.isNot(tok::kw_sil_property) && (isConditionalBlock || !isTerminatorForBraceItemListKind(Kind, Entries))) { SyntaxParsingContext NodeContext(SyntaxContext, SyntaxKind::CodeBlockItem); if (loadCurrentSyntaxNodeFromCache()) { continue; } if (Tok.is(tok::r_brace)) { SyntaxParsingContext ErrContext(SyntaxContext, SyntaxContextKind::Stmt); assert(IsTopLevel); diagnose(Tok, diag::extra_rbrace) .fixItRemove(Tok.getLoc()); consumeToken(); continue; } // Eat invalid tokens instead of allowing them to produce downstream errors. if (Tok.is(tok::unknown)) { SyntaxParsingContext ErrContext(SyntaxContext, SyntaxContextKind::Stmt); if (Tok.getText().startswith("\"\"\"")) { // This was due to unterminated multi-line string. IsInputIncomplete = true; } consumeToken(); continue; } bool NeedParseErrorRecovery = false; ASTNode Result; // If the previous statement didn't have a semicolon and this new // statement doesn't start a line, complain. const bool IsAtStartOfLineOrPreviousHadSemi = PreviousHadSemi || Tok.isAtStartOfLine(); if (!IsAtStartOfLineOrPreviousHadSemi) { SourceLoc EndOfPreviousLoc = getEndOfPreviousLoc(); diagnose(EndOfPreviousLoc, diag::statement_same_line_without_semi) .fixItInsert(EndOfPreviousLoc, ";"); // FIXME: Add semicolon to the AST? } ParserPosition BeginParserPosition; if (isCodeCompletionFirstPass()) BeginParserPosition = getParserPosition(); // Parse the decl, stmt, or expression. PreviousHadSemi = false; if (Tok.is(tok::pound_if)) { auto IfConfigResult = parseIfConfig( [&](SmallVectorImpl<ASTNode> &Elements, bool IsActive) { parseBraceItems(Elements, Kind, IsActive ? BraceItemListKind::ActiveConditionalBlock : BraceItemListKind::InactiveConditionalBlock); }); if (IfConfigResult.hasCodeCompletion() && isCodeCompletionFirstPass()) { consumeDecl(BeginParserPosition, None, IsTopLevel); return IfConfigResult; } BraceItemsStatus |= IfConfigResult; if (auto ICD = IfConfigResult.getPtrOrNull()) { Result = ICD; // Add the #if block itself Entries.push_back(ICD); for (auto &Entry : ICD->getActiveClauseElements()) { if (Entry.is<Decl *>() && isa<IfConfigDecl>(Entry.get<Decl *>())) // Don't hoist nested '#if'. continue; Entries.push_back(Entry); if (Entry.is<Decl *>()) Entry.get<Decl *>()->setEscapedFromIfConfig(true); } } else { NeedParseErrorRecovery = true; continue; } } else if (Tok.is(tok::pound_line)) { ParserStatus Status = parseLineDirective(true); BraceItemsStatus |= Status; NeedParseErrorRecovery = Status.isError(); } else if (Tok.is(tok::pound_sourceLocation)) { ParserStatus Status = parseLineDirective(false); BraceItemsStatus |= Status; NeedParseErrorRecovery = Status.isError(); } else if (isStartOfDecl()) { SmallVector<Decl*, 8> TmpDecls; ParserResult<Decl> DeclResult = parseDecl(IsTopLevel ? PD_AllowTopLevel : PD_Default, IsAtStartOfLineOrPreviousHadSemi, [&](Decl *D) {TmpDecls.push_back(D);}); BraceItemsStatus |= DeclResult; if (DeclResult.isParseError()) { NeedParseErrorRecovery = true; if (DeclResult.hasCodeCompletion() && IsTopLevel && isCodeCompletionFirstPass()) { consumeDecl(BeginParserPosition, None, IsTopLevel); return DeclResult; } } Result = DeclResult.getPtrOrNull(); Entries.append(TmpDecls.begin(), TmpDecls.end()); } else if (IsTopLevel) { // If this is a statement or expression at the top level of the module, // Parse it as a child of a TopLevelCodeDecl. auto *TLCD = new (Context) TopLevelCodeDecl(CurDeclContext); ContextChange CC(*this, TLCD, &State->getTopLevelContext()); SourceLoc StartLoc = Tok.getLoc(); // Expressions can't begin with a closure literal at statement position. // This prevents potential ambiguities with trailing closure syntax. if (Tok.is(tok::l_brace)) { diagnose(Tok, diag::statement_begins_with_closure); } ParserStatus Status = parseExprOrStmt(Result); BraceItemsStatus |= Status; if (Status.hasCodeCompletion() && isCodeCompletionFirstPass()) { consumeTopLevelDecl(BeginParserPosition, TLCD); auto Brace = BraceStmt::create(Context, StartLoc, {}, PreviousLoc); TLCD->setBody(Brace); Entries.push_back(TLCD); return Status; } if (Status.isError()) NeedParseErrorRecovery = true; else if (!allowTopLevelCode()) { diagnose(StartLoc, Result.is<Stmt*>() ? diag::illegal_top_level_stmt : diag::illegal_top_level_expr); } if (!Result.isNull()) { // NOTE: this is a 'virtual' brace statement which does not have // explicit '{' or '}', so the start and end locations should be // the same as those of the result node auto Brace = BraceStmt::create(Context, Result.getStartLoc(), Result, Result.getEndLoc()); TLCD->setBody(Brace); Entries.push_back(TLCD); } } else if (Tok.is(tok::kw_init) && isa<ConstructorDecl>(CurDeclContext)) { SourceLoc StartLoc = Tok.getLoc(); auto CD = cast<ConstructorDecl>(CurDeclContext); // Hint at missing 'self.' or 'super.' then skip this statement. bool isSelf = CD->getAttrs().hasAttribute<ConvenienceAttr>() || !isa<ClassDecl>(CD->getParent()); diagnose(StartLoc, diag::invalid_nested_init, isSelf) .fixItInsert(StartLoc, isSelf ? "self." : "super."); NeedParseErrorRecovery = true; BraceItemsStatus.setIsParseError(); } else { ParserStatus ExprOrStmtStatus = parseExprOrStmt(Result); BraceItemsStatus |= ExprOrStmtStatus; if (ExprOrStmtStatus.isError()) NeedParseErrorRecovery = true; if (!Result.isNull()) Entries.push_back(Result); } if (!NeedParseErrorRecovery && Tok.is(tok::semi)) { PreviousHadSemi = true; if (auto *E = Result.dyn_cast<Expr*>()) E->TrailingSemiLoc = consumeToken(tok::semi); else if (auto *S = Result.dyn_cast<Stmt*>()) S->TrailingSemiLoc = consumeToken(tok::semi); else if (auto *D = Result.dyn_cast<Decl*>()) D->TrailingSemiLoc = consumeToken(tok::semi); else assert(!Result && "Unsupported AST node"); } if (NeedParseErrorRecovery) { SyntaxParsingContext TokenListCtxt(SyntaxContext, SyntaxKind::NonEmptyTokenList); // If we had a parse error, skip to the start of the next stmt, decl or // '{'. // // It would be ideal to stop at the start of the next expression (e.g. // "X = 4"), but distinguishing the start of an expression from the middle // of one is "hard". skipUntilDeclStmtRBrace(tok::l_brace); // If we have to recover, pretend that we had a semicolon; it's less // noisy that way. PreviousHadSemi = true; } } return BraceItemsStatus; } /// Recover from a 'case' or 'default' outside of a 'switch' by consuming up to /// the next ':'. static ParserResult<Stmt> recoverFromInvalidCase(Parser &P) { assert(P.Tok.is(tok::kw_case) || P.Tok.is(tok::kw_default) && "not case or default?!"); P.diagnose(P.Tok, diag::case_outside_of_switch, P.Tok.getText()); P.skipUntil(tok::colon); // FIXME: Return an ErrorStmt? return nullptr; } ParserResult<Stmt> Parser::parseStmt() { AssertParserMadeProgressBeforeLeavingScopeRAII apmp(*this); SyntaxParsingContext LocalContext(SyntaxContext, SyntaxContextKind::Stmt); // Note that we're parsing a statement. StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(), StructureMarkerKind::Statement); LabeledStmtInfo LabelInfo; // If this is a label on a loop/switch statement, consume it and pass it into // parsing logic below. if (Tok.is(tok::identifier) && peekToken().is(tok::colon)) { LabelInfo.Loc = consumeIdentifier(&LabelInfo.Name); consumeToken(tok::colon); } SourceLoc tryLoc; (void)consumeIf(tok::kw_try, tryLoc); // Claim contextual statement keywords now that we've committed // to parsing a statement. if (isContextualYieldKeyword()) { Tok.setKind(tok::kw_yield); } // This needs to handle everything that `Parser::isStartOfStmt()` accepts as // start of statement. switch (Tok.getKind()) { case tok::pound_line: case tok::pound_sourceLocation: case tok::pound_if: case tok::pound_error: case tok::pound_warning: assert((LabelInfo || tryLoc.isValid()) && "unlabeled directives should be handled earlier"); // Bailout, and let parseBraceItems() parse them. LLVM_FALLTHROUGH; default: diagnose(Tok, tryLoc.isValid() ? diag::expected_expr : diag::expected_stmt); if (Tok.is(tok::at_sign)) { // Recover from erroneously placed attribute. consumeToken(tok::at_sign); consumeIf(tok::identifier); } return nullptr; case tok::kw_return: if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); return parseStmtReturn(tryLoc); case tok::kw_yield: if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); return parseStmtYield(tryLoc); case tok::kw_throw: if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); return parseStmtThrow(tryLoc); case tok::kw_defer: if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtDefer(); case tok::kw_if: if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtIf(LabelInfo); case tok::kw_guard: if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtGuard(); case tok::kw_while: if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtWhile(LabelInfo); case tok::kw_repeat: if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtRepeat(LabelInfo); case tok::kw_do: if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtDo(LabelInfo); case tok::kw_for: if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtForEach(LabelInfo); case tok::kw_switch: if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtSwitch(LabelInfo); /// 'case' and 'default' are only valid at the top level of a switch. case tok::kw_case: case tok::kw_default: return recoverFromInvalidCase(*this); case tok::kw_break: if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtBreak(); case tok::kw_continue: if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtContinue(); case tok::kw_fallthrough: { if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); SyntaxContext->setCreateSyntax(SyntaxKind::FallthroughStmt); return makeParserResult( new (Context) FallthroughStmt(consumeToken(tok::kw_fallthrough))); } case tok::pound_assert: if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt); if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText()); return parseStmtPoundAssert(); } } /// parseBraceItemList - A brace enclosed expression/statement/decl list. For /// example { 1; 4+5; } or { 1; 2 }. Always occurs as part of some other stmt /// or decl. /// /// brace-item-list: /// '{' brace-item* '}' /// ParserResult<BraceStmt> Parser::parseBraceItemList(Diag<> ID) { if (Tok.isNot(tok::l_brace)) { diagnose(Tok, ID); // Attempt to recover by looking for a left brace on the same line if (!skipUntilTokenOrEndOfLine(tok::l_brace)) return nullptr; } SyntaxParsingContext LocalContext(SyntaxContext, SyntaxKind::CodeBlock); SourceLoc LBLoc = consumeToken(tok::l_brace); SmallVector<ASTNode, 16> Entries; SourceLoc RBLoc; ParserStatus Status = parseBraceItems(Entries, BraceItemListKind::Brace, BraceItemListKind::Brace); if (parseMatchingToken(tok::r_brace, RBLoc, diag::expected_rbrace_in_brace_stmt, LBLoc)) { // Synthesize a r-brace if the source doesn't have any. LocalContext.synthesize(tok::r_brace, LBLoc.getAdvancedLoc(1)); } return makeParserResult(Status, BraceStmt::create(Context, LBLoc, Entries, RBLoc)); } /// parseStmtBreak /// /// stmt-break: /// 'break' identifier? /// ParserResult<Stmt> Parser::parseStmtBreak() { SyntaxContext->setCreateSyntax(SyntaxKind::BreakStmt); SourceLoc Loc = consumeToken(tok::kw_break); SourceLoc TargetLoc; Identifier Target; // If we have an identifier after this, which is not the start of another // stmt or decl, we assume it is the label to break to, unless there is a // line break. There is ambiguity with expressions (e.g. "break x+y") but // since the expression after the break is dead, we don't feel bad eagerly // parsing this. if (Tok.is(tok::identifier) && !Tok.isAtStartOfLine() && !isStartOfStmt() && !isStartOfDecl()) TargetLoc = consumeIdentifier(&Target); return makeParserResult(new (Context) BreakStmt(Loc, Target, TargetLoc)); } /// parseStmtContinue /// /// stmt-continue: /// 'continue' identifier? /// ParserResult<Stmt> Parser::parseStmtContinue() { SyntaxContext->setCreateSyntax(SyntaxKind::ContinueStmt); SourceLoc Loc = consumeToken(tok::kw_continue); SourceLoc TargetLoc; Identifier Target; // If we have an identifier after this, which is not the start of another // stmt or decl, we assume it is the label to continue to, unless there is a // line break. There is ambiguity with expressions (e.g. "continue x+y") but // since the expression after the continue is dead, we don't feel bad eagerly // parsing this. if (Tok.is(tok::identifier) && !Tok.isAtStartOfLine() && !isStartOfStmt() && !isStartOfDecl()) TargetLoc = consumeIdentifier(&Target); return makeParserResult(new (Context) ContinueStmt(Loc, Target, TargetLoc)); } /// parseStmtReturn /// /// stmt-return: /// 'return' expr? /// ParserResult<Stmt> Parser::parseStmtReturn(SourceLoc tryLoc) { SyntaxContext->setCreateSyntax(SyntaxKind::ReturnStmt); SourceLoc ReturnLoc = consumeToken(tok::kw_return); if (Tok.is(tok::code_complete)) { auto CCE = new (Context) CodeCompletionExpr(SourceRange(Tok.getLoc())); auto Result = makeParserResult(new (Context) ReturnStmt(ReturnLoc, CCE)); if (CodeCompletion) { CodeCompletion->completeReturnStmt(CCE); } Result.setHasCodeCompletion(); consumeToken(); return Result; } // Handle the ambiguity between consuming the expression and allowing the // enclosing stmt-brace to get it by eagerly eating it unless the return is // followed by a '}', ';', statement or decl start keyword sequence. if (Tok.isNot(tok::r_brace, tok::semi, tok::eof, tok::pound_if, tok::pound_error, tok::pound_warning, tok::pound_endif, tok::pound_else, tok::pound_elseif) && !isStartOfStmt() && !isStartOfDecl()) { SourceLoc ExprLoc = Tok.getLoc(); // Issue a warning when the returned expression is on a different line than // the return keyword, but both have the same indentation. if (SourceMgr.getLineAndColumn(ReturnLoc).second == SourceMgr.getLineAndColumn(ExprLoc).second) { diagnose(ExprLoc, diag::unindented_code_after_return); diagnose(ExprLoc, diag::indent_expression_to_silence); } ParserResult<Expr> Result = parseExpr(diag::expected_expr_return); if (Result.isNull()) { // Create an ErrorExpr to tell the type checker that this return // statement had an expression argument in the source. This suppresses // the error about missing return value in a non-void function. Result = makeParserErrorResult(new (Context) ErrorExpr(ExprLoc)); } if (tryLoc.isValid()) { diagnose(tryLoc, diag::try_on_return_throw_yield, /*return=*/0) .fixItInsert(ExprLoc, "try ") .fixItRemoveChars(tryLoc, ReturnLoc); // Note: We can't use tryLoc here because that's outside the ReturnStmt's // source range. if (Result.isNonNull() && !isa<ErrorExpr>(Result.get())) Result = makeParserResult(new (Context) TryExpr(ExprLoc, Result.get())); } return makeParserResult( Result, new (Context) ReturnStmt(ReturnLoc, Result.getPtrOrNull())); } if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, "return"); return makeParserResult(new (Context) ReturnStmt(ReturnLoc, nullptr)); } /// parseStmtYield /// /// stmt-yield: /// 'yield' expr /// 'yield' '(' expr-list ')' /// /// Note that a parenthesis always starts the second (list) grammar. ParserResult<Stmt> Parser::parseStmtYield(SourceLoc tryLoc) { SyntaxContext->setCreateSyntax(SyntaxKind::YieldStmt); SourceLoc yieldLoc = consumeToken(tok::kw_yield); if (Tok.is(tok::code_complete)) { auto cce = new (Context) CodeCompletionExpr(SourceRange(Tok.getLoc())); auto result = makeParserResult( YieldStmt::create(Context, yieldLoc, SourceLoc(), cce, SourceLoc())); if (CodeCompletion) { CodeCompletion->completeYieldStmt(cce, /*index=*/ None); } result.setHasCodeCompletion(); consumeToken(); return result; } ParserStatus status; SourceLoc lpLoc, rpLoc; SmallVector<Expr*, 4> yields; if (Tok.is(tok::l_paren)) { // If there was a 'try' on the yield, and there are multiple // yielded values, suggest just removing the try instead of // suggesting adding it to every yielded value. if (tryLoc.isValid()) { diagnose(tryLoc, diag::try_on_return_throw_yield, /*yield=*/2) .fixItRemoveChars(tryLoc, yieldLoc); } SyntaxParsingContext YieldsCtxt(SyntaxContext, SyntaxKind::YieldList); SmallVector<Identifier, 4> yieldLabels; SmallVector<SourceLoc, 4> yieldLabelLocs; Expr *trailingClosure = nullptr; status = parseExprList(tok::l_paren, tok::r_paren, /*postfix (allow trailing closure)*/ false, /*expr basic (irrelevant)*/ true, lpLoc, yields, yieldLabels, yieldLabelLocs, rpLoc, trailingClosure, SyntaxKind::ExprList); assert(trailingClosure == nullptr); assert(yieldLabels.empty()); assert(yieldLabelLocs.empty()); } else { SourceLoc beginLoc = Tok.getLoc(); // There's a single yielded value, so suggest moving 'try' before it. if (tryLoc.isValid()) { diagnose(tryLoc, diag::try_on_return_throw_yield, /*yield=*/2) .fixItInsert(beginLoc, "try ") .fixItRemoveChars(tryLoc, yieldLoc); } auto expr = parseExpr(diag::expected_expr_yield); if (expr.hasCodeCompletion()) return makeParserCodeCompletionResult<Stmt>(); if (expr.isParseError()) { auto endLoc = (Tok.getLoc() == beginLoc ? beginLoc : PreviousLoc); yields.push_back( new (Context) ErrorExpr(SourceRange(beginLoc, endLoc))); } else { yields.push_back(expr.get()); } } return makeParserResult( status, YieldStmt::create(Context, yieldLoc, lpLoc, yields, rpLoc)); } /// parseStmtThrow /// /// stmt-throw /// 'throw' expr /// ParserResult<Stmt> Parser::parseStmtThrow(SourceLoc tryLoc) { SyntaxContext->setCreateSyntax(SyntaxKind::ThrowStmt); SourceLoc throwLoc = consumeToken(tok::kw_throw); SourceLoc exprLoc; if (Tok.isNot(tok::eof)) exprLoc = Tok.getLoc(); ParserResult<Expr> Result = parseExpr(diag::expected_expr_throw); if (Result.hasCodeCompletion()) return makeParserCodeCompletionResult<Stmt>(); if (Result.isNull()) Result = makeParserErrorResult(new (Context) ErrorExpr(throwLoc)); if (tryLoc.isValid() && exprLoc.isValid()) { diagnose(tryLoc, diag::try_on_return_throw_yield, /*throw=*/1) .fixItInsert(exprLoc, "try ") .fixItRemoveChars(tryLoc, throwLoc); // Note: We can't use tryLoc here because that's outside the ThrowStmt's // source range. if (Result.isNonNull() && !isa<ErrorExpr>(Result.get())) Result = makeParserResult(new (Context) TryExpr(exprLoc, Result.get())); } return makeParserResult(Result, new (Context) ThrowStmt(throwLoc, Result.get())); } /// parseStmtDefer /// /// stmt-defer: /// 'defer' brace-stmt /// ParserResult<Stmt> Parser::parseStmtDefer() { SyntaxContext->setCreateSyntax(SyntaxKind::DeferStmt); SourceLoc DeferLoc = consumeToken(tok::kw_defer); // Macro expand out the defer into a closure and call, which we can typecheck // and emit where needed. // // The AST representation for a defer statement is a bit weird. We retain the // brace statement that the user wrote, but actually model this as if they // wrote: // // func tmpClosure() { body } // tmpClosure() // This is emitted on each path that needs to run this. // // As such, the body of the 'defer' is actually type checked within the // closure's DeclContext. auto params = ParameterList::createEmpty(Context); DeclName name(Context, Context.getIdentifier("$defer"), params); auto tempDecl = FuncDecl::create(Context, /*StaticLoc=*/ SourceLoc(), StaticSpellingKind::None, /*FuncLoc=*/ SourceLoc(), name, /*NameLoc=*/ PreviousLoc, /*Throws=*/ false, /*ThrowsLoc=*/ SourceLoc(), /*generic params*/ nullptr, params, TypeLoc(), CurDeclContext); tempDecl->setImplicit(); setLocalDiscriminator(tempDecl); ParserStatus Status; { // Change the DeclContext for any variables declared in the defer to be within // the defer closure. ParseFunctionBody cc(*this, tempDecl); ParserResult<BraceStmt> Body = parseBraceItemList(diag::expected_lbrace_after_defer); if (Body.isNull()) return nullptr; Status |= Body; tempDecl->setBodyParsed(Body.get()); } SourceLoc loc = tempDecl->getBodySourceRange().Start; // Form the call, which will be emitted on any path that needs to run the // code. auto DRE = new (Context) DeclRefExpr(tempDecl, DeclNameLoc(loc), /*Implicit*/true, AccessSemantics::DirectToStorage); auto call = CallExpr::createImplicit(Context, DRE, { }, { }); auto DS = new (Context) DeferStmt(DeferLoc, tempDecl, call); return makeParserResult(Status, DS); } namespace { struct GuardedPattern { Pattern *ThePattern = nullptr; SourceLoc WhereLoc; Expr *Guard = nullptr; }; /// Contexts in which a guarded pattern can appear. enum class GuardedPatternContext { Case, Catch, }; } // unnamed namespace static void parseWhereGuard(Parser &P, GuardedPattern &result, ParserStatus &status, GuardedPatternContext parsingContext, bool isExprBasic) { if (P.Tok.is(tok::kw_where)) { SyntaxParsingContext WhereClauseCtxt(P.SyntaxContext, SyntaxKind::WhereClause); result.WhereLoc = P.consumeToken(tok::kw_where); SourceLoc startOfGuard = P.Tok.getLoc(); auto diagKind = [=]() -> Diag<> { switch (parsingContext) { case GuardedPatternContext::Case: return diag::expected_case_where_expr; case GuardedPatternContext::Catch: return diag::expected_catch_where_expr; } llvm_unreachable("bad context"); }(); ParserResult<Expr> guardResult = P.parseExprImpl(diagKind, isExprBasic); status |= guardResult; // Use the parsed guard expression if possible. if (guardResult.isNonNull()) { result.Guard = guardResult.get(); // Otherwise, fake up an ErrorExpr. } else { // If we didn't consume any tokens failing to parse the // expression, don't put in the source range of the ErrorExpr. SourceRange errorRange; if (startOfGuard == P.Tok.getLoc()) { errorRange = result.WhereLoc; } else { errorRange = SourceRange(startOfGuard, P.PreviousLoc); } result.Guard = new (P.Context) ErrorExpr(errorRange); } } } /// Parse a pattern-matching clause for a case or catch statement, /// including the guard expression: /// /// pattern 'where' expr static void parseGuardedPattern(Parser &P, GuardedPattern &result, ParserStatus &status, SmallVectorImpl<VarDecl *> &boundDecls, GuardedPatternContext parsingContext, bool isFirstPattern) { ParserResult<Pattern> patternResult; bool isExprBasic = [&]() -> bool { switch (parsingContext) { // 'case' is terminated with a colon and so allows a trailing closure. case GuardedPatternContext::Case: return false; // 'catch' is terminated with a brace and so cannot. case GuardedPatternContext::Catch: return true; } llvm_unreachable("bad pattern context"); }(); // Do some special-case code completion for the start of the pattern. if (P.Tok.is(tok::code_complete)) { auto CCE = new (P.Context) CodeCompletionExpr(P.Tok.getLoc()); result.ThePattern = new (P.Context) ExprPattern(CCE); if (P.CodeCompletion) { switch (parsingContext) { case GuardedPatternContext::Case: P.CodeCompletion->completeCaseStmtBeginning(CCE); break; case GuardedPatternContext::Catch: P.CodeCompletion->completePostfixExprBeginning(CCE); break; } } P.consumeToken(tok::code_complete); status.setHasCodeCompletion(); return; } // If this is a 'catch' clause and we have "catch {" or "catch where...", // then we get an implicit "let error" pattern. if (parsingContext == GuardedPatternContext::Catch && P.Tok.isAny(tok::l_brace, tok::kw_where)) { auto loc = P.Tok.getLoc(); auto errorName = P.Context.Id_error; auto var = new (P.Context) VarDecl(/*IsStatic*/false, VarDecl::Introducer::Let, /*IsCaptureList*/false, loc, errorName, P.CurDeclContext); var->setImplicit(); auto namePattern = new (P.Context) NamedPattern(var); auto varPattern = new (P.Context) VarPattern(loc, /*isLet*/true, namePattern, /*implicit*/true); patternResult = makeParserResult(varPattern); } // Okay, if the special code-completion didn't kick in, parse a // matching pattern. if (patternResult.isNull()) { llvm::SaveAndRestore<decltype(P.InVarOrLetPattern)> T(P.InVarOrLetPattern, Parser::IVOLP_InMatchingPattern); patternResult = P.parseMatchingPattern(isExprBasic); } // If that didn't work, use a bogus pattern so that we can fill out // the AST. if (patternResult.isNull()) patternResult = makeParserErrorResult(new (P.Context) AnyPattern(P.PreviousLoc)); // Fill in the pattern. status |= patternResult; result.ThePattern = patternResult.get(); if (isFirstPattern) { // Add variable bindings from the pattern to the case scope. We have // to do this with a full AST walk, because the freshly parsed pattern // represents tuples and var patterns as tupleexprs and // unresolved_pattern_expr nodes, instead of as proper pattern nodes. patternResult.get()->forEachVariable([&](VarDecl *VD) { P.setLocalDiscriminator(VD); if (VD->hasName()) P.addToScope(VD); boundDecls.push_back(VD); }); // Now that we have them, mark them as being initialized without a PBD. for (auto VD : boundDecls) VD->setHasNonPatternBindingInit(); // Parse the optional 'where' guard. parseWhereGuard(P, result, status, parsingContext, isExprBasic); } else { // If boundDecls already contains variables, then we must match the // same number and same names in this pattern as were declared in a // previous pattern (and later we will make sure they have the same // types). Scope guardScope(&P, ScopeKind::CaseVars); SmallVector<VarDecl*, 4> repeatedDecls; patternResult.get()->forEachVariable([&](VarDecl *VD) { if (!VD->hasName()) return; bool found = false; for (auto previous : boundDecls) { if (previous->hasName() && previous->getName() == VD->getName()) { found = true; break; } } if (!found) { // Diagnose a declaration that doesn't match a previous pattern. P.diagnose(VD->getLoc(), diag::extra_var_in_multiple_pattern_list, VD->getName()); status.setIsParseError(); } repeatedDecls.push_back(VD); P.setLocalDiscriminator(VD); if (VD->hasName()) P.addToScope(VD); }); for (auto previous : boundDecls) { bool found = false; for (auto repeat : repeatedDecls) { if (previous->hasName() && previous->getName() == repeat->getName()) { found = true; break; } } if (!found) { // Diagnose a previous declaration that is missing in this pattern. P.diagnose(previous->getLoc(), diag::extra_var_in_multiple_pattern_list, previous->getName()); status.setIsParseError(); } } for (auto VD : repeatedDecls) { VD->setHasNonPatternBindingInit(); } // Parse the optional 'where' guard, with this particular pattern's bound // vars in scope. parseWhereGuard(P, result, status, parsingContext, isExprBasic); } } /// Validate availability spec list, emitting diagnostics if necessary and removing /// specs for unrecognized platforms. static void validateAvailabilitySpecList(Parser &P, SmallVectorImpl<AvailabilitySpec *> &Specs) { llvm::SmallSet<PlatformKind, 4> Platforms; bool HasOtherPlatformSpec = false; if (Specs.size() == 1 && isa<PlatformAgnosticVersionConstraintAvailabilitySpec>(Specs[0])) { // @available(swift N) and @available(_PackageDescription N) are allowed // only in isolation; they cannot be combined with other availability specs // in a single list. return; } SmallVector<AvailabilitySpec *, 5> RecognizedSpecs; for (auto *Spec : Specs) { RecognizedSpecs.push_back(Spec); if (isa<OtherPlatformAvailabilitySpec>(Spec)) { HasOtherPlatformSpec = true; continue; } if (auto *PlatformAgnosticSpec = dyn_cast<PlatformAgnosticVersionConstraintAvailabilitySpec>(Spec)) { P.diagnose(PlatformAgnosticSpec->getPlatformAgnosticNameLoc(), diag::availability_must_occur_alone, PlatformAgnosticSpec->isLanguageVersionSpecific() ? "swift" : "_PackageDescription"); continue; } auto *VersionSpec = cast<PlatformVersionConstraintAvailabilitySpec>(Spec); // We keep specs for unrecognized platforms around for error recovery // during parsing but remove them once parsing is completed. if (VersionSpec->isUnrecognizedPlatform()) { RecognizedSpecs.pop_back(); continue; } bool Inserted = Platforms.insert(VersionSpec->getPlatform()).second; if (!Inserted) { // Rule out multiple version specs referring to the same platform. // For example, we emit an error for /// #available(OSX 10.10, OSX 10.11, *) PlatformKind Platform = VersionSpec->getPlatform(); P.diagnose(VersionSpec->getPlatformLoc(), diag::availability_query_repeated_platform, platformString(Platform)); } } if (!HasOtherPlatformSpec) { SourceLoc InsertWildcardLoc = Specs.back()->getSourceRange().End; P.diagnose(InsertWildcardLoc, diag::availability_query_wildcard_required) .fixItInsertAfter(InsertWildcardLoc, ", *"); } Specs = RecognizedSpecs; } // #available(...) ParserResult<PoundAvailableInfo> Parser::parseStmtConditionPoundAvailable() { SyntaxParsingContext ConditonCtxt(SyntaxContext, SyntaxKind::AvailabilityCondition); SourceLoc PoundLoc = consumeToken(tok::pound_available); if (!Tok.isFollowingLParen()) { diagnose(Tok, diag::avail_query_expected_condition); return makeParserError(); } StructureMarkerRAII ParsingAvailabilitySpecList(*this, Tok); if (ParsingAvailabilitySpecList.isFailed()) { return makeParserError(); } SourceLoc LParenLoc = consumeToken(tok::l_paren); SmallVector<AvailabilitySpec *, 5> Specs; ParserStatus Status = parseAvailabilitySpecList(Specs); for (auto *Spec : Specs) { if (auto *PlatformAgnostic = dyn_cast<PlatformAgnosticVersionConstraintAvailabilitySpec>(Spec)) { diagnose(PlatformAgnostic->getPlatformAgnosticNameLoc(), PlatformAgnostic->isLanguageVersionSpecific() ? diag::pound_available_swift_not_allowed : diag::pound_available_package_description_not_allowed); Status.setIsParseError(); } } SourceLoc RParenLoc; if (parseMatchingToken(tok::r_paren, RParenLoc, diag::avail_query_expected_rparen, LParenLoc)) Status.setIsParseError(); auto *result = PoundAvailableInfo::create(Context, PoundLoc, Specs,RParenLoc); return makeParserResult(Status, result); } ParserStatus Parser::parseAvailabilitySpecList(SmallVectorImpl<AvailabilitySpec *> &Specs) { SyntaxParsingContext AvailabilitySpecContext( SyntaxContext, SyntaxKind::AvailabilitySpecList); ParserStatus Status = makeParserSuccess(); // We don't use parseList() because we want to provide more specific // diagnostics disallowing operators in version specs. while (1) { SyntaxParsingContext AvailabilityEntryContext( SyntaxContext, SyntaxKind::AvailabilityArgument); auto SpecResult = parseAvailabilitySpec(); if (auto *Spec = SpecResult.getPtrOrNull()) { Specs.push_back(Spec); } else { if (SpecResult.hasCodeCompletion()) { return makeParserCodeCompletionStatus(); } Status.setIsParseError(); } // We don't allow binary operators to combine specs. if (Tok.isBinaryOperator()) { diagnose(Tok, diag::avail_query_disallowed_operator, Tok.getText()); consumeToken(); Status.setIsParseError(); } else if (consumeIf(tok::comma)) { // There is more to parse in this list. // Before continuing to parse the next specification, we check that it's // also in the shorthand syntax and provide a more specific diagnostic if // that's not the case. if (Tok.isIdentifierOrUnderscore() && !peekToken().isAny(tok::integer_literal, tok::floating_literal) && !Specs.empty()) { auto Text = Tok.getText(); if (Text == "deprecated" || Text == "renamed" || Text == "introduced" || Text == "message" || Text == "obsoleted" || Text == "unavailable") { auto *Previous = Specs.back(); auto &SourceManager = Context.SourceMgr; auto PreviousSpecText = SourceManager.extractText(L->getCharSourceRangeFromSourceRange( SourceManager, Previous->getSourceRange())); diagnose(Tok, diag::avail_query_argument_and_shorthand_mix_not_allowed, Text, PreviousSpecText); // If this was preceded by a single platform version constraint, we // can guess that the intention was to treat it as 'introduced' and // suggest a fix-it to combine them. if (Specs.size() == 1 && PlatformVersionConstraintAvailabilitySpec::classof(Previous) && Text != "introduced") { auto *PlatformSpec = cast<PlatformVersionConstraintAvailabilitySpec>(Previous); auto PlatformName = platformString(PlatformSpec->getPlatform()); auto PlatformNameEndLoc = PlatformSpec->getPlatformLoc().getAdvancedLoc( PlatformName.size()); diagnose(PlatformSpec->getPlatformLoc(), diag::avail_query_meant_introduced) .fixItInsert(PlatformNameEndLoc, ", introduced:"); } Status.setIsParseError(); break; } } // Otherwise, keep going. } else { break; } } if (Status.isSuccess()) validateAvailabilitySpecList(*this, Specs); return Status; } ParserStatus Parser::parseStmtConditionElement(SmallVectorImpl<StmtConditionElement> &result, Diag<> DefaultID, StmtKind ParentKind, StringRef &BindingKindStr) { ParserStatus Status; // Parse a leading #available condition if present. if (Tok.is(tok::pound_available)) { auto res = parseStmtConditionPoundAvailable(); if (res.isNull() || res.hasCodeCompletion()) { Status |= res; return Status; } BindingKindStr = StringRef(); result.push_back({res.get()}); return Status; } // Handle code completion after the #. if (Tok.is(tok::pound) && peekToken().is(tok::code_complete) && Tok.getLoc().getAdvancedLoc(1) == peekToken().getLoc()) { auto Expr = parseExprPoundCodeCompletion(ParentKind); Status |= Expr; result.push_back(Expr.get()); } // Parse the basic expression case. If we have a leading let/var/case // keyword or an assignment, then we know this is a binding. if (Tok.isNot(tok::kw_let, tok::kw_var, tok::kw_case)) { // If we lack it, then this is theoretically a boolean condition. // However, we also need to handle migrating from Swift 2 syntax, in // which a comma followed by an expression could actually be a pattern // clause followed by a binding. Determine what we have by checking for a // syntactically valid pattern followed by an '=', which can never be a // boolean condition. // // However, if this is the first clause, and we see "x = y", then this is // almost certainly a typo for '==' and definitely not a continuation of // another clause, so parse it as an expression. This also avoids // lookahead + backtracking on simple if conditions that are obviously // boolean conditions. auto isBooleanExpr = [&]() -> bool { Parser::BacktrackingScope Backtrack(*this); return !canParseTypedPattern() || Tok.isNot(tok::equal); }; if (BindingKindStr.empty() || isBooleanExpr()) { auto diagID = result.empty() ? DefaultID : diag::expected_expr_conditional; auto BoolExpr = parseExprBasic(diagID); Status |= BoolExpr; if (BoolExpr.isNull()) return Status; result.push_back(BoolExpr.get()); BindingKindStr = StringRef(); return Status; } } SyntaxParsingContext ConditionCtxt(SyntaxContext); SourceLoc IntroducerLoc; if (Tok.isAny(tok::kw_let, tok::kw_var, tok::kw_case)) { BindingKindStr = Tok.getText(); IntroducerLoc = consumeToken(); } else { // If we lack the leading let/var/case keyword, then we're here because // the user wrote something like "if let x = foo(), y = bar() {". Fix // this by inserting a new 'let' keyword before y. IntroducerLoc = Tok.getLoc(); assert(!BindingKindStr.empty() && "Shouldn't get here without a leading binding"); diagnose(Tok.getLoc(), diag::expected_binding_keyword, BindingKindStr) .fixItInsert(Tok.getLoc(), BindingKindStr.str()+" "); } // We're parsing a conditional binding. assert(CurDeclContext->isLocalContext() && "conditional binding in non-local context?!"); ParserResult<Pattern> ThePattern; if (BindingKindStr == "case") { ConditionCtxt.setCreateSyntax(SyntaxKind::MatchingPatternCondition); // In our recursive parse, remember that we're in a matching pattern. llvm::SaveAndRestore<decltype(InVarOrLetPattern)> T(InVarOrLetPattern, IVOLP_InMatchingPattern); ThePattern = parseMatchingPattern(/*isExprBasic*/ true); } else if (Tok.is(tok::kw_case)) { ConditionCtxt.setCreateSyntax(SyntaxKind::Unknown); // If will probably be a common typo to write "if let case" instead of // "if case let" so detect this and produce a nice fixit. diagnose(IntroducerLoc, diag::wrong_condition_case_location, BindingKindStr) .fixItRemove(IntroducerLoc) .fixItInsertAfter(Tok.getLoc(), " " + BindingKindStr.str()); consumeToken(tok::kw_case); bool wasLet = BindingKindStr == "let"; BindingKindStr = "case"; // In our recursive parse, remember that we're in a var/let pattern. llvm::SaveAndRestore<decltype(InVarOrLetPattern)> T(InVarOrLetPattern, wasLet ? IVOLP_InLet : IVOLP_InVar); ThePattern = parseMatchingPattern(/*isExprBasic*/ true); if (ThePattern.isNonNull()) { auto *P = new (Context) VarPattern(IntroducerLoc, wasLet, ThePattern.get(), /*impl*/false); ThePattern = makeParserResult(Status, P); } } else { ConditionCtxt.setCreateSyntax(SyntaxKind::OptionalBindingCondition); // Otherwise, this is an implicit optional binding "if let". ThePattern = parseMatchingPatternAsLetOrVar(BindingKindStr == "let", IntroducerLoc, /*isExprBasic*/ true); // The let/var pattern is part of the statement. if (Pattern *P = ThePattern.getPtrOrNull()) P->setImplicit(); } ThePattern = parseOptionalPatternTypeAnnotation(ThePattern, BindingKindStr != "case"); if (ThePattern.hasCodeCompletion()) Status.setHasCodeCompletion(); if (ThePattern.isNull()) { // Recover by creating AnyPattern. ThePattern = makeParserResult(new (Context) AnyPattern(PreviousLoc)); } // Conditional bindings must have an initializer. ParserResult<Expr> Init; if (Tok.is(tok::equal)) { SyntaxParsingContext InitCtxt(SyntaxContext, SyntaxKind::InitializerClause); consumeToken(); Init = parseExprBasic(diag::expected_expr_conditional_var); } else { diagnose(Tok, diag::conditional_var_initializer_required); } if (Init.hasCodeCompletion()) Status.setHasCodeCompletion(); if (Init.isNull()) { // Recover by creating ErrorExpr. Init = makeParserResult(new (Context) ErrorExpr(ThePattern.get()->getEndLoc())); } result.push_back({IntroducerLoc, ThePattern.get(), Init.get()}); // Add variable bindings from the pattern to our current scope and mark // them as being having a non-pattern-binding initializer. ThePattern.get()->forEachVariable([&](VarDecl *VD) { setLocalDiscriminator(VD); if (VD->hasName()) addToScope(VD); VD->setHasNonPatternBindingInit(); }); return Status; } /// Parse the condition of an 'if' or 'while'. /// /// condition: /// condition-clause (',' condition-clause)* /// condition-clause: /// expr-basic /// ('var' | 'let' | 'case') pattern '=' expr-basic /// '#available' '(' availability-spec (',' availability-spec)* ')' /// /// The use of expr-basic here disallows trailing closures, which are /// problematic given the curly braces around the if/while body. /// ParserStatus Parser::parseStmtCondition(StmtCondition &Condition, Diag<> DefaultID, StmtKind ParentKind) { SyntaxParsingContext ConditionListCtxt(SyntaxContext, SyntaxKind::ConditionElementList); ParserStatus Status; Condition = StmtCondition(); SmallVector<StmtConditionElement, 4> result; // For error recovery purposes, keep track of the disposition of the last // pattern binding we saw ('let', 'var', or 'case'). StringRef BindingKindStr; // We have a simple comma separated list of clauses, but also need to handle // a variety of common errors situations (including migrating from Swift 2 // syntax). while (true) { SyntaxParsingContext ConditionElementCtxt(SyntaxContext, SyntaxKind::ConditionElement); Status |= parseStmtConditionElement(result, DefaultID, ParentKind, BindingKindStr); if (Status.shouldStopParsing()) break; // If a comma exists consume it and succeed. if (consumeIf(tok::comma)) continue; // If we have an "&&" token followed by a continuation of the statement // condition, then fixit the "&&" to "," and keep going. if (Tok.isAny(tok::oper_binary_spaced, tok::oper_binary_unspaced) && Tok.getText() == "&&") { diagnose(Tok, diag::expected_comma_stmtcondition) .fixItReplaceChars(getEndOfPreviousLoc(), Tok.getRange().getEnd(), ","); consumeToken(); continue; } // Boolean conditions are separated by commas, not the 'where' keyword, as // they were in Swift 2 and earlier. if (Tok.is(tok::kw_where)) { diagnose(Tok, diag::expected_comma_stmtcondition) .fixItReplaceChars(getEndOfPreviousLoc(), Tok.getRange().getEnd(), ","); consumeToken(); continue; } break; }; Condition = Context.AllocateCopy(result); return Status; } /// /// stmt-if: /// 'if' condition stmt-brace stmt-if-else? /// stmt-if-else: /// 'else' stmt-brace /// 'else' stmt-if ParserResult<Stmt> Parser::parseStmtIf(LabeledStmtInfo LabelInfo, bool IfWasImplicitlyInserted) { SyntaxContext->setCreateSyntax(SyntaxKind::IfStmt); SourceLoc IfLoc; if (IfWasImplicitlyInserted) { // The code was invalid due to a missing 'if' (e.g. 'else x < y {') and a // fixit implicitly inserted it. IfLoc = Tok.getLoc(); } else { IfLoc = consumeToken(tok::kw_if); } ParserStatus Status; StmtCondition Condition; ParserResult<BraceStmt> NormalBody; // A scope encloses the condition and true branch for any variables bound // by a conditional binding. The else branch does *not* see these variables. { Scope S(this, ScopeKind::IfVars); auto recoverWithCond = [&](ParserStatus Status, StmtCondition Condition) -> ParserResult<Stmt> { if (Condition.empty()) { SmallVector<StmtConditionElement, 1> ConditionElems; ConditionElems.emplace_back(new (Context) ErrorExpr(IfLoc)); Condition = Context.AllocateCopy(ConditionElems); } auto EndLoc = Condition.back().getEndLoc(); return makeParserResult( Status, new (Context) IfStmt( LabelInfo, IfLoc, Condition, BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true), SourceLoc(), nullptr)); }; if (Tok.is(tok::l_brace)) { SourceLoc LBraceLoc = Tok.getLoc(); diagnose(IfLoc, diag::missing_condition_after_if) .highlight(SourceRange(IfLoc, LBraceLoc)); SmallVector<StmtConditionElement, 1> ConditionElems; ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc)); Condition = Context.AllocateCopy(ConditionElems); } else { Status |= parseStmtCondition(Condition, diag::expected_condition_if, StmtKind::If); if (Status.isError() || Status.hasCodeCompletion()) return recoverWithCond(Status, Condition); } if (Tok.is(tok::kw_else)) { SourceLoc ElseLoc = Tok.getLoc(); diagnose(ElseLoc, diag::unexpected_else_after_if); diagnose(ElseLoc, diag::suggest_removing_else) .fixItRemove(ElseLoc); consumeToken(tok::kw_else); } NormalBody = parseBraceItemList(diag::expected_lbrace_after_if); Status |= NormalBody; if (NormalBody.isNull()) return recoverWithCond(Status, Condition); } // The else branch, if any, is outside of the scope of the condition. SourceLoc ElseLoc; ParserResult<Stmt> ElseBody; if (Tok.is(tok::kw_else)) { ElseLoc = consumeToken(tok::kw_else); bool implicitlyInsertIf = false; if (Tok.isNot(tok::kw_if, tok::l_brace, tok::code_complete)) { // The code looks like 'if ... { ... } else not_if_or_lbrace', so we've // got a problem. If the last bit is 'else ... {' on one line, let's // assume they've forgotten the 'if'. BacktrackingScope backtrack(*this); implicitlyInsertIf = skipUntilTokenOrEndOfLine(tok::l_brace); } if (Tok.is(tok::kw_if) || implicitlyInsertIf) { if (implicitlyInsertIf) { diagnose(ElseLoc, diag::expected_lbrace_or_if_after_else_fixit) .fixItInsertAfter(ElseLoc, " if"); } SyntaxParsingContext ElseIfCtxt(SyntaxContext, SyntaxKind::IfStmt); ElseBody = parseStmtIf(LabeledStmtInfo(), implicitlyInsertIf); } else if (Tok.is(tok::code_complete)) { if (CodeCompletion) CodeCompletion->completeAfterIfStmt(/*hasElse*/true); Status.setHasCodeCompletion(); consumeToken(tok::code_complete); } else { ElseBody = parseBraceItemList(diag::expected_lbrace_or_if_after_else); } Status |= ElseBody; } else if (Tok.is(tok::code_complete)) { if (CodeCompletion) CodeCompletion->completeAfterIfStmt(/*hasElse*/false); Status.setHasCodeCompletion(); consumeToken(tok::code_complete); } return makeParserResult( Status, new (Context) IfStmt(LabelInfo, IfLoc, Condition, NormalBody.get(), ElseLoc, ElseBody.getPtrOrNull())); } /// stmt-guard: /// 'guard' condition 'else' stmt-brace /// ParserResult<Stmt> Parser::parseStmtGuard() { SyntaxContext->setCreateSyntax(SyntaxKind::GuardStmt); SourceLoc GuardLoc = consumeToken(tok::kw_guard); ParserStatus Status; StmtCondition Condition; ParserResult<BraceStmt> Body; auto recoverWithCond = [&](ParserStatus Status, StmtCondition Condition) -> ParserResult<Stmt> { if (Condition.empty()) { SmallVector<StmtConditionElement, 1> ConditionElems; ConditionElems.emplace_back(new (Context) ErrorExpr(GuardLoc)); Condition = Context.AllocateCopy(ConditionElems); } auto EndLoc = Condition.back().getEndLoc(); return makeParserResult( Status, new (Context) GuardStmt( GuardLoc, Condition, BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true))); }; if (Tok.is(tok::l_brace)) { SourceLoc LBraceLoc = Tok.getLoc(); diagnose(GuardLoc, diag::missing_condition_after_guard) .highlight(SourceRange(GuardLoc, LBraceLoc)); SmallVector<StmtConditionElement, 1> ConditionElems; ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc)); Condition = Context.AllocateCopy(ConditionElems); } else { Status |= parseStmtCondition(Condition, diag::expected_condition_guard, StmtKind::Guard); if (Status.isError() || Status.hasCodeCompletion()) { // FIXME: better recovery return recoverWithCond(Status, Condition); } } // Parse the 'else'. If it is missing, and if the following token isn't a { // then the parser is hopelessly lost - just give up instead of spewing. if (!consumeIf(tok::kw_else)) { checkForInputIncomplete(); auto diag = diagnose(Tok, diag::expected_else_after_guard); if (Tok.is(tok::l_brace)) diag.fixItInsert(Tok.getLoc(), "else "); else return recoverWithCond(Status, Condition); } // Before parsing the body, disable all of the bound variables so that they // cannot be used unbound. SmallVector<VarDecl *, 4> Vars; for (auto &elt : Condition) if (auto pattern = elt.getPatternOrNull()) pattern->collectVariables(Vars); Vars.append(DisabledVars.begin(), DisabledVars.end()); llvm::SaveAndRestore<decltype(DisabledVars)> RestoreCurVars(DisabledVars, Vars); llvm::SaveAndRestore<decltype(DisabledVarReason)> RestoreReason(DisabledVarReason, diag::bound_var_guard_body); Body = parseBraceItemList(diag::expected_lbrace_after_guard); if (Body.isNull()) return recoverWithCond(Status, Condition); Status |= Body; return makeParserResult(Status, new (Context) GuardStmt(GuardLoc, Condition, Body.get())); } /// /// stmt-while: /// (identifier ':')? 'while' expr-basic stmt-brace ParserResult<Stmt> Parser::parseStmtWhile(LabeledStmtInfo LabelInfo) { SyntaxContext->setCreateSyntax(SyntaxKind::WhileStmt); SourceLoc WhileLoc = consumeToken(tok::kw_while); Scope S(this, ScopeKind::WhileVars); ParserStatus Status; StmtCondition Condition; auto recoverWithCond = [&](ParserStatus Status, StmtCondition Condition) -> ParserResult<Stmt> { if (Condition.empty()) { SmallVector<StmtConditionElement, 1> ConditionElems; ConditionElems.emplace_back(new (Context) ErrorExpr(WhileLoc)); Condition = Context.AllocateCopy(ConditionElems); } auto EndLoc = Condition.back().getEndLoc(); return makeParserResult( Status, new (Context) WhileStmt( LabelInfo, WhileLoc, Condition, BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true))); }; if (Tok.is(tok::l_brace)) { SourceLoc LBraceLoc = Tok.getLoc(); diagnose(WhileLoc, diag::missing_condition_after_while) .highlight(SourceRange(WhileLoc, LBraceLoc)); SmallVector<StmtConditionElement, 1> ConditionElems; ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc)); Condition = Context.AllocateCopy(ConditionElems); } else { Status |= parseStmtCondition(Condition, diag::expected_condition_while, StmtKind::While); if (Status.isError() || Status.hasCodeCompletion()) return recoverWithCond(Status, Condition); } ParserResult<BraceStmt> Body = parseBraceItemList(diag::expected_lbrace_after_while); Status |= Body; if (Body.isNull()) return recoverWithCond(Status, Condition); return makeParserResult( Status, new (Context) WhileStmt(LabelInfo, WhileLoc, Condition, Body.get())); } /// /// stmt-repeat: /// (identifier ':')? 'repeat' stmt-brace 'while' expr ParserResult<Stmt> Parser::parseStmtRepeat(LabeledStmtInfo labelInfo) { SyntaxContext->setCreateSyntax(SyntaxKind::RepeatWhileStmt); SourceLoc repeatLoc = consumeToken(tok::kw_repeat); ParserStatus status; ParserResult<BraceStmt> body = parseBraceItemList(diag::expected_lbrace_after_repeat); status |= body; if (body.isNull()) body = makeParserResult( body, BraceStmt::create(Context, repeatLoc, {}, PreviousLoc, true)); SourceLoc whileLoc; if (!consumeIf(tok::kw_while, whileLoc)) { diagnose(body.getPtrOrNull()->getEndLoc(), diag::expected_while_after_repeat_body); return body; } ParserResult<Expr> condition; if (Tok.is(tok::l_brace)) { SourceLoc lbraceLoc = Tok.getLoc(); diagnose(whileLoc, diag::missing_condition_after_while); condition = makeParserErrorResult(new (Context) ErrorExpr(lbraceLoc)); } else { condition = parseExpr(diag::expected_expr_repeat_while); status |= condition; if (condition.isNull()) { condition = makeParserErrorResult(new (Context) ErrorExpr(whileLoc)); } } return makeParserResult( status, new (Context) RepeatWhileStmt(labelInfo, repeatLoc, condition.get(), whileLoc, body.get())); } /// /// stmt-do: /// (identifier ':')? 'do' stmt-brace /// (identifier ':')? 'do' stmt-brace stmt-catch+ ParserResult<Stmt> Parser::parseStmtDo(LabeledStmtInfo labelInfo) { SyntaxContext->setCreateSyntax(SyntaxKind::DoStmt); SourceLoc doLoc = consumeToken(tok::kw_do); ParserStatus status; ParserResult<BraceStmt> body = parseBraceItemList(diag::expected_lbrace_after_do); status |= body; if (body.isNull()) body = makeParserResult( body, BraceStmt::create(Context, doLoc, {}, PreviousLoc, true)); // If the next token is 'catch', this is a 'do'/'catch' statement. if (Tok.is(tok::kw_catch)) { SyntaxParsingContext CatchListCtxt(SyntaxContext, SyntaxKind::CatchClauseList); // Parse 'catch' clauses SmallVector<CatchStmt*, 4> allClauses; do { ParserResult<CatchStmt> clause = parseStmtCatch(); status |= clause; if (status.hasCodeCompletion() && clause.isNull()) return makeParserResult<Stmt>(status, nullptr); // parseStmtCatch promises to return non-null unless we are // completing inside the catch's pattern. allClauses.push_back(clause.get()); } while (Tok.is(tok::kw_catch) && !status.hasCodeCompletion()); // Recover from all of the clauses failing to parse by returning a // normal do-statement. if (allClauses.empty()) { assert(status.isError()); return makeParserResult(status, new (Context) DoStmt(labelInfo, doLoc, body.get())); } return makeParserResult(status, DoCatchStmt::create(Context, labelInfo, doLoc, body.get(), allClauses)); } SourceLoc whileLoc; // If we don't see a 'while', this is just the bare 'do' scoping // statement. if (!consumeIf(tok::kw_while, whileLoc)) { return makeParserResult(status, new (Context) DoStmt(labelInfo, doLoc, body.get())); } // But if we do, advise the programmer that it's 'repeat' now. diagnose(doLoc, diag::do_while_now_repeat_while) .fixItReplace(doLoc, "repeat"); status.setIsParseError(); ParserResult<Expr> condition; if (Tok.is(tok::l_brace)) { SourceLoc lbraceLoc = Tok.getLoc(); diagnose(whileLoc, diag::missing_condition_after_while); condition = makeParserErrorResult(new (Context) ErrorExpr(lbraceLoc)); } else { condition = parseExpr(diag::expected_expr_repeat_while); status |= condition; if (condition.isNull() || condition.hasCodeCompletion()) return makeParserResult<Stmt>(status, nullptr); // FIXME: better recovery } return makeParserResult( status, new (Context) RepeatWhileStmt(labelInfo, doLoc, condition.get(), whileLoc, body.get())); } /// stmt-catch: /// 'catch' pattern ('where' expr)? stmt-brace /// /// Note that this is not a "first class" statement; it can only /// appear following a 'do' statement. /// /// This routine promises to return a non-null result unless there was /// a code-completion token in the pattern. ParserResult<CatchStmt> Parser::parseStmtCatch() { SyntaxParsingContext CatchClauseCtxt(SyntaxContext, SyntaxKind::CatchClause); // A catch block has its own scope for variables bound out of the pattern. Scope S(this, ScopeKind::CatchVars); SourceLoc catchLoc = consumeToken(tok::kw_catch); SmallVector<VarDecl*, 4> boundDecls; ParserStatus status; GuardedPattern pattern; parseGuardedPattern(*this, pattern, status, boundDecls, GuardedPatternContext::Catch, /* isFirst */ true); if (status.hasCodeCompletion()) { return makeParserCodeCompletionResult<CatchStmt>(); } auto bodyResult = parseBraceItemList(diag::expected_lbrace_after_catch); status |= bodyResult; if (bodyResult.isNull()) { bodyResult = makeParserErrorResult(BraceStmt::create(Context, PreviousLoc, {}, PreviousLoc, /*implicit=*/ true)); } auto result = new (Context) CatchStmt(catchLoc, pattern.ThePattern, pattern.WhereLoc, pattern.Guard, bodyResult.get()); return makeParserResult(status, result); } static bool isStmtForCStyle(Parser &P) { // If we have a leading identifier followed by a ':' or 'in', or have a // 'case', then this is obviously a for-each loop. "for in ..." is malformed // but it's obviously not a C-style for. if ((P.Tok.isIdentifierOrUnderscore() && P.peekToken().isAny(tok::colon, tok::kw_in)) || P.Tok.isAny(tok::kw_case, tok::kw_in)) return false; // Otherwise, we have to look forward if we see ';' in control part. Parser::BacktrackingScope Backtrack(P); // The condition of a c-style-for loop can be parenthesized. auto HasLParen = P.consumeIf(tok::l_paren); // Skip until we see ';', or something that ends control part. while (true) { if (P.Tok.isAny(tok::eof, tok::kw_in, tok::l_brace, tok::r_brace, tok::r_paren) || P.isStartOfStmt()) return false; // If we saw newline before ';', consider it is a foreach statement. if (!HasLParen && P.Tok.isAtStartOfLine()) return false; if (P.Tok.is(tok::semi)) return true; P.skipSingle(); } } /// /// stmt-for-each: /// (identifier ':')? 'for' pattern 'in' expr-basic \ /// ('where' expr-basic)? stmt-brace ParserResult<Stmt> Parser::parseStmtForEach(LabeledStmtInfo LabelInfo) { SyntaxContext->setCreateSyntax(SyntaxKind::ForInStmt); SourceLoc ForLoc = consumeToken(tok::kw_for); ParserStatus Status; ParserResult<Pattern> pattern; ParserResult<Expr> Container; // The C-style for loop which was supported in Swift2 and foreach-style-for // loop are conflated together into a single keyword, so we have to do some // lookahead to resolve what is going on. bool IsCStyleFor = isStmtForCStyle(*this); auto StartOfControl = Tok.getLoc(); // Parse the pattern. This is either 'case <refutable pattern>' or just a // normal pattern. if (consumeIf(tok::kw_case)) { llvm::SaveAndRestore<decltype(InVarOrLetPattern)> T(InVarOrLetPattern, Parser::IVOLP_InMatchingPattern); pattern = parseMatchingPattern(/*isExprBasic*/true); pattern = parseOptionalPatternTypeAnnotation(pattern, /*isOptional*/false); } else if (!IsCStyleFor || Tok.is(tok::kw_var)) { // Change the parser state to know that the pattern we're about to parse is // implicitly mutable. Bound variables can be changed to mutable explicitly // if desired by using a 'var' pattern. assert(InVarOrLetPattern == IVOLP_NotInVarOrLet && "for-each loops cannot exist inside other patterns"); InVarOrLetPattern = IVOLP_ImplicitlyImmutable; pattern = parseTypedPattern(); assert(InVarOrLetPattern == IVOLP_ImplicitlyImmutable); InVarOrLetPattern = IVOLP_NotInVarOrLet; } SourceLoc InLoc; if (pattern.isNull()) { // Recover by creating a "_" pattern. pattern = makeParserErrorResult(new (Context) AnyPattern(SourceLoc())); consumeIf(tok::kw_in, InLoc); } else if (!IsCStyleFor) { parseToken(tok::kw_in, InLoc, diag::expected_foreach_in); } // Bound variables all get their initial values from the generator. pattern.get()->markHasNonPatternBindingInit(); if (IsCStyleFor) { // Skip until start of body part. if (Tok.is(tok::l_paren)) { skipSingle(); } else { // If not parenthesized, don't run over the line. while (Tok.isNot(tok::eof, tok::r_brace, tok::l_brace, tok::code_complete) && !Tok.isAtStartOfLine()) skipSingle(); } if (Tok.is(tok::code_complete)) return makeParserCodeCompletionStatus(); assert(StartOfControl != Tok.getLoc()); SourceRange ControlRange(StartOfControl, PreviousLoc); Container = makeParserErrorResult(new (Context) ErrorExpr(ControlRange)); diagnose(ForLoc, diag::c_style_for_stmt_removed) .highlight(ControlRange); Status = makeParserError(); } else if (Tok.is(tok::l_brace)) { SourceLoc LBraceLoc = Tok.getLoc(); diagnose(LBraceLoc, diag::expected_foreach_container); Container = makeParserErrorResult(new (Context) ErrorExpr(LBraceLoc)); } else if (Tok.is(tok::code_complete)) { Container = makeParserResult(new (Context) CodeCompletionExpr(Tok.getLoc())); Container.setHasCodeCompletion(); Status |= Container; if (CodeCompletion) CodeCompletion->completeForEachSequenceBeginning( cast<CodeCompletionExpr>(Container.get())); consumeToken(tok::code_complete); } else { Container = parseExprBasic(diag::expected_foreach_container); Status |= Container; if (Container.isNull()) Container = makeParserErrorResult(new (Context) ErrorExpr(Tok.getLoc())); if (Container.isParseError()) // Recover. skipUntilDeclStmtRBrace(tok::l_brace, tok::kw_where); } // Introduce a new scope and place the variables in the pattern into that // scope. // FIXME: We may want to merge this scope with the scope introduced by // the stmt-brace, as in C++. Scope S(this, ScopeKind::ForeachVars); // Introduce variables to the current scope. addPatternVariablesToScope(pattern.get()); // Parse the 'where' expression if present. ParserResult<Expr> Where; if (Tok.is(tok::kw_where)) { SyntaxParsingContext WhereClauseCtxt(SyntaxContext, SyntaxKind::WhereClause); consumeToken(); Where = parseExprBasic(diag::expected_foreach_where_expr); if (Where.isNull()) Where = makeParserErrorResult(new (Context) ErrorExpr(Tok.getLoc())); Status |= Where; } // stmt-brace ParserResult<BraceStmt> Body = parseBraceItemList(diag::expected_foreach_lbrace); Status |= Body; if (Body.isNull()) Body = makeParserResult( Body, BraceStmt::create(Context, ForLoc, {}, PreviousLoc, true)); return makeParserResult( Status, new (Context) ForEachStmt(LabelInfo, ForLoc, pattern.get(), InLoc, Container.get(), Where.getPtrOrNull(), Body.get())); } /// /// stmt-switch: /// (identifier ':')? 'switch' expr-basic '{' stmt-case+ '}' ParserResult<Stmt> Parser::parseStmtSwitch(LabeledStmtInfo LabelInfo) { SyntaxContext->setCreateSyntax(SyntaxKind::SwitchStmt); SourceLoc SwitchLoc = consumeToken(tok::kw_switch); ParserStatus Status; ParserResult<Expr> SubjectExpr; SourceLoc SubjectLoc = Tok.getLoc(); if (Tok.is(tok::l_brace)) { diagnose(SubjectLoc, diag::expected_switch_expr); SubjectExpr = makeParserErrorResult(new (Context) ErrorExpr(SubjectLoc)); } else { SubjectExpr = parseExprBasic(diag::expected_switch_expr); if (SubjectExpr.hasCodeCompletion()) { return makeParserCodeCompletionResult<Stmt>(); } if (SubjectExpr.isNull()) { SubjectExpr = makeParserErrorResult(new (Context) ErrorExpr(SubjectLoc)); } Status |= SubjectExpr; } if (!Tok.is(tok::l_brace)) { diagnose(Tok, diag::expected_lbrace_after_switch); return nullptr; } SourceLoc lBraceLoc = consumeToken(tok::l_brace); SourceLoc rBraceLoc; SmallVector<ASTNode, 8> cases; Status |= parseStmtCases(cases, /*IsActive=*/true); // We cannot have additional cases after a default clause. Complain on // the first offender. bool hasDefault = false; for (auto Element : cases) { if (!Element.is<Stmt*>()) continue; auto *CS = cast<CaseStmt>(Element.get<Stmt*>()); if (hasDefault) { diagnose(CS->getLoc(), diag::case_after_default); break; } hasDefault |= CS->isDefault(); } if (parseMatchingToken(tok::r_brace, rBraceLoc, diag::expected_rbrace_switch, lBraceLoc)) { Status.setIsParseError(); } return makeParserResult( Status, SwitchStmt::create(LabelInfo, SwitchLoc, SubjectExpr.get(), lBraceLoc, cases, rBraceLoc, Context)); } ParserStatus Parser::parseStmtCases(SmallVectorImpl<ASTNode> &cases, bool IsActive) { SyntaxParsingContext CasesContext(SyntaxContext, SyntaxKind::SwitchCaseList); ParserStatus Status; while (Tok.isNot(tok::r_brace, tok::eof, tok::pound_endif, tok::pound_elseif, tok::pound_else)) { if (isAtStartOfSwitchCase(*this)) { ParserResult<CaseStmt> Case = parseStmtCase(IsActive); Status |= Case; if (Case.isNonNull()) cases.emplace_back(Case.get()); } else if (Tok.is(tok::pound_if)) { // '#if' in 'case' position can enclose one or more 'case' or 'default' // clauses. auto IfConfigResult = parseIfConfig( [&](SmallVectorImpl<ASTNode> &Elements, bool IsActive) { parseStmtCases(Elements, IsActive); }); Status |= IfConfigResult; if (auto ICD = IfConfigResult.getPtrOrNull()) { cases.emplace_back(ICD); for (auto &Entry : ICD->getActiveClauseElements()) { if (Entry.is<Decl*>() && (isa<IfConfigDecl>(Entry.get<Decl*>()))) // Don't hoist nested '#if'. continue; assert((Entry.is<Stmt*>() && isa<CaseStmt>(Entry.get<Stmt*>())) || (Entry.is<Decl*>() && isa<PoundDiagnosticDecl>(Entry.get<Decl*>()))); cases.push_back(Entry); } } } else if (Tok.is(tok::pound_warning) || Tok.is(tok::pound_error)) { auto PoundDiagnosticResult = parseDeclPoundDiagnostic(); Status |= PoundDiagnosticResult; if (auto PDD = PoundDiagnosticResult.getPtrOrNull()) { cases.emplace_back(PDD); } } else if (Tok.is(tok::code_complete)) { if (CodeCompletion) CodeCompletion->completeCaseStmtKeyword(); consumeToken(tok::code_complete); return makeParserCodeCompletionStatus(); } else { // If there are non-case-label statements at the start of the switch body, // raise an error and recover by discarding them. diagnose(Tok, diag::stmt_in_switch_not_covered_by_case); while (Tok.isNot(tok::r_brace, tok::eof, tok::pound_elseif, tok::pound_else, tok::pound_endif) && !isTerminatorForBraceItemListKind(BraceItemListKind::Case, {})) { skipSingle(); } } } return Status; } static ParserStatus parseStmtCase(Parser &P, SourceLoc &CaseLoc, SmallVectorImpl<CaseLabelItem> &LabelItems, SmallVectorImpl<VarDecl *> &BoundDecls, SourceLoc &ColonLoc, Optional<MutableArrayRef<VarDecl *>> &CaseBodyDecls) { SyntaxParsingContext CaseContext(P.SyntaxContext, SyntaxKind::SwitchCaseLabel); ParserStatus Status; bool isFirst = true; CaseLoc = P.consumeToken(tok::kw_case); { SyntaxParsingContext ListContext(P.SyntaxContext, SyntaxKind::CaseItemList); while (true) { SyntaxParsingContext ItemContext(P.SyntaxContext, SyntaxKind::CaseItem); GuardedPattern PatternResult; parseGuardedPattern(P, PatternResult, Status, BoundDecls, GuardedPatternContext::Case, isFirst); LabelItems.emplace_back(PatternResult.ThePattern, PatternResult.WhereLoc, PatternResult.Guard); isFirst = false; if (!P.consumeIf(tok::comma)) break; } // Grab the first case label item pattern and use it to initialize the case // body var decls. SmallVector<VarDecl *, 4> tmp; LabelItems.front().getPattern()->collectVariables(tmp); auto Result = P.Context.AllocateUninitialized<VarDecl *>(tmp.size()); for (unsigned i : indices(tmp)) { auto *vOld = tmp[i]; auto *vNew = new (P.Context) VarDecl( /*IsStatic*/ false, vOld->getIntroducer(), false /*IsCaptureList*/, vOld->getNameLoc(), vOld->getName(), vOld->getDeclContext()); vNew->setHasNonPatternBindingInit(); vNew->setImplicit(); Result[i] = vNew; } CaseBodyDecls.emplace(Result); } ColonLoc = P.Tok.getLoc(); if (!P.Tok.is(tok::colon)) { P.diagnose(P.Tok, diag::expected_case_colon, "case"); Status.setIsParseError(); } else P.consumeToken(tok::colon); return Status; } static ParserStatus parseStmtCaseDefault(Parser &P, SourceLoc &CaseLoc, SmallVectorImpl<CaseLabelItem> &LabelItems, SourceLoc &ColonLoc) { SyntaxParsingContext CaseContext(P.SyntaxContext, SyntaxKind::SwitchDefaultLabel); ParserStatus Status; CaseLoc = P.consumeToken(tok::kw_default); // We don't allow 'where' guards on a 'default' block. For recovery // parse one if present. SourceLoc WhereLoc; ParserResult<Expr> Guard; if (P.Tok.is(tok::kw_where)) { P.diagnose(P.Tok, diag::default_with_where); WhereLoc = P.consumeToken(tok::kw_where); Guard = P.parseExpr(diag::expected_case_where_expr); Status |= Guard; } ColonLoc = P.Tok.getLoc(); if (!P.Tok.is(tok::colon)) { P.diagnose(P.Tok, diag::expected_case_colon, "default"); Status.setIsParseError(); } else P.consumeToken(tok::colon); // Create an implicit AnyPattern to represent the default match. auto Any = new (P.Context) AnyPattern(CaseLoc); LabelItems.push_back( CaseLabelItem::getDefault(Any, WhereLoc, Guard.getPtrOrNull())); return Status; } namespace { struct FallthroughFinder : ASTWalker { FallthroughStmt *result; FallthroughFinder() : result(nullptr) {} // We walk through statements. If we find a fallthrough, then we got what // we came for. std::pair<bool, Stmt *> walkToStmtPre(Stmt *s) override { if (auto *f = dyn_cast<FallthroughStmt>(s)) { result = f; } return {true, s}; } // Expressions, patterns and decls cannot contain fallthrough statements, so // there is no reason to walk into them. std::pair<bool, Expr *> walkToExprPre(Expr *e) override { return {false, e}; } std::pair<bool, Pattern *> walkToPatternPre(Pattern *p) override { return {false, p}; } bool walkToDeclPre(Decl *d) override { return false; } bool walkToTypeLocPre(TypeLoc &tl) override { return false; } bool walkToTypeReprPre(TypeRepr *t) override { return false; } static FallthroughStmt *findFallthrough(Stmt *s) { FallthroughFinder finder; s->walk(finder); return finder.result; } }; } // end anonymous namespace ParserResult<CaseStmt> Parser::parseStmtCase(bool IsActive) { SyntaxParsingContext CaseContext(SyntaxContext, SyntaxKind::SwitchCase); // A case block has its own scope for variables bound out of the pattern. Scope S(this, ScopeKind::CaseVars, !IsActive); ParserStatus Status; SmallVector<CaseLabelItem, 2> CaseLabelItems; SmallVector<VarDecl *, 4> BoundDecls; SourceLoc UnknownAttrLoc; while (Tok.is(tok::at_sign)) { SyntaxParsingContext AttrCtx(SyntaxContext, SyntaxKind::Attribute); if (peekToken().isContextualKeyword("unknown")) { if (!UnknownAttrLoc.isValid()) { UnknownAttrLoc = consumeToken(tok::at_sign); } else { diagnose(Tok, diag::duplicate_attribute, false); diagnose(UnknownAttrLoc, diag::previous_attribute, false); consumeToken(tok::at_sign); } consumeIdentifier(); SyntaxParsingContext Args(SyntaxContext, SyntaxKind::TokenList); if (Tok.is(tok::l_paren)) { diagnose(Tok, diag::unexpected_lparen_in_attribute, "unknown"); skipSingle(); } } else { consumeToken(tok::at_sign); diagnose(Tok, diag::unknown_attribute, Tok.getText()); consumeIdentifier(); SyntaxParsingContext Args(SyntaxContext, SyntaxKind::TokenList); if (Tok.is(tok::l_paren)) skipSingle(); } } SourceLoc CaseLoc; SourceLoc ColonLoc; Optional<MutableArrayRef<VarDecl *>> CaseBodyDecls; if (Tok.is(tok::kw_case)) { Status |= ::parseStmtCase(*this, CaseLoc, CaseLabelItems, BoundDecls, ColonLoc, CaseBodyDecls); } else if (Tok.is(tok::kw_default)) { Status |= parseStmtCaseDefault(*this, CaseLoc, CaseLabelItems, ColonLoc); } else { llvm_unreachable("isAtStartOfSwitchCase() lied."); } assert(!CaseLabelItems.empty() && "did not parse any labels?!"); // Add a scope so that the parser can find our body bound decls if it emits // optimized accesses. Optional<Scope> BodyScope; if (CaseBodyDecls) { BodyScope.emplace(this, ScopeKind::CaseVars); for (auto *v : *CaseBodyDecls) { setLocalDiscriminator(v); // If we had any bad redefinitions, we already diagnosed them against the // first case label item. if (v->hasName()) addToScope(v, false /*diagnoseRedefinitions*/); } } SmallVector<ASTNode, 8> BodyItems; SourceLoc StartOfBody = Tok.getLoc(); if (Tok.isNot(tok::r_brace) && !isAtStartOfSwitchCase(*this)) { Status |= parseBraceItems(BodyItems, BraceItemListKind::Case); } else if (Status.isSuccess()) { diagnose(CaseLoc, diag::case_stmt_without_body, CaseLabelItems.back().isDefault()) .highlight(SourceRange(CaseLoc, ColonLoc)) .fixItInsertAfter(ColonLoc, " break"); } BraceStmt *Body; if (BodyItems.empty()) { Body = BraceStmt::create(Context, PreviousLoc, ArrayRef<ASTNode>(), PreviousLoc, /*implicit=*/true); } else { Body = BraceStmt::create(Context, StartOfBody, BodyItems, PreviousLoc, /*implicit=*/true); } return makeParserResult( Status, CaseStmt::create(Context, CaseLoc, CaseLabelItems, UnknownAttrLoc, ColonLoc, Body, CaseBodyDecls, None, FallthroughFinder::findFallthrough(Body))); } /// stmt-pound-assert: /// '#assert' '(' expr (',' string_literal)? ')' ParserResult<Stmt> Parser::parseStmtPoundAssert() { SyntaxContext->setCreateSyntax(SyntaxKind::PoundAssertStmt); SourceLoc startLoc = consumeToken(tok::pound_assert); SourceLoc endLoc; if (Tok.isNot(tok::l_paren)) { diagnose(Tok, diag::pound_assert_expected_lparen); return makeParserError(); } SourceLoc LBLoc = consumeToken(tok::l_paren); auto conditionExprResult = parseExpr(diag::pound_assert_expected_expression); if (conditionExprResult.isParseError()) return ParserStatus(conditionExprResult); StringRef message; if (consumeIf(tok::comma)) { if (Tok.isNot(tok::string_literal)) { diagnose(Tok.getLoc(), diag::pound_assert_expected_string_literal); return makeParserError(); } auto messageOpt = getStringLiteralIfNotInterpolated(Tok.getLoc(), "'#assert' message"); consumeToken(); if (!messageOpt) return makeParserError(); message = *messageOpt; } if (parseMatchingToken(tok::r_paren, endLoc, diag::pound_assert_expected_rparen, LBLoc)) { return makeParserError(); } // We check this after consuming everything, so that the SyntaxContext // understands this statement even when the feature is disabled. if (!Context.LangOpts.EnableExperimentalStaticAssert) { diagnose(startLoc, diag::pound_assert_disabled); return makeParserError(); } return makeParserResult<Stmt>(new (Context) PoundAssertStmt( SourceRange(startLoc, endLoc), conditionExprResult.get(), message)); }
#ifndef BOOST_ASTRONOMY_IO_IMAGE_EXTENSION_HDU_HPP #define BOOST_ASTRONOMY_IO_IMAGE_EXTENSION_HDU_HPP #include <string> #include <vector> #include <cstddef> #include <valarray> #include <boost/astronomy/io/hdu.hpp> #include <boost/astronomy/io/extension_hdu.hpp> #include <boost/astronomy/io/image.hpp> namespace boost { namespace astronomy { namespace io { template <bitpix DataType> struct image_extension : public boost::astronomy::io::extension_hdu { protected: image<DataType> data; public: image_extension(std::fstream &file) : extension_hdu(file) { //read image according to dimension specified by naxis switch (this->naxis()) { case 0: break; case 1: data.read_image(file, this->naxis(1), 1); break; case 2: data.read_image(file, this->naxis(1), this->naxis(2)); break; default: data.read_image(file, this->naxis(1), std::accumulate(this->naxis_.begin()+ 1, this->naxis_.end(), 0, std::multiplies<std::size_t>())); break; } set_unit_end(file); } image_extension(std::fstream &file, hdu const& other) : extension_hdu(file, other) { //read image according to dimension specified by naxis switch (this->naxis()) { case 0: break; case 1: data.read_image(file, this->naxis(1), 1); break; case 2: data.read_image(file, this->naxis(1), this->naxis(2)); break; default: data.read_image(file, this->naxis(1), std::accumulate(this->naxis_.begin()+ 1, this->naxis_.end(), 0, std::multiplies<std::size_t>())); break; } set_unit_end(file); } image_extension(std::fstream &file, std::streampos pos) : extension_hdu(file, pos) { //read image according to dimension specified by naxis switch (this->naxis()) { case 0: break; case 1: data.read_image(file, this->naxis(1), 1); break; case 2: data.read_image(file, this->naxis(1), this->naxis(2)); break; default: data.read_image(file, this->naxis(1), std::accumulate(this->naxis_.begin()+ 1, this->naxis_.end(), 0, std::multiplies<std::size_t>())); break; } set_unit_end(file); } }; }}} //namespace boost::astronomy::io #endif // !BOOST_ASTRONOMY_IO_IMAGE_EXTENSION_HDU_HPP
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_CommonStructs_hpp #define msr_airlib_CommonStructs_hpp #include "common/Common.hpp" #include <ostream> namespace msr { namespace airlib { //velocity struct Twist { Vector3r linear, angular; Twist() {} Twist(const Vector3r& linear_val, const Vector3r& angular_val) : linear(linear_val), angular(angular_val) { } static const Twist zero() { static const Twist zero_twist(Vector3r::Zero(), Vector3r::Zero()); return zero_twist; } }; //force & torque struct Wrench { Vector3r force, torque; Wrench() {} Wrench(const Vector3r& force_val, const Vector3r& torque_val) : force(force_val), torque(torque_val) { } //support basic arithmatic Wrench operator+(const Wrench& other) const { Wrench result; result.force = this->force + other.force; result.torque = this->torque + other.torque; return result; } Wrench operator+=(const Wrench& other) { force += other.force; torque += other.torque; return *this; } Wrench operator-(const Wrench& other) const { Wrench result; result.force = this->force - other.force; result.torque = this->torque - other.torque; return result; } Wrench operator-=(const Wrench& other) { force -= other.force; torque -= other.torque; return *this; } static const Wrench zero() { static const Wrench zero_wrench(Vector3r::Zero(), Vector3r::Zero()); return zero_wrench; } }; struct Momentums { Vector3r linear; Vector3r angular; Momentums() {} Momentums(const Vector3r& linear_val, const Vector3r& angular_val) : linear(linear_val), angular(angular_val) { } static const Momentums zero() { static const Momentums zero_val(Vector3r::Zero(), Vector3r::Zero()); return zero_val; } }; struct Accelerations { Vector3r linear; Vector3r angular; Accelerations() {} Accelerations(const Vector3r& linear_val, const Vector3r& angular_val) : linear(linear_val), angular(angular_val) { } static const Accelerations zero() { static const Accelerations zero_val(Vector3r::Zero(), Vector3r::Zero()); return zero_val; } }; struct PoseWithCovariance { VectorMath::Pose pose; vector<real_T> covariance; //36 elements, 6x6 matrix PoseWithCovariance() : covariance(36, 0) {} }; struct PowerSupply { vector<real_T> voltage, current; }; struct TwistWithCovariance { Twist twist; vector<real_T> covariance; //36 elements, 6x6 matrix TwistWithCovariance() : covariance(36, 0) {} }; struct Joystick { vector<float> axes; vector<int> buttons; }; struct Odometry { PoseWithCovariance pose; TwistWithCovariance twist; }; struct GeoPoint { double latitude = 0, longitude = 0; float altitude = 0; GeoPoint() {} GeoPoint(double latitude_val, double longitude_val, float altitude_val) { set(latitude_val, longitude_val, altitude_val); } void set(double latitude_val, double longitude_val, float altitude_val) { latitude = latitude_val, longitude = longitude_val; altitude = altitude_val; } friend std::ostream& operator<<(std::ostream &os, GeoPoint const &g) { return os << "[" << g.latitude << ", " << g.longitude << ", " << g.altitude << "]"; } std::string to_string() const { return std::to_string(latitude) + string(", ") + std::to_string(longitude) + string(", ") + std::to_string(altitude); } }; struct HomeGeoPoint { GeoPoint home_geo_point; double lat_rad, lon_rad; double cos_lat, sin_lat; HomeGeoPoint() {} HomeGeoPoint(const GeoPoint& home_geo_point_val) { initialize(home_geo_point_val); } void initialize(const GeoPoint& home_geo_point_val) { home_geo_point = home_geo_point_val; lat_rad = Utils::degreesToRadians(home_geo_point.latitude); lon_rad = Utils::degreesToRadians(home_geo_point.longitude); cos_lat = cos(lat_rad); sin_lat = sin(lat_rad); } }; struct ProjectionMatrix { float matrix[4][4]; void setTo(float val) { for (auto i = 0; i < 4; ++i) for (auto j = 0; j < 4; ++j) matrix[i][j] = val; } }; struct CollisionInfo { bool has_collided = false; Vector3r normal = Vector3r::Zero(); Vector3r impact_point = Vector3r::Zero(); Vector3r position = Vector3r::Zero(); real_T penetration_depth = 0; TTimePoint time_stamp = 0; unsigned int collision_count = 0; std::string object_name; int object_id = -1; CollisionInfo() {} CollisionInfo(bool has_collided_val, const Vector3r& normal_val, const Vector3r& impact_point_val, const Vector3r& position_val, real_T penetration_depth_val, TTimePoint time_stamp_val, const std::string& object_name_val, int object_id_val) : has_collided(has_collided_val), normal(normal_val), impact_point(impact_point_val), position(position_val), penetration_depth(penetration_depth_val), time_stamp(time_stamp_val), object_name(object_name_val), object_id(object_id_val) { } }; struct CameraInfo { Pose pose; float fov; ProjectionMatrix proj_mat; CameraInfo() {} CameraInfo(const Pose& pose_val, float fov_val, const ProjectionMatrix& proj_mat_val) : pose(pose_val), fov(fov_val), proj_mat(proj_mat_val) { } }; struct CollisionResponse { unsigned int collision_count_raw = 0; unsigned int collision_count_non_resting = 0; TTimePoint collision_time_stamp = 0; }; struct GeoPose { EIGEN_MAKE_ALIGNED_OPERATOR_NEW Quaternionr orientation; GeoPoint position; }; struct RCData { TTimePoint timestamp = 0; //pitch, roll, yaw should be in range -1 to 1 //switches should be integer value indicating its state, 0=on, 1=off for example. float pitch = 0, roll = 0, throttle = 0, yaw = 0; float left_z = 0, right_z = 0; uint16_t switches = 0; std::string vendor_id = ""; bool is_initialized = false; //is RC connected? bool is_valid = false; //must be true for data to be valid unsigned int getSwitch(uint16_t index) const { return switches && (1 << index) ? 1 : 0; } void add(const RCData& other) { pitch += other.pitch; roll += other.roll; throttle += other.throttle; yaw += other.yaw; } void subtract(const RCData& other) { pitch -= other.pitch; roll -= other.roll; throttle -= other.throttle; yaw -= other.yaw; } void divideBy(float k) { pitch /= k; roll /= k; throttle /= k; yaw /= k; } bool isAnyMoreThan(float k) { using std::abs; return abs(pitch) > k || abs(roll) > k || abs(throttle) > k || abs(yaw) > k; } string toString() { return Utils::stringf("RCData[pitch=%f, roll=%f, throttle=%f, yaw=%f]", pitch, roll, throttle, yaw); } }; struct LidarData { TTimePoint time_stamp = 0; vector<real_T> point_cloud; Pose pose; LidarData() {} }; }} //namespace #endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * OPCODE - Optimized Collision Detection * Copyright (C) 2001 Pierre Terdiman * Homepage: http://www.codercorner.com/Opcode.htm */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains code for a tree collider. * \file OPC_TreeCollider.cpp * \author Pierre Terdiman * \date March, 20, 2001 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains an AABB tree collider. * This class performs a collision test between two AABB trees. * * \class AABBTreeCollider * \author Pierre Terdiman * \version 1.3 * \date March, 20, 2001 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Precompiled Header #include "Stdafx.h" using namespace Opcode; #include "OPC_BoxBoxOverlap.h" #include "OPC_TriBoxOverlap.h" #include "OPC_TriTriOverlap.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Constructor. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AABBTreeCollider::AABBTreeCollider() : mIMesh0 (null), mIMesh1 (null), mNbBVBVTests (0), mNbPrimPrimTests (0), mNbBVPrimTests (0), mFullBoxBoxTest (true), mFullPrimBoxTest (true) { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Destructor. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AABBTreeCollider::~AABBTreeCollider() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Validates current settings. You should call this method after all the settings and callbacks have been defined. * \return null if everything is ok, else a string describing the problem */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const char* AABBTreeCollider::ValidateSettings() { if(TemporalCoherenceEnabled() && !FirstContactEnabled()) return "Temporal coherence only works with ""First contact"" mode!"; return null; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Generic collision query for generic OPCODE models. After the call, access the results with: * - GetContactStatus() * - GetNbPairs() * - GetPairs() * * \param cache [in] collision cache for model pointers and a colliding pair of primitives * \param world0 [in] world matrix for first object * \param world1 [in] world matrix for second object * \return true if success * \warning SCALE NOT SUPPORTED. The matrices must contain rotation & translation parts only. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABBTreeCollider::Collide(BVTCache& cache, const Matrix4x4* world0, const Matrix4x4* world1) { // Checkings if(!cache.Model0 || !cache.Model1) return false; if(cache.Model0->HasLeafNodes()!=cache.Model1->HasLeafNodes()) return false; if(cache.Model0->IsQuantized()!=cache.Model1->IsQuantized()) return false; /* Rules: - perform hull test - when hulls collide, disable hull test - if meshes overlap, reset countdown - if countdown reaches 0, enable hull test */ #ifdef __MESHMERIZER_H__ // Handle hulls if(cache.HullTest) { if(cache.Model0->GetHull() && cache.Model1->GetHull()) { struct Local { static Point* SVCallback(const Point& sv, udword& previndex, udword user_data) { CollisionHull* Hull = (CollisionHull*)user_data; previndex = Hull->ComputeSupportingVertex(sv, previndex); return (Point*)&Hull->GetVerts()[previndex]; } }; bool Collide; if(0) { static GJKEngine GJK; -- not thread safe, store in ThreadLocalData static bool GJKInitDone=false; -- not thread safe, to be removed if(!GJKInitDone) { GJK.Enable(GJK_BACKUP_PROCEDURE); GJK.Enable(GJK_DEGENERATE); GJK.Enable(GJK_HILLCLIMBING); GJKInitDone = true; } GJK.SetCallbackObj0(Local::SVCallback); GJK.SetCallbackObj1(Local::SVCallback); GJK.SetUserData0(udword(cache.Model0->GetHull())); GJK.SetUserData1(udword(cache.Model1->GetHull())); Collide = GJK.Collide(*world0, *world1, &cache.SepVector); } else { static SVEngine SVE; -- not thread safe, store in ThreadLocalData SVE.SetCallbackObj0(Local::SVCallback); SVE.SetCallbackObj1(Local::SVCallback); SVE.SetUserData0(udword(cache.Model0->GetHull())); SVE.SetUserData1(udword(cache.Model1->GetHull())); Collide = SVE.Collide(*world0, *world1, &cache.SepVector); } if(!Collide) { // Reset stats & contact status mFlags &= ~OPC_CONTACT; mNbBVBVTests = 0; mNbPrimPrimTests = 0; mNbBVPrimTests = 0; mPairs.Reset(); return true; } } } // Here, hulls collide cache.HullTest = false; #endif // __MESHMERIZER_H__ // Checkings if(!Setup(cache.Model0->GetMeshInterface(), cache.Model1->GetMeshInterface())) return false; // Simple double-dispatch bool Status; if(!cache.Model0->HasLeafNodes()) { if(cache.Model0->IsQuantized()) { const AABBQuantizedNoLeafTree* T0 = static_cast<const AABBQuantizedNoLeafTree *>(cache.Model0->GetTree()); const AABBQuantizedNoLeafTree* T1 = static_cast<const AABBQuantizedNoLeafTree *>(cache.Model1->GetTree()); Status = Collide(T0, T1, world0, world1, &cache); } else { const AABBNoLeafTree* T0 = static_cast<const AABBNoLeafTree *>(cache.Model0->GetTree()); const AABBNoLeafTree* T1 = static_cast<const AABBNoLeafTree *>(cache.Model1->GetTree()); Status = Collide(T0, T1, world0, world1, &cache); } } else { if(cache.Model0->IsQuantized()) { const AABBQuantizedTree* T0 = static_cast<const AABBQuantizedTree *>(cache.Model0->GetTree()); const AABBQuantizedTree* T1 = static_cast<const AABBQuantizedTree *>(cache.Model1->GetTree()); Status = Collide(T0, T1, world0, world1, &cache); } else { const AABBCollisionTree* T0 = static_cast<const AABBCollisionTree *>(cache.Model0->GetTree()); const AABBCollisionTree* T1 = static_cast<const AABBCollisionTree *>(cache.Model1->GetTree()); Status = Collide(T0, T1, world0, world1, &cache); } } #ifdef __MESHMERIZER_H__ if(Status) { // Reset counter as long as overlap occurs if(GetContactStatus()) cache.ResetCountDown(); // Enable hull test again when counter reaches zero cache.CountDown--; if(!cache.CountDown) { cache.ResetCountDown(); cache.HullTest = true; } } #endif return Status; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Initializes a collision query : * - reset stats & contact status * - setup matrices * * \param world0 [in] world matrix for first object * \param world1 [in] world matrix for second object * \warning SCALE NOT SUPPORTED. The matrices must contain rotation & translation parts only. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::InitQuery(const Matrix4x4* world0, const Matrix4x4* world1) { // Reset stats & contact status Collider::InitQuery(); mNbBVBVTests = 0; mNbPrimPrimTests = 0; mNbBVPrimTests = 0; mPairs.Reset(); // Setup matrices Matrix4x4 InvWorld0, InvWorld1; if(world0) InvertPRMatrix(InvWorld0, *world0); else InvWorld0.Identity(); if(world1) InvertPRMatrix(InvWorld1, *world1); else InvWorld1.Identity(); Matrix4x4 World0to1 = world0 ? (*world0 * InvWorld1) : InvWorld1; Matrix4x4 World1to0 = world1 ? (*world1 * InvWorld0) : InvWorld0; mR0to1 = World0to1; World0to1.GetTrans(mT0to1); mR1to0 = World1to0; World1to0.GetTrans(mT1to0); // Precompute absolute 1-to-0 rotation matrix for(udword i=0;i<3;i++) { for(udword j=0;j<3;j++) { // Epsilon value prevents floating-point inaccuracies (strategy borrowed from RAPID) mAR.m[i][j] = 1e-6f + fabsf(mR1to0.m[i][j]); } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Takes advantage of temporal coherence. * \param cache [in] cache for a pair of previously colliding primitives * \return true if we can return immediately * \warning only works for "First Contact" mode */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABBTreeCollider::CheckTemporalCoherence(Pair* cache) { // Checkings if(!cache) return false; // Test previously colliding primitives first if(TemporalCoherenceEnabled() && FirstContactEnabled()) { PrimTest(cache->id0, cache->id1); if(GetContactStatus()) return true; } return false; } #define UPDATE_CACHE \ if(cache && GetContactStatus()) \ { \ cache->id0 = mPairs.GetEntry(0); \ cache->id1 = mPairs.GetEntry(1); \ } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Collision query for normal AABB trees. * \param tree0 [in] AABB tree from first object * \param tree1 [in] AABB tree from second object * \param world0 [in] world matrix for first object * \param world1 [in] world matrix for second object * \param cache [in/out] cache for a pair of previously colliding primitives * \return true if success * \warning SCALE NOT SUPPORTED. The matrices must contain rotation & translation parts only. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABBTreeCollider::Collide(const AABBCollisionTree* tree0, const AABBCollisionTree* tree1, const Matrix4x4* world0, const Matrix4x4* world1, Pair* cache) { // Init collision query InitQuery(world0, world1); // Check previous state if(CheckTemporalCoherence(cache)) return true; // Perform collision query _Collide(tree0->GetNodes(), tree1->GetNodes()); UPDATE_CACHE return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Collision query for no-leaf AABB trees. * \param tree0 [in] AABB tree from first object * \param tree1 [in] AABB tree from second object * \param world0 [in] world matrix for first object * \param world1 [in] world matrix for second object * \param cache [in/out] cache for a pair of previously colliding primitives * \return true if success * \warning SCALE NOT SUPPORTED. The matrices must contain rotation & translation parts only. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABBTreeCollider::Collide(const AABBNoLeafTree* tree0, const AABBNoLeafTree* tree1, const Matrix4x4* world0, const Matrix4x4* world1, Pair* cache) { // Init collision query InitQuery(world0, world1); // Check previous state if(CheckTemporalCoherence(cache)) return true; // Perform collision query _Collide(tree0->GetNodes(), tree1->GetNodes()); UPDATE_CACHE return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Collision query for quantized AABB trees. * \param tree0 [in] AABB tree from first object * \param tree1 [in] AABB tree from second object * \param world0 [in] world matrix for first object * \param world1 [in] world matrix for second object * \param cache [in/out] cache for a pair of previously colliding primitives * \return true if success * \warning SCALE NOT SUPPORTED. The matrices must contain rotation & translation parts only. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABBTreeCollider::Collide(const AABBQuantizedTree* tree0, const AABBQuantizedTree* tree1, const Matrix4x4* world0, const Matrix4x4* world1, Pair* cache) { // Init collision query InitQuery(world0, world1); // Check previous state if(CheckTemporalCoherence(cache)) return true; // Setup dequantization coeffs mCenterCoeff0 = tree0->mCenterCoeff; mExtentsCoeff0 = tree0->mExtentsCoeff; mCenterCoeff1 = tree1->mCenterCoeff; mExtentsCoeff1 = tree1->mExtentsCoeff; // Dequantize box A const AABBQuantizedNode* N0 = tree0->GetNodes(); const Point a(float(N0->mAABB.mExtents[0]) * mExtentsCoeff0.x, float(N0->mAABB.mExtents[1]) * mExtentsCoeff0.y, float(N0->mAABB.mExtents[2]) * mExtentsCoeff0.z); const Point Pa(float(N0->mAABB.mCenter[0]) * mCenterCoeff0.x, float(N0->mAABB.mCenter[1]) * mCenterCoeff0.y, float(N0->mAABB.mCenter[2]) * mCenterCoeff0.z); // Dequantize box B const AABBQuantizedNode* N1 = tree1->GetNodes(); const Point b(float(N1->mAABB.mExtents[0]) * mExtentsCoeff1.x, float(N1->mAABB.mExtents[1]) * mExtentsCoeff1.y, float(N1->mAABB.mExtents[2]) * mExtentsCoeff1.z); const Point Pb(float(N1->mAABB.mCenter[0]) * mCenterCoeff1.x, float(N1->mAABB.mCenter[1]) * mCenterCoeff1.y, float(N1->mAABB.mCenter[2]) * mCenterCoeff1.z); // Perform collision query _Collide(N0, N1, a, Pa, b, Pb); UPDATE_CACHE return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Collision query for quantized no-leaf AABB trees. * \param tree0 [in] AABB tree from first object * \param tree1 [in] AABB tree from second object * \param world0 [in] world matrix for first object * \param world1 [in] world matrix for second object * \param cache [in/out] cache for a pair of previously colliding primitives * \return true if success * \warning SCALE NOT SUPPORTED. The matrices must contain rotation & translation parts only. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AABBTreeCollider::Collide(const AABBQuantizedNoLeafTree* tree0, const AABBQuantizedNoLeafTree* tree1, const Matrix4x4* world0, const Matrix4x4* world1, Pair* cache) { // Init collision query InitQuery(world0, world1); // Check previous state if(CheckTemporalCoherence(cache)) return true; // Setup dequantization coeffs mCenterCoeff0 = tree0->mCenterCoeff; mExtentsCoeff0 = tree0->mExtentsCoeff; mCenterCoeff1 = tree1->mCenterCoeff; mExtentsCoeff1 = tree1->mExtentsCoeff; // Perform collision query _Collide(tree0->GetNodes(), tree1->GetNodes()); UPDATE_CACHE return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Standard trees /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The normal AABB tree can use 2 different descent rules (with different performances) //#define ORIGINAL_CODE //!< UNC-like descent rules #define ALTERNATIVE_CODE //!< Alternative descent rules #ifdef ORIGINAL_CODE /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision query for normal AABB trees. * \param b0 [in] collision node from first tree * \param b1 [in] collision node from second tree */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_Collide(const AABBCollisionNode* b0, const AABBCollisionNode* b1) { // Perform BV-BV overlap test if(!BoxBoxOverlap(b0->mAABB.mExtents, b0->mAABB.mCenter, b1->mAABB.mExtents, b1->mAABB.mCenter)) return; if(b0->IsLeaf() && b1->IsLeaf()) { PrimTest(b0->GetPrimitive(), b1->GetPrimitive()); return; } if(b1->IsLeaf() || (!b0->IsLeaf() && (b0->GetSize() > b1->GetSize()))) { _Collide(b0->GetNeg(), b1); if(ContactFound()) return; _Collide(b0->GetPos(), b1); } else { _Collide(b0, b1->GetNeg()); if(ContactFound()) return; _Collide(b0, b1->GetPos()); } } #endif #ifdef ALTERNATIVE_CODE /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision query for normal AABB trees. * \param b0 [in] collision node from first tree * \param b1 [in] collision node from second tree */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_Collide(const AABBCollisionNode* b0, const AABBCollisionNode* b1) { // Perform BV-BV overlap test if(!BoxBoxOverlap(b0->mAABB.mExtents, b0->mAABB.mCenter, b1->mAABB.mExtents, b1->mAABB.mCenter)) { return; } if(b0->IsLeaf()) { if(b1->IsLeaf()) { PrimTest(b0->GetPrimitive(), b1->GetPrimitive()); } else { _Collide(b0, b1->GetNeg()); if(ContactFound()) return; _Collide(b0, b1->GetPos()); } } else if(b1->IsLeaf()) { _Collide(b0->GetNeg(), b1); if(ContactFound()) return; _Collide(b0->GetPos(), b1); } else { _Collide(b0->GetNeg(), b1->GetNeg()); if(ContactFound()) return; _Collide(b0->GetNeg(), b1->GetPos()); if(ContactFound()) return; _Collide(b0->GetPos(), b1->GetNeg()); if(ContactFound()) return; _Collide(b0->GetPos(), b1->GetPos()); } } #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // No-leaf trees /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Leaf-leaf test for two primitive indices. * \param id0 [in] index from first leaf-triangle * \param id1 [in] index from second leaf-triangle */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::PrimTest(udword id0, udword id1) { // Request vertices from the app VertexPointers VP0; VertexPointers VP1; ConversionArea VC0; ConversionArea VC1; mIMesh0->GetTriangle(VP0, id0, VC0); mIMesh1->GetTriangle(VP1, id1, VC1); // Transform from space 1 to space 0 Point u0,u1,u2; TransformPoint(u0, *VP1.Vertex[0], mR1to0, mT1to0); TransformPoint(u1, *VP1.Vertex[1], mR1to0, mT1to0); TransformPoint(u2, *VP1.Vertex[2], mR1to0, mT1to0); // Perform triangle-triangle overlap test if(TriTriOverlap(*VP0.Vertex[0], *VP0.Vertex[1], *VP0.Vertex[2], u0, u1, u2)) { // Keep track of colliding pairs mPairs.Add(id0).Add(id1); // Set contact status mFlags |= OPC_CONTACT; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Leaf-leaf test for a previously fetched triangle from tree A (in B's space) and a new leaf from B. * \param id1 [in] leaf-triangle index from tree B */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline_ void AABBTreeCollider::PrimTestTriIndex(udword id1) { // Request vertices from the app VertexPointers VP; ConversionArea VC; mIMesh1->GetTriangle(VP, id1, VC); // Perform triangle-triangle overlap test if(TriTriOverlap(mLeafVerts[0], mLeafVerts[1], mLeafVerts[2], *VP.Vertex[0], *VP.Vertex[1], *VP.Vertex[2])) { // Keep track of colliding pairs mPairs.Add(mLeafIndex).Add(id1); // Set contact status mFlags |= OPC_CONTACT; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Leaf-leaf test for a previously fetched triangle from tree B (in A's space) and a new leaf from A. * \param id0 [in] leaf-triangle index from tree A */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline_ void AABBTreeCollider::PrimTestIndexTri(udword id0) { // Request vertices from the app VertexPointers VP; ConversionArea VC; mIMesh0->GetTriangle(VP, id0, VC); // Perform triangle-triangle overlap test if(TriTriOverlap(mLeafVerts[0], mLeafVerts[1], mLeafVerts[2], *VP.Vertex[0], *VP.Vertex[1], *VP.Vertex[2])) { // Keep track of colliding pairs mPairs.Add(id0).Add(mLeafIndex); // Set contact status mFlags |= OPC_CONTACT; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision of a leaf node from A and a branch from B. * \param b [in] collision node from second tree */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_CollideTriBox(const AABBNoLeafNode* b) { // Perform triangle-box overlap test if(!TriBoxOverlap(b->mAABB.mCenter, b->mAABB.mExtents)) return; // Keep same triangle, deal with first child if(b->HasPosLeaf()) PrimTestTriIndex(b->GetPosPrimitive()); else _CollideTriBox(b->GetPos()); if(ContactFound()) return; // Keep same triangle, deal with second child if(b->HasNegLeaf()) PrimTestTriIndex(b->GetNegPrimitive()); else _CollideTriBox(b->GetNeg()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision of a leaf node from B and a branch from A. * \param b [in] collision node from first tree */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_CollideBoxTri(const AABBNoLeafNode* b) { // Perform triangle-box overlap test if(!TriBoxOverlap(b->mAABB.mCenter, b->mAABB.mExtents)) return; // Keep same triangle, deal with first child if(b->HasPosLeaf()) PrimTestIndexTri(b->GetPosPrimitive()); else _CollideBoxTri(b->GetPos()); if(ContactFound()) return; // Keep same triangle, deal with second child if(b->HasNegLeaf()) PrimTestIndexTri(b->GetNegPrimitive()); else _CollideBoxTri(b->GetNeg()); } //! Request triangle vertices from the app and transform them #define FETCH_LEAF(prim_index, imesh, rot, trans) \ mLeafIndex = prim_index; \ /* Request vertices from the app */ \ VertexPointers VP; ConversionArea VC; imesh->GetTriangle(VP, prim_index, VC); \ /* Transform them in a common space */ \ TransformPoint(mLeafVerts[0], *VP.Vertex[0], rot, trans); \ TransformPoint(mLeafVerts[1], *VP.Vertex[1], rot, trans); \ TransformPoint(mLeafVerts[2], *VP.Vertex[2], rot, trans); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision query for no-leaf AABB trees. * \param a [in] collision node from first tree * \param b [in] collision node from second tree */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_Collide(const AABBNoLeafNode* a, const AABBNoLeafNode* b) { // Perform BV-BV overlap test if(!BoxBoxOverlap(a->mAABB.mExtents, a->mAABB.mCenter, b->mAABB.mExtents, b->mAABB.mCenter)) return; // Catch leaf status BOOL BHasPosLeaf = b->HasPosLeaf(); BOOL BHasNegLeaf = b->HasNegLeaf(); if(a->HasPosLeaf()) { FETCH_LEAF(a->GetPosPrimitive(), mIMesh0, mR0to1, mT0to1) if(BHasPosLeaf) PrimTestTriIndex(b->GetPosPrimitive()); else _CollideTriBox(b->GetPos()); if(ContactFound()) return; if(BHasNegLeaf) PrimTestTriIndex(b->GetNegPrimitive()); else _CollideTriBox(b->GetNeg()); } else { if(BHasPosLeaf) { FETCH_LEAF(b->GetPosPrimitive(), mIMesh1, mR1to0, mT1to0) _CollideBoxTri(a->GetPos()); } else _Collide(a->GetPos(), b->GetPos()); if(ContactFound()) return; if(BHasNegLeaf) { FETCH_LEAF(b->GetNegPrimitive(), mIMesh1, mR1to0, mT1to0) _CollideBoxTri(a->GetPos()); } else _Collide(a->GetPos(), b->GetNeg()); } if(ContactFound()) return; if(a->HasNegLeaf()) { FETCH_LEAF(a->GetNegPrimitive(), mIMesh0, mR0to1, mT0to1) if(BHasPosLeaf) PrimTestTriIndex(b->GetPosPrimitive()); else _CollideTriBox(b->GetPos()); if(ContactFound()) return; if(BHasNegLeaf) PrimTestTriIndex(b->GetNegPrimitive()); else _CollideTriBox(b->GetNeg()); } else { if(BHasPosLeaf) { // ### That leaf has possibly already been fetched FETCH_LEAF(b->GetPosPrimitive(), mIMesh1, mR1to0, mT1to0) _CollideBoxTri(a->GetNeg()); } else _Collide(a->GetNeg(), b->GetPos()); if(ContactFound()) return; if(BHasNegLeaf) { // ### That leaf has possibly already been fetched FETCH_LEAF(b->GetNegPrimitive(), mIMesh1, mR1to0, mT1to0) _CollideBoxTri(a->GetNeg()); } else _Collide(a->GetNeg(), b->GetNeg()); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Quantized trees /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision query for quantized AABB trees. * \param b0 [in] collision node from first tree * \param b1 [in] collision node from second tree * \param a [in] extent from box A * \param Pa [in] center from box A * \param b [in] extent from box B * \param Pb [in] center from box B */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_Collide(const AABBQuantizedNode* b0, const AABBQuantizedNode* b1, const Point& a, const Point& Pa, const Point& b, const Point& Pb) { // Perform BV-BV overlap test if(!BoxBoxOverlap(a, Pa, b, Pb)) return; if(b0->IsLeaf() && b1->IsLeaf()) { PrimTest(b0->GetPrimitive(), b1->GetPrimitive()); return; } if(b1->IsLeaf() || (!b0->IsLeaf() && (b0->GetSize() > b1->GetSize()))) { // Dequantize box const QuantizedAABB* Box = &b0->GetNeg()->mAABB; const Point negPa(float(Box->mCenter[0]) * mCenterCoeff0.x, float(Box->mCenter[1]) * mCenterCoeff0.y, float(Box->mCenter[2]) * mCenterCoeff0.z); const Point nega(float(Box->mExtents[0]) * mExtentsCoeff0.x, float(Box->mExtents[1]) * mExtentsCoeff0.y, float(Box->mExtents[2]) * mExtentsCoeff0.z); _Collide(b0->GetNeg(), b1, nega, negPa, b, Pb); if(ContactFound()) return; // Dequantize box Box = &b0->GetPos()->mAABB; const Point posPa(float(Box->mCenter[0]) * mCenterCoeff0.x, float(Box->mCenter[1]) * mCenterCoeff0.y, float(Box->mCenter[2]) * mCenterCoeff0.z); const Point posa(float(Box->mExtents[0]) * mExtentsCoeff0.x, float(Box->mExtents[1]) * mExtentsCoeff0.y, float(Box->mExtents[2]) * mExtentsCoeff0.z); _Collide(b0->GetPos(), b1, posa, posPa, b, Pb); } else { // Dequantize box const QuantizedAABB* Box = &b1->GetNeg()->mAABB; const Point negPb(float(Box->mCenter[0]) * mCenterCoeff1.x, float(Box->mCenter[1]) * mCenterCoeff1.y, float(Box->mCenter[2]) * mCenterCoeff1.z); const Point negb(float(Box->mExtents[0]) * mExtentsCoeff1.x, float(Box->mExtents[1]) * mExtentsCoeff1.y, float(Box->mExtents[2]) * mExtentsCoeff1.z); _Collide(b0, b1->GetNeg(), a, Pa, negb, negPb); if(ContactFound()) return; // Dequantize box Box = &b1->GetPos()->mAABB; const Point posPb(float(Box->mCenter[0]) * mCenterCoeff1.x, float(Box->mCenter[1]) * mCenterCoeff1.y, float(Box->mCenter[2]) * mCenterCoeff1.z); const Point posb(float(Box->mExtents[0]) * mExtentsCoeff1.x, float(Box->mExtents[1]) * mExtentsCoeff1.y, float(Box->mExtents[2]) * mExtentsCoeff1.z); _Collide(b0, b1->GetPos(), a, Pa, posb, posPb); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Quantized no-leaf trees /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision of a leaf node from A and a quantized branch from B. * \param leaf [in] leaf triangle from first tree * \param b [in] collision node from second tree */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_CollideTriBox(const AABBQuantizedNoLeafNode* b) { // Dequantize box const QuantizedAABB* bb = &b->mAABB; const Point Pb(float(bb->mCenter[0]) * mCenterCoeff1.x, float(bb->mCenter[1]) * mCenterCoeff1.y, float(bb->mCenter[2]) * mCenterCoeff1.z); const Point eb(float(bb->mExtents[0]) * mExtentsCoeff1.x, float(bb->mExtents[1]) * mExtentsCoeff1.y, float(bb->mExtents[2]) * mExtentsCoeff1.z); // Perform triangle-box overlap test if(!TriBoxOverlap(Pb, eb)) return; if(b->HasPosLeaf()) PrimTestTriIndex(b->GetPosPrimitive()); else _CollideTriBox(b->GetPos()); if(ContactFound()) return; if(b->HasNegLeaf()) PrimTestTriIndex(b->GetNegPrimitive()); else _CollideTriBox(b->GetNeg()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision of a leaf node from B and a quantized branch from A. * \param b [in] collision node from first tree * \param leaf [in] leaf triangle from second tree */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_CollideBoxTri(const AABBQuantizedNoLeafNode* b) { // Dequantize box const QuantizedAABB* bb = &b->mAABB; const Point Pa(float(bb->mCenter[0]) * mCenterCoeff0.x, float(bb->mCenter[1]) * mCenterCoeff0.y, float(bb->mCenter[2]) * mCenterCoeff0.z); const Point ea(float(bb->mExtents[0]) * mExtentsCoeff0.x, float(bb->mExtents[1]) * mExtentsCoeff0.y, float(bb->mExtents[2]) * mExtentsCoeff0.z); // Perform triangle-box overlap test if(!TriBoxOverlap(Pa, ea)) return; if(b->HasPosLeaf()) PrimTestIndexTri(b->GetPosPrimitive()); else _CollideBoxTri(b->GetPos()); if(ContactFound()) return; if(b->HasNegLeaf()) PrimTestIndexTri(b->GetNegPrimitive()); else _CollideBoxTri(b->GetNeg()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Recursive collision query for quantized no-leaf AABB trees. * \param a [in] collision node from first tree * \param b [in] collision node from second tree */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AABBTreeCollider::_Collide(const AABBQuantizedNoLeafNode* a, const AABBQuantizedNoLeafNode* b) { // Dequantize box A const QuantizedAABB* ab = &a->mAABB; const Point Pa(float(ab->mCenter[0]) * mCenterCoeff0.x, float(ab->mCenter[1]) * mCenterCoeff0.y, float(ab->mCenter[2]) * mCenterCoeff0.z); const Point ea(float(ab->mExtents[0]) * mExtentsCoeff0.x, float(ab->mExtents[1]) * mExtentsCoeff0.y, float(ab->mExtents[2]) * mExtentsCoeff0.z); // Dequantize box B const QuantizedAABB* bb = &b->mAABB; const Point Pb(float(bb->mCenter[0]) * mCenterCoeff1.x, float(bb->mCenter[1]) * mCenterCoeff1.y, float(bb->mCenter[2]) * mCenterCoeff1.z); const Point eb(float(bb->mExtents[0]) * mExtentsCoeff1.x, float(bb->mExtents[1]) * mExtentsCoeff1.y, float(bb->mExtents[2]) * mExtentsCoeff1.z); // Perform BV-BV overlap test if(!BoxBoxOverlap(ea, Pa, eb, Pb)) return; // Catch leaf status BOOL BHasPosLeaf = b->HasPosLeaf(); BOOL BHasNegLeaf = b->HasNegLeaf(); if(a->HasPosLeaf()) { FETCH_LEAF(a->GetPosPrimitive(), mIMesh0, mR0to1, mT0to1) if(BHasPosLeaf) PrimTestTriIndex(b->GetPosPrimitive()); else _CollideTriBox(b->GetPos()); if(ContactFound()) return; if(BHasNegLeaf) PrimTestTriIndex(b->GetNegPrimitive()); else _CollideTriBox(b->GetNeg()); } else { if(BHasPosLeaf) { FETCH_LEAF(b->GetPosPrimitive(), mIMesh1, mR1to0, mT1to0) _CollideBoxTri(a->GetPos()); } else _Collide(a->GetPos(), b->GetPos()); if(ContactFound()) return; if(BHasNegLeaf) { FETCH_LEAF(b->GetNegPrimitive(), mIMesh1, mR1to0, mT1to0) _CollideBoxTri(a->GetPos()); } else _Collide(a->GetPos(), b->GetNeg()); } if(ContactFound()) return; if(a->HasNegLeaf()) { FETCH_LEAF(a->GetNegPrimitive(), mIMesh0, mR0to1, mT0to1) if(BHasPosLeaf) PrimTestTriIndex(b->GetPosPrimitive()); else _CollideTriBox(b->GetPos()); if(ContactFound()) return; if(BHasNegLeaf) PrimTestTriIndex(b->GetNegPrimitive()); else _CollideTriBox(b->GetNeg()); } else { if(BHasPosLeaf) { // ### That leaf has possibly already been fetched FETCH_LEAF(b->GetPosPrimitive(), mIMesh1, mR1to0, mT1to0) _CollideBoxTri(a->GetNeg()); } else _Collide(a->GetNeg(), b->GetPos()); if(ContactFound()) return; if(BHasNegLeaf) { // ### That leaf has possibly already been fetched FETCH_LEAF(b->GetNegPrimitive(), mIMesh1, mR1to0, mT1to0) _CollideBoxTri(a->GetNeg()); } else _Collide(a->GetNeg(), b->GetNeg()); } }
#include <windows.h> #include <tchar.h> #include "uregex.h" namespace URegex { URegExp::URegExp() {} bool URegExp::isMatch(const char *s) { return true; } }; // namespace URegex
// Copyright (c) 2020, 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. #include "vm/closure_functions_cache.h" #include "vm/compiler/jit/compiler.h" #include "vm/object.h" #include "vm/object_store.h" namespace dart { FunctionPtr ClosureFunctionsCache::LookupClosureFunction( const Class& owner, TokenPosition token_pos) { auto thread = Thread::Current(); SafepointReadRwLocker ml(thread, thread->isolate_group()->program_lock()); return LookupClosureFunctionLocked(owner, token_pos); } FunctionPtr ClosureFunctionsCache::LookupClosureFunctionLocked( const Class& owner, TokenPosition token_pos) { auto thread = Thread::Current(); auto zone = thread->zone(); auto object_store = thread->isolate_group()->object_store(); DEBUG_ASSERT( thread->isolate_group()->program_lock()->IsCurrentThreadReader()); const auto& closures = GrowableObjectArray::Handle(zone, object_store->closure_functions()); auto& closure = Function::Handle(zone); intptr_t num_closures = closures.Length(); for (intptr_t i = 0; i < num_closures; i++) { closure ^= closures.At(i); if (closure.token_pos() == token_pos && closure.Owner() == owner.ptr()) { return closure.ptr(); } } return Function::null(); } FunctionPtr ClosureFunctionsCache::LookupClosureFunction( const Function& parent, TokenPosition token_pos) { auto thread = Thread::Current(); SafepointReadRwLocker ml(thread, thread->isolate_group()->program_lock()); return LookupClosureFunctionLocked(parent, token_pos); } FunctionPtr ClosureFunctionsCache::LookupClosureFunctionLocked( const Function& parent, TokenPosition token_pos) { auto thread = Thread::Current(); auto zone = thread->zone(); auto object_store = thread->isolate_group()->object_store(); DEBUG_ASSERT( thread->isolate_group()->program_lock()->IsCurrentThreadReader()); const auto& closures = GrowableObjectArray::Handle(zone, object_store->closure_functions()); auto& closure = Function::Handle(zone); intptr_t num_closures = closures.Length(); for (intptr_t i = 0; i < num_closures; i++) { closure ^= closures.At(i); if (closure.token_pos() == token_pos && closure.parent_function() == parent.ptr()) { return closure.ptr(); } } return Function::null(); } void ClosureFunctionsCache::AddClosureFunctionLocked(const Function& function) { ASSERT(!Compiler::IsBackgroundCompilation()); auto thread = Thread::Current(); auto zone = thread->zone(); auto object_store = thread->isolate_group()->object_store(); DEBUG_ASSERT( thread->isolate_group()->program_lock()->IsCurrentThreadWriter()); const auto& closures = GrowableObjectArray::Handle(zone, object_store->closure_functions()); ASSERT(!closures.IsNull()); ASSERT(function.IsNonImplicitClosureFunction()); closures.Add(function, Heap::kOld); } intptr_t ClosureFunctionsCache::FindClosureIndex(const Function& needle) { auto thread = Thread::Current(); auto zone = thread->zone(); auto object_store = thread->isolate_group()->object_store(); SafepointReadRwLocker ml(thread, thread->isolate_group()->program_lock()); const auto& closures_array = GrowableObjectArray::Handle(zone, object_store->closure_functions()); intptr_t num_closures = closures_array.Length(); for (intptr_t i = 0; i < num_closures; i++) { if (closures_array.At(i) == needle.ptr()) { return i; } } return -1; } FunctionPtr ClosureFunctionsCache::ClosureFunctionFromIndex(intptr_t idx) { auto thread = Thread::Current(); auto zone = thread->zone(); auto object_store = thread->isolate_group()->object_store(); SafepointReadRwLocker ml(thread, thread->isolate_group()->program_lock()); const auto& closures_array = GrowableObjectArray::Handle(zone, object_store->closure_functions()); if (idx < 0 || idx >= closures_array.Length()) { return Function::null(); } return Function::RawCast(closures_array.At(idx)); } FunctionPtr ClosureFunctionsCache::GetUniqueInnerClosure( const Function& outer) { auto thread = Thread::Current(); auto zone = thread->zone(); auto object_store = thread->isolate_group()->object_store(); SafepointReadRwLocker ml(thread, thread->isolate_group()->program_lock()); const auto& closures = GrowableObjectArray::Handle(zone, object_store->closure_functions()); auto& entry = Function::Handle(zone); for (intptr_t i = (closures.Length() - 1); i >= 0; i--) { entry ^= closures.At(i); if (entry.parent_function() == outer.ptr()) { #if defined(DEBUG) auto& other = Function::Handle(zone); for (intptr_t j = i - 1; j >= 0; j--) { other ^= closures.At(j); ASSERT(other.parent_function() != outer.ptr()); } #endif return entry.ptr(); } } return Function::null(); } void ClosureFunctionsCache::ForAllClosureFunctions( std::function<bool(const Function&)> callback) { auto thread = Thread::Current(); auto zone = thread->zone(); auto object_store = thread->isolate_group()->object_store(); auto& current_data = Array::Handle(zone); auto& entry = Function::Handle(zone); // NOTE: Inner functions may get added to the closures array while iterating - // we guarantee that any closure functions added on this thread by a // [callback] call will be visited as well. // // We avoid holding a lock while accessing the closures array, since often // times [callback] will do very heavy things (e.g. compiling the function). // // This means we can possibly miss a concurrently added closure function - // which the caller should be ok with (or it guarantees that this cannot // happen). const auto& closures = GrowableObjectArray::Handle(zone, object_store->closure_functions()); if (!thread->IsInStoppedMutatorsScope()) { // The empty read locker scope will implicitly issue an acquire memory // fence, which means any closure functions added so far will be visible and // iterated further down. SafepointReadRwLocker ml(thread, thread->isolate_group()->program_lock()); } // We have an outer loop to ensure any new closure functions added by // [callback] will be iterated as well. intptr_t i = 0; while (true) { intptr_t current_length = closures.Length(); if (i == current_length) break; current_data = closures.data(); if (current_data.Length() < current_length) { current_length = current_data.Length(); } for (; i < current_length; ++i) { entry ^= current_data.At(i); if (!callback(entry)) { return; // Stop iteration. } } } } } // namespace dart
//---------------------------------------------------------------------------------------------------------------------- // // toml++ v2.1.0 // https://github.com/marzer/tomlplusplus // SPDX-License-Identifier: MIT // //---------------------------------------------------------------------------------------------------------------------- // // - THIS FILE WAS ASSEMBLED FROM MULTIPLE HEADER FILES BY A SCRIPT - PLEASE DON'T EDIT IT DIRECTLY - // // If you wish to submit a contribution to toml++, hooray and thanks! Before you crack on, please be aware that this // file was assembled from a number of smaller files by a python script, and code contributions should not be made // against it directly. You should instead make your changes in the relevant source file(s). The file names of the files // that contributed to this header can be found at the beginnings and ends of the corresponding sections of this file. // //---------------------------------------------------------------------------------------------------------------------- // // TOML Language Specifications: // latest: https://github.com/toml-lang/toml/blob/master/README.md // v1.0.0-rc.2: https://toml.io/en/v1.0.0-rc.2 // v1.0.0-rc.1: https://toml.io/en/v1.0.0-rc.1 // v0.5.0: https://toml.io/en/v0.5.0 // changelog: https://github.com/toml-lang/toml/blob/master/CHANGELOG.md // //---------------------------------------------------------------------------------------------------------------------- // // MIT License // // Copyright (c) 2019-2020 Mark Gillard <mark.gillard@outlook.com.au> // // 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 INCLUDE_TOMLPLUSPLUS_H #define INCLUDE_TOMLPLUSPLUS_H #if 1 //------ ↓ toml_preprocessor.h -------------------------------------------------------------------------------- #ifndef __cplusplus #error toml++ is a C++ library. #endif #ifdef __INTELLISENSE__ #define TOML_INTELLISENSE 1 #else #define TOML_INTELLISENSE 0 #endif #ifdef __clang__ #define TOML_CLANG __clang_major__ #else #define TOML_CLANG 0 #endif #ifdef __INTEL_COMPILER #define TOML_ICC __INTEL_COMPILER #ifdef __ICL #define TOML_ICC_CL TOML_ICC #else #define TOML_ICC_CL 0 #endif #else #define TOML_ICC 0 #define TOML_ICC_CL 0 #endif #if defined(_MSC_VER) && !TOML_CLANG && !TOML_ICC #define TOML_MSVC _MSC_VER #else #define TOML_MSVC 0 #endif #if defined(__GNUC__) && !TOML_CLANG && !TOML_ICC #define TOML_GCC __GNUC__ #else #define TOML_GCC 0 #endif #if TOML_CLANG #define TOML_PUSH_WARNINGS _Pragma("clang diagnostic push") #define TOML_DISABLE_SWITCH_WARNINGS _Pragma("clang diagnostic ignored \"-Wswitch\"") #define TOML_DISABLE_INIT_WARNINGS _Pragma("clang diagnostic ignored \"-Wmissing-field-initializers\"") #define TOML_DISABLE_ARITHMETIC_WARNINGS _Pragma("clang diagnostic ignored \"-Wfloat-equal\"") \ _Pragma("clang diagnostic ignored \"-Wdouble-promotion\"") \ _Pragma("clang diagnostic ignored \"-Wchar-subscripts\"") \ _Pragma("clang diagnostic ignored \"-Wshift-sign-overflow\"") #define TOML_DISABLE_SHADOW_WARNINGS _Pragma("clang diagnostic ignored \"-Wshadow\"") #define TOML_DISABLE_SPAM_WARNINGS _Pragma("clang diagnostic ignored \"-Wweak-vtables\"") \ _Pragma("clang diagnostic ignored \"-Wweak-template-vtables\"") \ _Pragma("clang diagnostic ignored \"-Wpadded\"") #define TOML_POP_WARNINGS _Pragma("clang diagnostic pop") #define TOML_DISABLE_WARNINGS TOML_PUSH_WARNINGS \ _Pragma("clang diagnostic ignored \"-Weverything\"") #define TOML_ENABLE_WARNINGS TOML_POP_WARNINGS #define TOML_ASSUME(cond) __builtin_assume(cond) #define TOML_UNREACHABLE __builtin_unreachable() #define TOML_ATTR(...) __attribute__((__VA_ARGS__)) #if defined(_MSC_VER) // msvc compat mode #ifdef __has_declspec_attribute #if __has_declspec_attribute(novtable) #define TOML_INTERFACE __declspec(novtable) #endif #if __has_declspec_attribute(empty_bases) #define TOML_EMPTY_BASES __declspec(empty_bases) #endif #ifndef TOML_ALWAYS_INLINE #define TOML_ALWAYS_INLINE __forceinline #endif #if __has_declspec_attribute(noinline) #define TOML_NEVER_INLINE __declspec(noinline) #endif #endif #endif #ifdef __has_attribute #if !defined(TOML_ALWAYS_INLINE) && __has_attribute(always_inline) #define TOML_ALWAYS_INLINE __attribute__((__always_inline__)) inline #endif #if !defined(TOML_NEVER_INLINE) && __has_attribute(noinline) #define TOML_NEVER_INLINE __attribute__((__noinline__)) #endif #if !defined(TOML_TRIVIAL_ABI) && __has_attribute(trivial_abi) #define TOML_TRIVIAL_ABI __attribute__((__trivial_abi__)) #endif #endif #ifndef __EXCEPTIONS #define TOML_COMPILER_EXCEPTIONS 0 #endif #define TOML_LIKELY(...) (__builtin_expect(!!(__VA_ARGS__), 1) ) #define TOML_UNLIKELY(...) (__builtin_expect(!!(__VA_ARGS__), 0) ) //floating-point from_chars and to_chars are not implemented in any version of clang as of 1/1/2020 #ifndef TOML_FLOAT_CHARCONV #define TOML_FLOAT_CHARCONV 0 #endif #define TOML_SIMPLE_STATIC_ASSERT_MESSAGES 1 #endif // clang #if TOML_MSVC || TOML_ICC_CL #define TOML_CPP_VERSION _MSVC_LANG #define TOML_PUSH_WARNINGS __pragma(warning(push)) #if TOML_MSVC // !intel-cl #define TOML_PUSH_WARNINGS __pragma(warning(push)) #define TOML_DISABLE_SWITCH_WARNINGS __pragma(warning(disable: 4063)) #define TOML_POP_WARNINGS __pragma(warning(pop)) #define TOML_DISABLE_WARNINGS __pragma(warning(push, 0)) #define TOML_ENABLE_WARNINGS TOML_POP_WARNINGS #endif #ifndef TOML_ALWAYS_INLINE #define TOML_ALWAYS_INLINE __forceinline #endif #define TOML_NEVER_INLINE __declspec(noinline) #define TOML_ASSUME(cond) __assume(cond) #define TOML_UNREACHABLE __assume(0) #define TOML_INTERFACE __declspec(novtable) #define TOML_EMPTY_BASES __declspec(empty_bases) #if !defined(TOML_RELOPS_REORDERING) && defined(__cpp_impl_three_way_comparison) #define TOML_RELOPS_REORDERING 1 #endif #ifndef _CPPUNWIND #define TOML_COMPILER_EXCEPTIONS 0 #endif #endif // msvc #if TOML_ICC #define TOML_PUSH_WARNINGS __pragma(warning(push)) #define TOML_DISABLE_SPAM_WARNINGS __pragma(warning(disable: 82)) /* storage class is not first */ \ __pragma(warning(disable: 111)) /* statement unreachable (false-positive) */ \ __pragma(warning(disable: 1011)) /* missing return (false-positive) */ \ __pragma(warning(disable: 2261)) /* assume expr side-effects discarded */ #define TOML_POP_WARNINGS __pragma(warning(pop)) #define TOML_DISABLE_WARNINGS __pragma(warning(push, 0)) #define TOML_ENABLE_WARNINGS TOML_POP_WARNINGS #endif // icc #if TOML_GCC #define TOML_PUSH_WARNINGS _Pragma("GCC diagnostic push") #define TOML_DISABLE_SWITCH_WARNINGS _Pragma("GCC diagnostic ignored \"-Wswitch\"") \ _Pragma("GCC diagnostic ignored \"-Wswitch-enum\"") \ _Pragma("GCC diagnostic ignored \"-Wswitch-default\"") #define TOML_DISABLE_INIT_WARNINGS _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") \ _Pragma("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") \ _Pragma("GCC diagnostic ignored \"-Wuninitialized\"") #define TOML_DISABLE_ARITHMETIC_WARNINGS _Pragma("GCC diagnostic ignored \"-Wfloat-equal\"") \ _Pragma("GCC diagnostic ignored \"-Wsign-conversion\"") \ _Pragma("GCC diagnostic ignored \"-Wchar-subscripts\"") #define TOML_DISABLE_SHADOW_WARNINGS _Pragma("GCC diagnostic ignored \"-Wshadow\"") #define TOML_DISABLE_SPAM_WARNINGS _Pragma("GCC diagnostic ignored \"-Wpadded\"") \ _Pragma("GCC diagnostic ignored \"-Wcast-align\"") \ _Pragma("GCC diagnostic ignored \"-Wcomment\"") \ _Pragma("GCC diagnostic ignored \"-Wtype-limits\"") \ _Pragma("GCC diagnostic ignored \"-Wsuggest-attribute=const\"") \ _Pragma("GCC diagnostic ignored \"-Wsuggest-attribute=pure\"") #define TOML_POP_WARNINGS _Pragma("GCC diagnostic pop") #define TOML_DISABLE_WARNINGS TOML_PUSH_WARNINGS \ _Pragma("GCC diagnostic ignored \"-Wall\"") \ _Pragma("GCC diagnostic ignored \"-Wextra\"") \ _Pragma("GCC diagnostic ignored \"-Wpedantic\"") \ TOML_DISABLE_SWITCH_WARNINGS \ TOML_DISABLE_INIT_WARNINGS \ TOML_DISABLE_ARITHMETIC_WARNINGS \ TOML_DISABLE_SHADOW_WARNINGS \ TOML_DISABLE_SPAM_WARNINGS #define TOML_ENABLE_WARNINGS TOML_POP_WARNINGS #define TOML_ATTR(...) __attribute__((__VA_ARGS__)) #ifndef TOML_ALWAYS_INLINE #define TOML_ALWAYS_INLINE __attribute__((__always_inline__)) inline #endif #define TOML_NEVER_INLINE __attribute__((__noinline__)) #define TOML_UNREACHABLE __builtin_unreachable() #if !defined(TOML_RELOPS_REORDERING) && defined(__cpp_impl_three_way_comparison) #define TOML_RELOPS_REORDERING 1 #endif #ifndef __cpp_exceptions #define TOML_COMPILER_EXCEPTIONS 0 #endif #define TOML_LIKELY(...) (__builtin_expect(!!(__VA_ARGS__), 1) ) #define TOML_UNLIKELY(...) (__builtin_expect(!!(__VA_ARGS__), 0) ) // floating-point from_chars and to_chars are not implemented in any version of gcc as of 1/1/2020 #ifndef TOML_FLOAT_CHARCONV #define TOML_FLOAT_CHARCONV 0 #endif #endif #ifdef TOML_CONFIG_HEADER #include TOML_CONFIG_HEADER #endif #ifdef DOXYGEN #define TOML_HEADER_ONLY 0 #define TOML_WINDOWS_COMPAT 1 #endif #if defined(TOML_ALL_INLINE) && !defined(TOML_HEADER_ONLY) #define TOML_HEADER_ONLY TOML_ALL_INLINE #endif #if !defined(TOML_HEADER_ONLY) || (defined(TOML_HEADER_ONLY) && TOML_HEADER_ONLY) || TOML_INTELLISENSE #undef TOML_HEADER_ONLY #define TOML_HEADER_ONLY 1 #endif #if defined(TOML_IMPLEMENTATION) || TOML_HEADER_ONLY #undef TOML_IMPLEMENTATION #define TOML_IMPLEMENTATION 1 #else #define TOML_IMPLEMENTATION 0 #endif #ifndef TOML_API #define TOML_API #endif #ifndef TOML_UNRELEASED_FEATURES #define TOML_UNRELEASED_FEATURES 0 #endif #ifndef TOML_LARGE_FILES #define TOML_LARGE_FILES 0 #endif #ifndef TOML_UNDEF_MACROS #define TOML_UNDEF_MACROS 1 #endif #ifndef TOML_PARSER #define TOML_PARSER 1 #endif #ifndef DOXYGEN #if defined(_WIN32) && !defined(TOML_WINDOWS_COMPAT) #define TOML_WINDOWS_COMPAT 1 #endif #if !defined(_WIN32) || !defined(TOML_WINDOWS_COMPAT) #undef TOML_WINDOWS_COMPAT #define TOML_WINDOWS_COMPAT 0 #endif #endif #ifdef TOML_OPTIONAL_TYPE #define TOML_HAS_CUSTOM_OPTIONAL_TYPE 1 #else #define TOML_HAS_CUSTOM_OPTIONAL_TYPE 0 #endif #ifdef TOML_CHAR_8_STRINGS #if TOML_CHAR_8_STRINGS #error TOML_CHAR_8_STRINGS was removed in toml++ 2.0.0; \ all value setters and getters can now work with char8_t strings implicitly so changing the underlying string type \ is no longer necessary. #endif #endif #ifndef TOML_CPP_VERSION #define TOML_CPP_VERSION __cplusplus #endif #if TOML_CPP_VERSION < 201103L #error toml++ requires C++17 or higher. For a TOML library supporting pre-C++11 see https://github.com/ToruNiina/Boost.toml #elif TOML_CPP_VERSION < 201703L #error toml++ requires C++17 or higher. For a TOML library supporting C++11 see https://github.com/ToruNiina/toml11 #elif TOML_CPP_VERSION >= 202600L #define TOML_CPP 26 #elif TOML_CPP_VERSION >= 202300L #define TOML_CPP 23 #elif TOML_CPP_VERSION >= 202002L #define TOML_CPP 20 #elif TOML_CPP_VERSION >= 201703L #define TOML_CPP 17 #endif #undef TOML_CPP_VERSION #ifdef __has_include #define TOML_HAS_INCLUDE(header) __has_include(header) #else #define TOML_HAS_INCLUDE(header) 0 #endif #ifndef TOML_COMPILER_EXCEPTIONS #define TOML_COMPILER_EXCEPTIONS 1 #endif #if TOML_COMPILER_EXCEPTIONS #if !defined(TOML_EXCEPTIONS) || (defined(TOML_EXCEPTIONS) && TOML_EXCEPTIONS) #undef TOML_EXCEPTIONS #define TOML_EXCEPTIONS 1 #endif #else #if defined(TOML_EXCEPTIONS) && TOML_EXCEPTIONS #error TOML_EXCEPTIONS was explicitly enabled but exceptions are disabled/unsupported by the compiler. #endif #undef TOML_EXCEPTIONS #define TOML_EXCEPTIONS 0 #endif #if TOML_EXCEPTIONS #define TOML_MAY_THROW #else #define TOML_MAY_THROW noexcept #endif #ifndef TOML_INT_CHARCONV #define TOML_INT_CHARCONV 1 #endif #ifndef TOML_FLOAT_CHARCONV #define TOML_FLOAT_CHARCONV 1 #endif #if (TOML_INT_CHARCONV || TOML_FLOAT_CHARCONV) && !TOML_HAS_INCLUDE(<charconv>) #undef TOML_INT_CHARCONV #undef TOML_FLOAT_CHARCONV #define TOML_INT_CHARCONV 0 #define TOML_FLOAT_CHARCONV 0 #endif #ifndef TOML_PUSH_WARNINGS #define TOML_PUSH_WARNINGS #endif #ifndef TOML_DISABLE_SWITCH_WARNINGS #define TOML_DISABLE_SWITCH_WARNINGS #endif #ifndef TOML_DISABLE_INIT_WARNINGS #define TOML_DISABLE_INIT_WARNINGS #endif #ifndef TOML_DISABLE_SPAM_WARNINGS #define TOML_DISABLE_SPAM_WARNINGS #endif #ifndef TOML_DISABLE_ARITHMETIC_WARNINGS #define TOML_DISABLE_ARITHMETIC_WARNINGS #endif #ifndef TOML_DISABLE_SHADOW_WARNINGS #define TOML_DISABLE_SHADOW_WARNINGS #endif #ifndef TOML_POP_WARNINGS #define TOML_POP_WARNINGS #endif #ifndef TOML_DISABLE_WARNINGS #define TOML_DISABLE_WARNINGS #endif #ifndef TOML_ENABLE_WARNINGS #define TOML_ENABLE_WARNINGS #endif #ifndef TOML_ATTR #define TOML_ATTR(...) #endif #ifndef TOML_INTERFACE #define TOML_INTERFACE #endif #ifndef TOML_EMPTY_BASES #define TOML_EMPTY_BASES #endif #ifndef TOML_NEVER_INLINE #define TOML_NEVER_INLINE #endif #ifndef TOML_ASSUME #define TOML_ASSUME(cond) (void)0 #endif #ifndef TOML_UNREACHABLE #define TOML_UNREACHABLE TOML_ASSERT(false) #endif #define TOML_NO_DEFAULT_CASE default: TOML_UNREACHABLE #ifdef __cpp_consteval #define TOML_CONSTEVAL consteval #else #define TOML_CONSTEVAL constexpr #endif #if !defined(DOXYGEN) && !TOML_INTELLISENSE #if !defined(TOML_LIKELY) && __has_cpp_attribute(likely) #define TOML_LIKELY(...) (__VA_ARGS__) [[likely]] #endif #if !defined(TOML_UNLIKELY) && __has_cpp_attribute(unlikely) #define TOML_UNLIKELY(...) (__VA_ARGS__) [[unlikely]] #endif #if __has_cpp_attribute(nodiscard) >= 201907L #define TOML_NODISCARD_CTOR [[nodiscard]] #endif #endif #ifndef TOML_LIKELY #define TOML_LIKELY(...) (__VA_ARGS__) #endif #ifndef TOML_UNLIKELY #define TOML_UNLIKELY(...) (__VA_ARGS__) #endif #ifndef TOML_NODISCARD_CTOR #define TOML_NODISCARD_CTOR #endif #ifndef TOML_TRIVIAL_ABI #define TOML_TRIVIAL_ABI #endif #ifndef TOML_RELOPS_REORDERING #define TOML_RELOPS_REORDERING 0 #endif #if TOML_RELOPS_REORDERING #define TOML_ASYMMETRICAL_EQUALITY_OPS(...) #else #define TOML_ASYMMETRICAL_EQUALITY_OPS(LHS, RHS, ...) \ __VA_ARGS__ [[nodiscard]] friend bool operator == (RHS rhs, LHS lhs) noexcept { return lhs == rhs; } \ __VA_ARGS__ [[nodiscard]] friend bool operator != (LHS lhs, RHS rhs) noexcept { return !(lhs == rhs); } \ __VA_ARGS__ [[nodiscard]] friend bool operator != (RHS rhs, LHS lhs) noexcept { return !(lhs == rhs); } #endif #ifndef TOML_SIMPLE_STATIC_ASSERT_MESSAGES #define TOML_SIMPLE_STATIC_ASSERT_MESSAGES 0 #endif #define TOML_CONCAT_1(x, y) x##y #define TOML_CONCAT(x, y) TOML_CONCAT_1(x, y) #define TOML_EVAL_BOOL_1(T, F) T #define TOML_EVAL_BOOL_0(T, F) F #if defined(__aarch64__) || defined(__ARM_ARCH_ISA_A64) || defined(_M_ARM64) || defined(__ARM_64BIT_STATE) \ || defined(__arm__) || defined(_M_ARM) || defined(__ARM_32BIT_STATE) #define TOML_ARM 1 #else #define TOML_ARM 0 #endif #ifdef __FLT16_MANT_DIG__ #if __FLT_RADIX__ == 2 \ && __FLT16_MANT_DIG__ == 11 \ && __FLT16_DIG__ == 3 \ && __FLT16_MIN_EXP__ == -13 \ && __FLT16_MIN_10_EXP__ == -4 \ && __FLT16_MAX_EXP__ == 16 \ && __FLT16_MAX_10_EXP__ == 4 #if (TOML_ARM && TOML_GCC) || TOML_CLANG #define TOML_FP16 __fp16 #endif #if TOML_ARM && (TOML_GCC || TOML_CLANG) #define TOML_FLOAT16 _Float16 #endif #endif #endif #if defined(__SIZEOF_FLOAT128__) \ && defined(__FLT128_MANT_DIG__) \ && defined(__LDBL_MANT_DIG__) \ && __FLT128_MANT_DIG__ > __LDBL_MANT_DIG__ #define TOML_FLOAT128 __float128 #endif #ifdef __SIZEOF_INT128__ #define TOML_INT128 __int128_t #define TOML_UINT128 __uint128_t #endif #define TOML_LIB_MAJOR 2 #define TOML_LIB_MINOR 1 #define TOML_LIB_PATCH 0 #define TOML_LANG_MAJOR 1 #define TOML_LANG_MINOR 0 #define TOML_LANG_PATCH 0 #define TOML_LIB_SINGLE_HEADER 1 #define TOML_MAKE_VERSION(maj, min, rev) \ ((maj) * 1000 + (min) * 25 + (rev)) #if TOML_UNRELEASED_FEATURES #define TOML_LANG_EFFECTIVE_VERSION \ TOML_MAKE_VERSION(TOML_LANG_MAJOR, TOML_LANG_MINOR, TOML_LANG_PATCH+1) #else #define TOML_LANG_EFFECTIVE_VERSION \ TOML_MAKE_VERSION(TOML_LANG_MAJOR, TOML_LANG_MINOR, TOML_LANG_PATCH) #endif #define TOML_LANG_HIGHER_THAN(maj, min, rev) \ (TOML_LANG_EFFECTIVE_VERSION > TOML_MAKE_VERSION(maj, min, rev)) #define TOML_LANG_AT_LEAST(maj, min, rev) \ (TOML_LANG_EFFECTIVE_VERSION >= TOML_MAKE_VERSION(maj, min, rev)) #define TOML_LANG_UNRELEASED \ TOML_LANG_HIGHER_THAN(TOML_LANG_MAJOR, TOML_LANG_MINOR, TOML_LANG_PATCH) #ifndef TOML_ABI_NAMESPACES #ifdef DOXYGEN #define TOML_ABI_NAMESPACES 0 #else #define TOML_ABI_NAMESPACES 1 #endif #endif #if TOML_ABI_NAMESPACES #define TOML_NAMESPACE_START namespace toml { inline namespace TOML_CONCAT(v, TOML_LIB_MAJOR) #define TOML_NAMESPACE_END } #define TOML_NAMESPACE ::toml::TOML_CONCAT(v, TOML_LIB_MAJOR) #define TOML_ABI_NAMESPACE_START(name) inline namespace name { #define TOML_ABI_NAMESPACE_BOOL(cond, T, F) TOML_ABI_NAMESPACE_START(TOML_CONCAT(TOML_EVAL_BOOL_, cond)(T, F)) #define TOML_ABI_NAMESPACE_END } #else #define TOML_NAMESPACE_START namespace toml #define TOML_NAMESPACE_END #define TOML_NAMESPACE toml #define TOML_ABI_NAMESPACE_START(...) #define TOML_ABI_NAMESPACE_BOOL(...) #define TOML_ABI_NAMESPACE_END #endif #define TOML_IMPL_NAMESPACE_START TOML_NAMESPACE_START { namespace impl #define TOML_IMPL_NAMESPACE_END } TOML_NAMESPACE_END #if TOML_HEADER_ONLY #define TOML_ANON_NAMESPACE_START TOML_IMPL_NAMESPACE_START #define TOML_ANON_NAMESPACE_END TOML_IMPL_NAMESPACE_END #define TOML_ANON_NAMESPACE TOML_NAMESPACE::impl #define TOML_USING_ANON_NAMESPACE using namespace TOML_ANON_NAMESPACE #define TOML_EXTERNAL_LINKAGE inline #define TOML_INTERNAL_LINKAGE inline #else #define TOML_ANON_NAMESPACE_START namespace #define TOML_ANON_NAMESPACE_END #define TOML_ANON_NAMESPACE #define TOML_USING_ANON_NAMESPACE (void)0 #define TOML_EXTERNAL_LINKAGE #define TOML_INTERNAL_LINKAGE static #endif TOML_DISABLE_WARNINGS #ifndef TOML_ASSERT #if defined(NDEBUG) || !defined(_DEBUG) #define TOML_ASSERT(expr) (void)0 #else #ifndef assert #include <cassert> #endif #define TOML_ASSERT(expr) assert(expr) #endif #endif TOML_ENABLE_WARNINGS #endif //------ ↑ toml_preprocessor.h -------------------------------------------------------------------------------- TOML_PUSH_WARNINGS TOML_DISABLE_SPAM_WARNINGS #if 1 //---------------------------------- ↓ toml_common.h ---------------------------------------------------------- TOML_DISABLE_WARNINGS #include <cstdint> #include <cstddef> #include <cstring> #include <cfloat> #include <climits> #include <limits> #include <memory> #include <string_view> #include <string> #include <vector> #include <map> #include <iosfwd> #if !TOML_HAS_CUSTOM_OPTIONAL_TYPE #include <optional> #endif #if TOML_HAS_INCLUDE(<version>) #include <version> #endif TOML_ENABLE_WARNINGS #ifdef __cpp_lib_launder #define TOML_LAUNDER(x) std::launder(x) #else #define TOML_LAUNDER(x) x #endif #ifndef DOXYGEN #ifndef TOML_DISABLE_ENVIRONMENT_CHECKS #define TOML_ENV_MESSAGE \ "If you're seeing this error it's because you're building toml++ for an environment that doesn't conform to " \ "one of the 'ground truths' assumed by the library. Essentially this just means that I don't have the " \ "resources to test on more platforms, but I wish I did! You can try disabling the checks by defining " \ "TOML_DISABLE_ENVIRONMENT_CHECKS, but your mileage may vary. Please consider filing an issue at " \ "https://github.com/marzer/tomlplusplus/issues to help me improve support for your target environment. Thanks!" static_assert(CHAR_BIT == 8, TOML_ENV_MESSAGE); static_assert(FLT_RADIX == 2, TOML_ENV_MESSAGE); static_assert('A' == 65, TOML_ENV_MESSAGE); static_assert(sizeof(double) == 8, TOML_ENV_MESSAGE); static_assert(std::numeric_limits<double>::is_iec559, TOML_ENV_MESSAGE); static_assert(std::numeric_limits<double>::digits == 53, TOML_ENV_MESSAGE); static_assert(std::numeric_limits<double>::digits10 == 15, TOML_ENV_MESSAGE); #undef TOML_ENV_MESSAGE #endif // !TOML_DISABLE_ENVIRONMENT_CHECKS #endif // !DOXYGEN #ifndef DOXYGEN // undocumented forward declarations are hidden from doxygen because they fuck it up =/ namespace toml // non-abi namespace; this is not an error { using namespace std::string_literals; using namespace std::string_view_literals; using ::std::size_t; using ::std::intptr_t; using ::std::uintptr_t; using ::std::ptrdiff_t; using ::std::nullptr_t; using ::std::int8_t; using ::std::int16_t; using ::std::int32_t; using ::std::int64_t; using ::std::uint8_t; using ::std::uint16_t; using ::std::uint32_t; using ::std::uint64_t; using ::std::uint_least32_t; using ::std::uint_least64_t; // legacy typedefs using string_char = char; using string = std::string; using string_view = std::string_view; } TOML_NAMESPACE_START // abi namespace { struct date; struct time; struct time_offset; TOML_ABI_NAMESPACE_BOOL(TOML_HAS_CUSTOM_OPTIONAL_TYPE, custopt, stdopt) struct date_time; TOML_ABI_NAMESPACE_END class node; class array; class table; template <typename> class node_view; template <typename> class value; template <typename> class default_formatter; template <typename> class json_formatter; [[nodiscard]] TOML_API bool operator == (const array& lhs, const array& rhs) noexcept; [[nodiscard]] TOML_API bool operator != (const array& lhs, const array& rhs) noexcept; [[nodiscard]] TOML_API bool operator == (const table& lhs, const table& rhs) noexcept; [[nodiscard]] TOML_API bool operator != (const table& lhs, const table& rhs) noexcept; template <typename Char> std::basic_ostream<Char>& operator << (std::basic_ostream<Char>&, const array&); template <typename Char, typename T> std::basic_ostream<Char>& operator << (std::basic_ostream<Char>&, const value<T>&); template <typename Char> std::basic_ostream<Char>& operator << (std::basic_ostream<Char>&, const table&); template <typename T, typename U> std::basic_ostream<T>& operator << (std::basic_ostream<T>&, default_formatter<U>&); template <typename T, typename U> std::basic_ostream<T>& operator << (std::basic_ostream<T>&, default_formatter<U>&&); template <typename T, typename U> std::basic_ostream<T>& operator << (std::basic_ostream<T>&, json_formatter<U>&); template <typename T, typename U> std::basic_ostream<T>& operator << (std::basic_ostream<T>&, json_formatter<U>&&); template <typename Char, typename T> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>&, const node_view<T>&); namespace impl { template <typename T> using string_map = std::map<std::string, T, std::less<>>; // heterogeneous lookup template <typename T> using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>; template <typename T, typename... U> inline constexpr bool is_one_of = (false || ... || std::is_same_v<T, U>); template <typename T> inline constexpr bool is_cvref = std::is_reference_v<T> || std::is_const_v<T> || std::is_volatile_v<T>; template <typename T> inline constexpr bool is_wide_string = is_one_of< std::decay_t<T>, const wchar_t*, wchar_t*, std::wstring_view, std::wstring >; template <typename T> inline constexpr bool dependent_false = false; #define TOML_P2S_DECL(Type) \ template <typename Char> \ inline void print_to_stream(Type, std::basic_ostream<Char>&) TOML_P2S_DECL(int8_t); TOML_P2S_DECL(int16_t); TOML_P2S_DECL(int32_t); TOML_P2S_DECL(int64_t); TOML_P2S_DECL(uint8_t); TOML_P2S_DECL(uint16_t); TOML_P2S_DECL(uint32_t); TOML_P2S_DECL(uint64_t); TOML_P2S_DECL(float); TOML_P2S_DECL(const date&); TOML_P2S_DECL(const time&); TOML_P2S_DECL(time_offset); TOML_P2S_DECL(const date_time&); #undef TOML_P2S_DECL #if TOML_WINDOWS_COMPAT [[nodiscard]] TOML_API std::string narrow(std::wstring_view) noexcept; [[nodiscard]] TOML_API std::wstring widen(std::string_view) noexcept; #ifdef __cpp_lib_char8_t [[nodiscard]] TOML_API std::wstring widen(std::u8string_view) noexcept; #endif #endif // TOML_WINDOWS_COMPAT #if TOML_ABI_NAMESPACES #if TOML_EXCEPTIONS TOML_ABI_NAMESPACE_START(ex) #define TOML_PARSER_TYPENAME TOML_NAMESPACE::impl::ex::parser #else TOML_ABI_NAMESPACE_START(noex) #define TOML_PARSER_TYPENAME TOML_NAMESPACE::impl::noex::parser #endif #else #define TOML_PARSER_TYPENAME TOML_NAMESPACE::impl::parser #endif class parser; TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS } } TOML_NAMESPACE_END #endif // !DOXYGEN namespace toml { } TOML_NAMESPACE_START // abi namespace { inline namespace literals {} #if TOML_HAS_CUSTOM_OPTIONAL_TYPE template <typename T> using optional = TOML_OPTIONAL_TYPE<T>; #else template <typename T> using optional = std::optional<T>; #endif enum class node_type : uint8_t { none, table, array, string, integer, floating_point, boolean, date, time, date_time }; using source_path_ptr = std::shared_ptr<const std::string>; template <typename T> struct TOML_TRIVIAL_ABI inserter { T&& value; }; template <typename T> inserter(T&&) -> inserter<T>; } TOML_NAMESPACE_END TOML_IMPL_NAMESPACE_START { // general value traits // (as they relate to their equivalent native TOML type) template <typename T> struct value_traits { using native_type = void; static constexpr bool is_native = false; static constexpr bool is_losslessly_convertible_to_native = false; static constexpr bool can_represent_native = false; static constexpr bool can_partially_represent_native = false; static constexpr auto type = node_type::none; }; template <typename T> struct value_traits<T&> : value_traits<T> {}; template <typename T> struct value_traits<T&&> : value_traits<T> {}; template <typename T> struct value_traits<T* const> : value_traits<T*> {}; template <typename T> struct value_traits<T* volatile> : value_traits<T*> {}; template <typename T> struct value_traits<T* const volatile> : value_traits<T*> {}; // integer value traits template <typename T> struct integer_value_limits { static constexpr auto min = (std::numeric_limits<T>::min)(); static constexpr auto max = (std::numeric_limits<T>::max)(); }; template <typename T> struct integer_value_traits_base : integer_value_limits<T> { using native_type = int64_t; static constexpr bool is_native = std::is_same_v<T, native_type>; static constexpr bool is_signed = static_cast<T>(-1) < T{}; // for impls not specializing std::is_signed<T> static constexpr auto type = node_type::integer; static constexpr bool can_partially_represent_native = true; }; template <typename T> struct unsigned_integer_value_traits : integer_value_traits_base<T> { static constexpr bool is_losslessly_convertible_to_native = integer_value_limits<T>::max <= 9223372036854775807ULL; static constexpr bool can_represent_native = false; }; template <typename T> struct signed_integer_value_traits : integer_value_traits_base<T> { using native_type = int64_t; static constexpr bool is_losslessly_convertible_to_native = integer_value_limits<T>::min >= (-9223372036854775807LL - 1LL) && integer_value_limits<T>::max <= 9223372036854775807LL; static constexpr bool can_represent_native = integer_value_limits<T>::min <= (-9223372036854775807LL - 1LL) && integer_value_limits<T>::max >= 9223372036854775807LL; }; template <typename T, bool S = integer_value_traits_base<T>::is_signed> struct integer_value_traits : signed_integer_value_traits<T> {}; template <typename T> struct integer_value_traits<T, false> : unsigned_integer_value_traits<T> {}; template <> struct value_traits<signed char> : integer_value_traits<signed char> {}; template <> struct value_traits<unsigned char> : integer_value_traits<unsigned char> {}; template <> struct value_traits<signed short> : integer_value_traits<signed short> {}; template <> struct value_traits<unsigned short> : integer_value_traits<unsigned short> {}; template <> struct value_traits<signed int> : integer_value_traits<signed int> {}; template <> struct value_traits<unsigned int> : integer_value_traits<unsigned int> {}; template <> struct value_traits<signed long> : integer_value_traits<signed long> {}; template <> struct value_traits<unsigned long> : integer_value_traits<unsigned long> {}; template <> struct value_traits<signed long long> : integer_value_traits<signed long long> {}; template <> struct value_traits<unsigned long long> : integer_value_traits<unsigned long long> {}; #ifdef TOML_INT128 template <> struct integer_value_limits<TOML_INT128> { static constexpr TOML_INT128 max = static_cast<TOML_INT128>( (TOML_UINT128{ 1u } << ((__SIZEOF_INT128__ * CHAR_BIT) - 1)) - 1 ); static constexpr TOML_INT128 min = -max - TOML_INT128{ 1 }; }; template <> struct integer_value_limits<TOML_UINT128> { static constexpr TOML_UINT128 min = TOML_UINT128{}; static constexpr TOML_UINT128 max = (2u * static_cast<TOML_UINT128>(integer_value_limits<TOML_INT128>::max)) + 1u; }; template <> struct value_traits<TOML_INT128> : integer_value_traits<TOML_INT128> {}; template <> struct value_traits<TOML_UINT128> : integer_value_traits<TOML_UINT128> {}; #endif #ifdef TOML_SMALL_INT_TYPE template <> struct value_traits<TOML_SMALL_INT_TYPE> : signed_integer_value_traits<TOML_SMALL_INT_TYPE> {}; #endif static_assert(value_traits<int64_t>::is_native); static_assert(value_traits<int64_t>::is_signed); static_assert(value_traits<int64_t>::is_losslessly_convertible_to_native); static_assert(value_traits<int64_t>::can_represent_native); static_assert(value_traits<int64_t>::can_partially_represent_native); // float value traits template <typename T> struct float_value_limits { static constexpr bool is_iec559 = std::numeric_limits<T>::is_iec559; static constexpr int digits = std::numeric_limits<T>::digits; static constexpr int digits10 = std::numeric_limits<T>::digits10; }; template <typename T> struct float_value_traits : float_value_limits<T> { using native_type = double; static constexpr bool is_native = std::is_same_v<T, native_type>; static constexpr bool is_signed = true; static constexpr bool is_losslessly_convertible_to_native = float_value_limits<T>::is_iec559 && float_value_limits<T>::digits <= 53 && float_value_limits<T>::digits10 <= 15; static constexpr bool can_represent_native = float_value_limits<T>::is_iec559 && float_value_limits<T>::digits >= 53 // DBL_MANT_DIG && float_value_limits<T>::digits10 >= 15; // DBL_DIG static constexpr bool can_partially_represent_native //32-bit float values = float_value_limits<T>::is_iec559 && float_value_limits<T>::digits >= 24 && float_value_limits<T>::digits10 >= 6; static constexpr auto type = node_type::floating_point; }; template <> struct value_traits<float> : float_value_traits<float> {}; template <> struct value_traits<double> : float_value_traits<double> {}; template <> struct value_traits<long double> : float_value_traits<long double> {}; template <int mant_dig, int dig> struct extended_float_value_limits { static constexpr bool is_iec559 = true; static constexpr int digits = mant_dig; static constexpr int digits10 = dig; }; #ifdef TOML_FP16 template <> struct float_value_limits<TOML_FP16> : extended_float_value_limits<__FLT16_MANT_DIG__, __FLT16_DIG__> {}; template <> struct value_traits<TOML_FP16> : float_value_traits<TOML_FP16> {}; #endif #ifdef TOML_FLOAT16 template <> struct float_value_limits<TOML_FLOAT16> : extended_float_value_limits<__FLT16_MANT_DIG__, __FLT16_DIG__> {}; template <> struct value_traits<TOML_FLOAT16> : float_value_traits<TOML_FLOAT16> {}; #endif #ifdef TOML_FLOAT128 template <> struct float_value_limits<TOML_FLOAT128> : extended_float_value_limits<__FLT128_MANT_DIG__, __FLT128_DIG__> {}; template <> struct value_traits<TOML_FLOAT128> : float_value_traits<TOML_FLOAT128> {}; #endif #ifdef TOML_SMALL_FLOAT_TYPE template <> struct value_traits<TOML_SMALL_FLOAT_TYPE> : float_value_traits<TOML_SMALL_FLOAT_TYPE> {}; #endif static_assert(value_traits<double>::is_native); static_assert(value_traits<double>::is_losslessly_convertible_to_native); static_assert(value_traits<double>::can_represent_native); static_assert(value_traits<double>::can_partially_represent_native); // string value traits template <typename T> struct string_value_traits { using native_type = std::string; static constexpr bool is_native = std::is_same_v<T, native_type>; static constexpr bool is_losslessly_convertible_to_native = true; static constexpr bool can_represent_native = !std::is_array_v<T> && (!std::is_pointer_v<T> || std::is_const_v<std::remove_pointer_t<T>>); static constexpr bool can_partially_represent_native = can_represent_native; static constexpr auto type = node_type::string; }; template <> struct value_traits<std::string> : string_value_traits<std::string> {}; template <> struct value_traits<std::string_view> : string_value_traits<std::string_view> {}; template <> struct value_traits<const char*> : string_value_traits<const char *> {}; template <size_t N> struct value_traits<const char[N]> : string_value_traits<const char[N]> {}; template <> struct value_traits<char*> : string_value_traits<char*> {}; template <size_t N> struct value_traits<char[N]> : string_value_traits<char[N]> {}; #ifdef __cpp_lib_char8_t template <> struct value_traits<std::u8string> : string_value_traits<std::u8string> {}; template <> struct value_traits<std::u8string_view> : string_value_traits<std::u8string_view> {}; template <> struct value_traits<const char8_t*> : string_value_traits<const char8_t*> {}; template <size_t N> struct value_traits<const char8_t[N]> : string_value_traits<const char8_t[N]> {}; template <> struct value_traits<char8_t*> : string_value_traits<char8_t*> {}; template <size_t N> struct value_traits<char8_t[N]> : string_value_traits<char8_t[N]> {}; #endif #if TOML_WINDOWS_COMPAT template <typename T> struct wstring_value_traits { using native_type = std::string; static constexpr bool is_native = false; static constexpr bool is_losslessly_convertible_to_native = true; //narrow static constexpr bool can_represent_native = std::is_same_v<T, std::wstring>; //widen static constexpr bool can_partially_represent_native = can_represent_native; static constexpr auto type = node_type::string; }; template <> struct value_traits<std::wstring> : wstring_value_traits<std::wstring> {}; template <> struct value_traits<std::wstring_view> : wstring_value_traits<std::wstring_view> {}; template <> struct value_traits<const wchar_t*> : wstring_value_traits<const wchar_t*> {}; template <size_t N> struct value_traits<const wchar_t[N]> : wstring_value_traits<const wchar_t[N]> {}; template <> struct value_traits<wchar_t*> : wstring_value_traits<wchar_t*> {}; template <size_t N> struct value_traits<wchar_t[N]> : wstring_value_traits<wchar_t[N]> {}; #endif // other native value traits template <typename T, node_type NodeType> struct native_value_traits { using native_type = T; static constexpr bool is_native = true; static constexpr bool is_losslessly_convertible_to_native = true; static constexpr bool can_represent_native = true; static constexpr bool can_partially_represent_native = true; static constexpr auto type = NodeType; }; template <> struct value_traits<bool> : native_value_traits<bool, node_type::boolean> {}; template <> struct value_traits<date> : native_value_traits<date, node_type::date> {}; template <> struct value_traits<time> : native_value_traits<time, node_type::time> {}; template <> struct value_traits<date_time> : native_value_traits<date_time, node_type::date_time> {}; // native value category queries template <typename T> using native_type_of = typename value_traits<T>::native_type; template <typename T> inline constexpr bool is_native = value_traits<T>::is_native; template <typename T> inline constexpr bool can_represent_native = value_traits<T>::can_represent_native; template <typename T> inline constexpr bool can_partially_represent_native = value_traits<T>::can_partially_represent_native; template <typename T> inline constexpr bool is_losslessly_convertible_to_native = value_traits<T>::is_losslessly_convertible_to_native; template <typename T, typename... U> inline constexpr bool is_natively_one_of = is_one_of<native_type_of<T>, U...>; // native <=> node conversions template <typename T> struct node_wrapper { using type = T; }; template <> struct node_wrapper<std::string> { using type = value<std::string>; }; template <> struct node_wrapper<int64_t> { using type = value<int64_t>; }; template <> struct node_wrapper<double> { using type = value<double>; }; template <> struct node_wrapper<bool> { using type = value<bool>; }; template <> struct node_wrapper<date> { using type = value<date>; }; template <> struct node_wrapper<time> { using type = value<time>; }; template <> struct node_wrapper<date_time> { using type = value<date_time>; }; template <typename T> using wrap_node = typename node_wrapper<T>::type; template <typename T> struct node_unwrapper { using type = T; }; template <typename T> struct node_unwrapper<value<T>> { using type = T; }; template <typename T> using unwrap_node = typename node_unwrapper<T>::type; template <typename T> struct node_type_getter { static constexpr auto value = value_traits<T>::type; }; template <> struct node_type_getter<table> { static constexpr auto value = node_type::table; }; template <> struct node_type_getter<array> { static constexpr auto value = node_type::array; }; template <> struct node_type_getter<void> { static constexpr auto value = node_type::none; }; template <typename T> inline constexpr node_type node_type_of = node_type_getter<unwrap_node<remove_cvref_t<T>>>::value; template <typename T> inline constexpr bool is_node_view = is_one_of<impl::remove_cvref_t<T>, node_view<node>, node_view<const node>>; } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { template <typename T> inline constexpr bool is_table = std::is_same_v<impl::remove_cvref_t<T>, table>; template <typename T> inline constexpr bool is_array = std::is_same_v<impl::remove_cvref_t<T>, array>; template <typename T> inline constexpr bool is_string = std::is_same_v<impl::wrap_node<impl::remove_cvref_t<T>>, value<std::string>>; template <typename T> inline constexpr bool is_integer = std::is_same_v<impl::wrap_node<impl::remove_cvref_t<T>>, value<int64_t>>; template <typename T> inline constexpr bool is_floating_point = std::is_same_v<impl::wrap_node<impl::remove_cvref_t<T>>, value<double>>; template <typename T> inline constexpr bool is_number = is_integer<T> || is_floating_point<T>; template <typename T> inline constexpr bool is_boolean = std::is_same_v<impl::wrap_node<impl::remove_cvref_t<T>>, value<bool>>; template <typename T> inline constexpr bool is_date = std::is_same_v<impl::wrap_node<impl::remove_cvref_t<T>>, value<date>>; template <typename T> inline constexpr bool is_time = std::is_same_v<impl::wrap_node<impl::remove_cvref_t<T>>, value<time>>; template <typename T> inline constexpr bool is_date_time = std::is_same_v<impl::wrap_node<impl::remove_cvref_t<T>>, value<date_time>>; } TOML_NAMESPACE_END TOML_IMPL_NAMESPACE_START { template <typename T> [[nodiscard]] TOML_ATTR(const) TOML_ALWAYS_INLINE constexpr std::underlying_type_t<T> unwrap_enum(T val) noexcept { return static_cast<std::underlying_type_t<T>>(val); } // Q: "why not use the built-in fpclassify?" // A: Because it gets broken by -ffast-math and friends enum class fp_class : unsigned { ok, neg_inf, pos_inf, nan }; [[nodiscard]] TOML_ATTR(pure) inline fp_class fpclassify(const double& val) noexcept { constexpr uint64_t sign = 0b1000000000000000000000000000000000000000000000000000000000000000ull; constexpr uint64_t exponent = 0b0111111111110000000000000000000000000000000000000000000000000000ull; constexpr uint64_t mantissa = 0b0000000000001111111111111111111111111111111111111111111111111111ull; uint64_t val_bits; memcpy(&val_bits, &val, sizeof(val)); if ((val_bits & exponent) != exponent) return fp_class::ok; if ((val_bits & mantissa)) return fp_class::nan; return (val_bits & sign) ? fp_class::neg_inf : fp_class::pos_inf; } // Q: "why not use std::find??" // A: Because <algorithm> is _huge_ and std::find would be the only thing I used from it. // I don't want to impose such a heavy compile-time burden on users. template <typename T> [[nodiscard]] inline const T* find(const std::vector<T>& haystack, const T& needle) noexcept { for (size_t i = 0, e = haystack.size(); i < e; i++) if (haystack[i] == needle) return haystack.data() + i; return nullptr; } inline constexpr std::string_view low_character_escape_table[] = { "\\u0000"sv, "\\u0001"sv, "\\u0002"sv, "\\u0003"sv, "\\u0004"sv, "\\u0005"sv, "\\u0006"sv, "\\u0007"sv, "\\b"sv, "\\t"sv, "\\n"sv, "\\u000B"sv, "\\f"sv, "\\r"sv, "\\u000E"sv, "\\u000F"sv, "\\u0010"sv, "\\u0011"sv, "\\u0012"sv, "\\u0013"sv, "\\u0014"sv, "\\u0015"sv, "\\u0016"sv, "\\u0017"sv, "\\u0018"sv, "\\u0019"sv, "\\u001A"sv, "\\u001B"sv, "\\u001C"sv, "\\u001D"sv, "\\u001E"sv, "\\u001F"sv, }; inline constexpr std::string_view node_type_friendly_names[] = { "none"sv, "table"sv, "array"sv, "string"sv, "integer"sv, "floating-point"sv, "boolean"sv, "date"sv, "time"sv, "date-time"sv }; } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { [[nodiscard]] TOML_ATTR(const) TOML_ALWAYS_INLINE TOML_CONSTEVAL size_t operator"" _sz(unsigned long long n) noexcept { return static_cast<size_t>(n); } TOML_ABI_NAMESPACE_BOOL(TOML_LARGE_FILES, lf, sf) #if TOML_LARGE_FILES using source_index = uint32_t; #else using source_index = uint16_t; #endif struct TOML_TRIVIAL_ABI source_position { source_index line; source_index column; [[nodiscard]] explicit constexpr operator bool () const noexcept { return line > source_index{} && column > source_index{}; } [[nodiscard]] friend constexpr bool operator == (const source_position& lhs, const source_position& rhs) noexcept { return lhs.line == rhs.line && lhs.column == rhs.column; } [[nodiscard]] friend constexpr bool operator != (const source_position& lhs, const source_position& rhs) noexcept { return lhs.line != rhs.line || lhs.column != rhs.column; } [[nodiscard]] friend constexpr bool operator < (const source_position& lhs, const source_position& rhs) noexcept { return lhs.line < rhs.line || (lhs.line == rhs.line && lhs.column < rhs.column); } [[nodiscard]] friend constexpr bool operator <= (const source_position& lhs, const source_position& rhs) noexcept { return lhs.line < rhs.line || (lhs.line == rhs.line && lhs.column <= rhs.column); } }; struct source_region { source_position begin; source_position end; source_path_ptr path; #if TOML_WINDOWS_COMPAT [[nodiscard]] optional<std::wstring> wide_path() const noexcept { if (!path || path->empty()) return {}; return { impl::widen(*path) }; } #endif }; TOML_ABI_NAMESPACE_END // TOML_LARGE_FILES template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, node_type rhs) { using underlying_t = std::underlying_type_t<node_type>; const auto str = impl::node_type_friendly_names[static_cast<underlying_t>(rhs)]; if constexpr (std::is_same_v<Char, char>) return lhs << str; else { if constexpr (sizeof(Char) == 1) return lhs << std::basic_string_view<Char>{ reinterpret_cast<const Char*>(str.data()), str.length() }; else return lhs << str.data(); } } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, node_type); #endif } TOML_NAMESPACE_END #endif //---------------------------------- ↑ toml_common.h ---------------------------------------------------------- #if 1 //--------------------------------------------------------- ↓ toml_date_time.h -------------------------------- TOML_NAMESPACE_START { struct TOML_TRIVIAL_ABI date { uint16_t year; uint8_t month; uint8_t day; [[nodiscard]] friend constexpr bool operator == (date lhs, date rhs) noexcept { return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day; } [[nodiscard]] friend constexpr bool operator != (date lhs, date rhs) noexcept { return lhs.year != rhs.year || lhs.month != rhs.month || lhs.day != rhs.day; } private: [[nodiscard]] TOML_ALWAYS_INLINE static constexpr uint32_t pack(date d) noexcept { return static_cast<uint32_t>(d.year) << 16 | static_cast<uint32_t>(d.month) << 8 | static_cast<uint32_t>(d.day); } public: [[nodiscard]] friend constexpr bool operator < (date lhs, date rhs) noexcept { return pack(lhs) < pack(rhs); } [[nodiscard]] friend constexpr bool operator <= (date lhs, date rhs) noexcept { return pack(lhs) <= pack(rhs); } [[nodiscard]] friend constexpr bool operator > (date lhs, date rhs) noexcept { return pack(lhs) > pack(rhs); } [[nodiscard]] friend constexpr bool operator >= (date lhs, date rhs) noexcept { return pack(lhs) >= pack(rhs); } }; template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const date& rhs) { impl::print_to_stream(rhs, lhs); return lhs; } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, const date&); #endif struct TOML_TRIVIAL_ABI time { uint8_t hour; uint8_t minute; uint8_t second; uint32_t nanosecond; [[nodiscard]] friend constexpr bool operator == (const time& lhs, const time& rhs) noexcept { return lhs.hour == rhs.hour && lhs.minute == rhs.minute && lhs.second == rhs.second && lhs.nanosecond == rhs.nanosecond; } [[nodiscard]] friend constexpr bool operator != (const time& lhs, const time& rhs) noexcept { return !(lhs == rhs); } private: [[nodiscard]] TOML_ALWAYS_INLINE static constexpr uint64_t pack(time t) noexcept { return static_cast<uint64_t>(t.hour) << 48 | static_cast<uint64_t>(t.minute) << 40 | static_cast<uint64_t>(t.second) << 32 | static_cast<uint64_t>(t.nanosecond); } public: [[nodiscard]] friend constexpr bool operator < (time lhs, time rhs) noexcept { return pack(lhs) < pack(rhs); } [[nodiscard]] friend constexpr bool operator <= (time lhs, time rhs) noexcept { return pack(lhs) <= pack(rhs); } [[nodiscard]] friend constexpr bool operator > (time lhs, time rhs) noexcept { return pack(lhs) > pack(rhs); } [[nodiscard]] friend constexpr bool operator >= (time lhs, time rhs) noexcept { return pack(lhs) >= pack(rhs); } }; template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const time& rhs) { impl::print_to_stream(rhs, lhs); return lhs; } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, const time&); #endif struct TOML_TRIVIAL_ABI time_offset { int16_t minutes; TOML_NODISCARD_CTOR constexpr time_offset() noexcept : minutes{} {} TOML_NODISCARD_CTOR constexpr time_offset(int8_t h, int8_t m) noexcept : minutes{ static_cast<int16_t>(h * 60 + m) } {} [[nodiscard]] friend constexpr bool operator == (time_offset lhs, time_offset rhs) noexcept { return lhs.minutes == rhs.minutes; } [[nodiscard]] friend constexpr bool operator != (time_offset lhs, time_offset rhs) noexcept { return lhs.minutes != rhs.minutes; } [[nodiscard]] friend constexpr bool operator < (time_offset lhs, time_offset rhs) noexcept { return lhs.minutes < rhs.minutes; } [[nodiscard]] friend constexpr bool operator <= (time_offset lhs, time_offset rhs) noexcept { return lhs.minutes <= rhs.minutes; } [[nodiscard]] friend constexpr bool operator > (time_offset lhs, time_offset rhs) noexcept { return lhs.minutes > rhs.minutes; } [[nodiscard]] friend constexpr bool operator >= (time_offset lhs, time_offset rhs) noexcept { return lhs.minutes >= rhs.minutes; } }; template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const time_offset& rhs) { impl::print_to_stream(rhs, lhs); return lhs; } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, const time_offset&); #endif TOML_ABI_NAMESPACE_BOOL(TOML_HAS_CUSTOM_OPTIONAL_TYPE, custopt, stdopt) struct date_time { toml::date date; toml::time time; optional<toml::time_offset> offset; TOML_NODISCARD_CTOR constexpr date_time() noexcept : date{}, time{} {} TOML_NODISCARD_CTOR constexpr date_time(toml::date d, toml::time t) noexcept : date{ d }, time{ t } {} TOML_NODISCARD_CTOR constexpr date_time(toml::date d, toml::time t, toml::time_offset off) noexcept : date{ d }, time{ t }, offset{ off } {} [[nodiscard]] constexpr bool is_local() const noexcept { return !offset.has_value(); } [[nodiscard]] friend constexpr bool operator == (const date_time& lhs, const date_time& rhs) noexcept { return lhs.date == rhs.date && lhs.time == rhs.time && lhs.offset == rhs.offset; } [[nodiscard]] friend constexpr bool operator != (const date_time& lhs, const date_time& rhs) noexcept { return !(lhs == rhs); } [[nodiscard]] friend constexpr bool operator < (const date_time& lhs, const date_time& rhs) noexcept { if (lhs.date != rhs.date) return lhs.date < rhs.date; if (lhs.time != rhs.time) return lhs.time < rhs.time; return lhs.offset < rhs.offset; } [[nodiscard]] friend constexpr bool operator <= (const date_time& lhs, const date_time& rhs) noexcept { if (lhs.date != rhs.date) return lhs.date < rhs.date; if (lhs.time != rhs.time) return lhs.time < rhs.time; return lhs.offset <= rhs.offset; } [[nodiscard]] friend constexpr bool operator > (const date_time& lhs, const date_time& rhs) noexcept { return !(lhs <= rhs); } [[nodiscard]] friend constexpr bool operator >= (const date_time& lhs, const date_time& rhs) noexcept { return !(lhs < rhs); } }; TOML_ABI_NAMESPACE_END // TOML_HAS_CUSTOM_OPTIONAL_TYPE template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const date_time& rhs) { impl::print_to_stream(rhs, lhs); return lhs; } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, const date_time&); #endif } TOML_NAMESPACE_END #endif //--------------------------------------------------------- ↑ toml_date_time.h -------------------------------- #if 1 //------------------------------------------------------------------------------- ↓ toml_print_to_stream.h ---- TOML_DISABLE_WARNINGS #include <cmath> #if TOML_INT_CHARCONV || TOML_FLOAT_CHARCONV #include <charconv> #endif #if !TOML_INT_CHARCONV || !TOML_FLOAT_CHARCONV #include <sstream> #endif #if !TOML_INT_CHARCONV #include <iomanip> #endif TOML_ENABLE_WARNINGS TOML_IMPL_NAMESPACE_START { // Q: "why does print_to_stream() exist? why not just use ostream::write(), ostream::put() etc?" // A: - I'm supporting C++20's char8_t as well; wrapping streams allows switching string modes transparently. // - I'm using <charconv> to format numerics. Faster and locale-independent. // - I can avoid forcing users to drag in <sstream> and <iomanip>. // Q: "there's a bit of reinterpret_casting here, is any of it UB?" // A: - If the source string data is char and the output string is char8_t, then technically yes, // but not in the other direction. I test in both modes on Clang, GCC and MSVC and have yet to // see it actually causing an issue, but in the event it does present a problem it's not going to // be a show-stopper since all it means is I need to do duplicate some code. // - Strings in C++. Honestly. template <typename Char1, typename Char2> inline void print_to_stream(std::basic_string_view<Char1> str, std::basic_ostream<Char2>& stream) { static_assert(sizeof(Char1) == 1); static_assert(sizeof(Char2) == 1); stream.write(reinterpret_cast<const Char2*>(str.data()), static_cast<std::streamsize>(str.length())); } template <typename Char1, typename Char2> inline void print_to_stream(const std::basic_string<Char1>& str, std::basic_ostream<Char2>& stream) { static_assert(sizeof(Char1) == 1); static_assert(sizeof(Char2) == 1); stream.write(reinterpret_cast<const Char2*>(str.data()), static_cast<std::streamsize>(str.length())); } template <typename Char> inline void print_to_stream(char character, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); stream.put(static_cast<Char>(character)); } template <typename Char> TOML_ATTR(nonnull) inline void print_to_stream(const char* str, size_t len, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); stream.write(reinterpret_cast<const Char*>(str), static_cast<std::streamsize>(len)); } #ifdef __cpp_lib_char8_t template <typename Char> inline void print_to_stream(char8_t character, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); stream.put(static_cast<Char>(character)); } template <typename Char> TOML_ATTR(nonnull) inline void print_to_stream(const char8_t* str, size_t len, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); stream.write(reinterpret_cast<const Char*>(str), static_cast<std::streamsize>(len)); } #endif template <typename T> inline constexpr size_t charconv_buffer_length = 0; template <> inline constexpr size_t charconv_buffer_length<double> = 60; template <> inline constexpr size_t charconv_buffer_length<float> = 40; template <> inline constexpr size_t charconv_buffer_length<uint64_t> = 20; // strlen("18446744073709551615") template <> inline constexpr size_t charconv_buffer_length<int64_t> = 20; // strlen("-9223372036854775808") template <> inline constexpr size_t charconv_buffer_length<int32_t> = 11; // strlen("-2147483648") template <> inline constexpr size_t charconv_buffer_length<int16_t> = 6; // strlen("-32768") template <> inline constexpr size_t charconv_buffer_length<int8_t> = 4; // strlen("-128") template <> inline constexpr size_t charconv_buffer_length<uint32_t> = 10; // strlen("4294967295") template <> inline constexpr size_t charconv_buffer_length<uint16_t> = 5; // strlen("65535") template <> inline constexpr size_t charconv_buffer_length<uint8_t> = 3; // strlen("255") template <typename T, typename Char> inline void print_integer_to_stream(T val, std::basic_ostream<Char>& stream) { static_assert( sizeof(Char) == 1, "The stream's underlying character type must be 1 byte in size." ); #if TOML_INT_CHARCONV char buf[charconv_buffer_length<T>]; const auto res = std::to_chars(buf, buf + sizeof(buf), val); const auto len = static_cast<size_t>(res.ptr - buf); print_to_stream(buf, len, stream); #else std::ostringstream ss; ss.imbue(std::locale::classic()); using cast_type = std::conditional_t<std::is_signed_v<T>, int64_t, uint64_t>; ss << static_cast<cast_type>(val); const auto str = std::move(ss).str(); print_to_stream(str, stream); #endif } #define TOML_P2S_OVERLOAD(Type) \ template <typename Char> \ inline void print_to_stream(Type val, std::basic_ostream<Char>& stream) \ { \ static_assert(sizeof(Char) == 1); \ print_integer_to_stream(val, stream); \ } TOML_P2S_OVERLOAD(int8_t) TOML_P2S_OVERLOAD(int16_t) TOML_P2S_OVERLOAD(int32_t) TOML_P2S_OVERLOAD(int64_t) TOML_P2S_OVERLOAD(uint8_t) TOML_P2S_OVERLOAD(uint16_t) TOML_P2S_OVERLOAD(uint32_t) TOML_P2S_OVERLOAD(uint64_t) #undef TOML_P2S_OVERLOAD template <typename T, typename Char> inline void print_floating_point_to_stream(T val, std::basic_ostream<Char>& stream, bool hexfloat = false) { static_assert( sizeof(Char) == 1, "The stream's underlying character type must be 1 byte in size." ); switch (impl::fpclassify(val)) { case fp_class::neg_inf: print_to_stream("-inf"sv, stream); break; case fp_class::pos_inf: print_to_stream("inf"sv, stream); break; case fp_class::nan: print_to_stream("nan"sv, stream); break; case fp_class::ok: { static constexpr auto needs_decimal_point = [](auto&& s) noexcept { for (auto c : s) if (c == '.' || c == 'E' || c == 'e') return false; return true; }; #if TOML_FLOAT_CHARCONV { char buf[charconv_buffer_length<T>]; const auto res = hexfloat ? std::to_chars(buf, buf + sizeof(buf), val, std::chars_format::hex) : std::to_chars(buf, buf + sizeof(buf), val); const auto str = std::string_view{ buf, static_cast<size_t>(res.ptr - buf) }; print_to_stream(str, stream); if (!hexfloat && needs_decimal_point(str)) print_to_stream(".0"sv, stream); } #else { std::ostringstream ss; ss.imbue(std::locale::classic()); ss.precision(std::numeric_limits<T>::digits10 + 1); if (hexfloat) ss << std::hexfloat; ss << val; const auto str = std::move(ss).str(); print_to_stream(str, stream); if (!hexfloat && needs_decimal_point(str)) print_to_stream(".0"sv, stream); } #endif break; } TOML_NO_DEFAULT_CASE; } } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API void print_floating_point_to_stream(double, std::ostream&, bool); #endif #define TOML_P2S_OVERLOAD(Type) \ template <typename Char> \ inline void print_to_stream(Type val, std::basic_ostream<Char>& stream) \ { \ static_assert(sizeof(Char) == 1); \ print_floating_point_to_stream(val, stream); \ } TOML_P2S_OVERLOAD(double) #undef TOML_P2S_OVERLOAD template <typename Char> inline void print_to_stream(bool val, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); print_to_stream(val ? "true"sv : "false"sv, stream); } template <typename T, typename Char> inline void print_to_stream(T val, std::basic_ostream<Char>& stream, size_t zero_pad_to_digits) { static_assert(sizeof(Char) == 1); #if TOML_INT_CHARCONV char buf[charconv_buffer_length<T>]; const auto res = std::to_chars(buf, buf + sizeof(buf), val); const auto len = static_cast<size_t>(res.ptr - buf); for (size_t i = len; i < zero_pad_to_digits; i++) print_to_stream('0', stream); print_to_stream(buf, static_cast<size_t>(res.ptr - buf), stream); #else std::ostringstream ss; ss.imbue(std::locale::classic()); using cast_type = std::conditional_t<std::is_signed_v<T>, int64_t, uint64_t>; ss << std::setfill('0') << std::setw(static_cast<int>(zero_pad_to_digits)) << static_cast<cast_type>(val); const auto str = std::move(ss).str(); print_to_stream(str, stream); #endif } template <typename Char> inline void print_to_stream(const toml::date& val, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); print_to_stream(val.year, stream, 4_sz); print_to_stream('-', stream); print_to_stream(val.month, stream, 2_sz); print_to_stream('-', stream); print_to_stream(val.day, stream, 2_sz); } template <typename Char> inline void print_to_stream(const toml::time& val, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); print_to_stream(val.hour, stream, 2_sz); print_to_stream(':', stream); print_to_stream(val.minute, stream, 2_sz); print_to_stream(':', stream); print_to_stream(val.second, stream, 2_sz); if (val.nanosecond && val.nanosecond <= 999999999u) { print_to_stream('.', stream); auto ns = val.nanosecond; size_t digits = 9_sz; while (ns % 10u == 0u) { ns /= 10u; digits--; } print_to_stream(ns, stream, digits); } } template <typename Char> inline void print_to_stream(toml::time_offset val, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); if (!val.minutes) print_to_stream('Z', stream); else { auto mins = static_cast<int>(val.minutes); if (mins < 0) { print_to_stream('-', stream); mins = -mins; } else print_to_stream('+', stream); const auto hours = mins / 60; if (hours) { print_to_stream(static_cast<unsigned int>(hours), stream, 2_sz); mins -= hours * 60; } else print_to_stream("00"sv, stream); print_to_stream(':', stream); print_to_stream(static_cast<unsigned int>(mins), stream, 2_sz); } } template <typename Char> inline void print_to_stream(const toml::date_time& val, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); print_to_stream(val.date, stream); print_to_stream('T', stream); print_to_stream(val.time, stream); if (val.offset) print_to_stream(*val.offset, stream); } TOML_PUSH_WARNINGS TOML_DISABLE_ARITHMETIC_WARNINGS template <typename T, typename Char> void print_to_stream_with_escapes(T && str, std::basic_ostream<Char>& stream) { static_assert(sizeof(Char) == 1); for (auto c : str) { if TOML_UNLIKELY(c >= '\x00' && c <= '\x1F') print_to_stream(low_character_escape_table[c], stream); else if TOML_UNLIKELY(c == '\x7F') print_to_stream("\\u007F"sv, stream); else if TOML_UNLIKELY(c == '"') print_to_stream("\\\""sv, stream); else if TOML_UNLIKELY(c == '\\') print_to_stream("\\\\"sv, stream); else print_to_stream(c, stream); } } TOML_POP_WARNINGS // TOML_DISABLE_ARITHMETIC_WARNINGS } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const source_position& rhs) { static_assert( sizeof(Char) == 1, "The stream's underlying character type must be 1 byte in size." ); impl::print_to_stream("line "sv, lhs); impl::print_to_stream(rhs.line, lhs); impl::print_to_stream(", column "sv, lhs); impl::print_to_stream(rhs.column, lhs); return lhs; } template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const source_region& rhs) { static_assert( sizeof(Char) == 1, "The stream's underlying character type must be 1 byte in size." ); lhs << rhs.begin; if (rhs.path) { impl::print_to_stream(" of '"sv, lhs); impl::print_to_stream(*rhs.path, lhs); impl::print_to_stream('\'', lhs); } return lhs; } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, const source_position&); extern template TOML_API std::ostream& operator << (std::ostream&, const source_region&); #endif } TOML_NAMESPACE_END #endif //------------------------------------------------------------------------------- ↑ toml_print_to_stream.h ---- #if 1 //---------- ↓ toml_node.h ------------------------------------------------------------------------------------ #if defined(DOXYGEN) || TOML_SIMPLE_STATIC_ASSERT_MESSAGES #define TOML_SA_NEWLINE " " #define TOML_SA_LIST_SEP ", " #define TOML_SA_LIST_BEG " (" #define TOML_SA_LIST_END ")" #define TOML_SA_LIST_NEW " " #define TOML_SA_LIST_NXT ", " #else #define TOML_SA_NEWLINE "\n| " #define TOML_SA_LIST_SEP TOML_SA_NEWLINE " - " #define TOML_SA_LIST_BEG TOML_SA_LIST_SEP #define TOML_SA_LIST_END #define TOML_SA_LIST_NEW TOML_SA_NEWLINE TOML_SA_NEWLINE #define TOML_SA_LIST_NXT TOML_SA_LIST_NEW #endif #define TOML_SA_NATIVE_VALUE_TYPE_LIST \ TOML_SA_LIST_BEG "std::string" \ TOML_SA_LIST_SEP "int64_t" \ TOML_SA_LIST_SEP "double" \ TOML_SA_LIST_SEP "bool" \ TOML_SA_LIST_SEP "toml::date" \ TOML_SA_LIST_SEP "toml::time" \ TOML_SA_LIST_SEP "toml::date_time" \ TOML_SA_LIST_END #define TOML_SA_NODE_TYPE_LIST \ TOML_SA_LIST_BEG "toml::table" \ TOML_SA_LIST_SEP "toml::array" \ TOML_SA_LIST_SEP "toml::value<std::string>" \ TOML_SA_LIST_SEP "toml::value<int64_t>" \ TOML_SA_LIST_SEP "toml::value<double>" \ TOML_SA_LIST_SEP "toml::value<bool>" \ TOML_SA_LIST_SEP "toml::value<toml::date>" \ TOML_SA_LIST_SEP "toml::value<toml::time>" \ TOML_SA_LIST_SEP "toml::value<toml::date_time>" \ TOML_SA_LIST_END #define TOML_SA_UNWRAPPED_NODE_TYPE_LIST \ TOML_SA_LIST_NEW "A native TOML value type" \ TOML_SA_NATIVE_VALUE_TYPE_LIST \ \ TOML_SA_LIST_NXT "A TOML node type" \ TOML_SA_NODE_TYPE_LIST TOML_NAMESPACE_START { class TOML_INTERFACE TOML_API node { private: friend class TOML_PARSER_TYPENAME; source_region source_{}; protected: node() noexcept = default; node(const node&) noexcept; node(node&&) noexcept; node& operator= (const node&) noexcept; node& operator= (node&&) noexcept; template <typename T> [[nodiscard]] TOML_ALWAYS_INLINE impl::wrap_node<T>& ref_cast() & noexcept { return *reinterpret_cast<impl::wrap_node<T>*>(this); } template <typename T> [[nodiscard]] TOML_ALWAYS_INLINE impl::wrap_node<T>&& ref_cast() && noexcept { return std::move(*reinterpret_cast<impl::wrap_node<T>*>(this)); } template <typename T> [[nodiscard]] TOML_ALWAYS_INLINE const impl::wrap_node<T>& ref_cast() const & noexcept { return *reinterpret_cast<const impl::wrap_node<T>*>(this); } template <typename N, typename T> using ref_cast_type = decltype(std::declval<N>().template ref_cast<T>()); public: virtual ~node() noexcept = default; [[nodiscard]] virtual node_type type() const noexcept = 0; [[nodiscard]] virtual bool is_table() const noexcept = 0; [[nodiscard]] virtual bool is_array() const noexcept = 0; [[nodiscard]] virtual bool is_value() const noexcept = 0; [[nodiscard]] virtual bool is_string() const noexcept; [[nodiscard]] virtual bool is_integer() const noexcept; [[nodiscard]] virtual bool is_floating_point() const noexcept; [[nodiscard]] virtual bool is_number() const noexcept; [[nodiscard]] virtual bool is_boolean() const noexcept; [[nodiscard]] virtual bool is_date() const noexcept; [[nodiscard]] virtual bool is_time() const noexcept; [[nodiscard]] virtual bool is_date_time() const noexcept; [[nodiscard]] virtual bool is_array_of_tables() const noexcept; template <typename T> [[nodiscard]] bool is() const noexcept { using type = impl::unwrap_node<T>; static_assert( (impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>, "The template type argument of node::is() must be one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); if constexpr (std::is_same_v<type, table>) return is_table(); else if constexpr (std::is_same_v<type, array>) return is_array(); else if constexpr (std::is_same_v<type, std::string>) return is_string(); else if constexpr (std::is_same_v<type, int64_t>) return is_integer(); else if constexpr (std::is_same_v<type, double>) return is_floating_point(); else if constexpr (std::is_same_v<type, bool>) return is_boolean(); else if constexpr (std::is_same_v<type, date>) return is_date(); else if constexpr (std::is_same_v<type, time>) return is_time(); else if constexpr (std::is_same_v<type, date_time>) return is_date_time(); } [[nodiscard]] virtual table* as_table() noexcept; [[nodiscard]] virtual array* as_array() noexcept; [[nodiscard]] virtual toml::value<std::string>* as_string() noexcept; [[nodiscard]] virtual toml::value<int64_t>* as_integer() noexcept; [[nodiscard]] virtual toml::value<double>* as_floating_point() noexcept; [[nodiscard]] virtual toml::value<bool>* as_boolean() noexcept; [[nodiscard]] virtual toml::value<date>* as_date() noexcept; [[nodiscard]] virtual toml::value<time>* as_time() noexcept; [[nodiscard]] virtual toml::value<date_time>* as_date_time() noexcept; [[nodiscard]] virtual const table* as_table() const noexcept; [[nodiscard]] virtual const array* as_array() const noexcept; [[nodiscard]] virtual const toml::value<std::string>* as_string() const noexcept; [[nodiscard]] virtual const toml::value<int64_t>* as_integer() const noexcept; [[nodiscard]] virtual const toml::value<double>* as_floating_point() const noexcept; [[nodiscard]] virtual const toml::value<bool>* as_boolean() const noexcept; [[nodiscard]] virtual const toml::value<date>* as_date() const noexcept; [[nodiscard]] virtual const toml::value<time>* as_time() const noexcept; [[nodiscard]] virtual const toml::value<date_time>* as_date_time() const noexcept; [[nodiscard]] virtual bool is_homogeneous(node_type ntype, node*& first_nonmatch) noexcept = 0; [[nodiscard]] virtual bool is_homogeneous(node_type ntype, const node*& first_nonmatch) const noexcept = 0; [[nodiscard]] virtual bool is_homogeneous(node_type ntype) const noexcept = 0; template <typename ElemType = void> [[nodiscard]] bool is_homogeneous() const noexcept { using type = impl::unwrap_node<ElemType>; static_assert( std::is_void_v<type> || ((impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>), "The template type argument of node::is_homogeneous() must be void or one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); return is_homogeneous(impl::node_type_of<type>); } private: #ifndef DOXYGEN template <typename T> [[nodiscard]] decltype(auto) get_value_exact() const noexcept; #endif // !DOXYGEN public: template <typename T> [[nodiscard]] optional<T> value_exact() const noexcept; template <typename T> [[nodiscard]] optional<T> value() const noexcept; template <typename T> [[nodiscard]] auto value_or(T&& default_value) const noexcept; //template <typename T> //[[nodiscard]] //std::vector<T> select_exact() const noexcept; //template <typename T> //[[nodiscard]] //std::vector<T> select() const noexcept; template <typename T> [[nodiscard]] impl::wrap_node<T>* as() noexcept { using type = impl::unwrap_node<T>; static_assert( (impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>, "The template type argument of node::as() must be one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); if constexpr (std::is_same_v<type, table>) return as_table(); else if constexpr (std::is_same_v<type, array>) return as_array(); else if constexpr (std::is_same_v<type, std::string>) return as_string(); else if constexpr (std::is_same_v<type, int64_t>) return as_integer(); else if constexpr (std::is_same_v<type, double>) return as_floating_point(); else if constexpr (std::is_same_v<type, bool>) return as_boolean(); else if constexpr (std::is_same_v<type, date>) return as_date(); else if constexpr (std::is_same_v<type, time>) return as_time(); else if constexpr (std::is_same_v<type, date_time>) return as_date_time(); } template <typename T> [[nodiscard]] const impl::wrap_node<T>* as() const noexcept { using type = impl::unwrap_node<T>; static_assert( (impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>, "The template type argument of node::as() must be one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); if constexpr (std::is_same_v<type, table>) return as_table(); else if constexpr (std::is_same_v<type, array>) return as_array(); else if constexpr (std::is_same_v<type, std::string>) return as_string(); else if constexpr (std::is_same_v<type, int64_t>) return as_integer(); else if constexpr (std::is_same_v<type, double>) return as_floating_point(); else if constexpr (std::is_same_v<type, bool>) return as_boolean(); else if constexpr (std::is_same_v<type, date>) return as_date(); else if constexpr (std::is_same_v<type, time>) return as_time(); else if constexpr (std::is_same_v<type, date_time>) return as_date_time(); } [[nodiscard]] const source_region& source() const noexcept; private: template <typename Func, typename N, typename T> static constexpr bool can_visit = std::is_invocable_v<Func, ref_cast_type<N, T>>; template <typename Func, typename N> static constexpr bool can_visit_any = can_visit<Func, N, table> || can_visit<Func, N, array> || can_visit<Func, N, std::string> || can_visit<Func, N, int64_t> || can_visit<Func, N, double> || can_visit<Func, N, bool> || can_visit<Func, N, date> || can_visit<Func, N, time> || can_visit<Func, N, date_time>; template <typename Func, typename N> static constexpr bool can_visit_all = can_visit<Func, N, table> && can_visit<Func, N, array> && can_visit<Func, N, std::string> && can_visit<Func, N, int64_t> && can_visit<Func, N, double> && can_visit<Func, N, bool> && can_visit<Func, N, date> && can_visit<Func, N, time> && can_visit<Func, N, date_time>; template <typename Func, typename N, typename T> static constexpr bool visit_is_nothrow_one = !can_visit<Func, N, T> || std::is_nothrow_invocable_v<Func, ref_cast_type<N, T>>; template <typename Func, typename N> static constexpr bool visit_is_nothrow = visit_is_nothrow_one<Func, N, table> && visit_is_nothrow_one<Func, N, array> && visit_is_nothrow_one<Func, N, std::string> && visit_is_nothrow_one<Func, N, int64_t> && visit_is_nothrow_one<Func, N, double> && visit_is_nothrow_one<Func, N, bool> && visit_is_nothrow_one<Func, N, date> && visit_is_nothrow_one<Func, N, time> && visit_is_nothrow_one<Func, N, date_time>; template <typename Func, typename N, typename T, bool = can_visit<Func, N, T>> struct visit_return_type final { using type = decltype(std::declval<Func>()(std::declval<ref_cast_type<N, T>>())); }; template <typename Func, typename N, typename T> struct visit_return_type<Func, N, T, false> final { using type = void; }; template <typename A, typename B> using nonvoid = std::conditional_t<std::is_void_v<A>, B, A>; template <typename N, typename Func> static decltype(auto) do_visit(N&& n, Func&& visitor) noexcept(visit_is_nothrow<Func&&, N&&>) { static_assert( can_visit_any<Func&&, N&&>, "TOML node visitors must be invocable for at least one of the toml::node specializations:" TOML_SA_NODE_TYPE_LIST ); switch (n.type()) { case node_type::table: if constexpr (can_visit<Func&&, N&&, table>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<table>()); break; case node_type::array: if constexpr (can_visit<Func&&, N&&, array>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<array>()); break; case node_type::string: if constexpr (can_visit<Func&&, N&&, std::string>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<std::string>()); break; case node_type::integer: if constexpr (can_visit<Func&&, N&&, int64_t>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<int64_t>()); break; case node_type::floating_point: if constexpr (can_visit<Func&&, N&&, double>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<double>()); break; case node_type::boolean: if constexpr (can_visit<Func&&, N&&, bool>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<bool>()); break; case node_type::date: if constexpr (can_visit<Func&&, N&&, date>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<date>()); break; case node_type::time: if constexpr (can_visit<Func&&, N&&, time>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<time>()); break; case node_type::date_time: if constexpr (can_visit<Func&&, N&&, date_time>) return std::forward<Func>(visitor)(std::forward<N>(n).template ref_cast<date_time>()); break; case node_type::none: TOML_UNREACHABLE; TOML_NO_DEFAULT_CASE; } if constexpr (can_visit_all<Func&&, N&&>) TOML_UNREACHABLE; else { using return_type = nonvoid<typename visit_return_type<Func&&, N&&, table>::type, nonvoid<typename visit_return_type<Func&&, N&&, array>::type, nonvoid<typename visit_return_type<Func&&, N&&, std::string>::type, nonvoid<typename visit_return_type<Func&&, N&&, int64_t>::type, nonvoid<typename visit_return_type<Func&&, N&&, double>::type, nonvoid<typename visit_return_type<Func&&, N&&, bool>::type, nonvoid<typename visit_return_type<Func&&, N&&, date>::type, nonvoid<typename visit_return_type<Func&&, N&&, time>::type, typename visit_return_type<Func&&, N&&, date_time>::type >>>>>>>>; if constexpr (!std::is_void_v<return_type>) { static_assert( std::is_default_constructible_v<return_type>, "Non-exhaustive visitors must return a default-constructible type, or void" ); return return_type{}; } } } template <typename T, typename N> [[nodiscard]] static decltype(auto) do_ref(N&& n) noexcept { using type = impl::unwrap_node<T>; static_assert( (impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>, "The template type argument of node::ref() must be one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); TOML_ASSERT( n.template is<T>() && "template type argument T provided to toml::node::ref() didn't match the node's actual type" ); if constexpr (impl::is_native<type>) return std::forward<N>(n).template ref_cast<type>().get(); else return std::forward<N>(n).template ref_cast<type>(); } public: template <typename Func> decltype(auto) visit(Func&& visitor) & noexcept(visit_is_nothrow<Func&&, node&>) { return do_visit(*this, std::forward<Func>(visitor)); } template <typename Func> decltype(auto) visit(Func&& visitor) && noexcept(visit_is_nothrow<Func&&, node&&>) { return do_visit(std::move(*this), std::forward<Func>(visitor)); } template <typename Func> decltype(auto) visit(Func&& visitor) const& noexcept(visit_is_nothrow<Func&&, const node&>) { return do_visit(*this, std::forward<Func>(visitor)); } template <typename T> [[nodiscard]] impl::unwrap_node<T>& ref() & noexcept { return do_ref<T>(*this); } template <typename T> [[nodiscard]] impl::unwrap_node<T>&& ref() && noexcept { return do_ref<T>(std::move(*this)); } template <typename T> [[nodiscard]] const impl::unwrap_node<T>& ref() const& noexcept { return do_ref<T>(*this); } [[nodiscard]] operator node_view<node>() noexcept; [[nodiscard]] operator node_view<const node>() const noexcept; }; } TOML_NAMESPACE_END #endif //---------- ↑ toml_node.h ------------------------------------------------------------------------------------ #if 1 //---------------------------------- ↓ toml_value.h ----------------------------------------------------------- #ifndef DOXYGEN #if TOML_WINDOWS_COMPAT #define TOML_SA_VALUE_MESSAGE_WSTRING TOML_SA_LIST_SEP "std::wstring" #else #define TOML_SA_VALUE_MESSAGE_WSTRING #endif #ifdef __cpp_lib_char8_t #define TOML_SA_VALUE_MESSAGE_U8STRING_VIEW TOML_SA_LIST_SEP "std::u8string_view" #define TOML_SA_VALUE_MESSAGE_CONST_CHAR8 TOML_SA_LIST_SEP "const char8_t*" #else #define TOML_SA_VALUE_MESSAGE_U8STRING_VIEW #define TOML_SA_VALUE_MESSAGE_CONST_CHAR8 #endif #define TOML_SA_VALUE_EXACT_FUNC_MESSAGE(type_arg) \ "The " type_arg " must be one of:" \ TOML_SA_LIST_NEW "A native TOML value type" \ TOML_SA_NATIVE_VALUE_TYPE_LIST \ \ TOML_SA_LIST_NXT "A non-view type capable of losslessly representing a native TOML value type" \ TOML_SA_LIST_BEG "std::string" \ TOML_SA_VALUE_MESSAGE_WSTRING \ TOML_SA_LIST_SEP "any signed integer type >= 64 bits" \ TOML_SA_LIST_SEP "any floating-point type >= 64 bits" \ TOML_SA_LIST_END \ \ TOML_SA_LIST_NXT "An immutable view type not requiring additional temporary storage" \ TOML_SA_LIST_BEG "std::string_view" \ TOML_SA_VALUE_MESSAGE_U8STRING_VIEW \ TOML_SA_LIST_SEP "const char*" \ TOML_SA_VALUE_MESSAGE_CONST_CHAR8 \ TOML_SA_LIST_END #define TOML_SA_VALUE_FUNC_MESSAGE(type_arg) \ "The " type_arg " must be one of:" \ TOML_SA_LIST_NEW "A native TOML value type" \ TOML_SA_NATIVE_VALUE_TYPE_LIST \ \ TOML_SA_LIST_NXT "A non-view type capable of losslessly representing a native TOML value type" \ TOML_SA_LIST_BEG "std::string" \ TOML_SA_VALUE_MESSAGE_WSTRING \ TOML_SA_LIST_SEP "any signed integer type >= 64 bits" \ TOML_SA_LIST_SEP "any floating-point type >= 64 bits" \ TOML_SA_LIST_END \ \ TOML_SA_LIST_NXT "A non-view type capable of (reasonably) representing a native TOML value type" \ TOML_SA_LIST_BEG "any other integer type" \ TOML_SA_LIST_SEP "any floating-point type >= 32 bits" \ TOML_SA_LIST_END \ \ TOML_SA_LIST_NXT "An immutable view type not requiring additional temporary storage" \ TOML_SA_LIST_BEG "std::string_view" \ TOML_SA_VALUE_MESSAGE_U8STRING_VIEW \ TOML_SA_LIST_SEP "const char*" \ TOML_SA_VALUE_MESSAGE_CONST_CHAR8 \ TOML_SA_LIST_END #endif // !DOXYGEN TOML_PUSH_WARNINGS TOML_DISABLE_ARITHMETIC_WARNINGS TOML_IMPL_NAMESPACE_START { template <typename T, typename...> struct native_value_maker { template <typename... Args> [[nodiscard]] static T make(Args&&... args) noexcept(std::is_nothrow_constructible_v<T, Args&&...>) { return T(std::forward<Args>(args)...); } }; template <typename T> struct native_value_maker<T, T> { template <typename U> [[nodiscard]] TOML_ALWAYS_INLINE static U&& make(U&& val) noexcept { return std::forward<U>(val); } }; #if defined(__cpp_lib_char8_t) || TOML_WINDOWS_COMPAT struct string_maker { template <typename T> [[nodiscard]] static std::string make(T&& arg) noexcept { #ifdef __cpp_lib_char8_t if constexpr (is_one_of<std::decay_t<T>, char8_t*, const char8_t*>) return std::string(reinterpret_cast<const char*>(static_cast<const char8_t*>(arg))); else if constexpr (is_one_of<remove_cvref_t<T>, std::u8string, std::u8string_view>) return std::string(reinterpret_cast<const char*>(static_cast<const char8_t*>(arg.data())), arg.length()); #endif // __cpp_lib_char8_t #if TOML_WINDOWS_COMPAT if constexpr (is_wide_string<T>) return narrow(std::forward<T>(arg)); #endif // TOML_WINDOWS_COMPAT } }; #ifdef __cpp_lib_char8_t template <> struct native_value_maker<std::string, char8_t*> : string_maker {}; template <> struct native_value_maker<std::string, const char8_t*> : string_maker {}; template <> struct native_value_maker<std::string, std::u8string> : string_maker {}; template <> struct native_value_maker<std::string, std::u8string_view> : string_maker {}; #endif // __cpp_lib_char8_t #if TOML_WINDOWS_COMPAT template <> struct native_value_maker<std::string, wchar_t*> : string_maker {}; template <> struct native_value_maker<std::string, const wchar_t*> : string_maker {}; template <> struct native_value_maker<std::string, std::wstring> : string_maker {}; template <> struct native_value_maker<std::string, std::wstring_view> : string_maker {}; #endif // TOML_WINDOWS_COMPAT #endif // defined(__cpp_lib_char8_t) || TOML_WINDOWS_COMPAT template <typename T> [[nodiscard]] TOML_ATTR(const) inline optional<T> node_integer_cast(int64_t val) noexcept { static_assert(node_type_of<T> == node_type::integer); static_assert(!is_cvref<T>); using traits = value_traits<T>; if constexpr (!traits::is_signed) { if constexpr ((sizeof(T) * CHAR_BIT) < 63) // 63 bits == int64_max { using common_t = decltype(int64_t{} + T{}); if (val < int64_t{} || static_cast<common_t>(val) > static_cast<common_t>(traits::max)) return {}; } else { if (val < int64_t{}) return {}; } } else { if (val < traits::min || val > traits::max) return {}; } return { static_cast<T>(val) }; } } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { template <typename ValueType> class TOML_API value final : public node { static_assert( impl::is_native<ValueType> && !impl::is_cvref<ValueType>, "A toml::value<> must model one of the native TOML value types:" TOML_SA_NATIVE_VALUE_TYPE_LIST ); private: friend class TOML_PARSER_TYPENAME; template <typename T, typename U> [[nodiscard]] TOML_ALWAYS_INLINE TOML_ATTR(const) static auto as_value([[maybe_unused]] U* ptr) noexcept { if constexpr (std::is_same_v<value_type, T>) return ptr; else return nullptr; } ValueType val_; public: using value_type = ValueType; using value_arg = std::conditional_t< std::is_same_v<value_type, std::string>, std::string_view, std::conditional_t<impl::is_one_of<value_type, double, int64_t, bool>, value_type, const value_type&> >; template <typename... Args> TOML_NODISCARD_CTOR explicit value(Args&&... args) noexcept(noexcept(value_type( impl::native_value_maker<value_type, std::decay_t<Args>...>::make(std::forward<Args>(args)...) ))) : val_(impl::native_value_maker<value_type, std::decay_t<Args>...>::make(std::forward<Args>(args)...)) {} TOML_NODISCARD_CTOR value(const value& other) noexcept : node{ other }, val_{ other.val_ } {} TOML_NODISCARD_CTOR value(value&& other) noexcept : node{ std::move(other) }, val_{ std::move(other.val_) } {} value& operator= (const value& rhs) noexcept { node::operator=(rhs); val_ = rhs.val_; return *this; } value& operator= (value&& rhs) noexcept { if (&rhs != this) { node::operator=(std::move(rhs)); val_ = std::move(rhs.val_); } return *this; } [[nodiscard]] node_type type() const noexcept override { return impl::node_type_of<value_type>; } [[nodiscard]] bool is_table() const noexcept override { return false; } [[nodiscard]] bool is_array() const noexcept override { return false; } [[nodiscard]] bool is_value() const noexcept override { return true; } [[nodiscard]] bool is_string() const noexcept override { return std::is_same_v<value_type, std::string>; } [[nodiscard]] bool is_integer() const noexcept override { return std::is_same_v<value_type, int64_t>; } [[nodiscard]] bool is_floating_point() const noexcept override { return std::is_same_v<value_type, double>; } [[nodiscard]] bool is_number() const noexcept override { return impl::is_one_of<value_type, int64_t, double>; } [[nodiscard]] bool is_boolean() const noexcept override { return std::is_same_v<value_type, bool>; } [[nodiscard]] bool is_date() const noexcept override { return std::is_same_v<value_type, date>; } [[nodiscard]] bool is_time() const noexcept override { return std::is_same_v<value_type, time>; } [[nodiscard]] bool is_date_time() const noexcept override { return std::is_same_v<value_type, date_time>; } [[nodiscard]] value<std::string>* as_string() noexcept override { return as_value<std::string>(this); } [[nodiscard]] value<int64_t>* as_integer() noexcept override { return as_value<int64_t>(this); } [[nodiscard]] value<double>* as_floating_point() noexcept override { return as_value<double>(this); } [[nodiscard]] value<bool>* as_boolean() noexcept override { return as_value<bool>(this); } [[nodiscard]] value<date>* as_date() noexcept override { return as_value<date>(this); } [[nodiscard]] value<time>* as_time() noexcept override { return as_value<time>(this); } [[nodiscard]] value<date_time>* as_date_time() noexcept override { return as_value<date_time>(this); } [[nodiscard]] const value<std::string>* as_string() const noexcept override { return as_value<std::string>(this); } [[nodiscard]] const value<int64_t>* as_integer() const noexcept override { return as_value<int64_t>(this); } [[nodiscard]] const value<double>* as_floating_point() const noexcept override { return as_value<double>(this); } [[nodiscard]] const value<bool>* as_boolean() const noexcept override { return as_value<bool>(this); } [[nodiscard]] const value<date>* as_date() const noexcept override { return as_value<date>(this); } [[nodiscard]] const value<time>* as_time() const noexcept override { return as_value<time>(this); } [[nodiscard]] const value<date_time>* as_date_time() const noexcept override { return as_value<date_time>(this); } [[nodiscard]] bool is_homogeneous(node_type ntype) const noexcept override { return ntype == node_type::none || ntype == impl::node_type_of<value_type>; } [[nodiscard]] bool is_homogeneous(node_type ntype, toml::node*& first_nonmatch) noexcept override { if (ntype != node_type::none && ntype != impl::node_type_of<value_type>) { first_nonmatch = this; return false; } return true; } [[nodiscard]] bool is_homogeneous(node_type ntype, const toml::node*& first_nonmatch) const noexcept override { if (ntype != node_type::none && ntype != impl::node_type_of<value_type>) { first_nonmatch = this; return false; } return true; } template <typename ElemType = void> [[nodiscard]] bool is_homogeneous() const noexcept { using type = impl::unwrap_node<ElemType>; static_assert( std::is_void_v<type> || ((impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>), "The template type argument of value::is_homogeneous() must be void or one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); using type = impl::unwrap_node<ElemType>; if constexpr (std::is_void_v<type>) return true; else return impl::node_type_of<type> == impl::node_type_of<value_type>; } [[nodiscard]] value_type& get() & noexcept { return val_; } [[nodiscard]] value_type&& get() && noexcept { return std::move(val_); } [[nodiscard]] const value_type& get() const & noexcept { return val_; } [[nodiscard]] value_type& operator* () & noexcept { return val_; } [[nodiscard]] value_type&& operator* () && noexcept { return std::move(val_); } [[nodiscard]] const value_type& operator* () const& noexcept { return val_; } [[nodiscard]] explicit operator value_type& () & noexcept { return val_; } [[nodiscard]] explicit operator value_type && () && noexcept { return std::move(val_); } [[nodiscard]] explicit operator const value_type& () const& noexcept { return val_; } template <typename Char, typename T> friend std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const value<T>& rhs); value& operator= (value_arg rhs) noexcept { if constexpr (std::is_same_v<value_type, std::string>) val_.assign(rhs); else val_ = rhs; return *this; } template <typename T = value_type, typename = std::enable_if_t<std::is_same_v<T, std::string>>> value& operator= (std::string&& rhs) noexcept { val_ = std::move(rhs); return *this; } [[nodiscard]] friend bool operator == (const value& lhs, value_arg rhs) noexcept { if constexpr (std::is_same_v<value_type, double>) { const auto lhs_class = impl::fpclassify(lhs.val_); const auto rhs_class = impl::fpclassify(rhs); if (lhs_class == impl::fp_class::nan && rhs_class == impl::fp_class::nan) return true; if ((lhs_class == impl::fp_class::nan) != (rhs_class == impl::fp_class::nan)) return false; } return lhs.val_ == rhs; } TOML_ASYMMETRICAL_EQUALITY_OPS(const value&, value_arg, ) [[nodiscard]] friend bool operator < (const value& lhs, value_arg rhs) noexcept { return lhs.val_ < rhs; } [[nodiscard]] friend bool operator < (value_arg lhs, const value& rhs) noexcept { return lhs < rhs.val_; } [[nodiscard]] friend bool operator <= (const value& lhs, value_arg rhs) noexcept { return lhs.val_ <= rhs; } [[nodiscard]] friend bool operator <= (value_arg lhs, const value& rhs) noexcept { return lhs <= rhs.val_; } [[nodiscard]] friend bool operator > (const value& lhs, value_arg rhs) noexcept { return lhs.val_ > rhs; } [[nodiscard]] friend bool operator > (value_arg lhs, const value& rhs) noexcept { return lhs > rhs.val_; } [[nodiscard]] friend bool operator >= (const value& lhs, value_arg rhs) noexcept { return lhs.val_ >= rhs; } [[nodiscard]] friend bool operator >= (value_arg lhs, const value& rhs) noexcept { return lhs >= rhs.val_; } template <typename T> [[nodiscard]] friend bool operator == (const value& lhs, const value<T>& rhs) noexcept { if constexpr (std::is_same_v<value_type, T>) return lhs == rhs.val_; //calls asymmetrical value-equality operator defined above else return false; } template <typename T> [[nodiscard]] friend bool operator != (const value& lhs, const value<T>& rhs) noexcept { return !(lhs == rhs); } template <typename T> [[nodiscard]] friend bool operator < (const value& lhs, const value<T>& rhs) noexcept { if constexpr (std::is_same_v<value_type, T>) return lhs.val_ < rhs.val_; else return impl::node_type_of<value_type> < impl::node_type_of<T>; } template <typename T> [[nodiscard]] friend bool operator <= (const value& lhs, const value<T>& rhs) noexcept { if constexpr (std::is_same_v<value_type, T>) return lhs.val_ <= rhs.val_; else return impl::node_type_of<value_type> <= impl::node_type_of<T>; } template <typename T> [[nodiscard]] friend bool operator > (const value& lhs, const value<T>& rhs) noexcept { if constexpr (std::is_same_v<value_type, T>) return lhs.val_ > rhs.val_; else return impl::node_type_of<value_type> > impl::node_type_of<T>; } template <typename T> [[nodiscard]] friend bool operator >= (const value& lhs, const value<T>& rhs) noexcept { if constexpr (std::is_same_v<value_type, T>) return lhs.val_ >= rhs.val_; else return impl::node_type_of<value_type> >= impl::node_type_of<T>; } }; template <typename T> value(T) -> value<impl::native_type_of<impl::remove_cvref_t<T>>>; #ifndef DOXYGEN TOML_PUSH_WARNINGS TOML_DISABLE_INIT_WARNINGS TOML_DISABLE_SWITCH_WARNINGS #if !TOML_HEADER_ONLY extern template class TOML_API value<std::string>; extern template class TOML_API value<int64_t>; extern template class TOML_API value<double>; extern template class TOML_API value<bool>; extern template class TOML_API value<date>; extern template class TOML_API value<time>; extern template class TOML_API value<date_time>; #endif template <typename T> [[nodiscard]] inline decltype(auto) node::get_value_exact() const noexcept { using namespace impl; static_assert(node_type_of<T> != node_type::none); static_assert(node_type_of<T> != node_type::table); static_assert(node_type_of<T> != node_type::array); static_assert(is_native<T> || can_represent_native<T>); static_assert(!is_cvref<T>); TOML_ASSERT(this->type() == node_type_of<T>); if constexpr (node_type_of<T> == node_type::string) { const auto& str = *ref_cast<std::string>(); if constexpr (std::is_same_v<T, std::string>) return str; else if constexpr (std::is_same_v<T, std::string_view>) return T{ str }; else if constexpr (std::is_same_v<T, const char*>) return str.c_str(); else if constexpr (std::is_same_v<T, std::wstring>) { #if TOML_WINDOWS_COMPAT return widen(str); #else static_assert(dependent_false<T>, "Evaluated unreachable branch!"); #endif } #ifdef __cpp_lib_char8_t // char -> char8_t (potentially unsafe - the feature is 'experimental'!) else if constexpr (is_one_of<T, std::u8string, std::u8string_view>) return T(reinterpret_cast<const char8_t*>(str.c_str()), str.length()); else if constexpr (std::is_same_v<T, const char8_t*>) return reinterpret_cast<const char8_t*>(str.c_str()); else static_assert(dependent_false<T>, "Evaluated unreachable branch!"); #endif } else return static_cast<T>(*ref_cast<native_type_of<T>>()); } template <typename T> inline optional<T> node::value_exact() const noexcept { using namespace impl; static_assert( !is_wide_string<T> || TOML_WINDOWS_COMPAT, "Retrieving values as wide-character strings with node::value_exact() is only " "supported on Windows with TOML_WINDOWS_COMPAT enabled." ); static_assert( (is_native<T> || can_represent_native<T>) && !is_cvref<T>, TOML_SA_VALUE_EXACT_FUNC_MESSAGE("return type of node::value_exact()") ); // prevent additional compiler error spam when the static_assert fails by gating behind if constexpr if constexpr ((is_native<T> || can_represent_native<T>) && !is_cvref<T>) { if (type() == node_type_of<T>) return { this->get_value_exact<T>() }; else return {}; } } template <typename T> inline optional<T> node::value() const noexcept { using namespace impl; static_assert( !is_wide_string<T> || TOML_WINDOWS_COMPAT, "Retrieving values as wide-character strings with node::value() is only " "supported on Windows with TOML_WINDOWS_COMPAT enabled." ); static_assert( (is_native<T> || can_represent_native<T> || can_partially_represent_native<T>) && !is_cvref<T>, TOML_SA_VALUE_FUNC_MESSAGE("return type of node::value()") ); // when asking for strings, dates, times and date_times there's no 'fuzzy' conversion // semantics to be mindful of so the exact retrieval is enough. if constexpr (is_natively_one_of<T, std::string, time, date, date_time>) { if (type() == node_type_of<T>) return { this->get_value_exact<T>() }; else return {}; } // everything else requires a bit of logicking. else { switch (type()) { // int -> * case node_type::integer: { // int -> int if constexpr (is_natively_one_of<T, int64_t>) { if constexpr (is_native<T> || can_represent_native<T>) return static_cast<T>(*ref_cast<int64_t>()); else return node_integer_cast<T>(*ref_cast<int64_t>()); } // int -> float else if constexpr (is_natively_one_of<T, double>) { const int64_t val = *ref_cast<int64_t>(); if constexpr (std::numeric_limits<T>::digits < 64) { constexpr auto largest_whole_float = (int64_t{ 1 } << std::numeric_limits<T>::digits); if (val < -largest_whole_float || val > largest_whole_float) return {}; } return static_cast<T>(val); } // int -> bool else if constexpr (is_natively_one_of<T, bool>) return static_cast<bool>(*ref_cast<int64_t>()); // int -> anything else else return {}; } // float -> * case node_type::floating_point: { // float -> float if constexpr (is_natively_one_of<T, double>) { if constexpr (is_native<T> || can_represent_native<T>) return { static_cast<T>(*ref_cast<double>()) }; else { const double val = *ref_cast<double>(); if (val < (std::numeric_limits<T>::lowest)() || val > (std::numeric_limits<T>::max)()) return {}; return { static_cast<T>(val) }; } } // float -> int else if constexpr (is_natively_one_of<T, int64_t>) { const double val = *ref_cast<double>(); if (static_cast<double>(static_cast<int64_t>(val)) == val) return node_integer_cast<T>(static_cast<int64_t>(val)); else return {}; } // float -> anything else else return {}; } // bool -> * case node_type::boolean: { // bool -> bool if constexpr (is_natively_one_of<T, bool>) return { *ref_cast<bool>() }; // bool -> int else if constexpr (is_natively_one_of<T, int64_t>) return { static_cast<T>(*ref_cast<bool>()) }; // bool -> anything else else return {}; } } // non-values, or 'exact' types covered above return {}; } } template <typename T> inline auto node::value_or(T&& default_value) const noexcept { using namespace impl; static_assert( !is_wide_string<T> || TOML_WINDOWS_COMPAT, "Retrieving values as wide-character strings with node::value_or() is only " "supported on Windows with TOML_WINDOWS_COMPAT enabled." ); if constexpr (is_wide_string<T>) { #if TOML_WINDOWS_COMPAT if (type() == node_type::string) return widen(*ref_cast<std::string>()); return std::wstring{ std::forward<T>(default_value) }; #else static_assert(dependent_false<T>, "Evaluated unreachable branch!"); #endif } else { using value_type = std::conditional_t< std::is_pointer_v<std::decay_t<T>>, std::add_pointer_t<std::add_const_t<std::remove_pointer_t<std::decay_t<T>>>>, std::decay_t<T> >; using traits = value_traits<value_type>; static_assert( traits::is_native || traits::can_represent_native || traits::can_partially_represent_native, "The default value type of node::value_or() must be one of:" TOML_SA_LIST_NEW "A native TOML value type" TOML_SA_NATIVE_VALUE_TYPE_LIST TOML_SA_LIST_NXT "A non-view type capable of losslessly representing a native TOML value type" TOML_SA_LIST_BEG "std::string" #if TOML_WINDOWS_COMPAT TOML_SA_LIST_SEP "std::wstring" #endif TOML_SA_LIST_SEP "any signed integer type >= 64 bits" TOML_SA_LIST_SEP "any floating-point type >= 64 bits" TOML_SA_LIST_END TOML_SA_LIST_NXT "A non-view type capable of (reasonably) representing a native TOML value type" TOML_SA_LIST_BEG "any other integer type" TOML_SA_LIST_SEP "any floating-point type >= 32 bits" TOML_SA_LIST_END TOML_SA_LIST_NXT "A compatible view type" TOML_SA_LIST_BEG "std::string_view" #ifdef __cpp_lib_char8_t TOML_SA_LIST_SEP "std::u8string_view" #endif #if TOML_WINDOWS_COMPAT TOML_SA_LIST_SEP "std::wstring_view" #endif TOML_SA_LIST_SEP "const char*" #ifdef __cpp_lib_char8_t TOML_SA_LIST_SEP "const char8_t*" #endif #if TOML_WINDOWS_COMPAT TOML_SA_LIST_SEP "const wchar_t*" #endif TOML_SA_LIST_END ); // prevent additional compiler error spam when the static_assert fails by gating behind if constexpr if constexpr (traits::is_native || traits::can_represent_native || traits::can_partially_represent_native) { if constexpr (traits::is_native) { if (type() == node_type_of<value_type>) return *ref_cast<typename traits::native_type>(); } if (auto val = this->value<value_type>()) return *val; if constexpr (std::is_pointer_v<value_type>) return value_type{ default_value }; else return std::forward<T>(default_value); } } } #if !TOML_HEADER_ONLY #define TOML_EXTERN(name, T) \ extern template TOML_API optional<T> node::name<T>() const noexcept TOML_EXTERN(value_exact, std::string_view); TOML_EXTERN(value_exact, std::string); TOML_EXTERN(value_exact, const char*); TOML_EXTERN(value_exact, int64_t); TOML_EXTERN(value_exact, double); TOML_EXTERN(value_exact, date); TOML_EXTERN(value_exact, time); TOML_EXTERN(value_exact, date_time); TOML_EXTERN(value_exact, bool); TOML_EXTERN(value, std::string_view); TOML_EXTERN(value, std::string); TOML_EXTERN(value, const char*); TOML_EXTERN(value, signed char); TOML_EXTERN(value, signed short); TOML_EXTERN(value, signed int); TOML_EXTERN(value, signed long); TOML_EXTERN(value, signed long long); TOML_EXTERN(value, unsigned char); TOML_EXTERN(value, unsigned short); TOML_EXTERN(value, unsigned int); TOML_EXTERN(value, unsigned long); TOML_EXTERN(value, unsigned long long); TOML_EXTERN(value, double); TOML_EXTERN(value, float); TOML_EXTERN(value, date); TOML_EXTERN(value, time); TOML_EXTERN(value, date_time); TOML_EXTERN(value, bool); #ifdef __cpp_lib_char8_t TOML_EXTERN(value_exact, std::u8string_view); TOML_EXTERN(value_exact, std::u8string); TOML_EXTERN(value_exact, const char8_t*); TOML_EXTERN(value, std::u8string_view); TOML_EXTERN(value, std::u8string); TOML_EXTERN(value, const char8_t*); #endif #if TOML_WINDOWS_COMPAT TOML_EXTERN(value_exact, std::wstring); TOML_EXTERN(value, std::wstring); #endif #undef TOML_EXTERN #endif // !TOML_HEADER_ONLY TOML_POP_WARNINGS // TOML_DISABLE_INIT_WARNINGS, TOML_DISABLE_SWITCH_WARNINGS #endif // !DOXYGEN } TOML_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_ARITHMETIC_WARNINGS #endif //---------------------------------- ↑ toml_value.h ----------------------------------------------------------- #if 1 //----------------------------------------------------------- ↓ toml_array.h ---------------------------------- TOML_IMPL_NAMESPACE_START { template <bool IsConst> class TOML_TRIVIAL_ABI array_iterator final { private: friend class TOML_NAMESPACE::array; using raw_mutable_iterator = std::vector<std::unique_ptr<node>>::iterator; using raw_const_iterator = std::vector<std::unique_ptr<node>>::const_iterator; using raw_iterator = std::conditional_t<IsConst, raw_const_iterator, raw_mutable_iterator>; mutable raw_iterator raw_; array_iterator(raw_mutable_iterator raw) noexcept : raw_{ raw } {} template <bool C = IsConst, typename = std::enable_if_t<C>> TOML_NODISCARD_CTOR array_iterator(raw_const_iterator raw) noexcept : raw_{ raw } {} public: using value_type = std::conditional_t<IsConst, const node, node>; using reference = value_type&; using pointer = value_type*; using difference_type = ptrdiff_t; array_iterator() noexcept = default; array_iterator(const array_iterator&) noexcept = default; array_iterator& operator = (const array_iterator&) noexcept = default; array_iterator& operator++() noexcept // ++pre { ++raw_; return *this; } array_iterator operator++(int) noexcept // post++ { array_iterator out{ raw_ }; ++raw_; return out; } array_iterator& operator--() noexcept // --pre { --raw_; return *this; } array_iterator operator--(int) noexcept // post-- { array_iterator out{ raw_ }; --raw_; return out; } [[nodiscard]] reference operator * () const noexcept { return *raw_->get(); } [[nodiscard]] pointer operator -> () const noexcept { return raw_->get(); } array_iterator& operator += (ptrdiff_t rhs) noexcept { raw_ += rhs; return *this; } array_iterator& operator -= (ptrdiff_t rhs) noexcept { raw_ -= rhs; return *this; } [[nodiscard]] friend constexpr array_iterator operator + (const array_iterator& lhs, ptrdiff_t rhs) noexcept { return { lhs.raw_ + rhs }; } [[nodiscard]] friend constexpr array_iterator operator + (ptrdiff_t lhs, const array_iterator& rhs) noexcept { return { rhs.raw_ + lhs }; } [[nodiscard]] friend constexpr array_iterator operator - (const array_iterator& lhs, ptrdiff_t rhs) noexcept { return { lhs.raw_ - rhs }; } [[nodiscard]] friend constexpr ptrdiff_t operator - (const array_iterator& lhs, const array_iterator& rhs) noexcept { return lhs.raw_ - rhs.raw_; } [[nodiscard]] friend constexpr bool operator == (const array_iterator& lhs, const array_iterator& rhs) noexcept { return lhs.raw_ == rhs.raw_; } [[nodiscard]] friend constexpr bool operator != (const array_iterator& lhs, const array_iterator& rhs) noexcept { return lhs.raw_ != rhs.raw_; } [[nodiscard]] friend constexpr bool operator < (const array_iterator& lhs, const array_iterator& rhs) noexcept { return lhs.raw_ < rhs.raw_; } [[nodiscard]] friend constexpr bool operator <= (const array_iterator& lhs, const array_iterator& rhs) noexcept { return lhs.raw_ <= rhs.raw_; } [[nodiscard]] friend constexpr bool operator > (const array_iterator& lhs, const array_iterator& rhs) noexcept { return lhs.raw_ > rhs.raw_; } [[nodiscard]] friend constexpr bool operator >= (const array_iterator& lhs, const array_iterator& rhs) noexcept { return lhs.raw_ >= rhs.raw_; } [[nodiscard]] reference operator[] (ptrdiff_t idx) const noexcept { return *(raw_ + idx)->get(); } TOML_DISABLE_WARNINGS template <bool C = IsConst, typename = std::enable_if_t<!C>> [[nodiscard]] operator array_iterator<true>() const noexcept { return array_iterator<true>{ raw_ }; } TOML_ENABLE_WARNINGS }; template <typename T> [[nodiscard]] TOML_ATTR(returns_nonnull) auto* make_node_specialized(T&& val) noexcept { using type = unwrap_node<remove_cvref_t<T>>; static_assert(!std::is_same_v<type, node>); static_assert(!is_node_view<type>); if constexpr (is_one_of<type, array, table>) { return new type{ std::forward<T>(val) }; } else { static_assert( !is_wide_string<T> || TOML_WINDOWS_COMPAT, "Instantiating values from wide-character strings is only " "supported on Windows with TOML_WINDOWS_COMPAT enabled." ); static_assert( is_native<type> || is_losslessly_convertible_to_native<type>, "Value initializers must be (or be promotable to) one of the TOML value types" ); if constexpr (is_wide_string<T>) { #if TOML_WINDOWS_COMPAT return new value{ narrow(std::forward<T>(val)) }; #else static_assert(dependent_false<T>, "Evaluated unreachable branch!"); #endif } else return new value{ std::forward<T>(val) }; } } template <typename T> [[nodiscard]] auto* make_node(T&& val) noexcept { using type = unwrap_node<remove_cvref_t<T>>; if constexpr (std::is_same_v<type, node> || is_node_view<type>) { if constexpr (is_node_view<type>) { if (!val) return static_cast<toml::node*>(nullptr); } return std::forward<T>(val).visit([](auto&& concrete) noexcept { return static_cast<toml::node*>(make_node_specialized(std::forward<decltype(concrete)>(concrete))); }); } else return make_node_specialized(std::forward<T>(val)); } template <typename T> [[nodiscard]] auto* make_node(inserter<T>&& val) noexcept { return make_node(std::move(val.value)); } } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { using array_iterator = impl::array_iterator<false>; using const_array_iterator = impl::array_iterator<true>; class TOML_API array final : public node { private: friend class TOML_PARSER_TYPENAME; std::vector<std::unique_ptr<node>> elements; void preinsertion_resize(size_t idx, size_t count) noexcept; template <typename T> void emplace_back_if_not_empty_view(T&& val) noexcept { if constexpr (impl::is_node_view<T>) { if (!val) return; } elements.emplace_back(impl::make_node(std::forward<T>(val))); } public: using value_type = node; using size_type = size_t; using difference_type = ptrdiff_t; using reference = node&; using const_reference = const node&; using iterator = array_iterator; using const_iterator = const_array_iterator; TOML_NODISCARD_CTOR array() noexcept; TOML_NODISCARD_CTOR array(const array&) noexcept; TOML_NODISCARD_CTOR array(array&& other) noexcept; array& operator= (const array&) noexcept; array& operator= (array&& rhs) noexcept; template <typename ElemType, typename... ElemTypes, typename = std::enable_if_t< (sizeof...(ElemTypes) > 0_sz) || !std::is_same_v<impl::remove_cvref_t<ElemType>, array> >> TOML_NODISCARD_CTOR explicit array(ElemType&& val, ElemTypes&&... vals) { elements.reserve(sizeof...(ElemTypes) + 1_sz); emplace_back_if_not_empty_view(std::forward<ElemType>(val)); if constexpr (sizeof...(ElemTypes) > 0) { ( emplace_back_if_not_empty_view(std::forward<ElemTypes>(vals)), ... ); } } [[nodiscard]] node_type type() const noexcept override; [[nodiscard]] bool is_table() const noexcept override; [[nodiscard]] bool is_array() const noexcept override; [[nodiscard]] bool is_value() const noexcept override; [[nodiscard]] array* as_array() noexcept override; [[nodiscard]] const array* as_array() const noexcept override; [[nodiscard]] bool is_array_of_tables() const noexcept override; [[nodiscard]] bool is_homogeneous(node_type ntype) const noexcept override; [[nodiscard]] bool is_homogeneous(node_type ntype, node*& first_nonmatch) noexcept override; [[nodiscard]] bool is_homogeneous(node_type ntype, const node*& first_nonmatch) const noexcept override; template <typename ElemType = void> [[nodiscard]] bool is_homogeneous() const noexcept { using type = impl::unwrap_node<ElemType>; static_assert( std::is_void_v<type> || ((impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>), "The template type argument of array::is_homogeneous() must be void or one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); return is_homogeneous(impl::node_type_of<type>); } [[nodiscard]] node& operator[] (size_t index) noexcept; [[nodiscard]] const node& operator[] (size_t index) const noexcept; [[nodiscard]] node& front() noexcept; [[nodiscard]] const node& front() const noexcept; [[nodiscard]] node& back() noexcept; [[nodiscard]] const node& back() const noexcept; [[nodiscard]] iterator begin() noexcept; [[nodiscard]] const_iterator begin() const noexcept; [[nodiscard]] const_iterator cbegin() const noexcept; [[nodiscard]] iterator end() noexcept; [[nodiscard]] const_iterator end() const noexcept; [[nodiscard]] const_iterator cend() const noexcept; [[nodiscard]] bool empty() const noexcept; [[nodiscard]] size_t size() const noexcept; void reserve(size_t new_capacity); void clear() noexcept; [[nodiscard]] size_t max_size() const noexcept; [[nodiscard]] size_t capacity() const noexcept; void shrink_to_fit(); template <typename ElemType> iterator insert(const_iterator pos, ElemType&& val) noexcept { if constexpr (impl::is_node_view<ElemType>) { if (!val) return end(); } return { elements.emplace(pos.raw_, impl::make_node(std::forward<ElemType>(val))) }; } template <typename ElemType> iterator insert(const_iterator pos, size_t count, ElemType&& val) noexcept { if constexpr (impl::is_node_view<ElemType>) { if (!val) return end(); } switch (count) { case 0: return { elements.begin() + (pos.raw_ - elements.cbegin()) }; case 1: return insert(pos, std::forward<ElemType>(val)); default: { const auto start_idx = static_cast<size_t>(pos.raw_ - elements.cbegin()); preinsertion_resize(start_idx, count); size_t i = start_idx; for (size_t e = start_idx + count - 1_sz; i < e; i++) elements[i].reset(impl::make_node(val)); elements[i].reset(impl::make_node(std::forward<ElemType>(val))); return { elements.begin() + static_cast<ptrdiff_t>(start_idx) }; } } } template <typename Iter> iterator insert(const_iterator pos, Iter first, Iter last) noexcept { const auto distance = std::distance(first, last); if (distance <= 0) return { elements.begin() + (pos.raw_ - elements.cbegin()) }; else { auto count = distance; using deref_type = decltype(*first); if constexpr (impl::is_node_view<deref_type>) { for (auto it = first; it != last; it++) if (!(*it)) count--; if (!count) return { elements.begin() + (pos.raw_ - elements.cbegin()) }; } const auto start_idx = static_cast<size_t>(pos.raw_ - elements.cbegin()); preinsertion_resize(start_idx, static_cast<size_t>(count)); size_t i = start_idx; for (auto it = first; it != last; it++) { if constexpr (impl::is_node_view<deref_type>) { if (!(*it)) continue; } if constexpr (std::is_rvalue_reference_v<deref_type>) elements[i++].reset(impl::make_node(std::move(*it))); else elements[i++].reset(impl::make_node(*it)); } return { elements.begin() + static_cast<ptrdiff_t>(start_idx) }; } } template <typename ElemType> iterator insert(const_iterator pos, std::initializer_list<ElemType> ilist) noexcept { return insert(pos, ilist.begin(), ilist.end()); } template <typename ElemType, typename... Args> iterator emplace(const_iterator pos, Args&&... args) noexcept { using type = impl::unwrap_node<ElemType>; static_assert( (impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>, "Emplacement type parameter must be one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); return { elements.emplace(pos.raw_, new impl::wrap_node<type>{ std::forward<Args>(args)...} ) }; } iterator erase(const_iterator pos) noexcept; iterator erase(const_iterator first, const_iterator last) noexcept; template <typename ElemType> void resize(size_t new_size, ElemType&& default_init_val) noexcept { static_assert( !impl::is_node_view<ElemType>, "The default element type argument to toml::array::resize may not be toml::node_view." ); if (!new_size) elements.clear(); else if (new_size < elements.size()) elements.resize(new_size); else if (new_size > elements.size()) insert(cend(), new_size - elements.size(), std::forward<ElemType>(default_init_val)); } void truncate(size_t new_size); template <typename ElemType> void push_back(ElemType&& val) noexcept { emplace_back_if_not_empty_view(std::forward<ElemType>(val)); } template <typename ElemType, typename... Args> decltype(auto) emplace_back(Args&&... args) noexcept { using type = impl::unwrap_node<ElemType>; static_assert( (impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>, "Emplacement type parameter must be one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); auto nde = new impl::wrap_node<type>{ std::forward<Args>(args)... }; elements.emplace_back(nde); return *nde; } void pop_back() noexcept; [[nodiscard]] node* get(size_t index) noexcept; [[nodiscard]] const node* get(size_t index) const noexcept; template <typename ElemType> [[nodiscard]] impl::wrap_node<ElemType>* get_as(size_t index) noexcept { if (auto val = get(index)) return val->as<ElemType>(); return nullptr; } template <typename ElemType> [[nodiscard]] const impl::wrap_node<ElemType>* get_as(size_t index) const noexcept { if (auto val = get(index)) return val->as<ElemType>(); return nullptr; } friend bool operator == (const array& lhs, const array& rhs) noexcept; friend bool operator != (const array& lhs, const array& rhs) noexcept; private: template <typename T> [[nodiscard]] static bool container_equality(const array& lhs, const T& rhs) noexcept { using element_type = std::remove_const_t<typename T::value_type>; static_assert( impl::is_native<element_type> || impl::is_losslessly_convertible_to_native<element_type>, "Container element type must be (or be promotable to) one of the TOML value types" ); if (lhs.size() != rhs.size()) return false; if (rhs.size() == 0_sz) return true; size_t i{}; for (auto& list_elem : rhs) { const auto elem = lhs.get_as<impl::native_type_of<element_type>>(i++); if (!elem || *elem != list_elem) return false; } return true; } [[nodiscard]] size_t total_leaf_count() const noexcept; void flatten_child(array&& child, size_t& dest_index) noexcept; public: template <typename T> [[nodiscard]] friend bool operator == (const array& lhs, const std::initializer_list<T>& rhs) noexcept { return container_equality(lhs, rhs); } TOML_ASYMMETRICAL_EQUALITY_OPS(const array&, const std::initializer_list<T>&, template <typename T>) template <typename T> [[nodiscard]] friend bool operator == (const array& lhs, const std::vector<T>& rhs) noexcept { return container_equality(lhs, rhs); } TOML_ASYMMETRICAL_EQUALITY_OPS(const array&, const std::vector<T>&, template <typename T>) array& flatten() &; array&& flatten() && { return static_cast<toml::array&&>(static_cast<toml::array&>(*this).flatten()); } template <typename Char> friend std::basic_ostream<Char>& operator << (std::basic_ostream<Char>&, const array&); }; } TOML_NAMESPACE_END #endif //----------------------------------------------------------- ↑ toml_array.h ---------------------------------- #if 1 //------------------------------------------------------------------------------------ ↓ toml_table.h --------- TOML_IMPL_NAMESPACE_START { template <bool IsConst> struct table_proxy_pair final { using value_type = std::conditional_t<IsConst, const node, node>; const std::string& first; value_type& second; }; template <bool IsConst> class table_iterator final { private: friend class TOML_NAMESPACE::table; using proxy_type = table_proxy_pair<IsConst>; using raw_mutable_iterator = string_map<std::unique_ptr<node>>::iterator; using raw_const_iterator = string_map<std::unique_ptr<node>>::const_iterator; using raw_iterator = std::conditional_t<IsConst, raw_const_iterator, raw_mutable_iterator>; mutable raw_iterator raw_; mutable std::aligned_storage_t<sizeof(proxy_type), alignof(proxy_type)> proxy; mutable bool proxy_instantiated = false; [[nodiscard]] proxy_type* get_proxy() const noexcept { if (!proxy_instantiated) { auto p = new (&proxy) proxy_type{ raw_->first, *raw_->second.get() }; proxy_instantiated = true; return p; } else return TOML_LAUNDER(reinterpret_cast<proxy_type*>(&proxy)); } table_iterator(raw_mutable_iterator raw) noexcept : raw_{ raw } {} template <bool C = IsConst, typename = std::enable_if_t<C>> TOML_NODISCARD_CTOR table_iterator(raw_const_iterator raw) noexcept : raw_{ raw } {} public: table_iterator() noexcept = default; table_iterator(const table_iterator& other) noexcept : raw_{ other.raw_ } {} table_iterator& operator = (const table_iterator& rhs) noexcept { raw_ = rhs.raw_; proxy_instantiated = false; return *this; } using value_type = table_proxy_pair<IsConst>; using reference = value_type&; using pointer = value_type*; table_iterator& operator++() noexcept // ++pre { ++raw_; proxy_instantiated = false; return *this; } table_iterator operator++(int) noexcept // post++ { table_iterator out{ raw_ }; ++raw_; proxy_instantiated = false; return out; } table_iterator& operator--() noexcept // --pre { --raw_; proxy_instantiated = false; return *this; } table_iterator operator--(int) noexcept // post-- { table_iterator out{ raw_ }; --raw_; proxy_instantiated = false; return out; } [[nodiscard]] reference operator* () const noexcept { return *get_proxy(); } [[nodiscard]] pointer operator -> () const noexcept { return get_proxy(); } [[nodiscard]] friend constexpr bool operator == (const table_iterator& lhs, const table_iterator& rhs) noexcept { return lhs.raw_ == rhs.raw_; } [[nodiscard]] friend constexpr bool operator != (const table_iterator& lhs, const table_iterator& rhs) noexcept { return lhs.raw_ != rhs.raw_; } TOML_DISABLE_WARNINGS template <bool C = IsConst, typename = std::enable_if_t<!C>> [[nodiscard]] operator table_iterator<true>() const noexcept { return table_iterator<true>{ raw_ }; } TOML_ENABLE_WARNINGS }; struct table_init_pair final { std::string key; std::unique_ptr<node> value; template <typename V> table_init_pair(std::string&& k, V&& v) noexcept : key{ std::move(k) }, value{ make_node(std::forward<V>(v)) } {} template <typename V> table_init_pair(std::string_view k, V&& v) noexcept : key{ k }, value{ make_node(std::forward<V>(v)) } {} template <typename V> table_init_pair(const char* k, V&& v) noexcept : key{ k }, value{ make_node(std::forward<V>(v)) } {} #if TOML_WINDOWS_COMPAT template <typename V> table_init_pair(std::wstring&& k, V&& v) noexcept : key{ narrow(k) }, value{ make_node(std::forward<V>(v)) } {} template <typename V> table_init_pair(std::wstring_view k, V&& v) noexcept : key{ narrow(k) }, value{ make_node(std::forward<V>(v)) } {} template <typename V> table_init_pair(const wchar_t* k, V&& v) noexcept : key{ narrow(std::wstring_view{ k }) }, value{ make_node(std::forward<V>(v)) } {} #endif }; } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { using table_iterator = impl::table_iterator<false>; using const_table_iterator = impl::table_iterator<true>; class TOML_API table final : public node { private: friend class TOML_PARSER_TYPENAME; impl::string_map<std::unique_ptr<node>> map; bool inline_ = false; table(impl::table_init_pair*, size_t) noexcept; public: using iterator = table_iterator; using const_iterator = const_table_iterator; TOML_NODISCARD_CTOR table() noexcept; TOML_NODISCARD_CTOR table(const table&) noexcept; TOML_NODISCARD_CTOR table(table&& other) noexcept; table& operator= (const table&) noexcept; table& operator= (table&& rhs) noexcept; template <size_t N> TOML_NODISCARD_CTOR explicit table(impl::table_init_pair(&& arr)[N]) noexcept : table{ arr, N } {} [[nodiscard]] node_type type() const noexcept override; [[nodiscard]] bool is_table() const noexcept override; [[nodiscard]] bool is_array() const noexcept override; [[nodiscard]] bool is_value() const noexcept override; [[nodiscard]] table* as_table() noexcept override; [[nodiscard]] const table* as_table() const noexcept override; [[nodiscard]] bool is_homogeneous(node_type ntype) const noexcept override; [[nodiscard]] bool is_homogeneous(node_type ntype, node*& first_nonmatch) noexcept override; [[nodiscard]] bool is_homogeneous(node_type ntype, const node*& first_nonmatch) const noexcept override; template <typename ElemType = void> [[nodiscard]] bool is_homogeneous() const noexcept { using type = impl::unwrap_node<ElemType>; static_assert( std::is_void_v<type> || ((impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>), "The template type argument of table::is_homogeneous() must be void or one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); return is_homogeneous(impl::node_type_of<type>); } [[nodiscard]] bool is_inline() const noexcept; void is_inline(bool val) noexcept; [[nodiscard]] node_view<node> operator[] (std::string_view key) noexcept; [[nodiscard]] node_view<const node> operator[] (std::string_view key) const noexcept; #if TOML_WINDOWS_COMPAT [[nodiscard]] node_view<node> operator[] (std::wstring_view key) noexcept; [[nodiscard]] node_view<const node> operator[] (std::wstring_view key) const noexcept; #endif // TOML_WINDOWS_COMPAT [[nodiscard]] iterator begin() noexcept; [[nodiscard]] const_iterator begin() const noexcept; [[nodiscard]] const_iterator cbegin() const noexcept; [[nodiscard]] iterator end() noexcept; [[nodiscard]] const_iterator end() const noexcept; [[nodiscard]] const_iterator cend() const noexcept; [[nodiscard]] bool empty() const noexcept; [[nodiscard]] size_t size() const noexcept; void clear() noexcept; template <typename KeyType, typename ValueType, typename = std::enable_if_t< std::is_convertible_v<KeyType&&, std::string_view> || impl::is_wide_string<KeyType> >> std::pair<iterator, bool> insert(KeyType&& key, ValueType&& val) noexcept { static_assert( !impl::is_wide_string<KeyType> || TOML_WINDOWS_COMPAT, "Insertion using wide-character keys is only supported on Windows with TOML_WINDOWS_COMPAT enabled." ); if constexpr (impl::is_node_view<ValueType>) { if (!val) return { end(), false }; } if constexpr (impl::is_wide_string<KeyType>) { #if TOML_WINDOWS_COMPAT return insert(impl::narrow(std::forward<KeyType>(key)), std::forward<ValueType>(val)); #else static_assert(impl::dependent_false<KeyType>, "Evaluated unreachable branch!"); #endif } else { auto ipos = map.lower_bound(key); if (ipos == map.end() || ipos->first != key) { ipos = map.emplace_hint(ipos, std::forward<KeyType>(key), impl::make_node(std::forward<ValueType>(val))); return { iterator{ ipos }, true }; } return { iterator{ ipos }, false }; } } template <typename Iter, typename = std::enable_if_t< !std::is_convertible_v<Iter, std::string_view> && !impl::is_wide_string<Iter> >> void insert(Iter first, Iter last) noexcept { if (first == last) return; for (auto it = first; it != last; it++) { if constexpr (std::is_rvalue_reference_v<decltype(*it)>) insert(std::move((*it).first), std::move((*it).second)); else insert((*it).first, (*it).second); } } template <typename KeyType, typename ValueType> std::pair<iterator, bool> insert_or_assign(KeyType&& key, ValueType&& val) noexcept { static_assert( !impl::is_wide_string<KeyType> || TOML_WINDOWS_COMPAT, "Insertion using wide-character keys is only supported on Windows with TOML_WINDOWS_COMPAT enabled." ); if constexpr (impl::is_node_view<ValueType>) { if (!val) return { end(), false }; } if constexpr (impl::is_wide_string<KeyType>) { #if TOML_WINDOWS_COMPAT return insert_or_assign(impl::narrow(std::forward<KeyType>(key)), std::forward<ValueType>(val)); #else static_assert(impl::dependent_false<KeyType>, "Evaluated unreachable branch!"); #endif } else { auto ipos = map.lower_bound(key); if (ipos == map.end() || ipos->first != key) { ipos = map.emplace_hint(ipos, std::forward<KeyType>(key), impl::make_node(std::forward<ValueType>(val))); return { iterator{ ipos }, true }; } else { (*ipos).second.reset(impl::make_node(std::forward<ValueType>(val))); return { iterator{ ipos }, false }; } } } template <typename ValueType, typename KeyType, typename... ValueArgs> std::pair<iterator, bool> emplace(KeyType&& key, ValueArgs&&... args) noexcept { static_assert( !impl::is_wide_string<KeyType> || TOML_WINDOWS_COMPAT, "Emplacement using wide-character keys is only supported on Windows with TOML_WINDOWS_COMPAT enabled." ); if constexpr (impl::is_wide_string<KeyType>) { #if TOML_WINDOWS_COMPAT return emplace<ValueType>(impl::narrow(std::forward<KeyType>(key)), std::forward<ValueArgs>(args)...); #else static_assert(impl::dependent_false<KeyType>, "Evaluated unreachable branch!"); #endif } else { using type = impl::unwrap_node<ValueType>; static_assert( (impl::is_native<type> || impl::is_one_of<type, table, array>) && !impl::is_cvref<type>, "The emplacement type argument of table::emplace() must be one of:" TOML_SA_UNWRAPPED_NODE_TYPE_LIST ); auto ipos = map.lower_bound(key); if (ipos == map.end() || ipos->first != key) { ipos = map.emplace_hint( ipos, std::forward<KeyType>(key), new impl::wrap_node<type>{ std::forward<ValueArgs>(args)... } ); return { iterator{ ipos }, true }; } return { iterator{ ipos }, false }; } } iterator erase(iterator pos) noexcept; iterator erase(const_iterator pos) noexcept; iterator erase(const_iterator first, const_iterator last) noexcept; bool erase(std::string_view key) noexcept; #if TOML_WINDOWS_COMPAT bool erase(std::wstring_view key) noexcept; #endif private: template <typename Map, typename Key> [[nodiscard]] static auto do_get(Map& vals, const Key& key) noexcept -> std::conditional_t<std::is_const_v<Map>, const node*, node*> { static_assert( !impl::is_wide_string<Key> || TOML_WINDOWS_COMPAT, "Retrieval using wide-character keys is only supported on Windows with TOML_WINDOWS_COMPAT enabled." ); if constexpr (impl::is_wide_string<Key>) { #if TOML_WINDOWS_COMPAT return do_get(vals, impl::narrow(key)); #else static_assert(impl::dependent_false<Key>, "Evaluated unreachable branch!"); #endif } else { if (auto it = vals.find(key); it != vals.end()) return { it->second.get() }; return {}; } } template <typename T, typename Map, typename Key> [[nodiscard]] static auto do_get_as(Map& vals, const Key& key) noexcept { const auto node = do_get(vals, key); return node ? node->template as<T>() : nullptr; } template <typename Map, typename Key> [[nodiscard]] TOML_ALWAYS_INLINE static bool do_contains(Map& vals, const Key& key) noexcept { return do_get(vals, key) != nullptr; } public: [[nodiscard]] node* get(std::string_view key) noexcept; [[nodiscard]] const node* get(std::string_view key) const noexcept; [[nodiscard]] iterator find(std::string_view key) noexcept; [[nodiscard]] const_iterator find(std::string_view key) const noexcept; [[nodiscard]] bool contains(std::string_view key) const noexcept; #if TOML_WINDOWS_COMPAT [[nodiscard]] node* get(std::wstring_view key) noexcept; [[nodiscard]] const node* get(std::wstring_view key) const noexcept; [[nodiscard]] iterator find(std::wstring_view key) noexcept; [[nodiscard]] const_iterator find(std::wstring_view key) const noexcept; [[nodiscard]] bool contains(std::wstring_view key) const noexcept; #endif // TOML_WINDOWS_COMPAT template <typename ValueType> [[nodiscard]] impl::wrap_node<ValueType>* get_as(std::string_view key) noexcept { return do_get_as<ValueType>(map, key); } template <typename ValueType> [[nodiscard]] const impl::wrap_node<ValueType>* get_as(std::string_view key) const noexcept { return do_get_as<ValueType>(map, key); } #if TOML_WINDOWS_COMPAT template <typename ValueType> [[nodiscard]] impl::wrap_node<ValueType>* get_as(std::wstring_view key) noexcept { return get_as<ValueType>(impl::narrow(key)); } template <typename ValueType> [[nodiscard]] const impl::wrap_node<ValueType>* get_as(std::wstring_view key) const noexcept { return get_as<ValueType>(impl::narrow(key)); } #endif // TOML_WINDOWS_COMPAT friend bool operator == (const table& lhs, const table& rhs) noexcept; friend bool operator != (const table& lhs, const table& rhs) noexcept; template <typename Char> friend std::basic_ostream<Char>& operator << (std::basic_ostream<Char>&, const table&); }; #ifndef DOXYGEN //template <typename T> //inline std::vector<T> node::select_exact() const noexcept //{ // using namespace impl; // static_assert( // !is_wide_string<T> || TOML_WINDOWS_COMPAT, // "Retrieving values as wide-character strings with node::select_exact() is only " // "supported on Windows with TOML_WINDOWS_COMPAT enabled." // ); // static_assert( // (is_native<T> || can_represent_native<T>) && !is_cvref<T>, // TOML_SA_VALUE_EXACT_FUNC_MESSAGE("return type of node::select_exact()") // ); //} //template <typename T> //inline std::vector<T> node::select() const noexcept //{ // using namespace impl; // static_assert( // !is_wide_string<T> || TOML_WINDOWS_COMPAT, // "Retrieving values as wide-character strings with node::select() is only " // "supported on Windows with TOML_WINDOWS_COMPAT enabled." // ); // static_assert( // (is_native<T> || can_represent_native<T> || can_partially_represent_native<T>) && !is_cvref<T>, // TOML_SA_VALUE_FUNC_MESSAGE("return type of node::select()") // ); //} #endif // !DOXYGEN } TOML_NAMESPACE_END #endif //------------------------------------------------------------------------------------ ↑ toml_table.h --------- #if 1 //------- ↓ toml_node_view.h ---------------------------------------------------------------------------------- TOML_PUSH_WARNINGS TOML_DISABLE_ARITHMETIC_WARNINGS TOML_NAMESPACE_START { template <typename ViewedType> class TOML_API TOML_TRIVIAL_ABI node_view { public: using viewed_type = ViewedType; private: friend class TOML_NAMESPACE::node; friend class TOML_NAMESPACE::table; template <typename T> friend class TOML_NAMESPACE::node_view; mutable viewed_type* node_ = nullptr; TOML_NODISCARD_CTOR node_view(viewed_type* node) noexcept : node_{ node } {} template <typename Func> static constexpr bool visit_is_nothrow = noexcept(std::declval<viewed_type*>()->visit(std::declval<Func&&>())); public: TOML_NODISCARD_CTOR node_view() noexcept = default; TOML_NODISCARD_CTOR node_view(const node_view&) noexcept = default; node_view& operator= (const node_view&) & noexcept = default; TOML_NODISCARD_CTOR node_view(node_view&&) noexcept = default; node_view& operator= (node_view&&) & noexcept = default; [[nodiscard]] explicit operator bool() const noexcept { return node_ != nullptr; } [[nodiscard]] viewed_type* node() const noexcept { return node_; } [[nodiscard, deprecated("use node_view::node() instead")]] viewed_type* get() const noexcept { return node_; } [[nodiscard]] node_type type() const noexcept { return node_ ? node_->type() : node_type::none; } [[nodiscard]] bool is_table() const noexcept { return node_ && node_->is_table(); } [[nodiscard]] bool is_array() const noexcept { return node_ && node_->is_array(); } [[nodiscard]] bool is_value() const noexcept { return node_ && node_->is_value(); } [[nodiscard]] bool is_string() const noexcept { return node_ && node_->is_string(); } [[nodiscard]] bool is_integer() const noexcept { return node_ && node_->is_integer(); } [[nodiscard]] bool is_floating_point() const noexcept { return node_ && node_->is_floating_point(); } [[nodiscard]] bool is_number() const noexcept { return node_ && node_->is_number(); } [[nodiscard]] bool is_boolean() const noexcept { return node_ && node_->is_boolean(); } [[nodiscard]] bool is_date() const noexcept { return node_ && node_->is_date(); } [[nodiscard]] bool is_time() const noexcept { return node_ && node_->is_time(); } [[nodiscard]] bool is_date_time() const noexcept { return node_ && node_->is_date_time(); } [[nodiscard]] bool is_array_of_tables() const noexcept { return node_ && node_->is_array_of_tables(); } template <typename T> [[nodiscard]] bool is() const noexcept { return node_ ? node_->template is<T>() : false; } template <typename T> [[nodiscard]] auto as() const noexcept { return node_ ? node_->template as<T>() : nullptr; } [[nodiscard]] auto as_table() const noexcept { return as<table>(); } [[nodiscard]] auto as_array() const noexcept { return as<array>(); } [[nodiscard]] auto as_string() const noexcept { return as<std::string>(); } [[nodiscard]] auto as_integer() const noexcept { return as<int64_t>(); } [[nodiscard]] auto as_floating_point() const noexcept { return as<double>(); } [[nodiscard]] auto as_boolean() const noexcept { return as<bool>(); } [[nodiscard]] auto as_date() const noexcept { return as<date>(); } [[nodiscard]] auto as_time() const noexcept { return as<time>(); } [[nodiscard]] auto as_date_time() const noexcept { return as<date_time>(); } [[nodiscard]] bool is_homogeneous(node_type ntype, viewed_type*& first_nonmatch) const noexcept { if (!node_) { first_nonmatch = {}; return false; } return node_->is_homogeneous(ntype, first_nonmatch); } [[nodiscard]] bool is_homogeneous(node_type ntype) const noexcept { return node_ ? node_->is_homogeneous(ntype) : false; } template <typename ElemType = void> [[nodiscard]] bool is_homogeneous() const noexcept { return node_ ? node_->template is_homogeneous<impl::unwrap_node<ElemType>>() : false; } template <typename T> [[nodiscard]] optional<T> value_exact() const noexcept { if (node_) return node_->template value_exact<T>(); return {}; } TOML_PUSH_WARNINGS TOML_DISABLE_INIT_WARNINGS template <typename T> [[nodiscard]] optional<T> value() const noexcept { if (node_) return node_->template value<T>(); return {}; } TOML_POP_WARNINGS template <typename T> [[nodiscard]] auto value_or(T&& default_value) const noexcept { using namespace ::toml::impl; static_assert( !is_wide_string<T> || TOML_WINDOWS_COMPAT, "Retrieving values as wide-character strings is only " "supported on Windows with TOML_WINDOWS_COMPAT enabled." ); if constexpr (is_wide_string<T>) { #if TOML_WINDOWS_COMPAT if (node_) return node_->value_or(std::forward<T>(default_value)); return std::wstring{ std::forward<T>(default_value) }; #else static_assert(impl::dependent_false<T>, "Evaluated unreachable branch!"); #endif } else { using value_type = std::conditional_t< std::is_pointer_v<std::decay_t<T>>, std::add_pointer_t<std::add_const_t<std::remove_pointer_t<std::decay_t<T>>>>, std::decay_t<T> >; if (node_) return node_->value_or(std::forward<T>(default_value)); if constexpr (std::is_pointer_v<value_type>) return value_type{ default_value }; else return std::forward<T>(default_value); } } template <typename Func> decltype(auto) visit(Func&& visitor) const noexcept(visit_is_nothrow<Func&&>) { using return_type = decltype(node_->visit(std::forward<Func>(visitor))); if (node_) return node_->visit(std::forward<Func>(visitor)); if constexpr (!std::is_void_v<return_type>) return return_type{}; } template <typename T> [[nodiscard]] decltype(auto) ref() const noexcept { TOML_ASSERT( node_ && "toml::node_view::ref() called on a node_view that did not reference a node" ); return node_->template ref<impl::unwrap_node<T>>(); } [[nodiscard]] friend bool operator == (const node_view& lhs, const table& rhs) noexcept { if (lhs.node_ == &rhs) return true; const auto tbl = lhs.as<table>(); return tbl && *tbl == rhs; } TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const table&, ) [[nodiscard]] friend bool operator == (const node_view& lhs, const array& rhs) noexcept { if (lhs.node_ == &rhs) return true; const auto arr = lhs.as<array>(); return arr && *arr == rhs; } TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const array&, ) template <typename T> [[nodiscard]] friend bool operator == (const node_view& lhs, const toml::value<T>& rhs) noexcept { if (lhs.node_ == &rhs) return true; const auto val = lhs.as<T>(); return val && *val == rhs; } TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const toml::value<T>&, template <typename T>) template <typename T, typename = std::enable_if_t< impl::is_native<T> || impl::is_losslessly_convertible_to_native<T> >> [[nodiscard]] friend bool operator == (const node_view& lhs, const T& rhs) noexcept { static_assert( !impl::is_wide_string<T> || TOML_WINDOWS_COMPAT, "Comparison with wide-character strings is only " "supported on Windows with TOML_WINDOWS_COMPAT enabled." ); if constexpr (impl::is_wide_string<T>) { #if TOML_WINDOWS_COMPAT return lhs == impl::narrow(rhs); #else static_assert(impl::dependent_false<T>, "Evaluated unreachable branch!"); #endif } else { const auto val = lhs.as<impl::native_type_of<T>>(); return val && *val == rhs; } } TOML_ASYMMETRICAL_EQUALITY_OPS( const node_view&, const T&, template <typename T, typename = std::enable_if_t< impl::is_native<T> || impl::is_losslessly_convertible_to_native<T> >> ) template <typename T> [[nodiscard]] friend bool operator == (const node_view& lhs, const std::initializer_list<T>& rhs) noexcept { const auto arr = lhs.as<array>(); return arr && *arr == rhs; } TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const std::initializer_list<T>&, template <typename T>) template <typename T> [[nodiscard]] friend bool operator == (const node_view& lhs, const std::vector<T>& rhs) noexcept { const auto arr = lhs.as<array>(); return arr && *arr == rhs; } TOML_ASYMMETRICAL_EQUALITY_OPS(const node_view&, const std::vector<T>&, template <typename T>) [[nodiscard]] node_view operator[] (std::string_view key) const noexcept { if (auto tbl = this->as_table()) return { tbl->get(key) }; return { nullptr }; } #if TOML_WINDOWS_COMPAT [[nodiscard]] node_view operator[] (std::wstring_view key) const noexcept { if (auto tbl = this->as_table()) return { tbl->get(key) }; return { nullptr }; } #endif // TOML_WINDOWS_COMPAT [[nodiscard]] node_view operator[] (size_t index) const noexcept { if (auto arr = this->as_array()) return { arr->get(index) }; return { nullptr }; } template <typename Char, typename T> friend std::basic_ostream<Char>& operator << (std::basic_ostream<Char>&, const node_view<T>&); }; template <typename Char, typename T> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& os, const node_view<T>& nv) { if (nv.node_) { nv.node_->visit([&os](const auto& n) { os << n; }); } return os; } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template class TOML_API node_view<node>; extern template class TOML_API node_view<const node>; extern template TOML_API std::ostream& operator << (std::ostream&, const node_view<node>&); extern template TOML_API std::ostream& operator << (std::ostream&, const node_view<const node>&); #define TOML_EXTERN(name, T) \ extern template TOML_API optional<T> node_view<node>::name<T>() const noexcept; \ extern template TOML_API optional<T> node_view<const node>::name<T>() const noexcept TOML_EXTERN(value_exact, std::string_view); TOML_EXTERN(value_exact, std::string); TOML_EXTERN(value_exact, const char*); TOML_EXTERN(value_exact, int64_t); TOML_EXTERN(value_exact, double); TOML_EXTERN(value_exact, date); TOML_EXTERN(value_exact, time); TOML_EXTERN(value_exact, date_time); TOML_EXTERN(value_exact, bool); TOML_EXTERN(value, std::string_view); TOML_EXTERN(value, std::string); TOML_EXTERN(value, const char*); TOML_EXTERN(value, signed char); TOML_EXTERN(value, signed short); TOML_EXTERN(value, signed int); TOML_EXTERN(value, signed long); TOML_EXTERN(value, signed long long); TOML_EXTERN(value, unsigned char); TOML_EXTERN(value, unsigned short); TOML_EXTERN(value, unsigned int); TOML_EXTERN(value, unsigned long); TOML_EXTERN(value, unsigned long long); TOML_EXTERN(value, double); TOML_EXTERN(value, float); TOML_EXTERN(value, date); TOML_EXTERN(value, time); TOML_EXTERN(value, date_time); TOML_EXTERN(value, bool); #ifdef __cpp_lib_char8_t TOML_EXTERN(value_exact, std::u8string_view); TOML_EXTERN(value_exact, std::u8string); TOML_EXTERN(value_exact, const char8_t*); TOML_EXTERN(value, std::u8string_view); TOML_EXTERN(value, std::u8string); TOML_EXTERN(value, const char8_t*); #endif #if TOML_WINDOWS_COMPAT TOML_EXTERN(value_exact, std::wstring); TOML_EXTERN(value, std::wstring); #endif #undef TOML_EXTERN #endif // !TOML_HEADER_ONLY } TOML_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_ARITHMETIC_WARNINGS #endif //------- ↑ toml_node_view.h ---------------------------------------------------------------------------------- #if 1 //----------------------------------- ↓ toml_utf8.h ----------------------------------------------------------- #ifndef DOXYGEN TOML_IMPL_NAMESPACE_START { template <typename... T> [[nodiscard]] TOML_ATTR(const) constexpr bool is_match(char32_t codepoint, T... vals) noexcept { static_assert((std::is_same_v<char32_t, T> && ...)); return ((codepoint == vals) || ...); } [[nodiscard]] TOML_ATTR(const) constexpr bool is_ascii_whitespace(char32_t codepoint) noexcept { return codepoint == U'\t' || codepoint == U' '; } [[nodiscard]] TOML_ATTR(const) constexpr bool is_unicode_whitespace(char32_t codepoint) noexcept { // see: https://en.wikipedia.org/wiki/Whitespace_character#Unicode // (characters that don't say "is a line-break") return codepoint == U'\u00A0' // no-break space || codepoint == U'\u1680' // ogham space mark || (codepoint >= U'\u2000' && codepoint <= U'\u200A') // em quad -> hair space || codepoint == U'\u202F' // narrow no-break space || codepoint == U'\u205F' // medium mathematical space || codepoint == U'\u3000' // ideographic space ; } [[nodiscard]] TOML_ATTR(const) constexpr bool is_whitespace(char32_t codepoint) noexcept { return is_ascii_whitespace(codepoint) || is_unicode_whitespace(codepoint); } template <bool IncludeCarriageReturn = true> [[nodiscard]] TOML_ATTR(const) constexpr bool is_ascii_line_break(char32_t codepoint) noexcept { constexpr auto low_range_end = IncludeCarriageReturn ? U'\r' : U'\f'; return (codepoint >= U'\n' && codepoint <= low_range_end); } [[nodiscard]] TOML_ATTR(const) constexpr bool is_unicode_line_break(char32_t codepoint) noexcept { // see https://en.wikipedia.org/wiki/Whitespace_character#Unicode // (characters that say "is a line-break") return codepoint == U'\u0085' // next line || codepoint == U'\u2028' // line separator || codepoint == U'\u2029' // paragraph separator ; } template <bool IncludeCarriageReturn = true> [[nodiscard]] TOML_ATTR(const) constexpr bool is_line_break(char32_t codepoint) noexcept { return is_ascii_line_break<IncludeCarriageReturn>(codepoint) || is_unicode_line_break(codepoint); } [[nodiscard]] TOML_ATTR(const) constexpr bool is_string_delimiter(char32_t codepoint) noexcept { return codepoint == U'"' || codepoint == U'\''; } [[nodiscard]] TOML_ATTR(const) constexpr bool is_ascii_letter(char32_t codepoint) noexcept { return (codepoint >= U'a' && codepoint <= U'z') || (codepoint >= U'A' && codepoint <= U'Z'); } [[nodiscard]] TOML_ATTR(const) constexpr bool is_binary_digit(char32_t codepoint) noexcept { return codepoint == U'0' || codepoint == U'1'; } [[nodiscard]] TOML_ATTR(const) constexpr bool is_octal_digit(char32_t codepoint) noexcept { return (codepoint >= U'0' && codepoint <= U'7'); } [[nodiscard]] TOML_ATTR(const) constexpr bool is_decimal_digit(char32_t codepoint) noexcept { return (codepoint >= U'0' && codepoint <= U'9'); } [[nodiscard]] TOML_ATTR(const) constexpr bool is_hexadecimal_digit(char32_t c) noexcept { return U'0' <= c && c <= U'f' && (1ull << (static_cast<uint_least64_t>(c) - 0x30u)) & 0x7E0000007E03FFull; } template <typename T> [[nodiscard]] TOML_ATTR(const) constexpr std::uint_least32_t hex_to_dec(const T codepoint) noexcept { if constexpr (std::is_same_v<remove_cvref_t<T>, std::uint_least32_t>) return codepoint >= 0x41u // >= 'A' ? 10u + (codepoint | 0x20u) - 0x61u // - 'a' : codepoint - 0x30u // - '0' ; else return hex_to_dec(static_cast<std::uint_least32_t>(codepoint)); } #if TOML_LANG_UNRELEASED // toml/issues/687 (unicode bare keys) [[nodiscard]] TOML_ATTR(const) constexpr bool is_unicode_letter(char32_t c) noexcept { if (U'\xAA' > c || c > U'\U0003134A') return false; const auto child_index_0 = (static_cast<uint_least64_t>(c) - 0xAAull) / 0xC4Bull; if ((1ull << child_index_0) & 0x26180C0000ull) return false; if ((1ull << child_index_0) & 0x8A7FFC004001CFA0ull) return true; switch (child_index_0) { case 0x00: // [0] 00AA - 0CF4 { if (c > U'\u0CF2') return false; TOML_ASSUME(U'\xAA' <= c); constexpr uint_least64_t bitmask_table_1[] = { 0xFFFFDFFFFFC10801u, 0xFFFFFFFFFFFFDFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x07C000FFF0FFFFFFu, 0x0000000000000014u, 0x0000000000000000u, 0xFEFFFFF5D02F37C0u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFEFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFF00FFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFC09FFFFFFFFFBFu, 0x000000007FFFFFFFu, 0xFFFFFFC000000000u, 0xFFC00000000001E1u, 0x00000001FFFFFFFFu, 0xFFFFFFFFFFFFFFB0u, 0x18000BFFFFFFFFFFu, 0xFFFFFF4000270030u, 0xFFFFFFF80000003Fu, 0x0FFFFFFFFFFFFFFFu, 0xFFFFFFFF00000080u, 0x44010FFFFFC10C01u, 0xFFC07FFFFFC00000u, 0xFFC0000000000001u, 0x000000003FFFF7FFu, 0xFFFFFFFFFC000000u, 0x00FFC0400008FFFFu, 0x7FFFFE67F87FFF80u, 0x00EC00100008F17Fu, 0x7FFFFE61F80400C0u, 0x001780000000DB7Fu, 0x7FFFFEEFF8000700u, 0x00C000400008FB7Fu, 0x7FFFFE67F8008000u, 0x00EC00000008FB7Fu, 0xC6358F71FA000080u, 0x000000400000FFF1u, 0x7FFFFF77F8000000u, 0x00C1C0000008FFFFu, 0x7FFFFF77F8400000u, 0x00D000000008FBFFu, 0x0000000000000180u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0xAAull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0xAAull) % 0x40ull)); // 1922 codepoints from 124 ranges (spanning a search area of 3147) } case 0x01: // [1] 0CF5 - 193F { if (U'\u0D04' > c || c > U'\u191E') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x027FFFFFFFFFDDFFu, 0x0FC0000038070400u, 0xF2FFBFFFFFC7FFFEu, 0xE000000000000007u, 0xF000DFFFFFFFFFFFu, 0x6000000000000007u, 0xF200DFFAFFFFFF7Du, 0x100000000F000005u, 0xF000000000000000u, 0x000001FFFFFFFFEFu, 0x00000000000001F0u, 0xF000000000000000u, 0x0800007FFFFFFFFFu, 0x3FFE1C0623C3F000u, 0xFFFFFFFFF0000400u, 0xFF7FFFFFFFFFF20Bu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFF3D7F3DFu, 0xD7F3DFFFFFFFF3DFu, 0xFFFFFFFFFFF7FFF3u, 0xFFFFFFFFFFF3DFFFu, 0xF0000000007FFFFFu, 0xFFFFFFFFF0000FFFu, 0xE3F3FFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xEFFFF9FFFFFFFFFFu, 0xFFFFFFFFF07FFFFFu, 0xF01FE07FFFFFFFFFu, 0xF0003FFFF0003DFFu, 0xF0001DFFF0003FFFu, 0x0000FFFFFFFFFFFFu, 0x0000000001080000u, 0xFFFFFFFFF0000000u, 0xF01FFFFFFFFFFFFFu, 0xFFFFF05FFFFFFFF9u, 0xF003FFFFFFFFFFFFu, 0x0000000007FFFFFFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0xD04ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0xD04ull) % 0x40ull)); // 2239 codepoints from 83 ranges (spanning a search area of 3147) } case 0x02: // [2] 1940 - 258A { if (U'\u1950' > c || c > U'\u2184') return false; constexpr uint_least64_t bitmask_table_1[] = { 0xFFFF001F3FFFFFFFu, 0x03FFFFFF0FFFFFFFu, 0xFFFF000000000000u, 0xFFFFFFFFFFFF007Fu, 0x000000000000001Fu, 0x0000000000800000u, 0xFFE0000000000000u, 0x0FE0000FFFFFFFFFu, 0xFFF8000000000000u, 0xFFFFFC00C001FFFFu, 0xFFFF0000003FFFFFu, 0xE0000000000FFFFFu, 0x01FF3FFFFFFFFC00u, 0x0000E7FFFFFFFFFFu, 0xFFFF046FDE000000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x0000FFFFFFFFFFFFu, 0xFFFF000000000000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x3F3FFFFFFFFF3F3Fu, 0xFFFF3FFFFFFFAAFFu, 0x1FDC5FDFFFFFFFFFu, 0x00001FDC1FFF0FCFu, 0x0000000000000000u, 0x0000800200000000u, 0x0000000000001FFFu, 0xFC84000000000000u, 0x43E0F3FFBD503E2Fu, 0x0018000000000000u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x1950ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x1950ull) % 0x40ull)); // 1184 codepoints from 59 ranges (spanning a search area of 3147) } case 0x03: // [3] 258B - 31D5 { if (U'\u2C00' > c || c > U'\u31BF') return false; constexpr uint_least64_t bitmask_table_1[] = { 0xFFFF7FFFFFFFFFFFu, 0xFFFFFFFF7FFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x000C781FFFFFFFFFu, 0xFFFF20BFFFFFFFFFu, 0x000080FFFFFFFFFFu, 0x7F7F7F7F007FFFFFu, 0x000000007F7F7F7Fu, 0x0000800000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x183E000000000060u, 0xFFFFFFFFFFFFFFFEu, 0xFFFFFFFEE07FFFFFu, 0xF7FFFFFFFFFFFFFFu, 0xFFFEFFFFFFFFFFE0u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFF00007FFFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x2C00ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 771 codepoints from 30 ranges (spanning a search area of 3147) } case 0x04: return (U'\u31F0' <= c && c <= U'\u31FF') || U'\u3400' <= c; case 0x06: return c <= U'\u4DBF' || U'\u4E00' <= c; case 0x0C: return c <= U'\u9FFC' || U'\uA000' <= c; case 0x0D: // [13] A079 - ACC3 { TOML_ASSUME(U'\uA079' <= c && c <= U'\uACC3'); constexpr uint_least64_t bitmask_table_1[] = { 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x00000000000FFFFFu, 0xFFFFFFFFFF800000u, 0xFFFFFFFFFFFFFF9Fu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x0006007FFF8FFFFFu, 0x003FFFFFFFFFFF80u, 0xFFFFFF9FFFFFFFC0u, 0x00001FFFFFFFFFFFu, 0xFFFFFE7FC0000000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFCFFFFu, 0xF00000000003FE7Fu, 0x000003FFFFFBDDFFu, 0x07FFFFFFFFFFFF80u, 0x07FFFFFFFFFFFE00u, 0x7E00000000000000u, 0xFF801FFFFFFE0034u, 0xFFFFFF8000003FFFu, 0x03FFFFFFFFFFF80Fu, 0x007FEF8000400000u, 0x0000FFFFFFFFFFBEu, 0x3FFFFF800007FB80u, 0x317FFFFFFFFFFFE2u, 0x0E03FF9C0000029Fu, 0xFFBFBF803F3F3F00u, 0xFF81FFFBFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x000003FFFFFFFFFFu, 0xFFFFFFFFFFFFFF80u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x00000000000007FFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0xA079ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0xA079ull) % 0x40ull)); // 2554 codepoints from 52 ranges (spanning a search area of 3147) } case 0x11: return c <= U'\uD7A3' || (U'\uD7B0' <= c && c <= U'\uD7C6') || (U'\uD7CB' <= c && c <= U'\uD7FB'); case 0x14: // [20] F686 - 102D0 { if (U'\uF900' > c) return false; TOML_ASSUME(c <= U'\U000102D0'); constexpr uint_least64_t bitmask_table_1[] = { 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFF3FFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x0000000003FFFFFFu, 0x5F7FFDFFA0F8007Fu, 0xFFFFFFFFFFFFFFDBu, 0x0003FFFFFFFFFFFFu, 0xFFFFFFFFFFF80000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x3FFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFF0000u, 0xFFFFFFFFFFFCFFFFu, 0x0FFF0000000000FFu, 0x0000000000000000u, 0xFFDF000000000000u, 0xFFFFFFFFFFFFFFFFu, 0x1FFFFFFFFFFFFFFFu, 0x07FFFFFE00000000u, 0xFFFFFFC007FFFFFEu, 0x7FFFFFFFFFFFFFFFu, 0x000000001CFCFCFCu, 0xB7FFFF7FFFFFEFFFu, 0x000000003FFF3FFFu, 0xFFFFFFFFFFFFFFFFu, 0x07FFFFFFFFFFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFFF1FFFFFFFu, 0x000000000001FFFFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0xF900ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 1710 codepoints from 34 ranges (spanning a search area of 3147) } case 0x15: // [21] 102D1 - 10F1B { if (U'\U00010300' > c) return false; TOML_ASSUME(c <= U'\U00010F1B'); constexpr uint_least64_t bitmask_table_1[] = { 0xFFFFE000FFFFFFFFu, 0x003FFFFFFFFF03FDu, 0xFFFFFFFF3FFFFFFFu, 0x000000000000FF0Fu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFF00003FFFFFFFu, 0x0FFFFFFFFF0FFFFFu, 0xFFFF00FFFFFFFFFFu, 0x0000000FFFFFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x007FFFFFFFFFFFFFu, 0x000000FF003FFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x91BFFFFFFFFFFD3Fu, 0x007FFFFF003FFFFFu, 0x000000007FFFFFFFu, 0x0037FFFF00000000u, 0x03FFFFFF003FFFFFu, 0x0000000000000000u, 0xC0FFFFFFFFFFFFFFu, 0x0000000000000000u, 0x003FFFFFFEEF0001u, 0x1FFFFFFF00000000u, 0x000000001FFFFFFFu, 0x0000001FFFFFFEFFu, 0x003FFFFFFFFFFFFFu, 0x0007FFFF003FFFFFu, 0x000000000003FFFFu, 0x0000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0x00000000000001FFu, 0x0007FFFFFFFFFFFFu, 0x0007FFFFFFFFFFFFu, 0x0000000FFFFFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x000303FFFFFFFFFFu, 0x0000000000000000u, 0x000000000FFFFFFFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x10300ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 1620 codepoints from 48 ranges (spanning a search area of 3147) } case 0x16: // [22] 10F1C - 11B66 { if (c > U'\U00011AF8') return false; TOML_ASSUME(U'\U00010F1C' <= c); constexpr uint_least64_t bitmask_table_1[] = { 0x000003FFFFF00801u, 0x0000000000000000u, 0x000001FFFFF00000u, 0xFFFFFF8007FFFFF0u, 0x000000000FFFFFFFu, 0xFFFFFF8000000000u, 0xFFF00000000FFFFFu, 0xFFFFFF8000001FFFu, 0xFFF00900000007FFu, 0xFFFFFF80047FFFFFu, 0x400001E0007FFFFFu, 0xFFBFFFF000000001u, 0x000000000000FFFFu, 0xFFFBD7F000000000u, 0xFFFFFFFFFFF01FFBu, 0xFF99FE0000000007u, 0x001000023EDFDFFFu, 0x000000000000003Eu, 0x0000000000000000u, 0xFFFFFFF000000000u, 0x0000780001FFFFFFu, 0xFFFFFFF000000038u, 0x00000B00000FFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFF000000000u, 0xF00000000007FFFFu, 0xFFFFFFF000000000u, 0x00000100000FFFFFu, 0xFFFFFFF000000000u, 0x0000000010007FFFu, 0x7FFFFFF000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFF000000000u, 0x000000000000FFFFu, 0x0000000000000000u, 0xFFFFFFFFFFFFFFF0u, 0xF6FF27F80000000Fu, 0x00000028000FFFFFu, 0x0000000000000000u, 0x001FFFFFFFFFCFF0u, 0xFFFF8010000000A0u, 0x00100000407FFFFFu, 0x00003FFFFFFFFFFFu, 0xFFFFFFF000000002u, 0x000000001FFFFFFFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x10F1Cull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x10F1Cull) % 0x40ull)); // 1130 codepoints from 67 ranges (spanning a search area of 3147) } case 0x17: // [23] 11B67 - 127B1 { if (U'\U00011C00' > c || c > U'\U00012543') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x00007FFFFFFFFDFFu, 0xFFFC000000000001u, 0x000000000000FFFFu, 0x0000000000000000u, 0x0001FFFFFFFFFB7Fu, 0xFFFFFDBF00000040u, 0x00000000010003FFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0007FFFF00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0001000000000000u, 0x0000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x0000000003FFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x000000000000000Fu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x11C00ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 1304 codepoints from 16 ranges (spanning a search area of 3147) } case 0x18: return U'\U00013000' <= c; case 0x19: return c <= U'\U0001342E'; case 0x1A: return U'\U00014400' <= c && c <= U'\U00014646'; case 0x1D: // [29] 16529 - 17173 { if (U'\U00016800' > c) return false; TOML_ASSUME(c <= U'\U00017173'); constexpr uint_least64_t bitmask_table_1[] = { 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x01FFFFFFFFFFFFFFu, 0x000000007FFFFFFFu, 0x0000000000000000u, 0x00003FFFFFFF0000u, 0x0000FFFFFFFFFFFFu, 0xE0FFFFF80000000Fu, 0x000000000000FFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0x00000000000107FFu, 0x00000000FFF80000u, 0x0000000B00000000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x000FFFFFFFFFFFFFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x16800ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 1250 codepoints from 14 ranges (spanning a search area of 3147) } case 0x1F: return c <= U'\U000187F7' || U'\U00018800' <= c; case 0x20: return c <= U'\U00018CD5' || (U'\U00018D00' <= c && c <= U'\U00018D08'); case 0x23: // [35] 1AEEB - 1BB35 { if (U'\U0001B000' > c || c > U'\U0001B2FB') return false; constexpr uint_least64_t bitmask_table_1[] = { 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x000000007FFFFFFFu, 0xFFFF00F000070000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x0FFFFFFFFFFFFFFFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x1B000ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 690 codepoints from 4 ranges (spanning a search area of 3147) } case 0x24: // [36] 1BB36 - 1C780 { if (U'\U0001BC00' > c || c > U'\U0001BC99') return false; switch ((static_cast<uint_least64_t>(c) - 0x1BC00ull) / 0x40ull) { case 0x01: return c <= U'\U0001BC7C' && (1ull << (static_cast<uint_least64_t>(c) - 0x1BC40u)) & 0x1FFF07FFFFFFFFFFull; case 0x02: return (1u << (static_cast<uint_least32_t>(c) - 0x1BC80u)) & 0x3FF01FFu; default: return true; } // 139 codepoints from 4 ranges (spanning a search area of 3147) } case 0x26: // [38] 1D3CC - 1E016 { if (U'\U0001D400' > c || c > U'\U0001D7CB') return false; constexpr uint_least64_t bitmask_table_1[] = { 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFDFFFFFu, 0xEBFFDE64DFFFFFFFu, 0xFFFFFFFFFFFFFFEFu, 0x7BFFFFFFDFDFE7BFu, 0xFFFFFFFFFFFDFC5Fu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFF3FFFFFFFFFu, 0xF7FFFFFFF7FFFFFDu, 0xFFDFFFFFFFDFFFFFu, 0xFFFF7FFFFFFF7FFFu, 0xFFFFFDFFFFFFFDFFu, 0x0000000000000FF7u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x1D400ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 936 codepoints from 30 ranges (spanning a search area of 3147) } case 0x27: // [39] 1E017 - 1EC61 { if (U'\U0001E100' > c || c > U'\U0001E94B') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x3F801FFFFFFFFFFFu, 0x0000000000004000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000FFFFFFFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu, 0x000000000000001Fu, 0xFFFFFFFFFFFFFFFFu, 0x000000000000080Fu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x1E100ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 363 codepoints from 7 ranges (spanning a search area of 3147) } case 0x28: // [40] 1EC62 - 1F8AC { if (U'\U0001EE00' > c || c > U'\U0001EEBB') return false; switch ((static_cast<uint_least64_t>(c) - 0x1EE00ull) / 0x40ull) { case 0x00: return c <= U'\U0001EE3B' && (1ull << (static_cast<uint_least64_t>(c) - 0x1EE00u)) & 0xAF7FE96FFFFFFEFull; case 0x01: return U'\U0001EE42' <= c && c <= U'\U0001EE7E' && (1ull << (static_cast<uint_least64_t>(c) - 0x1EE42u)) & 0x17BDFDE5AAA5BAA1ull; case 0x02: return (1ull << (static_cast<uint_least64_t>(c) - 0x1EE80u)) & 0xFFFFBEE0FFFFBFFull; TOML_NO_DEFAULT_CASE; } // 141 codepoints from 33 ranges (spanning a search area of 3147) } case 0x29: return U'\U00020000' <= c; case 0x37: return c <= U'\U0002A6DD' || U'\U0002A700' <= c; case 0x38: return c <= U'\U0002B734' || (U'\U0002B740' <= c && c <= U'\U0002B81D') || U'\U0002B820' <= c; case 0x3A: return c <= U'\U0002CEA1' || U'\U0002CEB0' <= c; case 0x3C: return c <= U'\U0002EBE0'; case 0x3D: return U'\U0002F800' <= c && c <= U'\U0002FA1D'; case 0x3E: return U'\U00030000' <= c; TOML_NO_DEFAULT_CASE; } // 131189 codepoints from 620 ranges (spanning a search area of 1114112) } [[nodiscard]] TOML_ATTR(const) constexpr bool is_unicode_number(char32_t c) noexcept { if (U'\u0660' > c || c > U'\U0001FBF9') return false; const auto child_index_0 = (static_cast<uint_least64_t>(c) - 0x660ull) / 0x7D7ull; if ((1ull << child_index_0) & 0x47FFDFE07FCFFFD0ull) return false; switch (child_index_0) { case 0x00: // [0] 0660 - 0E36 { if (c > U'\u0DEF') return false; TOML_ASSUME(U'\u0660' <= c); constexpr uint_least64_t bitmask_table_1[] = { 0x00000000000003FFu, 0x0000000000000000u, 0x0000000003FF0000u, 0x0000000000000000u, 0x0000000000000000u, 0x000003FF00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x000000000000FFC0u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x660ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x660ull) % 0x40ull)); // 130 codepoints from 13 ranges (spanning a search area of 2007) } case 0x01: // [1] 0E37 - 160D { if (U'\u0E50' > c || c > U'\u1099') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x00000000000003FFu, 0x0000000000000000u, 0x00000000000003FFu, 0x0000000003FF0000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x03FF000000000000u, 0x0000000000000000u, 0x00000000000003FFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0xE50ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0xE50ull) % 0x40ull)); // 50 codepoints from 5 ranges (spanning a search area of 2007) } case 0x02: // [2] 160E - 1DE4 { if (U'\u16EE' > c || c > U'\u1C59') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x0000000000000007u, 0x0000000000000000u, 0x0000000000000000u, 0x0FFC000000000000u, 0x00000FFC00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000003FF000000u, 0x0000000000000000u, 0x00000FFC00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000FFC0FFC0000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000FFC00000000u, 0x0000000000000000u, 0x0000000000000FFCu, 0x0000000000000000u, 0x00000FFC0FFC0000u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x16EEull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x16EEull) % 0x40ull)); // 103 codepoints from 11 ranges (spanning a search area of 2007) } case 0x03: return U'\u2160' <= c && c <= U'\u2188' && (1ull << (static_cast<uint_least64_t>(c) - 0x2160u)) & 0x1E7FFFFFFFFull; case 0x05: return U'\u3007' <= c && c <= U'\u303A' && (1ull << (static_cast<uint_least64_t>(c) - 0x3007u)) & 0xE0007FC000001ull; case 0x14: // [20] A32C - AB02 { if (U'\uA620' > c || c > U'\uAA59') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x00000000000003FFu, 0x0000000000000000u, 0x0000000000000000u, 0x000000000000FFC0u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x03FF000000000000u, 0x000003FF00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x03FF000000000000u, 0x0000000003FF0000u, 0x03FF000000000000u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0xA620ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0xA620ull) % 0x40ull)); // 70 codepoints from 7 ranges (spanning a search area of 2007) } case 0x15: return U'\uABF0' <= c && c <= U'\uABF9'; case 0x1F: return U'\uFF10' <= c && c <= U'\uFF19'; case 0x20: // [32] 10140 - 10916 { if (c > U'\U000104A9') return false; TOML_ASSUME(U'\U00010140' <= c); constexpr uint_least64_t bitmask_table_1[] = { 0x001FFFFFFFFFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000402u, 0x0000000000000000u, 0x00000000003E0000u, 0x0000000000000000u, 0x0000000000000000u, 0x000003FF00000000u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x10140ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 70 codepoints from 5 ranges (spanning a search area of 2007) } case 0x21: return (U'\U00010D30' <= c && c <= U'\U00010D39') || (U'\U00011066' <= c && c <= U'\U0001106F'); case 0x22: // [34] 110EE - 118C4 { if (U'\U000110F0' > c || c > U'\U00011739') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x00000000000003FFu, 0x000000000000FFC0u, 0x0000000000000000u, 0x000003FF00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000000000003FFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x000003FF00000000u, 0x0000000000000000u, 0x000003FF00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x000003FF00000000u, 0x0000000000000000u, 0x0000000003FF0000u, 0x0000000000000000u, 0x00000000000003FFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x110F0ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x110F0ull) % 0x40ull)); // 90 codepoints from 9 ranges (spanning a search area of 2007) } case 0x23: // [35] 118C5 - 1209B { if (U'\U000118E0' > c || c > U'\U00011DA9') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x00000000000003FFu, 0x03FF000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x03FF000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x03FF000000000000u, 0x0000000000000000u, 0x00000000000003FFu, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x118E0ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x118E0ull) % 0x40ull)); // 50 codepoints from 5 ranges (spanning a search area of 2007) } case 0x24: return U'\U00012400' <= c && c <= U'\U0001246E'; case 0x2D: return (U'\U00016A60' <= c && c <= U'\U00016A69') || (U'\U00016B50' <= c && c <= U'\U00016B59'); case 0x3B: return U'\U0001D7CE' <= c && c <= U'\U0001D7FF'; case 0x3C: return (U'\U0001E140' <= c && c <= U'\U0001E149') || (U'\U0001E2F0' <= c && c <= U'\U0001E2F9'); case 0x3D: return U'\U0001E950' <= c && c <= U'\U0001E959'; case 0x3F: return U'\U0001FBF0' <= c; TOML_NO_DEFAULT_CASE; } // 876 codepoints from 72 ranges (spanning a search area of 1114112) } [[nodiscard]] TOML_ATTR(const) constexpr bool is_unicode_combining_mark(char32_t c) noexcept { if (U'\u0300' > c || c > U'\U000E01EF') return false; const auto child_index_0 = (static_cast<uint_least64_t>(c) - 0x300ull) / 0x37FCull; if ((1ull << child_index_0) & 0x7FFFFFFFFFFFFE02ull) return false; switch (child_index_0) { case 0x00: // [0] 0300 - 3AFB { if (c > U'\u309A') return false; TOML_ASSUME(U'\u0300' <= c); constexpr uint_least64_t bitmask_table_1[] = { 0xFFFFFFFFFFFFFFFFu, 0x0000FFFFFFFFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000000000000F8u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xBFFFFFFFFFFE0000u, 0x00000000000000B6u, 0x0000000007FF0000u, 0x00010000FFFFF800u, 0x0000000000000000u, 0x00003D9F9FC00000u, 0xFFFF000000020000u, 0x00000000000007FFu, 0x0001FFC000000000u, 0x200FF80000000000u, 0x00003EEFFBC00000u, 0x000000000E000000u, 0x0000000000000000u, 0xFFFFFFFBFFF80000u, 0xDC0000000000000Fu, 0x0000000C00FEFFFFu, 0xD00000000000000Eu, 0x4000000C0080399Fu, 0xD00000000000000Eu, 0x0023000000023987u, 0xD00000000000000Eu, 0xFC00000C00003BBFu, 0xD00000000000000Eu, 0x0000000C00E0399Fu, 0xC000000000000004u, 0x0000000000803DC7u, 0xC00000000000001Fu, 0x0000000C00603DDFu, 0xD00000000000000Eu, 0x0000000C00603DDFu, 0xD80000000000000Fu, 0x0000000C00803DDFu, 0x000000000000000Eu, 0x000C0000FF5F8400u, 0x07F2000000000000u, 0x0000000000007F80u, 0x1FF2000000000000u, 0x0000000000003F00u, 0xC2A0000003000000u, 0xFFFE000000000000u, 0x1FFFFFFFFEFFE0DFu, 0x0000000000000040u, 0x7FFFF80000000000u, 0x001E3F9DC3C00000u, 0x000000003C00BFFCu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000000E0000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x001C0000001C0000u, 0x000C0000000C0000u, 0xFFF0000000000000u, 0x00000000200FFFFFu, 0x0000000000003800u, 0x0000000000000000u, 0x0000020000000060u, 0x0000000000000000u, 0x0FFF0FFF00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x000000000F800000u, 0x9FFFFFFF7FE00000u, 0xBFFF000000000000u, 0x0000000000000001u, 0xFFF000000000001Fu, 0x000FF8000000001Fu, 0x00003FFE00000007u, 0x000FFFC000000000u, 0x00FFFFF000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x039021FFFFF70000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xFBFFFFFFFFFFFFFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0001FFE21FFF0000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0003800000000000u, 0x0000000000000000u, 0x8000000000000000u, 0x0000000000000000u, 0xFFFFFFFF00000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000FC0000000000u, 0x0000000000000000u, 0x0000000006000000u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x300ull) / 0x40ull] & (0x1ull << (static_cast<uint_least64_t>(c) % 0x40ull)); // 1106 codepoints from 156 ranges (spanning a search area of 14332) } case 0x02: // [2] 72F8 - AAF3 { if (U'\uA66F' > c || c > U'\uAAEF') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x0001800000007FE1u, 0x0000000000000000u, 0x0000000000000006u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x21F0000010880000u, 0x0000000000000000u, 0x0000000000060000u, 0xFFFE0000007FFFE0u, 0x7F80000000010007u, 0x0000001FFF000000u, 0x00000000001E0000u, 0x004000000003FFF0u, 0xFC00000000000000u, 0x00000000601000FFu, 0x0000000000007000u, 0xF00000000005833Au, 0x0000000000000001u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0xA66Full) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0xA66Full) % 0x40ull)); // 137 codepoints from 28 ranges (spanning a search area of 14332) } case 0x03: return (U'\uAAF5' <= c && c <= U'\uAAF6') || (U'\uABE3' <= c && c <= U'\uABEA') || (U'\uABEC' <= c && c <= U'\uABED'); case 0x04: // [4] E2F0 - 11AEB { if (U'\uFB1E' > c || c > U'\U00011A99') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x0000000000000001u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0003FFFC00000000u, 0x000000000003FFFCu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000080000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000004u, 0x0000000000000000u, 0x000000001F000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0003C1B800000000u, 0x000000021C000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000180u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000000000003C0u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000006000u, 0x0000000000000000u, 0x0007FF0000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000001C00000000u, 0x000001FFFC000000u, 0x0000001E00000000u, 0x000000001FFC0000u, 0x0000001C00000000u, 0x00000180007FFE00u, 0x0000001C00200000u, 0x00037807FFE00000u, 0x0000000000000000u, 0x0000000103FFC000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000003C00001FFEu, 0x0200E67F60000000u, 0x00000000007C7F30u, 0x0000000000000000u, 0x0000000000000000u, 0x000001FFFF800000u, 0x0000000000000001u, 0x0000003FFFFC0000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xC0000007FCFE0000u, 0x0000000000000000u, 0x00000007FFFC0000u, 0x0000000000000000u, 0x0000000003FFE000u, 0x8000000000000000u, 0x0000000000003FFFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x000000001FFFC000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000035E6FC0000u, 0x0000000000000000u, 0xF3F8000000000000u, 0x00001FF800000047u, 0x3FF80201EFE00000u, 0x0FFFF00000000000u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0xFB1Eull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0xFB1Eull) % 0x40ull)); // 402 codepoints from 63 ranges (spanning a search area of 14332) } case 0x05: // [5] 11AEC - 152E7 { if (U'\U00011C2F' > c || c > U'\U00011EF6') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x000000000001FEFFu, 0xFDFFFFF800000000u, 0x00000000000000FFu, 0x0000000000000000u, 0x00000000017F68FCu, 0x000001F6F8000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x00000000000000F0u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x11C2Full) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x11C2Full) % 0x40ull)); // 85 codepoints from 13 ranges (spanning a search area of 14332) } case 0x06: // [6] 152E8 - 18AE3 { if (U'\U00016AF0' > c || c > U'\U00016FF1') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x000000000000001Fu, 0x000000000000007Fu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFFE80000000u, 0x0000000780FFFFFFu, 0x0010000000000000u, 0x0000000000000003u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x16AF0ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x16AF0ull) % 0x40ull)); // 75 codepoints from 7 ranges (spanning a search area of 14332) } case 0x07: return U'\U0001BC9D' <= c && c <= U'\U0001BC9E'; case 0x08: // [8] 1C2E0 - 1FADB { if (U'\U0001D165' > c || c > U'\U0001E94A') return false; constexpr uint_least64_t bitmask_table_1[] = { 0x0000007F3FC03F1Fu, 0x00000000000001E0u, 0x0000000000000000u, 0x00000000E0000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xFFFFFFFFF8000000u, 0xFFFFFFFFFFC3FFFFu, 0xF7C00000800100FFu, 0x00000000000007FFu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0xDFCFFFFBF8000000u, 0x000000000000003Eu, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x000000000003F800u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000780u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0000000000000000u, 0x0003F80000000000u, 0x0000000000000000u, 0x0000003F80000000u, }; return bitmask_table_1[(static_cast<uint_least64_t>(c) - 0x1D165ull) / 0x40ull] & (0x1ull << ((static_cast<uint_least64_t>(c) - 0x1D165ull) % 0x40ull)); // 223 codepoints from 21 ranges (spanning a search area of 14332) } case 0x3F: return U'\U000E0100' <= c; TOML_NO_DEFAULT_CASE; } // 2282 codepoints from 293 ranges (spanning a search area of 1114112) } #endif // TOML_LANG_UNRELEASED [[nodiscard]] TOML_ATTR(const) constexpr bool is_bare_key_character(char32_t codepoint) noexcept { return is_ascii_letter(codepoint) || is_decimal_digit(codepoint) || codepoint == U'-' || codepoint == U'_' #if TOML_LANG_UNRELEASED // toml/issues/644 ('+' in bare keys) & toml/issues/687 (unicode bare keys) || codepoint == U'+' || is_unicode_letter(codepoint) || is_unicode_number(codepoint) || is_unicode_combining_mark(codepoint) #endif ; } [[nodiscard]] TOML_ATTR(const) constexpr bool is_value_terminator(char32_t codepoint) noexcept { return is_ascii_line_break(codepoint) || is_ascii_whitespace(codepoint) || codepoint == U']' || codepoint == U'}' || codepoint == U',' || codepoint == U'#' || is_unicode_line_break(codepoint) || is_unicode_whitespace(codepoint) ; } [[nodiscard]] TOML_ATTR(const) constexpr bool is_control_character(char32_t codepoint) noexcept { return codepoint <= U'\u001F' || codepoint == U'\u007F'; } [[nodiscard]] TOML_ATTR(const) constexpr bool is_nontab_control_character(char32_t codepoint) noexcept { return codepoint <= U'\u0008' || (codepoint >= U'\u000A' && codepoint <= U'\u001F') || codepoint == U'\u007F'; } [[nodiscard]] TOML_ATTR(const) constexpr bool is_unicode_surrogate(char32_t codepoint) noexcept { return codepoint >= 0xD800u && codepoint <= 0xDFFF; } struct utf8_decoder final { // utf8_decoder based on this: https://bjoern.hoehrmann.de/utf-8/decoder/dfa/ // Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de> uint_least32_t state{}; char32_t codepoint{}; static constexpr uint8_t state_table[] { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,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,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,12,12,12,12,12 }; [[nodiscard]] constexpr bool error() const noexcept { return state == uint_least32_t{ 12u }; } [[nodiscard]] constexpr bool has_code_point() const noexcept { return state == uint_least32_t{}; } [[nodiscard]] constexpr bool needs_more_input() const noexcept { return state > uint_least32_t{} && state != uint_least32_t{ 12u }; } constexpr void operator () (uint8_t byte) noexcept { TOML_ASSERT(!error()); const auto type = state_table[byte]; codepoint = static_cast<char32_t>( has_code_point() ? (uint_least32_t{ 255u } >> type) & byte : (byte & uint_least32_t{ 63u }) | (static_cast<uint_least32_t>(codepoint) << 6) ); state = state_table[state + uint_least32_t{ 256u } + type]; } }; } TOML_IMPL_NAMESPACE_END #endif // !DOXYGEN #endif //----------------------------------- ↑ toml_utf8.h ----------------------------------------------------------- #if 1 //--------------------------------------------------------- ↓ toml_formatter.h -------------------------------- TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS TOML_NAMESPACE_START { enum class format_flags : uint8_t { none, quote_dates_and_times = 1, allow_literal_strings = 2, allow_multi_line_strings = 4, }; [[nodiscard]] TOML_ALWAYS_INLINE TOML_ATTR(const) TOML_ATTR(flatten) constexpr format_flags operator & (format_flags lhs, format_flags rhs) noexcept { return static_cast<format_flags>(impl::unwrap_enum(lhs) & impl::unwrap_enum(rhs)); } [[nodiscard]] TOML_ALWAYS_INLINE TOML_ATTR(const) TOML_ATTR(flatten) constexpr format_flags operator | (format_flags lhs, format_flags rhs) noexcept { return static_cast<format_flags>( impl::unwrap_enum(lhs) | impl::unwrap_enum(rhs) ); } } TOML_NAMESPACE_END TOML_IMPL_NAMESPACE_START { template <typename Char = char> class TOML_API formatter { private: const toml::node* source_; std::basic_ostream<Char>* stream_ = nullptr; format_flags flags_; int8_t indent_; bool naked_newline_; protected: [[nodiscard]] const toml::node& source() const noexcept { return *source_; } [[nodiscard]] std::basic_ostream<Char>& stream() const noexcept { return *stream_; } static constexpr size_t indent_columns = 4; static constexpr std::string_view indent_string = " "sv; [[nodiscard]] int8_t indent() const noexcept { return indent_; } void indent(int8_t level) noexcept { indent_ = level; } void increase_indent() noexcept { indent_++; } void decrease_indent() noexcept { indent_--; } [[nodiscard]] bool quote_dates_and_times() const noexcept { return (flags_ & format_flags::quote_dates_and_times) != format_flags::none; } [[nodiscard]] bool literal_strings_allowed() const noexcept { return (flags_ & format_flags::allow_literal_strings) != format_flags::none; } [[nodiscard]] bool multi_line_strings_allowed() const noexcept { return (flags_ & format_flags::allow_multi_line_strings) != format_flags::none; } [[nodiscard]] bool naked_newline() const noexcept { return naked_newline_; } void clear_naked_newline() noexcept { naked_newline_ = false; } void attach(std::basic_ostream<Char>& stream) noexcept { indent_ = {}; naked_newline_ = true; stream_ = &stream; } void detach() noexcept { stream_ = nullptr; } void print_newline(bool force = false) { if (!naked_newline_ || force) { print_to_stream('\n', *stream_); naked_newline_ = true; } } void print_indent() { for (int8_t i = 0; i < indent_; i++) { print_to_stream(indent_string, *stream_); naked_newline_ = false; } } void print_quoted_string(std::string_view str, bool allow_multi_line = true) { auto literals = literal_strings_allowed(); if (str.empty()) { print_to_stream(literals ? "''"sv : "\"\""sv, *stream_); clear_naked_newline(); return; } auto multi_line = allow_multi_line && multi_line_strings_allowed(); if (multi_line || literals) { utf8_decoder decoder; bool has_line_breaks = false; bool has_control_chars = false; bool has_single_quotes = false; for (size_t i = 0; i < str.length() && !(has_line_breaks && has_control_chars && has_single_quotes); i++) { decoder(static_cast<uint8_t>(str[i])); if (decoder.error()) { has_line_breaks = false; has_control_chars = true; //force "" has_single_quotes = true; break; } else if (decoder.has_code_point()) { if (is_line_break(decoder.codepoint)) has_line_breaks = true; else if (is_nontab_control_character(decoder.codepoint)) has_control_chars = true; else if (decoder.codepoint == U'\'') has_single_quotes = true; } } multi_line = multi_line && has_line_breaks; literals = literals && !has_control_chars && !(!multi_line && has_single_quotes); } if (literals) { const auto quot = multi_line ? "'''"sv : "'"sv; print_to_stream(quot, *stream_); print_to_stream(str, *stream_); print_to_stream(quot, *stream_); } else { const auto quot = multi_line ? R"(""")"sv : R"(")"sv; print_to_stream(quot, *stream_); print_to_stream_with_escapes(str, *stream_); print_to_stream(quot, *stream_); } clear_naked_newline(); } template <typename T> void print(const value<T>& val) { if constexpr (std::is_same_v<T, std::string>) { print_quoted_string(val.get()); } else { static constexpr auto is_dt = std::is_same_v<T, date> || std::is_same_v<T, time> || std::is_same_v<T, date_time>; if constexpr (is_dt) { if (quote_dates_and_times()) { const auto quot = literal_strings_allowed() ? '\'' : '"'; print_to_stream(quot, *stream_); print_to_stream(*val, *stream_); print_to_stream(quot, *stream_); } else print_to_stream(*val, *stream_); } else print_to_stream(*val, *stream_); naked_newline_ = false; } } void print_value(const node& val_node, node_type type) { TOML_ASSUME(type > node_type::array); switch (type) { case node_type::string: print(*reinterpret_cast<const value<std::string>*>(&val_node)); break; case node_type::integer: print(*reinterpret_cast<const value<int64_t>*>(&val_node)); break; case node_type::floating_point: print(*reinterpret_cast<const value<double>*>(&val_node)); break; case node_type::boolean: print(*reinterpret_cast<const value<bool>*>(&val_node)); break; case node_type::date: print(*reinterpret_cast<const value<date>*>(&val_node)); break; case node_type::time: print(*reinterpret_cast<const value<time>*>(&val_node)); break; case node_type::date_time: print(*reinterpret_cast<const value<date_time>*>(&val_node)); break; TOML_NO_DEFAULT_CASE; } } formatter(const toml::node& source, format_flags flags) noexcept : source_{ &source }, flags_{ flags } {} }; #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template class TOML_API formatter<char>; #endif } TOML_IMPL_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS #endif //--------------------------------------------------------- ↑ toml_formatter.h -------------------------------- #if 1 //------------------------------------------------------------------------------ ↓ toml_default_formatter.h --- TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS TOML_IMPL_NAMESPACE_START { [[nodiscard]] TOML_API std::string default_formatter_make_key_segment(const std::string&) noexcept; [[nodiscard]] TOML_API size_t default_formatter_inline_columns(const node&) noexcept; [[nodiscard]] TOML_API bool default_formatter_forces_multiline(const node&, size_t = 0) noexcept; } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { template <typename Char = char> class TOML_API default_formatter final : impl::formatter<Char> { private: using base = impl::formatter<Char>; std::vector<std::string> key_path; void print_key_segment(const std::string& str) { if (str.empty()) impl::print_to_stream("''"sv, base::stream()); else { bool requiresQuotes = false; { impl::utf8_decoder decoder; for (size_t i = 0; i < str.length() && !requiresQuotes; i++) { decoder(static_cast<uint8_t>(str[i])); if (decoder.error()) requiresQuotes = true; else if (decoder.has_code_point()) requiresQuotes = !impl::is_bare_key_character(decoder.codepoint); } } if (requiresQuotes) { impl::print_to_stream('"', base::stream()); impl::print_to_stream_with_escapes(str, base::stream()); impl::print_to_stream('"', base::stream()); } else impl::print_to_stream(str, base::stream()); } base::clear_naked_newline(); } void print_key_path() { for (const auto& segment : key_path) { if (std::addressof(segment) > key_path.data()) impl::print_to_stream('.', base::stream()); impl::print_to_stream(segment, base::stream()); } base::clear_naked_newline(); } void print_inline(const table& /*tbl*/); void print(const array& arr) { if (arr.empty()) impl::print_to_stream("[]"sv, base::stream()); else { const auto original_indent = base::indent(); const auto multiline = impl::default_formatter_forces_multiline( arr, base::indent_columns * static_cast<size_t>(original_indent < 0 ? 0 : original_indent) ); impl::print_to_stream("["sv, base::stream()); if (multiline) { if (original_indent < 0) base::indent(0); base::increase_indent(); } else impl::print_to_stream(' ', base::stream()); for (size_t i = 0; i < arr.size(); i++) { if (i > 0_sz) { impl::print_to_stream(',', base::stream()); if (!multiline) impl::print_to_stream(' ', base::stream()); } if (multiline) { base::print_newline(true); base::print_indent(); } auto& v = arr[i]; const auto type = v.type(); TOML_ASSUME(type != node_type::none); switch (type) { case node_type::table: print_inline(*reinterpret_cast<const table*>(&v)); break; case node_type::array: print(*reinterpret_cast<const array*>(&v)); break; default: base::print_value(v, type); } } if (multiline) { base::indent(original_indent); base::print_newline(true); base::print_indent(); } else impl::print_to_stream(' ', base::stream()); impl::print_to_stream("]"sv, base::stream()); } base::clear_naked_newline(); } void print(const table& tbl) { static constexpr auto is_non_inline_array_of_tables = [](auto&& nde) noexcept { auto arr = nde.as_array(); return arr && arr->is_array_of_tables() && !arr->template get_as<table>(0_sz)->is_inline(); }; // values, arrays, and inline tables/table arrays for (auto&& [k, v] : tbl) { const auto type = v.type(); if ((type == node_type::table && !reinterpret_cast<const table*>(&v)->is_inline()) || (type == node_type::array && is_non_inline_array_of_tables(v))) continue; base::print_newline(); base::print_indent(); print_key_segment(k); impl::print_to_stream(" = "sv, base::stream()); TOML_ASSUME(type != node_type::none); switch (type) { case node_type::table: print_inline(*reinterpret_cast<const table*>(&v)); break; case node_type::array: print(*reinterpret_cast<const array*>(&v)); break; default: base::print_value(v, type); } } // non-inline tables for (auto&& [k, v] : tbl) { const auto type = v.type(); if (type != node_type::table || reinterpret_cast<const table*>(&v)->is_inline()) continue; auto& child_tbl = *reinterpret_cast<const table*>(&v); // we can skip indenting and emitting the headers for tables that only contain other tables // (so we don't over-nest) size_t child_value_count{}; //includes inline tables and non-table arrays size_t child_table_count{}; size_t child_table_array_count{}; for (auto&& [child_k, child_v] : child_tbl) { (void)child_k; const auto child_type = child_v.type(); TOML_ASSUME(child_type != node_type::none); switch (child_type) { case node_type::table: if (reinterpret_cast<const table*>(&child_v)->is_inline()) child_value_count++; else child_table_count++; break; case node_type::array: if (is_non_inline_array_of_tables(child_v)) child_table_array_count++; else child_value_count++; break; default: child_value_count++; } } bool skip_self = false; if (child_value_count == 0_sz && (child_table_count > 0_sz || child_table_array_count > 0_sz)) skip_self = true; key_path.push_back(impl::default_formatter_make_key_segment(k)); if (!skip_self) { if (!base::naked_newline()) { base::print_newline(); base::print_newline(true); } base::increase_indent(); base::print_indent(); impl::print_to_stream("["sv, base::stream()); print_key_path(); impl::print_to_stream("]"sv, base::stream()); base::print_newline(); } print(child_tbl); key_path.pop_back(); if (!skip_self) base::decrease_indent(); } // table arrays for (auto&& [k, v] : tbl) { if (!is_non_inline_array_of_tables(v)) continue; auto& arr = *reinterpret_cast<const array*>(&v); base::increase_indent(); key_path.push_back(impl::default_formatter_make_key_segment(k)); for (size_t i = 0; i < arr.size(); i++) { base::print_newline(); base::print_newline(true); base::print_indent(); impl::print_to_stream("[["sv, base::stream()); print_key_path(); impl::print_to_stream("]]"sv, base::stream()); base::print_newline(true); print(*reinterpret_cast<const table*>(&arr[i])); } key_path.pop_back(); base::decrease_indent(); } } void print() { switch (auto source_type = base::source().type()) { case node_type::table: { auto& tbl = *reinterpret_cast<const table*>(&base::source()); if (tbl.is_inline()) print_inline(tbl); else { base::decrease_indent(); // so root kvps and tables have the same indent print(tbl); base::print_newline(); } break; } case node_type::array: print(*reinterpret_cast<const array*>(&base::source())); break; default: base::print_value(base::source(), source_type); } } public: static constexpr format_flags default_flags = format_flags::allow_literal_strings | format_flags::allow_multi_line_strings; TOML_NODISCARD_CTOR explicit default_formatter(const toml::node& source, format_flags flags = default_flags) noexcept : base{ source, flags } {} template <typename T, typename U> friend std::basic_ostream<T>& operator << (std::basic_ostream<T>&, default_formatter<U>&); template <typename T, typename U> friend std::basic_ostream<T>& operator << (std::basic_ostream<T>&, default_formatter<U>&&); }; #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template class TOML_API default_formatter<char>; #endif default_formatter(const table&) -> default_formatter<char>; default_formatter(const array&) -> default_formatter<char>; template <typename T> default_formatter(const value<T>&) -> default_formatter<char>; template <typename T, typename U> inline std::basic_ostream<T>& operator << (std::basic_ostream<T>& lhs, default_formatter<U>& rhs) { rhs.attach(lhs); rhs.key_path.clear(); rhs.print(); rhs.detach(); return lhs; } template <typename T, typename U> inline std::basic_ostream<T>& operator << (std::basic_ostream<T>& lhs, default_formatter<U>&& rhs) { return lhs << rhs; //as lvalue } #ifndef DOXYGEN #if !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, default_formatter<char>&); extern template TOML_API std::ostream& operator << (std::ostream&, default_formatter<char>&&); extern template TOML_API std::ostream& operator << (std::ostream&, const table&); extern template TOML_API std::ostream& operator << (std::ostream&, const array&); extern template TOML_API std::ostream& operator << (std::ostream&, const value<std::string>&); extern template TOML_API std::ostream& operator << (std::ostream&, const value<int64_t>&); extern template TOML_API std::ostream& operator << (std::ostream&, const value<double>&); extern template TOML_API std::ostream& operator << (std::ostream&, const value<bool>&); extern template TOML_API std::ostream& operator << (std::ostream&, const value<toml::date>&); extern template TOML_API std::ostream& operator << (std::ostream&, const value<toml::time>&); extern template TOML_API std::ostream& operator << (std::ostream&, const value<toml::date_time>&); #endif template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const table& rhs) { return lhs << default_formatter<Char>{ rhs }; } template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const array& rhs) { return lhs << default_formatter<Char>{ rhs }; } template <typename Char, typename T> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const value<T>& rhs) { return lhs << default_formatter<Char>{ rhs }; } #endif // !DOXYGEN } TOML_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS #endif //------------------------------------------------------------------------------ ↑ toml_default_formatter.h --- #if 1 //----- ↓ toml_json_formatter.h ------------------------------------------------------------------------------- TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS TOML_NAMESPACE_START { template <typename Char = char> class TOML_API json_formatter final : impl::formatter<Char> { private: using base = impl::formatter<Char>; void print(const toml::table& tbl); void print(const array& arr) { if (arr.empty()) impl::print_to_stream("[]"sv, base::stream()); else { impl::print_to_stream('[', base::stream()); base::increase_indent(); for (size_t i = 0; i < arr.size(); i++) { if (i > 0_sz) impl::print_to_stream(',', base::stream()); base::print_newline(true); base::print_indent(); auto& v = arr[i]; const auto type = v.type(); TOML_ASSUME(type != node_type::none); switch (type) { case node_type::table: print(*reinterpret_cast<const table*>(&v)); break; case node_type::array: print(*reinterpret_cast<const array*>(&v)); break; default: base::print_value(v, type); } } base::decrease_indent(); base::print_newline(true); base::print_indent(); impl::print_to_stream(']', base::stream()); } base::clear_naked_newline(); } void print() { switch (auto source_type = base::source().type()) { case node_type::table: print(*reinterpret_cast<const table*>(&base::source())); base::print_newline(); break; case node_type::array: print(*reinterpret_cast<const array*>(&base::source())); break; default: base::print_value(base::source(), source_type); } } public: static constexpr format_flags default_flags = format_flags::quote_dates_and_times; TOML_NODISCARD_CTOR explicit json_formatter(const toml::node& source, format_flags flags = default_flags) noexcept : base{ source, flags } {} template <typename T, typename U> friend std::basic_ostream<T>& operator << (std::basic_ostream<T>&, json_formatter<U>&); template <typename T, typename U> friend std::basic_ostream<T>& operator << (std::basic_ostream<T>&, json_formatter<U>&&); }; #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template class TOML_API json_formatter<char>; #endif json_formatter(const table&) -> json_formatter<char>; json_formatter(const array&) -> json_formatter<char>; template <typename T> json_formatter(const value<T>&) -> json_formatter<char>; template <typename T, typename U> inline std::basic_ostream<T>& operator << (std::basic_ostream<T>& lhs, json_formatter<U>& rhs) { rhs.attach(lhs); rhs.print(); rhs.detach(); return lhs; } template <typename T, typename U> inline std::basic_ostream<T>& operator << (std::basic_ostream<T>& lhs, json_formatter<U>&& rhs) { return lhs << rhs; //as lvalue } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, json_formatter<char>&); extern template TOML_API std::ostream& operator << (std::ostream&, json_formatter<char>&&); #endif } TOML_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS #endif //----- ↑ toml_json_formatter.h ------------------------------------------------------------------------------- #if TOML_PARSER #if 1 //------------------------------- ↓ toml_parse_error.h -------------------------------------------------------- TOML_DISABLE_WARNINGS #if TOML_EXCEPTIONS #include <stdexcept> #endif TOML_ENABLE_WARNINGS TOML_PUSH_WARNINGS TOML_DISABLE_INIT_WARNINGS TOML_NAMESPACE_START { TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) #if defined(DOXYGEN) || !TOML_EXCEPTIONS class parse_error final { private: std::string description_; source_region source_; public: TOML_NODISCARD_CTOR parse_error(std::string&& desc, source_region&& src) noexcept : description_{ std::move(desc) }, source_{ std::move(src) } {} TOML_NODISCARD_CTOR parse_error(std::string&& desc, const source_region& src) noexcept : parse_error{ std::move(desc), source_region{ src } } {} TOML_NODISCARD_CTOR parse_error(std::string&& desc, const source_position& position, const source_path_ptr& path = {}) noexcept : parse_error{ std::move(desc), source_region{ position, position, path } } {} [[nodiscard]] std::string_view description() const noexcept { return description_; } [[nodiscard]] const source_region& source() const noexcept { return source_; } }; #else class parse_error final : public std::runtime_error { private: source_region source_; public: TOML_NODISCARD_CTOR TOML_ATTR(nonnull) parse_error(const char* desc, source_region&& src) noexcept : std::runtime_error{ desc }, source_{ std::move(src) } {} TOML_NODISCARD_CTOR TOML_ATTR(nonnull) parse_error(const char* desc, const source_region& src) noexcept : parse_error{ desc, source_region{ src } } {} TOML_NODISCARD_CTOR TOML_ATTR(nonnull) parse_error(const char* desc, const source_position& position, const source_path_ptr& path = {}) noexcept : parse_error{ desc, source_region{ position, position, path } } {} [[nodiscard]] std::string_view description() const noexcept { return std::string_view{ what() }; } [[nodiscard]] const source_region& source() const noexcept { return source_; } }; #endif TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS template <typename Char> inline std::basic_ostream<Char>& operator << (std::basic_ostream<Char>& lhs, const parse_error& rhs) { lhs << rhs.description(); lhs << "\n\t(error occurred at "sv; lhs << rhs.source(); lhs << ")"sv; return lhs; } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API std::ostream& operator << (std::ostream&, const parse_error&); #endif } TOML_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_INIT_WARNINGS #endif //------------------------------- ↑ toml_parse_error.h -------------------------------------------------------- #if 1 //-------------------------------------------------------- ↓ toml_utf8_streams.h ------------------------------ TOML_IMPL_NAMESPACE_START { template <typename T> class utf8_byte_stream; inline constexpr auto utf8_byte_order_mark = "\xEF\xBB\xBF"sv; template <typename Char> class TOML_API utf8_byte_stream<std::basic_string_view<Char>> final { static_assert(sizeof(Char) == 1_sz); private: std::basic_string_view<Char> source; size_t position = {}; public: explicit constexpr utf8_byte_stream(std::basic_string_view<Char> sv) noexcept : source{ sv } { // trim trailing nulls size_t actual_len = source.length(); for (size_t i = actual_len; i --> 0_sz;) { if (source[i] != Char{}) // not '\0' { actual_len = i + 1_sz; break; } } if (source.length() != actual_len) // not '\0' source = source.substr(0_sz, actual_len); // skip bom if (source.length() >= 3_sz && memcmp(utf8_byte_order_mark.data(), source.data(), 3_sz) == 0) position += 3_sz; } [[nodiscard]] TOML_ALWAYS_INLINE constexpr bool eof() const noexcept { return position >= source.length(); } [[nodiscard]] TOML_ALWAYS_INLINE constexpr bool peek_eof() const noexcept { return eof(); } [[nodiscard]] TOML_ALWAYS_INLINE constexpr bool error() const noexcept { return false; } [[nodiscard]] constexpr unsigned int operator() () noexcept { if (position >= source.length()) return 0xFFFFFFFFu; return static_cast<unsigned int>(static_cast<uint8_t>(source[position++])); } }; template <typename Char> class TOML_API utf8_byte_stream<std::basic_istream<Char>> final { static_assert(sizeof(Char) == 1_sz); private: std::basic_istream<Char>* source; public: explicit utf8_byte_stream(std::basic_istream<Char>& stream) : source{ &stream } { if (!source->good()) // eof, fail, bad return; const auto initial_pos = source->tellg(); Char bom[3]; source->read(bom, 3); if (source->bad() || (source->gcount() == 3 && memcmp(utf8_byte_order_mark.data(), bom, 3_sz) == 0)) return; source->clear(); source->seekg(initial_pos, std::basic_istream<Char>::beg); } [[nodiscard]] TOML_ALWAYS_INLINE bool eof() const noexcept { return source->eof(); } [[nodiscard]] TOML_ALWAYS_INLINE bool peek_eof() const { using stream_traits = typename std::remove_pointer_t<decltype(source)>::traits_type; return eof() || source->peek() == stream_traits::eof(); } [[nodiscard]] TOML_ALWAYS_INLINE bool error() const noexcept { return !(*source); } [[nodiscard]] unsigned int operator() () { auto val = source->get(); if (val == std::basic_istream<Char>::traits_type::eof()) return 0xFFFFFFFFu; return static_cast<unsigned int>(val); } }; TOML_ABI_NAMESPACE_BOOL(TOML_LARGE_FILES, lf, sf) struct utf8_codepoint final { char32_t value; char bytes[4]; source_position position; [[nodiscard]] std::string_view as_view() const noexcept { return bytes[3] ? std::string_view{ bytes, 4_sz } : std::string_view{ bytes }; } [[nodiscard]] TOML_ATTR(pure) constexpr operator char32_t& () noexcept { return value; } [[nodiscard]] TOML_ATTR(pure) constexpr operator const char32_t& () const noexcept { return value; } [[nodiscard]] TOML_ATTR(pure) constexpr const char32_t& operator* () const noexcept { return value; } }; static_assert(std::is_trivial_v<utf8_codepoint>); static_assert(std::is_standard_layout_v<utf8_codepoint>); TOML_ABI_NAMESPACE_END // TOML_LARGE_FILES TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) #if TOML_EXCEPTIONS #define TOML_ERROR_CHECK (void)0 #define TOML_ERROR throw parse_error #else #define TOML_ERROR_CHECK if (err) return nullptr #define TOML_ERROR err.emplace #endif struct TOML_INTERFACE utf8_reader_interface { [[nodiscard]] virtual const source_path_ptr& source_path() const noexcept = 0; [[nodiscard]] virtual const utf8_codepoint* read_next() = 0; [[nodiscard]] virtual bool peek_eof() const = 0; #if !TOML_EXCEPTIONS [[nodiscard]] virtual optional<parse_error>&& error() noexcept = 0; #endif virtual ~utf8_reader_interface() noexcept = default; }; template <typename T> class TOML_EMPTY_BASES TOML_API utf8_reader final : public utf8_reader_interface { private: utf8_byte_stream<T> stream; utf8_decoder decoder; utf8_codepoint codepoints[2]; size_t cp_idx = 1; uint8_t current_byte_count{}; source_path_ptr source_path_; #if !TOML_EXCEPTIONS optional<parse_error> err; #endif public: template <typename U, typename String = std::string_view> explicit utf8_reader(U && source, String&& source_path = {}) noexcept(std::is_nothrow_constructible_v<utf8_byte_stream<T>, U&&>) : stream{ std::forward<U>(source) } { std::memset(codepoints, 0, sizeof(codepoints)); codepoints[0].position = { 1, 1 }; codepoints[1].position = { 1, 1 }; if (!source_path.empty()) source_path_ = std::make_shared<const std::string>(std::forward<String>(source_path)); } [[nodiscard]] const source_path_ptr& source_path() const noexcept override { return source_path_; } [[nodiscard]] const utf8_codepoint* read_next() override { TOML_ERROR_CHECK; auto& prev = codepoints[(cp_idx - 1_sz) % 2_sz]; if (stream.eof()) return nullptr; else if (stream.error()) TOML_ERROR("An error occurred while reading from the underlying stream", prev.position, source_path_ ); else if (decoder.error()) TOML_ERROR( "Encountered invalid utf-8 sequence", prev.position, source_path_ ); TOML_ERROR_CHECK; while (true) { uint8_t next_byte; { unsigned int next_byte_raw{ 0xFFFFFFFFu }; if constexpr (noexcept(stream()) || !TOML_EXCEPTIONS) { next_byte_raw = stream(); } #if TOML_EXCEPTIONS else { try { next_byte_raw = stream(); } catch (const std::exception& exc) { throw parse_error{ exc.what(), prev.position, source_path_ }; } catch (...) { throw parse_error{ "An unspecified error occurred", prev.position, source_path_ }; } } #endif if (next_byte_raw >= 256u) { if (stream.eof()) { if (decoder.needs_more_input()) TOML_ERROR("Encountered EOF during incomplete utf-8 code point sequence", prev.position, source_path_); return nullptr; } else TOML_ERROR("An error occurred while reading from the underlying stream", prev.position, source_path_); } TOML_ERROR_CHECK; next_byte = static_cast<uint8_t>(next_byte_raw); } decoder(next_byte); if (decoder.error()) TOML_ERROR( "Encountered invalid utf-8 sequence", prev.position, source_path_ ); TOML_ERROR_CHECK; auto& current = codepoints[cp_idx % 2_sz]; current.bytes[current_byte_count++] = static_cast<char>(next_byte); if (decoder.has_code_point()) { //store codepoint current.value = decoder.codepoint; //reset prev (will be the next 'current') std::memset(prev.bytes, 0, sizeof(prev.bytes)); current_byte_count = {}; if (is_line_break<false>(current.value)) prev.position = { static_cast<source_index>(current.position.line + 1), 1 }; else prev.position = { current.position.line, static_cast<source_index>(current.position.column + 1) }; cp_idx++; return &current; } } TOML_UNREACHABLE; } [[nodiscard]] bool peek_eof() const override { return stream.peek_eof(); } #if !TOML_EXCEPTIONS [[nodiscard]] optional<parse_error>&& error() noexcept override { return std::move(err); } #endif }; template <typename Char> utf8_reader(std::basic_string_view<Char>, std::string_view) -> utf8_reader<std::basic_string_view<Char>>; template <typename Char> utf8_reader(std::basic_string_view<Char>, std::string&&) -> utf8_reader<std::basic_string_view<Char>>; template <typename Char> utf8_reader(std::basic_istream<Char>&, std::string_view) -> utf8_reader<std::basic_istream<Char>>; template <typename Char> utf8_reader(std::basic_istream<Char>&, std::string&&) -> utf8_reader<std::basic_istream<Char>>; class TOML_EMPTY_BASES TOML_API utf8_buffered_reader final : public utf8_reader_interface { public: static constexpr size_t max_history_length = 72; private: static constexpr size_t history_buffer_size = max_history_length - 1; //'head' is stored in the reader utf8_reader_interface& reader; struct { utf8_codepoint buffer[history_buffer_size]; size_t count, first; } history = {}; const utf8_codepoint* head = {}; size_t negative_offset = {}; public: explicit utf8_buffered_reader(utf8_reader_interface& reader_) noexcept; const source_path_ptr& source_path() const noexcept override; const utf8_codepoint* read_next() override; const utf8_codepoint* step_back(size_t count) noexcept; bool peek_eof() const override; #if !TOML_EXCEPTIONS optional<parse_error>&& error() noexcept override; #endif }; TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS } TOML_IMPL_NAMESPACE_END #endif //-------------------------------------------------------- ↑ toml_utf8_streams.h ------------------------------ #if 1 //------------------------------------------------------------------------------------ ↓ toml_parser.h -------- TOML_NAMESPACE_START { TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) #if defined(DOXYGEN) || !TOML_EXCEPTIONS class parse_result final { private: std::aligned_storage_t< (sizeof(toml::table) < sizeof(parse_error) ? sizeof(parse_error) : sizeof(toml::table)), (alignof(toml::table) < alignof(parse_error) ? alignof(parse_error) : alignof(toml::table)) > storage; bool is_err; void destroy() noexcept { if (is_err) TOML_LAUNDER(reinterpret_cast<parse_error*>(&storage))->~parse_error(); else TOML_LAUNDER(reinterpret_cast<toml::table*>(&storage))->~table(); } public: using iterator = table_iterator; using const_iterator = const_table_iterator; [[nodiscard]] bool succeeded() const noexcept { return !is_err; } [[nodiscard]] bool failed() const noexcept { return is_err; } [[nodiscard]] explicit operator bool() const noexcept { return !is_err; } [[nodiscard]] toml::table& table() & noexcept { TOML_ASSERT(!is_err); return *TOML_LAUNDER(reinterpret_cast<toml::table*>(&storage)); } [[nodiscard]] toml::table&& table() && noexcept { TOML_ASSERT(!is_err); return std::move(*TOML_LAUNDER(reinterpret_cast<toml::table*>(&storage))); } [[nodiscard]] const toml::table& table() const& noexcept { TOML_ASSERT(!is_err); return *TOML_LAUNDER(reinterpret_cast<const toml::table*>(&storage)); } [[nodiscard, deprecated("use parse_result::table() instead")]] toml::table& get() & noexcept { return table(); } [[nodiscard, deprecated("use parse_result::table() instead")]] toml::table&& get() && noexcept { return std::move(table()); } [[nodiscard, deprecated("use parse_result::table() instead")]] const toml::table& get() const& noexcept { return table(); } [[nodiscard]] parse_error& error() & noexcept { TOML_ASSERT(is_err); return *TOML_LAUNDER(reinterpret_cast<parse_error*>(&storage)); } [[nodiscard]] parse_error&& error() && noexcept { TOML_ASSERT(is_err); return std::move(*TOML_LAUNDER(reinterpret_cast<parse_error*>(&storage))); } [[nodiscard]] const parse_error& error() const& noexcept { TOML_ASSERT(is_err); return *TOML_LAUNDER(reinterpret_cast<const parse_error*>(&storage)); } [[nodiscard]] operator toml::table& () noexcept { return table(); } [[nodiscard]] operator toml::table&& () noexcept { return std::move(table()); } [[nodiscard]] operator const toml::table& () const noexcept { return table(); } [[nodiscard]] explicit operator parse_error& () noexcept { return error(); } [[nodiscard]] explicit operator parse_error && () noexcept { return std::move(error()); } [[nodiscard]] explicit operator const parse_error& () const noexcept { return error(); } TOML_NODISCARD_CTOR explicit parse_result(toml::table&& tbl) noexcept : is_err{ false } { ::new (&storage) toml::table{ std::move(tbl) }; } TOML_NODISCARD_CTOR explicit parse_result(parse_error&& err) noexcept : is_err{ true } { ::new (&storage) parse_error{ std::move(err) }; } TOML_NODISCARD_CTOR parse_result(parse_result&& res) noexcept : is_err{ res.is_err } { if (is_err) ::new (&storage) parse_error{ std::move(res).error() }; else ::new (&storage) toml::table{ std::move(res).table() }; } parse_result& operator=(parse_result&& rhs) noexcept { if (is_err != rhs.is_err) { destroy(); is_err = rhs.is_err; if (is_err) ::new (&storage) parse_error{ std::move(rhs).error() }; else ::new (&storage) toml::table{ std::move(rhs).table() }; } else { if (is_err) error() = std::move(rhs).error(); else table() = std::move(rhs).table(); } return *this; } ~parse_result() noexcept { destroy(); } [[nodiscard]] node_view<node> operator[] (string_view key) noexcept { return is_err ? node_view<node>{} : table()[key]; } [[nodiscard]] node_view<const node> operator[] (string_view key) const noexcept { return is_err ? node_view<const node>{} : table()[key]; } #if TOML_WINDOWS_COMPAT [[nodiscard]] node_view<node> operator[] (std::wstring_view key) noexcept { return is_err ? node_view<node>{} : table()[key]; } [[nodiscard]] node_view<const node> operator[] (std::wstring_view key) const noexcept { return is_err ? node_view<const node>{} : table()[key]; } #endif // TOML_WINDOWS_COMPAT [[nodiscard]] table_iterator begin() noexcept { return is_err ? table_iterator{} : table().begin(); } [[nodiscard]] const_table_iterator begin() const noexcept { return is_err ? const_table_iterator{} : table().begin(); } [[nodiscard]] const_table_iterator cbegin() const noexcept { return is_err ? const_table_iterator{} : table().cbegin(); } [[nodiscard]] table_iterator end() noexcept { return is_err ? table_iterator{} : table().end(); } [[nodiscard]] const_table_iterator end() const noexcept { return is_err ? const_table_iterator{} : table().end(); } [[nodiscard]] const_table_iterator cend() const noexcept { return is_err ? const_table_iterator{} : table().cend(); } }; #else using parse_result = table; #endif TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS } TOML_NAMESPACE_END TOML_IMPL_NAMESPACE_START { TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) [[nodiscard]] TOML_API parse_result do_parse(utf8_reader_interface&&) TOML_MAY_THROW; TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS } TOML_IMPL_NAMESPACE_END #if TOML_EXCEPTIONS #define TOML_THROW_PARSE_ERROR(msg, path) \ throw parse_error{ \ msg, source_position{}, std::make_shared<const std::string>(std::move(path)) \ } #else #define TOML_THROW_PARSE_ERROR(msg, path) \ return parse_result{ parse_error{ \ msg, source_position{}, std::make_shared<const std::string>(std::move(path)) \ }} #endif TOML_NAMESPACE_START { TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) [[nodiscard]] TOML_API parse_result parse(std::string_view doc, std::string_view source_path = {}) TOML_MAY_THROW; [[nodiscard]] TOML_API parse_result parse(std::string_view doc, std::string&& source_path) TOML_MAY_THROW; #if TOML_WINDOWS_COMPAT [[nodiscard]] TOML_API parse_result parse(std::string_view doc, std::wstring_view source_path) TOML_MAY_THROW; #endif // TOML_WINDOWS_COMPAT #ifdef __cpp_lib_char8_t [[nodiscard]] TOML_API parse_result parse(std::u8string_view doc, std::string_view source_path = {}) TOML_MAY_THROW; [[nodiscard]] TOML_API parse_result parse(std::u8string_view doc, std::string&& source_path) TOML_MAY_THROW; #if TOML_WINDOWS_COMPAT [[nodiscard]] TOML_API parse_result parse(std::u8string_view doc, std::wstring_view source_path) TOML_MAY_THROW; #endif // TOML_WINDOWS_COMPAT #endif // __cpp_lib_char8_t template <typename Char> [[nodiscard]] inline parse_result parse(std::basic_istream<Char>& doc, std::string_view source_path = {}) TOML_MAY_THROW { static_assert( sizeof(Char) == 1, "The stream's underlying character type must be 1 byte in size." ); return impl::do_parse(impl::utf8_reader{ doc, source_path }); } template <typename Char> [[nodiscard]] inline parse_result parse(std::basic_istream<Char>& doc, std::string&& source_path) TOML_MAY_THROW { static_assert( sizeof(Char) == 1, "The stream's underlying character type must be 1 byte in size." ); return impl::do_parse(impl::utf8_reader{ doc, std::move(source_path) }); } #if TOML_WINDOWS_COMPAT template <typename Char> [[nodiscard]] inline parse_result parse(std::basic_istream<Char>& doc, std::wstring_view source_path) TOML_MAY_THROW { return parse(doc, impl::narrow(source_path)); } #endif // TOML_WINDOWS_COMPAT // Q: "why are the parse_file functions templated??" // A: I don't want to force users to drag in <fstream> if they're not going to do // any parsing directly from files. Keeping them templated delays their instantiation // until they're actually required, so only those users wanting to use parse_file() // are burdened by the <fstream> overhead. template <typename Char, typename StreamChar = char> [[nodiscard]] inline parse_result parse_file(std::basic_string_view<Char> file_path) TOML_MAY_THROW { static_assert( !std::is_same_v<Char, wchar_t> || TOML_WINDOWS_COMPAT, "Wide-character file paths are only supported on Windows with TOML_WINDOWS_COMPAT enabled." ); #if TOML_WINDOWS_COMPAT static_assert( sizeof(Char) == 1 || std::is_same_v<Char, wchar_t>, "The file path's underlying character type must be wchar_t or be 1 byte in size." ); #else static_assert( sizeof(Char) == 1, "The file path's underlying character type must be 1 byte in size." ); #endif static_assert( std::is_same_v<StreamChar, char>, "StreamChar must be 'char' (it is as an instantiation-delaying hack and is not user-configurable)." ); std::string file_path_str; #if TOML_WINDOWS_COMPAT if constexpr (std::is_same_v<Char, wchar_t>) file_path_str = impl::narrow(file_path); else #endif file_path_str = std::string_view{ reinterpret_cast<const char*>(file_path.data()), file_path.length() }; // open file with a custom-sized stack buffer using ifstream = std::basic_ifstream<StreamChar>; ifstream file; StreamChar file_buffer[sizeof(void*) * 4096_sz]; file.rdbuf()->pubsetbuf(file_buffer, sizeof(file_buffer)); file.open(file_path_str, ifstream::in | ifstream::binary | ifstream::ate); if (!file.is_open()) TOML_THROW_PARSE_ERROR("File could not be opened for reading", file_path_str); // get size const auto file_size = file.tellg(); if (file_size == -1) TOML_THROW_PARSE_ERROR("Could not determine file size", file_path_str); file.seekg(0, ifstream::beg); // read the whole file into memory first if the file isn't too large constexpr auto large_file_threshold = 1024 * 1024 * static_cast<int>(sizeof(void*)) * 4; // 32 megabytes on 64-bit if (file_size <= large_file_threshold) { std::vector<StreamChar> file_data; file_data.resize(static_cast<size_t>(file_size)); file.read(file_data.data(), static_cast<std::streamsize>(file_size)); return parse(std::basic_string_view<StreamChar>{ file_data.data(), file_data.size() }, std::move(file_path_str)); } // otherwise parse it using the streams else return parse(file, std::move(file_path_str)); } #if !defined(DOXYGEN) && !TOML_HEADER_ONLY extern template TOML_API parse_result parse(std::istream&, std::string_view) TOML_MAY_THROW; extern template TOML_API parse_result parse(std::istream&, std::string&&) TOML_MAY_THROW; extern template TOML_API parse_result parse_file(std::string_view) TOML_MAY_THROW; #ifdef __cpp_lib_char8_t extern template TOML_API parse_result parse_file(std::u8string_view) TOML_MAY_THROW; #endif #if TOML_WINDOWS_COMPAT extern template TOML_API parse_result parse_file(std::wstring_view) TOML_MAY_THROW; #endif #endif template <typename Char> [[nodiscard]] inline parse_result parse_file(const std::basic_string<Char>& file_path) TOML_MAY_THROW { return parse_file(std::basic_string_view<Char>{ file_path }); } template <typename Char> [[nodiscard]] inline parse_result parse_file(const Char* file_path) TOML_MAY_THROW { return parse_file(std::basic_string_view<Char>{ file_path }); } inline namespace literals { [[nodiscard]] TOML_API parse_result operator"" _toml(const char* str, size_t len) TOML_MAY_THROW; #ifdef __cpp_lib_char8_t [[nodiscard]] TOML_API parse_result operator"" _toml(const char8_t* str, size_t len) TOML_MAY_THROW; #endif // __cpp_lib_char8_t } TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS } TOML_NAMESPACE_END #undef TOML_THROW_PARSE_ERROR #endif //------------------------------------------------------------------------------------ ↑ toml_parser.h -------- #endif // TOML_PARSER #if TOML_IMPLEMENTATION #if 1 //--------- ↓ toml_node.hpp ----------------------------------------------------------------------------------- TOML_NAMESPACE_START { TOML_EXTERNAL_LINKAGE node::node(const node& /*other*/) noexcept { // does not copy source information // this is not an error } TOML_EXTERNAL_LINKAGE node::node(node && other) noexcept : source_{ std::move(other.source_) } { other.source_.begin = {}; other.source_.end = {}; } TOML_EXTERNAL_LINKAGE node& node::operator= (const node& /*rhs*/) noexcept { // does not copy source information // this is not an error source_ = {}; return *this; } TOML_EXTERNAL_LINKAGE node& node::operator= (node && rhs) noexcept { source_ = std::move(rhs.source_); rhs.source_.begin = {}; rhs.source_.end = {}; return *this; } #define TOML_MEMBER_ATTR(attr) TOML_EXTERNAL_LINKAGE TOML_ATTR(attr) TOML_MEMBER_ATTR(const) bool node::is_string() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool node::is_integer() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool node::is_floating_point() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool node::is_number() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool node::is_boolean() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool node::is_date() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool node::is_time() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool node::is_date_time() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool node::is_array_of_tables() const noexcept { return false; } TOML_MEMBER_ATTR(const) table* node::as_table() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) array* node::as_array() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) value<std::string>* node::as_string() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) value<int64_t>* node::as_integer() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) value<double>* node::as_floating_point() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) value<bool>* node::as_boolean() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) value<date>* node::as_date() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) value<time>* node::as_time() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) value<date_time>* node::as_date_time() noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const table* node::as_table() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const array* node::as_array() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const value<std::string>* node::as_string() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const value<int64_t>* node::as_integer() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const value<double>* node::as_floating_point() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const value<bool>* node::as_boolean() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const value<date>* node::as_date() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const value<time>* node::as_time() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const value<date_time>* node::as_date_time() const noexcept { return nullptr; } TOML_MEMBER_ATTR(const) const source_region& node::source() const noexcept { return source_; } #undef TOML_MEMBER_ATTR TOML_EXTERNAL_LINKAGE node::operator node_view<node>() noexcept { return node_view<node>(this); } TOML_EXTERNAL_LINKAGE node::operator node_view<const node>() const noexcept { return node_view<const node>(this); } } TOML_NAMESPACE_END #endif //--------- ↑ toml_node.hpp ----------------------------------------------------------------------------------- #if 1 //--------------------------------- ↓ toml_array.hpp ---------------------------------------------------------- TOML_NAMESPACE_START { TOML_EXTERNAL_LINKAGE array::array() noexcept = default; TOML_EXTERNAL_LINKAGE array::array(const array& other) noexcept : node{ other } { elements.reserve(other.elements.size()); for (const auto& elem : other) elements.emplace_back(impl::make_node(elem)); } TOML_EXTERNAL_LINKAGE array::array(array&& other) noexcept : node{ std::move(other) }, elements{ std::move(other.elements) } {} TOML_EXTERNAL_LINKAGE array& array::operator= (const array& rhs) noexcept { if (&rhs != this) { node::operator=(rhs); elements.clear(); elements.reserve(rhs.elements.size()); for (const auto& elem : rhs) elements.emplace_back(impl::make_node(elem)); } return *this; } TOML_EXTERNAL_LINKAGE array& array::operator= (array&& rhs) noexcept { if (&rhs != this) { node::operator=(std::move(rhs)); elements = std::move(rhs.elements); } return *this; } TOML_EXTERNAL_LINKAGE void array::preinsertion_resize(size_t idx, size_t count) noexcept { TOML_ASSERT(idx <= elements.size()); TOML_ASSERT(count >= 1_sz); const auto old_size = elements.size(); const auto new_size = old_size + count; const auto inserting_at_end = idx == old_size; elements.resize(new_size); if (!inserting_at_end) { for(size_t left = old_size, right = new_size - 1_sz; left --> idx; right--) elements[right] = std::move(elements[left]); } } #define TOML_MEMBER_ATTR(attr) TOML_EXTERNAL_LINKAGE TOML_ATTR(attr) TOML_MEMBER_ATTR(const) node_type array::type() const noexcept { return node_type::array; } TOML_MEMBER_ATTR(const) bool array::is_table() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool array::is_array() const noexcept { return true; } TOML_MEMBER_ATTR(const) bool array::is_value() const noexcept { return false; } TOML_MEMBER_ATTR(const) const array* array::as_array() const noexcept { return this; } TOML_MEMBER_ATTR(const) array* array::as_array() noexcept { return this; } TOML_MEMBER_ATTR(pure) const node& array::operator[] (size_t index) const noexcept { return *elements[index]; } TOML_MEMBER_ATTR(pure) node& array::operator[] (size_t index) noexcept { return *elements[index]; } TOML_MEMBER_ATTR(pure) const node& array::front() const noexcept { return *elements.front(); } TOML_MEMBER_ATTR(pure) const node& array::back() const noexcept { return *elements.back(); } TOML_MEMBER_ATTR(pure) node& array::front() noexcept { return *elements.front(); } TOML_MEMBER_ATTR(pure) node& array::back() noexcept { return *elements.back(); } TOML_MEMBER_ATTR(pure) array::const_iterator array::begin() const noexcept { return { elements.begin() }; } TOML_MEMBER_ATTR(pure) array::const_iterator array::end() const noexcept { return { elements.end() }; } TOML_MEMBER_ATTR(pure) array::const_iterator array::cbegin() const noexcept { return { elements.cbegin() }; } TOML_MEMBER_ATTR(pure) array::const_iterator array::cend() const noexcept { return { elements.cend() }; } TOML_MEMBER_ATTR(pure) array::iterator array::begin() noexcept { return { elements.begin() }; } TOML_MEMBER_ATTR(pure) array::iterator array::end() noexcept { return { elements.end() }; } TOML_MEMBER_ATTR(pure) size_t array::size() const noexcept { return elements.size(); } TOML_MEMBER_ATTR(pure) size_t array::capacity() const noexcept { return elements.capacity(); } TOML_MEMBER_ATTR(pure) bool array::empty() const noexcept { return elements.empty(); } TOML_MEMBER_ATTR(const) size_t array::max_size() const noexcept { return elements.max_size(); } TOML_EXTERNAL_LINKAGE void array::reserve(size_t new_capacity) { elements.reserve(new_capacity); } TOML_EXTERNAL_LINKAGE void array::clear() noexcept { elements.clear(); } TOML_EXTERNAL_LINKAGE void array::shrink_to_fit() { elements.shrink_to_fit(); } #undef TOML_MEMBER_ATTR TOML_EXTERNAL_LINKAGE bool array::is_homogeneous(node_type ntype) const noexcept { if (elements.empty()) return false; if (ntype == node_type::none) ntype = elements[0]->type(); for (const auto& val : elements) if (val->type() != ntype) return false; return true; } namespace impl { template <typename T, typename U> TOML_INTERNAL_LINKAGE bool array_is_homogeneous(T& elements, node_type ntype, U& first_nonmatch) noexcept { if (elements.empty()) { first_nonmatch = {}; return false; } if (ntype == node_type::none) ntype = elements[0]->type(); for (const auto& val : elements) { if (val->type() != ntype) { first_nonmatch = val.get(); return false; } } return true; } } TOML_EXTERNAL_LINKAGE bool array::is_homogeneous(node_type ntype, toml::node*& first_nonmatch) noexcept { return impl::array_is_homogeneous(elements, ntype, first_nonmatch); } TOML_EXTERNAL_LINKAGE bool array::is_homogeneous(node_type ntype, const toml::node*& first_nonmatch) const noexcept { return impl::array_is_homogeneous(elements, ntype, first_nonmatch); } TOML_EXTERNAL_LINKAGE void array::truncate(size_t new_size) { if (new_size < elements.size()) elements.resize(new_size); } TOML_EXTERNAL_LINKAGE array::iterator array::erase(const_iterator pos) noexcept { return { elements.erase(pos.raw_) }; } TOML_EXTERNAL_LINKAGE array::iterator array::erase(const_iterator first, const_iterator last) noexcept { return { elements.erase(first.raw_, last.raw_) }; } TOML_EXTERNAL_LINKAGE void array::pop_back() noexcept { elements.pop_back(); } TOML_EXTERNAL_LINKAGE TOML_ATTR(pure) node* array::get(size_t index) noexcept { return index < elements.size() ? elements[index].get() : nullptr; } TOML_EXTERNAL_LINKAGE TOML_ATTR(pure) const node* array::get(size_t index) const noexcept { return index < elements.size() ? elements[index].get() : nullptr; } TOML_API TOML_EXTERNAL_LINKAGE bool operator == (const array& lhs, const array& rhs) noexcept { if (&lhs == &rhs) return true; if (lhs.elements.size() != rhs.elements.size()) return false; for (size_t i = 0, e = lhs.elements.size(); i < e; i++) { const auto lhs_type = lhs.elements[i]->type(); const node& rhs_ = *rhs.elements[i]; const auto rhs_type = rhs_.type(); if (lhs_type != rhs_type) return false; const bool equal = lhs.elements[i]->visit([&](const auto& lhs_) noexcept { return lhs_ == *reinterpret_cast<std::remove_reference_t<decltype(lhs_)>*>(&rhs_); }); if (!equal) return false; } return true; } TOML_API TOML_EXTERNAL_LINKAGE bool operator != (const array& lhs, const array& rhs) noexcept { return !(lhs == rhs); } TOML_EXTERNAL_LINKAGE size_t array::total_leaf_count() const noexcept { size_t leaves{}; for (size_t i = 0, e = elements.size(); i < e; i++) { auto arr = elements[i]->as_array(); leaves += arr ? arr->total_leaf_count() : 1_sz; } return leaves; } TOML_EXTERNAL_LINKAGE void array::flatten_child(array&& child, size_t& dest_index) noexcept { for (size_t i = 0, e = child.size(); i < e; i++) { auto type = child.elements[i]->type(); if (type == node_type::array) { array& arr = *reinterpret_cast<array*>(child.elements[i].get()); if (!arr.empty()) flatten_child(std::move(arr), dest_index); } else elements[dest_index++] = std::move(child.elements[i]); } } TOML_EXTERNAL_LINKAGE array& array::flatten() & { if (elements.empty()) return *this; bool requires_flattening = false; size_t size_after_flattening = elements.size(); for (size_t i = elements.size(); i --> 0_sz;) { auto arr = elements[i]->as_array(); if (!arr) continue; size_after_flattening--; //discount the array itself const auto leaf_count = arr->total_leaf_count(); if (leaf_count > 0_sz) { requires_flattening = true; size_after_flattening += leaf_count; } else elements.erase(elements.cbegin() + static_cast<ptrdiff_t>(i)); } if (!requires_flattening) return *this; elements.reserve(size_after_flattening); size_t i = 0; while (i < elements.size()) { auto arr = elements[i]->as_array(); if (!arr) { i++; continue; } std::unique_ptr<node> arr_storage = std::move(elements[i]); const auto leaf_count = arr->total_leaf_count(); if (leaf_count > 1_sz) preinsertion_resize(i + 1_sz, leaf_count - 1_sz); flatten_child(std::move(*arr), i); //increments i } return *this; } TOML_EXTERNAL_LINKAGE bool array::is_array_of_tables() const noexcept { return is_homogeneous(node_type::table); } } TOML_NAMESPACE_END #endif //--------------------------------- ↑ toml_array.hpp ---------------------------------------------------------- #if 1 //---------------------------------------------------------- ↓ toml_table.hpp --------------------------------- TOML_NAMESPACE_START { TOML_EXTERNAL_LINKAGE table::table() noexcept {} TOML_EXTERNAL_LINKAGE table::table(const table& other) noexcept : node{ std::move(other) }, inline_{ other.inline_ } { for (auto&& [k, v] : other) map.emplace_hint(map.end(), k, impl::make_node(v)); } TOML_EXTERNAL_LINKAGE table::table(table&& other) noexcept : node{ std::move(other) }, map{ std::move(other.map) }, inline_{ other.inline_ } {} TOML_EXTERNAL_LINKAGE table& table::operator= (const table& rhs) noexcept { if (&rhs != this) { node::operator=(rhs); map.clear(); for (auto&& [k, v] : rhs) map.emplace_hint(map.end(), k, impl::make_node(v)); inline_ = rhs.inline_; } return *this; } TOML_EXTERNAL_LINKAGE table& table::operator= (table&& rhs) noexcept { if (&rhs != this) { node::operator=(std::move(rhs)); map = std::move(rhs.map); inline_ = rhs.inline_; } return *this; } TOML_EXTERNAL_LINKAGE table::table(impl::table_init_pair* pairs, size_t count) noexcept { for (size_t i = 0; i < count; i++) { if (!pairs[i].value) // empty node_views continue; map.insert_or_assign( std::move(pairs[i].key), std::move(pairs[i].value) ); } } #define TOML_MEMBER_ATTR(attr) TOML_EXTERNAL_LINKAGE TOML_ATTR(attr) TOML_MEMBER_ATTR(const) node_type table::type() const noexcept { return node_type::table; } TOML_MEMBER_ATTR(const) bool table::is_table() const noexcept { return true; } TOML_MEMBER_ATTR(const) bool table::is_array() const noexcept { return false; } TOML_MEMBER_ATTR(const) bool table::is_value() const noexcept { return false; } TOML_MEMBER_ATTR(const) const table* table::as_table() const noexcept { return this; } TOML_MEMBER_ATTR(const) table* table::as_table() noexcept { return this; } TOML_MEMBER_ATTR(pure) bool table::is_inline() const noexcept { return inline_; } TOML_EXTERNAL_LINKAGE void table::is_inline(bool val) noexcept { inline_ = val; } TOML_EXTERNAL_LINKAGE table::const_iterator table::begin() const noexcept { return { map.begin() }; } TOML_EXTERNAL_LINKAGE table::const_iterator table::end() const noexcept { return { map.end() }; } TOML_EXTERNAL_LINKAGE table::const_iterator table::cbegin() const noexcept { return { map.cbegin() }; } TOML_EXTERNAL_LINKAGE table::const_iterator table::cend() const noexcept { return { map.cend() }; } TOML_EXTERNAL_LINKAGE table::iterator table::begin() noexcept { return { map.begin() }; } TOML_EXTERNAL_LINKAGE table::iterator table::end() noexcept { return { map.end() }; } TOML_MEMBER_ATTR(pure) bool table::empty() const noexcept { return map.empty(); } TOML_MEMBER_ATTR(pure) size_t table::size() const noexcept { return map.size(); } TOML_EXTERNAL_LINKAGE void table::clear() noexcept { map.clear(); } #undef TOML_MEMBER_ATTR TOML_EXTERNAL_LINKAGE bool table::is_homogeneous(node_type ntype) const noexcept { if (map.empty()) return false; if (ntype == node_type::none) ntype = map.cbegin()->second->type(); for (const auto& [k, v] : map) { (void)k; if (v->type() != ntype) return false; } return true; } namespace impl { template <typename T, typename U> TOML_INTERNAL_LINKAGE bool table_is_homogeneous(T& map, node_type ntype, U& first_nonmatch) noexcept { if (map.empty()) { first_nonmatch = {}; return false; } if (ntype == node_type::none) ntype = map.cbegin()->second->type(); for (const auto& [k, v] : map) { (void)k; if (v->type() != ntype) { first_nonmatch = v.get(); return false; } } return true; } } TOML_EXTERNAL_LINKAGE bool table::is_homogeneous(node_type ntype, toml::node*& first_nonmatch) noexcept { return impl::table_is_homogeneous(map, ntype, first_nonmatch); } TOML_EXTERNAL_LINKAGE bool table::is_homogeneous(node_type ntype, const toml::node*& first_nonmatch) const noexcept { return impl::table_is_homogeneous(map, ntype, first_nonmatch); } TOML_EXTERNAL_LINKAGE node_view<node> table::operator[] (std::string_view key) noexcept { return { this->get(key) }; } TOML_EXTERNAL_LINKAGE node_view<const node> table::operator[] (std::string_view key) const noexcept { return { this->get(key) }; } TOML_EXTERNAL_LINKAGE table::iterator table::erase(iterator pos) noexcept { return { map.erase(pos.raw_) }; } TOML_EXTERNAL_LINKAGE table::iterator table::erase(const_iterator pos) noexcept { return { map.erase(pos.raw_) }; } TOML_EXTERNAL_LINKAGE table::iterator table::erase(const_iterator first, const_iterator last) noexcept { return { map.erase(first.raw_, last.raw_) }; } TOML_EXTERNAL_LINKAGE bool table::erase(std::string_view key) noexcept { if (auto it = map.find(key); it != map.end()) { map.erase(it); return true; } return false; } TOML_EXTERNAL_LINKAGE node* table::get(std::string_view key) noexcept { return do_get(map, key); } TOML_EXTERNAL_LINKAGE const node* table::get(std::string_view key) const noexcept { return do_get(map, key); } TOML_EXTERNAL_LINKAGE table::iterator table::find(std::string_view key) noexcept { return { map.find(key) }; } TOML_EXTERNAL_LINKAGE table::const_iterator table::find(std::string_view key) const noexcept { return { map.find(key) }; } TOML_EXTERNAL_LINKAGE bool table::contains(std::string_view key) const noexcept { return do_contains(map, key); } #if TOML_WINDOWS_COMPAT TOML_EXTERNAL_LINKAGE node_view<node> table::operator[] (std::wstring_view key) noexcept { return { this->get(key) }; } TOML_EXTERNAL_LINKAGE node_view<const node> table::operator[] (std::wstring_view key) const noexcept { return { this->get(key) }; } TOML_EXTERNAL_LINKAGE bool table::erase(std::wstring_view key) noexcept { return erase(impl::narrow(key)); } TOML_EXTERNAL_LINKAGE node* table::get(std::wstring_view key) noexcept { return get(impl::narrow(key)); } TOML_EXTERNAL_LINKAGE const node* table::get(std::wstring_view key) const noexcept { return get(impl::narrow(key)); } TOML_EXTERNAL_LINKAGE table::iterator table::find(std::wstring_view key) noexcept { return find(impl::narrow(key)); } TOML_EXTERNAL_LINKAGE table::const_iterator table::find(std::wstring_view key) const noexcept { return find(impl::narrow(key)); } TOML_EXTERNAL_LINKAGE bool table::contains(std::wstring_view key) const noexcept { return contains(impl::narrow(key)); } #endif // TOML_WINDOWS_COMPAT TOML_API TOML_EXTERNAL_LINKAGE bool operator == (const table& lhs, const table& rhs) noexcept { if (&lhs == &rhs) return true; if (lhs.map.size() != rhs.map.size()) return false; for (auto l = lhs.map.begin(), r = rhs.map.begin(), e = lhs.map.end(); l != e; l++, r++) { if (l->first != r->first) return false; const auto lhs_type = l->second->type(); const node& rhs_ = *r->second; const auto rhs_type = rhs_.type(); if (lhs_type != rhs_type) return false; const bool equal = l->second->visit([&](const auto& lhs_) noexcept { return lhs_ == *reinterpret_cast<std::remove_reference_t<decltype(lhs_)>*>(&rhs_); }); if (!equal) return false; } return true; } TOML_API TOML_EXTERNAL_LINKAGE bool operator != (const table& lhs, const table& rhs) noexcept { return !(lhs == rhs); } } TOML_NAMESPACE_END #endif //---------------------------------------------------------- ↑ toml_table.hpp --------------------------------- #if 1 //----------------------------------------------------------------------------- ↓ toml_default_formatter.hpp -- TOML_DISABLE_WARNINGS #include <cmath> TOML_ENABLE_WARNINGS TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS TOML_DISABLE_ARITHMETIC_WARNINGS TOML_IMPL_NAMESPACE_START { inline constexpr size_t default_formatter_line_wrap = 120_sz; TOML_API TOML_EXTERNAL_LINKAGE std::string default_formatter_make_key_segment(const std::string& str) noexcept { if (str.empty()) return "''"s; else { bool requiresQuotes = false; { utf8_decoder decoder; for (size_t i = 0; i < str.length() && !requiresQuotes; i++) { decoder(static_cast<uint8_t>(str[i])); if (decoder.error()) requiresQuotes = true; else if (decoder.has_code_point()) requiresQuotes = !is_bare_key_character(decoder.codepoint); } } if (requiresQuotes) { std::string s; s.reserve(str.length() + 2_sz); s += '"'; for (auto c : str) { if TOML_UNLIKELY(c >= '\x00' && c <= '\x1F') { const auto& sv = low_character_escape_table[c]; s.append(reinterpret_cast<const char*>(sv.data()), sv.length()); } else if TOML_UNLIKELY(c == '\x7F') s.append("\\u007F"sv); else if TOML_UNLIKELY(c == '"') s.append("\\\""sv); else s += c; } s += '"'; return s; } else return str; } } TOML_API TOML_EXTERNAL_LINKAGE size_t default_formatter_inline_columns(const node& node) noexcept { switch (node.type()) { case node_type::table: { auto& n = *reinterpret_cast<const table*>(&node); if (n.empty()) return 2_sz; // "{}" size_t weight = 3_sz; // "{ }" for (auto&& [k, v] : n) { weight += k.length() + default_formatter_inline_columns(v) + 2_sz; // + ", " if (weight >= default_formatter_line_wrap) break; } return weight; } case node_type::array: { auto& n = *reinterpret_cast<const array*>(&node); if (n.empty()) return 2_sz; // "[]" size_t weight = 3_sz; // "[ ]" for (auto& elem : n) { weight += default_formatter_inline_columns(elem) + 2_sz; // + ", " if (weight >= default_formatter_line_wrap) break; } return weight; } case node_type::string: { auto& n = *reinterpret_cast<const value<std::string>*>(&node); return n.get().length() + 2_sz; // + "" } case node_type::integer: { auto& n = *reinterpret_cast<const value<int64_t>*>(&node); auto v = n.get(); if (!v) return 1_sz; size_t weight = {}; if (v < 0) { weight += 1; v *= -1; } return weight + static_cast<size_t>(log10(static_cast<double>(v))) + 1_sz; } case node_type::floating_point: { auto& n = *reinterpret_cast<const value<double>*>(&node); auto v = n.get(); if (v == 0.0) return 3_sz; // "0.0" size_t weight = 2_sz; // ".0" if (v < 0.0) { weight += 1; v *= -1.0; } return weight + static_cast<size_t>(log10(static_cast<double>(v))) + 1_sz; break; } case node_type::boolean: return 5_sz; case node_type::date: [[fallthrough]]; case node_type::time: return 10_sz; case node_type::date_time: return 30_sz; case node_type::none: TOML_UNREACHABLE; TOML_NO_DEFAULT_CASE; } TOML_UNREACHABLE; } TOML_API TOML_EXTERNAL_LINKAGE bool default_formatter_forces_multiline(const node& node, size_t starting_column_bias) noexcept { return (default_formatter_inline_columns(node) + starting_column_bias) > default_formatter_line_wrap; } } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { template <typename Char> inline void default_formatter<Char>::print_inline(const toml::table& tbl) { if (tbl.empty()) impl::print_to_stream("{}"sv, base::stream()); else { impl::print_to_stream("{ "sv, base::stream()); bool first = false; for (auto&& [k, v] : tbl) { if (first) impl::print_to_stream(", "sv, base::stream()); first = true; print_key_segment(k); impl::print_to_stream(" = "sv, base::stream()); const auto type = v.type(); TOML_ASSUME(type != node_type::none); switch (type) { case node_type::table: print_inline(*reinterpret_cast<const table*>(&v)); break; case node_type::array: print(*reinterpret_cast<const array*>(&v)); break; default: base::print_value(v, type); } } impl::print_to_stream(" }"sv, base::stream()); } base::clear_naked_newline(); } } TOML_NAMESPACE_END // implementations of windows wide string nonsense #if TOML_WINDOWS_COMPAT TOML_DISABLE_WARNINGS #include <Windows.h> // fuckkkk :( TOML_ENABLE_WARNINGS TOML_IMPL_NAMESPACE_START { TOML_API TOML_EXTERNAL_LINKAGE std::string narrow(std::wstring_view str) noexcept { if (str.empty()) return {}; std::string s; const auto len = WideCharToMultiByte( 65001, 0, str.data(), static_cast<int>(str.length()), nullptr, 0, nullptr, nullptr ); if (len) { s.resize(static_cast<size_t>(len)); WideCharToMultiByte(65001, 0, str.data(), static_cast<int>(str.length()), s.data(), len, nullptr, nullptr); } return s; } TOML_API TOML_EXTERNAL_LINKAGE std::wstring widen(std::string_view str) noexcept { if (str.empty()) return {}; std::wstring s; const auto len = MultiByteToWideChar(65001, 0, str.data(), static_cast<int>(str.length()), nullptr, 0); if (len) { s.resize(static_cast<size_t>(len)); MultiByteToWideChar(65001, 0, str.data(), static_cast<int>(str.length()), s.data(), len); } return s; } #ifdef __cpp_lib_char8_t TOML_API TOML_EXTERNAL_LINKAGE std::wstring widen(std::u8string_view str) noexcept { if (str.empty()) return {}; return widen(std::string_view{ reinterpret_cast<const char*>(str.data()), str.length() }); } #endif // __cpp_lib_char8_t } TOML_IMPL_NAMESPACE_END #endif // TOML_WINDOWS_COMPAT TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS, TOML_DISABLE_ARITHMETIC_WARNINGS #endif //----------------------------------------------------------------------------- ↑ toml_default_formatter.hpp -- #if 1 //---- ↓ toml_json_formatter.hpp ------------------------------------------------------------------------------ TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS TOML_NAMESPACE_START { template <typename Char> inline void json_formatter<Char>::print(const toml::table& tbl) { if (tbl.empty()) impl::print_to_stream("{}"sv, base::stream()); else { impl::print_to_stream('{', base::stream()); base::increase_indent(); bool first = false; for (auto&& [k, v] : tbl) { if (first) impl::print_to_stream(", "sv, base::stream()); first = true; base::print_newline(true); base::print_indent(); base::print_quoted_string(k, false); impl::print_to_stream(" : "sv, base::stream()); const auto type = v.type(); TOML_ASSUME(type != node_type::none); switch (type) { case node_type::table: print(*reinterpret_cast<const table*>(&v)); break; case node_type::array: print(*reinterpret_cast<const array*>(&v)); break; default: base::print_value(v, type); } } base::decrease_indent(); base::print_newline(true); base::print_indent(); impl::print_to_stream('}', base::stream()); } base::clear_naked_newline(); } } TOML_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS #endif //---- ↑ toml_json_formatter.hpp ------------------------------------------------------------------------------ #if TOML_PARSER #if 1 //------------------------------ ↓ toml_utf8_streams.hpp ------------------------------------------------------ #if !TOML_EXCEPTIONS #undef TOML_ERROR_CHECK #define TOML_ERROR_CHECK if (reader.error()) return nullptr #endif TOML_IMPL_NAMESPACE_START { TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) TOML_EXTERNAL_LINKAGE utf8_buffered_reader::utf8_buffered_reader(utf8_reader_interface& reader_) noexcept : reader{ reader_ } {} TOML_EXTERNAL_LINKAGE const source_path_ptr& utf8_buffered_reader::source_path() const noexcept { return reader.source_path(); } TOML_EXTERNAL_LINKAGE const utf8_codepoint* utf8_buffered_reader::read_next() { TOML_ERROR_CHECK; if (negative_offset) { negative_offset--; // an entry negative offset of 1 just means "replay the current head" if (!negative_offset) return head; // otherwise step back into the history buffer else return history.buffer + ((history.first + history.count - negative_offset) % history_buffer_size); } else { // first character read from stream if TOML_UNLIKELY(!history.count && !head) head = reader.read_next(); // subsequent characters and not eof else if (head) { if TOML_UNLIKELY(history.count < history_buffer_size) history.buffer[history.count++] = *head; else history.buffer[(history.first++ + history_buffer_size) % history_buffer_size] = *head; head = reader.read_next(); } return head; } } TOML_EXTERNAL_LINKAGE const utf8_codepoint* utf8_buffered_reader::step_back(size_t count) noexcept { TOML_ERROR_CHECK; TOML_ASSERT(history.count); TOML_ASSERT(negative_offset + count <= history.count); negative_offset += count; return negative_offset ? history.buffer + ((history.first + history.count - negative_offset) % history_buffer_size) : head; } TOML_EXTERNAL_LINKAGE bool utf8_buffered_reader::peek_eof() const { return reader.peek_eof(); } #if !TOML_EXCEPTIONS TOML_EXTERNAL_LINKAGE optional<parse_error>&& utf8_buffered_reader::error() noexcept { return reader.error(); } #endif TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS } TOML_IMPL_NAMESPACE_END #undef TOML_ERROR_CHECK #undef TOML_ERROR #endif //------------------------------ ↑ toml_utf8_streams.hpp ------------------------------------------------------ #if 1 //---------------------------------------------------------- ↓ toml_parser.hpp -------------------------------- TOML_DISABLE_WARNINGS #include <cmath> #if TOML_INT_CHARCONV || TOML_FLOAT_CHARCONV #include <charconv> #endif #if !TOML_INT_CHARCONV || !TOML_FLOAT_CHARCONV #include <sstream> #endif #if !TOML_HEADER_ONLY using namespace std::string_view_literals; #endif TOML_ENABLE_WARNINGS TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS #if TOML_EXCEPTIONS && !defined(__INTELLISENSE__) #define TOML_RETURNS_BY_THROWING [[noreturn]] #else #define TOML_RETURNS_BY_THROWING #endif TOML_ANON_NAMESPACE_START { template <uint64_t> struct parse_integer_traits; template <> struct parse_integer_traits<2> final { static constexpr auto scope_qualifier = "binary integer"sv; static constexpr auto is_digit = ::toml::impl::is_binary_digit; static constexpr auto is_signed = false; static constexpr auto buffer_length = 63; static constexpr auto prefix_codepoint = U'b'; static constexpr auto prefix = "b"sv; }; template <> struct parse_integer_traits<8> final { static constexpr auto scope_qualifier = "octal integer"sv; static constexpr auto is_digit = ::toml::impl::is_octal_digit; static constexpr auto is_signed = false; static constexpr auto buffer_length = 21; // strlen("777777777777777777777") static constexpr auto prefix_codepoint = U'o'; static constexpr auto prefix = "o"sv; }; template <> struct parse_integer_traits<10> final { static constexpr auto scope_qualifier = "decimal integer"sv; static constexpr auto is_digit = ::toml::impl::is_decimal_digit; static constexpr auto is_signed = true; static constexpr auto buffer_length = 19; //strlen("9223372036854775807") }; template <> struct parse_integer_traits<16> final { static constexpr auto scope_qualifier = "hexadecimal integer"sv; static constexpr auto is_digit = ::toml::impl::is_hexadecimal_digit; static constexpr auto is_signed = false; static constexpr auto buffer_length = 16; //strlen("7FFFFFFFFFFFFFFF") static constexpr auto prefix_codepoint = U'x'; static constexpr auto prefix = "x"sv; }; [[nodiscard]] TOML_INTERNAL_LINKAGE std::string_view to_sv(::toml::node_type val) noexcept { using namespace ::toml::impl; return node_type_friendly_names[unwrap_enum(val)]; } [[nodiscard]] TOML_INTERNAL_LINKAGE std::string_view to_sv(const std::string& str) noexcept { return std::string_view{ str }; } [[nodiscard]] TOML_ATTR(const) TOML_INTERNAL_LINKAGE std::string_view to_sv(bool val) noexcept { using namespace std::string_view_literals; return val ? "true"sv : "false"sv; } [[nodiscard]] TOML_INTERNAL_LINKAGE std::string_view to_sv(const ::toml::impl::utf8_codepoint& cp) noexcept { using namespace ::toml; using namespace ::toml::impl; if TOML_UNLIKELY(cp.value <= U'\x1F') return low_character_escape_table[cp.value]; else if TOML_UNLIKELY(cp.value == U'\x7F') return "\\u007F"sv; else return cp.as_view(); } template <typename T> TOML_ATTR(nonnull) TOML_INTERNAL_LINKAGE TOML_NEVER_INLINE void concatenate(char*& write_pos, char *const buf_end, const T& arg) noexcept { using namespace ::toml; using namespace ::toml::impl; static_assert( is_one_of<remove_cvref_t<T>, std::string_view, int64_t, uint64_t, double>, "concatenate inputs are limited to std::string_view, int64_t, uint64_t and double to keep " "instantiations to a minimum as an anti-bloat measure (hint: to_sv will probably help)" ); if (write_pos >= buf_end) return; using arg_t = remove_cvref_t<T>; if constexpr (std::is_same_v<arg_t, std::string_view>) { const auto max_chars = static_cast<size_t>(buf_end - write_pos); const auto len = max_chars < arg.length() ? max_chars : arg.length(); std::memcpy(write_pos, arg.data(), len); write_pos += len; } else if constexpr (std::is_floating_point_v<arg_t>) { #if TOML_FLOAT_CHARCONV { const auto result = std::to_chars(write_pos, buf_end, arg); write_pos = result.ptr; } #else { std::ostringstream ss; ss.imbue(std::locale::classic()); ss.precision(std::numeric_limits<arg_t>::digits10 + 1); ss << arg; concatenate(write_pos, buf_end, to_sv(std::move(ss).str())); } #endif } else if constexpr (std::is_integral_v<arg_t>) { #if TOML_INT_CHARCONV { const auto result = std::to_chars(write_pos, buf_end, arg); write_pos = result.ptr; } #else { std::ostringstream ss; ss.imbue(std::locale::classic()); using cast_type = std::conditional_t<std::is_signed_v<arg_t>, int64_t, uint64_t>; ss << static_cast<cast_type>(arg); concatenate(write_pos, buf_end, to_sv(std::move(ss).str())); } #endif } } struct error_builder final { static constexpr std::size_t buf_size = 512; char buf[buf_size]; char* write_pos = buf; char* const max_write_pos = buf + (buf_size - std::size_t{ 1 }); //allow for null terminator error_builder(std::string_view scope) noexcept { concatenate(write_pos, max_write_pos, "Error while parsing "sv); concatenate(write_pos, max_write_pos, scope); concatenate(write_pos, max_write_pos, ": "sv); } template <typename T> void append(const T& arg) noexcept { concatenate(write_pos, max_write_pos, arg); } TOML_RETURNS_BY_THROWING auto finish(const ::toml::source_position& pos, const ::toml::source_path_ptr& source_path) const TOML_MAY_THROW { using namespace ::toml; *write_pos = '\0'; #if TOML_EXCEPTIONS throw parse_error{ buf, pos, source_path }; #else return parse_error{ std::string(buf, static_cast<size_t>(write_pos - buf)), pos, source_path }; #endif } }; struct parse_scope final { std::string_view& storage_; std::string_view parent_; TOML_NODISCARD_CTOR explicit parse_scope(std::string_view& current_scope, std::string_view new_scope) noexcept : storage_{ current_scope }, parent_{ current_scope } { storage_ = new_scope; } ~parse_scope() noexcept { storage_ = parent_; } }; #define push_parse_scope_2(scope, line) parse_scope ps_##line{ current_scope, scope } #define push_parse_scope_1(scope, line) push_parse_scope_2(scope, line) #define push_parse_scope(scope) push_parse_scope_1(scope, __LINE__) struct parsed_key final { std::vector<std::string> segments; }; struct parsed_key_value_pair final { parsed_key key; toml::node* value; }; } TOML_ANON_NAMESPACE_END TOML_IMPL_NAMESPACE_START { // Q: "what the fuck is this? MACROS????" // A: The parser needs to work in exceptionless mode (returning error objects directly) // and exception mode (reporting parse failures by throwing). Two totally different control flows. // These macros encapsulate the differences between the two modes so I can write code code // as though I was only targeting one mode and not want yeet myself into the sun. // They're all #undef'd at the bottom of the parser's implementation so they should be harmless outside // of toml++. #if defined(NDEBUG) || !defined(_DEBUG) #define assert_or_assume(cond) TOML_ASSUME(cond) #else #define assert_or_assume(cond) TOML_ASSERT(cond) #endif #define is_eof() !cp #define assert_not_eof() assert_or_assume(cp != nullptr) #define return_if_eof(...) do { if (is_eof()) return __VA_ARGS__; } while(false) #if TOML_EXCEPTIONS #define is_error() false #define return_after_error(...) TOML_UNREACHABLE #define assert_not_error() (void)0 #define return_if_error(...) (void)0 #define return_if_error_or_eof(...) return_if_eof(__VA_ARGS__) #else #define is_error() !!err #define return_after_error(...) return __VA_ARGS__ #define assert_not_error() TOML_ASSERT(!is_error()) #define return_if_error(...) do { if (is_error()) return __VA_ARGS__; } while(false) #define return_if_error_or_eof(...) do { if (is_eof() || is_error()) return __VA_ARGS__; } while(false) #endif #define set_error_and_return(ret, ...) \ do { if (!is_error()) set_error(__VA_ARGS__); return_after_error(ret); } while(false) #define set_error_and_return_default(...) set_error_and_return({}, __VA_ARGS__) #define set_error_and_return_if_eof(...) \ do { if (is_eof()) set_error_and_return(__VA_ARGS__, "encountered end-of-file"sv); } while(false) #define advance_and_return_if_error(...) \ do { assert_not_eof(); advance(); return_if_error(__VA_ARGS__); } while (false) #define advance_and_return_if_error_or_eof(...) \ do { \ assert_not_eof(); \ advance(); \ return_if_error(__VA_ARGS__); \ set_error_and_return_if_eof(__VA_ARGS__); \ } while (false) TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) class parser final { private: utf8_buffered_reader reader; table root; source_position prev_pos = { 1, 1 }; const utf8_codepoint* cp = {}; std::vector<table*> implicit_tables; std::vector<table*> dotted_key_tables; std::vector<array*> table_arrays; std::string recording_buffer; //for diagnostics bool recording = false, recording_whitespace = true; std::string_view current_scope; #if !TOML_EXCEPTIONS mutable optional<toml::parse_error> err; #endif [[nodiscard]] source_position current_position(source_index fallback_offset = 0) const noexcept { if (!is_eof()) return cp->position; return { prev_pos.line, static_cast<source_index>(prev_pos.column + fallback_offset) }; } template <typename... T> TOML_RETURNS_BY_THROWING TOML_NEVER_INLINE void set_error_at(source_position pos, const T&... reason) const TOML_MAY_THROW { static_assert(sizeof...(T) > 0_sz); #if !TOML_EXCEPTIONS if (err) return; #endif error_builder builder{ current_scope }; (builder.append(reason), ...); #if TOML_EXCEPTIONS builder.finish(pos, reader.source_path()); #else err.emplace(builder.finish(pos, reader.source_path())); #endif } template <typename... T> TOML_RETURNS_BY_THROWING void set_error(const T&... reason) const TOML_MAY_THROW { set_error_at(current_position(1), reason...); } void go_back(size_t count = 1_sz) noexcept { return_if_error(); assert_or_assume(count); cp = reader.step_back(count); prev_pos = cp->position; } void advance() TOML_MAY_THROW { return_if_error(); assert_not_eof(); prev_pos = cp->position; cp = reader.read_next(); #if !TOML_EXCEPTIONS if (reader.error()) { err = std::move(reader.error()); return; } #endif if (recording && !is_eof()) { if (recording_whitespace || !(is_whitespace(*cp) || is_line_break(*cp))) recording_buffer.append(cp->as_view()); } } void start_recording(bool include_current = true) noexcept { return_if_error(); recording = true; recording_whitespace = true; recording_buffer.clear(); if (include_current && !is_eof()) recording_buffer.append(cp->as_view()); } void stop_recording(size_t pop_bytes = 0_sz) noexcept { return_if_error(); recording = false; if (pop_bytes) { if (pop_bytes >= recording_buffer.length()) recording_buffer.clear(); else if (pop_bytes == 1_sz) recording_buffer.pop_back(); else recording_buffer.erase( recording_buffer.begin() + static_cast<ptrdiff_t>(recording_buffer.length() - pop_bytes), recording_buffer.end() ); } } bool consume_leading_whitespace() TOML_MAY_THROW { return_if_error_or_eof({}); bool consumed = false; while (!is_eof() && is_whitespace(*cp)) { consumed = true; advance_and_return_if_error({}); } return consumed; } bool consume_line_break() TOML_MAY_THROW { return_if_error_or_eof({}); if (!is_line_break(*cp)) return false; if (*cp == U'\r') { advance_and_return_if_error({}); // skip \r if (is_eof()) return true; //eof after \r is 'fine' else if (*cp != U'\n') set_error_and_return_default("expected \\n, saw '"sv, to_sv(*cp), "'"sv); } advance_and_return_if_error({}); // skip \n (or other single-character line ending) return true; } bool consume_rest_of_line() TOML_MAY_THROW { return_if_error_or_eof({}); do { if (is_line_break(*cp)) return consume_line_break(); else advance(); return_if_error({}); } while (!is_eof()); return true; } bool consume_comment() TOML_MAY_THROW { return_if_error_or_eof({}); if (*cp != U'#') return false; push_parse_scope("comment"sv); advance_and_return_if_error({}); //skip the '#' while (!is_eof()) { if (consume_line_break()) return true; if constexpr (TOML_LANG_AT_LEAST(1, 0, 0)) { // toml/issues/567 (disallow non-TAB control characters in comments) if (is_nontab_control_character(*cp)) set_error_and_return_default( "control characters other than TAB (U+0009) are explicitly prohibited"sv ); // toml/pull/720 (disallow surrogates in comments) else if (is_unicode_surrogate(*cp)) set_error_and_return_default( "unicode surrogates (U+D800 to U+DFFF) are explicitly prohibited"sv ); } advance_and_return_if_error({}); } return true; } [[nodiscard]] bool consume_expected_sequence(std::u32string_view seq) TOML_MAY_THROW { return_if_error({}); TOML_ASSERT(!seq.empty()); for (auto c : seq) { set_error_and_return_if_eof({}); if (*cp != c) return false; advance_and_return_if_error({}); } return true; } template <typename T> [[nodiscard]] bool consume_digit_sequence(T* digits, size_t len) TOML_MAY_THROW { return_if_error({}); assert_or_assume(digits); assert_or_assume(len); for (size_t i = 0; i < len; i++) { set_error_and_return_if_eof({}); if (!is_decimal_digit(*cp)) return false; digits[i] = static_cast<T>(*cp - U'0'); advance_and_return_if_error({}); } return true; } template <typename T> [[nodiscard]] size_t consume_variable_length_digit_sequence(T* buffer, size_t max_len) TOML_MAY_THROW { return_if_error({}); assert_or_assume(buffer); assert_or_assume(max_len); size_t i = {}; for (; i < max_len; i++) { if (is_eof() || !is_decimal_digit(*cp)) break; buffer[i] = static_cast<T>(*cp - U'0'); advance_and_return_if_error({}); } return i; } //template <bool MultiLine> [[nodiscard]] std::string parse_basic_string(bool multi_line) TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'"'); push_parse_scope("string"sv); // skip the '"' advance_and_return_if_error_or_eof({}); // multiline strings ignore a single line ending right at the beginning if (multi_line) { consume_line_break(); return_if_error({}); set_error_and_return_if_eof({}); } std::string str; bool escaped = false; [[maybe_unused]] bool skipping_whitespace = false; do { if (escaped) { escaped = false; // handle 'line ending slashes' in multi-line mode if (multi_line) { if (is_line_break(*cp) || is_whitespace(*cp)) { consume_leading_whitespace(); if (!consume_line_break()) set_error_and_return_default( "line-ending backslashes must be the last non-whitespace character on the line"sv ); skipping_whitespace = true; return_if_error({}); continue; } } bool skipped_escaped_codepoint = false; assert_not_eof(); switch (const auto escaped_codepoint = *cp) { // 'regular' escape codes case U'b': str += '\b'; break; case U'f': str += '\f'; break; case U'n': str += '\n'; break; case U'r': str += '\r'; break; case U't': str += '\t'; break; case U'"': str += '"'; break; case U'\\': str += '\\'; break; // unicode scalar sequences case U'x': #if TOML_LANG_UNRELEASED // toml/pull/709 (\xHH unicode scalar sequences) [[fallthrough]]; #else set_error_and_return_default( "escape sequence '\\x' is not supported in TOML 1.0.0 and earlier"sv ); #endif case U'u': [[fallthrough]]; case U'U': { push_parse_scope("unicode scalar escape sequence"sv); advance_and_return_if_error_or_eof({}); skipped_escaped_codepoint = true; uint32_t place_value = escaped_codepoint == U'U' ? 0x10000000u : (escaped_codepoint == U'u' ? 0x1000u : 0x10u); uint32_t sequence_value{}; while (place_value) { set_error_and_return_if_eof({}); if (!is_hexadecimal_digit(*cp)) set_error_and_return_default("expected hex digit, saw '"sv, to_sv(*cp), "'"sv); sequence_value += place_value * hex_to_dec(*cp); place_value /= 16u; advance_and_return_if_error({}); } if (is_unicode_surrogate(sequence_value)) set_error_and_return_default( "unicode surrogates (U+D800 - U+DFFF) are explicitly prohibited"sv ); else if (sequence_value > 0x10FFFFu) set_error_and_return_default("values greater than U+10FFFF are invalid"sv); else if (sequence_value <= 0x7Fu) //ascii str += static_cast<char>(sequence_value & 0x7Fu); else if (sequence_value <= 0x7FFu) { str += static_cast<char>(0xC0u | ((sequence_value >> 6) & 0x1Fu)); str += static_cast<char>(0x80u | (sequence_value & 0x3Fu)); } else if (sequence_value <= 0xFFFFu) { str += static_cast<char>(0xE0u | ((sequence_value >> 12) & 0x0Fu)); str += static_cast<char>(0x80u | ((sequence_value >> 6) & 0x1Fu)); str += static_cast<char>(0x80u | (sequence_value & 0x3Fu)); } else { str += static_cast<char>(0xF0u | ((sequence_value >> 18) & 0x07u)); str += static_cast<char>(0x80u | ((sequence_value >> 12) & 0x3Fu)); str += static_cast<char>(0x80u | ((sequence_value >> 6) & 0x3Fu)); str += static_cast<char>(0x80u | (sequence_value & 0x3Fu)); } break; } // ??? default: set_error_and_return_default("unknown escape sequence '\\"sv, to_sv(*cp), "'"sv); } // skip the escaped character if (!skipped_escaped_codepoint) advance_and_return_if_error_or_eof({}); } else { // handle closing delimiters if (*cp == U'"') { if (multi_line) { size_t lookaheads = {}; size_t consecutive_delimiters = 1_sz; do { advance_and_return_if_error({}); lookaheads++; if (!is_eof() && *cp == U'"') consecutive_delimiters++; else break; } while (lookaheads < 4_sz); switch (consecutive_delimiters) { // """ " (one quote somewhere in a ML string) case 1_sz: str += '"'; skipping_whitespace = false; continue; // """ "" (two quotes somewhere in a ML string) case 2_sz: str.append("\"\""sv); skipping_whitespace = false; continue; // """ """ (the end of the string) case 3_sz: return str; // """ """" (one at the end of the string) case 4_sz: str += '"'; return str; // """ """"" (two quotes at the end of the string) case 5_sz: str.append("\"\""sv); advance_and_return_if_error({}); // skip the last '"' return str; TOML_NO_DEFAULT_CASE; } } else { advance_and_return_if_error({}); // skip the closing delimiter return str; } } // handle escapes else if (*cp == U'\\') { advance_and_return_if_error_or_eof({}); // skip the '\' skipping_whitespace = false; escaped = true; continue; } // handle line endings in multi-line mode if (multi_line && is_line_break(*cp)) { consume_line_break(); return_if_error({}); if (!skipping_whitespace) str += '\n'; continue; } // handle control characters if (is_nontab_control_character(*cp)) set_error_and_return_default( "unescaped control characters other than TAB (U+0009) are explicitly prohibited"sv ); // handle surrogates in strings (1.0.0 and later) if constexpr (TOML_LANG_AT_LEAST(1, 0, 0)) { if (is_unicode_surrogate(*cp)) set_error_and_return_default( "unescaped unicode surrogates (U+D800 to U+DFFF) are explicitly prohibited"sv ); } if (multi_line) { if (!skipping_whitespace || !is_whitespace(*cp)) { skipping_whitespace = false; str.append(cp->as_view()); } } else str.append(cp->as_view()); advance_and_return_if_error({}); } } while (!is_eof()); set_error_and_return_default("encountered end-of-file"sv); } [[nodiscard]] std::string parse_literal_string(bool multi_line) TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'\''); push_parse_scope("literal string"sv); // skip the delimiter advance_and_return_if_error_or_eof({}); // multiline strings ignore a single line ending right at the beginning if (multi_line) { consume_line_break(); return_if_error({}); set_error_and_return_if_eof({}); } std::string str; do { assert_not_error(); // handle closing delimiters if (*cp == U'\'') { if (multi_line) { size_t lookaheads = {}; size_t consecutive_delimiters = 1_sz; do { advance_and_return_if_error({}); lookaheads++; if (!is_eof() && *cp == U'\'') consecutive_delimiters++; else break; } while (lookaheads < 4_sz); switch (consecutive_delimiters) { // ''' ' (one quote somewhere in a ML string) case 1_sz: str += '\''; continue; // ''' '' (two quotes somewhere in a ML string) case 2_sz: str.append("''"sv); continue; // ''' ''' (the end of the string) case 3_sz: return str; // ''' '''' (one at the end of the string) case 4_sz: str += '\''; return str; // ''' ''''' (two quotes at the end of the string) case 5_sz: str.append("''"sv); advance_and_return_if_error({}); // skip the last ' return str; TOML_NO_DEFAULT_CASE; } } else { advance_and_return_if_error({}); // skip the closing delimiter return str; } } // handle line endings in multi-line mode if (multi_line && is_line_break(*cp)) { consume_line_break(); str += '\n'; continue; } // handle control characters if (is_nontab_control_character(*cp)) set_error_and_return_default( "control characters other than TAB (U+0009) are explicitly prohibited"sv ); // handle surrogates in strings (1.0.0 and later) if constexpr (TOML_LANG_AT_LEAST(1, 0, 0)) { if (is_unicode_surrogate(*cp)) set_error_and_return_default( "unicode surrogates (U+D800 - U+DFFF) are explicitly prohibited"sv ); } str.append(cp->as_view()); advance_and_return_if_error({}); } while (!is_eof()); set_error_and_return_default("encountered end-of-file"sv); } struct parsed_string final { std::string value; bool was_multi_line; }; [[nodiscard]] TOML_NEVER_INLINE parsed_string parse_string() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_string_delimiter(*cp)); push_parse_scope("string"sv); // get the first three characters to determine the string type const auto first = cp->value; advance_and_return_if_error_or_eof({}); const auto second = cp->value; advance_and_return_if_error({}); const auto third = cp ? cp->value : U'\0'; // if we were eof at the third character then first and second need to be // the same string character (otherwise it's an unterminated string) if (is_eof()) { if (second == first) return {}; set_error_and_return_default("encountered end-of-file"sv); } // if the first three characters are all the same string delimiter then // it's a multi-line string. else if (first == second && first == third) { return { first == U'\'' ? parse_literal_string(true) : parse_basic_string(true), true }; } // otherwise it's just a regular string. else { // step back two characters so that the current // character is the string delimiter go_back(2_sz); return { first == U'\'' ? parse_literal_string(false) : parse_basic_string(false), false }; } } [[nodiscard]] std::string parse_bare_key_segment() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_bare_key_character(*cp)); std::string segment; while (!is_eof()) { if (!is_bare_key_character(*cp)) break; segment.append(cp->as_view()); advance_and_return_if_error({}); } return segment; } [[nodiscard]] bool parse_boolean() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_match(*cp, U't', U'f', U'T', U'F')); push_parse_scope("boolean"sv); start_recording(true); auto result = is_match(*cp, U't', U'T'); if (!consume_expected_sequence(result ? U"true"sv : U"false"sv)) set_error_and_return_default( "expected '"sv, to_sv(result), "', saw '"sv, to_sv(recording_buffer), "'"sv ); stop_recording(); if (cp && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); return result; } [[nodiscard]] double parse_inf_or_nan() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_match(*cp, U'i', U'n', U'I', U'N', U'+', U'-')); push_parse_scope("floating-point"sv); start_recording(true); const bool negative = *cp == U'-'; if (negative || *cp == U'+') advance_and_return_if_error_or_eof({}); const bool inf = is_match(*cp, U'i', U'I'); if (!consume_expected_sequence(inf ? U"inf"sv : U"nan"sv)) set_error_and_return_default( "expected '"sv, inf ? "inf"sv : "nan"sv, "', saw '"sv, to_sv(recording_buffer), "'"sv ); stop_recording(); if (cp && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); return inf ? (negative ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity()) : std::numeric_limits<double>::quiet_NaN(); } TOML_PUSH_WARNINGS TOML_DISABLE_SWITCH_WARNINGS TOML_DISABLE_INIT_WARNINGS [[nodiscard]] double parse_float() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_match(*cp, U'+', U'-', U'.') || is_decimal_digit(*cp)); push_parse_scope("floating-point"sv); // sign const int sign = *cp == U'-' ? -1 : 1; if (is_match(*cp, U'+', U'-')) advance_and_return_if_error_or_eof({}); // consume value chars char chars[64]; size_t length = {}; const utf8_codepoint* prev = {}; bool seen_decimal = false, seen_exponent = false; char first_integer_part = '\0'; while (!is_eof() && !is_value_terminator(*cp)) { if (*cp == U'_') { if (!prev || !is_decimal_digit(*prev)) set_error_and_return_default("underscores may only follow digits"sv); prev = cp; advance_and_return_if_error_or_eof({}); continue; } else if (prev && *prev == U'_' && !is_decimal_digit(*cp)) set_error_and_return_default("underscores must be followed by digits"sv); else if (*cp == U'.') { // .1 // -.1 // +.1 (no integer part) if (!first_integer_part) set_error_and_return_default("expected decimal digit, saw '.'"sv); // 1.0e+.10 (exponent cannot have '.') else if (seen_exponent) set_error_and_return_default("expected exponent decimal digit or sign, saw '.'"sv); // 1.0.e+.10 // 1..0 // (multiple '.') else if (seen_decimal) set_error_and_return_default("expected decimal digit or exponent, saw '.'"sv); seen_decimal = true; } else if (is_match(*cp, U'e', U'E')) { if (prev && !is_decimal_digit(*prev)) set_error_and_return_default("expected decimal digit, saw '"sv, to_sv(*cp), "'"sv); // 1.0ee+10 (multiple 'e') else if (seen_exponent) set_error_and_return_default("expected decimal digit, saw '"sv, to_sv(*cp), "'"sv); seen_decimal = true; // implied seen_exponent = true; } else if (is_match(*cp, U'+', U'-')) { // 1.-0 (sign in mantissa) if (!seen_exponent) set_error_and_return_default("expected decimal digit or '.', saw '"sv, to_sv(*cp), "'"sv); // 1.0e1-0 (misplaced exponent sign) else if (!is_match(*prev, U'e', U'E')) set_error_and_return_default("expected exponent digit, saw '"sv, to_sv(*cp), "'"sv); } else if (length == sizeof(chars)) set_error_and_return_default( "exceeds maximum length of "sv, static_cast<uint64_t>(sizeof(chars)), " characters"sv ); else if (is_decimal_digit(*cp)) { if (!seen_decimal) { if (!first_integer_part) first_integer_part = static_cast<char>(cp->bytes[0]); else if (first_integer_part == '0') set_error_and_return_default("leading zeroes are prohibited"sv); } } else set_error_and_return_default("expected decimal digit, saw '"sv, to_sv(*cp), "'"sv); chars[length++] = static_cast<char>(cp->bytes[0]); prev = cp; advance_and_return_if_error({}); } // sanity-check ending state if (prev) { if (*prev == U'_') { set_error_and_return_if_eof({}); set_error_and_return_default("underscores must be followed by digits"sv); } else if (is_match(*prev, U'e', U'E', U'+', U'-', U'.')) { set_error_and_return_if_eof({}); set_error_and_return_default("expected decimal digit, saw '"sv, to_sv(*cp), "'"sv); } } // convert to double double result; #if TOML_FLOAT_CHARCONV { auto fc_result = std::from_chars(chars, chars + length, result); switch (fc_result.ec) { case std::errc{}: //ok return result * sign; case std::errc::invalid_argument: set_error_and_return_default( "'"sv, std::string_view{ chars, length }, "' could not be interpreted as a value"sv ); break; case std::errc::result_out_of_range: set_error_and_return_default( "'"sv, std::string_view{ chars, length }, "' is not representable in 64 bits"sv ); break; default: //?? set_error_and_return_default( "an unspecified error occurred while trying to interpret '"sv, std::string_view{ chars, length }, "' as a value"sv ); } } #else { std::stringstream ss; ss.imbue(std::locale::classic()); ss.write(chars, static_cast<std::streamsize>(length)); if ((ss >> result)) return result * sign; else set_error_and_return_default( "'"sv, std::string_view{ chars, length }, "' could not be interpreted as a value"sv ); } #endif } [[nodiscard]] double parse_hex_float() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_match(*cp, U'0', U'+', U'-')); push_parse_scope("hexadecimal floating-point"sv); #if TOML_LANG_UNRELEASED // toml/issues/562 (hexfloats) // sign const int sign = *cp == U'-' ? -1 : 1; if (is_match(*cp, U'+', U'-')) advance_and_return_if_error_or_eof({}); // '0' if (*cp != U'0') set_error_and_return_default(" expected '0', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // 'x' or 'X' if (!is_match(*cp, U'x', U'X')) set_error_and_return_default("expected 'x' or 'X', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // <HEX DIGITS> ([.]<HEX DIGITS>)? [pP] [+-]? <DEC DIGITS> // consume value fragments struct fragment { char chars[24]; size_t length; double value; }; fragment fragments[] = { {}, // mantissa, whole part {}, // mantissa, fractional part {} // exponent }; fragment* current_fragment = fragments; const utf8_codepoint* prev = {}; int exponent_sign = 1; while (!is_eof() && !is_value_terminator(*cp)) { if (*cp == U'_') { if (!prev || !is_hexadecimal_digit(*prev)) set_error_and_return_default("underscores may only follow digits"sv); prev = cp; advance_and_return_if_error_or_eof({}); continue; } else if (prev && *prev == U'_' && !is_hexadecimal_digit(*cp)) set_error_and_return_default("underscores must be followed by digits"sv); else if (*cp == U'.') { // 0x10.0p-.0 (exponent cannot have '.') if (current_fragment == fragments + 2) set_error_and_return_default("expected exponent digit or sign, saw '.'"sv); // 0x10.0.p-0 (multiple '.') else if (current_fragment == fragments + 1) set_error_and_return_default("expected hexadecimal digit or exponent, saw '.'"sv); else current_fragment++; } else if (is_match(*cp, U'p', U'P')) { // 0x10.0pp-0 (multiple 'p') if (current_fragment == fragments + 2) set_error_and_return_default("expected exponent digit or sign, saw '"sv, to_sv(*cp), "'"sv); // 0x.p-0 (mantissa is just '.') else if (fragments[0].length == 0_sz && fragments[1].length == 0_sz) set_error_and_return_default("expected hexadecimal digit, saw '"sv, to_sv(*cp), "'"sv); else current_fragment = fragments + 2; } else if (is_match(*cp, U'+', U'-')) { // 0x-10.0p-0 (sign in mantissa) if (current_fragment != fragments + 2) set_error_and_return_default("expected hexadecimal digit or '.', saw '"sv, to_sv(*cp), "'"sv); // 0x10.0p0- (misplaced exponent sign) else if (!is_match(*prev, U'p', U'P')) set_error_and_return_default("expected exponent digit, saw '"sv, to_sv(*cp), "'"sv); else exponent_sign = *cp == U'-' ? -1 : 1; } else if (current_fragment < fragments + 2 && !is_hexadecimal_digit(*cp)) set_error_and_return_default("expected hexadecimal digit or '.', saw '"sv, to_sv(*cp), "'"sv); else if (current_fragment == fragments + 2 && !is_decimal_digit(*cp)) set_error_and_return_default("expected exponent digit or sign, saw '"sv, to_sv(*cp), "'"sv); else if (current_fragment->length == sizeof(fragment::chars)) set_error_and_return_default( "fragment exceeeds maximum length of "sv, static_cast<uint64_t>(sizeof(fragment::chars)), " characters"sv ); else current_fragment->chars[current_fragment->length++] = static_cast<char>(cp->bytes[0]); prev = cp; advance_and_return_if_error({}); } // sanity-check ending state if (current_fragment != fragments + 2 || current_fragment->length == 0_sz) { set_error_and_return_if_eof({}); set_error_and_return_default("missing exponent"sv); } else if (prev && *prev == U'_') { set_error_and_return_if_eof({}); set_error_and_return_default("underscores must be followed by digits"sv); } // calculate values for the three fragments for (int fragment_idx = 0; fragment_idx < 3; fragment_idx++) { auto& f = fragments[fragment_idx]; const uint32_t base = fragment_idx == 2 ? 10 : 16; // left-trim zeroes const char* c = f.chars; size_t sig = {}; while (f.length && *c == '0') { f.length--; c++; sig++; } if (!f.length) continue; // calculate value auto place = 1u; for (size_t i = 0; i < f.length - 1_sz; i++) place *= base; uint32_t val{}; while (place) { if (base == 16) val += place * hex_to_dec(*c); else val += place * static_cast<uint32_t>(*c - '0'); if (fragment_idx == 1) sig++; c++; place /= base; } f.value = static_cast<double>(val); // shift the fractional part if (fragment_idx == 1) { while (sig--) f.value /= base; } } return (fragments[0].value + fragments[1].value) * pow(2.0, fragments[2].value * exponent_sign) * sign; #else // !TOML_LANG_UNRELEASED set_error_and_return_default( "hexadecimal floating-point values are not supported " "in TOML 1.0.0 and earlier"sv ); #endif // !TOML_LANG_UNRELEASED } template <uint64_t base> [[nodiscard]] int64_t parse_integer() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); using traits = parse_integer_traits<base>; push_parse_scope(traits::scope_qualifier); [[maybe_unused]] int64_t sign = 1; if constexpr (traits::is_signed) { sign = *cp == U'-' ? -1 : 1; if (is_match(*cp, U'+', U'-')) advance_and_return_if_error_or_eof({}); } if constexpr (base == 10) { if (!traits::is_digit(*cp)) set_error_and_return_default("expected expected digit or sign, saw '"sv, to_sv(*cp), "'"sv); } else { // '0' if (*cp != U'0') set_error_and_return_default("expected '0', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // 'b', 'o', 'x' if (*cp != traits::prefix_codepoint) set_error_and_return_default("expected '"sv, traits::prefix, "', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); } // consume value chars char chars[traits::buffer_length]; size_t length = {}; const utf8_codepoint* prev = {}; while (!is_eof() && !is_value_terminator(*cp)) { if (*cp == U'_') { if (!prev || !traits::is_digit(*prev)) set_error_and_return_default("underscores may only follow digits"sv); prev = cp; advance_and_return_if_error_or_eof({}); continue; } else if (prev && *prev == U'_' && !traits::is_digit(*cp)) set_error_and_return_default("underscores must be followed by digits"sv); else if (!traits::is_digit(*cp)) set_error_and_return_default("expected digit, saw '"sv, to_sv(*cp), "'"sv); else if (length == sizeof(chars)) set_error_and_return_default( "exceeds maximum length of "sv, static_cast<uint64_t>(sizeof(chars)), " characters"sv ); else chars[length++] = static_cast<char>(cp->bytes[0]); prev = cp; advance_and_return_if_error({}); } // sanity check ending state if (prev && *prev == U'_') { set_error_and_return_if_eof({}); set_error_and_return_default("underscores must be followed by digits"sv); } // check for leading zeroes if constexpr (base == 10) { if (chars[0] == '0') set_error_and_return_default("leading zeroes are prohibited"sv); } // single digits can be converted trivially if (length == 1_sz) { if constexpr (base == 16) return static_cast<int64_t>(hex_to_dec(chars[0])); else if constexpr (base <= 10) return static_cast<int64_t>(chars[0] - '0'); } // otherwise do the thing uint64_t result = {}; { const char* msd = chars; const char* end = msd + length; while (msd < end && *msd == '0') msd++; if (msd == end) return 0ll; uint64_t power = 1; while (--end >= msd) { if constexpr (base == 16) result += power * hex_to_dec(*end); else result += power * static_cast<uint64_t>(*end - '0'); power *= base; } } // range check if (result > static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()) + (sign < 0 ? 1ull : 0ull)) set_error_and_return_default( "'"sv, std::string_view{ chars, length }, "' is not representable in 64 bits"sv ); if constexpr (traits::is_signed) return static_cast<int64_t>(result) * sign; else return static_cast<int64_t>(result); } [[nodiscard]] date parse_date(bool part_of_datetime = false) TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_decimal_digit(*cp)); push_parse_scope("date"sv); // "YYYY" uint32_t digits[4]; if (!consume_digit_sequence(digits, 4_sz)) set_error_and_return_default("expected 4-digit year, saw '"sv, to_sv(*cp), "'"sv); const auto year = digits[3] + digits[2] * 10u + digits[1] * 100u + digits[0] * 1000u; const auto is_leap_year = (year % 4u == 0u) && ((year % 100u != 0u) || (year % 400u == 0u)); set_error_and_return_if_eof({}); // '-' if (*cp != U'-') set_error_and_return_default("expected '-', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "MM" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit month, saw '"sv, to_sv(*cp), "'"sv); const auto month = digits[1] + digits[0] * 10u; if (month == 0u || month > 12u) set_error_and_return_default( "expected month between 1 and 12 (inclusive), saw "sv, static_cast<uint64_t>(month) ); const auto max_days_in_month = month == 2u ? (is_leap_year ? 29u : 28u) : (month == 4u || month == 6u || month == 9u || month == 11u ? 30u : 31u) ; set_error_and_return_if_eof({}); // '-' if (*cp != U'-') set_error_and_return_default("expected '-', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "DD" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit day, saw '"sv, to_sv(*cp), "'"sv); const auto day = digits[1] + digits[0] * 10u; if (day == 0u || day > max_days_in_month) set_error_and_return_default( "expected day between 1 and "sv, static_cast<uint64_t>(max_days_in_month), " (inclusive), saw "sv, static_cast<uint64_t>(day) ); if (!part_of_datetime && !is_eof() && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); return { static_cast<uint16_t>(year), static_cast<uint8_t>(month), static_cast<uint8_t>(day) }; } [[nodiscard]] time parse_time(bool part_of_datetime = false) TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_decimal_digit(*cp)); push_parse_scope("time"sv); static constexpr auto max_digits = 9_sz; uint32_t digits[max_digits]; // "HH" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit hour, saw '"sv, to_sv(*cp), "'"sv); const auto hour = digits[1] + digits[0] * 10u; if (hour > 23u) set_error_and_return_default( "expected hour between 0 to 59 (inclusive), saw "sv, static_cast<uint64_t>(hour) ); set_error_and_return_if_eof({}); // ':' if (*cp != U':') set_error_and_return_default("expected ':', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "MM" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit minute, saw '"sv, to_sv(*cp), "'"sv); const auto minute = digits[1] + digits[0] * 10u; if (minute > 59u) set_error_and_return_default( "expected minute between 0 and 59 (inclusive), saw "sv, static_cast<uint64_t>(minute) ); auto time = ::toml::time{ static_cast<uint8_t>(hour), static_cast<uint8_t>(minute), }; // ':' if constexpr (TOML_LANG_UNRELEASED) // toml/issues/671 (allow omission of seconds) { if (is_eof() || is_value_terminator(*cp) || (part_of_datetime && is_match(*cp, U'+', U'-', U'Z'))) return time; } else set_error_and_return_if_eof({}); if (*cp != U':') set_error_and_return_default("expected ':', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "SS" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit second, saw '"sv, to_sv(*cp), "'"sv); const auto second = digits[1] + digits[0] * 10u; if (second > 59u) set_error_and_return_default( "expected second between 0 and 59 (inclusive), saw "sv, static_cast<uint64_t>(second) ); time.second = static_cast<uint8_t>(second); // '.' (early-exiting is allowed; fractional is optional) if (is_eof() || is_value_terminator(*cp) || (part_of_datetime && is_match(*cp, U'+', U'-', U'Z'))) return time; if (*cp != U'.') set_error_and_return_default("expected '.', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "FFFFFFFFF" auto digit_count = consume_variable_length_digit_sequence(digits, max_digits); if (!digit_count) { set_error_and_return_if_eof({}); set_error_and_return_default("expected fractional digits, saw '"sv, to_sv(*cp), "'"sv); } else if (!is_eof()) { if (digit_count == max_digits && is_decimal_digit(*cp)) set_error_and_return_default( "fractional component exceeds maximum precision of "sv, static_cast<uint64_t>(max_digits) ); else if (!part_of_datetime && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); } uint32_t value = 0u; uint32_t place = 1u; for (auto i = digit_count; i --> 0_sz;) { value += digits[i] * place; place *= 10u; } for (auto i = digit_count; i < max_digits; i++) //implicit zeros value *= 10u; time.nanosecond = value; return time; } [[nodiscard]] date_time parse_date_time() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_decimal_digit(*cp)); push_parse_scope("date-time"sv); // "YYYY-MM-DD" auto date = parse_date(true); set_error_and_return_if_eof({}); // ' ' or 'T' if (!is_match(*cp, U' ', U'T')) set_error_and_return_default("expected space or 'T', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "HH:MM:SS.FFFFFFFFF" auto time = parse_time(true); return_if_error({}); // no offset if (is_eof() || is_value_terminator(*cp)) return { date, time }; // zero offset ("Z") time_offset offset; if (*cp == U'Z') advance_and_return_if_error({}); // explicit offset ("+/-HH:MM") else if (is_match(*cp, U'+', U'-')) { push_parse_scope("date-time offset"sv); // sign int sign = *cp == U'-' ? -1 : 1; advance_and_return_if_error_or_eof({}); // "HH" int digits[2]; if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit hour, saw '"sv, to_sv(*cp), "'"sv); const auto hour = digits[1] + digits[0] * 10; if (hour > 23) set_error_and_return_default( "expected hour between 0 and 23 (inclusive), saw "sv, static_cast<int64_t>(hour) ); set_error_and_return_if_eof({}); // ':' if (*cp != U':') set_error_and_return_default("expected ':', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // "MM" if (!consume_digit_sequence(digits, 2_sz)) set_error_and_return_default("expected 2-digit minute, saw '"sv, to_sv(*cp), "'"sv); const auto minute = digits[1] + digits[0] * 10; if (minute > 59) set_error_and_return_default( "expected minute between 0 and 59 (inclusive), saw "sv, static_cast<int64_t>(minute) ); offset.minutes = static_cast<int16_t>((hour * 60 + minute) * sign); } if (!is_eof() && !is_value_terminator(*cp)) set_error_and_return_default("expected value-terminator, saw '"sv, to_sv(*cp), "'"sv); return { date, time, offset }; } TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS, TOML_DISABLE_INIT_WARNINGS [[nodiscard]] toml::array* parse_array() TOML_MAY_THROW; [[nodiscard]] toml::table* parse_inline_table() TOML_MAY_THROW; [[nodiscard]] node* parse_value_known_prefixes() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(!is_control_character(*cp)); assert_or_assume(*cp != U'_'); switch (cp->value) { // arrays case U'[': return parse_array(); // inline tables case U'{': return parse_inline_table(); // floats beginning with '.' case U'.': return new value{ parse_float() }; // strings case U'"': [[fallthrough]]; case U'\'': return new value{ std::move(parse_string().value) }; // bools case U't': [[fallthrough]]; case U'f': [[fallthrough]]; case U'T': [[fallthrough]]; case U'F': return new value{ parse_boolean() }; // inf/nan case U'i': [[fallthrough]]; case U'I': [[fallthrough]]; case U'n': [[fallthrough]]; case U'N': return new value{ parse_inf_or_nan() }; } return nullptr; } [[nodiscard]] node* parse_value() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(!is_value_terminator(*cp)); push_parse_scope("value"sv); // check if it begins with some control character // (note that this will also fail for whitespace but we're assuming we've // called consume_leading_whitespace() before calling parse_value()) if TOML_UNLIKELY(is_control_character(*cp)) set_error_and_return_default("unexpected control character"sv); // underscores at the beginning else if (*cp == U'_') set_error_and_return_default("values may not begin with underscores"sv); const auto begin_pos = cp->position; node* val{}; do { assert_or_assume(!is_control_character(*cp)); assert_or_assume(*cp != U'_'); // detect the value type and parse accordingly, // starting with value types that can be detected // unambiguously from just one character. val = parse_value_known_prefixes(); return_if_error({}); if (val) break; // value types from here down require more than one character to unambiguously identify // so scan ahead and collect a set of value 'traits'. enum value_traits : int { has_nothing = 0, has_digits = 1, has_b = 1 << 1, // as second char only (0b) has_e = 1 << 2, // only float exponents has_o = 1 << 3, // as second char only (0o) has_p = 1 << 4, // only hexfloat exponents has_t = 1 << 5, has_x = 1 << 6, // as second or third char only (0x, -0x, +0x) has_z = 1 << 7, has_colon = 1 << 8, has_plus = 1 << 9, has_minus = 1 << 10, has_dot = 1 << 11, begins_sign = 1 << 12, begins_digit = 1 << 13, begins_zero = 1 << 14 // Q: "why not make these real values in the enum??" // A: because the visual studio debugger stops treating them as a set of flags if you add // non-pow2 values, making them much harder to debug. #define signs_msk (has_plus | has_minus) #define bzero_msk (begins_zero | has_digits) #define bdigit_msk (begins_digit | has_digits) }; value_traits traits = has_nothing; const auto has_any = [&](auto t) noexcept { return (traits & t) != has_nothing; }; const auto has_none = [&](auto t) noexcept { return (traits & t) == has_nothing; }; const auto add_trait = [&](auto t) noexcept { traits = static_cast<value_traits>(traits | t); }; // examine the first character to get the 'begins with' traits // (good fail-fast opportunity; all the remaining types begin with numeric digits or signs) if (is_decimal_digit(*cp)) add_trait(*cp == U'0' ? begins_zero : begins_digit); else if (is_match(*cp, U'+', U'-')) add_trait(begins_sign); else break; // scan the rest of the value to determine the remaining traits char32_t chars[utf8_buffered_reader::max_history_length]; size_t char_count = {}, advance_count = {}; bool eof_while_scanning = false; const auto scan = [&]() TOML_MAY_THROW { if (is_eof()) return; assert_or_assume(!is_value_terminator(*cp)); do { if (const auto c = **cp; c != U'_') { chars[char_count++] = c; if (is_decimal_digit(c)) add_trait(has_digits); else if (is_ascii_letter(c)) { assert_or_assume((c >= U'a' && c <= U'z') || (c >= U'A' && c <= U'Z')); switch (static_cast<char32_t>(c | 32u)) { case U'b': if (char_count == 2_sz && has_any(begins_zero)) add_trait(has_b); break; case U'e': if (char_count > 1_sz && has_none(has_b | has_o | has_p | has_t | has_x | has_z | has_colon) && (has_none(has_plus | has_minus) || has_any(begins_sign))) add_trait(has_e); break; case U'o': if (char_count == 2_sz && has_any(begins_zero)) add_trait(has_o); break; case U'p': if (has_any(has_x)) add_trait(has_p); break; case U'x': if ((char_count == 2_sz && has_any(begins_zero)) || (char_count == 3_sz && has_any(begins_sign) && chars[1] == U'0')) add_trait(has_x); break; case U't': add_trait(has_t); break; case U'z': add_trait(has_z); break; } } else if (c <= U':') { assert_or_assume(c < U'0' || c > U'9'); switch (c) { case U'+': add_trait(has_plus); break; case U'-': add_trait(has_minus); break; case U'.': add_trait(has_dot); break; case U':': add_trait(has_colon); break; } } } advance_and_return_if_error(); advance_count++; eof_while_scanning = is_eof(); } while (advance_count < utf8_buffered_reader::max_history_length && !is_eof() && !is_value_terminator(*cp) ); }; scan(); return_if_error({}); // force further scanning if this could have been a date-time with a space instead of a T if (char_count == 10_sz && traits == (bdigit_msk | has_minus) && chars[4] == U'-' && chars[7] == U'-' && !is_eof() && *cp == U' ') { const auto pre_advance_count = advance_count; const auto pre_scan_traits = traits; chars[char_count++] = *cp; add_trait(has_t); const auto backpedal = [&]() noexcept { go_back(advance_count - pre_advance_count); advance_count = pre_advance_count; traits = pre_scan_traits; char_count = 10_sz; }; advance_and_return_if_error({}); advance_count++; if (is_eof() || !is_decimal_digit(*cp)) backpedal(); else { chars[char_count++] = *cp; advance_and_return_if_error({}); advance_count++; scan(); return_if_error({}); if (char_count == 12_sz) backpedal(); } } // set the reader back to where we started go_back(advance_count); if (char_count < utf8_buffered_reader::max_history_length - 1_sz) chars[char_count] = U'\0'; // if after scanning ahead we still only have one value character, // the only valid value type is an integer. if (char_count == 1_sz) { if (has_any(begins_zero | begins_digit)) { val = new value{ static_cast<int64_t>(chars[0] - U'0') }; advance(); //skip the digit break; } //anything else would be ambiguous. else set_error_and_return_default( eof_while_scanning ? "encountered end-of-file"sv : "could not determine value type"sv ); } // now things that can be identified from two or more characters return_if_error({}); assert_or_assume(char_count >= 2_sz); // do some 'fuzzy matching' where there's no ambiguity, since that allows the specific // typed parse functions to take over and show better diagnostics if there's an issue // (as opposed to the fallback "could not determine type" message) if (has_any(has_p)) val = new value{ parse_hex_float() }; else if (has_any(has_x)) val = new value{ parse_integer<16>() }; else if (has_any(has_o)) val = new value{ parse_integer<8>() }; else if (has_any(has_b)) val = new value{ parse_integer<2>() }; else if (has_any(has_e) || (has_any(begins_zero | begins_digit) && chars[1] == U'.')) val = new value{ parse_float() }; else if (has_any(begins_sign)) { // single-digit signed integers if (char_count == 2_sz && has_any(has_digits)) { val = new value{ static_cast<int64_t>(chars[1] - U'0') * (chars[0] == U'-' ? -1LL : 1LL) }; advance(); //skip the sign advance(); //skip the digit break; } // simple signed floats (e.g. +1.0) if (is_decimal_digit(chars[1]) && chars[2] == U'.') val = new value{ parse_float() }; // signed infinity or nan else if (is_match(chars[1], U'i', U'n', U'I', U'N')) val = new value{ parse_inf_or_nan() }; } return_if_error({}); if (val) break; // match trait masks against what they can match exclusively. // all correct value parses will come out of this list, so doing this as a switch is likely to // be a better friend to the optimizer on the success path (failure path can be slow but that // doesn't matter much). switch (unwrap_enum(traits)) { //=================== binary integers // 0b10 case bzero_msk | has_b: val = new value{ parse_integer<2>() }; break; //=================== octal integers // 0o10 case bzero_msk | has_o: val = new value{ parse_integer<8>() }; break; //=================== decimal integers // 00 // 10 // +10 // -10 case bzero_msk: [[fallthrough]]; case bdigit_msk: [[fallthrough]]; case begins_sign | has_digits | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_plus: val = new value{ parse_integer<10>() }; break; //=================== hexadecimal integers // 0x10 case bzero_msk | has_x: val = new value{ parse_integer<16>() }; break; //=================== decimal floats // 0e1 // 0e-1 // 0e+1 // 0.0 // 0.0e1 // 0.0e-1 // 0.0e+1 case bzero_msk | has_e: [[fallthrough]]; case bzero_msk | has_e | has_minus: [[fallthrough]]; case bzero_msk | has_e | has_plus: [[fallthrough]]; case bzero_msk | has_dot: [[fallthrough]]; case bzero_msk | has_dot | has_e: [[fallthrough]]; case bzero_msk | has_dot | has_e | has_minus: [[fallthrough]]; case bzero_msk | has_dot | has_e | has_plus: [[fallthrough]]; // 1e1 // 1e-1 // 1e+1 // 1.0 // 1.0e1 // 1.0e-1 // 1.0e+1 case bdigit_msk | has_e: [[fallthrough]]; case bdigit_msk | has_e | has_minus: [[fallthrough]]; case bdigit_msk | has_e | has_plus: [[fallthrough]]; case bdigit_msk | has_dot: [[fallthrough]]; case bdigit_msk | has_dot | has_e: [[fallthrough]]; case bdigit_msk | has_dot | has_e | has_minus: [[fallthrough]]; case bdigit_msk | has_dot | has_e | has_plus: [[fallthrough]]; // +1e1 // +1.0 // +1.0e1 // +1.0e+1 // +1.0e-1 // -1.0e+1 case begins_sign | has_digits | has_e | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_e | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_e | signs_msk: [[fallthrough]]; // -1e1 // -1e+1 // +1e-1 // -1.0 // -1.0e1 // -1.0e-1 case begins_sign | has_digits | has_e | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_e | signs_msk: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_dot | has_e | has_minus: val = new value{ parse_float() }; break; //=================== hexadecimal floats // 0x10p0 // 0x10p-0 // 0x10p+0 case bzero_msk | has_x | has_p: [[fallthrough]]; case bzero_msk | has_x | has_p | has_minus: [[fallthrough]]; case bzero_msk | has_x | has_p | has_plus: [[fallthrough]]; // -0x10p0 // -0x10p-0 // +0x10p0 // +0x10p+0 // -0x10p+0 // +0x10p-0 case begins_sign | has_digits | has_x | has_p | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_x | has_p | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_x | has_p | signs_msk: [[fallthrough]]; // 0x10.1p0 // 0x10.1p-0 // 0x10.1p+0 case bzero_msk | has_x | has_dot | has_p: [[fallthrough]]; case bzero_msk | has_x | has_dot | has_p | has_minus: [[fallthrough]]; case bzero_msk | has_x | has_dot | has_p | has_plus: [[fallthrough]]; // -0x10.1p0 // -0x10.1p-0 // +0x10.1p0 // +0x10.1p+0 // -0x10.1p+0 // +0x10.1p-0 case begins_sign | has_digits | has_x | has_dot | has_p | has_minus: [[fallthrough]]; case begins_sign | has_digits | has_x | has_dot | has_p | has_plus: [[fallthrough]]; case begins_sign | has_digits | has_x | has_dot | has_p | signs_msk: val = new value{ parse_hex_float() }; break; //=================== times // HH:MM // HH:MM:SS // HH:MM:SS.FFFFFF case bzero_msk | has_colon: [[fallthrough]]; case bzero_msk | has_colon | has_dot: [[fallthrough]]; case bdigit_msk | has_colon: [[fallthrough]]; case bdigit_msk | has_colon | has_dot: val = new value{ parse_time() }; break; //=================== local dates // YYYY-MM-DD case bzero_msk | has_minus: [[fallthrough]]; case bdigit_msk | has_minus: val = new value{ parse_date() }; break; //=================== date-times // YYYY-MM-DDTHH:MM // YYYY-MM-DDTHH:MM-HH:MM // YYYY-MM-DDTHH:MM+HH:MM // YYYY-MM-DD HH:MM // YYYY-MM-DD HH:MM-HH:MM // YYYY-MM-DD HH:MM+HH:MM // YYYY-MM-DDTHH:MM:SS // YYYY-MM-DDTHH:MM:SS-HH:MM // YYYY-MM-DDTHH:MM:SS+HH:MM // YYYY-MM-DD HH:MM:SS // YYYY-MM-DD HH:MM:SS-HH:MM // YYYY-MM-DD HH:MM:SS+HH:MM case bzero_msk | has_minus | has_colon | has_t: [[fallthrough]]; case bzero_msk | signs_msk | has_colon | has_t: [[fallthrough]]; case bdigit_msk | has_minus | has_colon | has_t: [[fallthrough]]; case bdigit_msk | signs_msk | has_colon | has_t: [[fallthrough]]; // YYYY-MM-DDTHH:MM:SS.FFFFFF // YYYY-MM-DDTHH:MM:SS.FFFFFF-HH:MM // YYYY-MM-DDTHH:MM:SS.FFFFFF+HH:MM // YYYY-MM-DD HH:MM:SS.FFFFFF // YYYY-MM-DD HH:MM:SS.FFFFFF-HH:MM // YYYY-MM-DD HH:MM:SS.FFFFFF+HH:MM case bzero_msk | has_minus | has_colon | has_dot | has_t: [[fallthrough]]; case bzero_msk | signs_msk | has_colon | has_dot | has_t: [[fallthrough]]; case bdigit_msk | has_minus | has_colon | has_dot | has_t: [[fallthrough]]; case bdigit_msk | signs_msk | has_colon | has_dot | has_t: [[fallthrough]]; // YYYY-MM-DDTHH:MMZ // YYYY-MM-DD HH:MMZ // YYYY-MM-DDTHH:MM:SSZ // YYYY-MM-DD HH:MM:SSZ // YYYY-MM-DDTHH:MM:SS.FFFFFFZ // YYYY-MM-DD HH:MM:SS.FFFFFFZ case bzero_msk | has_minus | has_colon | has_z | has_t: [[fallthrough]]; case bzero_msk | has_minus | has_colon | has_dot | has_z | has_t: [[fallthrough]]; case bdigit_msk | has_minus | has_colon | has_z | has_t: [[fallthrough]]; case bdigit_msk | has_minus | has_colon | has_dot | has_z | has_t: val = new value{ parse_date_time() }; break; } #undef signs_msk #undef bzero_msk #undef bdigit_msk } while (false); if (!val) { set_error_at(begin_pos, "could not determine value type"sv); return_after_error({}); } #if !TOML_LANG_AT_LEAST(1, 0, 0) // toml/issues/665 (heterogeneous arrays) { if (auto arr = val->as_array(); arr && !arr->is_homogeneous()) { delete arr; set_error_at( begin_pos, "arrays cannot contain values of different types before TOML 1.0.0"sv ); return_after_error({}); } } #endif val->source_ = { begin_pos, current_position(1), reader.source_path() }; return val; } [[nodiscard]] parsed_key parse_key() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_bare_key_character(*cp) || is_string_delimiter(*cp)); push_parse_scope("key"sv); parsed_key key; recording_whitespace = false; while (!is_error()) { #if TOML_LANG_UNRELEASED // toml/issues/687 (unicode bare keys) if (is_unicode_combining_mark(*cp)) set_error_and_return_default("bare keys may not begin with unicode combining marks"sv); else #endif // bare_key_segment if (is_bare_key_character(*cp)) key.segments.emplace_back(parse_bare_key_segment()); // "quoted key segment" else if (is_string_delimiter(*cp)) { const auto begin_pos = cp->position; recording_whitespace = true; auto str = parse_string(); recording_whitespace = false; return_if_error({}); if (str.was_multi_line) { set_error_at( begin_pos, "multi-line strings are prohibited in "sv, key.segments.empty() ? ""sv : "dotted "sv, "keys"sv ); return_after_error({}); } else key.segments.emplace_back(std::move(str.value)); } // ??? else set_error_and_return_default( "expected bare key starting character or string delimiter, saw '"sv, to_sv(*cp), "'"sv ); // whitespace following the key segment consume_leading_whitespace(); // eof or no more key to come if (is_eof() || *cp != U'.') break; // was a dotted key, so go around again to consume the next segment advance_and_return_if_error_or_eof({}); consume_leading_whitespace(); set_error_and_return_if_eof({}); } return_if_error({}); return key; } [[nodiscard]] parsed_key_value_pair parse_key_value_pair() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(is_string_delimiter(*cp) || is_bare_key_character(*cp)); push_parse_scope("key-value pair"sv); // get the key start_recording(); auto key = parse_key(); stop_recording(1_sz); // skip past any whitespace that followed the key consume_leading_whitespace(); set_error_and_return_if_eof({}); // '=' if (*cp != U'=') set_error_and_return_default("expected '=', saw '"sv, to_sv(*cp), "'"sv); advance_and_return_if_error_or_eof({}); // skip past any whitespace that followed the '=' consume_leading_whitespace(); return_if_error({}); set_error_and_return_if_eof({}); // get the value if (is_value_terminator(*cp)) set_error_and_return_default("expected value, saw '"sv, to_sv(*cp), "'"sv); return { std::move(key), parse_value() }; } [[nodiscard]] toml::table* parse_table_header() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'['); push_parse_scope("table header"sv); const auto header_begin_pos = cp->position; source_position header_end_pos; parsed_key key; bool is_arr = false; //parse header { // skip first '[' advance_and_return_if_error_or_eof({}); // skip past any whitespace that followed the '[' const bool had_leading_whitespace = consume_leading_whitespace(); set_error_and_return_if_eof({}); // skip second '[' (if present) if (*cp == U'[') { if (had_leading_whitespace) set_error_and_return_default( "[[array-of-table]] brackets must be contiguous (i.e. [ [ this ] ] is prohibited)"sv ); is_arr = true; advance_and_return_if_error_or_eof({}); // skip past any whitespace that followed the '[' consume_leading_whitespace(); set_error_and_return_if_eof({}); } // check for a premature closing ']' if (*cp == U']') set_error_and_return_default("tables with blank bare keys are explicitly prohibited"sv); // get the actual key start_recording(); key = parse_key(); stop_recording(1_sz); return_if_error({}); // skip past any whitespace that followed the key consume_leading_whitespace(); return_if_error({}); set_error_and_return_if_eof({}); // consume the closing ']' if (*cp != U']') set_error_and_return_default("expected ']', saw '"sv, to_sv(*cp), "'"sv); if (is_arr) { advance_and_return_if_error_or_eof({}); if (*cp != U']') set_error_and_return_default("expected ']', saw '"sv, to_sv(*cp), "'"sv); } advance_and_return_if_error({}); header_end_pos = current_position(1); // handle the rest of the line after the header consume_leading_whitespace(); if (!is_eof() && !consume_comment() && !consume_line_break()) set_error_and_return_default("expected a comment or whitespace, saw '"sv, to_sv(*cp), "'"sv); } TOML_ASSERT(!key.segments.empty()); // check if each parent is a table/table array, or can be created implicitly as a table. auto parent = &root; for (size_t i = 0; i < key.segments.size() - 1_sz; i++) { auto child = parent->get(key.segments[i]); if (!child) { child = parent->map.emplace( key.segments[i], new toml::table{} ).first->second.get(); implicit_tables.push_back(&child->ref_cast<table>()); child->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; parent = &child->ref_cast<table>(); } else if (child->is_table()) { parent = &child->ref_cast<table>(); } else if (child->is_array() && find(table_arrays, &child->ref_cast<array>())) { // table arrays are a special case; // the spec dictates we select the most recently declared element in the array. TOML_ASSERT(!child->ref_cast<array>().elements.empty()); TOML_ASSERT(child->ref_cast<array>().elements.back()->is_table()); parent = &child->ref_cast<array>().elements.back()->ref_cast<table>(); } else { if (!is_arr && child->type() == node_type::table) set_error_and_return_default( "cannot redefine existing table '"sv, to_sv(recording_buffer), "'"sv ); else set_error_and_return_default( "cannot redefine existing "sv, to_sv(child->type()), " '"sv, to_sv(recording_buffer), "' as "sv, is_arr ? "array-of-tables"sv : "table"sv ); } } // check the last parent table for a node matching the last key. // if there was no matching node, then sweet; // we can freely instantiate a new table/table array. auto matching_node = parent->get(key.segments.back()); if (!matching_node) { // if it's an array we need to make the array and it's first table element, // set the starting regions, and return the table element if (is_arr) { auto tab_arr = &parent->map.emplace( key.segments.back(), new toml::array{} ).first->second->ref_cast<array>(); table_arrays.push_back(tab_arr); tab_arr->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; tab_arr->elements.emplace_back(new toml::table{}); tab_arr->elements.back()->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; return &tab_arr->elements.back()->ref_cast<table>(); } //otherwise we're just making a table else { auto tab = &parent->map.emplace( key.segments.back(), new toml::table{}) .first->second->ref_cast<table>(); tab->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; return tab; } } // if there was already a matching node some sanity checking is necessary; // this is ok if we're making an array and the existing element is already an array (new element) // or if we're making a table and the existing element is an implicitly-created table (promote it), // otherwise this is a redefinition error. else { if (is_arr && matching_node->is_array() && find(table_arrays, &matching_node->ref_cast<array>())) { auto tab_arr = &matching_node->ref_cast<array>(); tab_arr->elements.emplace_back(new toml::table{}); tab_arr->elements.back()->source_ = { header_begin_pos, header_end_pos, reader.source_path() }; return &tab_arr->elements.back()->ref_cast<table>(); } else if (!is_arr && matching_node->is_table() && !implicit_tables.empty()) { auto tbl = &matching_node->ref_cast<table>(); if (auto found = find(implicit_tables, tbl)) { implicit_tables.erase(implicit_tables.cbegin() + (found - implicit_tables.data())); tbl->source_.begin = header_begin_pos; tbl->source_.end = header_end_pos; return tbl; } } //if we get here it's a redefinition error. if (!is_arr && matching_node->type() == node_type::table) set_error_and_return_default("cannot redefine existing table '"sv, to_sv(recording_buffer), "'"sv); else set_error_and_return_default( "cannot redefine existing "sv, to_sv(matching_node->type()), " '"sv, to_sv(recording_buffer), "' as "sv, is_arr ? "array-of-tables"sv : "table"sv ); } } void parse_key_value_pair_and_insert(toml::table* tab) TOML_MAY_THROW { return_if_error(); assert_not_eof(); push_parse_scope("key-value pair"sv); auto kvp = parse_key_value_pair(); return_if_error(); TOML_ASSERT(kvp.key.segments.size() >= 1_sz); if (kvp.key.segments.size() > 1_sz) { for (size_t i = 0; i < kvp.key.segments.size() - 1_sz; i++) { auto child = tab->get(kvp.key.segments[i]); if (!child) { child = tab->map.emplace( std::move(kvp.key.segments[i]), new toml::table{} ).first->second.get(); dotted_key_tables.push_back(&child->ref_cast<table>()); dotted_key_tables.back()->inline_ = true; child->source_ = kvp.value->source_; } else if (!child->is_table() || !find(dotted_key_tables, &child->ref_cast<table>())) set_error("cannot redefine existing "sv, to_sv(child->type()), " as dotted key-value pair"sv); else child->source_.end = kvp.value->source_.end; return_if_error(); tab = &child->ref_cast<table>(); } } if (auto conflicting_node = tab->get(kvp.key.segments.back())) { if (conflicting_node->type() == kvp.value->type()) set_error( "cannot redefine existing "sv, to_sv(conflicting_node->type()), " '"sv, to_sv(recording_buffer), "'"sv ); else set_error( "cannot redefine existing "sv, to_sv(conflicting_node->type()), " '"sv, to_sv(recording_buffer), "' as "sv, to_sv(kvp.value->type()) ); } return_if_error(); tab->map.emplace( std::move(kvp.key.segments.back()), std::unique_ptr<node>{ kvp.value } ); } void parse_document() TOML_MAY_THROW { assert_not_error(); assert_not_eof(); push_parse_scope("root table"sv); table* current_table = &root; do { return_if_error(); // leading whitespace, line endings, comments if (consume_leading_whitespace() || consume_line_break() || consume_comment()) continue; // [tables] // [[table array]] else if (*cp == U'[') current_table = parse_table_header(); // bare_keys // dotted.keys // "quoted keys" else if (is_bare_key_character(*cp) || is_string_delimiter(*cp)) { push_parse_scope("key-value pair"sv); parse_key_value_pair_and_insert(current_table); // handle the rest of the line after the kvp // (this is not done in parse_key_value_pair() because that is also used for inline tables) consume_leading_whitespace(); return_if_error(); if (!is_eof() && !consume_comment() && !consume_line_break()) set_error("expected a comment or whitespace, saw '"sv, to_sv(*cp), "'"sv); } else // ?? set_error("expected keys, tables, whitespace or comments, saw '"sv, to_sv(*cp), "'"sv); } while (!is_eof()); auto eof_pos = current_position(1); root.source_.end = eof_pos; if (current_table && current_table != &root && current_table->source_.end <= current_table->source_.begin) current_table->source_.end = eof_pos; } static void update_region_ends(node& nde) noexcept { const auto type = nde.type(); if (type > node_type::array) return; if (type == node_type::table) { auto& tbl = nde.ref_cast<table>(); if (tbl.inline_) //inline tables (and all their inline descendants) are already correctly terminated return; auto end = nde.source_.end; for (auto& [k, v] : tbl.map) { (void)k; update_region_ends(*v); if (end < v->source_.end) end = v->source_.end; } } else //arrays { auto& arr = nde.ref_cast<array>(); auto end = nde.source_.end; for (auto& v : arr.elements) { update_region_ends(*v); if (end < v->source_.end) end = v->source_.end; } nde.source_.end = end; } } public: parser(utf8_reader_interface&& reader_) TOML_MAY_THROW : reader{ reader_ } { root.source_ = { prev_pos, prev_pos, reader.source_path() }; if (!reader.peek_eof()) { cp = reader.read_next(); #if !TOML_EXCEPTIONS if (reader.error()) { err = std::move(reader.error()); return; } #endif if (cp) parse_document(); } update_region_ends(root); } TOML_PUSH_WARNINGS TOML_DISABLE_INIT_WARNINGS [[nodiscard]] operator parse_result() && noexcept { #if TOML_EXCEPTIONS return { std::move(root) }; #else if (err) return parse_result{ *std::move(err) }; else return parse_result{ std::move(root) }; #endif } TOML_POP_WARNINGS }; TOML_EXTERNAL_LINKAGE toml::array* parser::parse_array() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'['); push_parse_scope("array"sv); // skip opening '[' advance_and_return_if_error_or_eof({}); auto arr = new array{}; auto& vals = arr->elements; enum parse_elem : int { none, comma, val }; parse_elem prev = none; while (!is_error()) { while (consume_leading_whitespace() || consume_line_break() || consume_comment()) continue; set_error_and_return_if_eof({}); // commas - only legal after a value if (*cp == U',') { if (prev == val) { prev = comma; advance_and_return_if_error_or_eof({}); continue; } set_error_and_return_default("expected value or closing ']', saw comma"sv); } // closing ']' else if (*cp == U']') { advance_and_return_if_error({}); break; } // must be a value else { if (prev == val) { set_error_and_return_default("expected comma or closing ']', saw '"sv, to_sv(*cp), "'"sv); continue; } prev = val; vals.emplace_back(parse_value()); } } return_if_error({}); return arr; } TOML_EXTERNAL_LINKAGE toml::table* parser::parse_inline_table() TOML_MAY_THROW { return_if_error({}); assert_not_eof(); assert_or_assume(*cp == U'{'); push_parse_scope("inline table"sv); // skip opening '{' advance_and_return_if_error_or_eof({}); auto tab = new table{}; tab->inline_ = true; enum parse_elem : int { none, comma, kvp }; parse_elem prev = none; while (!is_error()) { if constexpr (TOML_LANG_UNRELEASED) // toml/issues/516 (newlines/trailing commas in inline tables) { while (consume_leading_whitespace() || consume_line_break() || consume_comment()) continue; } else { while (consume_leading_whitespace()) continue; } set_error_and_return_if_eof({}); // commas - only legal after a key-value pair if (*cp == U',') { if (prev == kvp) { prev = comma; advance_and_return_if_error_or_eof({}); } else set_error_and_return_default("expected key-value pair or closing '}', saw comma"sv); } // closing '}' else if (*cp == U'}') { if constexpr (!TOML_LANG_UNRELEASED) // toml/issues/516 (newlines/trailing commas in inline tables) { if (prev == comma) { set_error_and_return_default("expected key-value pair, saw closing '}' (dangling comma)"sv); continue; } } advance_and_return_if_error({}); break; } // key-value pair else if (is_string_delimiter(*cp) || is_bare_key_character(*cp)) { if (prev == kvp) set_error_and_return_default("expected comma or closing '}', saw '"sv, to_sv(*cp), "'"sv); else { prev = kvp; parse_key_value_pair_and_insert(tab); } } else set_error_and_return_default("expected key or closing '}', saw '"sv, to_sv(*cp), "'"sv); } return_if_error({}); return tab; } TOML_API TOML_EXTERNAL_LINKAGE parse_result do_parse(utf8_reader_interface&& reader) TOML_MAY_THROW { return impl::parser{ std::move(reader) }; } TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS #undef push_parse_scope_2 #undef push_parse_scope_1 #undef push_parse_scope #undef TOML_RETURNS_BY_THROWING #undef is_eof #undef assert_not_eof #undef return_if_eof #undef is_error #undef return_after_error #undef assert_not_error #undef return_if_error #undef return_if_error_or_eof #undef set_error_and_return #undef set_error_and_return_default #undef set_error_and_return_if_eof #undef advance_and_return_if_error #undef advance_and_return_if_error_or_eof #undef assert_or_assume } TOML_IMPL_NAMESPACE_END TOML_NAMESPACE_START { TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::string_view doc, std::string_view source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, source_path }); } TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::string_view doc, std::string&& source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, std::move(source_path) }); } #if TOML_WINDOWS_COMPAT TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::string_view doc, std::wstring_view source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, impl::narrow(source_path) }); } #endif // TOML_WINDOWS_COMPAT #ifdef __cpp_lib_char8_t TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::u8string_view doc, std::string_view source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, source_path }); } TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::u8string_view doc, std::string&& source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, std::move(source_path) }); } #if TOML_WINDOWS_COMPAT TOML_API TOML_EXTERNAL_LINKAGE parse_result parse(std::u8string_view doc, std::wstring_view source_path) TOML_MAY_THROW { return impl::do_parse(impl::utf8_reader{ doc, impl::narrow(source_path) }); } #endif // TOML_WINDOWS_COMPAT #endif // __cpp_lib_char8_t inline namespace literals { TOML_API TOML_EXTERNAL_LINKAGE parse_result operator"" _toml(const char* str, size_t len) TOML_MAY_THROW { return parse(std::string_view{ str, len }); } #ifdef __cpp_lib_char8_t TOML_API TOML_EXTERNAL_LINKAGE parse_result operator"" _toml(const char8_t* str, size_t len) TOML_MAY_THROW { return parse(std::u8string_view{ str, len }); } #endif // __cpp_lib_char8_t } TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS } TOML_NAMESPACE_END TOML_POP_WARNINGS // TOML_DISABLE_SWITCH_WARNINGS #endif //---------------------------------------------------------- ↑ toml_parser.hpp -------------------------------- #endif // TOML_PARSER #if !TOML_HEADER_ONLY #if 1 //------------------------------------------------------------------------------- ↓ toml_instantiations.hpp --- TOML_DISABLE_WARNINGS #include <ostream> #include <istream> #include <fstream> TOML_ENABLE_WARNINGS #if TOML_PARSER #endif // internal implementation namespace TOML_IMPL_NAMESPACE_START { // formatters template class TOML_API formatter<char>; // print to stream machinery template TOML_API void print_floating_point_to_stream(double, std::ostream&, bool); } TOML_IMPL_NAMESPACE_END // public namespace TOML_NAMESPACE_START { // value<> template class TOML_API value<std::string>; template class TOML_API value<int64_t>; template class TOML_API value<double>; template class TOML_API value<bool>; template class TOML_API value<date>; template class TOML_API value<time>; template class TOML_API value<date_time>; // node_view template class TOML_API node_view<node>; template class TOML_API node_view<const node>; // formatters template class TOML_API default_formatter<char>; template class TOML_API json_formatter<char>; // various ostream operators template TOML_API std::ostream& operator << (std::ostream&, const source_position&); template TOML_API std::ostream& operator << (std::ostream&, const source_region&); template TOML_API std::ostream& operator << (std::ostream&, const date&); template TOML_API std::ostream& operator << (std::ostream&, const time&); template TOML_API std::ostream& operator << (std::ostream&, const time_offset&); template TOML_API std::ostream& operator << (std::ostream&, const date_time&); template TOML_API std::ostream& operator << (std::ostream&, const value<std::string>&); template TOML_API std::ostream& operator << (std::ostream&, const value<int64_t>&); template TOML_API std::ostream& operator << (std::ostream&, const value<double>&); template TOML_API std::ostream& operator << (std::ostream&, const value<bool>&); template TOML_API std::ostream& operator << (std::ostream&, const value<toml::date>&); template TOML_API std::ostream& operator << (std::ostream&, const value<toml::time>&); template TOML_API std::ostream& operator << (std::ostream&, const value<toml::date_time>&); template TOML_API std::ostream& operator << (std::ostream&, default_formatter<char>&); template TOML_API std::ostream& operator << (std::ostream&, default_formatter<char>&&); template TOML_API std::ostream& operator << (std::ostream&, json_formatter<char>&); template TOML_API std::ostream& operator << (std::ostream&, json_formatter<char>&&); template TOML_API std::ostream& operator << (std::ostream&, const table&); template TOML_API std::ostream& operator << (std::ostream&, const array&); template TOML_API std::ostream& operator << (std::ostream&, const node_view<node>&); template TOML_API std::ostream& operator << (std::ostream&, const node_view<const node>&); template TOML_API std::ostream& operator << (std::ostream&, node_type); // node::value, node_view:::value etc #define TOML_INSTANTIATE(name, T) \ template TOML_API optional<T> node::name<T>() const noexcept; \ template TOML_API optional<T> node_view<node>::name<T>() const noexcept; \ template TOML_API optional<T> node_view<const node>::name<T>() const noexcept TOML_INSTANTIATE(value_exact, std::string_view); TOML_INSTANTIATE(value_exact, std::string); TOML_INSTANTIATE(value_exact, const char*); TOML_INSTANTIATE(value_exact, int64_t); TOML_INSTANTIATE(value_exact, double); TOML_INSTANTIATE(value_exact, date); TOML_INSTANTIATE(value_exact, time); TOML_INSTANTIATE(value_exact, date_time); TOML_INSTANTIATE(value_exact, bool); TOML_INSTANTIATE(value, std::string_view); TOML_INSTANTIATE(value, std::string); TOML_INSTANTIATE(value, const char*); TOML_INSTANTIATE(value, signed char); TOML_INSTANTIATE(value, signed short); TOML_INSTANTIATE(value, signed int); TOML_INSTANTIATE(value, signed long); TOML_INSTANTIATE(value, signed long long); TOML_INSTANTIATE(value, unsigned char); TOML_INSTANTIATE(value, unsigned short); TOML_INSTANTIATE(value, unsigned int); TOML_INSTANTIATE(value, unsigned long); TOML_INSTANTIATE(value, unsigned long long); TOML_INSTANTIATE(value, double); TOML_INSTANTIATE(value, float); TOML_INSTANTIATE(value, date); TOML_INSTANTIATE(value, time); TOML_INSTANTIATE(value, date_time); TOML_INSTANTIATE(value, bool); #ifdef __cpp_lib_char8_t TOML_INSTANTIATE(value_exact, std::u8string_view); TOML_INSTANTIATE(value_exact, std::u8string); TOML_INSTANTIATE(value_exact, const char8_t*); TOML_INSTANTIATE(value, std::u8string_view); TOML_INSTANTIATE(value, std::u8string); TOML_INSTANTIATE(value, const char8_t*); #endif #if TOML_WINDOWS_COMPAT TOML_INSTANTIATE(value_exact, std::wstring); TOML_INSTANTIATE(value, std::wstring); #endif #undef TOML_INSTANTIATE // parser instantiations #if TOML_PARSER // parse error ostream template TOML_API std::ostream& operator << (std::ostream&, const parse_error&); // parse() and parse_file() TOML_ABI_NAMESPACE_BOOL(TOML_EXCEPTIONS, ex, noex) template TOML_API parse_result parse(std::istream&, std::string_view) TOML_MAY_THROW; template TOML_API parse_result parse(std::istream&, std::string&&) TOML_MAY_THROW; template TOML_API parse_result parse_file(std::string_view) TOML_MAY_THROW; #ifdef __cpp_lib_char8_t template TOML_API parse_result parse_file(std::u8string_view) TOML_MAY_THROW; #endif #if TOML_WINDOWS_COMPAT template TOML_API parse_result parse_file(std::wstring_view) TOML_MAY_THROW; #endif TOML_ABI_NAMESPACE_END // TOML_EXCEPTIONS #endif // TOML_PARSER } TOML_NAMESPACE_END #endif //------------------------------------------------------------------------------- ↑ toml_instantiations.hpp --- #endif // !TOML_HEADER_ONLY #endif // TOML_IMPLEMENTATION TOML_POP_WARNINGS // TOML_DISABLE_SPAM_WARNINGS // macro hygiene #if TOML_UNDEF_MACROS #undef TOML_ABI_NAMESPACES #undef TOML_ABI_NAMESPACE_BOOL #undef TOML_ABI_NAMESPACE_END #undef TOML_ABI_NAMESPACE_START #undef TOML_ALWAYS_INLINE #undef TOML_ANON_NAMESPACE #undef TOML_ANON_NAMESPACE_END #undef TOML_ANON_NAMESPACE_START #undef TOML_ARM #undef TOML_ASSERT #undef TOML_ASSUME #undef TOML_ASYMMETRICAL_EQUALITY_OPS #undef TOML_ATTR #undef TOML_CLANG #undef TOML_COMPILER_EXCEPTIONS #undef TOML_CONCAT #undef TOML_CONCAT_1 #undef TOML_CONSTEVAL #undef TOML_CPP #undef TOML_DISABLE_ARITHMETIC_WARNINGS #undef TOML_DISABLE_INIT_WARNINGS #undef TOML_DISABLE_SPAM_WARNINGS #undef TOML_DISABLE_SHADOW_WARNINGS #undef TOML_DISABLE_SUGGEST_WARNINGS #undef TOML_DISABLE_SWITCH_WARNINGS #undef TOML_DISABLE_WARNINGS #undef TOML_ENABLE_WARNINGS #undef TOML_EMPTY_BASES #undef TOML_EVAL_BOOL_0 #undef TOML_EVAL_BOOL_1 #undef TOML_EXTERNAL_LINKAGE #undef TOML_FLOAT128 #undef TOML_FLOAT16 #undef TOML_FLOAT_CHARCONV #undef TOML_FP16 #undef TOML_GCC #undef TOML_HAS_CUSTOM_OPTIONAL_TYPE #undef TOML_HAS_INCLUDE #undef TOML_ICC #undef TOML_ICC_CL #undef TOML_IMPLEMENTATION #undef TOML_IMPL_NAMESPACE_END #undef TOML_IMPL_NAMESPACE_START #undef TOML_INT128 #undef TOML_INTELLISENSE #undef TOML_INTERFACE #undef TOML_INTERNAL_LINKAGE #undef TOML_INT_CHARCONV #undef TOML_LANG_AT_LEAST #undef TOML_LANG_EFFECTIVE_VERSION #undef TOML_LANG_HIGHER_THAN #undef TOML_LANG_UNRELEASED #undef TOML_LAUNDER #undef TOML_LIKELY #undef TOML_MAKE_VERSION #undef TOML_MAY_THROW #undef TOML_MSVC #undef TOML_NAMESPACE #undef TOML_NAMESPACE_END #undef TOML_NAMESPACE_START #undef TOML_NEVER_INLINE #undef TOML_NODISCARD_CTOR #undef TOML_NO_DEFAULT_CASE #undef TOML_PARSER_TYPENAME #undef TOML_POP_WARNINGS #undef TOML_PUSH_WARNINGS #undef TOML_RELOPS_REORDERING #undef TOML_SA_LIST_BEG #undef TOML_SA_LIST_END #undef TOML_SA_LIST_NEW #undef TOML_SA_LIST_NXT #undef TOML_SA_LIST_SEP #undef TOML_SA_NATIVE_VALUE_TYPE_LIST #undef TOML_SA_NEWLINE #undef TOML_SA_NODE_TYPE_LIST #undef TOML_SA_UNWRAPPED_NODE_TYPE_LIST #undef TOML_SA_VALUE_EXACT_FUNC_MESSAGE #undef TOML_SA_VALUE_FUNC_MESSAGE #undef TOML_SA_VALUE_MESSAGE_CONST_CHAR8 #undef TOML_SA_VALUE_MESSAGE_U8STRING_VIEW #undef TOML_SA_VALUE_MESSAGE_WSTRING #undef TOML_SIMPLE_STATIC_ASSERT_MESSAGES #undef TOML_TRIVIAL_ABI #undef TOML_UINT128 #undef TOML_UNLIKELY #undef TOML_UNREACHABLE #undef TOML_USING_ANON_NAMESPACE #endif #endif // INCLUDE_TOMLPLUSPLUS_H
// Copyright (c) 2011-2014 The Bitcoin Core developers // Copyright (c) 2017-2020 The CREDD developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util/system.h" #include "clientversion.h" #include "primitives/transaction.h" #include "sync.h" #include "utilstrencodings.h" #include "utilmoneystr.h" #include "test/test_creddit.h" #include <stdint.h> #include <vector> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(util_criticalsection) { RecursiveMutex cs; do { LOCK(cs); break; BOOST_ERROR("break was swallowed!"); } while(0); do { TRY_LOCK(cs, lockTest); if (lockTest) break; BOOST_ERROR("break was swallowed!"); } while(0); } static const unsigned char ParseHex_expected[65] = { 0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, 0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, 0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, 0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, 0x5f }; BOOST_AUTO_TEST_CASE(util_ParseHex) { std::vector<unsigned char> result; std::vector<unsigned char> expected(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)); // Basic test vector result = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end()); // Spaces between bytes must be supported result = ParseHex("12 34 56 78"); BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78); // Stop parsing at invalid value result = ParseHex("1234 invalid 1234"); BOOST_CHECK(result.size() == 2 && result[0] == 0x12 && result[1] == 0x34); } BOOST_AUTO_TEST_CASE(util_HexStr) { BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)), "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + 5, true), "04 67 8a fd b0"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected, true), ""); std::vector<unsigned char> ParseHex_vec(ParseHex_expected, ParseHex_expected + 5); BOOST_CHECK_EQUAL( HexStr(ParseHex_vec, true), "04 67 8a fd b0"); } BOOST_AUTO_TEST_CASE(util_FormatISO8601DateTime) { BOOST_CHECK_EQUAL(FormatISO8601DateTime(1317425777), "2011-09-30T23:36:17Z"); } BOOST_AUTO_TEST_CASE(util_FormatISO8601DateTimeForBackup) { BOOST_CHECK_EQUAL(FormatISO8601DateTimeForBackup(1586310600), ".20200408T0150Z"); } BOOST_AUTO_TEST_CASE(util_FormatISO8601Date) { BOOST_CHECK_EQUAL(FormatISO8601Date(1317425777), "2011-09-30"); } BOOST_AUTO_TEST_CASE(util_FormatISO8601Time) { BOOST_CHECK_EQUAL(FormatISO8601Time(1317425777), "23:36:17Z"); } struct TestArgsManager : public ArgsManager { TestArgsManager() { m_network_only_args.clear(); } std::map<std::string, std::vector<std::string> >& GetOverrideArgs() { return m_override_args; } std::map<std::string, std::vector<std::string> >& GetConfigArgs() { return m_config_args; } void ReadConfigString(const std::string str_config) { std::istringstream streamConfig(str_config); { LOCK(cs_args); m_config_args.clear(); } ReadConfigStream(streamConfig); } void SetNetworkOnlyArg(const std::string arg) { LOCK(cs_args); m_network_only_args.insert(arg); } }; BOOST_AUTO_TEST_CASE(util_ParseParameters) { TestArgsManager testArgs; const char *argv_test[] = {"-ignored", "-a", "-b", "-ccc=argument", "-ccc=multiple", "f", "-d=e"}; testArgs.ParseParameters(0, (char**)argv_test); BOOST_CHECK(testArgs.GetOverrideArgs().empty() && testArgs.GetConfigArgs().empty()); testArgs.ParseParameters(1, (char**)argv_test); BOOST_CHECK(testArgs.GetOverrideArgs().empty() && testArgs.GetConfigArgs().empty()); testArgs.ParseParameters(5, (char**)argv_test); // expectation: -ignored is ignored (program name argument), // -a, -b and -ccc end up in map, -d ignored because it is after // a non-option argument (non-GNU option parsing) BOOST_CHECK(testArgs.GetOverrideArgs().size() == 3 && testArgs.GetConfigArgs().empty()); BOOST_CHECK(testArgs.IsArgSet("-a") && testArgs.IsArgSet("-b") && testArgs.IsArgSet("-ccc") && !testArgs.IsArgSet("f") && !testArgs.IsArgSet("-d")); BOOST_CHECK(testArgs.GetOverrideArgs().count("-a") && testArgs.GetOverrideArgs().count("-b") && testArgs.GetOverrideArgs().count("-ccc") && !testArgs.GetOverrideArgs().count("f") && !testArgs.GetOverrideArgs().count("-d")); BOOST_CHECK(testArgs.GetOverrideArgs()["-a"].size() == 1); BOOST_CHECK(testArgs.GetOverrideArgs()["-a"].front() == ""); BOOST_CHECK(testArgs.GetOverrideArgs()["-ccc"].size() == 2); BOOST_CHECK(testArgs.GetOverrideArgs()["-ccc"].front() == "argument"); BOOST_CHECK(testArgs.GetOverrideArgs()["-ccc"].back() == "multiple"); } BOOST_AUTO_TEST_CASE(util_GetBoolArg) { TestArgsManager testArgs; const char *argv_test[] = { "ignored", "-a", "-nob", "-c=0", "-d=1", "-e=false", "-f=true"}; testArgs.ParseParameters(7, (char**)argv_test); // Each letter should be set. for (char opt : "abcdef") BOOST_CHECK(testArgs.IsArgSet({'-', opt}) || !opt); // Nothing else should be in the map BOOST_CHECK(testArgs.GetOverrideArgs().size() == 6 && testArgs.GetConfigArgs().empty()); // The -no prefix should get stripped on the way in. BOOST_CHECK(!testArgs.IsArgSet("-nob")); // The -b option is flagged as negated, and nothing else is BOOST_CHECK(testArgs.IsArgNegated("-b")); BOOST_CHECK(!testArgs.IsArgNegated("-a")); // Check expected values. BOOST_CHECK(testArgs.GetBoolArg("-a", false) == true); BOOST_CHECK(testArgs.GetBoolArg("-b", true) == false); BOOST_CHECK(testArgs.GetBoolArg("-c", true) == false); BOOST_CHECK(testArgs.GetBoolArg("-d", false) == true); BOOST_CHECK(testArgs.GetBoolArg("-e", true) == false); BOOST_CHECK(testArgs.GetBoolArg("-f", true) == false); } BOOST_AUTO_TEST_CASE(util_GetBoolArgEdgeCases) { // Test some awful edge cases that hopefully no user will ever exercise. TestArgsManager testArgs; // Params test const char *argv_test[] = {"ignored", "-nofoo", "-foo", "-nobar=0"}; testArgs.ParseParameters(4, (char**)argv_test); // This was passed twice, second one overrides the negative setting. BOOST_CHECK(!testArgs.IsArgNegated("-foo")); BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == ""); // A double negative is a positive, and not marked as negated. BOOST_CHECK(!testArgs.IsArgNegated("-bar")); BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "1"); // Config test const char *conf_test = "nofoo=1\nfoo=1\nnobar=0\n"; testArgs.ParseParameters(1, (char**)argv_test); testArgs.ReadConfigString(conf_test); // This was passed twice, second one overrides the negative setting, // and the value. BOOST_CHECK(!testArgs.IsArgNegated("-foo")); BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "1"); // A double negative is a positive, and does not count as negated. BOOST_CHECK(!testArgs.IsArgNegated("-bar")); BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "1"); // Combined test const char *combo_test_args[] = {"ignored", "-nofoo", "-bar"}; const char *combo_test_conf = "foo=1\nnobar=1\n"; testArgs.ParseParameters(3, (char**)combo_test_args); testArgs.ReadConfigString(combo_test_conf); // Command line overrides, but doesn't erase old setting BOOST_CHECK(testArgs.IsArgNegated("-foo")); BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "0"); BOOST_CHECK(testArgs.GetArgs("-foo").size() == 0); // Command line overrides, but doesn't erase old setting BOOST_CHECK(!testArgs.IsArgNegated("-bar")); BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == ""); BOOST_CHECK(testArgs.GetArgs("-bar").size() == 1 && testArgs.GetArgs("-bar").front() == ""); } BOOST_AUTO_TEST_CASE(util_ReadConfigStream) { const char *str_config = "a=\n" "b=1\n" "ccc=argument\n" "ccc=multiple\n" "d=e\n" "nofff=1\n" "noggg=0\n" "h=1\n" "noh=1\n" "noi=1\n" "i=1\n" "sec1.ccc=extend1\n" "\n" "[sec1]\n" "ccc=extend2\n" "d=eee\n" "h=1\n" "[sec2]\n" "ccc=extend3\n" "iii=2\n"; TestArgsManager test_args; test_args.ReadConfigString(str_config); // expectation: a, b, ccc, d, fff, ggg, h, i end up in map // so do sec1.ccc, sec1.d, sec1.h, sec2.ccc, sec2.iii BOOST_CHECK(test_args.GetOverrideArgs().empty()); BOOST_CHECK(test_args.GetConfigArgs().size() == 13); BOOST_CHECK(test_args.GetConfigArgs().count("-a") && test_args.GetConfigArgs().count("-b") && test_args.GetConfigArgs().count("-ccc") && test_args.GetConfigArgs().count("-d") && test_args.GetConfigArgs().count("-fff") && test_args.GetConfigArgs().count("-ggg") && test_args.GetConfigArgs().count("-h") && test_args.GetConfigArgs().count("-i") ); BOOST_CHECK(test_args.GetConfigArgs().count("-sec1.ccc") && test_args.GetConfigArgs().count("-sec1.h") && test_args.GetConfigArgs().count("-sec2.ccc") && test_args.GetConfigArgs().count("-sec2.iii") ); BOOST_CHECK(test_args.IsArgSet("-a") && test_args.IsArgSet("-b") && test_args.IsArgSet("-ccc") && test_args.IsArgSet("-d") && test_args.IsArgSet("-fff") && test_args.IsArgSet("-ggg") && test_args.IsArgSet("-h") && test_args.IsArgSet("-i") && !test_args.IsArgSet("-zzz") && !test_args.IsArgSet("-iii") ); BOOST_CHECK(test_args.GetArg("-a", "xxx") == "" && test_args.GetArg("-b", "xxx") == "1" && test_args.GetArg("-ccc", "xxx") == "argument" && test_args.GetArg("-d", "xxx") == "e" && test_args.GetArg("-fff", "xxx") == "0" && test_args.GetArg("-ggg", "xxx") == "1" && test_args.GetArg("-h", "xxx") == "0" && test_args.GetArg("-i", "xxx") == "1" && test_args.GetArg("-zzz", "xxx") == "xxx" && test_args.GetArg("-iii", "xxx") == "xxx" ); for (bool def : {false, true}) { BOOST_CHECK(test_args.GetBoolArg("-a", def) && test_args.GetBoolArg("-b", def) && !test_args.GetBoolArg("-ccc", def) && !test_args.GetBoolArg("-d", def) && !test_args.GetBoolArg("-fff", def) && test_args.GetBoolArg("-ggg", def) && !test_args.GetBoolArg("-h", def) && test_args.GetBoolArg("-i", def) && test_args.GetBoolArg("-zzz", def) == def && test_args.GetBoolArg("-iii", def) == def ); } BOOST_CHECK(test_args.GetArgs("-a").size() == 1 && test_args.GetArgs("-a").front() == ""); BOOST_CHECK(test_args.GetArgs("-b").size() == 1 && test_args.GetArgs("-b").front() == "1"); BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2 && test_args.GetArgs("-ccc").front() == "argument" && test_args.GetArgs("-ccc").back() == "multiple"); BOOST_CHECK(test_args.GetArgs("-fff").size() == 0); BOOST_CHECK(test_args.GetArgs("-nofff").size() == 0); BOOST_CHECK(test_args.GetArgs("-ggg").size() == 1 && test_args.GetArgs("-ggg").front() == "1"); BOOST_CHECK(test_args.GetArgs("-noggg").size() == 0); BOOST_CHECK(test_args.GetArgs("-h").size() == 0); BOOST_CHECK(test_args.GetArgs("-noh").size() == 0); BOOST_CHECK(test_args.GetArgs("-i").size() == 1 && test_args.GetArgs("-i").front() == "1"); BOOST_CHECK(test_args.GetArgs("-noi").size() == 0); BOOST_CHECK(test_args.GetArgs("-zzz").size() == 0); BOOST_CHECK(!test_args.IsArgNegated("-a")); BOOST_CHECK(!test_args.IsArgNegated("-b")); BOOST_CHECK(!test_args.IsArgNegated("-ccc")); BOOST_CHECK(!test_args.IsArgNegated("-d")); BOOST_CHECK(test_args.IsArgNegated("-fff")); BOOST_CHECK(!test_args.IsArgNegated("-ggg")); BOOST_CHECK(test_args.IsArgNegated("-h")); // last setting takes precedence BOOST_CHECK(!test_args.IsArgNegated("-i")); // last setting takes precedence BOOST_CHECK(!test_args.IsArgNegated("-zzz")); // Test sections work test_args.SelectConfigNetwork("sec1"); // same as original BOOST_CHECK(test_args.GetArg("-a", "xxx") == "" && test_args.GetArg("-b", "xxx") == "1" && test_args.GetArg("-fff", "xxx") == "0" && test_args.GetArg("-ggg", "xxx") == "1" && test_args.GetArg("-zzz", "xxx") == "xxx" && test_args.GetArg("-iii", "xxx") == "xxx" ); // d is overridden BOOST_CHECK(test_args.GetArg("-d", "xxx") == "eee"); // section-specific setting BOOST_CHECK(test_args.GetArg("-h", "xxx") == "1"); // section takes priority for multiple values BOOST_CHECK(test_args.GetArg("-ccc", "xxx") == "extend1"); // check multiple values works const std::vector<std::string> sec1_ccc_expected = {"extend1","extend2","argument","multiple"}; const auto& sec1_ccc_res = test_args.GetArgs("-ccc"); BOOST_CHECK_EQUAL_COLLECTIONS(sec1_ccc_res.begin(), sec1_ccc_res.end(), sec1_ccc_expected.begin(), sec1_ccc_expected.end()); test_args.SelectConfigNetwork("sec2"); // same as original BOOST_CHECK(test_args.GetArg("-a", "xxx") == "" && test_args.GetArg("-b", "xxx") == "1" && test_args.GetArg("-d", "xxx") == "e" && test_args.GetArg("-fff", "xxx") == "0" && test_args.GetArg("-ggg", "xxx") == "1" && test_args.GetArg("-zzz", "xxx") == "xxx" && test_args.GetArg("-h", "xxx") == "0" ); // section-specific setting BOOST_CHECK(test_args.GetArg("-iii", "xxx") == "2"); // section takes priority for multiple values BOOST_CHECK(test_args.GetArg("-ccc", "xxx") == "extend3"); // check multiple values works const std::vector<std::string> sec2_ccc_expected = {"extend3","argument","multiple"}; const auto& sec2_ccc_res = test_args.GetArgs("-ccc"); BOOST_CHECK_EQUAL_COLLECTIONS(sec2_ccc_res.begin(), sec2_ccc_res.end(), sec2_ccc_expected.begin(), sec2_ccc_expected.end()); // Test section only options test_args.SetNetworkOnlyArg("-d"); test_args.SetNetworkOnlyArg("-ccc"); test_args.SetNetworkOnlyArg("-h"); test_args.SelectConfigNetwork(CBaseChainParams::MAIN); BOOST_CHECK(test_args.GetArg("-d", "xxx") == "e"); BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2); BOOST_CHECK(test_args.GetArg("-h", "xxx") == "0"); test_args.SelectConfigNetwork("sec1"); BOOST_CHECK(test_args.GetArg("-d", "xxx") == "eee"); BOOST_CHECK(test_args.GetArgs("-d").size() == 1); BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2); BOOST_CHECK(test_args.GetArg("-h", "xxx") == "1"); test_args.SelectConfigNetwork("sec2"); BOOST_CHECK(test_args.GetArg("-d", "xxx") == "xxx"); BOOST_CHECK(test_args.GetArgs("-d").size() == 0); BOOST_CHECK(test_args.GetArgs("-ccc").size() == 1); BOOST_CHECK(test_args.GetArg("-h", "xxx") == "0"); } BOOST_AUTO_TEST_CASE(util_GetArg) { TestArgsManager testArgs; testArgs.GetOverrideArgs().clear(); testArgs.GetOverrideArgs()["strtest1"] = {"string..."}; // strtest2 undefined on purpose testArgs.GetOverrideArgs()["inttest1"] = {"12345"}; testArgs.GetOverrideArgs()["inttest2"] = {"81985529216486895"}; // inttest3 undefined on purpose testArgs.GetOverrideArgs()["booltest1"] = {""}; // booltest2 undefined on purpose testArgs.GetOverrideArgs()["booltest3"] = {"0"}; testArgs.GetOverrideArgs()["booltest4"] = {"1"}; // priorities testArgs.GetOverrideArgs()["pritest1"] = {"a", "b"}; testArgs.GetConfigArgs()["pritest2"] = {"a", "b"}; testArgs.GetOverrideArgs()["pritest3"] = {"a"}; testArgs.GetConfigArgs()["pritest3"] = {"b"}; testArgs.GetOverrideArgs()["pritest4"] = {"a","b"}; testArgs.GetConfigArgs()["pritest4"] = {"c","d"}; BOOST_CHECK_EQUAL(testArgs.GetArg("strtest1", "default"), "string..."); BOOST_CHECK_EQUAL(testArgs.GetArg("strtest2", "default"), "default"); BOOST_CHECK_EQUAL(testArgs.GetArg("inttest1", -1), 12345); BOOST_CHECK_EQUAL(testArgs.GetArg("inttest2", -1), 81985529216486895LL); BOOST_CHECK_EQUAL(testArgs.GetArg("inttest3", -1), -1); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest1", false), true); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest2", false), false); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest3", false), false); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest4", false), true); BOOST_CHECK_EQUAL(testArgs.GetArg("pritest1", "default"), "b"); BOOST_CHECK_EQUAL(testArgs.GetArg("pritest2", "default"), "a"); BOOST_CHECK_EQUAL(testArgs.GetArg("pritest3", "default"), "a"); BOOST_CHECK_EQUAL(testArgs.GetArg("pritest4", "default"), "b"); } BOOST_AUTO_TEST_CASE(util_GetChainName) { TestArgsManager test_args; const char* argv_testnet[] = {"cmd", "-testnet"}; const char* argv_regtest[] = {"cmd", "-regtest"}; const char* argv_test_no_reg[] = {"cmd", "-testnet", "-noregtest"}; const char* argv_both[] = {"cmd", "-testnet", "-regtest"}; // equivalent to "-testnet" // regtest in testnet section is ignored const char* testnetconf = "testnet=1\nregtest=0\n[test]\nregtest=1"; test_args.ParseParameters(0, (char**)argv_testnet); BOOST_CHECK_EQUAL(test_args.GetChainName(), "main"); test_args.ParseParameters(2, (char**)argv_testnet); BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); test_args.ParseParameters(2, (char**)argv_regtest); BOOST_CHECK_EQUAL(test_args.GetChainName(), "regtest"); test_args.ParseParameters(3, (char**)argv_test_no_reg); BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); test_args.ParseParameters(3, (char**)argv_both); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); test_args.ParseParameters(0, (char**)argv_testnet); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); test_args.ParseParameters(2, (char**)argv_testnet); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); test_args.ParseParameters(2, (char**)argv_regtest); test_args.ReadConfigString(testnetconf); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); test_args.ParseParameters(3, (char**)argv_test_no_reg); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); test_args.ParseParameters(3, (char**)argv_both); test_args.ReadConfigString(testnetconf); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); // check setting the network to test (and thus making // [test] regtest=1 potentially relevent) doesn't break things test_args.SelectConfigNetwork("test"); test_args.ParseParameters(0, (char**)argv_testnet); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); test_args.ParseParameters(2, (char**)argv_testnet); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); test_args.ParseParameters(2, (char**)argv_regtest); test_args.ReadConfigString(testnetconf); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); test_args.ParseParameters(2, (char**)argv_test_no_reg); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), "test"); test_args.ParseParameters(3, (char**)argv_both); test_args.ReadConfigString(testnetconf); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); } BOOST_AUTO_TEST_CASE(util_FormatMoney) { BOOST_CHECK_EQUAL(FormatMoney(0, false), "0.00"); BOOST_CHECK_EQUAL(FormatMoney((COIN/10000)*123456789, false), "12345.6789"); BOOST_CHECK_EQUAL(FormatMoney(COIN, true), "+1.00"); BOOST_CHECK_EQUAL(FormatMoney(-COIN, false), "-1.00"); BOOST_CHECK_EQUAL(FormatMoney(-COIN, true), "-1.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000, false), "100000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000, false), "10000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000, false), "1000000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100000, false), "100000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10000, false), "10000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*1000, false), "1000.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*100, false), "100.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN*10, false), "10.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN, false), "1.00"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10, false), "0.10"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100, false), "0.01"); BOOST_CHECK_EQUAL(FormatMoney(COIN/1000, false), "0.001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10000, false), "0.0001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100000, false), "0.00001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/1000000, false), "0.000001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/10000000, false), "0.0000001"); BOOST_CHECK_EQUAL(FormatMoney(COIN/100000000, false), "0.00000001"); } BOOST_AUTO_TEST_CASE(util_ParseMoney) { CAmount ret = 0; BOOST_CHECK(ParseMoney("0.0", ret)); BOOST_CHECK_EQUAL(ret, 0); BOOST_CHECK(ParseMoney("12345.6789", ret)); BOOST_CHECK_EQUAL(ret, (COIN/10000)*123456789); BOOST_CHECK(ParseMoney("100000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100000000); BOOST_CHECK(ParseMoney("10000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10000000); BOOST_CHECK(ParseMoney("1000000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*1000000); BOOST_CHECK(ParseMoney("100000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100000); BOOST_CHECK(ParseMoney("10000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10000); BOOST_CHECK(ParseMoney("1000.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*1000); BOOST_CHECK(ParseMoney("100.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*100); BOOST_CHECK(ParseMoney("10.00", ret)); BOOST_CHECK_EQUAL(ret, COIN*10); BOOST_CHECK(ParseMoney("1.00", ret)); BOOST_CHECK_EQUAL(ret, COIN); BOOST_CHECK(ParseMoney("1", ret)); BOOST_CHECK_EQUAL(ret, COIN); BOOST_CHECK(ParseMoney("0.1", ret)); BOOST_CHECK_EQUAL(ret, COIN/10); BOOST_CHECK(ParseMoney("0.01", ret)); BOOST_CHECK_EQUAL(ret, COIN/100); BOOST_CHECK(ParseMoney("0.001", ret)); BOOST_CHECK_EQUAL(ret, COIN/1000); BOOST_CHECK(ParseMoney("0.0001", ret)); BOOST_CHECK_EQUAL(ret, COIN/10000); BOOST_CHECK(ParseMoney("0.00001", ret)); BOOST_CHECK_EQUAL(ret, COIN/100000); BOOST_CHECK(ParseMoney("0.000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/1000000); BOOST_CHECK(ParseMoney("0.0000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/10000000); BOOST_CHECK(ParseMoney("0.00000001", ret)); BOOST_CHECK_EQUAL(ret, COIN/100000000); // Attempted 63 bit overflow should fail BOOST_CHECK(!ParseMoney("92233720368.54775808", ret)); // Parsing negative amounts must fail BOOST_CHECK(!ParseMoney("-1", ret)); } BOOST_AUTO_TEST_CASE(util_IsHex) { BOOST_CHECK(IsHex("00")); BOOST_CHECK(IsHex("00112233445566778899aabbccddeeffAABBCCDDEEFF")); BOOST_CHECK(IsHex("ff")); BOOST_CHECK(IsHex("FF")); BOOST_CHECK(!IsHex("")); BOOST_CHECK(!IsHex("0")); BOOST_CHECK(!IsHex("a")); BOOST_CHECK(!IsHex("eleven")); BOOST_CHECK(!IsHex("00xx00")); BOOST_CHECK(!IsHex("0x0000")); } BOOST_AUTO_TEST_CASE(util_seed_insecure_rand) { int i; int count=0; SeedInsecureRand(true); for (int mod=2;mod<11;mod++) { int mask = 1; // Really rough binomal confidence approximation. int err = 30*10000./mod*sqrt((1./mod*(1-1./mod))/10000.); //mask is 2^ceil(log2(mod))-1 while(mask<mod-1)mask=(mask<<1)+1; count = 0; //How often does it get a zero from the uniform range [0,mod)? for (i=0;i<10000;i++) { uint32_t rval; do{ rval=InsecureRand32()&mask; }while(rval>=(uint32_t)mod); count += rval==0; } BOOST_CHECK(count<=10000/mod+err); BOOST_CHECK(count>=10000/mod-err); } } BOOST_AUTO_TEST_CASE(util_TimingResistantEqual) { BOOST_CHECK(TimingResistantEqual(std::string(""), std::string(""))); BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string(""))); BOOST_CHECK(!TimingResistantEqual(std::string(""), std::string("abc"))); BOOST_CHECK(!TimingResistantEqual(std::string("a"), std::string("aa"))); BOOST_CHECK(!TimingResistantEqual(std::string("aa"), std::string("a"))); BOOST_CHECK(TimingResistantEqual(std::string("abc"), std::string("abc"))); BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("aba"))); } /* Test strprintf formatting directives. * Put a string before and after to ensure sanity of element sizes on stack. */ #define B "check_prefix" #define E "check_postfix" BOOST_AUTO_TEST_CASE(strprintf_numbers) { int64_t s64t = -9223372036854775807LL; /* signed 64 bit test value */ uint64_t u64t = 18446744073709551615ULL; /* unsigned 64 bit test value */ BOOST_CHECK(strprintf("%s %d %s", B, s64t, E) == B" -9223372036854775807 " E); BOOST_CHECK(strprintf("%s %u %s", B, u64t, E) == B" 18446744073709551615 " E); BOOST_CHECK(strprintf("%s %x %s", B, u64t, E) == B" ffffffffffffffff " E); size_t st = 12345678; /* unsigned size_t test value */ ssize_t sst = -12345678; /* signed size_t test value */ BOOST_CHECK(strprintf("%s %d %s", B, sst, E) == B" -12345678 " E); BOOST_CHECK(strprintf("%s %u %s", B, st, E) == B" 12345678 " E); BOOST_CHECK(strprintf("%s %x %s", B, st, E) == B" bc614e " E); ptrdiff_t pt = 87654321; /* positive ptrdiff_t test value */ ptrdiff_t spt = -87654321; /* negative ptrdiff_t test value */ BOOST_CHECK(strprintf("%s %d %s", B, spt, E) == B" -87654321 " E); BOOST_CHECK(strprintf("%s %u %s", B, pt, E) == B" 87654321 " E); BOOST_CHECK(strprintf("%s %x %s", B, pt, E) == B" 5397fb1 " E); } #undef B #undef E /* Check for mingw/wine issue #3494 * Remove this test before time.ctime(0xffffffff) == 'Sun Feb 7 07:28:15 2106' */ BOOST_AUTO_TEST_CASE(gettime) { BOOST_CHECK((GetTime() & ~0xFFFFFFFFLL) == 0); } BOOST_AUTO_TEST_CASE(util_time_GetTime) { SetMockTime(111); // Check that mock time does not change after a sleep for (const auto& num_sleep : {0, 1}) { MilliSleep(num_sleep); BOOST_CHECK_EQUAL(111, GetTime()); // Deprecated time getter BOOST_CHECK_EQUAL(111, GetTime<std::chrono::seconds>().count()); BOOST_CHECK_EQUAL(111000, GetTime<std::chrono::milliseconds>().count()); BOOST_CHECK_EQUAL(111000000, GetTime<std::chrono::microseconds>().count()); } SetMockTime(0); // Check that system time changes after a sleep const auto ms_0 = GetTime<std::chrono::milliseconds>(); const auto us_0 = GetTime<std::chrono::microseconds>(); MilliSleep(1); BOOST_CHECK(ms_0 < GetTime<std::chrono::milliseconds>()); BOOST_CHECK(us_0 < GetTime<std::chrono::microseconds>()); } BOOST_AUTO_TEST_CASE(test_IsDigit) { BOOST_CHECK_EQUAL(IsDigit('0'), true); BOOST_CHECK_EQUAL(IsDigit('1'), true); BOOST_CHECK_EQUAL(IsDigit('8'), true); BOOST_CHECK_EQUAL(IsDigit('9'), true); BOOST_CHECK_EQUAL(IsDigit('0' - 1), false); BOOST_CHECK_EQUAL(IsDigit('9' + 1), false); BOOST_CHECK_EQUAL(IsDigit(0), false); BOOST_CHECK_EQUAL(IsDigit(1), false); BOOST_CHECK_EQUAL(IsDigit(8), false); BOOST_CHECK_EQUAL(IsDigit(9), false); } BOOST_AUTO_TEST_CASE(test_ParseInt32) { int32_t n; // Valid values BOOST_CHECK(ParseInt32("1234", NULL)); BOOST_CHECK(ParseInt32("0", &n) && n == 0); BOOST_CHECK(ParseInt32("1234", &n) && n == 1234); BOOST_CHECK(ParseInt32("01234", &n) && n == 1234); // no octal BOOST_CHECK(ParseInt32("2147483647", &n) && n == 2147483647); BOOST_CHECK(ParseInt32("-2147483648", &n) && n == -2147483648); BOOST_CHECK(ParseInt32("-1234", &n) && n == -1234); // Invalid values BOOST_CHECK(!ParseInt32("", &n)); BOOST_CHECK(!ParseInt32(" 1", &n)); // no padding inside BOOST_CHECK(!ParseInt32("1 ", &n)); BOOST_CHECK(!ParseInt32("1a", &n)); BOOST_CHECK(!ParseInt32("aap", &n)); BOOST_CHECK(!ParseInt32("0x1", &n)); // no hex BOOST_CHECK(!ParseInt32("0x1", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseInt32(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseInt32("-2147483649", NULL)); BOOST_CHECK(!ParseInt32("2147483648", NULL)); BOOST_CHECK(!ParseInt32("-32482348723847471234", NULL)); BOOST_CHECK(!ParseInt32("32482348723847471234", NULL)); } BOOST_AUTO_TEST_CASE(test_ParseInt64) { int64_t n; // Valid values BOOST_CHECK(ParseInt64("1234", NULL)); BOOST_CHECK(ParseInt64("0", &n) && n == 0LL); BOOST_CHECK(ParseInt64("1234", &n) && n == 1234LL); BOOST_CHECK(ParseInt64("01234", &n) && n == 1234LL); // no octal BOOST_CHECK(ParseInt64("2147483647", &n) && n == 2147483647LL); BOOST_CHECK(ParseInt64("-2147483648", &n) && n == -2147483648LL); BOOST_CHECK(ParseInt64("9223372036854775807", &n) && n == (int64_t)9223372036854775807); BOOST_CHECK(ParseInt64("-9223372036854775808", &n) && n == (int64_t)-9223372036854775807-1); BOOST_CHECK(ParseInt64("-1234", &n) && n == -1234LL); // Invalid values BOOST_CHECK(!ParseInt64("", &n)); BOOST_CHECK(!ParseInt64(" 1", &n)); // no padding inside BOOST_CHECK(!ParseInt64("1 ", &n)); BOOST_CHECK(!ParseInt64("1a", &n)); BOOST_CHECK(!ParseInt64("aap", &n)); BOOST_CHECK(!ParseInt64("0x1", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseInt64(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseInt64("-9223372036854775809", NULL)); BOOST_CHECK(!ParseInt64("9223372036854775808", NULL)); BOOST_CHECK(!ParseInt64("-32482348723847471234", NULL)); BOOST_CHECK(!ParseInt64("32482348723847471234", NULL)); } BOOST_AUTO_TEST_CASE(test_ParseDouble) { double n; // Valid values BOOST_CHECK(ParseDouble("1234", NULL)); BOOST_CHECK(ParseDouble("0", &n) && n == 0.0); BOOST_CHECK(ParseDouble("1234", &n) && n == 1234.0); BOOST_CHECK(ParseDouble("01234", &n) && n == 1234.0); // no octal BOOST_CHECK(ParseDouble("2147483647", &n) && n == 2147483647.0); BOOST_CHECK(ParseDouble("-2147483648", &n) && n == -2147483648.0); BOOST_CHECK(ParseDouble("-1234", &n) && n == -1234.0); BOOST_CHECK(ParseDouble("1e6", &n) && n == 1e6); BOOST_CHECK(ParseDouble("-1e6", &n) && n == -1e6); // Invalid values BOOST_CHECK(!ParseDouble("", &n)); BOOST_CHECK(!ParseDouble(" 1", &n)); // no padding inside BOOST_CHECK(!ParseDouble("1 ", &n)); BOOST_CHECK(!ParseDouble("1a", &n)); BOOST_CHECK(!ParseDouble("aap", &n)); BOOST_CHECK(!ParseDouble("0x1", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseDouble(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseDouble("-1e10000", NULL)); BOOST_CHECK(!ParseDouble("1e10000", NULL)); } BOOST_AUTO_TEST_CASE(test_FormatParagraph) { BOOST_CHECK_EQUAL(FormatParagraph("", 79, 0), ""); BOOST_CHECK_EQUAL(FormatParagraph("test", 79, 0), "test"); BOOST_CHECK_EQUAL(FormatParagraph(" test", 79, 0), "test"); BOOST_CHECK_EQUAL(FormatParagraph("test test", 79, 0), "test test"); BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 0), "test\ntest"); BOOST_CHECK_EQUAL(FormatParagraph("testerde test ", 4, 0), "testerde\ntest"); BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 4), "test\n test"); BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string. This is a second sentence in the very long test string."), "This is a very long test string. This is a second sentence in the very long\ntest string."); } BOOST_AUTO_TEST_CASE(test_FormatSubVersion) { std::vector<std::string> comments; comments.push_back(std::string("comment1")); std::vector<std::string> comments2; comments2.push_back(std::string("comment1")); comments2.push_back(std::string("comment2")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, std::vector<std::string>()),std::string("/Test:0.9.99/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments),std::string("/Test:0.9.99(comment1)/")); BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments2),std::string("/Test:0.9.99(comment1; comment2)/")); } BOOST_AUTO_TEST_CASE(test_ParseFixedPoint) { int64_t amount = 0; BOOST_CHECK(ParseFixedPoint("0", 8, &amount)); BOOST_CHECK_EQUAL(amount, 0LL); BOOST_CHECK(ParseFixedPoint("1", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000LL); BOOST_CHECK(ParseFixedPoint("0.0", 8, &amount)); BOOST_CHECK_EQUAL(amount, 0LL); BOOST_CHECK(ParseFixedPoint("-0.1", 8, &amount)); BOOST_CHECK_EQUAL(amount, -10000000LL); BOOST_CHECK(ParseFixedPoint("1.1", 8, &amount)); BOOST_CHECK_EQUAL(amount, 110000000LL); BOOST_CHECK(ParseFixedPoint("1.10000000000000000", 8, &amount)); BOOST_CHECK_EQUAL(amount, 110000000LL); BOOST_CHECK(ParseFixedPoint("1.1e1", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1100000000LL); BOOST_CHECK(ParseFixedPoint("1.1e-1", 8, &amount)); BOOST_CHECK_EQUAL(amount, 11000000LL); BOOST_CHECK(ParseFixedPoint("1000", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000000LL); BOOST_CHECK(ParseFixedPoint("-1000", 8, &amount)); BOOST_CHECK_EQUAL(amount, -100000000000LL); BOOST_CHECK(ParseFixedPoint("0.00000001", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1LL); BOOST_CHECK(ParseFixedPoint("0.0000000100000000", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1LL); BOOST_CHECK(ParseFixedPoint("-0.00000001", 8, &amount)); BOOST_CHECK_EQUAL(amount, -1LL); BOOST_CHECK(ParseFixedPoint("1000000000.00000001", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000000000001LL); BOOST_CHECK(ParseFixedPoint("9999999999.99999999", 8, &amount)); BOOST_CHECK_EQUAL(amount, 999999999999999999LL); BOOST_CHECK(ParseFixedPoint("-9999999999.99999999", 8, &amount)); BOOST_CHECK_EQUAL(amount, -999999999999999999LL); BOOST_CHECK(!ParseFixedPoint("", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("a-1000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-a1000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-1000a", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-01000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("00.1", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(".1", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("--0.1", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("0.000000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-0.000000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("0.00000001000000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-10000000000.00000000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("10000000000.00000000", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-10000000000.00000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("10000000000.00000001", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-10000000000.00000009", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("10000000000.00000009", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-99999999999.99999999", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("99999909999.09999999", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("92233720368.54775807", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("92233720368.54775808", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-92233720368.54775808", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("-92233720368.54775809", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("1.1e", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("1.1e-", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("1.", 8, &amount)); } BOOST_AUTO_TEST_CASE(test_ToLower) { BOOST_CHECK_EQUAL(ToLower('@'), '@'); BOOST_CHECK_EQUAL(ToLower('A'), 'a'); BOOST_CHECK_EQUAL(ToLower('Z'), 'z'); BOOST_CHECK_EQUAL(ToLower('['), '['); BOOST_CHECK_EQUAL(ToLower(0), 0); BOOST_CHECK_EQUAL(ToLower(255), 255); std::string testVector; Downcase(testVector); BOOST_CHECK_EQUAL(testVector, ""); testVector = "#HODL"; Downcase(testVector); BOOST_CHECK_EQUAL(testVector, "#hodl"); testVector = "\x00\xfe\xff"; Downcase(testVector); BOOST_CHECK_EQUAL(testVector, "\x00\xfe\xff"); } BOOST_AUTO_TEST_CASE(test_ToUpper) { BOOST_CHECK_EQUAL(ToUpper('`'), '`'); BOOST_CHECK_EQUAL(ToUpper('a'), 'A'); BOOST_CHECK_EQUAL(ToUpper('z'), 'Z'); BOOST_CHECK_EQUAL(ToUpper('{'), '{'); BOOST_CHECK_EQUAL(ToUpper(0), 0); BOOST_CHECK_EQUAL(ToUpper(255), 255); } BOOST_AUTO_TEST_CASE(test_Capitalize) { BOOST_CHECK_EQUAL(Capitalize(""), ""); BOOST_CHECK_EQUAL(Capitalize("creddit"), "Creddit"); BOOST_CHECK_EQUAL(Capitalize("\x00\xfe\xff"), "\x00\xfe\xff"); } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2011 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. // This file input format is based loosely on // Tools/DumpRenderTree/ImageDiff.m // The exact format of this tool's output to stdout is important, to match // what the run-webkit-tests script expects. #include <algorithm> #include <iostream> #include <string> #include <vector> #include "base/basictypes.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/process_util.h" #include "base/safe_numerics.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/size.h" #if defined(OS_WIN) #include "windows.h" #endif // Causes the app to remain open, waiting for pairs of filenames on stdin. // The caller is then responsible for terminating this app. static const char kOptionPollStdin[] = "use-stdin"; static const char kOptionGenerateDiff[] = "diff"; // Return codes used by this utility. static const int kStatusSame = 0; static const int kStatusDifferent = 1; static const int kStatusError = 2; // Color codes. static const uint32 RGBA_RED = 0x000000ff; static const uint32 RGBA_ALPHA = 0xff000000; class Image { public: Image() : w_(0), h_(0) { } Image(const Image& image) : w_(image.w_), h_(image.h_), data_(image.data_) { } bool has_image() const { return w_ > 0 && h_ > 0; } int w() const { return w_; } int h() const { return h_; } const unsigned char* data() const { return &data_.front(); } // Creates the image from stdin with the given data length. On success, it // will return true. On failure, no other methods should be accessed. bool CreateFromStdin(size_t byte_length) { if (byte_length == 0) return false; scoped_ptr<unsigned char[]> source(new unsigned char[byte_length]); if (fread(source.get(), 1, byte_length, stdin) != byte_length) return false; if (!gfx::PNGCodec::Decode(source.get(), byte_length, gfx::PNGCodec::FORMAT_RGBA, &data_, &w_, &h_)) { Clear(); return false; } return true; } // Creates the image from the given filename on disk, and returns true on // success. bool CreateFromFilename(const base::FilePath& path) { FILE* f = file_util::OpenFile(path, "rb"); if (!f) return false; std::vector<unsigned char> compressed; const int buf_size = 1024; unsigned char buf[buf_size]; size_t num_read = 0; while ((num_read = fread(buf, 1, buf_size, f)) > 0) { compressed.insert(compressed.end(), buf, buf + num_read); } file_util::CloseFile(f); if (!gfx::PNGCodec::Decode(&compressed[0], compressed.size(), gfx::PNGCodec::FORMAT_RGBA, &data_, &w_, &h_)) { Clear(); return false; } return true; } void Clear() { w_ = h_ = 0; data_.clear(); } // Returns the RGBA value of the pixel at the given location uint32 pixel_at(int x, int y) const { DCHECK(x >= 0 && x < w_); DCHECK(y >= 0 && y < h_); return *reinterpret_cast<const uint32*>(&(data_[(y * w_ + x) * 4])); } void set_pixel_at(int x, int y, uint32 color) const { DCHECK(x >= 0 && x < w_); DCHECK(y >= 0 && y < h_); void* addr = &const_cast<unsigned char*>(&data_.front())[(y * w_ + x) * 4]; *reinterpret_cast<uint32*>(addr) = color; } private: // pixel dimensions of the image int w_, h_; std::vector<unsigned char> data_; }; float PercentageDifferent(const Image& baseline, const Image& actual) { int w = std::min(baseline.w(), actual.w()); int h = std::min(baseline.h(), actual.h()); // compute pixels different in the overlap int pixels_different = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (baseline.pixel_at(x, y) != actual.pixel_at(x, y)) pixels_different++; } } // count pixels that are a difference in size as also being different int max_w = std::max(baseline.w(), actual.w()); int max_h = std::max(baseline.h(), actual.h()); // ...pixels off the right side, but not including the lower right corner pixels_different += (max_w - w) * h; // ...pixels along the bottom, including the lower right corner pixels_different += (max_h - h) * max_w; // Like the WebKit ImageDiff tool, we define percentage different in terms // of the size of the 'actual' bitmap. float total_pixels = static_cast<float>(actual.w()) * static_cast<float>(actual.h()); if (total_pixels == 0) return 100.0f; // when the bitmap is empty, they are 100% different return static_cast<float>(pixels_different) / total_pixels * 100; } void PrintHelp() { fprintf(stderr, "Usage:\n" " image_diff <compare file> <reference file>\n" " Compares two files on disk, returning 0 when they are the same\n" " image_diff --use-stdin\n" " Stays open reading pairs of filenames from stdin, comparing them,\n" " and sending 0 to stdout when they are the same\n" " image_diff --diff <compare file> <reference file> <output file>\n" " Compares two files on disk, outputs an image that visualizes the" " difference to <output file>\n"); /* For unfinished webkit-like-mode (see below) "\n" " image_diff -s\n" " Reads stream input from stdin, should be EXACTLY of the format\n" " \"Content-length: <byte length> <data>Content-length: ...\n" " it will take as many file pairs as given, and will compare them as\n" " (cmp_file, reference_file) pairs\n"); */ } int CompareImages(const base::FilePath& file1, const base::FilePath& file2) { Image actual_image; Image baseline_image; if (!actual_image.CreateFromFilename(file1)) { fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n", file1.value().c_str()); return kStatusError; } if (!baseline_image.CreateFromFilename(file2)) { fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n", file2.value().c_str()); return kStatusError; } float percent = PercentageDifferent(actual_image, baseline_image); if (percent > 0.0) { // failure: The WebKit version also writes the difference image to // stdout, which seems excessive for our needs. printf("diff: %01.2f%% failed\n", percent); return kStatusDifferent; } // success printf("diff: %01.2f%% passed\n", percent); return kStatusSame; /* Untested mode that acts like WebKit's image comparator. I wrote this but decided it's too complicated. We may use it in the future if it looks useful char buffer[2048]; while (fgets(buffer, sizeof(buffer), stdin)) { if (strncmp("Content-length: ", buffer, 16) == 0) { char* context; strtok_s(buffer, " ", &context); int image_size = strtol(strtok_s(NULL, " ", &context), NULL, 10); bool success = false; if (image_size > 0 && actual_image.has_image() == 0) { if (!actual_image.CreateFromStdin(image_size)) { fputs("Error, input image can't be decoded.\n", stderr); return 1; } } else if (image_size > 0 && baseline_image.has_image() == 0) { if (!baseline_image.CreateFromStdin(image_size)) { fputs("Error, baseline image can't be decoded.\n", stderr); return 1; } } else { fputs("Error, image size must be specified.\n", stderr); return 1; } } if (actual_image.has_image() && baseline_image.has_image()) { float percent = PercentageDifferent(actual_image, baseline_image); if (percent > 0.0) { // failure: The WebKit version also writes the difference image to // stdout, which seems excessive for our needs. printf("diff: %01.2f%% failed\n", percent); } else { // success printf("diff: %01.2f%% passed\n", percent); } actual_image.Clear(); baseline_image.Clear(); } fflush(stdout); } */ } bool CreateImageDiff(const Image& image1, const Image& image2, Image* out) { int w = std::min(image1.w(), image2.w()); int h = std::min(image1.h(), image2.h()); *out = Image(image1); bool same = (image1.w() == image2.w()) && (image1.h() == image2.h()); // TODO(estade): do something with the extra pixels if the image sizes // are different. for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { uint32 base_pixel = image1.pixel_at(x, y); if (base_pixel != image2.pixel_at(x, y)) { // Set differing pixels red. out->set_pixel_at(x, y, RGBA_RED | RGBA_ALPHA); same = false; } else { // Set same pixels as faded. uint32 alpha = base_pixel & RGBA_ALPHA; uint32 new_pixel = base_pixel - ((alpha / 2) & RGBA_ALPHA); out->set_pixel_at(x, y, new_pixel); } } } return same; } int DiffImages(const base::FilePath& file1, const base::FilePath& file2, const base::FilePath& out_file) { Image actual_image; Image baseline_image; if (!actual_image.CreateFromFilename(file1)) { fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n", file1.value().c_str()); return kStatusError; } if (!baseline_image.CreateFromFilename(file2)) { fprintf(stderr, "image_diff: Unable to open file \"%" PRFilePath "\"\n", file2.value().c_str()); return kStatusError; } Image diff_image; bool same = CreateImageDiff(baseline_image, actual_image, &diff_image); if (same) return kStatusSame; std::vector<unsigned char> png_encoding; gfx::PNGCodec::Encode(diff_image.data(), gfx::PNGCodec::FORMAT_RGBA, gfx::Size(diff_image.w(), diff_image.h()), diff_image.w() * 4, false, std::vector<gfx::PNGCodec::Comment>(), &png_encoding); if (file_util::WriteFile(out_file, reinterpret_cast<char*>(&png_encoding.front()), base::checked_numeric_cast<int>(png_encoding.size())) < 0) return kStatusError; return kStatusDifferent; } // It isn't strictly correct to only support ASCII paths, but this // program reads paths on stdin and the program that spawns it outputs // paths as non-wide strings anyway. base::FilePath FilePathFromASCII(const std::string& str) { #if defined(OS_WIN) return base::FilePath(ASCIIToWide(str)); #else return base::FilePath(str); #endif } int main(int argc, const char* argv[]) { base::EnableTerminationOnHeapCorruption(); CommandLine::Init(argc, argv); const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); if (parsed_command_line.HasSwitch(kOptionPollStdin)) { // Watch stdin for filenames. std::string stdin_buffer; base::FilePath filename1; while (std::getline(std::cin, stdin_buffer)) { if (stdin_buffer.empty()) continue; if (!filename1.empty()) { // CompareImages writes results to stdout unless an error occurred. base::FilePath filename2 = FilePathFromASCII(stdin_buffer); if (CompareImages(filename1, filename2) == kStatusError) printf("error\n"); fflush(stdout); filename1 = base::FilePath(); } else { // Save the first filename in another buffer and wait for the second // filename to arrive via stdin. filename1 = FilePathFromASCII(stdin_buffer); } } return 0; } const CommandLine::StringVector& args = parsed_command_line.GetArgs(); if (parsed_command_line.HasSwitch(kOptionGenerateDiff)) { if (args.size() == 3) { return DiffImages(base::FilePath(args[0]), base::FilePath(args[1]), base::FilePath(args[2])); } } else if (args.size() == 2) { return CompareImages(base::FilePath(args[0]), base::FilePath(args[1])); } PrintHelp(); return kStatusError; }
#include <iostream> #include <pthread.h> #include <queue> #include <unistd.h> #include "event_pool.hpp" #define THREAD_AMOUNT_MAX 5 class Singleton; //包含就绪队列 class ThreadPool { public: ThreadPool(int num = THREAD_AMOUNT_MAX) :thread_amount_(num) ,hangup_amount_(0) { pthread_mutex_init(&mutex_, NULL); pthread_cond_init(&cond_, NULL); } void InitThreadPool() { for(int i = 0; i < thread_amount_; ++i) { pthread_t tid_; pthread_create(&tid_, NULL, start_rounte, this); } } void EventPush(Event * event) { LockQueue(); if(hangup_amount_ > 0) { RouseOneThread(); } ready_queue_.push(event); UnLockQueue(); } ~ThreadPool() { pthread_mutex_destroy(&mutex_); pthread_cond_destroy(&cond_); } // static void RemoveEventPool(EventPool * peventpool) // { // s_peventpool = peventpool; // } private: void EventPop(Event & event) { event = *(ready_queue_.front()); ready_queue_.pop(); } void RouseOneThread() { pthread_cond_signal(&cond_); } void LockQueue() { pthread_mutex_lock(&mutex_); } void UnLockQueue() { pthread_mutex_unlock(&mutex_); } bool EventIsEmpty() { return ready_queue_.empty(); } static void * start_rounte(void * arg) { ThreadPool *tp = static_cast<ThreadPool *>(arg); pthread_detach(pthread_self()); for(;;) { tp->LockQueue(); while(tp->EventIsEmpty()) { tp->ThreadHangup(); } Event event_; tp->EventPop(event_); tp->UnLockQueue(); Singleton::GetEventPool()->EventPop(event_.GetFd()); event_.run(); } } void ThreadHangup() { ++hangup_amount_; pthread_cond_wait(&cond_, &mutex_); --hangup_amount_; } private: std::queue<Event *> ready_queue_; pthread_mutex_t mutex_; pthread_cond_t cond_; int thread_amount_; int hangup_amount_; // static EventPool * s_peventpool; }; // EventPool* ThreadPool::s_peventpool = NULL;
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/gpu/test/video_test_helpers.h" #include <limits> #include "base/stl_util.h" #include "base/sys_byteorder.h" #include "media/base/video_decoder_config.h" #include "media/base/video_frame_layout.h" #include "media/video/h264_parser.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { namespace test { // The structure for IVF frame header. IVF is a video file format. // The helpful description is in https://wiki.multimedia.cx/index.php/IVF. struct EncodedDataHelper::IVFHeader { uint32_t frame_size; uint64_t timestamp; }; // The structure for IVF frame data and header. // The data to be read is |header.frame_size| bytes from |data|. struct EncodedDataHelper::IVFFrame { const char* data; IVFHeader header; }; EncodedDataHelper::EncodedDataHelper(const std::vector<uint8_t>& stream, VideoCodecProfile profile) : data_(std::string(reinterpret_cast<const char*>(stream.data()), stream.size())), profile_(profile) {} EncodedDataHelper::~EncodedDataHelper() { base::STLClearObject(&data_); } bool EncodedDataHelper::IsNALHeader(const std::string& data, size_t pos) { return data[pos] == 0 && data[pos + 1] == 0 && data[pos + 2] == 0 && data[pos + 3] == 1; } scoped_refptr<DecoderBuffer> EncodedDataHelper::GetNextBuffer() { switch (VideoCodecProfileToVideoCodec(profile_)) { case kCodecH264: return GetNextFragment(); case kCodecVP8: case kCodecVP9: return GetNextFrame(); default: NOTREACHED(); return nullptr; } } scoped_refptr<DecoderBuffer> EncodedDataHelper::GetNextFragment() { if (next_pos_to_decode_ == 0) { size_t skipped_fragments_count = 0; if (!LookForSPS(&skipped_fragments_count)) { next_pos_to_decode_ = 0; return nullptr; } num_skipped_fragments_ += skipped_fragments_count; } size_t start_pos = next_pos_to_decode_; size_t next_nalu_pos = GetBytesForNextNALU(start_pos); // Update next_pos_to_decode_. next_pos_to_decode_ = next_nalu_pos; return DecoderBuffer::CopyFrom( reinterpret_cast<const uint8_t*>(&data_[start_pos]), next_nalu_pos - start_pos); } size_t EncodedDataHelper::GetBytesForNextNALU(size_t start_pos) { size_t pos = start_pos; if (pos + 4 > data_.size()) return pos; if (!IsNALHeader(data_, pos)) { ADD_FAILURE(); return std::numeric_limits<std::size_t>::max(); } pos += 4; while (pos + 4 <= data_.size() && !IsNALHeader(data_, pos)) { ++pos; } if (pos + 3 >= data_.size()) pos = data_.size(); return pos; } bool EncodedDataHelper::LookForSPS(size_t* skipped_fragments_count) { *skipped_fragments_count = 0; while (next_pos_to_decode_ + 4 < data_.size()) { if ((data_[next_pos_to_decode_ + 4] & 0x1f) == 0x7) { return true; } *skipped_fragments_count += 1; next_pos_to_decode_ = GetBytesForNextNALU(next_pos_to_decode_); } return false; } scoped_refptr<DecoderBuffer> EncodedDataHelper::GetNextFrame() { // Helpful description: http://wiki.multimedia.cx/index.php?title=IVF constexpr size_t kIVFHeaderSize = 32; // Only IVF video files are supported. The first 4bytes of an IVF video file's // header should be "DKIF". if (next_pos_to_decode_ == 0) { if ((data_.size() < kIVFHeaderSize) || strncmp(&data_[0], "DKIF", 4) != 0) { LOG(ERROR) << "Unexpected data encountered while parsing IVF header"; return nullptr; } next_pos_to_decode_ = kIVFHeaderSize; // Skip IVF header. } // Group IVF data whose timestamps are the same. Spatial layers in a // spatial-SVC stream may separately be stored in IVF data, where the // timestamps of the IVF frame headers are the same. However, it is necessary // for VD(A) to feed the spatial layers by a single DecoderBuffer. So this // grouping is required. std::vector<IVFFrame> ivf_frames; while (!ReachEndOfStream()) { auto frame_header = GetNextIVFFrameHeader(); if (!frame_header) return nullptr; // Timestamp is different from the current one. The next IVF data must be // grouped in the next group. if (!ivf_frames.empty() && frame_header->timestamp != ivf_frames[0].header.timestamp) { break; } auto frame_data = ReadNextIVFFrame(); if (!frame_data) return nullptr; ivf_frames.push_back(*frame_data); } if (ivf_frames.empty()) { LOG(ERROR) << "No IVF frame is available"; return nullptr; } // Standard stream case. if (ivf_frames.size() == 1) { return DecoderBuffer::CopyFrom( reinterpret_cast<const uint8_t*>(ivf_frames[0].data), ivf_frames[0].header.frame_size); } if (ivf_frames.size() > 3) { LOG(ERROR) << "Number of IVF frames with same timestamps exceeds maximum of" << "3: ivf_frames.size()=" << ivf_frames.size(); return nullptr; } std::string data; std::vector<uint32_t> frame_sizes; frame_sizes.reserve(ivf_frames.size()); for (const IVFFrame& ivf : ivf_frames) { data.append(ivf.data, ivf.header.frame_size); frame_sizes.push_back(ivf.header.frame_size); } // Copy frame_sizes information to DecoderBuffer's side data. Since side_data // is uint8_t*, we need to copy as uint8_t from uint32_t. The copied data is // recognized as uint32_t in VD(A). const uint8_t* side_data = reinterpret_cast<const uint8_t*>(frame_sizes.data()); size_t side_data_size = frame_sizes.size() * sizeof(uint32_t) / sizeof(uint8_t); return DecoderBuffer::CopyFrom(reinterpret_cast<const uint8_t*>(data.data()), data.size(), side_data, side_data_size); } base::Optional<EncodedDataHelper::IVFHeader> EncodedDataHelper::GetNextIVFFrameHeader() const { constexpr size_t kIVFFrameHeaderSize = 12; const size_t pos = next_pos_to_decode_; // Read VP8/9 frame size from IVF header. if (pos + kIVFFrameHeaderSize > data_.size()) { LOG(ERROR) << "Unexpected data encountered while parsing IVF frame header"; return base::nullopt; } uint32_t frame_size = 0; uint64_t timestamp = 0; memcpy(&frame_size, &data_[pos], 4); memcpy(&timestamp, &data_[pos + 4], 8); return IVFHeader{frame_size, timestamp}; } base::Optional<EncodedDataHelper::IVFFrame> EncodedDataHelper::ReadNextIVFFrame() { constexpr size_t kIVFFrameHeaderSize = 12; auto frame_header = GetNextIVFFrameHeader(); if (!frame_header) return base::nullopt; // Skip IVF frame header. const size_t pos = next_pos_to_decode_ + kIVFFrameHeaderSize; // Make sure we are not reading out of bounds. if (pos + frame_header->frame_size > data_.size()) { LOG(ERROR) << "Unexpected data encountered while parsing IVF frame header"; next_pos_to_decode_ = data_.size(); return base::nullopt; } // Update next_pos_to_decode_. next_pos_to_decode_ = pos + frame_header->frame_size; return IVFFrame{&data_[pos], *frame_header}; } // static bool EncodedDataHelper::HasConfigInfo(const uint8_t* data, size_t size, VideoCodecProfile profile) { if (profile >= H264PROFILE_MIN && profile <= H264PROFILE_MAX) { H264Parser parser; parser.SetStream(data, size); H264NALU nalu; H264Parser::Result result = parser.AdvanceToNextNALU(&nalu); if (result != H264Parser::kOk) { // Let the VDA figure out there's something wrong with the stream. return false; } return nalu.nal_unit_type == H264NALU::kSPS; } else if (profile >= VP8PROFILE_MIN && profile <= VP9PROFILE_MAX) { return (size > 0 && !(data[0] & 0x01)); } // Shouldn't happen at this point. LOG(FATAL) << "Invalid profile: " << GetProfileName(profile); return false; } AlignedDataHelper::AlignedDataHelper(const std::vector<uint8_t>& stream, uint32_t num_frames, VideoPixelFormat pixel_format, const gfx::Rect& visible_area, const gfx::Size& coded_size) : num_frames_(num_frames), pixel_format_(pixel_format), visible_area_(visible_area), coded_size_(coded_size) { // TODO(b/150257482): Rather than aligning the video stream data here, we // could directly create a vector of aligned video frames. CreateAlignedInputStream(stream); } AlignedDataHelper::~AlignedDataHelper() {} scoped_refptr<VideoFrame> AlignedDataHelper::GetNextFrame() { size_t num_planes = VideoFrame::NumPlanes(pixel_format_); CHECK_LE(num_planes, 3u); uint8_t* frame_data[3] = {}; std::vector<ColorPlaneLayout> planes(num_planes); size_t offset = data_pos_; for (size_t i = 0; i < num_planes; i++) { frame_data[i] = reinterpret_cast<uint8_t*>(&aligned_data_[0]) + offset; planes[i].stride = VideoFrame::RowBytes(i, pixel_format_, coded_size_.width()); planes[i].offset = offset; planes[i].size = aligned_plane_size_[i]; offset += aligned_plane_size_[i]; } auto layout = VideoFrameLayout::CreateWithPlanes(pixel_format_, coded_size_, std::move(planes)); if (!layout) { LOG(ERROR) << "Failed to create VideoFrameLayout"; return nullptr; } // TODO(crbug.com/1045825): Investigate use of MOJO_SHARED_BUFFER, similar to // changes made in crrev.com/c/2050895. scoped_refptr<VideoFrame> video_frame = VideoFrame::WrapExternalYuvDataWithLayout( *layout, visible_area_, visible_area_.size(), frame_data[0], frame_data[1], frame_data[2], base::TimeTicks::Now().since_origin()); data_pos_ += static_cast<off_t>(aligned_frame_size_); DCHECK_LE(data_pos_, aligned_data_.size()); EXPECT_NE(nullptr, video_frame.get()); return video_frame; } void AlignedDataHelper::Rewind() { data_pos_ = 0; } bool AlignedDataHelper::AtHeadOfStream() const { return data_pos_ == 0; } bool AlignedDataHelper::AtEndOfStream() const { return data_pos_ == aligned_data_.size(); } void AlignedDataHelper::CreateAlignedInputStream( const std::vector<uint8_t>& stream) { ASSERT_NE(pixel_format_, PIXEL_FORMAT_UNKNOWN); size_t num_planes = VideoFrame::NumPlanes(pixel_format_); std::vector<size_t> coded_bpl(num_planes); std::vector<size_t> visible_bpl(num_planes); std::vector<size_t> visible_plane_rows(num_planes); // Calculate padding in bytes to be added after each plane required to keep // starting addresses of all planes at a byte boundary required by the // platform. This padding will be added after each plane when copying to the // temporary file. // At the same time we also need to take into account coded_size requested by // the VEA; each row of visible_bpl bytes in the original file needs to be // copied into a row of coded_bpl bytes in the aligned file. for (size_t i = 0; i < num_planes; i++) { coded_bpl[i] = VideoFrame::RowBytes(i, pixel_format_, coded_size_.width()); visible_bpl[i] = VideoFrame::RowBytes(i, pixel_format_, visible_area_.width()); visible_plane_rows[i] = VideoFrame::Rows(i, pixel_format_, visible_area_.height()); size_t coded_area_size = coded_bpl[i] * VideoFrame::Rows(i, pixel_format_, coded_size_.height()); const size_t aligned_size = AlignToPlatformRequirements(coded_area_size); aligned_plane_size_.push_back(aligned_size); aligned_frame_size_ += aligned_size; } // NOTE: VideoFrame::AllocationSize() cannot used here because the width and // height on each plane is aligned by 2 for YUV format. size_t frame_buffer_size = 0; for (size_t i = 0; i < num_planes; ++i) { size_t row_bytes = VideoFrame::RowBytes(i, pixel_format_, visible_area_.width()); size_t rows = VideoFrame::Rows(i, pixel_format_, visible_area_.height()); frame_buffer_size += rows * row_bytes; } LOG_ASSERT(stream.size() % frame_buffer_size == 0U) << "Stream byte size is not a product of calculated frame byte size"; LOG_ASSERT(aligned_frame_size_ > 0UL); aligned_data_.resize(aligned_frame_size_ * num_frames_); off_t src_offset = 0; off_t dest_offset = 0; for (size_t frame = 0; frame < num_frames_; frame++) { const char* src_ptr = reinterpret_cast<const char*>(&stream[src_offset]); for (size_t i = 0; i < num_planes; i++) { // Assert that each plane of frame starts at required byte boundary. ASSERT_EQ(0u, dest_offset & (kPlatformBufferAlignment - 1)) << "Planes of frame should be mapped per platform requirements"; char* dst_ptr = &aligned_data_[dest_offset]; for (size_t j = 0; j < visible_plane_rows[i]; j++) { memcpy(dst_ptr, src_ptr, visible_bpl[i]); src_ptr += visible_bpl[i]; dst_ptr += static_cast<off_t>(coded_bpl[i]); } dest_offset += aligned_plane_size_[i]; } src_offset += static_cast<off_t>(frame_buffer_size); } } } // namespace test } // namespace media
#include "../idlib/precompiled.h" #pragma hdrstop #include "prey_local.h" CLASS_DECLARATION( idThread, hhThread ) END_CLASS hhThread::hhThread() : idThread() {} hhThread::hhThread( idEntity *self, const function_t *func ) : idThread( self, func ) {} hhThread::hhThread( const function_t *func ) : idThread( func ) {} hhThread::hhThread( idInterpreter *source, const function_t *func, int args ) : idThread( source, func, args ) {} /* ================ hhThread::PushParm ================ */ void hhThread::PushParm( int value ) { interpreter.Push( value ); } /* ================ hhThread::PushString ================ */ void hhThread::PushString( const char *text ) { PushParm( (int)new idStr(text) ); } /* ================ hhThread::PushFloat ================ */ void hhThread::PushFloat( float value ) { PushParm( *(int*)&value ); } /* ================ hhThread::PushInt ================ */ void hhThread::PushInt( int value ) { PushParm( value ); } /* ================ hhThread::PushVector ================ */ void hhThread::PushVector( const idVec3 &vec ) { float val = 0.0f; for( int ix = 0; ix < vec.GetDimension(); ++ix ) { val = vec[ ix ]; PushParm( *(int*)&val ); } } /* ================ hhThread::PushEntity ================ */ void hhThread::PushEntity( const idEntity *ent ) { HH_ASSERT( ent ); PushParm( ent->entityNumber + 1 ); } /* ================ hhThread::ClearStack ================ */ void hhThread::ClearStack() { interpreter.Reset(); } /* ================ hhThread::ParseAndPushArgsOntoStack ================ */ bool hhThread::ParseAndPushArgsOntoStack( const idCmdArgs &args, const function_t* function ) { idList<idStr> parmList; hhUtils::SplitString( args, parmList ); return ParseAndPushArgsOntoStack( parmList, function ); } /* ================ hhThread::ParseAndPushArgsOntoStack ================ */ bool hhThread::ParseAndPushArgsOntoStack( const idList<idStr>& args, const function_t* function ) { int numParms = function->def->TypeDef()->NumParameters(); idTypeDef* parmType = NULL; const char* parm = NULL; for( int ix = 0; ix < numParms; ++ix ) { parmType = function->def->TypeDef()->GetParmType( ix ); parm = args[ ix ].c_str(); parmType->PushOntoStack( parm, this ); } return true; }
#include "global.hpp" #include "Scanner.hpp" class TaskD { public: void solve(std::istream& inStream, std::ostream& outStream) { Scanner in(inStream); Writer out(outStream); } };
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "CorLib.h" char DigitalToHex(unsigned char x) { return x < 10 ? x + '0' : x - 10 + 'A'; } char *ByteArrayToHex(unsigned char *pInput, int index, int length) { char *pOutput = (char *)platform_malloc(length * 3); char *p = pOutput; pInput += index; for (int i = 0; i < length; i++, pInput++) { *p++ = DigitalToHex(*pInput / 16); *p++ = DigitalToHex(*pInput % 16); *p++ = '-'; } *(--p) = 0; return pOutput; } HRESULT Library_corlib_native_System_BitConverter::get_IsLittleEndian___STATIC__BOOLEAN(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned long x = 0x12345678; unsigned char *p = reinterpret_cast<unsigned char *>(&x); stack.SetResult_Boolean(*p == 0x78); NANOCLR_NOCLEANUP_NOLABEL(); } HRESULT Library_corlib_native_System_BitConverter::DoubleToInt64Bits___STATIC__I8__R8(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); #if !defined(NANOCLR_EMULATED_FLOATINGPOINT) double input = stack.Arg0().NumericByRefConst().r8; #else CLR_INT64 input = stack.Arg0().NumericByRefConst().r8; #endif __int64 *p = reinterpret_cast<__int64 *>(&input); stack.SetResult_I8(*p); NANOCLR_NOCLEANUP_NOLABEL(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__BOOLEAN(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); bool input = stack.Arg0().NumericByRefConst().u1 != 0; NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 1, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); *reinterpret_cast<bool *>(p) = input; } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__CHAR(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); char input = stack.Arg0().NumericByRefConst().u2; NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 2, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char* p = stack.TopValue().DereferenceArray()->GetFirstElement(); *reinterpret_cast<char*>(p) = input; } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__R8(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); #if !defined(NANOCLR_EMULATED_FLOATINGPOINT) double input = stack.Arg0().NumericByRefConst().r8; #else CLR_INT64 input = stack.Arg0().NumericByRefConst().r8; #endif NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 8, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); #if !defined(NANOCLR_EMULATED_FLOATINGPOINT) *reinterpret_cast<double *>(p) = input; #else *reinterpret_cast<CLR_INT64 *>(p) = input; #endif } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__R4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); #if !defined(NANOCLR_EMULATED_FLOATINGPOINT) float input = stack.Arg0().NumericByRefConst().r4; #else CLR_INT32 input = stack.Arg0().NumericByRefConst().r4; #endif NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 4, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); #if !defined(NANOCLR_EMULATED_FLOATINGPOINT) *reinterpret_cast<float *>(p) = input; #else *reinterpret_cast<CLR_INT32 *>(p) = input; #endif } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); int input = stack.Arg0().NumericByRefConst().s4; NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 4, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); *reinterpret_cast<int *>(p) = input; } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__I8(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); __int64 input = stack.Arg0().NumericByRefConst().s8; NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 8, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); *reinterpret_cast<__int64 *>(p) = input; } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__I2(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); short input = stack.Arg0().NumericByRefConst().s2; NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 2, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); *reinterpret_cast<short *>(p) = input; } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__U4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned int input = stack.Arg0().NumericByRefConst().u4; NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 4, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); *reinterpret_cast<unsigned int *>(p) = input; } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__U8(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned __int64 input = stack.Arg0().NumericByRefConst().u8; NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 8, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); *reinterpret_cast<unsigned __int64 *>(p) = input; } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__U2(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned short input = stack.Arg0().NumericByRefConst().u2; NANOCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 2, g_CLR_RT_WellKnownTypes.m_UInt8)); { unsigned char *p = stack.TopValue().DereferenceArray()->GetFirstElement(); *reinterpret_cast<unsigned short *>(p) = input; } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::Int64BitsToDouble___STATIC__R8__I8(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); __int64 input = stack.Arg0().NumericByRefConst().s8; #if !defined(NANOCLR_EMULATED_FLOATINGPOINT) double *p = reinterpret_cast<double *>(&input); #else CLR_INT64 *p = reinterpret_cast<CLR_INT64 *>(&input); #endif stack.SetResult_R8(*p); NANOCLR_NOCLEANUP_NOLABEL(); } HRESULT Library_corlib_native_System_BitConverter::ToBoolean___STATIC__BOOLEAN__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; unsigned char b = 0; int index = 0; bool res = false; CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); p = pArray->GetFirstElement(); b = *(p + index); res = (b != 0); // assume any value not zero is true. Zero is false. stack.SetResult_Boolean(res); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToChar___STATIC__CHAR__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; wchar_t value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 2 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); p = pArray->GetFirstElement(); for (int i = 0; i < 2; ++i) { pValue[i] = p[index + i]; } stack.SetResult(value, DATATYPE_CHAR); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToDouble___STATIC__R8__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; double value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 8 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); // fetch unsigned char aligned values, and store in object that is correctly aligned for this system. p = pArray->GetFirstElement(); for (int i = 0; i < 8; ++i) { pValue[i] = p[index + i]; } stack.SetResult_R8(value); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToSingle___STATIC__R4__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; float value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 4 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); // fetch unsigned char aligned values, and store in object that is correctly aligned for this system. p = pArray->GetFirstElement(); for (int i = 0; i < 4; ++i) { pValue[i] = p[index + i]; } stack.SetResult_R4(value); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToInt16___STATIC__I2__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; signed short value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 2 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); p = pArray->GetFirstElement(); // big vs little endian? for (int i = 0; i < 2; ++i) { pValue[i] = p[index + i]; } stack.SetResult_I4(value); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToInt32___STATIC__I4__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; signed int value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 4 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); p = pArray->GetFirstElement(); // big vs little endian? for (int i = 0; i < 4; ++i) { pValue[i] = p[index + i]; } stack.SetResult_I4(value); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToInt64___STATIC__I8__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; CLR_INT64 value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 8 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); p = pArray->GetFirstElement(); for (int i = 0; i < 8; ++i) { pValue[i] = p[index + i]; } stack.SetResult_I8(value); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToUInt16___STATIC__U2__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; CLR_UINT16 value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 2 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); p = pArray->GetFirstElement(); for (int i = 0; i < 2; ++i) { pValue[i] = p[index + i]; } stack.SetResult_I4(value); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToUInt32___STATIC__U4__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; CLR_UINT32 value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 4 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); p = pArray->GetFirstElement(); for (int i = 0; i < 4; ++i) { pValue[i] = p[index + i]; } stack.SetResult_U4(value); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToUInt64___STATIC__U8__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); unsigned char *p = NULL; int index = 0; CLR_UINT64 value = 0; unsigned char *pValue = (unsigned char *)(&value); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + 8 > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); p = pArray->GetFirstElement(); for (int i = 0; i < 8; ++i) { pValue[i] = p[index + i]; } stack.SetResult_U8(value); NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToString___STATIC__STRING__SZARRAY_U1(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); if (pArray->m_numOfElements == 0) { NANOCLR_CHECK_HRESULT(stack.SetResult_String("")); } else { unsigned char *p = pArray->GetFirstElement(); char *pOutput = ByteArrayToHex(p, 0, pArray->m_numOfElements); NANOCLR_CHECK_HRESULT(stack.SetResult_String(pOutput)); platform_free(pOutput); } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToString___STATIC__STRING__SZARRAY_U1__I4(CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); int index = 0; CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; if (pArray->m_numOfElements == 0 && index == 0) { NANOCLR_CHECK_HRESULT(stack.SetResult_String("")); } else { if (index < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); unsigned char *p = pArray->GetFirstElement(); char *pOutput = ByteArrayToHex(p, index, pArray->m_numOfElements - index); NANOCLR_CHECK_HRESULT(stack.SetResult_String(pOutput)); platform_free(pOutput); } NANOCLR_NOCLEANUP(); } HRESULT Library_corlib_native_System_BitConverter::ToString___STATIC__STRING__SZARRAY_U1__I4__I4( CLR_RT_StackFrame &stack) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); int index = 0; int length = 0; CLR_RT_HeapBlock_Array *pArray = stack.Arg0().DereferenceArray(); FAULT_ON_NULL_ARG(pArray); index = stack.Arg1().NumericByRefConst().s4; length = stack.Arg2().NumericByRefConst().s4; if (pArray->m_numOfElements == 0 && index == 0 && length == 0) { NANOCLR_CHECK_HRESULT(stack.SetResult_String("")); } else { if (index < 0 || length < 0 || (unsigned int)index >= pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); if ((unsigned int)index + length > pArray->m_numOfElements) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); unsigned char *p = pArray->GetFirstElement(); char *pOutput = ByteArrayToHex(p, index, length); NANOCLR_CHECK_HRESULT(stack.SetResult_String(pOutput)); platform_free(pOutput); } NANOCLR_NOCLEANUP(); }
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/xtrace/model/ListIpOrHostsRequest.h> using AlibabaCloud::Xtrace::Model::ListIpOrHostsRequest; ListIpOrHostsRequest::ListIpOrHostsRequest() : RpcServiceRequest("xtrace", "2019-08-08", "ListIpOrHosts") { setMethod(HttpRequest::Method::Post); } ListIpOrHostsRequest::~ListIpOrHostsRequest() {} std::string ListIpOrHostsRequest::getRegionId()const { return regionId_; } void ListIpOrHostsRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setParameter("RegionId", regionId); } long ListIpOrHostsRequest::getEndTime()const { return endTime_; } void ListIpOrHostsRequest::setEndTime(long endTime) { endTime_ = endTime; setParameter("EndTime", std::to_string(endTime)); } std::string ListIpOrHostsRequest::getServiceName()const { return serviceName_; } void ListIpOrHostsRequest::setServiceName(const std::string& serviceName) { serviceName_ = serviceName; setParameter("ServiceName", serviceName); } long ListIpOrHostsRequest::getStartTime()const { return startTime_; } void ListIpOrHostsRequest::setStartTime(long startTime) { startTime_ = startTime; setParameter("StartTime", std::to_string(startTime)); }
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey $ // $Authors: Douglas McCloskey $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/KERNEL/MRMFeature.h> #include <OpenMS/KERNEL/Feature.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/FORMAT/QcMLFile.h> #include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureQC.h> using namespace OpenMS; using namespace std; START_TEST(MRMFeatureQC, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MRMFeatureQC* ptr = nullptr; MRMFeatureQC* nullPointer = nullptr; START_SECTION(MRMFeatureQC()) { ptr = new MRMFeatureQC(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~MRMFeatureQC()) { delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <mesos/executor.hpp> #include <mesos/scheduler.hpp> #include <process/clock.hpp> #include <process/future.hpp> #include <process/owned.hpp> #include <process/pid.hpp> #include "docker/docker.hpp" #include "slave/slave.hpp" #include "slave/containerizer/docker.hpp" #include "slave/containerizer/fetcher.hpp" #include "tests/containerizer.hpp" #include "tests/flags.hpp" #include "tests/mesos.hpp" #include "tests/utils.hpp" using mesos::internal::master::Master; using mesos::internal::slave::Containerizer; using mesos::internal::slave::DockerContainerizer; using mesos::internal::slave::Fetcher; using mesos::internal::slave::MesosContainerizer; using mesos::internal::slave::MesosContainerizerProcess; using mesos::internal::slave::Slave; using process::Clock; using process::Future; using process::Owned; using process::PID; using testing::_; using testing::AtMost; using testing::Eq; using testing::Return; using std::vector; using std::queue; using std::string; using std::map; namespace mesos { namespace internal { namespace tests { class HealthCheckTest : public MesosTest { public: vector<TaskInfo> populateTasks( const string& cmd, const string& healthCmd, const Offer& offer, int gracePeriodSeconds = 0, const Option<int>& consecutiveFailures = None(), const Option<map<string, string>>& env = None(), const Option<ContainerInfo>& containerInfo = None()) { CommandInfo healthCommand; healthCommand.set_value(healthCmd); return populateTasks( cmd, healthCommand, offer, gracePeriodSeconds, consecutiveFailures, env, containerInfo); } vector<TaskInfo> populateTasks( const string& cmd, CommandInfo healthCommand, const Offer& offer, int gracePeriodSeconds = 0, const Option<int>& consecutiveFailures = None(), const Option<map<string, string>>& env = None(), const Option<ContainerInfo>& containerInfo = None()) { TaskInfo task; task.set_name(""); task.mutable_task_id()->set_value("1"); task.mutable_slave_id()->CopyFrom(offer.slave_id()); task.mutable_resources()->CopyFrom(offer.resources()); CommandInfo command; command.set_value(cmd); Environment::Variable* variable = command.mutable_environment()->add_variables(); // We need to set the correct directory to launch health check process // instead of the default for tests. variable->set_name("MESOS_LAUNCHER_DIR"); variable->set_value(path::join(tests::flags.build_dir, "src")); task.mutable_command()->CopyFrom(command); if (containerInfo.isSome()) { task.mutable_container()->CopyFrom(containerInfo.get()); } HealthCheck healthCheck; if (env.isSome()) { foreachpair (const string& name, const string value, env.get()) { Environment::Variable* variable = healthCommand.mutable_environment()->mutable_variables()->Add(); variable->set_name(name); variable->set_value(value); } } healthCheck.mutable_command()->CopyFrom(healthCommand); healthCheck.set_delay_seconds(0); healthCheck.set_interval_seconds(0); healthCheck.set_grace_period_seconds(gracePeriodSeconds); if (consecutiveFailures.isSome()) { healthCheck.set_consecutive_failures(consecutiveFailures.get()); } task.mutable_health_check()->CopyFrom(healthCheck); vector<TaskInfo> tasks; tasks.push_back(task); return tasks; } }; // Testing a healthy task reporting one healthy status to scheduler. TEST_F(HealthCheckTest, HealthyTask) { Try<PID<Master> > master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); flags.isolation = "posix/cpu,posix/mem"; Fetcher fetcher; Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, false, &fetcher); CHECK_SOME(containerizer); Try<PID<Slave> > slave = StartSlave(containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)) .Times(1); Future<vector<Offer> > offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_NE(0u, offers.get().size()); vector<TaskInfo> tasks = populateTasks("sleep 120", "exit 0", offers.get()[0]); Future<TaskStatus> statusRunning; Future<TaskStatus> statusHealth; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusHealth)); driver.launchTasks(offers.get()[0].id(), tasks); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(statusHealth); EXPECT_EQ(TASK_RUNNING, statusHealth.get().state()); EXPECT_TRUE(statusHealth.get().has_healthy()); EXPECT_TRUE(statusHealth.get().healthy()); Future<TaskStatus> explicitReconciliation; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&explicitReconciliation)); vector<TaskStatus> statuses; TaskStatus status; // Send a task status to trigger explicit reconciliation. const TaskID taskId = statusHealth.get().task_id(); const SlaveID slaveId = statusHealth.get().slave_id(); status.mutable_task_id()->CopyFrom(taskId); // State is not checked by reconciliation, but is required to be // a valid task status. status.set_state(TASK_RUNNING); statuses.push_back(status); driver.reconcileTasks(statuses); AWAIT_READY(explicitReconciliation); EXPECT_EQ(TASK_RUNNING, explicitReconciliation.get().state()); EXPECT_TRUE(explicitReconciliation.get().has_healthy()); EXPECT_TRUE(explicitReconciliation.get().healthy()); Future<TaskStatus> implicitReconciliation; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&implicitReconciliation)); // Send an empty vector of task statuses to trigger implicit // reconciliation. statuses.clear(); driver.reconcileTasks(statuses); AWAIT_READY(implicitReconciliation); EXPECT_EQ(TASK_RUNNING, implicitReconciliation.get().state()); EXPECT_TRUE(implicitReconciliation.get().has_healthy()); EXPECT_TRUE(implicitReconciliation.get().healthy()); driver.stop(); driver.join(); Shutdown(); } // Testing a healthy task reporting one healthy status to scheduler for // docker executor. TEST_F(HealthCheckTest, ROOT_DOCKER_DockerHealthyTask) { Owned<Docker> docker(Docker::create(tests::flags.docker, tests::flags.docker_socket, false).get()); Try<Nothing> validateResult = docker->validateVersion(Version(1, 3, 0)); ASSERT_SOME(validateResult) << "-------------------------------------------------------------\n" << "We cannot run this test because of 'docker exec' command \n" << "require docker version greater than '1.3.0'. You won't be \n" << "able to use the docker exec method, but feel free to disable\n" << "this test.\n" << "-------------------------------------------------------------"; Try<PID<Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); Fetcher fetcher; Try<DockerContainerizer*> containerizer = DockerContainerizer::create(flags, &fetcher); CHECK_SOME(containerizer); Try<PID<Slave>> slave = StartSlave(containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)) .Times(1); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_NE(0u, offers.get().size()); ContainerInfo containerInfo; containerInfo.set_type(ContainerInfo::DOCKER); // TODO(tnachen): Use local image to test if possible. ContainerInfo::DockerInfo dockerInfo; dockerInfo.set_image("busybox"); containerInfo.mutable_docker()->CopyFrom(dockerInfo); vector<TaskInfo> tasks = populateTasks( "sleep 120", "exit 0", offers.get()[0], 0, None(), None(), containerInfo); Future<TaskStatus> statusRunning; Future<TaskStatus> statusHealth; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusHealth)); driver.launchTasks(offers.get()[0].id(), tasks); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(statusHealth); EXPECT_EQ(TASK_RUNNING, statusHealth.get().state()); EXPECT_TRUE(statusHealth.get().has_healthy()); EXPECT_TRUE(statusHealth.get().healthy()); driver.stop(); driver.join(); Shutdown(); Future<std::list<Docker::Container>> containers = docker->ps(true, slave::DOCKER_NAME_PREFIX); AWAIT_READY(containers); // Cleanup all mesos launched containers. foreach (const Docker::Container& container, containers.get()) { AWAIT_READY_FOR(docker->rm(container.id, true), Seconds(30)); } } // Same as above, but use the non-shell version of the health command. TEST_F(HealthCheckTest, HealthyTaskNonShell) { Try<PID<Master> > master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); flags.isolation = "posix/cpu,posix/mem"; Fetcher fetcher; Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, false, &fetcher); CHECK_SOME(containerizer); Try<PID<Slave> > slave = StartSlave(containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)) .Times(1); Future<vector<Offer> > offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_NE(0u, offers.get().size()); CommandInfo command; command.set_shell(false); command.set_value("true"); command.add_arguments("true"); vector<TaskInfo> tasks = populateTasks("sleep 120", command, offers.get()[0]); Future<TaskStatus> statusRunning; Future<TaskStatus> statusHealth; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusHealth)); driver.launchTasks(offers.get()[0].id(), tasks); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(statusHealth); EXPECT_EQ(TASK_RUNNING, statusHealth.get().state()); EXPECT_TRUE(statusHealth.get().healthy()); driver.stop(); driver.join(); Shutdown(); } // Testing health status change reporting to scheduler. TEST_F(HealthCheckTest, HealthStatusChange) { Try<PID<Master> > master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); flags.isolation = "posix/cpu,posix/mem"; Fetcher fetcher; Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, false, &fetcher); CHECK_SOME(containerizer); Try<PID<Slave> > slave = StartSlave(containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)); Future<vector<Offer> > offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_NE(0u, offers.get().size()); // Create a temporary file. Try<string> temporaryPath = os::mktemp(); ASSERT_SOME(temporaryPath); string tmpPath = temporaryPath.get(); // This command fails every other invocation. // For all runs i in Nat0, the following case i % 2 applies: // // Case 0: // - Remove the temporary file. // // Case 1: // - Attempt to remove the nonexistent temporary file. // - Create the temporary file. // - Exit with a non-zero status. string alt = "rm " + tmpPath + " || (touch " + tmpPath + " && exit 1)"; vector<TaskInfo> tasks = populateTasks( "sleep 120", alt, offers.get()[0], 0, 3); Future<TaskStatus> statusRunning; Future<TaskStatus> statusHealth1; Future<TaskStatus> statusHealth2; Future<TaskStatus> statusHealth3; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusHealth1)) .WillOnce(FutureArg<1>(&statusHealth2)) .WillOnce(FutureArg<1>(&statusHealth3)); driver.launchTasks(offers.get()[0].id(), tasks); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(statusHealth1); EXPECT_EQ(TASK_RUNNING, statusHealth1.get().state()); EXPECT_TRUE(statusHealth1.get().healthy()); AWAIT_READY(statusHealth2); EXPECT_EQ(TASK_RUNNING, statusHealth2.get().state()); EXPECT_FALSE(statusHealth2.get().healthy()); AWAIT_READY(statusHealth3); EXPECT_EQ(TASK_RUNNING, statusHealth3.get().state()); EXPECT_TRUE(statusHealth3.get().healthy()); os::rm(tmpPath); // Clean up the temporary file. driver.stop(); driver.join(); Shutdown(); } // Testing health status change reporting to scheduler for docker executor. TEST_F(HealthCheckTest, ROOT_DOCKER_DockerHealthStatusChange) { Owned<Docker> docker(Docker::create(tests::flags.docker, tests::flags.docker_socket, false).get()); Try<Nothing> validateResult = docker->validateVersion(Version(1, 3, 0)); ASSERT_SOME(validateResult) << "-------------------------------------------------------------\n" << "We cannot run this test because of 'docker exec' command \n" << "require docker version greater than '1.3.0'. You won't be \n" << "able to use the docker exec method, but feel free to disable\n" << "this test.\n" << "-------------------------------------------------------------"; Try<PID<Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); Fetcher fetcher; Try<DockerContainerizer*> containerizer = DockerContainerizer::create(flags, &fetcher); CHECK_SOME(containerizer); Try<PID<Slave>> slave = StartSlave(containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_NE(0u, offers.get().size()); ContainerInfo containerInfo; containerInfo.set_type(ContainerInfo::DOCKER); // TODO(tnachen): Use local image to test if possible. ContainerInfo::DockerInfo dockerInfo; dockerInfo.set_image("busybox"); containerInfo.mutable_docker()->CopyFrom(dockerInfo); // Create a temporary file in host and then we could this file to make sure // the health check command is run in docker container. string tmpPath = path::join(os::getcwd(), "foobar"); ASSERT_SOME(os::write(tmpPath, "bar")); // This command fails every other invocation. // For all runs i in Nat0, the following case i % 2 applies: // // Case 0: // - Attempt to remove the nonexistent temporary file. // - Create the temporary file. // - Exit with a non-zero status. // // Case 1: // - Remove the temporary file. string alt = "rm " + tmpPath + " || (mkdir -p " + os::getcwd() + " && echo foo >" + tmpPath + " && exit 1)"; vector<TaskInfo> tasks = populateTasks( "sleep 120", alt, offers.get()[0], 0, 3, None(), containerInfo); Future<TaskStatus> statusRunning; Future<TaskStatus> statusHealth1; Future<TaskStatus> statusHealth2; Future<TaskStatus> statusHealth3; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusHealth1)) .WillOnce(FutureArg<1>(&statusHealth2)) .WillOnce(FutureArg<1>(&statusHealth3)); driver.launchTasks(offers.get()[0].id(), tasks); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(statusHealth1); EXPECT_EQ(TASK_RUNNING, statusHealth1.get().state()); EXPECT_FALSE(statusHealth1.get().healthy()); AWAIT_READY(statusHealth2); EXPECT_EQ(TASK_RUNNING, statusHealth2.get().state()); EXPECT_TRUE(statusHealth2.get().healthy()); AWAIT_READY(statusHealth3); EXPECT_EQ(TASK_RUNNING, statusHealth3.get().state()); EXPECT_FALSE(statusHealth3.get().healthy()); // Check the temporary file created in host still exists and the content // don't change. ASSERT_SOME(os::read(tmpPath)); EXPECT_EQ("bar", os::read(tmpPath).get()); driver.stop(); driver.join(); Shutdown(); Future<std::list<Docker::Container>> containers = docker->ps(true, slave::DOCKER_NAME_PREFIX); AWAIT_READY(containers); // Cleanup all mesos launched containers. foreach (const Docker::Container& container, containers.get()) { AWAIT_READY_FOR(docker->rm(container.id, true), Seconds(30)); } } // Testing killing task after number of consecutive failures. // Temporarily disabled due to MESOS-1613. TEST_F(HealthCheckTest, DISABLED_ConsecutiveFailures) { Try<PID<Master> > master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); flags.isolation = "posix/cpu,posix/mem"; Fetcher fetcher; Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, false, &fetcher); CHECK_SOME(containerizer); Try<PID<Slave> > slave = StartSlave(containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)) .Times(1); Future<vector<Offer> > offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_NE(0u, offers.get().size()); vector<TaskInfo> tasks = populateTasks( "sleep 120", "exit 1", offers.get()[0], 0, 4); // Expecting four unhealthy updates and one final kill update. Future<TaskStatus> statusRunning; Future<TaskStatus> status1; Future<TaskStatus> status2; Future<TaskStatus> status3; Future<TaskStatus> status4; Future<TaskStatus> statusKilled; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&status1)) .WillOnce(FutureArg<1>(&status2)) .WillOnce(FutureArg<1>(&status3)) .WillOnce(FutureArg<1>(&status4)) .WillOnce(FutureArg<1>(&statusKilled)); driver.launchTasks(offers.get()[0].id(), tasks); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(status1); EXPECT_EQ(TASK_RUNNING, status1.get().state()); EXPECT_FALSE(status1.get().healthy()); AWAIT_READY(status2); EXPECT_EQ(TASK_RUNNING, status2.get().state()); EXPECT_FALSE(status2.get().healthy()); AWAIT_READY(status3); EXPECT_EQ(TASK_RUNNING, status3.get().state()); EXPECT_FALSE(status3.get().healthy()); AWAIT_READY(status4); EXPECT_EQ(TASK_RUNNING, status4.get().state()); EXPECT_FALSE(status4.get().healthy()); AWAIT_READY(statusKilled); EXPECT_EQ(TASK_KILLED, statusKilled.get().state()); EXPECT_TRUE(statusKilled.get().has_healthy()); EXPECT_FALSE(statusKilled.get().healthy()); driver.stop(); driver.join(); Shutdown(); } // Testing command using environment variable. TEST_F(HealthCheckTest, EnvironmentSetup) { Try<PID<Master> > master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); flags.isolation = "posix/cpu,posix/mem"; Fetcher fetcher; Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, false, &fetcher); CHECK_SOME(containerizer); Try<PID<Slave> > slave = StartSlave(containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)) .Times(1); Future<vector<Offer> > offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_NE(0u, offers.get().size()); map<string, string> env; env["STATUS"] = "0"; vector<TaskInfo> tasks = populateTasks( "sleep 120", "exit $STATUS", offers.get()[0], 0, None(), env); Future<TaskStatus> statusRunning; Future<TaskStatus> statusHealth; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusHealth)); driver.launchTasks(offers.get()[0].id(), tasks); AWAIT_READY(statusRunning); EXPECT_EQ(TASK_RUNNING, statusRunning.get().state()); AWAIT_READY(statusHealth); EXPECT_EQ(TASK_RUNNING, statusHealth.get().state()); EXPECT_TRUE(statusHealth.get().healthy()); driver.stop(); driver.join(); Shutdown(); } // Testing grace period that ignores all failed task failures. TEST_F(HealthCheckTest, DISABLED_GracePeriod) { Try<PID<Master> > master = StartMaster(); ASSERT_SOME(master); slave::Flags flags = CreateSlaveFlags(); flags.isolation = "posix/cpu,posix/mem"; Fetcher fetcher; Try<MesosContainerizer*> containerizer = MesosContainerizer::create(flags, false, &fetcher); CHECK_SOME(containerizer); Try<PID<Slave> > slave = StartSlave(containerizer.get()); ASSERT_SOME(slave); MockScheduler sched; MesosSchedulerDriver driver( &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)) .Times(1); Future<vector<Offer> > offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); EXPECT_NE(0u, offers.get().size()); vector<TaskInfo> tasks = populateTasks( "sleep 120", "exit 1", offers.get()[0], 6); Future<TaskStatus> statusRunning; Future<TaskStatus> statusHealth; EXPECT_CALL(sched, statusUpdate(&driver, _)) .WillOnce(FutureArg<1>(&statusRunning)) .WillOnce(FutureArg<1>(&statusHealth)) .WillRepeatedly(Return()); driver.launchTasks(offers.get()[0].id(), tasks); Clock::pause(); EXPECT_TRUE(statusHealth.isPending()); // No task unhealthy update should be called in grace period. Clock::advance(Seconds(5)); EXPECT_TRUE(statusHealth.isPending()); Clock::advance(Seconds(1)); Clock::settle(); Clock::resume(); AWAIT_READY(statusHealth); EXPECT_EQ(TASK_RUNNING, statusHealth.get().state()); EXPECT_FALSE(statusHealth.get().healthy()); driver.stop(); driver.join(); Shutdown(); } } // namespace tests { } // namespace internal { } // namespace mesos {
#include "CoolProp.h" // PropsSI #include "HumidAirProp.h" // HAPropsSI #include "node.hpp" // prototypes /** * TO-DO * Automatic prune nodes that can be computed * * NOT IMPORTANT * Divide functions per number of inputs : non-type template parameters * Enum function names and include more functions * makes evalFun accept doubles and put everything in another header file * * NOT-DO * Variable = "string" (implement as a equation parser to scope) * User-defined functions (implement as a equation parser to scope) */ /** * NodeVar find variables */ StringSet NodeVar::findVars(Scope &local){ StringSet names; if (local.find(name) == local.end()){ names.insert(name); } return names; } /** * Default functions */ std::map<std::string,int> funCodes = { {"exp", '1'}, {"log", '2'}, {"log10", '3'}, {"abs",'4'}, {"pow",'5'}, {"PropsSI",'6'}, {"HAPropsSI",'7'} }; std::map<int,std::string> funNames = { {'1', "exp"}, {'2', "log"}, {'3', "log10"}, {'4',"abs"}, {'5',"pow"}, {'6',"PropsSI"}, {'7',"HAPropsSI"} }; /** * Evaluates a function */ double evalFun(const char code,Node** input, Scope &local){ double ans; switch (code){ case '1': ans = exp(input[0] -> eval(local)); break; case '2': ans = log(input[0] -> eval(local)); break; case '3': ans = log10(input[0] -> eval(local)); break; case '4': ans = abs(input[0] -> eval(local)); break; case '5': ans = pow(input[0] -> eval(local), input[1] -> eval(local)); break; case '6': { std::string p = input[0]->toString(); std::string v1 = input[1]->toString(); double n1 = input[2] -> eval(local); std::string v2 = input[3]->toString(); double n2 = input[4] -> eval(local); std::string fluid = input[5]->toString(); ans = CoolProp::PropsSI(p,v1,n1,v2,n2,fluid); } break; case '7': { std::string p = input[0]->toString(); std::string v1 = input[1]->toString(); double n1 = input[2] -> eval(local); std::string v2 = input[3]->toString(); double n2 = input[4] -> eval(local); std::string v3 = input[5]->toString(); double n3 = input[6] -> eval(local); ans = HumidAir::HAPropsSI(p,v1,n1,v2,n2,v3,n3); } break; default: throw std::invalid_argument("code @evalFun"); } return ans; } /** * NodeFun constructor */ NodeFun::NodeFun(std::string alias, int number, Node** var){ op = funCodes[alias]; n = number; inputs = new Node*[n]; for (int i=0; i<n; ++i){ inputs[i] = var[i]; } } /** * NodeFun destructor */ NodeFun::~NodeFun(){ int n = get_n(); for (int i=0;i<n;++i){ delete inputs[i]; } delete[] inputs; } /** * NodeFun find vars */ StringSet NodeFun::findVars(Scope &local){ StringSet names; std::set<std::string> dummy; for (int i=0;i<n;++i){ dummy = inputs[i] -> findVars(local); names.insert(dummy.begin(),dummy.end()); } return names; } /** * NodeFun give string */ std::string NodeFun::toString(){ std::string out; for (int i = 0; i<n; ++i){ out += inputs[i] -> toString()+ ' '; } out += funNames[op] + ' '; return out; } /** * NodeFun copy */ NodeFun* NodeFun::get_copy(){ Node** copy_inputs = new Node*[n]; for (int i=0;i<n;++i){ copy_inputs[i] = inputs[i]->get_copy(); } return new NodeFun(funNames[op], n, copy_inputs); } /** * NodeFun swap variables */ void NodeFun::swap_var(std::string var, Node* tree){ for (int i = 0; i<n ; ++i){ char type = inputs[i] ->get_type(); if (type == 'v' && inputs[i]->toString() == var){ // Create a copy, swap and delete old; Node* copy = tree ->get_copy(); std::swap(inputs[i],copy); delete copy; } else if (type == 'o' || type == 'f'){ inputs[i] -> swap_var(var,tree); } } } /** * NodeOp constructor */ NodeOp::NodeOp(char symbol, Node* a, Node* b){ op = symbol; n = 2; inputs = new Node*[2]; inputs[0] = a; inputs[1] = b; } /** * NodeOp eval */ double NodeOp::eval(Scope &local){ const double left = inputs[0] -> eval(local); const double right = inputs[1] -> eval(local); return evalOp(left,right,op); } /** * Evaluates a operation */ double evalOp(const double left,const double right,const char op){ double ans; switch (op){ case '+': ans = left+right; break; case '-': ans = left-right; break; case '*': ans = left*right; break; case '/': ans = left/right; break; case '^': ans = pow(left,right); break; default: throw std::invalid_argument("op @evalOP"); } return ans; } /** * NodeOp to string */ std::string NodeOp::toString(){ std::string out; out+= inputs[0] -> toString() + ' ' ; out+= inputs[1] -> toString() + ' ' ; out+= get_op(); out+= ' '; return out; } /** * NodeOp copy */ NodeOp* NodeOp::get_copy(){ Node* left = inputs[0]->get_copy(); Node* right = inputs[1]->get_copy(); return new NodeOp(op,left,right); }
#pragma once #include <filesystem> #include <fstream> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <type_traits> #include <vector> #include "libs/json.hpp" namespace chm { namespace fs = std::filesystem; namespace nl = nlohmann; /** * Vrátí chybový text s cestou konfigurace. * @param[in] p Cesta ke konfiguračnímu souboru. * @return Chybový text. */ std::string configStream(const fs::path& p); /** * Pokusí se o získání pole z JSON objektu. * @tparam T Primitivní typ položky pole. * @param[in] obj JSON objekt. * @param[in] key Klíč pole. * @param[in] path Cesta původního JSON souboru. * @return Pole. */ template<typename T> std::vector<T> getJSONArray( const nl::json& obj, const std::string& key, const fs::path& path ); /** * Pokusí se o získání hodnoty z JSON objektu. * @tparam T Primitivní typ hodnoty. * @param[in] obj JSON objekt. * @param[in] key Klíč hodnoty. * @param[in] path Cesta původního JSON souboru. * @return Získaná hodnota. */ template<typename T> T getJSONValue( const nl::json& obj, const std::string& key, const fs::path& path ); /** * Pokusí se o získání objektu v JSON souboru. * @param[in] p Cesta k JSON souboru. * @return Kořenový JSON objekt. */ nl::json getRoot(const fs::path& p); /** * Vyhodí výjimku při chybě během otevírání souboru. * @param[in] p Cesta k souboru. */ void throwCouldNotOpen(const fs::path& p); /** * Vyhodí výjimku, když hledaný klíč v JSON objektu neexistuje. * @param[in] key Klíč. * @param[in] path Cesta původního JSON souboru. */ void throwMissingKey(const std::string& key, const fs::path& path); /** * Vyhodí výjimku, když hodnota v JSON objektu není správného typu. * @param[in] key Klíč hodnoty. * @param[in] val Hodnota. * @param[in] expectedType Očekávaný typ. * @param[in] path Cesta původního JSON souboru. */ void throwWrongType( const std::string& key, const nl::json& val, const std::string& expectedType, const fs::path& path ); template<typename T> inline T getJSONValue(const nl::json& obj, const std::string& key, const fs::path& path) { if(!obj.contains(key)) throwMissingKey(key, path); const auto& val = obj.at(key); try { return val.get<T>(); } catch(const nl::json::exception&) { throwWrongType(key, val, typeid(T).name(), path); } return T(); } template<typename T> inline std::vector<T> getJSONArray( const nl::json& obj, const std::string& key, const fs::path& path ) { if(!obj.contains(key)) throwMissingKey(key, path); const auto& arr = obj.at(key); if(!arr.is_array()) throwWrongType(key, arr, "JSON type", path); std::vector<T> res; if constexpr(std::is_same<T, nl::json>::value) for(const auto& item : arr) { if(!item.is_object()) throwWrongType(key, item, "JSON object", path); res.push_back(item); } else try { for(const auto& item : arr) res.push_back(item.get<T>()); } catch(const nl::json::exception&) { std::stringstream s; s << configStream(path) << "Key: " << key << "\nExpected type: JSON array of " << typeid(T).name(); throw std::runtime_error(s.str()); } return res; } }
// DialogBarPlayerControl.cpp : implementation file // #include "stdafx.h" #include "Player.h" #include "DialogBarPlayerControl.h" #include "MainFrm.h" #include "PlayerDoc.h" #include "MakeDelegate.h" #include <algorithm> #include <string> #include <sstream> #include <iomanip> using std::setfill; using std::setw; #ifdef _DEBUG #define new DEBUG_NEW #endif enum { RANGE_MAX = 0x7FFF }; enum { WM_SET_TIME = WM_USER + 101 }; namespace { std::basic_string<TCHAR> secondsToString(int seconds) { std::basic_ostringstream<TCHAR> buffer; int s = seconds % 60; int m = (seconds / 60) % 60; int h = seconds / 3600; if (h > 0) { buffer << h << ':'; } buffer << setfill(_T('0')) << setw(2) << m << ':' << setfill(_T('0')) << setw(2) << s; return buffer.str(); } HICON LoadIcon(int idr, int iconSize) { return (HICON) LoadImage( AfxGetApp()->m_hInstance, MAKEINTRESOURCE(idr), IMAGE_ICON, iconSize, iconSize, // use actual size LR_DEFAULTCOLOR); } double GetValueByMouseClick(CWnd* pDlg, CSliderCtrl* pSliderCtrl) { CRect rectClient, rectChannel, rectThumb; pDlg->GetClientRect(rectClient); pSliderCtrl->GetChannelRect(rectChannel); pSliderCtrl->GetThumbRect(rectThumb); rectChannel.DeflateRect(rectThumb.Width() / 2, 0); CPoint mousePt(AfxGetCurrentMessage()->pt); pSliderCtrl->ScreenToClient(&mousePt); return std::clamp( double(mousePt.x - rectClient.left - rectChannel.left) / (rectChannel.right - rectChannel.left), 0., 1.); } } // CDialogBarPlayerControl IMPLEMENT_DYNAMIC(CDialogBarPlayerControl, CPaneDialog) CDialogBarPlayerControl::CDialogBarPlayerControl() : m_pDoc(nullptr) , m_hPlay(NULL) , m_hPause(NULL) , m_hAudio(NULL) , m_hAudioOff(NULL) , m_hFullScreen(NULL) , m_savedVolume(0) , m_oldTotalTime(-1) // unset , m_oldCurrentTime(-1) // unset , m_tracking(false) , m_selStart(0) , m_selEnd(RANGE_MAX) { CDialogTemplate dlgtemplate; if (dlgtemplate.Load(MAKEINTRESOURCE(IDD))) { CSize size; dlgtemplate.GetSizeInPixels(&size); SetMinSize(size); } } CDialogBarPlayerControl::~CDialogBarPlayerControl() { if (m_pDoc) { m_pDoc->framePositionChanged.disconnect(MAKE_DELEGATE(&CDialogBarPlayerControl::onFramePositionChanged, this)); m_pDoc->totalTimeUpdated.disconnect(MAKE_DELEGATE(&CDialogBarPlayerControl::onTotalTimeUpdated, this)); m_pDoc->currentTimeUpdated.disconnect(MAKE_DELEGATE(&CDialogBarPlayerControl::onCurrentTimeUpdated, this)); m_pDoc->rangeStartTimeChanged.disconnect(MAKE_DELEGATE(&CDialogBarPlayerControl::onRangeStartTimeChanged, this)); m_pDoc->rangeEndTimeChanged.disconnect(MAKE_DELEGATE(&CDialogBarPlayerControl::onRangeEndTimeChanged, this)); } } void CDialogBarPlayerControl::DoDataExchange(CDataExchange* pDX) { __super::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDialogBarPlayerControl) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP DDX_Control(pDX, IDC_PROGRESS_SLIDER, m_progressSlider); DDX_Control(pDX, IDC_VOLUME_SLIDER, m_volumeSlider); } BEGIN_MESSAGE_MAP(CDialogBarPlayerControl, CPaneDialog) ON_WM_HSCROLL() ON_UPDATE_COMMAND_UI(IDC_PLAY_PAUSE, &CDialogBarPlayerControl::OnUpdatePlayPause) ON_UPDATE_COMMAND_UI(IDC_AUDIO_ON_OFF, &CDialogBarPlayerControl::OnUpdateAudioOnOff) ON_BN_CLICKED(IDC_PLAY_PAUSE, &CDialogBarPlayerControl::OnClickedPlayPause) ON_BN_CLICKED(IDC_AUDIO_ON_OFF, &CDialogBarPlayerControl::OnClickedAudioOnOff) ON_MESSAGE(WM_SET_TIME, &CDialogBarPlayerControl::OnSetTime) ON_MESSAGE(WM_INITDIALOG, &CDialogBarPlayerControl::HandleInitDialog) ON_UPDATE_COMMAND_UI(IDC_FRAME_STEP, &CDialogBarPlayerControl::OnUpdateFrameStep) ON_UPDATE_COMMAND_UI(IDC_VOLUME_SLIDER, &CDialogBarPlayerControl::OnUpdateVolumeSlider) END_MESSAGE_MAP() // CDialogBarPlayerControl message handlers LRESULT CDialogBarPlayerControl::HandleInitDialog(WPARAM wParam, LPARAM lParam) { __super::HandleInitDialog(wParam, lParam); CRect btnRect; GetDlgItem(IDC_PLAY_PAUSE)->GetClientRect(btnRect); const int iconSizeLimit = min(btnRect.Width() - 2 * GetSystemMetrics(SM_CXBORDER), btnRect.Height() - 2 * GetSystemMetrics(SM_CYBORDER)) * 4 / 5; const int iconSize = min(iconSizeLimit & ((iconSizeLimit > 32)? ~15 : ~7), 48); m_hPlay = LoadIcon(IDI_PLAY, iconSize); m_hPause = LoadIcon(IDI_PAUSE, iconSize); m_hAudio = LoadIcon(IDI_AUDIO, iconSize); m_hAudioOff = LoadIcon(IDI_AUDIO_OFF, iconSize); m_hFullScreen = LoadIcon(IDI_FULL_SCREEN, iconSize); static_cast<CButton*>(GetDlgItem(IDC_PLAY_PAUSE))->SetIcon(m_hPlay); static_cast<CButton*>(GetDlgItem(IDC_AUDIO_ON_OFF))->SetIcon(m_hAudio); static_cast<CButton*>(GetDlgItem(IDC_FULL_SCREEN))->SetIcon(m_hFullScreen); m_progressSlider.SetRange(0, RANGE_MAX); m_progressSlider.SetPageSize(0); m_progressSlider.ModifyStyle(0, TBS_ENABLESELRANGE); m_volumeSlider.SetRange(0, RANGE_MAX); m_volumeSlider.SetPos(RANGE_MAX); m_volumeSlider.SetPageSize(0); return TRUE; } void CDialogBarPlayerControl::setDocument(CPlayerDoc* pDoc) { ASSERT(!m_pDoc); m_pDoc = pDoc; m_volumeSlider.SetPos(int(RANGE_MAX * pDoc->soundVolume())); m_pDoc->framePositionChanged.connect(MAKE_DELEGATE(&CDialogBarPlayerControl::onFramePositionChanged, this)); m_pDoc->totalTimeUpdated.connect(MAKE_DELEGATE(&CDialogBarPlayerControl::onTotalTimeUpdated, this)); m_pDoc->currentTimeUpdated.connect(MAKE_DELEGATE(&CDialogBarPlayerControl::onCurrentTimeUpdated, this)); m_pDoc->rangeStartTimeChanged.connect(MAKE_DELEGATE(&CDialogBarPlayerControl::onRangeStartTimeChanged, this)); m_pDoc->rangeEndTimeChanged.connect(MAKE_DELEGATE(&CDialogBarPlayerControl::onRangeEndTimeChanged, this)); } void CDialogBarPlayerControl::onFramePositionChanged(long long frame, long long total) { if (!m_tracking) { ASSERT(total >= 0); const int pos = (total > 0)? int((frame * RANGE_MAX) / total) : 0; m_progressSlider.SendNotifyMessage(TBM_SETPOS, TRUE, pos); } } enum { MIN_SEL_WIDTH = 50 }; void CDialogBarPlayerControl::onRangeStartTimeChanged(long long frame, long long total) { ASSERT(total >= 0); const int pos = (total > 0) ? int((frame * (RANGE_MAX - MIN_SEL_WIDTH)) / total) : 0; m_selStart = pos; m_progressSlider.SendNotifyMessage(TBM_SETSEL, TRUE, MAKELPARAM(pos, m_selEnd)); } void CDialogBarPlayerControl::onRangeEndTimeChanged(long long frame, long long total) { ASSERT(total >= 0); const int pos = (total > 0) ? int((frame * (RANGE_MAX - MIN_SEL_WIDTH)) / total) + MIN_SEL_WIDTH : 0; m_selEnd = pos; m_progressSlider.SendNotifyMessage(TBM_SETSEL, TRUE, MAKELPARAM(m_selStart, pos)); } void CDialogBarPlayerControl::onTotalTimeUpdated(double secs) { int totalTime = int(secs + 0.5); if (totalTime == m_oldTotalTime) return; m_oldTotalTime = totalTime; SendNotifyMessage(WM_SET_TIME, IDC_TOTAL_TIME, totalTime); } void CDialogBarPlayerControl::onCurrentTimeUpdated(double secs) { int currentTime = int(secs + 0.5); if (currentTime == m_oldCurrentTime) return; m_oldCurrentTime = currentTime; SendNotifyMessage(WM_SET_TIME, IDC_CURRENT_TIME, currentTime); } LRESULT CDialogBarPlayerControl::OnSetTime(WPARAM wParam, LPARAM lParam) { SetDlgItemText(wParam, secondsToString(lParam).c_str()); return 0; } void CDialogBarPlayerControl::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { if (m_pDoc) { if (static_cast<CWnd*>(pScrollBar) == &m_progressSlider) { switch (nSBCode) { case SB_PAGELEFT: case SB_PAGERIGHT: m_pDoc->seekByPercent(GetValueByMouseClick(this, &m_progressSlider)); break; case SB_THUMBTRACK: m_pDoc->seekByPercent(m_progressSlider.GetPos() / double(RANGE_MAX)); m_tracking = true; break; case SB_ENDSCROLL: m_tracking = false; break; } } else if (static_cast<CWnd*>(pScrollBar) == &m_volumeSlider) { if (nSBCode == SB_PAGELEFT || nSBCode == SB_PAGERIGHT) { const double valueByMouseClick = GetValueByMouseClick(this, &m_volumeSlider); m_volumeSlider.SetPos(int(valueByMouseClick * RANGE_MAX)); m_pDoc->setVolume(valueByMouseClick); } else { m_pDoc->setVolume(m_volumeSlider.GetPos() / double(RANGE_MAX)); } } } __super::OnHScroll(nSBCode, nPos, pScrollBar); } void CDialogBarPlayerControl::OnUpdatePlayPause(CCmdUI *pCmdUI) { if (m_pDoc) { pCmdUI->Enable(m_pDoc->isPlaying()); if (pCmdUI->m_pOther) { static_cast<CButton*>(pCmdUI->m_pOther)->SetIcon( m_pDoc->isPaused() ? m_hPlay : m_hPause); } } } void CDialogBarPlayerControl::OnUpdateAudioOnOff(CCmdUI *pCmdUI) { if (m_pDoc) { pCmdUI->Enable(m_pDoc->isPlaying()); if (pCmdUI->m_pOther) { static_cast<CButton*>(pCmdUI->m_pOther)->SetIcon( (m_volumeSlider.GetPos() > 0) ? m_hAudio : m_hAudioOff); } } } void CDialogBarPlayerControl::OnClickedPlayPause() { if (m_pDoc) { if (m_pDoc->isPaused() && IsDlgButtonChecked(IDC_FRAME_STEP)) { m_pDoc->nextFrame(); } else { m_pDoc->pauseResume(); } } } void CDialogBarPlayerControl::OnClickedAudioOnOff() { int newVolume; if (m_savedVolume) { newVolume = m_savedVolume; m_savedVolume = 0; } else { m_savedVolume = m_volumeSlider.GetPos(); newVolume = 0; } m_volumeSlider.SetPos(newVolume); m_pDoc->setVolume(newVolume / double(RANGE_MAX)); } void CDialogBarPlayerControl::OnUpdateFrameStep(CCmdUI *pCmdUI) { if (pCmdUI->m_pOther) { pCmdUI->m_pOther->ShowWindow( (m_pDoc && m_pDoc->isPaused()) ? SW_SHOWNA : SW_HIDE); } } void CDialogBarPlayerControl::OnUpdateVolumeSlider(CCmdUI *pCmdUI) { if (pCmdUI->m_pOther) { pCmdUI->m_pOther->ShowWindow( (m_pDoc && m_pDoc->isPaused()) ? SW_HIDE : SW_SHOWNA); } }
/******************************************************************************* * Copyright 2019-2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <assert.h> #include "dnnl.h" #include "c_types_map.hpp" #include "type_helpers.hpp" #include "utils.hpp" using namespace dnnl::impl; using namespace dnnl::impl::utils; using namespace dnnl::impl::status; using namespace dnnl::impl::prop_kind; using namespace dnnl::impl::types; namespace { status_t lnorm_desc_init(layer_normalization_desc_t *lnorm_desc, prop_kind_t prop_kind, const memory_desc_t *data_desc, const memory_desc_t *stat_desc, const memory_desc_t *diff_data_desc, float epsilon, unsigned flags) { bool args_ok = true && !any_null(lnorm_desc, data_desc) && one_of(prop_kind, forward_training, forward_inference, backward_data, backward) && 2 <= data_desc->ndims && data_desc->ndims <= 5 && IMPLICATION(prop_kind & backward, diff_data_desc != nullptr) && (flags & ~(dnnl_use_global_stats | dnnl_use_scaleshift)) == 0; if (!args_ok) return invalid_arguments; auto ld = layer_normalization_desc_t(); ld.primitive_kind = primitive_kind::layer_normalization; ld.prop_kind = prop_kind; bool runtime_dims_or_strides = memory_desc_wrapper(data_desc).has_runtime_dims_or_strides() || (stat_desc && memory_desc_wrapper(stat_desc) .has_runtime_dims_or_strides()); if (one_of(prop_kind, backward_data, backward)) runtime_dims_or_strides = runtime_dims_or_strides || memory_desc_wrapper(diff_data_desc) .has_runtime_dims_or_strides(); if (runtime_dims_or_strides) return unimplemented; ld.data_desc = *data_desc; ld.stat_desc = zero_md(); ld.diff_data_desc = zero_md(); if (one_of(ld.prop_kind, backward_data, backward)) ld.diff_data_desc = *diff_data_desc; if (stat_desc) ld.stat_desc = *stat_desc; else CHECK(dnnl_memory_desc_init_by_tag(&ld.stat_desc, ld.data_desc.ndims - 1, ld.data_desc.dims, data_type::f32, format_tag::any)); int ndims = data_desc->ndims; dims_t scaleshift_dims = {2, data_desc->dims[ndims - 1]}; dnnl_memory_desc_init_by_tag(&ld.data_scaleshift_desc, 2, scaleshift_dims, data_type::f32, dnnl_nc); ld.diff_data_scaleshift_desc = zero_md(); if (ld.prop_kind == backward) { ld.diff_data_scaleshift_desc = ld.data_scaleshift_desc; } ld.layer_norm_epsilon = epsilon; ld.flags = flags; if (ld.prop_kind == backward_data) { bool consistency = ld.diff_data_desc.ndims == ld.data_desc.ndims && array_cmp(ld.diff_data_desc.dims, ld.data_desc.dims, ld.diff_data_desc.ndims) && ld.data_desc.ndims == ld.stat_desc.ndims + 1 && array_cmp(ld.stat_desc.dims, ld.data_desc.dims, ld.stat_desc.ndims); if (!consistency) return invalid_arguments; } *lnorm_desc = ld; return success; } } // namespace status_t dnnl_layer_normalization_forward_desc_init( layer_normalization_desc_t *lnorm_desc, prop_kind_t prop_kind, const memory_desc_t *data_desc, const memory_desc_t *stat_desc, float epsilon, unsigned flags) { if (!one_of(prop_kind, forward_training, forward_inference)) return invalid_arguments; return lnorm_desc_init(lnorm_desc, prop_kind, data_desc, stat_desc, nullptr, epsilon, flags); } status_t dnnl_layer_normalization_backward_desc_init( layer_normalization_desc_t *lnorm_desc, prop_kind_t prop_kind, const memory_desc_t *diff_data_desc, const memory_desc_t *data_desc, const memory_desc_t *stat_desc, float epsilon, unsigned flags) { if (!one_of(prop_kind, backward, backward_data)) return invalid_arguments; return lnorm_desc_init(lnorm_desc, prop_kind, data_desc, stat_desc, diff_data_desc, epsilon, flags); } // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * WRspice Circuit Simulation and Analysis Tool: Device Library * * * *========================================================================* $Id:$ *========================================================================*/ /* * Author: 2000 Wladek Grabinski; EKV v2.6 Model Upgrade * Author: 1997 Eckhard Brass; EKV v2.5 Model Implementation * (C) 1990 Regents of the University of California. Spice3 Format */ #include "ekvdefs.h" int EKVdev::askModl(const sGENmodel *genmod, int which, IFdata *data) { const sEKVmodel *model = static_cast<const sEKVmodel*>(genmod); IFvalue *value = &data->v; // Need to override this for non-real returns. data->type = IF_REAL; switch(which) { case EKV_MOD_TNOM: value->rValue = model->EKVtnom-CONSTCtoK; return(OK); case EKV_MOD_EKVINT: value->rValue = model->EKVekvint; return(OK); case EKV_MOD_VTO: value->rValue = model->EKVvt0; return(OK); case EKV_MOD_KP: value->rValue = model->EKVkp; return(OK); case EKV_MOD_GAMMA: value->rValue = model->EKVgamma; return(OK); case EKV_MOD_PHI: value->rValue = model->EKVphi; return(OK); case EKV_MOD_COX: value->rValue = model->EKVcox; return(OK); case EKV_MOD_XJ: value->rValue = model->EKVxj; return(OK); case EKV_MOD_THETA: value->rValue = model->EKVtheta; return(OK); case EKV_MOD_E0: value->rValue = model->EKVe0; return(OK); case EKV_MOD_UCRIT: value->rValue = model->EKVucrit; return(OK); case EKV_MOD_DW: value->rValue = model->EKVdw; return(OK); case EKV_MOD_DL: value->rValue = model->EKVdl; return(OK); case EKV_MOD_LAMBDA: value->rValue = model->EKVlambda; return(OK); case EKV_MOD_WETA: value->rValue = model->EKVweta; return(OK); case EKV_MOD_LETA: value->rValue = model->EKVleta; return(OK); case EKV_MOD_IBA: value->rValue = model->EKViba; return(OK); case EKV_MOD_IBB: value->rValue = model->EKVibb; return(OK); case EKV_MOD_IBN: value->rValue = model->EKVibn; return(OK); case EKV_MOD_Q0: value->rValue = model->EKVq0; return(OK); case EKV_MOD_LK: value->rValue = model->EKVlk; return(OK); case EKV_MOD_TCV: value->rValue = model->EKVtcv; return(OK); case EKV_MOD_BEX: value->rValue = model->EKVbex; return(OK); case EKV_MOD_UCEX: value->rValue = model->EKVucex; return(OK); case EKV_MOD_IBBT: value->rValue = model->EKVibbt; return(OK); case EKV_MOD_NQS: value->rValue = model->EKVnqs; return(OK); case EKV_MOD_SATLIM: value->rValue = model->EKVsatlim; return(OK); case EKV_MOD_KF: value->rValue = model->EKVfNcoef; break; case EKV_MOD_AF: value->rValue = model->EKVfNexp; break; case EKV_MOD_IS: value->rValue = model->EKVjctSatCur; return(OK); case EKV_MOD_JS: value->rValue = model->EKVjctSatCurDensity; return(OK); case EKV_MOD_JSW: value->rValue = model->EKVjsw; return(OK); case EKV_MOD_N: value->rValue = model->EKVn; return(OK); case EKV_MOD_CBD: value->rValue = model->EKVcapBD; return(OK); case EKV_MOD_CBS: value->rValue = model->EKVcapBS; return(OK); case EKV_MOD_CJ: value->rValue = model->EKVbulkCapFactor; return(OK); case EKV_MOD_CJSW: value->rValue = model->EKVsideWallCapFactor; return(OK); case EKV_MOD_MJ: value->rValue = model->EKVbulkJctBotGradingCoeff; return(OK); case EKV_MOD_MJSW: value->rValue = model->EKVbulkJctSideGradingCoeff; return(OK); case EKV_MOD_FC: value->rValue = model->EKVfwdCapDepCoeff; return(OK); case EKV_MOD_PB: value->rValue = model->EKVbulkJctPotential; return(OK); case EKV_MOD_PBSW: value->rValue = model->EKVpbsw; return(OK); case EKV_MOD_TT: value->rValue = model->EKVtt; return(OK); case EKV_MOD_CGSO: value->rValue = model->EKVgateSourceOverlapCapFactor; return(OK); case EKV_MOD_CGDO: value->rValue = model->EKVgateDrainOverlapCapFactor; return(OK); case EKV_MOD_CGBO: value->rValue = model->EKVgateBulkOverlapCapFactor; return(OK); case EKV_MOD_RD: value->rValue = model->EKVdrainResistance; return(OK); case EKV_MOD_RS: value->rValue = model->EKVsourceResistance; return(OK); case EKV_MOD_RSH: value->rValue = model->EKVsheetResistance; return(OK); case EKV_MOD_RSC: value->rValue = model->EKVrsc; return(OK); case EKV_MOD_RDC: value->rValue = model->EKVrdc; return(OK); case EKV_MOD_XTI: value->rValue = model->EKVxti; return(OK); case EKV_MOD_TR1: value->rValue = model->EKVtr1; return(OK); case EKV_MOD_TR2: value->rValue = model->EKVtr2; return(OK); case EKV_MOD_NLEVEL: value->rValue = model->EKVnlevel; return(OK); case EKV_MOD_TYPE: if (model->EKVtype > 0) value->sValue = "nmos"; else value->sValue = "pmos"; data->type = IF_STRING; return(OK); // SRW case EKV_MOD_XQC: value->rValue = model->EKVxqcGiven ? 1.0 : 0.0; return (OK); default: return(E_BADPARM); } /* NOTREACHED */ return(OK); }
#include "nprotocolbase.h" #include "nprotocolbase_p.h" #include <algorithm> #include <cassert> NProtocolBase::NProtocolBase() : d(new NProtocolBase_P()) {} NProtocolBase::~NProtocolBase() { delete d; } size_t NProtocolBase::totalBytes() const { return d->totalBytes_; } void NProtocolBase::appendItem(NProtocolItemBase *item) { assert( (std::find(d->items_.begin(), d->items_.end(), item) == d->items_.end())); if (d->items_.empty()) { auto firstItem = dynamic_cast<NConstantByteArrayItem *>(item); assert(firstItem); d->headerItem_ = firstItem; item->setAddress(0); d->totalBytes_ = 0; } else { item->setAddress(d->items_.back()->address() + d->items_.back()->bytes()); } if (!d->bytesOfProtocolItem_) { d->bytesOfProtocolItem_ = dynamic_cast<NBytesOfProtocolItem *>(item); } d->items_.push_back(item); d->totalBytes_ += item->bytes(); } std::vector<NProtocolItemBase *> NProtocolBase::items() const { return d->items_; } void NProtocolBase::setDataHandle(std::function<void()> handle) { d->dataHandle_ = handle; } NProtocolBase_P::~NProtocolBase_P() { for (auto item : items_) { delete item; } } bool NProtocolBase_P::updateItemsAddressAndBytes(const char *byte) { NProtocolItemBase *prevItem = items_.front(); totalBytes_ = prevItem->bytes(); for (size_t i = 1; i < items_.size(); ++i) { items_.at(i)->setAddress(prevItem->address() + prevItem->bytes()); if (items_.at(i)->updateItemBytes(byte)) { prevItem = items_.at(i); totalBytes_ += prevItem->bytes(); } else { return false; } } return true; }
#include <iostream> void f1(int (*)(int)) { std::cout << "f1" << std::endl; } void f2(char (*)(int)) { std::cout << "f2" << std::endl; } void g(int (*)(int)) { std::cout << "g(int (*)(int))" << std::endl; } void g(char (*)(char)) { std::cout << "g(char (*)(char))" << std::endl; } void h(int (*)(int)) { std::cout << "h(int (*)(int))" << std::endl; } void h(char (*)(int)) { std::cout << "h(char (*)(int))" << std::endl; } // generic lambda auto glambda = [](auto a) { return a; }; int main() { f1(glambda); f2(glambda); g(glambda); h(glambda); }
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/cont/CellLocatorBoundingIntervalHierarchy.h> #include <vtkm/Bounds.h> #include <vtkm/Types.h> #include <vtkm/VecFromPortalPermute.h> #include <vtkm/cont/Algorithm.h> #include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandleConstant.h> #include <vtkm/cont/ArrayHandleCounting.h> #include <vtkm/cont/ArrayHandlePermutation.h> #include <vtkm/cont/ArrayHandleReverse.h> #include <vtkm/cont/ArrayHandleTransform.h> #include <vtkm/cont/DeviceAdapterAlgorithm.h> #include <vtkm/cont/ErrorBadDevice.h> #include <vtkm/exec/CellLocatorBoundingIntervalHierarchyExec.h> #include <vtkm/cont/Invoker.h> #include <vtkm/worklet/WorkletMapField.h> #include <vtkm/worklet/WorkletMapTopology.h> namespace vtkm { namespace cont { using IdArrayHandle = vtkm::cont::ArrayHandle<vtkm::Id>; using IdPermutationArrayHandle = vtkm::cont::ArrayHandlePermutation<IdArrayHandle, IdArrayHandle>; using CoordsArrayHandle = vtkm::cont::ArrayHandle<vtkm::FloatDefault>; using CoordsPermutationArrayHandle = vtkm::cont::ArrayHandlePermutation<IdArrayHandle, CoordsArrayHandle>; using CountingIdArrayHandle = vtkm::cont::ArrayHandleCounting<vtkm::Id>; using RangeArrayHandle = vtkm::cont::ArrayHandle<vtkm::Range>; using RangePermutationArrayHandle = vtkm::cont::ArrayHandlePermutation<IdArrayHandle, RangeArrayHandle>; using SplitArrayHandle = vtkm::cont::ArrayHandle<vtkm::worklet::spatialstructure::TreeNode>; using SplitPermutationArrayHandle = vtkm::cont::ArrayHandlePermutation<IdArrayHandle, SplitArrayHandle>; using SplitPropertiesArrayHandle = vtkm::cont::ArrayHandle<vtkm::worklet::spatialstructure::SplitProperties>; namespace { IdArrayHandle CalculateSegmentSizes(const IdArrayHandle& segmentIds, vtkm::Id numCells) { IdArrayHandle discardKeys; IdArrayHandle segmentSizes; vtkm::cont::Algorithm::ReduceByKey(segmentIds, vtkm::cont::ArrayHandleConstant<vtkm::Id>(1, numCells), discardKeys, segmentSizes, vtkm::Add()); return segmentSizes; } IdArrayHandle GenerateSegmentIds(const IdArrayHandle& segmentSizes, vtkm::Id numCells) { // Compact segment ids, removing non-contiguous values. // 1. Perform ScanInclusive to calculate the end positions of each segment IdArrayHandle segmentEnds; vtkm::cont::Algorithm::ScanInclusive(segmentSizes, segmentEnds); // 2. Perform UpperBounds to perform the final compaction. IdArrayHandle segmentIds; vtkm::cont::Algorithm::UpperBounds( segmentEnds, vtkm::cont::ArrayHandleCounting<vtkm::Id>(0, 1, numCells), segmentIds); return segmentIds; } void CalculatePlaneSplitCost(vtkm::IdComponent planeIndex, vtkm::IdComponent numPlanes, RangePermutationArrayHandle& segmentRanges, RangeArrayHandle& ranges, CoordsArrayHandle& coords, IdArrayHandle& segmentIds, SplitPropertiesArrayHandle& splits, vtkm::IdComponent index, vtkm::IdComponent numTotalPlanes) { vtkm::cont::Invoker invoker; // Make candidate split plane array vtkm::cont::ArrayHandle<vtkm::FloatDefault> splitPlanes; vtkm::worklet::spatialstructure::SplitPlaneCalculatorWorklet splitPlaneCalcWorklet(planeIndex, numPlanes); invoker(splitPlaneCalcWorklet, segmentRanges, splitPlanes); // Check if a point is to the left of the split plane or right vtkm::cont::ArrayHandle<vtkm::Id> isLEQOfSplitPlane, isROfSplitPlane; invoker(vtkm::worklet::spatialstructure::LEQWorklet{}, coords, splitPlanes, isLEQOfSplitPlane, isROfSplitPlane); // Count of points to the left vtkm::cont::ArrayHandle<vtkm::Id> pointsToLeft; IdArrayHandle discardKeys; vtkm::cont::Algorithm::ReduceByKey( segmentIds, isLEQOfSplitPlane, discardKeys, pointsToLeft, vtkm::Add()); // Count of points to the right vtkm::cont::ArrayHandle<vtkm::Id> pointsToRight; vtkm::cont::Algorithm::ReduceByKey( segmentIds, isROfSplitPlane, discardKeys, pointsToRight, vtkm::Add()); isLEQOfSplitPlane.ReleaseResourcesExecution(); isROfSplitPlane.ReleaseResourcesExecution(); // Calculate Lmax and Rmin vtkm::cont::ArrayHandle<vtkm::Range> lMaxRanges; { vtkm::cont::ArrayHandle<vtkm::Range> leqRanges; vtkm::worklet::spatialstructure::FilterRanges<true> worklet; invoker(worklet, coords, splitPlanes, ranges, leqRanges); vtkm::cont::Algorithm::ReduceByKey( segmentIds, leqRanges, discardKeys, lMaxRanges, vtkm::worklet::spatialstructure::RangeAdd()); } vtkm::cont::ArrayHandle<vtkm::Range> rMinRanges; { vtkm::cont::ArrayHandle<vtkm::Range> rRanges; vtkm::worklet::spatialstructure::FilterRanges<false> worklet; invoker(worklet, coords, splitPlanes, ranges, rRanges); vtkm::cont::Algorithm::ReduceByKey( segmentIds, rRanges, discardKeys, rMinRanges, vtkm::worklet::spatialstructure::RangeAdd()); } vtkm::cont::ArrayHandle<vtkm::FloatDefault> segmentedSplitPlanes; vtkm::cont::Algorithm::ReduceByKey( segmentIds, splitPlanes, discardKeys, segmentedSplitPlanes, vtkm::Minimum()); // Calculate costs vtkm::worklet::spatialstructure::SplitPropertiesCalculator splitPropertiesCalculator( index, numTotalPlanes + 1); invoker(splitPropertiesCalculator, pointsToLeft, pointsToRight, lMaxRanges, rMinRanges, segmentedSplitPlanes, splits); } void CalculateSplitCosts(vtkm::IdComponent numPlanes, RangePermutationArrayHandle& segmentRanges, RangeArrayHandle& ranges, CoordsArrayHandle& coords, IdArrayHandle& segmentIds, SplitPropertiesArrayHandle& splits) { for (vtkm::IdComponent planeIndex = 0; planeIndex < numPlanes; ++planeIndex) { CalculatePlaneSplitCost(planeIndex, numPlanes, segmentRanges, ranges, coords, segmentIds, splits, planeIndex, numPlanes); } // Calculate median costs CalculatePlaneSplitCost( 0, 1, segmentRanges, ranges, coords, segmentIds, splits, numPlanes, numPlanes); } IdArrayHandle CalculateSplitScatterIndices(const IdArrayHandle& cellIds, const IdArrayHandle& leqFlags, const IdArrayHandle& segmentIds) { vtkm::cont::Invoker invoker; // Count total number of true flags preceding in segment IdArrayHandle trueFlagCounts; vtkm::cont::Algorithm::ScanExclusiveByKey(segmentIds, leqFlags, trueFlagCounts); // Make a counting iterator. CountingIdArrayHandle counts(0, 1, cellIds.GetNumberOfValues()); // Total number of elements in previous segment vtkm::cont::ArrayHandle<vtkm::Id> countPreviousSegments; vtkm::cont::Algorithm::ScanInclusiveByKey( segmentIds, counts, countPreviousSegments, vtkm::Minimum()); // Total number of false flags so far in segment vtkm::cont::ArrayHandleTransform<IdArrayHandle, vtkm::worklet::spatialstructure::Invert> flagsInverse(leqFlags, vtkm::worklet::spatialstructure::Invert()); vtkm::cont::ArrayHandle<vtkm::Id> runningFalseFlagCount; vtkm::cont::Algorithm::ScanInclusiveByKey( segmentIds, flagsInverse, runningFalseFlagCount, vtkm::Add()); // Total number of false flags in segment IdArrayHandle totalFalseFlagSegmentCount = vtkm::worklet::spatialstructure::ReverseScanInclusiveByKey( segmentIds, runningFalseFlagCount, vtkm::Maximum()); // if point is to the left, // index = total number in previous segments + total number of false flags in this segment + total number of trues in previous segment // else // index = total number in previous segments + number of falses preceding it in the segment. IdArrayHandle scatterIndices; invoker(vtkm::worklet::spatialstructure::SplitIndicesCalculator{}, leqFlags, trueFlagCounts, countPreviousSegments, runningFalseFlagCount, totalFalseFlagSegmentCount, scatterIndices); return scatterIndices; } } // anonymous namespace CellLocatorBoundingIntervalHierarchy::~CellLocatorBoundingIntervalHierarchy() = default; void CellLocatorBoundingIntervalHierarchy::Build() { VTKM_LOG_SCOPE(vtkm::cont::LogLevel::Perf, "CellLocatorBoundingIntervalHierarchy::Build"); vtkm::cont::Invoker invoker; vtkm::cont::DynamicCellSet cellSet = this->GetCellSet(); vtkm::Id numCells = cellSet.GetNumberOfCells(); vtkm::cont::CoordinateSystem coords = this->GetCoordinates(); auto points = coords.GetDataAsMultiplexer(); //std::cout << "No of cells: " << numCells << "\n"; //std::cout.precision(3); //START_TIMER(s11); IdArrayHandle cellIds; vtkm::cont::Algorithm::Copy(CountingIdArrayHandle(0, 1, numCells), cellIds); IdArrayHandle segmentIds; vtkm::cont::Algorithm::Copy(vtkm::cont::ArrayHandleConstant<vtkm::Id>(0, numCells), segmentIds); //PRINT_TIMER("1.1", s11); //START_TIMER(s12); CoordsArrayHandle centerXs, centerYs, centerZs; RangeArrayHandle xRanges, yRanges, zRanges; invoker(vtkm::worklet::spatialstructure::CellRangesExtracter{}, cellSet, points, xRanges, yRanges, zRanges, centerXs, centerYs, centerZs); //PRINT_TIMER("1.2", s12); bool done = false; //vtkm::IdComponent iteration = 0; vtkm::Id nodesIndexOffset = 0; vtkm::Id numSegments = 1; IdArrayHandle discardKeys; IdArrayHandle segmentSizes; segmentSizes.Allocate(1); segmentSizes.WritePortal().Set(0, numCells); this->ProcessedCellIds.Allocate(numCells); vtkm::Id cellIdsOffset = 0; IdArrayHandle parentIndices; parentIndices.Allocate(1); parentIndices.WritePortal().Set(0, -1); while (!done) { //std::cout << "**** Iteration " << (++iteration) << " ****\n"; //Output(segmentSizes); //START_TIMER(s21); // Calculate the X, Y, Z bounding ranges for each segment RangeArrayHandle perSegmentXRanges, perSegmentYRanges, perSegmentZRanges; vtkm::cont::Algorithm::ReduceByKey( segmentIds, xRanges, discardKeys, perSegmentXRanges, vtkm::Add()); vtkm::cont::Algorithm::ReduceByKey( segmentIds, yRanges, discardKeys, perSegmentYRanges, vtkm::Add()); vtkm::cont::Algorithm::ReduceByKey( segmentIds, zRanges, discardKeys, perSegmentZRanges, vtkm::Add()); //PRINT_TIMER("2.1", s21); // Expand the per segment bounding ranges, to per cell; RangePermutationArrayHandle segmentXRanges(segmentIds, perSegmentXRanges); RangePermutationArrayHandle segmentYRanges(segmentIds, perSegmentYRanges); RangePermutationArrayHandle segmentZRanges(segmentIds, perSegmentZRanges); //START_TIMER(s22); // Calculate split costs for NumPlanes split planes, across X, Y and Z dimensions vtkm::Id numSplitPlanes = numSegments * (this->NumPlanes + 1); vtkm::cont::ArrayHandle<vtkm::worklet::spatialstructure::SplitProperties> xSplits, ySplits, zSplits; xSplits.Allocate(numSplitPlanes); ySplits.Allocate(numSplitPlanes); zSplits.Allocate(numSplitPlanes); CalculateSplitCosts(this->NumPlanes, segmentXRanges, xRanges, centerXs, segmentIds, xSplits); CalculateSplitCosts(this->NumPlanes, segmentYRanges, yRanges, centerYs, segmentIds, ySplits); CalculateSplitCosts(this->NumPlanes, segmentZRanges, zRanges, centerZs, segmentIds, zSplits); //PRINT_TIMER("2.2", s22); segmentXRanges.ReleaseResourcesExecution(); segmentYRanges.ReleaseResourcesExecution(); segmentZRanges.ReleaseResourcesExecution(); //START_TIMER(s23); // Select best split plane and dimension across X, Y, Z dimension, per segment SplitArrayHandle segmentSplits; vtkm::cont::ArrayHandle<vtkm::FloatDefault> segmentPlanes; vtkm::cont::ArrayHandle<vtkm::Id> splitChoices; CountingIdArrayHandle indices(0, 1, numSegments); vtkm::worklet::spatialstructure::SplitSelector worklet( this->NumPlanes, this->MaxLeafSize, this->NumPlanes + 1); invoker(worklet, indices, xSplits, ySplits, zSplits, segmentSizes, segmentSplits, segmentPlanes, splitChoices); //PRINT_TIMER("2.3", s23); // Expand the per segment split plane to per cell SplitPermutationArrayHandle splits(segmentIds, segmentSplits); CoordsPermutationArrayHandle planes(segmentIds, segmentPlanes); //START_TIMER(s31); IdArrayHandle leqFlags; invoker(vtkm::worklet::spatialstructure::CalculateSplitDirectionFlag{}, centerXs, centerYs, centerZs, splits, planes, leqFlags); //PRINT_TIMER("3.1", s31); //START_TIMER(s32); IdArrayHandle scatterIndices = CalculateSplitScatterIndices(cellIds, leqFlags, segmentIds); IdArrayHandle newSegmentIds; IdPermutationArrayHandle sizes(segmentIds, segmentSizes); invoker(vtkm::worklet::spatialstructure::SegmentSplitter{ this->MaxLeafSize }, segmentIds, leqFlags, sizes, newSegmentIds); //PRINT_TIMER("3.2", s32); //START_TIMER(s33); vtkm::cont::ArrayHandle<vtkm::Id> choices; vtkm::cont::Algorithm::Copy(IdPermutationArrayHandle(segmentIds, splitChoices), choices); cellIds = vtkm::worklet::spatialstructure::ScatterArray(cellIds, scatterIndices); segmentIds = vtkm::worklet::spatialstructure::ScatterArray(segmentIds, scatterIndices); newSegmentIds = vtkm::worklet::spatialstructure::ScatterArray(newSegmentIds, scatterIndices); xRanges = vtkm::worklet::spatialstructure::ScatterArray(xRanges, scatterIndices); yRanges = vtkm::worklet::spatialstructure::ScatterArray(yRanges, scatterIndices); zRanges = vtkm::worklet::spatialstructure::ScatterArray(zRanges, scatterIndices); centerXs = vtkm::worklet::spatialstructure::ScatterArray(centerXs, scatterIndices); centerYs = vtkm::worklet::spatialstructure::ScatterArray(centerYs, scatterIndices); centerZs = vtkm::worklet::spatialstructure::ScatterArray(centerZs, scatterIndices); choices = vtkm::worklet::spatialstructure::ScatterArray(choices, scatterIndices); //PRINT_TIMER("3.3", s33); // Move the cell ids at leafs to the processed cellids list //START_TIMER(s41); IdArrayHandle nonSplitSegmentSizes; invoker(vtkm::worklet::spatialstructure::NonSplitIndexCalculator{ this->MaxLeafSize }, segmentSizes, nonSplitSegmentSizes); IdArrayHandle nonSplitSegmentIndices; vtkm::cont::Algorithm::ScanExclusive(nonSplitSegmentSizes, nonSplitSegmentIndices); IdArrayHandle runningSplitSegmentCounts; vtkm::Id numNewSegments = vtkm::cont::Algorithm::ScanExclusive(splitChoices, runningSplitSegmentCounts); //PRINT_TIMER("4.1", s41); //START_TIMER(s42); IdArrayHandle doneCellIds; vtkm::cont::Algorithm::CopyIf( cellIds, choices, doneCellIds, vtkm::worklet::spatialstructure::Invert()); vtkm::cont::Algorithm::CopySubRange( doneCellIds, 0, doneCellIds.GetNumberOfValues(), this->ProcessedCellIds, cellIdsOffset); cellIds = vtkm::worklet::spatialstructure::CopyIfArray(cellIds, choices); newSegmentIds = vtkm::worklet::spatialstructure::CopyIfArray(newSegmentIds, choices); xRanges = vtkm::worklet::spatialstructure::CopyIfArray(xRanges, choices); yRanges = vtkm::worklet::spatialstructure::CopyIfArray(yRanges, choices); zRanges = vtkm::worklet::spatialstructure::CopyIfArray(zRanges, choices); centerXs = vtkm::worklet::spatialstructure::CopyIfArray(centerXs, choices); centerYs = vtkm::worklet::spatialstructure::CopyIfArray(centerYs, choices); centerZs = vtkm::worklet::spatialstructure::CopyIfArray(centerZs, choices); //PRINT_TIMER("4.2", s42); //START_TIMER(s43); // Make a new nodes with enough nodes for the current level, copying over the old one vtkm::Id nodesSize = this->Nodes.GetNumberOfValues() + numSegments; vtkm::cont::ArrayHandle<vtkm::exec::CellLocatorBoundingIntervalHierarchyNode> newTree; newTree.Allocate(nodesSize); vtkm::cont::Algorithm::CopySubRange(this->Nodes, 0, this->Nodes.GetNumberOfValues(), newTree); IdArrayHandle nextParentIndices; nextParentIndices.Allocate(2 * numNewSegments); CountingIdArrayHandle nodesIndices(nodesIndexOffset, 1, numSegments); vtkm::worklet::spatialstructure::TreeLevelAdder nodesAdder( cellIdsOffset, nodesSize, this->MaxLeafSize); invoker(nodesAdder, nodesIndices, segmentSplits, nonSplitSegmentIndices, segmentSizes, runningSplitSegmentCounts, parentIndices, newTree, nextParentIndices); nodesIndexOffset = nodesSize; cellIdsOffset += doneCellIds.GetNumberOfValues(); this->Nodes = newTree; //PRINT_TIMER("4.3", s43); //START_TIMER(s51); segmentIds = newSegmentIds; segmentSizes = CalculateSegmentSizes(segmentIds, segmentIds.GetNumberOfValues()); segmentIds = GenerateSegmentIds(segmentSizes, segmentIds.GetNumberOfValues()); IdArrayHandle uniqueSegmentIds; vtkm::cont::Algorithm::Copy(segmentIds, uniqueSegmentIds); vtkm::cont::Algorithm::Unique(uniqueSegmentIds); numSegments = uniqueSegmentIds.GetNumberOfValues(); done = segmentIds.GetNumberOfValues() == 0; parentIndices = nextParentIndices; //PRINT_TIMER("5.1", s51); //std::cout << "Iteration time: " << iterationTimer.GetElapsedTime() << "\n"; } //std::cout << "Total time: " << totalTimer.GetElapsedTime() << "\n"; } namespace { struct CellLocatorBIHPrepareForExecutionFunctor { template <typename DeviceAdapter, typename CellSetType> bool operator()( DeviceAdapter, const CellSetType& cellset, vtkm::cont::Token& token, vtkm::cont::VirtualObjectHandle<vtkm::exec::CellLocator>& bihExec, const vtkm::cont::ArrayHandle<vtkm::exec::CellLocatorBoundingIntervalHierarchyNode>& nodes, const vtkm::cont::ArrayHandle<vtkm::Id>& processedCellIds, const vtkm::cont::CoordinateSystem::MultiplexerArrayType& coords) const { using ExecutionType = vtkm::exec::CellLocatorBoundingIntervalHierarchyExec<DeviceAdapter, CellSetType>; ExecutionType* execObject = new ExecutionType(nodes, processedCellIds, cellset, coords, DeviceAdapter(), token); bihExec.Reset(execObject); return true; } }; struct BIHCellSetCaster { template <typename CellSet, typename... Args> void operator()(CellSet&& cellset, vtkm::cont::DeviceAdapterId device, vtkm::cont::Token& token, Args&&... args) const { //We need to go though CastAndCall first const bool success = vtkm::cont::TryExecuteOnDevice(device, CellLocatorBIHPrepareForExecutionFunctor(), cellset, token, std::forward<Args>(args)...); if (!success) { throwFailedRuntimeDeviceTransfer("BoundingIntervalHierarchy", device); } } }; } const vtkm::exec::CellLocator* CellLocatorBoundingIntervalHierarchy::PrepareForExecution( vtkm::cont::DeviceAdapterId device, vtkm::cont::Token& token) const { this->GetCellSet().CastAndCall(BIHCellSetCaster{}, device, token, this->ExecutionObjectHandle, this->Nodes, this->ProcessedCellIds, this->GetCoordinates().GetDataAsMultiplexer()); return this->ExecutionObjectHandle.PrepareForExecution(device, token); ; } } //namespace cont } //namespace vtkm
/* * QR Code Generator * Copyright (C) 2014 Stefano BARILETTI <hackaroth@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "QRCodeV17.h" #include <string.h> #include <iomanip> QRCodeV17::QRCodeV17() : QRCode() { Version = 17; Modules = 85; REMINDER_BIT_COUNT = 3; VersionInfoRequired = true; InitCapabilities(); InitECInfo(); InitAlignementPatterns(); } //------------------------------------------------------------------- QRCodeV17::~QRCodeV17() { } //---------------------------------------------------------------- void QRCodeV17::InitCapabilities(void) { CAP_L_CORRECTION_NUMERIC = 1548; CAP_L_CORRECTION_ALPHANUMERIC = 938; CAP_L_CORRECTION_BYTE = 644; CAP_L_CORRECTION_KANJI = 397; CAP_M_CORRECTION_NUMERIC = 1212; CAP_M_CORRECTION_ALPHANUMERIC = 734; CAP_M_CORRECTION_BYTE = 504; CAP_M_CORRECTION_KANJI = 310; CAP_Q_CORRECTION_NUMERIC = 876; CAP_Q_CORRECTION_ALPHANUMERIC = 531; CAP_Q_CORRECTION_BYTE = 364; CAP_Q_CORRECTION_KANJI = 224; CAP_H_CORRECTION_NUMERIC = 674; CAP_H_CORRECTION_ALPHANUMERIC = 408; CAP_H_CORRECTION_BYTE = 280; CAP_H_CORRECTION_KANJI = 173; } //---------------------------------------------------------------- void QRCodeV17::InitECInfo(void) { ECL_LOW_EC_INFO.TotalCW = 647; ECL_LOW_EC_INFO.EC_CWPerBlocks = 28; ECL_LOW_EC_INFO.BlocksGroup1 = 1; ECL_LOW_EC_INFO.BlocksGroup2 = 5; ECL_LOW_EC_INFO.CWBlockGroup1 = 107; ECL_LOW_EC_INFO.CWBlockGroup2 = 108; ECL_MEDIUM_EC_INFO.TotalCW = 507; ECL_MEDIUM_EC_INFO.EC_CWPerBlocks = 28; ECL_MEDIUM_EC_INFO.BlocksGroup1 = 10; ECL_MEDIUM_EC_INFO.BlocksGroup2 = 1; ECL_MEDIUM_EC_INFO.CWBlockGroup1 = 46; ECL_MEDIUM_EC_INFO.CWBlockGroup2 = 47; ECL_QUALITY_EC_INFO.TotalCW = 367; ECL_QUALITY_EC_INFO.EC_CWPerBlocks = 28; ECL_QUALITY_EC_INFO.BlocksGroup1 = 1; ECL_QUALITY_EC_INFO.BlocksGroup2 = 15; ECL_QUALITY_EC_INFO.CWBlockGroup1 = 22; ECL_QUALITY_EC_INFO.CWBlockGroup2 = 23; ECL_HIGH_EC_INFO.TotalCW = 283; ECL_HIGH_EC_INFO.EC_CWPerBlocks = 28; ECL_HIGH_EC_INFO.BlocksGroup1 = 2; ECL_HIGH_EC_INFO.BlocksGroup2 = 17; ECL_HIGH_EC_INFO.CWBlockGroup1 = 14; ECL_HIGH_EC_INFO.CWBlockGroup2 = 15; } //---------------------------------------------------------------- void QRCodeV17::InitAlignementPatterns(void) { AlignementPatterns.push_back(Point(30,6)); AlignementPatterns.push_back(Point(6,30)); AlignementPatterns.push_back(Point(30,30)); AlignementPatterns.push_back(Point(6,54)); AlignementPatterns.push_back(Point(54,6)); AlignementPatterns.push_back(Point(30,54)); AlignementPatterns.push_back(Point(54,30)); AlignementPatterns.push_back(Point(54,54)); AlignementPatterns.push_back(Point(30,78)); AlignementPatterns.push_back(Point(78,30)); AlignementPatterns.push_back(Point(54,78)); AlignementPatterns.push_back(Point(78,54)); AlignementPatterns.push_back(Point(78,78)); } //----------------------------------------------------------------
#include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); /* * Complete the 'minimumDistances' function below. * * The function is expected to return an INTEGER. * The function accepts INTEGER_ARRAY a as parameter. */ int minimumDistances(vector<int> a) { int n = a.size(); int temp=0,diff=-1; for(int i=0;i<n-1;i++){ for(int j=i+1;j<n;j++){ if(a[i]==a[j]){ temp=j-i; if(temp>diff && diff==-1){ diff=temp; } else if(temp<diff){ diff=temp; } } } } return diff; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string n_temp; getline(cin, n_temp); int n = stoi(ltrim(rtrim(n_temp))); string a_temp_temp; getline(cin, a_temp_temp); vector<string> a_temp = split(rtrim(a_temp_temp)); vector<int> a(n); for (int i = 0; i < n; i++) { int a_item = stoi(a_temp[i]); a[i] = a_item; } int result = minimumDistances(a); fout << result << "\n"; fout.close(); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end() ); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // type_traits // aligned_union<size_t Len, class ...Types> // Issue 3034 added: // The member typedef type shall be a trivial standard-layout type. #include <type_traits> #include "test_macros.h" int main(int, char**) { { typedef std::aligned_union<10, char >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<10, char>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 1, ""); static_assert(sizeof(T1) == 10, ""); } { typedef std::aligned_union<10, short >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<10, short>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 2, ""); static_assert(sizeof(T1) == 10, ""); } { typedef std::aligned_union<10, int >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<10, int>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 4, ""); static_assert(sizeof(T1) == 12, ""); } { typedef std::aligned_union<10, double >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<10, double>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 8, ""); static_assert(sizeof(T1) == 16, ""); } { typedef std::aligned_union<10, short, char >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<10, short, char>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 2, ""); static_assert(sizeof(T1) == 10, ""); } { typedef std::aligned_union<10, char, short >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<10, char, short>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 2, ""); static_assert(sizeof(T1) == 10, ""); } { typedef std::aligned_union<2, int, char, short >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<2, int, char, short>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 4, ""); static_assert(sizeof(T1) == 4, ""); } { typedef std::aligned_union<2, char, int, short >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<2, char, int, short>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 4, ""); static_assert(sizeof(T1) == 4, ""); } { typedef std::aligned_union<2, char, short, int >::type T1; #if TEST_STD_VER > 11 ASSERT_SAME_TYPE(T1, std::aligned_union_t<2, char, short, int>); #endif static_assert(std::is_trivial<T1>::value, ""); static_assert(std::is_standard_layout<T1>::value, ""); static_assert(std::alignment_of<T1>::value == 4, ""); static_assert(sizeof(T1) == 4, ""); } return 0; }
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "Maestro_precompiled.h" #include <IMovieSystem.h> #include <Range.h> #include <AnimKey.h> #include <Maestro/Types/AssetBlendKey.h> #include "AnimSerializer.h" void AnimSerializer::ReflectAnimTypes(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context); serializeContext != nullptr) { // Reflection for Maestro's AZ_TYPE_INFO'ed classes serializeContext->Class<CAnimParamType>() ->Version(1) ->Field("Type", &CAnimParamType::m_type) ->Field("Name", &CAnimParamType::m_name); serializeContext->Class<Range>() ->Field("Start", &Range::start) ->Field("End", &Range::end); // Curve Key classes serializeContext->Class<IKey>() ->Field("Time", &IKey::time) ->Field("Flags", &IKey::flags); serializeContext->Class<AZ::IAssetBlendKey, ITimeRangeKey>() ->Field("AssetId", &AZ::IAssetBlendKey::m_assetId) ->Field("Description", &AZ::IAssetBlendKey::m_description) ->Field("BlendInTime", &AZ::IAssetBlendKey::m_blendInTime) ->Field("BlendOutTime", &AZ::IAssetBlendKey::m_blendOutTime); serializeContext->Class<IBoolKey, IKey>(); serializeContext->Class<ICaptureKey, IKey>() ->Field("Duration", &ICaptureKey::duration) ->Field("TimeStep", &ICaptureKey::timeStep) ->Field("Folder", &ICaptureKey::folder) ->Field("Once", &ICaptureKey::once) ->Field("FilePrefix", &ICaptureKey::prefix); serializeContext->Class<ICharacterKey, ITimeRangeKey>() ->Field("Animation", &ICharacterKey::m_animation) ->Field("BlendGap", &ICharacterKey::m_bBlendGap) ->Field("PlayInPlace", &ICharacterKey::m_bInPlace); serializeContext->Class<ICommentKey, IKey>() ->Field("Comment", &ICommentKey::m_strComment) ->Field("Duration", &ICommentKey::m_duration) ->Field("Font", &ICommentKey::m_strFont) ->Field("Color", &ICommentKey::m_color) ->Field("Size", &ICommentKey::m_size) ->Field("Align", &ICommentKey::m_align); serializeContext->Class<IConsoleKey, IKey>() ->Field("Command", &IConsoleKey::command); serializeContext->Class<IDiscreteFloatKey, IKey>() ->Field("Value", &IDiscreteFloatKey::m_fValue); serializeContext->Class<IEventKey, IKey>() ->Field("Event", &IEventKey::event) ->Field("EventValue", &IEventKey::eventValue) ->Field("Anim", &IEventKey::animation) ->Field("Target", &IEventKey::target) ->Field("Length", &IEventKey::duration); serializeContext->Class<ILookAtKey, IKey>() ->Field("LookAtNodeName", &ILookAtKey::szSelection) ->Field("LookPose", &ILookAtKey::lookPose) ->Field("Duration", &ILookAtKey::fDuration) ->Field("SmoothTime", &ILookAtKey::smoothTime); serializeContext->Class<IScreenFaderKey, IKey>() ->Field("FadeTime", &IScreenFaderKey::m_fadeTime) ->Field("FadeColor", &IScreenFaderKey::m_fadeColor) ->Field("FadeType", &IScreenFaderKey::m_fadeType) ->Field("FadeChangeType", &IScreenFaderKey::m_fadeChangeType) ->Field("Texture", &IScreenFaderKey::m_strTexture) ->Field("useCurColor", &IScreenFaderKey::m_bUseCurColor); serializeContext->Class<ISelectKey, IKey>() ->Field("SelectedName", &ISelectKey::szSelection) ->Field("SelectedEntityId", &ISelectKey::cameraAzEntityId) ->Field("Duration", &ISelectKey::fDuration) ->Field("BlendTime", &ISelectKey::fBlendTime); serializeContext->Class<ISequenceKey, IKey>() ->Field("Node", &ISequenceKey::szSelection) ->Field("SequenceEntityId", &ISequenceKey::sequenceEntityId) ->Field("OverrideTimes", &ISequenceKey::bOverrideTimes) ->Field("StartTime", &ISequenceKey::fStartTime) ->Field("EndTime", &ISequenceKey::fEndTime); serializeContext->Class<ISoundKey, IKey>() ->Field("StartTrigger", &ISoundKey::sStartTrigger) ->Field("StopTrigger", &ISoundKey::sStopTrigger) ->Field("Duration", &ISoundKey::fDuration) ->Field("Color", &ISoundKey::customColor); serializeContext->Class<ITimeRangeKey, IKey>() ->Field("Duration", &ITimeRangeKey::m_duration) ->Field("Start", &ITimeRangeKey::m_startTime) ->Field("End", &ITimeRangeKey::m_endTime) ->Field("Speed", &ITimeRangeKey::m_speed) ->Field("Loop", &ITimeRangeKey::m_bLoop); } }
//The MIT License (MIT) // //Copyright (c) 2016 ZHAOZhengyi-tgx // //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. // DlgKeyInputPad.cpp : implementation file // #include "stdafx.h" #include "DlgKeyInputPad.h" static CString czInputString; // CDlgKeyInputPad dialog IMPLEMENT_DYNAMIC(CDlgKeyInputPad, CDialog) CDlgKeyInputPad::CDlgKeyInputPad(CWnd* pParent /*=NULL*/) : CDialog(CDlgKeyInputPad::IDD, pParent) { } CDlgKeyInputPad::~CDlgKeyInputPad() { } void CDlgKeyInputPad::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CDlgKeyInputPad, CDialog) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_1, &CDlgKeyInputPad::OnBnClickedButtonDlgKey1) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_2, &CDlgKeyInputPad::OnBnClickedButtonDlgKey2) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_3, &CDlgKeyInputPad::OnBnClickedButtonDlgKey3) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_4, &CDlgKeyInputPad::OnBnClickedButtonDlgKey4) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_5, &CDlgKeyInputPad::OnBnClickedButtonDlgKey5) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_6, &CDlgKeyInputPad::OnBnClickedButtonDlgKey6) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_7, &CDlgKeyInputPad::OnBnClickedButtonDlgKey7) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_8, &CDlgKeyInputPad::OnBnClickedButtonDlgKey8) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_9, &CDlgKeyInputPad::OnBnClickedButtonDlgKey9) ON_BN_CLICKED(IDC_BUTTON_DLG_KEY_0, &CDlgKeyInputPad::OnBnClickedButtonDlgKey0) ON_BN_CLICKED(IDC_CHECK_DLG_SHOW_NUMBER, &CDlgKeyInputPad::OnBnClickedCheckDlgShowNumber) ON_BN_CLICKED(IDOK, &CDlgKeyInputPad::OnBnClickedOk) // ON_BN_CLICKED(IDCANCEL, &CDlgKeyInputPad::OnBnClickedCancel) ON_BN_CLICKED(ID_BUTTON_DLG_KEY_PAD_CLEAR, &CDlgKeyInputPad::OnBnClickedButtonDlgKeyPadClear) ON_EN_CHANGE(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT, &CDlgKeyInputPad::OnEnChangeEditDlgKeyInputShowText) ON_BN_CLICKED(ID_BUTTON_DLG_KEY_PAD_OK, &CDlgKeyInputPad::OnBnClickedButtonDlgKeyPadOk) END_MESSAGE_MAP() // CDlgKeyInputPad message handlers BOOL CDlgKeyInputPad::OnInitDialog() { ((CButton *)GetDlgItem(IDC_CHECK_DLG_SHOW_NUMBER))->SetCheck(bFlagShowNumberKeyPad); CString cstrTemp; cstrTemp.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(_T(cstrTemp)); return CDialog::OnInitDialog(); } void CDlgKeyInputPad::SetInputNumber(int iNumber) { iInputNumber = iNumber; } int CDlgKeyInputPad::GetReturnNumber() { return iReturnNumber; } void CDlgKeyInputPad::SetFlagShowNumberOnKeyPad(BOOL bShow) { bFlagShowNumberKeyPad = bShow; } // IDC_BUTTON_DLG_KEY_1 void CDlgKeyInputPad::OnBnClickedButtonDlgKey1() { iInputNumber = iInputNumber * 10 + 1; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_2 void CDlgKeyInputPad::OnBnClickedButtonDlgKey2() { iInputNumber = iInputNumber * 10 + 2; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_3 void CDlgKeyInputPad::OnBnClickedButtonDlgKey3() { iInputNumber = iInputNumber * 10 + 3; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_4 void CDlgKeyInputPad::OnBnClickedButtonDlgKey4() { iInputNumber = iInputNumber * 10 + 4; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_5 void CDlgKeyInputPad::OnBnClickedButtonDlgKey5() { iInputNumber = iInputNumber * 10 + 5; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_6 void CDlgKeyInputPad::OnBnClickedButtonDlgKey6() { iInputNumber = iInputNumber * 10 + 6; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_7 void CDlgKeyInputPad::OnBnClickedButtonDlgKey7() { iInputNumber = iInputNumber * 10 + 7; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_8 void CDlgKeyInputPad::OnBnClickedButtonDlgKey8() { iInputNumber = iInputNumber * 10 + 8; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_9 void CDlgKeyInputPad::OnBnClickedButtonDlgKey9() { iInputNumber = iInputNumber * 10 + 9; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_BUTTON_DLG_KEY_0 void CDlgKeyInputPad::OnBnClickedButtonDlgKey0() {; iInputNumber = iInputNumber * 10 + 0; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_CHECK_DLG_SHOW_NUMBER void CDlgKeyInputPad::OnBnClickedCheckDlgShowNumber() { // TODO: Add your control notification handler code here bFlagShowNumberKeyPad = ((CButton*)GetDlgItem(IDC_CHECK_DLG_SHOW_NUMBER))->GetCheck(); } void CDlgKeyInputPad::OnBnClickedOk() { // TODO: Add your control notification handler code here iReturnNumber = iInputNumber; OnOK(); } // ID_BUTTON_DLG_KEY_PAD_CLEAR void CDlgKeyInputPad::OnBnClickedButtonDlgKeyPadClear() { iInputNumber = 0; czInputString.Format("%d", iInputNumber); GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->SetWindowTextA(czInputString); } // IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT void CDlgKeyInputPad::OnEnChangeEditDlgKeyInputShowText() { static char tempChar[32]; GetDlgItem(IDC_EDIT_DLG_KEY_INPUT_SHOW_TEXT)->GetWindowTextA(tempChar, 32); if(tempChar[0] <= '9' && tempChar[0] >= '0') { czInputString.Format("%s", tempChar); sscanf_s(tempChar, "%d", &iInputNumber); } else { AfxMessageBox("Pass must be positive integer", 0); OnBnClickedButtonDlgKeyPadClear(); } } void CDlgKeyInputPad::ReadIntegerFromEdit(int nResId, int *iValue) { static char tempChar[32]; GetDlgItem(nResId)->GetWindowTextA(&tempChar[0], 32); sscanf_s(tempChar, "%d", iValue); } // ID_BUTTON_DLG_KEY_PAD_OK void CDlgKeyInputPad::OnBnClickedButtonDlgKeyPadOk() { iReturnNumber = iInputNumber; OnOK(); }
#include "LWNetwork/LWProtocolManager.h" #include "LWNetwork/LWProtocol.h" #include "LWPlatform/LWPlatform.h" #include <LWCore/LWByteBuffer.h> #include <algorithm> #include <errno.h> bool LWProtocolManager::InitateNetwork(void) { return true; } void LWProtocolManager::TerminateNetwork(void) { return; } bool LWProtocolManager::PollSet(pollfd *SocketSet, uint32_t SetCnt, uint32_t Timeout) { uint32_t r = (uint32_t)poll(SocketSet, SetCnt, Timeout); if (r == SOCKET_ERROR) return false; return true; } uint32_t LWProtocolManager::GetHostIPs(uint32_t *IPBuffer, uint32_t BufferSize) { char hostbuffer[128]; addrinfo hint = { AI_CANONNAME, AF_INET, 0, 0, 0, nullptr, nullptr, nullptr }, *servinfo = nullptr; if (gethostname(hostbuffer, sizeof(hostbuffer)) == SOCKET_ERROR) return 0; if (getaddrinfo(hostbuffer, nullptr, &hint, &servinfo)) return 0; uint32_t i = 0; for (addrinfo *p = servinfo; p; p = p->ai_next, i++) { if (i < BufferSize) IPBuffer[i] = LWByteBuffer::MakeHost((uint32_t)((sockaddr_in*)p->ai_addr)->sin_addr.s_addr); } return i; } uint32_t LWProtocolManager::GetError(void) { uint32_t res = errno; errno = 0; return res; } /* bool LWProtocolManager::Poll(uint32_t Timeout) { if (!PollSet(m_SocketSet, m_ActiveSocketCount, Timeout)) return false; for (uint32_t i = 0; i < m_ActiveSocketCount; i++) { if (m_SocketSet[i].revents&(POLLIN | POLLHUP)) { LWProtocol *P = m_Protocols[m_Sockets[i].GetProtocolID()]; if (P) P->Read(m_Sockets[i], this); m_SocketSet[i].revents = 0; } if (m_Sockets[i].GetFlag()&LWSocket::Closeable) { m_Sockets[i].Close(); m_Sockets[i] = std::move(m_Sockets[m_ActiveSocketCount - 1]); m_SocketSet[i] = m_SocketSet[m_ActiveSocketCount - 1]; i--; m_ActiveSocketCount--; } } return true; }*/
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include "bgp/routing-instance/static_route.h" #include "bgp/routing-instance/routing_instance.h" #include <fstream> #include <algorithm> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/assign/list_of.hpp> #include "base/test/task_test_util.h" #include "bgp/bgp_config.h" #include "bgp/bgp_config_ifmap.h" #include "bgp/bgp_factory.h" #include "bgp/bgp_log.h" #include "bgp/bgp_sandesh.h" #include "bgp/inet/inet_table.h" #include "bgp/l3vpn/inetvpn_route.h" #include "bgp/l3vpn/inetvpn_table.h" #include "bgp/origin-vn/origin_vn.h" #include "bgp/routing-instance/static_route_types.h" #include "bgp/security_group/security_group.h" #include "bgp/test/bgp_test_util.h" #include "bgp/tunnel_encap/tunnel_encap.h" #include "control-node/control_node.h" #include "db/db_graph.h" #include "db/test/db_test_util.h" #include "ifmap/ifmap_link_table.h" #include "ifmap/ifmap_server_parser.h" #include "ifmap/test/ifmap_test_util.h" #include "io/event_manager.h" #include <pugixml/pugixml.hpp> #include "schema/bgp_schema_types.h" #include "schema/vnc_cfg_types.h" #include "testing/gunit.h" using namespace std; using boost::assign::list_of; using boost::assign::map_list_of; using namespace pugi; #define VERIFY_EQ(expected, actual) \ TASK_UTIL_EXPECT_EQ(expected, actual) class BgpPeerMock : public IPeer { public: BgpPeerMock(const Ip4Address &address) : address_(address) { } virtual ~BgpPeerMock() { } virtual std::string ToString() const { return address_.to_string(); } virtual std::string ToUVEKey() const { return address_.to_string(); } virtual bool SendUpdate(const uint8_t *msg, size_t msgsize) { return true; } virtual BgpServer *server() { return NULL; } virtual IPeerClose *peer_close() { return NULL; } virtual IPeerDebugStats *peer_stats() { return NULL; } virtual const IPeerDebugStats *peer_stats() const { return NULL; } virtual bool IsReady() const { return true; } virtual bool IsXmppPeer() const { return false; } virtual void Close() { } BgpProto::BgpPeerType PeerType() const { return BgpProto::IBGP; } virtual uint32_t bgp_identifier() const { return htonl(address_.to_ulong()); } virtual const std::string GetStateName() const { return ""; } virtual void UpdateRefCount(int count) const { } virtual tbb::atomic<int> GetRefCount() const { tbb::atomic<int> count; count = 0; return count; } private: Ip4Address address_; }; class StaticRouteTest : public ::testing::Test { protected: StaticRouteTest() : bgp_server_(new BgpServer(&evm_)) { IFMapLinkTable_Init(&config_db_, &config_graph_); vnc_cfg_Server_ModuleInit(&config_db_, &config_graph_); bgp_schema_Server_ModuleInit(&config_db_, &config_graph_); } ~StaticRouteTest() { STLDeleteValues(&peers_); } virtual void SetUp() { IFMapServerParser *parser = IFMapServerParser::GetInstance("schema"); vnc_cfg_ParserInit(parser); bgp_schema_ParserInit(parser); BgpIfmapConfigManager *config_manager = static_cast<BgpIfmapConfigManager *>( bgp_server_->config_manager()); config_manager->Initialize(&config_db_, &config_graph_, "localhost"); ri_mgr_ = bgp_server_->routing_instance_mgr(); } virtual void TearDown() { task_util::WaitForIdle(); bgp_server_->Shutdown(); task_util::WaitForIdle(); db_util::Clear(&config_db_); IFMapServerParser *parser = IFMapServerParser::GetInstance("schema"); parser->MetadataClear("schema"); } void NetworkConfig(const vector<string> &instance_names, const multimap<string, string> &connections) { string netconf( bgp_util::NetworkConfigGenerate(instance_names, connections)); IFMapServerParser *parser = IFMapServerParser::GetInstance("schema"); parser->Receive(&config_db_, netconf.data(), netconf.length(), 0); } int RouteCount(const string &instance_name) const { string tablename(instance_name); tablename.append(".inet.0"); BgpTable *table = static_cast<BgpTable *>( bgp_server_->database()->FindTable(tablename)); EXPECT_TRUE(table != NULL); if (table == NULL) { return 0; } return table->Size(); } void DisableStaticRouteQ(const string &instance_name) { RoutingInstance *rtinstance = ri_mgr_->GetRoutingInstance(instance_name); rtinstance->static_route_mgr()->DisableQueue(); } bool IsQueueEmpty(const string &instance_name) { RoutingInstance *rtinstance = ri_mgr_->GetRoutingInstance(instance_name); return rtinstance->static_route_mgr()->IsQueueEmpty(); } void EnableStaticRouteQ(const string &instance_name) { RoutingInstance *rtinstance = ri_mgr_->GetRoutingInstance(instance_name); rtinstance->static_route_mgr()->EnableQueue(); } void AddInetRoute(IPeer *peer, const string &instance_name, const string &prefix, int localpref, string nexthop="7.8.9.1", std::set<string> encap = std::set<string>(), std::vector<uint32_t> sglist = std::vector<uint32_t>(), uint32_t flags=0, int label=0) { boost::system::error_code error; Ip4Prefix nlri = Ip4Prefix::FromString(prefix, &error); EXPECT_FALSE(error); DBRequest request; request.oper = DBRequest::DB_ENTRY_ADD_CHANGE; request.key.reset(new InetTable::RequestKey(nlri, peer)); BgpAttrSpec attr_spec; boost::scoped_ptr<BgpAttrLocalPref> local_pref( new BgpAttrLocalPref(localpref)); attr_spec.push_back(local_pref.get()); IpAddress chain_addr = Ip4Address::from_string(nexthop, error); boost::scoped_ptr<BgpAttrNextHop> nexthop_attr( new BgpAttrNextHop(chain_addr.to_v4().to_ulong())); attr_spec.push_back(nexthop_attr.get()); ExtCommunitySpec ext_comm; for(std::vector<uint32_t>::iterator it = sglist.begin(); it != sglist.end(); it++) { SecurityGroup sgid(0, *it); ext_comm.communities.push_back(sgid.GetExtCommunityValue()); } for(std::set<string>::iterator it = encap.begin(); it != encap.end(); it++) { TunnelEncap tunnel_encap(*it); ext_comm.communities.push_back(tunnel_encap.GetExtCommunityValue()); } attr_spec.push_back(&ext_comm); BgpAttrPtr attr = bgp_server_->attr_db()->Locate(attr_spec); request.data.reset(new BgpTable::RequestData(attr, flags, label)); BgpTable *table = static_cast<BgpTable *>( bgp_server_->database()->FindTable(instance_name + ".inet.0")); ASSERT_TRUE(table != NULL); table->Enqueue(&request); } void DeleteInetRoute(IPeer *peer, const string &instance_name, const string &prefix) { boost::system::error_code error; Ip4Prefix nlri = Ip4Prefix::FromString(prefix, &error); EXPECT_FALSE(error); DBRequest request; request.oper = DBRequest::DB_ENTRY_DELETE; request.key.reset(new InetTable::RequestKey(nlri, peer)); BgpTable *table = static_cast<BgpTable *>( bgp_server_->database()->FindTable(instance_name + ".inet.0")); ASSERT_TRUE(table != NULL); table->Enqueue(&request); } BgpRoute *InetRouteLookup(const string &instance_name, const string &prefix) { BgpTable *table = static_cast<BgpTable *>( bgp_server_->database()->FindTable(instance_name + ".inet.0")); EXPECT_TRUE(table != NULL); if (table == NULL) { return NULL; } boost::system::error_code error; Ip4Prefix nlri = Ip4Prefix::FromString(prefix, &error); EXPECT_FALSE(error); InetTable::RequestKey key(nlri, NULL); BgpRoute *rt = static_cast<BgpRoute *>(table->Find(&key)); return rt; } set<string> GetRTargetFromPath(const BgpPath *path) { const BgpAttr *attr = path->GetAttr(); const ExtCommunity *ext_community = attr->ext_community(); set<string> rtlist; BOOST_FOREACH(const ExtCommunity::ExtCommunityValue &comm, ext_community->communities()) { if (!ExtCommunity::is_route_target(comm)) continue; RouteTarget rtarget(comm); rtlist.insert(rtarget.ToString()); } return rtlist; } std::set<std::string> GetTunnelEncapListFromRoute(const BgpPath *path) { const ExtCommunity *ext_comm = path->GetAttr()->ext_community(); assert(ext_comm); std::set<std::string> list; BOOST_FOREACH(const ExtCommunity::ExtCommunityValue &comm, ext_comm->communities()) { if (!ExtCommunity::is_tunnel_encap(comm)) continue; TunnelEncap encap(comm); list.insert(encap.ToXmppString()); } return list; } std::string GetOriginVnFromRoute(const BgpPath *path) { const ExtCommunity *ext_comm = path->GetAttr()->ext_community(); assert(ext_comm); BOOST_FOREACH(const ExtCommunity::ExtCommunityValue &comm, ext_comm->communities()) { if (!ExtCommunity::is_origin_vn(comm)) continue; OriginVn origin_vn(comm); return ri_mgr_->GetVirtualNetworkByVnIndex(origin_vn.vn_index()); } return "unresolved"; } string FileRead(const string &filename) { ifstream file(filename.c_str()); string content((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); return content; } std::auto_ptr<autogen::StaticRouteEntriesType> GetStaticRouteConfig(std::string filename) { std::auto_ptr<autogen::StaticRouteEntriesType> params (new autogen::StaticRouteEntriesType()); string content = FileRead(filename); istringstream sstream(content); xml_document xdoc; xml_parse_result result = xdoc.load(sstream); if (!result) { BGP_WARN_UT("Unable to load XML document. (status=" << result.status << ", offset=" << result.offset << ")"); assert(0); } xml_node node = xdoc.first_child(); params->XmlParse(node); return params; } static void ValidateShowStaticRouteResponse(Sandesh *sandesh, std::string &result) { ShowStaticRouteResp *resp = dynamic_cast<ShowStaticRouteResp *>(sandesh); TASK_UTIL_EXPECT_NE((ShowStaticRouteResp *)NULL, resp); validate_done_ = 1; TASK_UTIL_EXPECT_EQ(1, resp->get_static_route_entries().size()); int i = 0; cout << "*******************************************************"<<endl; BOOST_FOREACH(const StaticRouteEntriesInfo &info, resp->get_static_route_entries()) { TASK_UTIL_EXPECT_EQ(info.get_ri_name(), result); cout << info.log() << endl; i++; } cout << "*******************************************************"<<endl; } void VerifyStaticRouteSandesh(std::string ri_name) { BgpSandeshContext sandesh_context; sandesh_context.bgp_server = bgp_server_.get(); sandesh_context.xmpp_peer_manager = NULL; Sandesh::set_client_context(&sandesh_context); Sandesh::set_response_callback(boost::bind(ValidateShowStaticRouteResponse, _1, ri_name)); ShowStaticRouteReq *req = new ShowStaticRouteReq; req->set_ri_name(ri_name); validate_done_ = 0; req->HandleRequest(); req->Release(); TASK_UTIL_EXPECT_EQ(1, validate_done_); } EventManager evm_; DB config_db_; DBGraph config_graph_; boost::scoped_ptr<BgpServer> bgp_server_; RoutingInstanceMgr *ri_mgr_; vector<BgpPeerMock *> peers_; static int validate_done_; }; int StaticRouteTest::validate_done_; // // Basic Test // 1. Configure routing instance with static route property // 2. Add the nexthop route // 3. Validate the static route in both source (nat) and destination // routing instance TEST_F(StaticRouteTest, Basic) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("nat", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in nat instance.."); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); set<string> config_list = list_of("target:64496:1")("target:64496:2")("target:64496:3"); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); VerifyStaticRouteSandesh("nat"); // Delete nexthop route DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); } TEST_F(StaticRouteTest, UpdateRtList) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_3.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); set<string> config_list = list_of("target:64496:1")("target:64496:2")("target:64496:3"); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_3.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); config_list = list_of("target:1:1"); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Delete nexthop route DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); } TEST_F(StaticRouteTest, UpdateNexthop) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); set<string> config_list = list_of("target:64496:1")("target:64496:2")("target:64496:3"); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_4.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.1/32", 100, "5.4.3.2"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); static_rt = InetRouteLookup("blue", "192.168.1.0/24"); static_path = static_rt->BestPath(); attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "5.4.3.2"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); config_list = list_of("target:64496:1"); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Delete nexthop route DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); DeleteInetRoute(NULL, "nat", "192.168.1.1/32"); task_util::WaitForIdle(); } TEST_F(StaticRouteTest, MultiplePrefix) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); set<string> config_list = list_of("target:64496:1"); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_2.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.2.1/32", 100, "9.8.7.6"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.2.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.0.0/16"), NULL, 1000, 10000, "Wait for Static route in blue.."); static_rt = InetRouteLookup("blue", "192.168.2.0/24"); static_path = static_rt->BestPath(); attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "9.8.7.6"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("blue", "192.168.0.0/16"); static_path = static_rt->BestPath(); attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "9.8.7.6"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.2.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.0.0/16"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Delete nexthop route DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); DeleteInetRoute(NULL, "nat", "192.168.2.1/32"); task_util::WaitForIdle(); } TEST_F(StaticRouteTest, MultiplePrefixSameNexthopAndUpdateNexthop) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); set<string> config_list = list_of("target:64496:1"); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_5.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.2.1/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.2.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.3.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("blue", "192.168.2.0/24"); static_path = static_rt->BestPath(); attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("blue", "192.168.3.0/24"); static_path = static_rt->BestPath(); attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.2.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.3.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); AddInetRoute(NULL, "nat", "192.168.2.1/32", 100, "5.3.4.5"); task_util::WaitForIdle(); static_rt = InetRouteLookup("blue", "192.168.1.0/24"); static_path = static_rt->BestPath(); attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "5.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("blue", "192.168.2.0/24"); static_path = static_rt->BestPath(); attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "5.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("blue", "192.168.3.0/24"); static_path = static_rt->BestPath(); attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "5.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.2.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.3.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Delete nexthop route DeleteInetRoute(NULL, "nat", "192.168.2.1/32"); task_util::WaitForIdle(); } TEST_F(StaticRouteTest, ConfigUpdate) { vector<string> instance_names = list_of("blue")("nat")("red"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); set<string> config_list = list_of("target:64496:1"); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_6.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5"); AddInetRoute(NULL, "nat", "192.168.2.1/32", 100, "3.4.5.6"); AddInetRoute(NULL, "nat", "192.168.3.1/32", 100, "9.8.7.6"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.2.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.0.0/16"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("nat", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.2.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.0.0/16"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_7.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.0.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.2.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("red", "192.168.2.0/24"), NULL, 1000, 10000, "Wait for Static route in red.."); TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.3.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.4.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); AddInetRoute(NULL, "nat", "192.168.4.1/32", 100, "9.8.7.6"); task_util::WaitForIdle(); TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.3.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.4.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); set<string> config_list_1 = list_of("target:64496:3"); static_rt = InetRouteLookup("nat", "192.168.2.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list_1); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.3.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); static_rt = InetRouteLookup("nat", "192.168.4.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Delete nexthop route DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); DeleteInetRoute(NULL, "nat", "192.168.2.1/32"); DeleteInetRoute(NULL, "nat", "192.168.3.1/32"); DeleteInetRoute(NULL, "nat", "192.168.4.1/32"); task_util::WaitForIdle(); } TEST_F(StaticRouteTest, N_ECMP_PATHADD) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); boost::system::error_code ec; peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.1", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.2", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.3", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.4", ec))); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); // Add Nexthop Route AddInetRoute(peers_[0], "nat", "192.168.1.254/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("nat", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in nat instance.."); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); EXPECT_EQ(static_rt->count(), 1); static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); set<string> config_list = list_of("target:64496:1")("target:64496:2")("target:64496:3"); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Stop(); DeleteInetRoute(peers_[0], "nat", "192.168.1.254/32"); AddInetRoute(peers_[1], "nat", "192.168.1.254/32", 100, "2.3.1.5"); AddInetRoute(peers_[2], "nat", "192.168.1.254/32", 100, "2.3.2.5"); AddInetRoute(peers_[3], "nat", "192.168.1.254/32", 100, "2.3.3.5"); scheduler->Start(); task_util::WaitForIdle(); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); // Check for static route count TASK_UTIL_WAIT_EQ_NO_MSG(static_rt->count(), 3, 1000, 10000, "Wait for all paths in static route .."); EXPECT_EQ(static_rt->count(), 3); for (Route::PathList::iterator it = static_rt->GetPathList().begin(); it != static_rt->GetPathList().end(); it++) { BgpPath *path = static_cast<BgpPath *>(it.operator->()); BgpAttrPtr attr = path->GetAttr(); assert(path->GetPeer() != peers_[0]); set<string> list = GetRTargetFromPath(path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(path), "unresolved"); if (BgpPath::PathIdString(path->GetPathId()) == "2.3.1.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.1.5"); } else if (BgpPath::PathIdString(path->GetPathId()) == "2.3.2.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.2.5"); } else if (BgpPath::PathIdString(path->GetPathId()) == "2.3.3.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.3.5"); } } // Delete nexthop route DeleteInetRoute(peers_[1], "nat", "192.168.1.254/32"); DeleteInetRoute(peers_[2], "nat", "192.168.1.254/32"); DeleteInetRoute(peers_[3], "nat", "192.168.1.254/32"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); } TEST_F(StaticRouteTest, N_ECMP_PATHDEL) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); boost::system::error_code ec; peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.1", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.2", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.3", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.4", ec))); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); // Add Nexthop Route AddInetRoute(peers_[0], "nat", "192.168.1.254/32", 100, "2.3.1.5"); AddInetRoute(peers_[1], "nat", "192.168.1.254/32", 100, "2.3.2.5"); AddInetRoute(peers_[2], "nat", "192.168.1.254/32", 100, "2.3.3.5"); AddInetRoute(peers_[3], "nat", "192.168.1.254/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("nat", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in nat instance.."); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.1.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); EXPECT_EQ(static_rt->count(), 4); set<string> config_list = list_of("target:64496:1")("target:64496:2")("target:64496:3"); // Check for static route count TASK_UTIL_WAIT_EQ_NO_MSG(static_rt->count(), 4, 1000, 10000, "Wait for all paths in static route .."); EXPECT_EQ(static_rt->count(), 4); for (Route::PathList::iterator it = static_rt->GetPathList().begin(); it != static_rt->GetPathList().end(); it++) { BgpPath *path = static_cast<BgpPath *>(it.operator->()); BgpAttrPtr attr = path->GetAttr(); set<string> list = GetRTargetFromPath(path); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(path), "unresolved"); if (BgpPath::PathIdString(path->GetPathId()) == "2.3.1.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.1.5"); } else if (BgpPath::PathIdString(path->GetPathId()) == "2.3.2.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.2.5"); } else if (BgpPath::PathIdString(path->GetPathId()) == "2.3.3.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.3.5"); } else if (BgpPath::PathIdString(path->GetPathId()) == "2.3.4.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); } } TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Stop(); DeleteInetRoute(peers_[0], "nat", "192.168.1.254/32"); DeleteInetRoute(peers_[1], "nat", "192.168.1.254/32"); DeleteInetRoute(peers_[2], "nat", "192.168.1.254/32"); scheduler->Start(); task_util::WaitForIdle(); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); // Check for static route count TASK_UTIL_WAIT_EQ_NO_MSG(static_rt->count(), 1, 1000, 10000, "Wait for all paths in static route .."); EXPECT_EQ(static_rt->count(), 1); static_path = static_rt->BestPath(); EXPECT_EQ("2.3.4.5", BgpPath::PathIdString(static_path->GetPathId())); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Delete nexthop route DeleteInetRoute(peers_[3], "nat", "192.168.1.254/32"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); } TEST_F(StaticRouteTest, TunnelEncap) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); set<string> encap = list_of("gre")("vxlan"); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5", encap); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("nat", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in nat instance.."); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.4.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); set<string> tunnel_encap_list = GetTunnelEncapListFromRoute(static_path); set<string> config_list = list_of("target:64496:1")("target:64496:2")("target:64496:3"); EXPECT_EQ(list, config_list); EXPECT_EQ(encap, tunnel_encap_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); encap = list_of("udp"); // Update Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5", encap); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("nat", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in nat.."); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); list = GetRTargetFromPath(static_path); tunnel_encap_list = GetTunnelEncapListFromRoute(static_path); EXPECT_EQ(list, config_list); EXPECT_EQ(encap, tunnel_encap_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Delete nexthop route DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); } TEST_F(StaticRouteTest, MultiPathTunnelEncap) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); boost::system::error_code ec; peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.1", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.2", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.3", ec))); peers_.push_back( new BgpPeerMock(Ip4Address::from_string("192.168.0.4", ec))); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); // Add Nexthop Route set<string> encap_1 = list_of("gre"); set<string> encap_2 = list_of("udp"); set<string> encap_3 = list_of("vxlan"); AddInetRoute(peers_[0], "nat", "192.168.1.254/32", 100, "2.3.1.5", encap_1, vector<uint32_t>()); AddInetRoute(peers_[1], "nat", "192.168.1.254/32", 100, "2.3.2.5", encap_2, vector<uint32_t>()); AddInetRoute(peers_[2], "nat", "192.168.1.254/32", 100, "2.3.3.5", encap_3, vector<uint32_t>()); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("nat", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in nat instance.."); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); BgpRoute *static_rt = InetRouteLookup("blue", "192.168.1.0/24"); const BgpPath *static_path = static_rt->BestPath(); BgpAttrPtr attr = static_path->GetAttr(); EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.1.5"); EXPECT_EQ(GetOriginVnFromRoute(static_path), "blue"); static_rt = InetRouteLookup("nat", "192.168.1.0/24"); static_path = static_rt->BestPath(); set<string> list = GetRTargetFromPath(static_path); set<string> config_list = list_of("target:64496:1")("target:64496:2")("target:64496:3"); EXPECT_EQ(list, config_list); EXPECT_EQ(GetOriginVnFromRoute(static_path), "unresolved"); // Check for static route count TASK_UTIL_WAIT_EQ_NO_MSG(static_rt->count(), 3, 1000, 10000, "Wait for all paths in static route .."); EXPECT_EQ(static_rt->count(), 3); for (Route::PathList::iterator it = static_rt->GetPathList().begin(); it != static_rt->GetPathList().end(); it++) { BgpPath *path = static_cast<BgpPath *>(it.operator->()); BgpAttrPtr attr = path->GetAttr(); EXPECT_EQ(GetOriginVnFromRoute(path), "unresolved"); set<string> list = GetTunnelEncapListFromRoute(path); if (BgpPath::PathIdString(path->GetPathId()) == "2.3.1.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.1.5"); EXPECT_EQ(encap_1, list); } else if (BgpPath::PathIdString(path->GetPathId()) == "2.3.2.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.2.5"); EXPECT_EQ(encap_2, list); } else if (BgpPath::PathIdString(path->GetPathId()) == "2.3.3.5") { EXPECT_EQ(attr->nexthop().to_v4().to_string(), "2.3.3.5"); EXPECT_EQ(encap_3, list); } } // Delete nexthop route DeleteInetRoute(peers_[0], "nat", "192.168.1.254/32"); DeleteInetRoute(peers_[1], "nat", "192.168.1.254/32"); DeleteInetRoute(peers_[2], "nat", "192.168.1.254/32"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); } TEST_F(StaticRouteTest, DeleteEntryReuse) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); DisableStaticRouteQ("nat"); // Delete nexthop route DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); BgpRoute *nexthop_rt = InetRouteLookup("nat", "192.168.1.254/32"); TASK_UTIL_WAIT_EQ_NO_MSG(nexthop_rt->IsDeleted(), true, 1000, 10000, "Wait for delete marking of nexthop route in nat"); AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5"); TASK_UTIL_WAIT_EQ_NO_MSG(nexthop_rt->IsDeleted(), false, 1000, 10000, "Wait for clear of delete flag on nexthop route "); DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); TASK_UTIL_WAIT_EQ_NO_MSG(nexthop_rt->IsDeleted(), true, 1000, 10000, "Wait for delete marking of nexthop route in nat"); EnableStaticRouteQ("nat"); TASK_UTIL_EXPECT_TRUE(IsQueueEmpty("nat")); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); } TEST_F(StaticRouteTest, EntryAfterStop) { vector<string> instance_names = list_of("blue")("nat")("red")("green"); multimap<string, string> connections; NetworkConfig(instance_names, connections); task_util::WaitForIdle(); std::auto_ptr<autogen::StaticRouteEntriesType> params = GetStaticRouteConfig("controller/src/bgp/testdata/static_route_1.xml"); ifmap_test_util::IFMapMsgPropertyAdd(&config_db_, "routing-instance", "nat", "static-route-entries", params.release(), 0); task_util::WaitForIdle(); // Add Nexthop Route AddInetRoute(NULL, "nat", "192.168.1.254/32", 100, "2.3.4.5"); task_util::WaitForIdle(); // Check for Static route TASK_UTIL_WAIT_NE_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); DisableStaticRouteQ("nat"); ifmap_test_util::IFMapMsgPropertyDelete(&config_db_, "routing-instance", "nat", "static-route-entries"); AddInetRoute(NULL, "nat", "192.168.1.254/32", 200, "2.3.4.5"); EnableStaticRouteQ("nat"); TASK_UTIL_EXPECT_TRUE(IsQueueEmpty("nat")); DeleteInetRoute(NULL, "nat", "192.168.1.254/32"); // Check for Static route TASK_UTIL_WAIT_EQ_NO_MSG(InetRouteLookup("blue", "192.168.1.0/24"), NULL, 1000, 10000, "Wait for Static route in blue.."); } class TestEnvironment : public ::testing::Environment { virtual ~TestEnvironment() { } }; static void SetUp() { ControlNode::SetDefaultSchedulingPolicy(); BgpObjectFactory::Register<BgpConfigManager>( boost::factory<BgpIfmapConfigManager *>()); } static void TearDown() { task_util::WaitForIdle(); TaskScheduler *scheduler = TaskScheduler::GetInstance(); scheduler->Terminate(); } int main(int argc, char **argv) { bgp_log_test::init(); ::testing::InitGoogleTest(&argc, argv); ::testing::AddGlobalTestEnvironment(new TestEnvironment()); SetUp(); int result = RUN_ALL_TESTS(); TearDown(); return result; }
#include <stdlib.h> #include <iostream> #include <thread> #include "../inc/helpers/Menu.hh" #include "../inc/Core.hh" #include "../inc/helpers/lacze_do_gnuplota.hh" int main() { char option = ' ', choiseOne = ' ', choiseTwo = ' ', choiseTre = ' '; bool tipsMode = true; int ObjectIndex = 0, objectIndex; srand(time(0)); Menu Menu; Core Core; Vector3I startCorner, sizeTab; Vector3I destination; PzG::LaczeDoGNUPlota Lacze; Lacze.Inicjalizuj(); Lacze.ZmienTrybRys(PzG::TR_3D); Lacze.UstawZakresY(0, 500); Lacze.UstawZakresX(0, 500); Lacze.UstawZakresZ(0, 500); try { while(choiseOne != '0') { Menu.MenuDef(); std::cin >> choiseOne; switch(choiseOne) { case '0': choiseOne = '0'; break; case '1': choiseTwo = ' '; while(choiseTwo != '0') { Menu.MenuObj(); std::cin >> choiseTwo; switch(choiseTwo) { case '0': choiseTwo = '0'; break; case '1': choiseTre = ' '; while(choiseTre != '0') { Menu.MenuObjC(); std::cin >> choiseTre; switch(choiseTre) { case '0': choiseTre = '0'; break; case '1': if (tipsMode == true) {option = 'C'; Menu.MenuTip(option);} std::cout << "** Enter start point -> X Y Z **\n" << std::endl; std::cin >> startCorner; startCorner[2] = 0; std::cout << "\n** Enter size values -> W L H **\n" << std::endl; std::cin >> sizeTab; Core.NewDrone(startCorner, sizeTab, Lacze); ObjectIndex +=1; break; case '2': if (tipsMode == true) {option = 'C'; Menu.MenuTip(option);} std::cout << "** Enter start point -> X Y Z **\n" << std::endl; std::cin >> startCorner; startCorner[2] = 0; std::cout << "\n** Enter size values -> W L H **\n" << std::endl; std::cin >> sizeTab; Core.NewObstacle(startCorner, sizeTab, Lacze); break; } } break; case '2': if (tipsMode == true) {option = 'M'; Menu.MenuTip(option);} //std::cout << "*** Give number for object ***\n" << std::endl; //std::cin >> example; //std::cout << "*** Give vector -> X Y Z ***\n" << std::endl; //std::cin >> example; break; case '4': std::cout << "*** Give number for object ***\n" << std::endl; std::cin >> objectIndex; Core.DelDrone(objectIndex - 1); ObjectIndex = objectIndex - 1; std::cout << ObjectIndex << " --> Drone Index (Dell)" << std::endl; break; case '5': std::cout << "*** Give number for object ***\n" << std::endl; std::cin >> objectIndex; Core.GetDrone(objectIndex - 1); break; } } break; case '4': choiseTwo = ' '; while(choiseTwo != '0') { if (tipsMode == true) {option = 'L'; Menu.MenuTip(option);} Menu.MenuLau(); std::cin >> choiseTwo; switch(choiseTwo) { case '0': choiseTwo = '0'; break; case '1': std::cout << "*** Give number for Drone ***\n" << std::endl; std::cin >> objectIndex; std::cout << "*** Give destination for object ***\n" << std::endl; std::cin >> destination; Core.GetDrone(objectIndex).targetPosition = destination; break; case '2': while(true) { Core.Update(0.10f); Lacze.Rysuj(); using namespace std::chrono_literals; std::this_thread::sleep_for(10ms); } break; } } break; //case '$': //choiseTwo = '1'; //while(choiseTwo != '0') { //switch(choiseTwo) { //case '0': // choiseTwo = '0'; //break; //case '1': // std::cout << "\nTips mode --> " << tipsMode << std::endl; //break; //} //std::cin >> choiseTwo; //} //break; } } } catch(const std::runtime_error& e) { std::cerr << "Something go wrong" << e.what() << '\n'; exit(1); } }
/* Copyright 2019 Igor Kholopov Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "variable_name.h" #include <bier/core/exceptions.h> namespace bier { std::string VariableNameStorage::Allocate(const std::string& name, bool createNew) { if (name.empty()) { return std::to_string(anonymous_counter_++); } if (ContainerHas(name_to_id, name)) { if (createNew) { return name + std::to_string(name_to_id.at(name)++); } return name; } name_to_id.insert({name, 0}); return name; } std::string VariableNameStorage::AllocateUnique(const std::string& name) { check(!ContainerHas(name_to_id, name), IRException("Failed to allocate unique variable " + name, context_)); name_to_id.insert({name, 0}); return name; } const Function* VariableNameStorage::GetContextFunction() const { return context_; } } // namespace bier
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file Quantity.hh //---------------------------------------------------------------------------// #pragma once #include <type_traits> #include "Macros.hh" #include "NumericLimits.hh" #include "Types.hh" namespace celeritas { namespace detail { //---------------------------------------------------------------------------// //! Implementation class for creating a nonnumeric value comparable to //! Quantity. template<class T> struct UnitlessQuantity { T value_; //!< Special nonnumeric value }; //---------------------------------------------------------------------------// } // namespace detail //---------------------------------------------------------------------------// /*! * A numerical value tagged with a unit. * \tparam UnitT unit tag class * \tparam ValueT value type * * A quantity is a value expressed in terms of the given unit. Storing values * in a different unit system can help with some calculations (e.g. operating * in natural unit systems) by avoiding numerical multiplications and divisions * by large constants. It can also make debugging easier (numeric values are * obvious). * * Example usage by physics class, where charge is in units of q_e+, and * mass and momentum are expressed in atomic natural units (where m_e = 1 and c * = 1). * \code using MevEnergy = Quantity<Mev>; using MevMass = Quantity<UnitDivide<Mev, CLightSq>>; using MevMomentum = Quantity<UnitDivide<Mev, CLight>>; \endcode * * A relativistic equation that operates on these quantities can do so without * unnecessary floating point operations involving the speed of light: * \code real_type eval = value_as<MevEnergy>(energy); // Natural units MevMomentum momentum{std::sqrt(eval * eval + 2 * value_as<MevMass>(mass) * eval)}; \endcode * The resulting quantity can be converted to the native Celeritas unit system * with `native_value_from`, which multiplies in the constant value of * ElMomentumUnit: * \code * real_type mom = native_value_from(momentum); * \endcode * * When using a Quantity from another part of the code, e.g. an imported unit * system, use the \c quantity free function rather than \c .value() in order * to guarantee consistency of units between source and destination. * * \note The Quantity is designed to be a simple "strong type" class, not a * complex mathematical class. To operate on quantities, you must use `value_as` * (to operate within the Quantity's unit system) or `native_value_from` (to * operate in the Celeritas native unit system), use the resulting numeric * values in your mathematical expressions, then return a new Quantity class * with the resulting value and correct type. */ template<class UnitT, class ValueT = real_type> class Quantity { public: //!@{ //! Type aliases using value_type = ValueT; using unit_type = UnitT; using Unitless = detail::UnitlessQuantity<ValueT>; //!@} public: //! Construct with default (zero) constexpr Quantity() = default; //! Construct with value in celeritas native units explicit CELER_CONSTEXPR_FUNCTION Quantity(value_type value) : value_(value) { } //! Construct implicitly from a unitless quantity CELER_CONSTEXPR_FUNCTION Quantity(Unitless uq) : value_(uq.value_) {} //! Get numeric value, discarding units CELER_CONSTEXPR_FUNCTION value_type value() const { return value_; } private: value_type value_{}; }; //---------------------------------------------------------------------------// //! \cond #define CELER_DEFINE_QUANTITY_CMP(TOKEN) \ template<class U, class T> \ CELER_CONSTEXPR_FUNCTION bool operator TOKEN(Quantity<U, T> lhs, \ Quantity<U, T> rhs) \ { \ return lhs.value() TOKEN rhs.value(); \ } \ template<class U, class T> \ CELER_CONSTEXPR_FUNCTION bool operator TOKEN( \ Quantity<U, T> lhs, detail::UnitlessQuantity<T> rhs) \ { \ return lhs.value() TOKEN rhs.value_; \ } \ template<class U, class T> \ CELER_CONSTEXPR_FUNCTION bool operator TOKEN( \ detail::UnitlessQuantity<T> lhs, Quantity<U, T> rhs) \ { \ return lhs.value_ TOKEN rhs.value(); \ } \ namespace detail \ { \ template<class T> \ CELER_CONSTEXPR_FUNCTION bool \ operator TOKEN(UnitlessQuantity<T> lhs, UnitlessQuantity<T> rhs) \ { \ return lhs.value_ TOKEN rhs.value_; \ } \ } //!@{ //! Comparisons for Quantity CELER_DEFINE_QUANTITY_CMP(==) CELER_DEFINE_QUANTITY_CMP(!=) CELER_DEFINE_QUANTITY_CMP(<) CELER_DEFINE_QUANTITY_CMP(>) CELER_DEFINE_QUANTITY_CMP(<=) CELER_DEFINE_QUANTITY_CMP(>=) //!@} #undef CELER_DEFINE_QUANTITY_CMP //! \endcond //---------------------------------------------------------------------------// //! Value is C1::value() / C2::value() template<class C1, class C2> struct UnitDivide { //! Get the conversion factor of the resulting unit static CELER_CONSTEXPR_FUNCTION real_type value() { return C1::value() / C2::value(); } }; //! Value is C1::value() * C2::value() template<class C1, class C2> struct UnitProduct { //! Get the conversion factor of the resulting unit static CELER_CONSTEXPR_FUNCTION real_type value() { return C1::value() * C2::value(); } }; //---------------------------------------------------------------------------// // FREE FUNCTIONS //---------------------------------------------------------------------------// /*! * Get a zero quantity (analogous to nullptr). */ CELER_CONSTEXPR_FUNCTION detail::UnitlessQuantity<real_type> zero_quantity() { return {0}; } //---------------------------------------------------------------------------// /*! * Get a quantitity greater than any other numeric quantity. */ CELER_CONSTEXPR_FUNCTION detail::UnitlessQuantity<real_type> max_quantity() { return {numeric_limits<real_type>::infinity()}; } //---------------------------------------------------------------------------// /*! * Get a quantitity less than any other numeric quantity. */ CELER_CONSTEXPR_FUNCTION detail::UnitlessQuantity<real_type> neg_max_quantity() { return {-numeric_limits<real_type>::infinity()}; } //---------------------------------------------------------------------------// /*! * Swap two Quantities. */ template<class U, class V> CELER_CONSTEXPR_FUNCTION void swap(Quantity<U, V>& a, Quantity<U, V>& b) noexcept { Quantity<U, V> tmp{a}; a = b; b = tmp; } //---------------------------------------------------------------------------// /*! * Convert the given quantity into the native Celeritas unit system. * * \code assert(native_value_from(Quantity<CLight>{1}) == 2.998e10 * centimeter/second); * \endcode */ template<class UnitT, class ValueT> CELER_CONSTEXPR_FUNCTION auto native_value_from(Quantity<UnitT, ValueT> quant) -> decltype(auto) { return quant.value() * UnitT::value(); } //! Old spelling of "native_value_from". template<class UnitT, class ValueT> [[deprecated("use 'native_value_from'")]] CELER_CONSTEXPR_FUNCTION auto unit_cast(Quantity<UnitT, ValueT> quant) -> decltype(auto) { return quant.value() * UnitT::value(); } //---------------------------------------------------------------------------// /*! * Create a quantity from a value in the Celeritas unit system. * * This function can be used for defining a constant for use in another unit * system (typically a "natural" unit system for use in physics kernels). * * \code constexpr LightSpeed c = native_value_to<LightSpeed>(constants::c_light); assert(c.value() == 1); * \endcode */ template<class Q> CELER_CONSTEXPR_FUNCTION Q native_value_to(typename Q::value_type value) { using value_type = typename Q::value_type; using unit_type = typename Q::unit_type; return Q{value * (value_type{1} / unit_type::value())}; } //---------------------------------------------------------------------------// /*! * Use the value of a Quantity. * * The redundant unit type in the function signature is to make coupling safer * across different parts of the code and to make the user code more readable. * * \code assert(value_as<LightSpeed>(LightSpeed{1}) == 1); * \endcode */ template<class Q, class SrcUnitT, class ValueT> CELER_CONSTEXPR_FUNCTION auto value_as(Quantity<SrcUnitT, ValueT> quant) -> ValueT { static_assert(std::is_same<Q, Quantity<SrcUnitT, ValueT>>::value, "quantity units do not match"); return quant.value(); } //---------------------------------------------------------------------------// } // namespace celeritas
#include<iostream> #include<stdlib.h> #define size 100 using namespace std; class Stack{ private: int stack[size]; int element; int top; public: Stack(){ top=-1; } void push(int value){ element = value; if(top==size-1) cout<<"stack overflow!"; else{ top++; stack[top]=element; } } void pop(){ if(top==-1) cout<<"stack underflow!"; else top--; } void traversal(){ if(top==-1) cout<<"no elements in stack!"; else{ for(int i=top;i>=0;i--) cout<<stack[i]<<"\n"; } } int ret_top(){ return top; } bool empty(){ if(top==-1) return true; return false; } bool full(){ if(top==size-1) return true; return false; } }; int main(){ int element,choice; Stack obj; do{ start: cout<<"\n\nPress enter to continue..."; system("cls"); printf("\n 1.push \n 2.pop \n 3.display \n 4.exit \n 5.clear screen \n"); printf("enter your choice: "); scanf("%d",&choice); switch(choice) { case 1: printf("Enter element: "); scanf("%d",&element); obj.push(element); break; case 2: obj.pop(); break; case 3: obj.traversal(); break; case 4: exit(0); case 5: system("cls"); break; default: printf("wrong choice!!"); goto start; } }while(choice!=6); }
#include <bits/stdc++.h> using namespace std; // Function to find mean of grouped data. float mean(float mid[], int freq[], int n) { float sum = 0, freqSum = 0; for (int i = 0; i < n; i++) { sum = sum + mid[i] * freq[i]; freqSum = freqSum + freq[i]; } return sum / freqSum; } // deviation of grouped data. float groupedSD(float lower_limit[], float upper_limit[], int freq[], int n) { float mid[n], sum = 0, freqSum = 0, sd; for (int i = 0; i < n; i++) { mid[i] = (lower_limit[i] + upper_limit[i]) / 2; sum = sum + freq[i] * mid[i] * mid[i]; freqSum = freqSum + freq[i]; } // Formula to find standard deviation of grouped data. sd = sqrt((sum - freqSum * mean(mid, freq, n) * mean(mid, freq, n)) / (freqSum - 1)); return sd; } int main() { // the lower limit of interval. float lower_limit[] = {50, 61, 71, 86, 96}; // the upper limit of interval. float upper_limit[] = {60, 70, 85, 95, 100}; int freq[] = {9, 7, 9, 12, 8}; int n = sizeof(lower_limit) / sizeof(lower_limit[0]); cout << groupedSD(lower_limit, upper_limit, freq, n); return 0; }
#include "sgtexturematerial.h" #include "texture/sggridimagetexture.h" #define STB_IMAGE_IMPLEMENTATION #include <stb/stb_image.h> #include <string> static std::unordered_map<std::string, unsigned> g_nameMapToKey; static SGGridImageTexture g_imgTex(2048, 2048, Image::Format_RGBA, 256, 256); class SGTextureMaterialShader : public SGMaterialShader { public: SGTextureMaterialShader() { build(); } ~SGTextureMaterialShader() {} virtual void updateState(const float *mat4, const SGNodeState *stat) override { m_program.setMat4(m_matrixUniform, mat4); m_program.setFloat(m_opacityUniform, stat->opacity); } virtual const char* vertexShader() const override { return "attribute vec4 posAttr;\n" "attribute vec4 texAttr;\n" "varying vec4 tex;\n" "uniform mat4 matrix;\n" "void main() {\n" " tex = texAttr;\n" " gl_Position = matrix * posAttr;\n" "}\n"; } virtual const char* fragmentShader() const override { return "varying vec4 tex;\n" "uniform sampler2D uSampler;\n" "uniform float opacity;\n" "void main() {\n" " vec4 color = texture2D(uSampler, vec2(tex.x, tex.y)); \n" " gl_FragColor = vec4(color.rgb, color.a*opacity); \n" "}\n"; } virtual char const* const* attributeNames() const override { static const char* const attr[] = { "posAttr", "texAttr", 0 }; return attr; } bool build() { compile(); m_matrixUniform = m_program.uniformLocation("matrix"); m_opacityUniform = m_program.uniformLocation("opacity"); return true; } private: unsigned m_matrixUniform; unsigned m_opacityUniform; }; SGTextureMaterial::SGTextureMaterial() { m_tex = &g_imgTex; } E_MaterialType SGTextureMaterial::type() const { return E_MaterialType::TextureMaterialType; } SGMaterialShader * SGTextureMaterial::createShader() const { return new SGTextureMaterialShader; } const RectF& SGTextureMaterial::setImage(const char * path) { unsigned uid = 0; if (g_nameMapToKey.count(path)) { uid = g_nameMapToKey.at(path); } else { //come new image int x = 0, y = 0, n = 0; unsigned char *data = stbi_load(path, &x, &y, &n, 0); if (!data) { printf("image open failed...[%s]\n", path); } else { Image img(x, y, data, (Image::ImageFormat)n); uid = g_imgTex.add(img); //update cache g_nameMapToKey.emplace(std::make_pair(path, uid)); } } return g_imgTex.retrieve(uid); } SGTexture * SGTextureMaterial::texture() const { return m_tex; } void SGTextureMaterial::syncState() { m_tex->bind(); }
// Copyright (c) 2017-2021, The Khronos Group Inc. // // SPDX-License-Identifier: Apache-2.0 #include "pch.h" #include "common.h" #include "platformplugin.h" #ifdef XR_USE_PLATFORM_XLIB namespace { struct XlibPlatformPlugin : public IPlatformPlugin { XlibPlatformPlugin(const std::shared_ptr<Options>& /*unused*/) {} std::vector<std::string> GetInstanceExtensions() const override { return {}; } XrBaseInStructure* GetInstanceCreateExtension() const override { return nullptr; } }; } // namespace std::shared_ptr<IPlatformPlugin> CreatePlatformPlugin_Xlib(const std::shared_ptr<Options>& options) { return std::make_shared<XlibPlatformPlugin>(options); } #endif
// // c16rtomb.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // #include <uchar.h> #include <corecrt_internal_mbstring.h> using namespace __crt_mbstring; namespace { inline void store_first_surrogate(char16_t c16, mbstate_t* ps) { // Store the first (high) surrogate masked and shifted, so that all that's left to do // is to add the maksed second surrogate. // Note: _Wchar is the only field used in mbstate_t for this function const char32_t c32 = ((c16 & ~0xd800) << 10) + 0x10000; ps->_Wchar = c32; } inline char32_t combine_second_surrogate(char16_t c16, mbstate_t* ps) { return ps->_Wchar + (c16 & ~0xdc00); } inline constexpr bool has_surrogate(mbstate_t* ps) { return ps->_Wchar != 0; } inline constexpr bool is_first_surrogate(char16_t c16) { // UTF-16 high surrogate return 0xd800 <= c16 && c16 <= 0xdbff; } inline constexpr bool is_second_surrogate(char16_t c16) { // UTF-16 low surrogate return 0xdc00 <= c16 && c16 <= 0xdfff; } } extern "C" size_t __cdecl c16rtomb(char* s, char16_t c16, mbstate_t* ps) { // TODO: Bug 13307590 says this is always assuming UTF-8. return __c16rtomb_utf8(s, c16, ps); } size_t __cdecl __crt_mbstring::__c16rtomb_utf8(char* s, char16_t c16, mbstate_t* ps) { static mbstate_t internal_pst{}; if (ps == nullptr) { ps = &internal_pst; } if (!has_surrogate(ps)) { if (is_second_surrogate(c16)) { return return_illegal_sequence(ps); } else if (is_first_surrogate(c16)) { store_first_surrogate(c16, ps); return 0; } else { return c32rtomb(s, static_cast<char32_t>(c16), ps); } } else { // We've already seen the first (high) surrogate, so we're // expecting to complete this code point with its other half // in the second (low) surrogate if (!is_second_surrogate(c16)) { return return_illegal_sequence(ps); } const char32_t c32 = combine_second_surrogate(c16, ps); mbstate_t temp{}; const size_t retval = c32rtomb(s, c32, &temp); return reset_and_return(retval, ps); } }
// // Created by rui zhou on 2019-11-22. //
#include "vstgui.cpp" #include "lib/platform/linux/linuxstring.cpp" #include "lib/platform/linux/x11frame.cpp" #include "lib/platform/linux/x11platform.cpp" #include "lib/platform/linux/x11timer.cpp" #include "lib/platform/linux/cairobitmap.cpp" #include "lib/platform/linux/cairocontext.cpp" #include "lib/platform/linux/cairofont.cpp" #include "lib/platform/linux/cairogradient.cpp" #include "lib/platform/linux/cairopath.cpp" #include "lib/platform/linux/gtkoptionmenu.cpp" #include "lib/platform/linux/gtktextedit.cpp"
/* * Copyright (c) 2014 Advanced Micro Devices, Inc. * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2001-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Nathan Binkert * Steve Reinhardt * Ali Saidi */ #include "sim/process.hh" #include <fcntl.h> #include <unistd.h> #include <array> #include <map> #include <string> #include <vector> #include "base/intmath.hh" #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "base/statistics.hh" #include "config/the_isa.hh" #include "cpu/thread_context.hh" #include "mem/page_table.hh" #include "mem/se_translating_port_proxy.hh" #include "params/LiveProcess.hh" #include "params/Process.hh" #include "sim/emul_driver.hh" #include "sim/syscall_desc.hh" #include "sim/system.hh" #if THE_ISA == ALPHA_ISA #include "arch/alpha/linux/process.hh" #elif THE_ISA == SPARC_ISA #include "arch/sparc/linux/process.hh" #include "arch/sparc/solaris/process.hh" #elif THE_ISA == MIPS_ISA #include "arch/mips/linux/process.hh" #elif THE_ISA == ARM_ISA #include "arch/arm/linux/process.hh" #include "arch/arm/freebsd/process.hh" #elif THE_ISA == X86_ISA #include "arch/x86/linux/process.hh" #elif THE_ISA == POWER_ISA #include "arch/power/linux/process.hh" #elif THE_ISA == RISCV_ISA #include "arch/riscv/linux/process.hh" #else #error "THE_ISA not set" #endif using namespace std; using namespace TheISA; // current number of allocated processes int num_processes = 0; template<class IntType> AuxVector<IntType>::AuxVector(IntType type, IntType val) { a_type = TheISA::htog(type); a_val = TheISA::htog(val); } template struct AuxVector<uint32_t>; template struct AuxVector<uint64_t>; static int openFile(const string& filename, int flags, mode_t mode) { int sim_fd = open(filename.c_str(), flags, mode); if (sim_fd != -1) return sim_fd; fatal("Unable to open %s with mode %O", filename, mode); } static int openInputFile(const string &filename) { return openFile(filename, O_RDONLY, 0); } static int openOutputFile(const string &filename) { return openFile(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664); } Process::Process(ProcessParams * params) : SimObject(params), system(params->system), brk_point(0), stack_base(0), stack_size(0), stack_min(0), max_stack_size(params->max_stack_size), next_thread_stack_base(0), useArchPT(params->useArchPT), kvmInSE(params->kvmInSE), pTable(useArchPT ? static_cast<PageTableBase *>(new ArchPageTable(name(), _pid, system)) : static_cast<PageTableBase *>(new FuncPageTable(name(), _pid))), initVirtMem(system->getSystemPort(), this, SETranslatingPortProxy::Always), fd_array(make_shared<array<FDEntry, NUM_FDS>>()), imap {{"", -1}, {"cin", STDIN_FILENO}, {"stdin", STDIN_FILENO}}, oemap{{"", -1}, {"cout", STDOUT_FILENO}, {"stdout", STDOUT_FILENO}, {"cerr", STDERR_FILENO}, {"stderr", STDERR_FILENO}}, _uid(params->uid), _euid(params->euid), _gid(params->gid), _egid(params->egid), _pid(params->pid), _ppid(params->ppid) { int sim_fd; std::map<string,int>::iterator it; // Search through the input options and set fd if match is found; // otherwise, open an input file and seek to location. FDEntry *fde_stdin = getFDEntry(STDIN_FILENO); if ((it = imap.find(params->input)) != imap.end()) sim_fd = it->second; else sim_fd = openInputFile(params->input); fde_stdin->set(sim_fd, params->input, O_RDONLY, -1, false); // Search through the output/error options and set fd if match is found; // otherwise, open an output file and seek to location. FDEntry *fde_stdout = getFDEntry(STDOUT_FILENO); if ((it = oemap.find(params->output)) != oemap.end()) sim_fd = it->second; else sim_fd = openOutputFile(params->output); fde_stdout->set(sim_fd, params->output, O_WRONLY | O_CREAT | O_TRUNC, 0664, false); FDEntry *fde_stderr = getFDEntry(STDERR_FILENO); if (params->output == params->errout) // Reuse the same file descriptor if these match. sim_fd = fde_stdout->fd; else if ((it = oemap.find(params->errout)) != oemap.end()) sim_fd = it->second; else sim_fd = openOutputFile(params->errout); fde_stderr->set(sim_fd, params->errout, O_WRONLY | O_CREAT | O_TRUNC, 0664, false); mmap_end = 0; nxm_start = nxm_end = 0; // other parameters will be initialized when the program is loaded } void Process::regStats() { SimObject::regStats(); using namespace Stats; num_syscalls .name(name() + ".num_syscalls") .desc("Number of system calls") ; } void Process::inheritFDArray(Process *p) { fd_array = p->fd_array; } ThreadContext * Process::findFreeContext() { for (int id : contextIds) { ThreadContext *tc = system->getThreadContext(id); if (tc->status() == ThreadContext::Halted) return tc; } return NULL; } void Process::initState() { if (contextIds.empty()) fatal("Process %s is not associated with any HW contexts!\n", name()); // first thread context for this process... initialize & enable ThreadContext *tc = system->getThreadContext(contextIds[0]); // mark this context as active so it will start ticking. tc->activate(); pTable->initState(tc); } DrainState Process::drain() { findFileOffsets(); return DrainState::Drained; } int Process::allocFD(int sim_fd, const string& filename, int flags, int mode, bool pipe) { for (int free_fd = 0; free_fd < fd_array->size(); free_fd++) { FDEntry *fde = getFDEntry(free_fd); if (fde->isFree()) { fde->set(sim_fd, filename, flags, mode, pipe); return free_fd; } } fatal("Out of target file descriptors"); } void Process::resetFDEntry(int tgt_fd) { FDEntry *fde = getFDEntry(tgt_fd); assert(fde->fd > -1); fde->reset(); } int Process::getSimFD(int tgt_fd) { FDEntry *entry = getFDEntry(tgt_fd); return entry ? entry->fd : -1; } FDEntry * Process::getFDEntry(int tgt_fd) { assert(0 <= tgt_fd && tgt_fd < fd_array->size()); return &(*fd_array)[tgt_fd]; } int Process::getTgtFD(int sim_fd) { for (int index = 0; index < fd_array->size(); index++) if ((*fd_array)[index].fd == sim_fd) return index; return -1; } void Process::allocateMem(Addr vaddr, int64_t size, bool clobber) { int npages = divCeil(size, (int64_t)PageBytes); Addr paddr = system->allocPhysPages(npages); pTable->map(vaddr, paddr, size, clobber ? PageTableBase::Clobber : PageTableBase::Zero); } bool Process::fixupStackFault(Addr vaddr) { // Check if this is already on the stack and there's just no page there // yet. if (vaddr >= stack_min && vaddr < stack_base) { allocateMem(roundDown(vaddr, PageBytes), PageBytes); return true; } // We've accessed the next page of the stack, so extend it to include // this address. if (vaddr < stack_min && vaddr >= stack_base - max_stack_size) { while (vaddr < stack_min) { stack_min -= TheISA::PageBytes; if (stack_base - stack_min > max_stack_size) fatal("Maximum stack size exceeded\n"); allocateMem(stack_min, TheISA::PageBytes); inform("Increasing stack size by one page."); }; return true; } return false; } void Process::fixFileOffsets() { auto seek = [] (FDEntry *fde) { if (lseek(fde->fd, fde->fileOffset, SEEK_SET) < 0) fatal("Unable to see to location in %s", fde->filename); }; std::map<string,int>::iterator it; // Search through the input options and set fd if match is found; // otherwise, open an input file and seek to location. FDEntry *fde_stdin = getFDEntry(STDIN_FILENO); // Check if user has specified a different input file, and if so, use it // instead of the file specified in the checkpoint. This also resets the // file offset from the checkpointed value string new_in = ((ProcessParams*)params())->input; if (new_in != fde_stdin->filename) { warn("Using new input file (%s) rather than checkpointed (%s)\n", new_in, fde_stdin->filename); fde_stdin->filename = new_in; fde_stdin->fileOffset = 0; } if ((it = imap.find(fde_stdin->filename)) != imap.end()) { fde_stdin->fd = it->second; } else { fde_stdin->fd = openInputFile(fde_stdin->filename); seek(fde_stdin); } // Search through the output/error options and set fd if match is found; // otherwise, open an output file and seek to location. FDEntry *fde_stdout = getFDEntry(STDOUT_FILENO); // Check if user has specified a different output file, and if so, use it // instead of the file specified in the checkpoint. This also resets the // file offset from the checkpointed value string new_out = ((ProcessParams*)params())->output; if (new_out != fde_stdout->filename) { warn("Using new output file (%s) rather than checkpointed (%s)\n", new_out, fde_stdout->filename); fde_stdout->filename = new_out; fde_stdout->fileOffset = 0; } if ((it = oemap.find(fde_stdout->filename)) != oemap.end()) { fde_stdout->fd = it->second; } else { fde_stdout->fd = openOutputFile(fde_stdout->filename); seek(fde_stdout); } FDEntry *fde_stderr = getFDEntry(STDERR_FILENO); // Check if user has specified a different error file, and if so, use it // instead of the file specified in the checkpoint. This also resets the // file offset from the checkpointed value string new_err = ((ProcessParams*)params())->errout; if (new_err != fde_stderr->filename) { warn("Using new error file (%s) rather than checkpointed (%s)\n", new_err, fde_stderr->filename); fde_stderr->filename = new_err; fde_stderr->fileOffset = 0; } if (fde_stdout->filename == fde_stderr->filename) { // Reuse the same file descriptor if these match. fde_stderr->fd = fde_stdout->fd; } else if ((it = oemap.find(fde_stderr->filename)) != oemap.end()) { fde_stderr->fd = it->second; } else { fde_stderr->fd = openOutputFile(fde_stderr->filename); seek(fde_stderr); } for (int tgt_fd = 3; tgt_fd < fd_array->size(); tgt_fd++) { FDEntry *fde = getFDEntry(tgt_fd); if (fde->fd == -1) continue; if (fde->isPipe) { if (fde->filename == "PIPE-WRITE") continue; assert(fde->filename == "PIPE-READ"); int fds[2]; if (pipe(fds) < 0) fatal("Unable to create new pipe"); fde->fd = fds[0]; FDEntry *fde_write = getFDEntry(fde->readPipeSource); assert(fde_write->filename == "PIPE-WRITE"); fde_write->fd = fds[1]; } else { fde->fd = openFile(fde->filename.c_str(), fde->flags, fde->mode); seek(fde); } } } void Process::findFileOffsets() { for (auto& fde : *fd_array) { if (fde.fd != -1) fde.fileOffset = lseek(fde.fd, 0, SEEK_CUR); } } void Process::setReadPipeSource(int read_pipe_fd, int source_fd) { FDEntry *fde = getFDEntry(read_pipe_fd); assert(source_fd >= -1); fde->readPipeSource = source_fd; } void Process::serialize(CheckpointOut &cp) const { SERIALIZE_SCALAR(brk_point); SERIALIZE_SCALAR(stack_base); SERIALIZE_SCALAR(stack_size); SERIALIZE_SCALAR(stack_min); SERIALIZE_SCALAR(next_thread_stack_base); SERIALIZE_SCALAR(mmap_end); SERIALIZE_SCALAR(nxm_start); SERIALIZE_SCALAR(nxm_end); pTable->serialize(cp); for (int x = 0; x < fd_array->size(); x++) { (*fd_array)[x].serializeSection(cp, csprintf("FDEntry%d", x)); } } void Process::unserialize(CheckpointIn &cp) { UNSERIALIZE_SCALAR(brk_point); UNSERIALIZE_SCALAR(stack_base); UNSERIALIZE_SCALAR(stack_size); UNSERIALIZE_SCALAR(stack_min); UNSERIALIZE_SCALAR(next_thread_stack_base); UNSERIALIZE_SCALAR(mmap_end); UNSERIALIZE_SCALAR(nxm_start); UNSERIALIZE_SCALAR(nxm_end); pTable->unserialize(cp); for (int x = 0; x < fd_array->size(); x++) { FDEntry *fde = getFDEntry(x); fde->unserializeSection(cp, csprintf("FDEntry%d", x)); } fixFileOffsets(); // The above returns a bool so that you could do something if you don't // find the param in the checkpoint if you wanted to, like set a default // but in this case we'll just stick with the instantiated value if not // found. } bool Process::map(Addr vaddr, Addr paddr, int size, bool cacheable) { pTable->map(vaddr, paddr, size, cacheable ? PageTableBase::Zero : PageTableBase::Uncacheable); return true; } //////////////////////////////////////////////////////////////////////// // // LiveProcess member definitions // //////////////////////////////////////////////////////////////////////// LiveProcess::LiveProcess(LiveProcessParams *params, ObjectFile *_objFile) : Process(params), objFile(_objFile), argv(params->cmd), envp(params->env), cwd(params->cwd), executable(params->executable), drivers(params->drivers) { // load up symbols, if any... these may be used for debugging or // profiling. if (!debugSymbolTable) { debugSymbolTable = new SymbolTable(); if (!objFile->loadGlobalSymbols(debugSymbolTable) || !objFile->loadLocalSymbols(debugSymbolTable) || !objFile->loadWeakSymbols(debugSymbolTable)) { // didn't load any symbols delete debugSymbolTable; debugSymbolTable = NULL; } } } void LiveProcess::syscall(int64_t callnum, ThreadContext *tc) { num_syscalls++; SyscallDesc *desc = getDesc(callnum); if (desc == NULL) fatal("Syscall %d out of range", callnum); desc->doSyscall(callnum, this, tc); } IntReg LiveProcess::getSyscallArg(ThreadContext *tc, int &i, int width) { return getSyscallArg(tc, i); } EmulatedDriver * LiveProcess::findDriver(std::string filename) { for (EmulatedDriver *d : drivers) { if (d->match(filename)) return d; } return NULL; } void LiveProcess::updateBias() { ObjectFile *interp = objFile->getInterpreter(); if (!interp || !interp->relocatable()) return; // Determine how large the interpreters footprint will be in the process // address space. Addr interp_mapsize = roundUp(interp->mapSize(), TheISA::PageBytes); // We are allocating the memory area; set the bias to the lowest address // in the allocated memory region. Addr ld_bias = mmapGrowsDown() ? mmap_end - interp_mapsize : mmap_end; // Adjust the process mmap area to give the interpreter room; the real // execve system call would just invoke the kernel's internal mmap // functions to make these adjustments. mmap_end = mmapGrowsDown() ? ld_bias : mmap_end + interp_mapsize; interp->updateBias(ld_bias); } ObjectFile * LiveProcess::getInterpreter() { return objFile->getInterpreter(); } Addr LiveProcess::getBias() { ObjectFile *interp = getInterpreter(); return interp ? interp->bias() : objFile->bias(); } Addr LiveProcess::getStartPC() { ObjectFile *interp = getInterpreter(); return interp ? interp->entryPoint() : objFile->entryPoint(); } LiveProcess * LiveProcess::create(LiveProcessParams * params) { LiveProcess *process = NULL; // If not specified, set the executable parameter equal to the // simulated system's zeroth command line parameter if (params->executable == "") { params->executable = params->cmd[0]; } ObjectFile *objFile = createObjectFile(params->executable); if (objFile == NULL) { fatal("Can't load object file %s", params->executable); } #if THE_ISA == ALPHA_ISA if (objFile->getArch() != ObjectFile::Alpha) fatal("Object file architecture does not match compiled ISA (Alpha)."); switch (objFile->getOpSys()) { case ObjectFile::UnknownOpSys: warn("Unknown operating system; assuming Linux."); // fall through case ObjectFile::Linux: process = new AlphaLinuxProcess(params, objFile); break; default: fatal("Unknown/unsupported operating system."); } #elif THE_ISA == SPARC_ISA if (objFile->getArch() != ObjectFile::SPARC64 && objFile->getArch() != ObjectFile::SPARC32) fatal("Object file architecture does not match compiled ISA (SPARC)."); switch (objFile->getOpSys()) { case ObjectFile::UnknownOpSys: warn("Unknown operating system; assuming Linux."); // fall through case ObjectFile::Linux: if (objFile->getArch() == ObjectFile::SPARC64) { process = new Sparc64LinuxProcess(params, objFile); } else { process = new Sparc32LinuxProcess(params, objFile); } break; case ObjectFile::Solaris: process = new SparcSolarisProcess(params, objFile); break; default: fatal("Unknown/unsupported operating system."); } #elif THE_ISA == X86_ISA if (objFile->getArch() != ObjectFile::X86_64 && objFile->getArch() != ObjectFile::I386) fatal("Object file architecture does not match compiled ISA (x86)."); switch (objFile->getOpSys()) { case ObjectFile::UnknownOpSys: warn("Unknown operating system; assuming Linux."); // fall through case ObjectFile::Linux: if (objFile->getArch() == ObjectFile::X86_64) { process = new X86_64LinuxProcess(params, objFile); } else { process = new I386LinuxProcess(params, objFile); } break; default: fatal("Unknown/unsupported operating system."); } #elif THE_ISA == MIPS_ISA if (objFile->getArch() != ObjectFile::Mips) fatal("Object file architecture does not match compiled ISA (MIPS)."); switch (objFile->getOpSys()) { case ObjectFile::UnknownOpSys: warn("Unknown operating system; assuming Linux."); // fall through case ObjectFile::Linux: process = new MipsLinuxProcess(params, objFile); break; default: fatal("Unknown/unsupported operating system."); } #elif THE_ISA == ARM_ISA ObjectFile::Arch arch = objFile->getArch(); if (arch != ObjectFile::Arm && arch != ObjectFile::Thumb && arch != ObjectFile::Arm64) fatal("Object file architecture does not match compiled ISA (ARM)."); switch (objFile->getOpSys()) { case ObjectFile::UnknownOpSys: warn("Unknown operating system; assuming Linux."); // fall through case ObjectFile::Linux: if (arch == ObjectFile::Arm64) { process = new ArmLinuxProcess64(params, objFile, objFile->getArch()); } else { process = new ArmLinuxProcess32(params, objFile, objFile->getArch()); } break; case ObjectFile::FreeBSD: if (arch == ObjectFile::Arm64) { process = new ArmFreebsdProcess64(params, objFile, objFile->getArch()); } else { process = new ArmFreebsdProcess32(params, objFile, objFile->getArch()); } break; case ObjectFile::LinuxArmOABI: fatal("M5 does not support ARM OABI binaries. Please recompile with an" " EABI compiler."); default: fatal("Unknown/unsupported operating system."); } #elif THE_ISA == POWER_ISA if (objFile->getArch() != ObjectFile::Power) fatal("Object file architecture does not match compiled ISA (Power)."); switch (objFile->getOpSys()) { case ObjectFile::UnknownOpSys: warn("Unknown operating system; assuming Linux."); // fall through case ObjectFile::Linux: process = new PowerLinuxProcess(params, objFile); break; default: fatal("Unknown/unsupported operating system."); } #elif THE_ISA == RISCV_ISA if (objFile->getArch() != ObjectFile::Riscv) fatal("Object file architecture does not match compiled ISA (RISCV)."); switch (objFile->getOpSys()) { case ObjectFile::UnknownOpSys: warn("Unknown operating system; assuming Linux."); // fall through case ObjectFile::Linux: process = new RiscvLinuxProcess(params, objFile); break; default: fatal("Unknown/unsupported operating system."); } #else #error "THE_ISA not set" #endif if (process == NULL) fatal("Unknown error creating process object."); return process; } LiveProcess * LiveProcessParams::create() { return LiveProcess::create(this); }
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/array_ops.cc. #include <limits> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/kernels/concat_lib.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/types.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; #if GOOGLE_CUDA typedef Eigen::GpuDevice GPUDevice; #endif // GOOGLE_CUDA #ifdef TENSORFLOW_USE_SYCL typedef Eigen::SyclDevice SYCLDevice; #endif // TENSORFLOW_USE_SYCL enum AxisArgumentName { NAME_IS_AXIS, NAME_IS_CONCAT_DIM }; // -------------------------------------------------------------------------- template <typename Device, typename T, AxisArgumentName AxisArgName> class ConcatBaseOp : public OpKernel { public: typedef std::vector<std::unique_ptr<typename TTypes<T, 2>::ConstMatrix>> ConstMatrixVector; explicit ConcatBaseOp(OpKernelConstruction* c) : OpKernel(c) {} void Compute(OpKernelContext* c) override { const Tensor* concat_dim_tensor; const char* axis_attribute_name = AxisArgName == NAME_IS_AXIS ? "axis" : AxisArgName == NAME_IS_CONCAT_DIM ? "concat_dim" : "<invalid>"; OP_REQUIRES_OK(c, c->input(axis_attribute_name, &concat_dim_tensor)); OP_REQUIRES(c, IsLegacyScalar(concat_dim_tensor->shape()), errors::InvalidArgument( axis_attribute_name, " tensor should be a scalar integer, but got shape ", concat_dim_tensor->shape().DebugString())); int64 concat_dim; // In case of ConcatV2, "axis" could be int32 or int64 if (AxisArgName == NAME_IS_AXIS) { OP_REQUIRES( c, (concat_dim_tensor->dtype() == DT_INT32 || concat_dim_tensor->dtype() == DT_INT64), errors::InvalidArgument(axis_attribute_name, " tensor should be int32 or int64, but got ", DataTypeString(concat_dim_tensor->dtype()))); } else { OP_REQUIRES(c, (concat_dim_tensor->dtype() == DT_INT32), errors::InvalidArgument( axis_attribute_name, " tensor should be int32, but got ", DataTypeString(concat_dim_tensor->dtype()))); } if (concat_dim_tensor->dtype() == DT_INT32) { concat_dim = internal::SubtleMustCopy(concat_dim_tensor->scalar<int32>()()); } else { concat_dim = internal::SubtleMustCopy(concat_dim_tensor->scalar<int64>()()); } OpInputList values; OP_REQUIRES_OK(c, c->input_list("values", &values)); const int N = values.size(); const int input_dims = values[0].dims(); const TensorShape& input_shape = values[0].shape(); int32 axis = concat_dim < 0 ? concat_dim + input_dims : concat_dim; OP_REQUIRES(c, (0 <= axis && axis < input_dims) || (allow_legacy_scalars() && concat_dim == 0), errors::InvalidArgument( "ConcatOp : Expected concatenating dimensions in the range " "[", -input_dims, ", ", input_dims, "), but got ", concat_dim)); // Note that we reduce the concat of n-dimensional tensors into a two // dimensional concat. Assuming the dimensions of any input/output // tensor are {x0, x1,...,xn-1, y0, y1,...,ym-1}, where the concat is along // the dimension indicated with size y0, we flatten it to {x, y}, where y = // Prod_i(yi) and x = ((n > 0) ? Prod_i(xi) : 1). ConstMatrixVector inputs_flat; inputs_flat.reserve(N); int64 inputs_flat_dim0 = 1; for (int d = 0; d < axis; ++d) { inputs_flat_dim0 *= input_shape.dim_size(d); } int64 output_concat_dim = 0; const bool input_is_scalar = IsLegacyScalar(input_shape); for (int i = 0; i < N; ++i) { const auto& in = values[i]; const bool in_is_scalar = IsLegacyScalar(in.shape()); OP_REQUIRES( c, in.dims() == input_dims || (input_is_scalar && in_is_scalar), errors::InvalidArgument( "ConcatOp : Ranks of all input tensors should match: shape[0] = ", input_shape.DebugString(), " vs. shape[", i, "] = ", in.shape().DebugString())); for (int j = 0; j < input_dims; ++j) { if (j == axis) { continue; } OP_REQUIRES( c, in.dim_size(j) == input_shape.dim_size(j), errors::InvalidArgument( "ConcatOp : Dimensions of inputs should match: shape[0] = ", input_shape.DebugString(), " vs. shape[", i, "] = ", in.shape().DebugString())); } if (in.NumElements() > 0) { int64 inputs_flat_dim1 = in.NumElements() / inputs_flat_dim0; inputs_flat.emplace_back(new typename TTypes<T, 2>::ConstMatrix( in.shaped<T, 2>({inputs_flat_dim0, inputs_flat_dim1}))); } // TODO(irving): Remove check once !allow_legacy_scalars(). output_concat_dim += in.dims() > 0 ? in.dim_size(axis) : 1; } TensorShape output_shape(input_shape); // TODO(irving): Remove rank 0 case once !allow_legacy_scalars(). if (output_shape.dims() == 0) { output_shape.AddDim(output_concat_dim); } else { output_shape.set_dim(axis, output_concat_dim); } Tensor* output = nullptr; OP_REQUIRES_OK(c, c->allocate_output(0, output_shape, &output)); if (output->NumElements() > 0) { int64 output_dim1 = output->NumElements() / inputs_flat_dim0; auto output_flat = output->shaped<T, 2>({inputs_flat_dim0, output_dim1}); #if GOOGLE_CUDA if (std::is_same<Device, GPUDevice>::value) { ConcatGPU<T>(c, inputs_flat, output, &output_flat); return; } #endif // GOOGLE_CUDA #ifdef TENSORFLOW_USE_SYCL if (std::is_same<Device, SYCLDevice>::value) { ConcatSYCL<T>(c->eigen_sycl_device(), inputs_flat, &output_flat); return; } #endif // TENSORFLOW_USE_SYCL ConcatCPU<T>(c->device(), inputs_flat, &output_flat); } } }; template <typename Device, typename T> using ConcatOp = ConcatBaseOp<Device, T, NAME_IS_CONCAT_DIM>; template <typename Device, typename T> using ConcatV2Op = ConcatBaseOp<Device, T, NAME_IS_AXIS>; #define REGISTER_CONCAT(type) \ REGISTER_KERNEL_BUILDER(Name("Concat") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .HostMemory("concat_dim"), \ ConcatOp<CPUDevice, type>) \ REGISTER_KERNEL_BUILDER(Name("ConcatV2") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .HostMemory("axis"), \ ConcatV2Op<CPUDevice, type>) TF_CALL_POD_STRING_TYPES(REGISTER_CONCAT); REGISTER_CONCAT(quint8); REGISTER_CONCAT(qint8); REGISTER_CONCAT(quint16); REGISTER_CONCAT(qint16); REGISTER_CONCAT(qint32); #undef REGISTER_CONCAT #if GOOGLE_CUDA #define REGISTER_GPU(type) \ REGISTER_KERNEL_BUILDER(Name("Concat") \ .Device(DEVICE_GPU) \ .TypeConstraint<type>("T") \ .HostMemory("concat_dim"), \ ConcatOp<GPUDevice, type>) \ REGISTER_KERNEL_BUILDER(Name("ConcatV2") \ .Device(DEVICE_GPU) \ .TypeConstraint<type>("T") \ .HostMemory("axis"), \ ConcatV2Op<GPUDevice, type>) TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU); REGISTER_GPU(bfloat16); TF_CALL_uint8(REGISTER_GPU); TF_CALL_complex64(REGISTER_GPU); TF_CALL_complex128(REGISTER_GPU); TF_CALL_int64(REGISTER_GPU); REGISTER_GPU(bool); #undef REGISTER_GPU // A special GPU kernel for int32. // TODO(b/25387198): Also enable int32 in device memory. This kernel // registration requires all int32 inputs and outputs to be in host memory. REGISTER_KERNEL_BUILDER(Name("Concat") .Device(DEVICE_GPU) .TypeConstraint<int32>("T") .HostMemory("concat_dim") .HostMemory("values") .HostMemory("output"), ConcatOp<CPUDevice, int32>); REGISTER_KERNEL_BUILDER(Name("ConcatV2") .Device(DEVICE_GPU) .TypeConstraint<int32>("T") .HostMemory("values") .HostMemory("axis") .HostMemory("output"), ConcatV2Op<CPUDevice, int32>); #endif // GOOGLE_CUDA #ifdef TENSORFLOW_USE_SYCL #define REGISTER_SYCL(type) \ REGISTER_KERNEL_BUILDER(Name("Concat") \ .Device(DEVICE_SYCL) \ .TypeConstraint<type>("T") \ .HostMemory("concat_dim"), \ ConcatOp<SYCLDevice, type>) \ REGISTER_KERNEL_BUILDER(Name("ConcatV2") \ .Device(DEVICE_SYCL) \ .TypeConstraint<type>("T") \ .HostMemory("axis"), \ ConcatV2Op<SYCLDevice, type>) TF_CALL_GPU_NUMBER_TYPES_NO_HALF(REGISTER_SYCL); REGISTER_KERNEL_BUILDER(Name("Concat") .Device(DEVICE_SYCL) .TypeConstraint<int32>("T") .HostMemory("concat_dim") .HostMemory("values") .HostMemory("output"), ConcatOp<CPUDevice, int32>); REGISTER_KERNEL_BUILDER(Name("ConcatV2") .Device(DEVICE_SYCL) .TypeConstraint<int32>("T") .HostMemory("values") .HostMemory("axis") .HostMemory("output"), ConcatV2Op<CPUDevice, int32>); #undef REGISTER_SYCL #endif // TENSORFLOW_USE_SYCL class ConcatOffsetOp : public OpKernel { public: explicit ConcatOffsetOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) override { const Tensor& concat_dim = ctx->input(0); OP_REQUIRES( ctx, IsLegacyScalar(concat_dim.shape()), errors::InvalidArgument( "Concat dim tensor should be a scalar integer, but got shape ", concat_dim.shape().DebugString())); for (int i = 1; i < ctx->num_inputs(); ++i) { const Tensor& inp = ctx->input(i); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(inp.shape()), errors::InvalidArgument("input ", i, " should be a vector, but got shape ", inp.shape().DebugString())); } // Suppose a Concat() op needs to Concatenate N tensors, each of // which has the same number of dimensions. Their shapes match // except the concat dimension. // // E.g., say, we want to concatenate 3 tensors in the 2nd // dimension, and their shapes are: // // [2, 2, 5, 7] // [2, 3, 5, 7] // [2, 4, 5, 7] // // Here, N=3, cdim=1, dims=4. The concatenated tensor has shape // [2,9,5,7]. We will compute the cumulative sum along the 2nd // dimension to figure out each input's offset in the concatenated // output: // [0, 0, 0, 0] // [0, 2, 0, 0] // [0, 5, 0, 0] const int32 N = ctx->num_inputs() - 1; const Tensor& inp0 = ctx->input(1); auto inp0_vec = inp0.vec<int32>(); const int64 cdim = internal::SubtleMustCopy(concat_dim.scalar<int32>()()); const int64 dims = inp0.NumElements(); int32 axis = cdim < 0 ? cdim + dims : cdim; OP_REQUIRES(ctx, FastBoundsCheck(axis, dims), errors::InvalidArgument("Concat dim is out of range: ", cdim, " vs. ", dims)); int32 offset = 0; for (int i = 0; i < N; ++i) { const Tensor& inp = ctx->input(1 + i); OP_REQUIRES( ctx, dims == inp.NumElements(), errors::InvalidArgument("input ", i, " should contain ", dims, " elements, but got ", inp.NumElements())); auto inp_vec = inp.vec<int32>(); Tensor* out = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(i, {dims}, &out)); auto out_vec = out->vec<int32>(); for (int64 j = 0; j < dims; ++j) { if (j == axis) { out_vec(j) = offset; offset += inp_vec(j); } else { OP_REQUIRES(ctx, (inp0_vec(j) == inp_vec(j)), errors::InvalidArgument( "All dimensions except ", axis, " must match. Input ", i, " has shape [", inp.SummarizeValue(10), "] and doesn't match input 0 with shape [", inp0.SummarizeValue(10), "].")); out_vec(j) = 0; } } } } bool IsExpensive() override { return false; } }; REGISTER_KERNEL_BUILDER(Name("ConcatOffset").Device(DEVICE_CPU), ConcatOffsetOp); REGISTER_KERNEL_BUILDER(Name("ConcatOffset") .Device(DEVICE_GPU) .HostMemory("concat_dim") .HostMemory("shape") .HostMemory("offset"), ConcatOffsetOp); #ifdef TENSORFLOW_USE_SYCL REGISTER_KERNEL_BUILDER(Name("ConcatOffset") .Device(DEVICE_SYCL) .HostMemory("concat_dim") .HostMemory("shape") .HostMemory("offset"), ConcatOffsetOp); #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow
class Solution { public: vector<int> partitionLabels(string S) { vector<int>last(26,-1); int n = S.length(); for( int i = 0 ; i < n ; i++ ) last[S[i]-'a'] = i; vector<pair<int,int>> intervals; for( int l=0 , r=-1 ; l < n ; l++ ) { int c = S[l] - 'a'; if(r < l) intervals.push_back(make_pair(l,l)); r = max(r, last[c]); intervals[intervals.size()-1].second = r; } vector<int> ans; for( int i = 0 ; i < intervals.size() ; i++ ) ans.push_back( intervals[i].second - intervals[i].first + 1 ); return ans; } };
#include "video/Render.h" #include "video/Screen.h" using namespace Shiro; namespace Shiro { int RenderCopy(const Screen& screen, SDL_Texture *tex, const SDL_Rect *srcrect, SDL_Rect *dstrect) { if(screen.window == nullptr || screen.renderer == nullptr || tex == nullptr) { return -1; } float scaleX; float scaleY; SDL_RenderGetScale(screen.renderer, &scaleX, &scaleY); if(SDL_GetRenderTarget(screen.renderer) != nullptr) { if(dstrect != nullptr) { SDL_Rect scaledRect = { static_cast<int>(float(dstrect->x) * scaleX), static_cast<int>(float(dstrect->y) * scaleY), static_cast<int>(float(dstrect->w) * scaleX), static_cast<int>(float(dstrect->h) * scaleY), }; return SDL_RenderCopy(screen.renderer, tex, srcrect, &scaledRect); } else { return SDL_RenderCopy(screen.renderer, tex, srcrect, dstrect); } } if(dstrect == nullptr) { SDL_Rect rect = { screen.renderAreaX, screen.renderAreaY, screen.renderAreaW, screen.renderAreaH }; SDL_RenderSetScale(screen.renderer, 1.0, 1.0); int rc = SDL_RenderCopy(screen.renderer, tex, srcrect, &rect); SDL_RenderSetScale(screen.renderer, scaleX, scaleY); return rc; } int scaledRenderAreaX = static_cast<int>(float(screen.innerRenderAreaX) / scaleX); int scaledRenderAreaY = static_cast<int>(float(screen.innerRenderAreaY) / scaleY); SDL_Rect dst = { dstrect->x, dstrect->y, dstrect->w, dstrect->h }; dst.x += scaledRenderAreaX; dst.y += scaledRenderAreaY; return SDL_RenderCopy(screen.renderer, tex, srcrect, &dst); } int RenderCopyOuter(const Screen& screen, SDL_Texture *tex, const SDL_Rect *srcrect, SDL_Rect *dstrect, Render::Alignment alignment) { if(screen.window == nullptr || screen.renderer == nullptr || tex == nullptr) { return -1; } float scaleX; float scaleY; SDL_RenderGetScale(screen.renderer, &scaleX, &scaleY); if(SDL_GetRenderTarget(screen.renderer) != nullptr) { if(dstrect != nullptr) { SDL_Rect scaledRect = { static_cast<int>(float(dstrect->x) * scaleX), static_cast<int>(float(dstrect->y) * scaleY), static_cast<int>(float(dstrect->w) * scaleX), static_cast<int>(float(dstrect->h) * scaleY), }; return SDL_RenderCopy(screen.renderer, tex, srcrect, &scaledRect); } else { return SDL_RenderCopy(screen.renderer, tex, srcrect, dstrect); } } if(dstrect == nullptr) { SDL_Rect rect = { screen.renderAreaX, screen.renderAreaY, screen.renderAreaW, screen.renderAreaH }; SDL_RenderSetScale(screen.renderer, 1.0, 1.0); int rc = SDL_RenderCopy(screen.renderer, tex, srcrect, &rect); SDL_RenderSetScale(screen.renderer, scaleX, scaleY); return rc; } else { SDL_Rect scaledRect = { static_cast<int>(float(dstrect->x) * scaleX), static_cast<int>(float(dstrect->y) * scaleY), static_cast<int>(float(dstrect->w) * scaleX), static_cast<int>(float(dstrect->h) * scaleY), }; int xDelta = 0; int yDelta = 0; switch(alignment) { case Render::Alignment::topLeft: xDelta = screen.renderAreaX; yDelta = screen.renderAreaY; break; case Render::Alignment::bottomLeft: xDelta = screen.renderAreaX; yDelta = screen.renderAreaY + screen.renderAreaH; break; case Render::Alignment::topRight: xDelta = screen.renderAreaX + screen.renderAreaW; yDelta = screen.renderAreaY; break; case Render::Alignment::bottomRight: xDelta = screen.renderAreaX + screen.renderAreaW; yDelta = screen.renderAreaY + screen.renderAreaH; break; default: break; } SDL_Rect dst = { scaledRect.x + xDelta, scaledRect.y + yDelta, scaledRect.w, scaledRect.h }; SDL_RenderSetScale(screen.renderer, 1.0, 1.0); int rc = SDL_RenderCopy(screen.renderer, tex, srcrect, &dst); SDL_RenderSetScale(screen.renderer, scaleX, scaleY); return rc; } } int RenderFillRect(const Screen& screen, SDL_Rect *rect) { if(screen.window == nullptr || screen.renderer == nullptr) { return -1; } float scaleX; float scaleY; SDL_RenderGetScale(screen.renderer, &scaleX, &scaleY); if(SDL_GetRenderTarget(screen.renderer) != nullptr) { if(rect != nullptr) { SDL_Rect scaledRect = { static_cast<int>(float(rect->x) * scaleX), static_cast<int>(float(rect->y) * scaleY), static_cast<int>(float(rect->w) * scaleX), static_cast<int>(float(rect->h) * scaleY), }; return SDL_RenderFillRect(screen.renderer, &scaledRect); } else { return SDL_RenderFillRect(screen.renderer, rect); } } if(rect == nullptr) { SDL_Rect rect_ = { screen.renderAreaX, screen.renderAreaY, screen.renderAreaW, screen.renderAreaH }; SDL_RenderSetScale(screen.renderer, 1.0, 1.0); int rc = SDL_RenderFillRect(screen.renderer, &rect_); SDL_RenderSetScale(screen.renderer, scaleX, scaleY); return rc; } int scaledRenderAreaX = static_cast<int>(float(screen.innerRenderAreaX) / scaleX); int scaledRenderAreaY = static_cast<int>(float(screen.innerRenderAreaY) / scaleY); SDL_Rect dst = { rect->x, rect->y, rect->w, rect->h }; dst.x += scaledRenderAreaX; dst.y += scaledRenderAreaY; return SDL_RenderFillRect(screen.renderer, &dst); } int RenderFillRectOuter(const Screen& screen, SDL_Rect *rect, Render::Alignment alignment) { if(screen.window == nullptr || screen.renderer == nullptr) { return -1; } float scaleX; float scaleY; SDL_RenderGetScale(screen.renderer, &scaleX, &scaleY); if(SDL_GetRenderTarget(screen.renderer) != nullptr) { if(rect != nullptr) { SDL_Rect scaledRect = { static_cast<int>(float(rect->x) * scaleX), static_cast<int>(float(rect->y) * scaleY), static_cast<int>(float(rect->w) * scaleX), static_cast<int>(float(rect->h) * scaleY), }; return SDL_RenderFillRect(screen.renderer, &scaledRect); } else { return SDL_RenderFillRect(screen.renderer, rect); } } if(rect == nullptr) { SDL_Rect rect_ = { screen.renderAreaX, screen.renderAreaY, screen.renderAreaW, screen.renderAreaH }; SDL_RenderSetScale(screen.renderer, 1.0, 1.0); int rc = SDL_RenderFillRect(screen.renderer, &rect_); SDL_RenderSetScale(screen.renderer, scaleX, scaleY); return rc; } else { SDL_Rect scaledRect = { static_cast<int>(float(rect->x) * scaleX), static_cast<int>(float(rect->y) * scaleY), static_cast<int>(float(rect->w) * scaleX), static_cast<int>(float(rect->h) * scaleY), }; int xDelta = 0; int yDelta = 0; switch(alignment) { case Render::Alignment::topLeft: xDelta = screen.renderAreaX; yDelta = screen.renderAreaY; break; case Render::Alignment::bottomLeft: xDelta = screen.renderAreaX; yDelta = screen.renderAreaY + screen.renderAreaH; break; case Render::Alignment::topRight: xDelta = screen.renderAreaX + screen.renderAreaW; yDelta = screen.renderAreaY; break; case Render::Alignment::bottomRight: xDelta = screen.renderAreaX + screen.renderAreaW; yDelta = screen.renderAreaY + screen.renderAreaH; break; default: break; } SDL_Rect dst = { scaledRect.x + xDelta, scaledRect.y + yDelta, scaledRect.w, scaledRect.h }; SDL_RenderSetScale(screen.renderer, 1.0, 1.0); int rc = SDL_RenderFillRect(screen.renderer, &dst); SDL_RenderSetScale(screen.renderer, scaleX, scaleY); return rc; } } }
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once #include "effect_expression.hpp" #include "moving_average.hpp" #include <filesystem> namespace reshade { enum class special_uniform { none, frame_time, frame_count, random, ping_pong, date, timer, key, mouse_point, mouse_delta, mouse_button, }; enum class texture_reference { none, back_buffer, depth_buffer }; class base_object abstract { public: virtual ~base_object() {} template <typename T> T *as() { return dynamic_cast<T *>(this); } template <typename T> const T *as() const { return dynamic_cast<const T *>(this); } }; struct effect final { unsigned int rendering = 0; bool compile_sucess = false; std::string errors; std::string preamble; reshadefx::module module; std::filesystem::path source_file; std::vector<std::filesystem::path> included_files; std::vector<std::string> macro_ifdefs; size_t storage_offset = 0, storage_size = 0; }; struct texture final : reshadefx::texture_info { texture() {} texture(const reshadefx::texture_info &init) : texture_info(init) {} int annotation_as_int(const char *ann_name, size_t i = 0) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return 0; return it->second.first.is_integral() ? it->second.second.as_int[i] : static_cast<int>(it->second.second.as_float[i]); } float annotation_as_float(const char *ann_name, size_t i = 0) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return 0.0f; return it->second.first.is_floating_point() ? it->second.second.as_float[i] : static_cast<float>(it->second.second.as_int[i]); } std::string_view annotation_as_string(const char *ann_name) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return std::string_view(); return it->second.second.string_data; } bool matches_description(const reshadefx::texture_info &desc) const { return width == desc.width && height == desc.height && levels == desc.levels && format == desc.format; } size_t effect_index = std::numeric_limits<size_t>::max(); texture_reference impl_reference = texture_reference::none; std::unique_ptr<base_object> impl; bool shared = false; }; struct uniform final : reshadefx::uniform_info { uniform(const reshadefx::uniform_info &init) : uniform_info(init) {} int annotation_as_int(const char *ann_name, size_t i = 0) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return 0; return it->second.first.is_integral() ? it->second.second.as_int[i] : static_cast<int>(it->second.second.as_float[i]); } float annotation_as_float(const char *ann_name, size_t i = 0) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return 0.0f; return it->second.first.is_floating_point() ? it->second.second.as_float[i] : static_cast<float>(it->second.second.as_int[i]); } std::string_view annotation_as_string(const char *ann_name) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return std::string_view(); return it->second.second.string_data; } bool supports_toggle_key() const { if (type.base == reshadefx::type::t_bool) return true; if (type.base != reshadefx::type::t_int && type.base != reshadefx::type::t_uint) return false; const std::string_view ui_type = annotation_as_string("ui_type"); return ui_type == "list" || ui_type == "combo" || ui_type == "radio"; } size_t effect_index = std::numeric_limits<size_t>::max(); size_t storage_offset = 0; special_uniform special = special_uniform::none; uint32_t toggle_key_data[4] = {}; }; struct technique final : reshadefx::technique_info { technique(const reshadefx::technique_info &init) : technique_info(init) {} int annotation_as_int(const char *ann_name, size_t i = 0) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return 0; return it->second.first.is_integral() ? it->second.second.as_int[i] : static_cast<int>(it->second.second.as_float[i]); } float annotation_as_float(const char *ann_name, size_t i = 0) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return 0.0f; return it->second.first.is_floating_point() ? it->second.second.as_float[i] : static_cast<float>(it->second.second.as_int[i]); } std::string_view annotation_as_string(const char *ann_name) const { const auto it = annotations.find(ann_name); if (it == annotations.end()) return std::string_view(); return it->second.second.string_data; } size_t effect_index = std::numeric_limits<size_t>::max(); std::vector<std::unique_ptr<base_object>> passes_data; bool hidden = false; bool enabled = false; int32_t timeout = 0; int64_t timeleft = 0; uint32_t toggle_key_data[4] = {}; moving_average<uint64_t, 60> average_cpu_duration; moving_average<uint64_t, 60> average_gpu_duration; std::unique_ptr<base_object> impl; }; }
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <cmath> #include <cstdlib> #include <exception> #include <iostream> #include <set> #include "../../../../../../asio/asio/include/asio.hpp" #include "../../../../../../asio/asio/src/examples/cpp03/porthopper/protocol.hpp" using asio::ip::tcp; using asio::ip::udp; typedef boost::shared_ptr<tcp::socket> tcp_socket_ptr; typedef boost::shared_ptr<asio::steady_timer> timer_ptr; typedef boost::shared_ptr<control_request> control_request_ptr; class server { public: // Construct the server to wait for incoming control connections. server(asio::io_context& io_context, unsigned short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)), timer_(io_context), udp_socket_(io_context, udp::endpoint(udp::v4(), 0)), next_frame_number_(1) { // Start waiting for a new control connection. tcp_socket_ptr new_socket( new tcp::socket(acceptor_.get_executor().context())); acceptor_.async_accept(*new_socket, boost::bind(&server::handle_accept, this, asio::placeholders::error, new_socket)); // Start the timer used to generate outgoing frames. timer_.expires_after(asio::chrono::milliseconds(100)); timer_.async_wait(boost::bind(&server::handle_timer, this)); } // Handle a new control connection. void handle_accept(const asio::error_code& ec, tcp_socket_ptr socket) { if (!ec) { // Start receiving control requests on the connection. control_request_ptr request(new control_request); asio::async_read(*socket, request->to_buffers(), boost::bind(&server::handle_control_request, this, asio::placeholders::error, socket, request)); } // Start waiting for a new control connection. tcp_socket_ptr new_socket( new tcp::socket(acceptor_.get_executor().context())); acceptor_.async_accept(*new_socket, boost::bind(&server::handle_accept, this, asio::placeholders::error, new_socket)); } // Handle a new control request. void handle_control_request(const asio::error_code& ec, tcp_socket_ptr socket, control_request_ptr request) { if (!ec) { // Delay handling of the control request to simulate network latency. timer_ptr delay_timer( new asio::steady_timer(acceptor_.get_executor().context())); delay_timer->expires_after(asio::chrono::seconds(2)); delay_timer->async_wait( boost::bind(&server::handle_control_request_timer, this, socket, request, delay_timer)); } } void handle_control_request_timer(tcp_socket_ptr socket, control_request_ptr request, timer_ptr /*delay_timer*/) { // Determine what address this client is connected from, since // subscriptions must be stored on the server as a complete endpoint, not // just a port. We use the non-throwing overload of remote_endpoint() since // it may fail if the socket is no longer connected. asio::error_code ec; tcp::endpoint remote_endpoint = socket->remote_endpoint(ec); if (!ec) { // Remove old port subscription, if any. if (unsigned short old_port = request->old_port()) { udp::endpoint old_endpoint(remote_endpoint.address(), old_port); subscribers_.erase(old_endpoint); std::cout << "Removing subscription " << old_endpoint << std::endl; } // Add new port subscription, if any. if (unsigned short new_port = request->new_port()) { udp::endpoint new_endpoint(remote_endpoint.address(), new_port); subscribers_.insert(new_endpoint); std::cout << "Adding subscription " << new_endpoint << std::endl; } } // Wait for next control request on this connection. asio::async_read(*socket, request->to_buffers(), boost::bind(&server::handle_control_request, this, asio::placeholders::error, socket, request)); } // Every time the timer fires we will generate a new frame and send it to all // subscribers. void handle_timer() { // Generate payload. double x = next_frame_number_ * 0.2; double y = std::sin(x); int char_index = static_cast<int>((y + 1.0) * (frame::payload_size / 2)); std::string payload; for (int i = 0; i < frame::payload_size; ++i) payload += (i == char_index ? '*' : '.'); // Create the frame to be sent to all subscribers. frame f(next_frame_number_++, payload); // Send frame to all subscribers. We can use synchronous calls here since // UDP send operations typically do not block. std::set<udp::endpoint>::iterator j; for (j = subscribers_.begin(); j != subscribers_.end(); ++j) { asio::error_code ec; udp_socket_.send_to(f.to_buffers(), *j, 0, ec); } // Wait for next timeout. timer_.expires_after(asio::chrono::milliseconds(100)); timer_.async_wait(boost::bind(&server::handle_timer, this)); } private: // The acceptor used to accept incoming control connections. tcp::acceptor acceptor_; // The timer used for generating data. asio::steady_timer timer_; // The socket used to send data to subscribers. udp::socket udp_socket_; // The next frame number. unsigned long next_frame_number_; // The set of endpoints that are subscribed. std::set<udp::endpoint> subscribers_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: server <port>\n"; return 1; } asio::io_context io_context; using namespace std; // For atoi. server s(io_context, atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } return 0; }
/** * @file src/bin2llvmir/providers/abi/pic32.cpp * @brief ABI information for MIPS. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include "retdec/bin2llvmir/providers/abi/pic32.h" using namespace llvm; namespace retdec { namespace bin2llvmir { AbiPic32::AbiPic32(llvm::Module* m, Config* c) : Abi(m, c) { _regs.reserve(MIPS_REG_ENDING); _id2regs.resize(MIPS_REG_ENDING, nullptr); _regStackPointerId = MIPS_REG_SP; _regZeroReg = MIPS_REG_ZERO; // system calls _regSyscallId = MIPS_REG_V0; _regSyscallReturn = MIPS_REG_V0; _syscallRegs = { MIPS_REG_A0, MIPS_REG_A1, MIPS_REG_A2, MIPS_REG_A3}; _defcc = CallingConvention::ID::CC_PIC32; } AbiPic32::~AbiPic32() { } bool AbiPic32::isGeneralPurposeRegister(const llvm::Value* val) const { uint32_t rid = getRegisterId(val); return MIPS_REG_0 <= rid && rid <= MIPS_REG_31; } bool AbiPic32::isNopInstruction(cs_insn* insn) { // True NOP variants. // if (insn->id == MIPS_INS_NOP || insn->id == MIPS_INS_SSNOP) { return true; } return false; } std::size_t AbiPic32::getTypeByteSize(llvm::Type* t) const { if (t->isDoubleTy()) { t = Type::getFloatTy(_module->getContext()); } return Abi::getTypeByteSize(t); } std::size_t AbiPic32::getTypeBitSize(llvm::Type* t) const { if (t->isDoubleTy()) { t = Type::getFloatTy(_module->getContext()); } return Abi::getTypeByteSize(t); } } // namespace bin2llvmir } // namespace retdec
// Question: Write a C++ program to simulate the following contiguous memory allocation techniques //a) Worst-fit b) Best-fit c) First-fit //ID - NAME //219CS01000078 Blege Bright Edem //219CS01000037 Mensah Bernard //219EI01000036 Kodom Stephen #include <iostream> #include <stdio.h> #include<conio.h> #include <cstdlib> #include <string> using namespace std; // Menu choice declaration int choice; // All the functions in the program declaration void menu(); void start(); void worstFit(); void bestFit(); void firstFit(); void MFT(); void MVT(); void pagingTechnique(); void firstComeFirstServe(); void shortestJobNext(); void roundRobin(); void priority(); void banker_sAlgorithm(); // Main function int main() { // The program starts from here system("color 1f"); start(); // Returns no value to operating system return 0; } // Menu function for selecetion void menu(){ // Displays a message in the console cout <<"************************************OS MANAGEMENT SYSTEM***********************************"; cout <<"\n*******************************************************************************************"; cout <<"\n*********************************MENU**********************************************************"; cout << "\n\n1. \t\tFIRST-FIT" ; cout << "\n\n2. \t\tBEST-FIT"; cout << "\n\n3. \t\tWORST-FIT"; cout << "\n\n4. \t\tMFT" ; cout << "\n\n5. \t\tMVT"; cout << "\n\n6. \t\tPAGING SYSTEM"; cout << "\n\n7. \t\tFIRST-COME-FIRST-SERVE"; cout << "\n\n8. \t\tSHORTEST-JOB-FIRST/NEXT"; cout << "\n\n9. \t\tROUND ROBIN"; cout << "\n\n10. \t\tPRIORITY"; cout << "\n\n11. \t\tBANKER'S ALGORITHM"; cout << "\n\n12. \t\tEXIT"; // Selection cout << "\n\nChoice: "; cin >> choice; // The choice switch statement switch(choice){ // When user selects "1" from menu case 1: // Worst-Fit method is called firstFit(); break; // When user selects "2" from menu case 2: // Best-Fit method is called bestFit(); break; // When user selects "3" from menu case 3: // First-Fit method is called worstFit(); break; // When user selects "4" from menu case 4: MFT(); break; // When user selects "5" from menu case 5: MVT(); break; // When user selects "6" from menu case 6: pagingTechnique(); break; case 7: firstComeFirstServe(); break; case 8: shortestJobNext(); break; case 9: roundRobin(); break; case 10: priority(); break; case 11: banker_sAlgorithm(); break; case 12: // The program terminates suddenly cout << "\n\nClosing application....."; exit(0); break; // When user selects wrong number from menu default: cout << "\n\nPlease you entered wrong input.."; cout <<"\n\nEnter between (1-7).."; cout <<"\n\nPress any key.."; getch(); // The program goes back to the main menu menu(); } } void start(){ // The main menu is called when program starts menu(); } // Worst-Fit function processing void firstFit(){ // Maximum fragmentation size const int max = 25; // All the variables used in the method declaration int frag[max],blockSize[max],fileSize[max],i,j,numBlocks,numFiles,temp; static int bf[max],ff[max]; // Clears the console screen system("cls"); // Displays a message cout <<"***********************MEMORY MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n*******************************FIRST-FIT**********************************"; cout <<"\n**************************************************************************"; // Requesting and getting input cout << "\n\nPlease enter the number of memory blocks... "; cin >> numBlocks; cout << "\nEnter the number of files... "; cin >> numFiles; //Prompt for entering size of each block cout << "\nEnter the size of the blocks below:"; // Loops through each block to receive its size for(i=1;i<=numBlocks;i++){ cout <<"\nBlock "<<i<<": "; cin >> blockSize[i]; } cout << "\nEnter the size of the files below:"; // Loops through each file to receive its size for(i=1;i<=numFiles;i++){ cout <<"\nFile "<<i<<": "; cin >> fileSize[i]; } for(i=1;i<=numFiles;i++){ for(j=1;j<=numBlocks;j++){ if(bf[j]!=1){ temp=blockSize[j]-fileSize[i]; if(temp>=0){ ff[i]=j; break; } } } frag[i]=temp; bf[ff[i]]=1; } cout <<"\n*************************************************************************************"; cout << "\nFILE NO:\tFILE SIZE:\tBLOCK NO:\tBLOCK SIZE:\tFRAGMENTATION"; for(i=1;i<=numFiles;i++){ cout <<"\n"<<i<<"\t\t"<<fileSize[i]<<"\t\t"<<ff[i]<<"\t\t"<<blockSize[ff[i]]<<"\t\t"<<frag[i]; } cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); } // Best-Fit function processing void bestFit(){ // Maximum fragmentation size const int max = 25; // All the variables used in the method declaration int frag[max],blockSize[max],fileSize[max],i,j,numBlocks,numFiles,temp,lowest = 10000; static int bf[max],ff[max]; // Clears the console screen system("cls"); // Displays a message cout <<"***********************MEMORY MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n*******************************BEST-FIT**********************************"; cout <<"\n**************************************************************************"; // Requesting and getting input cout << "\n\nPlease enter the number of memory blocks... "; cin >> numBlocks; cout << "\nEnter the number of files... "; cin >> numFiles; //Prompt for entering size of each block cout << "\nEnter the size of the blocks below:"; // Loops through each block to receive its size for(i=1;i<=numBlocks;i++){ cout <<"\nBlock "<<i<<": "; cin >> blockSize[i]; } cout << "\nEnter the size of the files below:"; // Loops through each file to receive its size for(i=1;i<=numFiles;i++){ cout <<"\nFile "<<i<<": "; cin >> fileSize[i]; } // Loops through each file to receive its size for(i=1;i<=numFiles;i++){ for(j=1;j<=numBlocks;j++){ if(bf[j]!=1){ temp=blockSize[j]-fileSize[i]; if(temp >= 0){ if(lowest > temp){ ff[i] = j; lowest = temp; } } } } frag[i]=lowest; bf[ff[i]]=1; lowest=10000; } cout <<"\n\n*************************************************************************************"; cout << "\nFILE NO:\tFILE SIZE:\tBLOCK NO:\tBLOCK SIZE:\tFRAGMENTATION"; for(i=1;i<=numFiles;i++){ cout <<"\n"<<i<<"\t\t"<<fileSize[i]<<"\t\t"<<ff[i]<<"\t\t"<<blockSize[ff[i]]<<"\t\t"<<frag[i]; } cout <<"\n\n*************************************************************************************"; cout <<"\nPress any key to go back to main menu..."; getch(); system("cls"); menu(); } // First-Fit function processing void worstFit(){ // Maximum fragmentation size const int max = 25; // All the variables used in the method declaration int frag[max],blockSize[max],fileSize[max],i,j,numBlocks,numFiles,temp,highest = 0; static int bf[max],ff[max]; // Clears the console screen system("cls"); // Displays a message cout <<"***********************MEMORY MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n*******************************WORST-FIT**********************************"; cout <<"\n**************************************************************************"; // Requesting and getting input cout << "\n\nPlease enter the number of memory blocks... "; cin >> numBlocks; cout << "\nEnter the number of files... "; cin >> numFiles; //Prompt for entering size of each block cout << "\nEnter the size of the blocks below:"; // Loops through each block to receive its size for(i=1;i<=numBlocks;i++){ cout <<"\nBlock "<<i<<": "; cin >> blockSize[i]; } cout << "\nEnter the size of the files below:"; // Loops through each file to receive its size for(i=1;i<=numFiles;i++){ cout <<"\nFile "<<i<<": "; cin >> fileSize[i]; } // Loops through each file to receive its size for(i=1;i<=numFiles;i++){ for(j=1;j<=numBlocks;j++){ if(bf[j]!=1){ temp=blockSize[j]-fileSize[i]; if(temp >= 0){ if(highest < temp){ ff[i] = j; highest = temp; } } } } frag[i]=highest; bf[ff[i]]=1; highest=0; } cout <<"\n\n*************************************************************************************"; cout << "\nFILE NO:\tFILE SIZE:\tBLOCK NO:\tBLOCK SIZE:\tFRAGMENTATION"; for(i=1;i<=numFiles;i++){ cout <<"\n"<<i<<"\t\t"<<fileSize[i]<<"\t\t"<<ff[i]<<"\t\t"<<blockSize[ff[i]]<<"\t\t"<<frag[i]; } cout <<"\n\n*************************************************************************************"; cout <<"\nPress any key to go back to main menu..."; getch(); system("cls"); menu(); } void MFT(){ // Variables (i.e Memory size, Number of blocks , External Fragmentation, Number of processes, Memory Processes, Internal fragmentation int memSize,blockSize,numBlocks,exFragmentation,numProcess,memProcess[10],totalInFragmentation=0; // Counter & p int i,p=0; //Screen clear system("CLS"); // Displays a message cout <<"***********************MEMORY MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n*******************************MFT**********************************"; cout <<"\n**************************************************************************"; // Memory size input prompt cout << "\nPlease enter the total memory available(in Bytes).... "; cin >> memSize; // Block size input prompt cout << "Enter the block size( in Bytes)... "; cin >> blockSize; //Number of Blocks numBlocks = memSize/blockSize; // External Fragmentation exFragmentation = memSize - numBlocks * blockSize; // Process Input Prompt cout << "Enter the number of processes....... "; cin >> numProcess; // Looping through the number of processes for(i = 0; i < numProcess ; i++){ // Memory required input prompt cout << "Enter memory required for process "<<i+1<<" (in Bytes).... "; cin >> memProcess[i]; } cout << "\n NUMBER OF BLOCKS AVAILABLE IN MEMORY...... " <<numBlocks; cout << "\n\nPROCESS\tMEMORY REQUIRED\t ALLOCATED\tINTERNAL FRAGMENTATION"; for (i=0; i < numProcess && p < numBlocks ; i++){ cout << "\n "<<i+1<<"\t\t"<<memProcess[i]; if( memProcess[i] > blockSize ){ cout << "\t NO\t\t\t---"; }else{ cout <<"\t YES\t\t\t"<<blockSize-memProcess[i]; totalInFragmentation = totalInFragmentation + blockSize-memProcess[i]; p++; } } // Displays a message if(i < numProcess){ cout << "\n\n\n MEMORY IS FULL!!!, REMAINING PROCESS CANNOT BE ACCOMODATED"; } // Display total internal fragmentation and External fragmentation cout <<" \n\n TOTAL INTERNAL FRAGMENTATION IS "<<totalInFragmentation; cout <<" \n TOTAL EXTERNAL FRAGMENTATION IS "<<exFragmentation; cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); } void MVT(){ // Variables (i.e Memory size, Memory Processes, Total external fragmentation int memSize,memProcess[10],i,temp,n=0; // Prompt input reply char ch = 'y'; //Screen clear system("CLS"); // Displays a message cout <<"***********************MEMORY MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n*******************************MVT**********************************"; cout <<"\n**************************************************************************"; // Prompt memory size input cout << "\nPlease enter the total memory available(in Bytes)-- "; cin >> memSize; temp = memSize; // Looping through processes for(i=0;ch=='y';i++,n++){ // Prompt for memory required input cout << "\n Enter memory required for process "<<i+1<<" (in Bytes)"; cin >> memProcess[i]; // Decision to alert the user for input if(memProcess[i]<=temp){ // cout << "\nMemory is allocated for Process "<<i+1<<""; temp = temp - memProcess[i]; }else{ cout << "\n Memory is Full!!"; break; } cout <<"\nDo you want to continue(y/n)? -- "; cin >> ch; } cout << "\n\nTotal Memory Available -- "<<memSize; cout << "\n\n\tPROCESS\t\t MEMORY ALLOCATED"; for(i=0;i<n;i++){ cout <<"\n \t"<<i+1<<"\t\t"<<memProcess[i]; } cout << "\n\nTotal Memory Allocated is "<<memSize-temp; cout << "\nTotal External Fragmentation is "<<temp; cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); } void pagingTechnique(){ int memSize,pageSize,numPages,numProcess,remPages,i,j,x,y,pa,offset; int s[10],fno[10][20]; //Clearing the screen for processing system("CLS"); // Displays a message cout <<"***********************MEMORY MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n*******************************PAGING TECHNIQUE**********************************"; cout <<"\n**************************************************************************"; cout <<"\nPlease enter the memory size-- "; cin >> memSize; cout << "\nEnter the page size-- "; cin >> pageSize; numPages = memSize/pageSize; cout << "\nThe number of pages available in memory are -- "<<numPages; cout << "\nEnter number of processes-- "; cin >> numProcess; remPages = numPages; for(i=1;i<=numProcess;i++){ cout << "\nEnter number of pages required for p["<<i<<"] -- "; cin >> s[i]; if(s[i]>remPages){ cout << "\nMEMORY FULL!!"; break; } remPages = remPages - s[i]; cout << "\nEnter page table for p["<<i<<"] -- "; for(j=0;j<s[i];j++){ cin >> fno[i][j]; } } cout <<"\nEnter Logical Address to find Physical Address"; cout << "\nEnter process number , Page number and Offset(Eg. 3 6 54) -- "; cin >> x >> y >> offset; if(x>numProcess || y>s[i] || offset>=pageSize){ cout << "\nINVALID PROCESS OR PAGE NUMBER OR OFFSET"; }else{ pa = fno[x][y]*pageSize+offset; cout <<"\nThe Physical Address is -- "<<pa; } cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); } void firstComeFirstServe(){ int burstTime[20],waitingTime[20],turnAroundTime[20],i,n; float avgWaitingTime,avgTurnAroudTime; system("CLS"); // Displays a message cout <<"***********************PROCESS MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n******************FIRST-COME-FIRST-SERVE******************"; cout <<"\n**************************************************************************"; printf("\n\nEnter the number of processes -- "); scanf("%d", &n); printf("%d",n); for(i=0;i<n;i++){ printf("\nEnter Burst Time for Process %d -- ", i+1); scanf("%d", &burstTime[i]); } waitingTime[0] = avgWaitingTime = 0; turnAroundTime[0] = avgTurnAroudTime = burstTime[0]; for(i=1;i<n;i++){ waitingTime[i] = waitingTime[i-1] +burstTime[i-1]; turnAroundTime[i] = turnAroundTime[i-1] +burstTime[i]; avgWaitingTime = avgWaitingTime + waitingTime[i]; avgTurnAroudTime = avgTurnAroudTime + turnAroundTime[i]; } cout <<"\n*************************************************************************************"; printf("\n\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n"); for(i=0;i<n;i++){ printf("\n\t Process%d \t\t %d \t\t %d \t\t %d", i+1, burstTime[i], waitingTime[i], turnAroundTime[i]); } printf("\nAverage Waiting Time -- %f", avgWaitingTime/n); printf("\nAverage Turnaround Time -- %f", avgTurnAroudTime/n); cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); } //Shortest Job Next void shortestJobNext(){ int p[20], bt[20], wt[20], tat[20], i, k, n, temp; float wtavg, tatavg; system("cls"); cout <<"***********************PROCESS MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n******************SHORTEST-JOB-FIRST/NEXT******************"; cout <<"\n**************************************************************************"; printf("\n\nEnter the number of processes -- "); scanf("%d", &n); for(i=0;i<n;i++){ p[i]=i; printf("Enter Burst Time for Process %d -- ", i+1); scanf("%d", &bt[i]); } for(i=0;i<n;i++) for(k=i+1;k<n;k++) if(bt[i]>bt[k]) { temp=bt[i]; bt[i]=bt[k]; bt[k]=temp; temp=p[i]; p[i]=p[k]; p[k]=temp; } wt[0] = wtavg = 0; tat[0] = tatavg = bt[0]; for(i=1;i<n;i++) { wt[i] = wt[i-1] +bt[i-1]; tat[i] = tat[i-1] +bt[i]; wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i]; } cout <<"\n*************************************************************************************"; printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n"); for(i=0;i<n;i++){ printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i]+1, bt[i], wt[i], tat[i]); } printf("\nAverage Waiting Time -- %f", wtavg/n); printf("\nAverage Turnaround Time -- %f", tatavg/n); cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); } void roundRobin(){ int i,j,n,bu[10],wa[10],tat[10],t,ct[10],maxi; float awt=0,att=0,temp=0; system("CLS"); cout <<"***********************PROCESS MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n********************************ROUND ROBIN********************************"; cout <<"\n**************************************************************************"; printf("\n\nEnter the no of processes -- "); scanf("%d",&n); for(i=0;i<n;i++) { printf("\nEnter Burst Time for process %d -- ", i+1); scanf("%d",&bu[i]); ct[i]=bu[i]; } printf("\nEnter the size of time slice -- "); scanf("%d",&t); maxi=bu[0]; for(i=1;i<n;i++) if(maxi<bu[i]) maxi=bu[i]; for(j=0;j<(maxi/t)+1;j++) for(i=0;i<n;i++) if(bu[i]!=0) if(bu[i]<=t) { tat[i]=temp+bu[i]; temp=temp+bu[i]; bu[i]=0; } else { bu[i]=bu[i]-t; temp=temp+t; } for(i=0;i<n;i++) { wa[i]=tat[i]-ct[i]; att+=tat[i]; awt+=wa[i]; } printf("\nThe Average Turnaround time is -- %f",att/n); printf("\nThe Average Waiting time is -- %f ",awt/n); printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n"); for(i=0;i<n;i++) printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]); cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); } void priority(){ int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp; float wtavg, tatavg; system("CLS"); cout <<"***********************PROCESS MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n*****************************PRIORITY SCHEME******************************"; cout <<"\n**************************************************************************"; printf("\n\nEnter the number of processes --- "); scanf("%d",&n); for(i=0;i<n;i++) { p[i] = i; printf("Enter the Burst Time & Priority of Process %d --- ",i+1); scanf("%d %d",&bt[i], &pri[i]); } for(i=0;i<n;i++) for(k=i+1;k<n;k++) if(pri[i] > pri[k]) { temp=p[i]; p[i]=p[k]; p[k]=temp; temp=bt[i]; bt[i]=bt[k]; bt[k]=temp; temp=pri[i]; pri[i]=pri[k]; pri[k]=temp; } wtavg = wt[0] = 0; tatavg = tat[0] = bt[0]; for(i=1;i<n;i++) { wt[i] = wt[i-1] + bt[i-1]; tat[i] = tat[i-1] + bt[i]; wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i]; } printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUND TIME"); for(i=0;i<n;i++) printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i]+1,pri[i],bt[i],wt[i],tat[i]); printf("\nAverage Waiting Time is --- %f",wtavg/n); printf("\nAverage Turnaround Time is --- %f",tatavg/n); cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); } // Banker's Algorithm void banker_sAlgorithm(){ struct file { int all[10]; int maxi[10]; int need[10]; int flag; }; // Variables declaration struct file f[10]; int fl; int i, j, k, p, b, n, r, g, cnt=0, id, newr; int avail[10],seq[10]; //Clearing the screen for processing system("CLS"); // Displays a message cout <<"***********************PROCESS MANAGEMENT SCHEME***************************"; cout <<"\n**************************************************************************"; cout <<"\n******************BANKER'S ALGORITHM(DEADLOCK AVOIDANCE)******************"; cout <<"\n**************************************************************************"; // Operation request printf("\n\nEnter number of processes -- "); scanf("%d",&n); printf("Enter number of resources -- "); scanf("%d",&r); // Looping through requests for(i=0;i<n;i++) { cout << "Process "<<i+1<<" Details:"; printf("\nEnter allocation\t -- \t"); for(j=0;j<r;j++){ scanf("%d",&f[i].all[j]); } printf("Enter Max\t\t -- \t"); for(j=0;j<r;j++){ scanf("%d",&f[i].maxi[j]); } f[i].flag=0; } printf("\nEnter Available Resources\t -- \t"); for(i=0;i<r;i++){ scanf("%d",&avail[i]); } cout <<"New Request Details:"; printf("\nEnter pid \t -- \t"); scanf("%d",&id); printf("Enter Request for Resources \t -- \t"); for(i=0;i<r;i++){ scanf("%d",&newr); f[id].all[i] += newr; avail[i]=avail[i] - newr; } for(i=0;i<n;i++){ for(j=0;j<r;j++){ f[i].need[j]=f[i].maxi[j]-f[i].all[j]; if(f[i].need[j]<0){ f[i].need[j]=0; } } } cnt=0; fl=0; while(cnt!=n){ g=0; for(j=0;j<n;j++){ if(f[j].flag==0){ b=0; for(p=0;p<r;p++){ if(avail[p]>=f[j].need[p]) b=b+1; else b=b-1; } if(b==r){ printf("\nProcess%d is visited",j); seq[fl++]=j; f[j].flag=1; for(k=0;k<r;k++) avail[k]=avail[k]+f[j].all[k]; cnt=cnt+1; printf("("); for(k=0;k<r;k++) printf("%3d",avail[k]); printf(")"); g = 1; } } } if(g == 0){ printf("\n REQUEST NOT GRANTED -- DEADLOCK OCCURRED"); printf("\n SYSTEM IS IN UNSAFE STATE"); goto y; } } printf("\nSYSTEM IS IN SAFE STATE"); printf("\nThe Safe Sequence is -- ("); for(i=0;i<fl;i++){ printf("Process%d ",seq[i]); } printf(")"); y:printf("\nProcess\t\t Allocation\t\t Max\t\t\t Need\n"); // Looping through to display results after operation for(i=0;i<n;i++){ printf("Process%d\t",i); for(j=0;j<r;j++) printf("%6d",f[i].all[j]); cout <<"\t"; for(j=0;j<r;j++) printf("%6d",f[i].maxi[j]); cout <<"\t"; for(j=0;j<r;j++) printf("%6d",f[i].need[j]); printf("\n"); } cout <<"\n*************************************************************************************"; cout << "\n\nPress any key to go back to menu...... "; getch(); system("cls"); menu(); }
#include <iostream> using namespace std; int main(){ int n, v1, v2; bool sorted; while(cin >> n && n){ sorted = true; cin >> v1; n--; while(n--){ cin >> v2; if(sorted){ if(v1 < v2) v1 = v2; else sorted = false; } } if(sorted) cout << "SI\n"; else cout << "NO\n"; } return 0; }
#include "catch.hpp" #include "index_set.hpp" #include "util/index_helpers.hpp" TEST_CASE("[index_set] contains()") { SECTION("returns false if the index is before the first entry in the set") { realm::IndexSet set = {1, 2, 5}; REQUIRE_FALSE(set.contains(0)); } SECTION("returns false if the index is after the last entry in the set") { realm::IndexSet set = {1, 2, 5}; REQUIRE_FALSE(set.contains(6)); } SECTION("returns false if the index is between ranges in the set") { realm::IndexSet set = {1, 2, 5}; REQUIRE_FALSE(set.contains(4)); } SECTION("returns true if the index is in the set") { realm::IndexSet set = {1, 2, 5}; REQUIRE(set.contains(1)); REQUIRE(set.contains(2)); REQUIRE(set.contains(5)); } } TEST_CASE("[index_set] count()") { SECTION("returns the number of indices in the set in the given range") { realm::IndexSet set = {1, 2, 3, 5}; REQUIRE(set.count(0, 6) == 4); REQUIRE(set.count(0, 5) == 3); REQUIRE(set.count(0, 4) == 3); REQUIRE(set.count(0, 3) == 2); REQUIRE(set.count(0, 2) == 1); REQUIRE(set.count(0, 1) == 0); REQUIRE(set.count(0, 0) == 0); REQUIRE(set.count(0, 6) == 4); REQUIRE(set.count(1, 6) == 4); REQUIRE(set.count(2, 6) == 3); REQUIRE(set.count(3, 6) == 2); REQUIRE(set.count(4, 6) == 1); REQUIRE(set.count(5, 6) == 1); REQUIRE(set.count(6, 6) == 0); } SECTION("includes full ranges in the middle") { realm::IndexSet set = {1, 3, 4, 5, 10}; REQUIRE(set.count(0, 11) == 5); } SECTION("truncates ranges at the beginning and end") { realm::IndexSet set = {1, 2, 3, 5, 6, 7, 8, 9}; REQUIRE(set.count(3, 9) == 5); } SECTION("handles full chunks well") { size_t count = realm::_impl::ChunkedRangeVector::max_size * 4; realm::IndexSet set; for (size_t i = 0; i < count; ++i) { set.add(i * 3); set.add(i * 3 + 1); } for (size_t i = 0; i < count * 3; ++i) { REQUIRE(set.count(i) == 2 * count - (i + 1) * 2 / 3); REQUIRE(set.count(0, i) == (i + 1) / 3 + (i + 2) / 3); } } } TEST_CASE("[index_set] add()") { realm::IndexSet set; SECTION("extends existing ranges when next to an edge") { set.add(1); REQUIRE_INDICES(set, 1); set.add(2); REQUIRE_INDICES(set, 1, 2); set.add(0); REQUIRE_INDICES(set, 0, 1, 2); } SECTION("does not extend ranges over gaps") { set.add(0); REQUIRE_INDICES(set, 0); set.add(2); REQUIRE_INDICES(set, 0, 2); } SECTION("does nothing when the index is already in the set") { set.add(0); set.add(0); REQUIRE_INDICES(set, 0); } SECTION("merges existing ranges when adding the index between them") { set = {0, 2, 4}; set.add(1); REQUIRE_INDICES(set, 0, 1, 2, 4); } SECTION("combines multiple index sets without any shifting") { set = {0, 2, 6}; set.add({1, 4, 5}); REQUIRE_INDICES(set, 0, 1, 2, 4, 5, 6); } SECTION("handles front additions of ranges") { for (size_t i = 20; i > 0; i -= 2) set.add(i); REQUIRE_INDICES(set, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20); } SECTION("merges ranges even when they are in different chunks") { realm::IndexSet set2; for (int i = 0; i < 20; ++i) { set.add(i * 2); set2.add(i); set2.add(i * 2); } set.add(set2); REQUIRE(set.count() == 30); } } TEST_CASE("[index_set] add_shifted()") { realm::IndexSet set; SECTION("on an empty set is just add()") { set.add_shifted(5); REQUIRE_INDICES(set, 5); } SECTION("before the first range is just add()") { set = {10}; set.add_shifted(5); REQUIRE_INDICES(set, 5, 10); } SECTION("on first index of a range extends the range") { set = {5}; set.add_shifted(5); REQUIRE_INDICES(set, 5, 6); set.add_shifted(5); REQUIRE_INDICES(set, 5, 6, 7); } SECTION("in the middle of a range is shifted by that range") { set = {5, 6, 7}; set.add_shifted(6); REQUIRE_INDICES(set, 5, 6, 7, 9); } SECTION("after the last range adds the total count to the index to be added") { set = {5}; set.add_shifted(6); REQUIRE_INDICES(set, 5, 7); set.add_shifted(10); REQUIRE_INDICES(set, 5, 7, 12); } SECTION("in between ranges can be bumped into the next range") { set = {5, 7}; set.add_shifted(6); REQUIRE_INDICES(set, 5, 7, 8); } } TEST_CASE("[index_set] add_shifted_by()") { realm::IndexSet set; SECTION("does nothing given an empty set to add") { set = {5, 6, 7}; set.add_shifted_by({5, 6}, {}); REQUIRE_INDICES(set, 5, 6, 7); } SECTION("does nothing if values is a subset of shifted_by") { set = {5, 6, 7}; set.add_shifted_by({3, 4}, {3, 4}); REQUIRE_INDICES(set, 5, 6, 7); } SECTION("just adds the indices when they are all before the old indices and the shifted-by set is empty") { set = {5, 6}; set.add_shifted_by({}, {3, 4}); REQUIRE_INDICES(set, 3, 4, 5, 6); } SECTION("adds the indices shifted by the old count when they are all after the old indices and the shifted-by set is empty") { set = {5, 6}; set.add_shifted_by({}, {7, 9, 11, 13}); REQUIRE_INDICES(set, 5, 6, 9, 11, 13, 15); } SECTION("acts like bulk add_shifted() when shifted_by is empty") { set = {5, 10, 15, 20, 25}; set.add_shifted_by({}, {4, 5, 11}); REQUIRE_INDICES(set, 4, 5, 6, 10, 13, 15, 20, 25); } SECTION("shifts indices in values back by the number of indices in shifted_by before them") { set = {5}; set.add_shifted_by({0, 2, 3}, {6}); REQUIRE_INDICES(set, 3, 5); set = {5}; set.add_shifted_by({1, 3}, {4}); REQUIRE_INDICES(set, 2, 5); } SECTION("discards indices in both shifted_by and values") { set = {5}; set.add_shifted_by({2}, {2, 4}); REQUIRE_INDICES(set, 3, 5); } } TEST_CASE("[index_set] set()") { realm::IndexSet set; SECTION("clears the existing indices and replaces with the range [0, value)") { set = {8, 9}; set.set(5); REQUIRE_INDICES(set, 0, 1, 2, 3, 4); } } TEST_CASE("[index_set] insert_at()") { realm::IndexSet set; SECTION("on an empty set is add()") { set.insert_at(5); REQUIRE_INDICES(set, 5); set = {}; set.insert_at({1, 3, 5}); REQUIRE_INDICES(set, 1, 3, 5); } SECTION("with an empty set is a no-op") { set = {5, 6}; set.insert_at(realm::IndexSet{}); REQUIRE_INDICES(set, 5, 6); } SECTION("extends ranges containing the target range") { set = {5, 6}; set.insert_at(5); REQUIRE_INDICES(set, 5, 6, 7); set.insert_at(6, 2); REQUIRE_INDICES(set, 5, 6, 7, 8, 9); set.insert_at({5, 7, 11}); REQUIRE_INDICES(set, 5, 6, 7, 8, 9, 10, 11, 12); } SECTION("shifts ranges after the insertion point") { set = {5, 6}; set.insert_at(3); REQUIRE_INDICES(set, 3, 6, 7); set.insert_at(0, 2); REQUIRE_INDICES(set, 0, 1, 5, 8, 9); } SECTION("does not shift ranges before the insertion point") { set = {5, 6}; set.insert_at(10); REQUIRE_INDICES(set, 5, 6, 10); set.insert_at({15, 16}); REQUIRE_INDICES(set, 5, 6, 10, 15, 16); } SECTION("can not join ranges") { set = {5, 7}; set.insert_at(6); REQUIRE_INDICES(set, 5, 6, 8); } SECTION("adds later ranges after shifting for previous insertions") { set = {5, 10}; set.insert_at({5, 10}); REQUIRE_INDICES(set, 5, 6, 10, 12); } } TEST_CASE("[index_set] shift_for_insert_at()") { realm::IndexSet set; SECTION("does nothing given an empty set of insertion points") { set = {5, 8}; set.shift_for_insert_at(realm::IndexSet{}); REQUIRE_INDICES(set, 5, 8); } SECTION("does nothing when called on an empty set") { set = {}; set.shift_for_insert_at({5, 8}); REQUIRE(set.empty()); } SECTION("does nothing when the insertion points are all after the current indices") { set = {10, 20}; set.shift_for_insert_at({30, 40}); REQUIRE_INDICES(set, 10, 20); } SECTION("does shift when the insertion points are all before the current indices") { set = {10, 20}; set.shift_for_insert_at({2, 4}); REQUIRE_INDICES(set, 12, 22); } SECTION("shifts indices at or after the insertion points") { set = {5}; set.shift_for_insert_at(4); REQUIRE_INDICES(set, 6); set.shift_for_insert_at(6); REQUIRE_INDICES(set, 7); set.shift_for_insert_at({3, 8}); REQUIRE_INDICES(set, 9); } SECTION("shifts indices by the count specified") { set = {5}; set.shift_for_insert_at(3, 10); REQUIRE_INDICES(set, 15); } SECTION("does not shift indices before the insertion points") { set = {5}; set.shift_for_insert_at(6); REQUIRE_INDICES(set, 5); set.shift_for_insert_at({3, 8}); REQUIRE_INDICES(set, 6); } SECTION("splits ranges containing the insertion points") { set = {5, 6, 7, 8}; set.shift_for_insert_at(6); REQUIRE_INDICES(set, 5, 7, 8, 9); set.shift_for_insert_at({8, 10, 12}); REQUIRE_INDICES(set, 5, 7, 9, 11); } } TEST_CASE("[index_set] erase_at()") { realm::IndexSet set; SECTION("is a no-op on an empty set") { set.erase_at(10); REQUIRE(set.empty()); set.erase_at({1, 5, 8}); REQUIRE(set.empty()); } SECTION("does nothing when given an empty set") { set = {5}; set.erase_at(realm::IndexSet{}); REQUIRE_INDICES(set, 5); } SECTION("removes the specified indices") { set = {5}; set.erase_at(5); REQUIRE(set.empty()); set = {4, 7}; set.erase_at({4, 7}); REQUIRE(set.empty()); } SECTION("does not modify indices before the removed one") { set = {5, 8}; set.erase_at(8); REQUIRE_INDICES(set, 5); set = {5, 8, 9}; set.erase_at({8, 9}); REQUIRE_INDICES(set, 5); } SECTION("shifts indices after the removed one") { set = {5, 8}; set.erase_at(5); REQUIRE_INDICES(set, 7); set = {5, 10, 15, 20}; set.erase_at({5, 10}); REQUIRE_INDICES(set, 13, 18); } SECTION("shrinks ranges when used on one of the edges of them") { set = {5, 6, 7, 8}; set.erase_at(8); REQUIRE_INDICES(set, 5, 6, 7); set.erase_at(5); REQUIRE_INDICES(set, 5, 6); set = {5, 6, 7, 8}; set.erase_at({5, 8}); REQUIRE_INDICES(set, 5, 6); } SECTION("shrinks ranges when used in the middle of them") { set = {5, 6, 7, 8}; set.erase_at(7); REQUIRE_INDICES(set, 5, 6, 7); set = {5, 6, 7, 8}; set.erase_at({6, 7}); REQUIRE_INDICES(set, 5, 6); } SECTION("merges ranges when the gap between them is deleted") { set = {3, 5}; set.erase_at(4); REQUIRE_INDICES(set, 3, 4); set = {3, 5, 7}; set.erase_at({4, 6}); REQUIRE_INDICES(set, 3, 4, 5); } } TEST_CASE("[index_set] erase_or_unshift()") { realm::IndexSet set; SECTION("removes the given index") { set = {1, 2}; set.erase_or_unshift(2); REQUIRE_INDICES(set, 1); } SECTION("shifts indexes after the given index") { set = {1, 5}; set.erase_or_unshift(2); REQUIRE_INDICES(set, 1, 4); } SECTION("returns npos for indices in the set") { set = {1, 3, 5}; REQUIRE(realm::IndexSet(set).erase_or_unshift(1) == realm::IndexSet::npos); REQUIRE(realm::IndexSet(set).erase_or_unshift(3) == realm::IndexSet::npos); REQUIRE(realm::IndexSet(set).erase_or_unshift(5) == realm::IndexSet::npos); } SECTION("returns the number of indices in the set before the index for ones not in the set") { set = {1, 3, 5, 6}; REQUIRE(realm::IndexSet(set).erase_or_unshift(0) == 0); REQUIRE(realm::IndexSet(set).erase_or_unshift(2) == 1); REQUIRE(realm::IndexSet(set).erase_or_unshift(4) == 2); REQUIRE(realm::IndexSet(set).erase_or_unshift(7) == 3); } } TEST_CASE("[index_set] remove()") { realm::IndexSet set; SECTION("is a no-op if the set is empty") { set.remove(4); REQUIRE(set.empty()); set.remove({1, 2, 3}); REQUIRE(set.empty()); } SECTION("is a no-op if the set to remove is empty") { set = {5}; set.remove(realm::IndexSet{}); REQUIRE_INDICES(set, 5); } SECTION("is a no-op if the index to remove is not in the set") { set = {5}; set.remove(4); set.remove(6); set.remove({4, 6}); REQUIRE_INDICES(set, 5); } SECTION("removes one-element ranges") { set = {5}; set.remove(5); REQUIRE(set.empty()); set = {5}; set.remove({3, 4, 5}); REQUIRE(set.empty()); } SECTION("shrinks ranges beginning with the index") { set = {5, 6, 7}; set.remove(5); REQUIRE_INDICES(set, 6, 7); set = {5, 6, 7}; set.remove({3, 5}); REQUIRE_INDICES(set, 6, 7); } SECTION("shrinks ranges ending with the index") { set = {5, 6, 7}; set.remove(7); REQUIRE_INDICES(set, 5, 6); set = {5, 6, 7}; set.remove({3, 7}); REQUIRE_INDICES(set, 5, 6); } SECTION("splits ranges containing the index") { set = {5, 6, 7}; set.remove(6); REQUIRE_INDICES(set, 5, 7); set = {5, 6, 7}; set.remove({3, 6}); REQUIRE_INDICES(set, 5, 7); } SECTION("does not shift other indices and uses unshifted positions") { set = {5, 6, 7, 10, 11, 12, 13, 15}; set.remove({6, 11, 13}); REQUIRE_INDICES(set, 5, 7, 10, 12, 15); } } TEST_CASE("[index_set] shift()") { realm::IndexSet set; SECTION("is ind + count(0, ind), but adds the count-so-far to the stop index") { set = {1, 3, 5, 6}; REQUIRE(set.shift(0) == 0); REQUIRE(set.shift(1) == 2); REQUIRE(set.shift(2) == 4); REQUIRE(set.shift(3) == 7); REQUIRE(set.shift(4) == 8); } } TEST_CASE("[index_set] unshift()") { realm::IndexSet set; SECTION("is index - count(0, index)") { set = {1, 3, 5, 6}; REQUIRE(set.unshift(0) == 0); REQUIRE(set.unshift(2) == 1); REQUIRE(set.unshift(4) == 2); REQUIRE(set.unshift(7) == 3); REQUIRE(set.unshift(8) == 4); } } TEST_CASE("[index_set] clear()") { realm::IndexSet set; SECTION("removes all indices from the set") { set = {1, 2, 3}; set.clear(); REQUIRE(set.empty()); } }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /* * Copyright 2018 Google, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sstream> #include "base/cprintf.hh" #include "systemc/core/object.hh" #include "systemc/ext/utils/messages.hh" #include "systemc/ext/utils/sc_report_handler.hh" #include "systemc/ext/utils/sc_vector.hh" namespace sc_core { sc_vector_base::size_type sc_vector_base::size() const { return objs.size(); } const std::vector<sc_object *> & sc_vector_base::get_elements() const { elements.clear(); for (auto ptr: objs) { sc_object *obj_ptr = objectCast(ptr); if (obj_ptr) elements.push_back(obj_ptr); } return elements; } void sc_vector_base::checkIndex(size_type index) const { if (index >= size()) { std::ostringstream ss; gem5::ccprintf(ss, "%s[%d] >= size() = %d", name(), index, size()); SC_REPORT_ERROR(sc_core::SC_ID_OUT_OF_BOUNDS_, ss.str().c_str()); sc_abort(); } } void sc_vector_base::forceParent() const { sc_gem5::pushParentObj(get_parent_object()); } void sc_vector_base::unforceParent() const { sc_gem5::popParentObj(); } void sc_vector_base::reportEmpty(const char *kind_, bool empty_dest) const { std::ostringstream ss; ss << "target `" << name() << "' " << "(" << kind_ << ") "; if (!size()) ss << "not initialised yet"; else if (empty_dest) ss << "empty range given"; else ss << "empty destination range given"; SC_REPORT_WARNING(SC_ID_VECTOR_BIND_EMPTY_, ss.str().c_str()); } } // namespace sc_core
//===--- LICM.cpp - Loop invariant code motion ------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-licm" #include "swift/SIL/Dominance.h" #include "swift/SILOptimizer/Analysis/AliasAnalysis.h" #include "swift/SILOptimizer/Analysis/Analysis.h" #include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" #include "swift/SILOptimizer/Analysis/LoopAnalysis.h" #include "swift/SILOptimizer/Analysis/ArraySemantic.h" #include "swift/SILOptimizer/Analysis/SideEffectAnalysis.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Utils/CFG.h" #include "swift/SILOptimizer/Utils/SILSSAUpdater.h" #include "swift/SILOptimizer/Utils/Local.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILInstruction.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Support/Debug.h" #include "llvm/Support/CommandLine.h" using namespace swift; /// Instructions which read from memory, e.g. loads, or function calls without /// side effects. using ReadSet = llvm::SmallPtrSet<SILInstruction *, 8>; /// Instructions which (potentially) write memory. using WriteSet = SmallVector<SILInstruction *, 8>; /// Returns true if the \p MayWrites set contains any memory writes which may /// alias with the memory addressed by \a LI. static bool mayWriteTo(AliasAnalysis *AA, WriteSet &MayWrites, LoadInst *LI) { for (auto *W : MayWrites) if (AA->mayWriteToMemory(W, LI->getOperand())) { DEBUG(llvm::dbgs() << " mayWriteTo\n" << *W << " to " << *LI << "\n"); return true; } return false; } /// Returns true if the \p MayWrites set contains any memory writes which may /// alias with any memory which is read by \p AI. static bool mayWriteTo(AliasAnalysis *AA, SideEffectAnalysis *SEA, WriteSet &MayWrites, ApplyInst *AI) { SideEffectAnalysis::FunctionEffects E; SEA->getEffects(E, AI); assert(E.getMemBehavior(RetainObserveKind::IgnoreRetains) <= SILInstruction::MemoryBehavior::MayRead && "apply should only read from memory"); if (E.getGlobalEffects().mayRead() && !MayWrites.empty()) { // We don't know which memory is read in the callee. Therefore we bail if // there are any writes in the loop. return true; } for (unsigned Idx = 0, End = AI->getNumArguments(); Idx < End; ++Idx) { auto &ArgEffect = E.getParameterEffects()[Idx]; if (!ArgEffect.mayRead()) continue; SILValue Arg = AI->getArgument(Idx); // Check if the memory addressed by the argument may alias any writes. for (auto *W : MayWrites) { if (AA->mayWriteToMemory(W, Arg)) { DEBUG(llvm::dbgs() << " mayWriteTo\n" << *W << " to " << *AI << "\n"); return true; } } } return false; } static void removeWrittenTo(AliasAnalysis *AA, ReadSet &Reads, SILInstruction *ByInst) { // We can ignore retains, cond_fails, and dealloc_stacks. if (isa<StrongRetainInst>(ByInst) || isa<RetainValueInst>(ByInst) || isa<CondFailInst>(ByInst) || isa<DeallocStackInst>(ByInst)) return; SmallVector<SILInstruction *, 8> RS(Reads.begin(), Reads.end()); for (auto R : RS) { auto *LI = dyn_cast<LoadInst>(R); if (LI && !AA->mayWriteToMemory(ByInst, LI->getOperand())) continue; DEBUG(llvm::dbgs() << " mayWriteTo\n" << *ByInst << " to " << *R << "\n"); Reads.erase(R); } } static bool hasLoopInvariantOperands(SILInstruction *I, SILLoop *L) { auto Opds = I->getAllOperands(); return std::all_of(Opds.begin(), Opds.end(), [=](Operand &Op) { auto *Def = Op.get().getDef(); // Operand is defined outside the loop. if (auto *Inst = dyn_cast<SILInstruction>(Def)) return !L->contains(Inst->getParent()); if (auto *Arg = dyn_cast<SILArgument>(Def)) return !L->contains(Arg->getParent()); return false; }); } /// Check if an address does not depend on other values in a basic block. static SILInstruction *addressIndependent(SILValue Addr) { Addr = Addr.stripCasts(); if (GlobalAddrInst *SGAI = dyn_cast<GlobalAddrInst>(Addr)) return SGAI; if (StructElementAddrInst *SEAI = dyn_cast<StructElementAddrInst>(Addr)) return addressIndependent(SEAI->getOperand()); return nullptr; } /// Check if two addresses can potentially access the same memory. /// For now, return true when both can be traced to the same global variable. static bool addressCanPairUp(SILValue Addr1, SILValue Addr2) { SILInstruction *Origin1 = addressIndependent(Addr1); return Origin1 && Origin1 == addressIndependent(Addr2); } /// Move cond_fail down if it can potentially help register promotion later. static bool sinkCondFail(SILLoop *Loop) { // Only handle innermost loops for now. if (!Loop->getSubLoops().empty()) return false; bool Changed = false; for (auto *BB : Loop->getBlocks()) { // A list of CondFails that can be moved down. SmallVector<CondFailInst*, 4> CFs; // A pair of load and store that are independent of the CondFails and // can potentially access the same memory. LoadInst *LIOfPair = nullptr; bool foundPair = false; for (auto &Inst : *BB) { if (foundPair) { // Move CFs to right before Inst. for (unsigned I = 0, E = CFs.size(); I < E; I++) { DEBUG(llvm::dbgs() << "sinking cond_fail down "); DEBUG(CFs[I]->dump()); DEBUG(llvm::dbgs() << " before "); DEBUG(Inst.dump()); CFs[I]->moveBefore(&Inst); } Changed = true; foundPair = false; LIOfPair = nullptr; } if (auto CF = dyn_cast<CondFailInst>(&Inst)) { CFs.push_back(CF); } else if (auto LI = dyn_cast<LoadInst>(&Inst)) { if (addressIndependent(LI->getOperand())) { LIOfPair = LI; } else { CFs.clear(); LIOfPair = nullptr; } } else if (auto SI = dyn_cast<StoreInst>(&Inst)) { if (addressIndependent(SI->getDest())) { if (LIOfPair && addressCanPairUp(SI->getDest(), LIOfPair->getOperand())) foundPair = true; } else { CFs.clear(); LIOfPair = nullptr; } } else if (Inst.mayHaveSideEffects()) { CFs.clear(); LIOfPair = nullptr; } } } return Changed; } /// Checks if \p Inst has no side effects which prevent hoisting. /// The \a SafeReads set contain instructions which we already proved to have /// no such side effects. static bool hasNoSideEffect(SILInstruction *Inst, ReadSet &SafeReads) { // We can (and must) hoist cond_fail instructions if the operand is // invariant. We must hoist them so that we preserve memory safety. A // cond_fail that would have protected (executed before) a memory access // must - after hoisting - also be executed before said access. if (isa<CondFailInst>(Inst)) return true; // Can't hoist if the instruction could read from memory and is not marked // as safe. if (SafeReads.count(Inst)) return true; if (Inst->getMemoryBehavior() == SILInstruction::MemoryBehavior::None) return true; return false; } static bool canHoistInstruction(SILInstruction *Inst, SILLoop *Loop, ReadSet &SafeReads) { // Can't hoist terminators. if (isa<TermInst>(Inst)) return false; // Can't hoist allocation and dealloc stacks. if (isa<AllocationInst>(Inst) || isa<DeallocStackInst>(Inst)) return false; // Can't hoist instructions which may have side effects. if (!hasNoSideEffect(Inst, SafeReads)) return false; // The operands need to be loop invariant. if (!hasLoopInvariantOperands(Inst, Loop)) { DEBUG(llvm::dbgs() << " loop variant operands\n"); return false; } return true; } static bool hoistInstructions(SILLoop *Loop, DominanceInfo *DT, ReadSet &SafeReads, bool RunsOnHighLevelSil) { auto Preheader = Loop->getLoopPreheader(); if (!Preheader) return false; DEBUG(llvm::dbgs() << " Hoisting instructions.\n"); auto HeaderBB = Loop->getHeader(); bool Changed = false; // Traverse the dominator tree starting at the loop header. Hoisting // instructions as we go. auto DTRoot = DT->getNode(HeaderBB); SmallVector<SILBasicBlock *, 8> ExitingBBs; Loop->getExitingBlocks(ExitingBBs); for (llvm::df_iterator<DominanceInfoNode *> It = llvm::df_begin(DTRoot), E = llvm::df_end(DTRoot); It != E;) { auto *CurBB = It->getBlock(); // Don't decent into control-dependent code. Only traverse into basic blocks // that dominate all exits. if (!std::all_of(ExitingBBs.begin(), ExitingBBs.end(), [=](SILBasicBlock *ExitBB) { if (DT->dominates(CurBB, ExitBB)) return true; return false; })) { DEBUG(llvm::dbgs() << " skipping conditional block " << *CurBB << "\n"); It.skipChildren(); continue; } // We now that the block is guaranteed to be executed. Hoist if we can. for (auto InstIt = CurBB->begin(), E = CurBB->end(); InstIt != E; ) { SILInstruction *Inst = &*InstIt; ++InstIt; DEBUG(llvm::dbgs() << " looking at " << *Inst); if (canHoistInstruction(Inst, Loop, SafeReads)) { DEBUG(llvm::dbgs() << " hoisting to preheader.\n"); Changed = true; Inst->moveBefore(Preheader->getTerminator()); } else if (RunsOnHighLevelSil){ ArraySemanticsCall semCall(Inst); switch (semCall.getKind()) { case ArrayCallKind::kGetCount: case ArrayCallKind::kGetCapacity: if (hasLoopInvariantOperands(Inst, Loop) && semCall.canHoist(Preheader->getTerminator(), DT)) { Changed = true; semCall.hoist(Preheader->getTerminator(), DT); } break; default: break; } } } // Next block in dominator tree. ++It; } return Changed; } static bool sinkFixLifetime(SILLoop *Loop, DominanceInfo *DomTree, SILLoopInfo *LI) { DEBUG(llvm::errs() << " Sink fix_lifetime attempt\n"); auto Preheader = Loop->getLoopPreheader(); if (!Preheader) return false; // Only handle innermost loops for now. if (!Loop->getSubLoops().empty()) return false; // Only handle single exit blocks for now. auto *ExitBB = Loop->getExitBlock(); if (!ExitBB) return false; auto *ExitingBB = Loop->getExitingBlock(); if (!ExitingBB) return false; // We can sink fix_lifetime instructions if there are no reference counting // instructions in the loop. SmallVector<FixLifetimeInst *, 16> FixLifetimeInsts; for (auto *BB : Loop->getBlocks()) { for (auto &Inst : *BB) { if (auto FLI = dyn_cast<FixLifetimeInst>(&Inst)) { FixLifetimeInsts.push_back(FLI); } else if (Inst.mayHaveSideEffects() && !isa<LoadInst>(&Inst) && !isa<StoreInst>(&Inst)) { DEBUG(llvm::errs() << " mayhavesideeffects because of" << Inst); DEBUG(Inst.getParent()->dump()); return false; } } } // Sink the fix_lifetime instruction. bool Changed = false; for (auto *FLI : FixLifetimeInsts) if (DomTree->dominates(FLI->getOperand().getDef()->getParentBB(), Preheader)) { auto Succs = ExitingBB->getSuccessors(); for (unsigned EdgeIdx = 0; EdgeIdx < Succs.size(); ++EdgeIdx) { SILBasicBlock *BB = Succs[EdgeIdx]; if (BB == ExitBB) { auto *SplitBB = splitCriticalEdge(ExitingBB->getTerminator(), EdgeIdx, DomTree, LI); auto *OutsideBB = SplitBB ? SplitBB : ExitBB; // Update the ExitBB. ExitBB = OutsideBB; DEBUG(llvm::errs() << " moving fix_lifetime to exit BB " << *FLI); FLI->moveBefore(&*OutsideBB->begin()); Changed = true; } } } else { DEBUG(llvm::errs() << " does not dominate " << *FLI); } return Changed; } namespace { /// \brief Summary of may writes occurring in the loop tree rooted at \p /// Loop. This includes all writes of the sub loops and the loop itself. struct LoopNestSummary { SILLoop *Loop; WriteSet MayWrites; LoopNestSummary(SILLoop *Curr) : Loop(Curr) {} void copySummary(LoopNestSummary &Other) { MayWrites.append(Other.MayWrites.begin(), Other.MayWrites.end()); } LoopNestSummary(const LoopNestSummary &) = delete; LoopNestSummary &operator=(const LoopNestSummary &) = delete; LoopNestSummary(LoopNestSummary &&) = delete; }; /// \brief Optimize the loop tree bottom up propagating loop's summaries up the /// loop tree. class LoopTreeOptimization { llvm::DenseMap<SILLoop *, std::unique_ptr<LoopNestSummary>> LoopNestSummaryMap; SmallVector<SILLoop *, 8> BotUpWorkList; SILLoopInfo *LoopInfo; AliasAnalysis *AA; SideEffectAnalysis *SEA; DominanceInfo *DomTree; bool Changed; /// True if LICM is done on high-level SIL, i.e. semantic calls are not /// inlined yet. In this case some semantic calls can be hoisted. bool RunsOnHighLevelSil; public: LoopTreeOptimization(SILLoop *TopLevelLoop, SILLoopInfo *LI, AliasAnalysis *AA, SideEffectAnalysis *SEA, DominanceInfo *DT, bool RunsOnHighLevelSil) : LoopInfo(LI), AA(AA), SEA(SEA), DomTree(DT), Changed(false), RunsOnHighLevelSil(RunsOnHighLevelSil) { // Collect loops for a recursive bottom-up traversal in the loop tree. BotUpWorkList.push_back(TopLevelLoop); for (unsigned i = 0; i < BotUpWorkList.size(); ++i) { auto *L = BotUpWorkList[i]; for (auto *SubLoop : *L) BotUpWorkList.push_back(SubLoop); } } /// \brief Optimize this loop tree. bool optimize(); protected: /// \brief Propagate the sub-loops' summaries up to the current loop. void propagateSummaries(std::unique_ptr<LoopNestSummary> &CurrSummary); /// \brief Collect a set of reads that can be hoisted to the loop's preheader. void analyzeCurrentLoop(std::unique_ptr<LoopNestSummary> &CurrSummary, ReadSet &SafeReads); /// \brief Optimize the current loop nest. void optimizeLoop(SILLoop *CurrentLoop, ReadSet &SafeReads); }; } bool LoopTreeOptimization::optimize() { // Process loops bottom up in the loop tree. while (!BotUpWorkList.empty()) { SILLoop *CurrentLoop = BotUpWorkList.pop_back_val(); DEBUG(llvm::dbgs() << "Processing loop " << *CurrentLoop); // Collect all summary of all sub loops of the current loop. Since we // process the loop tree bottom up they are guaranteed to be available in // the map. auto CurrLoopSummary = llvm::make_unique<LoopNestSummary>(CurrentLoop); propagateSummaries(CurrLoopSummary); // Analyse the current loop for reads that can be hoisted. ReadSet SafeReads; analyzeCurrentLoop(CurrLoopSummary, SafeReads); optimizeLoop(CurrentLoop, SafeReads); // Store the summary for parent loops to use. LoopNestSummaryMap[CurrentLoop] = std::move(CurrLoopSummary); } return Changed; } void LoopTreeOptimization::propagateSummaries( std::unique_ptr<LoopNestSummary> &CurrSummary) { for (auto *SubLoop : *CurrSummary->Loop) { assert(LoopNestSummaryMap.count(SubLoop) && "Must have data for sub loops"); CurrSummary->copySummary(*LoopNestSummaryMap[SubLoop]); LoopNestSummaryMap.erase(SubLoop); } } void LoopTreeOptimization::analyzeCurrentLoop( std::unique_ptr<LoopNestSummary> &CurrSummary, ReadSet &SafeReads) { WriteSet &MayWrites = CurrSummary->MayWrites; SILLoop *Loop = CurrSummary->Loop; DEBUG(llvm::dbgs() << " Analysing accesses.\n"); // Contains function calls in the loop, which only read from memory. SmallVector<ApplyInst *, 8> ReadOnlyApplies; for (auto *BB : Loop->getBlocks()) { for (auto &Inst : *BB) { // Ignore fix_lifetime instructions. if (isa<FixLifetimeInst>(&Inst)) continue; // Collect loads. auto LI = dyn_cast<LoadInst>(&Inst); if (LI) { if (!mayWriteTo(AA, MayWrites, LI)) SafeReads.insert(LI); continue; } if (auto *AI = dyn_cast<ApplyInst>(&Inst)) { // In contrast to load instructions, we first collect all read-only // function calls and add them later to SafeReads. SideEffectAnalysis::FunctionEffects E; SEA->getEffects(E, AI); auto MB = E.getMemBehavior(RetainObserveKind::ObserveRetains); if (MB <= SILInstruction::MemoryBehavior::MayRead) ReadOnlyApplies.push_back(AI); } if (Inst.mayHaveSideEffects()) { MayWrites.push_back(&Inst); // Remove clobbered loads we have seen before. removeWrittenTo(AA, SafeReads, &Inst); } } } for (auto *AI : ReadOnlyApplies) { if (!mayWriteTo(AA, SEA, MayWrites, AI)) SafeReads.insert(AI); } } void LoopTreeOptimization::optimizeLoop(SILLoop *CurrentLoop, ReadSet &SafeReads) { Changed |= sinkCondFail(CurrentLoop); Changed |= hoistInstructions(CurrentLoop, DomTree, SafeReads, RunsOnHighLevelSil); Changed |= sinkFixLifetime(CurrentLoop, DomTree, LoopInfo); } namespace { /// Hoist loop invariant code out of innermost loops. class LICM : public SILFunctionTransform { public: LICM(bool RunsOnHighLevelSil) : RunsOnHighLevelSil(RunsOnHighLevelSil) {} /// True if LICM is done on high-level SIL, i.e. semantic calls are not /// inlined yet. In this case some semantic calls can be hoisted. /// We only hoist semantic calls on high-level SIL because we can be sure that /// e.g. an Array as SILValue is really immutable (including its content). bool RunsOnHighLevelSil; StringRef getName() override { return RunsOnHighLevelSil ? "High-level Loop Invariant Code Motion" : "Loop Invariant Code Motion"; } void run() override { SILFunction *F = getFunction(); SILLoopAnalysis *LA = PM->getAnalysis<SILLoopAnalysis>(); SILLoopInfo *LoopInfo = LA->get(F); if (LoopInfo->empty()) { DEBUG(llvm::dbgs() << "No loops in " << F->getName() << "\n"); return; } DominanceAnalysis *DA = PM->getAnalysis<DominanceAnalysis>(); AliasAnalysis *AA = PM->getAnalysis<AliasAnalysis>(); SideEffectAnalysis *SEA = PM->getAnalysis<SideEffectAnalysis>(); DominanceInfo *DomTree = nullptr; DEBUG(llvm::dbgs() << "Processing loops in " << F->getName() << "\n"); bool Changed = false; for (auto *TopLevelLoop : *LoopInfo) { if (!DomTree) DomTree = DA->get(F); LoopTreeOptimization Opt(TopLevelLoop, LoopInfo, AA, SEA, DomTree, RunsOnHighLevelSil); Changed |= Opt.optimize(); } if (Changed) { LA->lockInvalidation(); DA->lockInvalidation(); PM->invalidateAnalysis(F, SILAnalysis::InvalidationKind::FunctionBody); LA->unlockInvalidation(); DA->unlockInvalidation(); } } }; } SILTransform *swift::createLICM() { return new LICM(false); } SILTransform *swift::createHighLevelLICM() { return new LICM(true); }
// Copyright (c) 2020 Graphcore Ltd. All rights reserved. #ifndef INCLUDE_POPTORCH_TYPE_AND_CONSTANT_CANONICALIZATION_H #define INCLUDE_POPTORCH_TYPE_AND_CONSTANT_CANONICALIZATION_H #include <sstream> #include <string> #include <vector> namespace at { class Tensor; } // namespace at namespace c10 { struct Symbol; } // namespace c10 namespace torch { namespace jit { struct Graph; struct Node; } // namespace jit } // namespace torch namespace poptorch { namespace type_and_constant_canonicalization { void evaluateConstexprs(torch::jit::Graph *graph); void makeConstantIntParams(torch::jit::Graph *graph, const std::vector<std::string> &parameter_names, const std::vector<at::Tensor> &traced_tensors); // Change the graph to add a poptorch::host_side_cast node after every graph // input whose type is unsupported (Long, Double, BFloat16) to reflect the // the casting which would happen on the host and the correct types as they // would be on the graph. void castUnsupportedInputs(torch::jit::Graph *graph); // Change any unsupported output types to the appropriate equivalent (e.g. // double to float) and warn; error on any totally unsupported types e.g. 8 bit. void checkAndChangeOutputTypes(torch::jit::Graph *graph); // Changes all constants used in implicit casting operations into tensor // constants (poptorch::tensor_constant) of the correct type. Note the other // constants remain unchanged. void canonicaliseConstants(torch::jit::Graph *graph); } // namespace type_and_constant_canonicalization } // namespace poptorch #endif // INCLUDE_POPTORCH_TYPE_AND_CONSTANT_CANONICALIZATION_H
/****************************************************************************** * * Project: OGDI Bridge * Purpose: Implements OGROGDILayer class. * Author: Daniel Morissette, danmo@videotron.ca * (Based on some code contributed by Frank Warmerdam :) * ****************************************************************************** * Copyright (c) 2000, Daniel Morissette * Copyright (c) 2008-2013, Even Rouault <even dot rouault at mines-paris dot org> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** */ #include "ogrogdi.h" #include "cpl_conv.h" #include "cpl_string.h" CPL_CVSID("$Id: ogrogdilayer.cpp 7e07230bbff24eb333608de4dbd460b7312839d0 2017-12-11 19:08:47Z Even Rouault $") /************************************************************************/ /* OGROGDILayer() */ /************************************************************************/ OGROGDILayer::OGROGDILayer( OGROGDIDataSource *poODS, const char * pszName, ecs_Family eFamily ) : m_poODS(poODS), m_nClientID(poODS->GetClientID()), m_pszOGDILayerName(CPLStrdup(pszName)), m_eFamily(eFamily), m_poFeatureDefn(nullptr), // Keep a reference on the SpatialRef (owned by the dataset). m_poSpatialRef(m_poODS->GetSpatialRef()), m_sFilterBounds(*(m_poODS->GetGlobalBounds())), m_iNextShapeId(0), m_nTotalShapeCount(-1), m_nFilteredOutShapes(0) { // Select layer and feature family. ResetReading(); BuildFeatureDefn(); } /************************************************************************/ /* ~OGROGDILayer() */ /************************************************************************/ OGROGDILayer::~OGROGDILayer() { if( m_nFeaturesRead > 0 && m_poFeatureDefn != nullptr ) { CPLDebug( "OGDI", "%d features read on layer '%s'.", (int) m_nFeaturesRead, m_poFeatureDefn->GetName() ); } if (m_poFeatureDefn) m_poFeatureDefn->Release(); CPLFree(m_pszOGDILayerName); // Note: we do not delete m_poSpatialRef since it is owned by the dataset } /************************************************************************/ /* SetSpatialFilter() */ /************************************************************************/ void OGROGDILayer::SetSpatialFilter( OGRGeometry * poGeomIn ) { if( !InstallFilter( poGeomIn ) ) return; ResetReading(); m_nTotalShapeCount = -1; } /************************************************************************/ /* SetAttributeFilter() */ /************************************************************************/ OGRErr OGROGDILayer::SetAttributeFilter( const char *pszQuery ) { OGRErr eErr = OGRLayer::SetAttributeFilter(pszQuery); ResetReading(); m_nTotalShapeCount = -1; return eErr; } /************************************************************************/ /* ResetReading() */ /************************************************************************/ void OGROGDILayer::ResetReading() { ecs_LayerSelection sSelectionLayer; sSelectionLayer.Select = m_pszOGDILayerName; sSelectionLayer.F = m_eFamily; ecs_Result *psResult = cln_SelectLayer(m_nClientID, &sSelectionLayer); if( ECSERROR( psResult ) ) { CPLError( CE_Failure, CPLE_AppDefined, "Access to layer '%s' Failed: %s\n", m_pszOGDILayerName, psResult->message ? psResult->message : "(no message string)" ); return; } /* Reset spatial filter */ if( m_poFilterGeom != nullptr ) { OGREnvelope oEnv; m_poFilterGeom->getEnvelope(&oEnv); m_sFilterBounds.north = oEnv.MaxY; m_sFilterBounds.south = oEnv.MinY; m_sFilterBounds.east = oEnv.MinX; m_sFilterBounds.west = oEnv.MaxX; psResult = cln_SelectRegion( m_nClientID, &m_sFilterBounds); if( ECSERROR(psResult) ) { CPLError( CE_Failure, CPLE_AppDefined, "SelectRegion failed: %s", psResult->message ? psResult->message : "(no message string)" ); return; } } else { /* Reset to global bounds */ psResult = cln_SelectRegion( m_nClientID, m_poODS->GetGlobalBounds() ); if( ECSERROR(psResult) ) { CPLError( CE_Failure, CPLE_AppDefined, "SelectRegion failed: %s", psResult->message ? psResult->message : "(no message string)"); return; } } m_iNextShapeId = 0; m_nFilteredOutShapes = 0; } /************************************************************************/ /* GetNextFeature() */ /************************************************************************/ OGRFeature *OGROGDILayer::GetNextFeature() { /* Reset reading if we are not the current layer */ /* WARNING : this does not allow interleaved reading of layers */ if( m_poODS->GetCurrentLayer() != this ) { m_poODS->SetCurrentLayer(this); ResetReading(); } while( true ) { OGRFeature *poFeature = GetNextRawFeature(); if( poFeature == nullptr ) return nullptr; /* -------------------------------------------------------------------- */ /* Do we need to apply an attribute test? */ /* -------------------------------------------------------------------- */ if( (m_poAttrQuery != nullptr && !m_poAttrQuery->Evaluate( poFeature ) ) || (m_poFilterGeom != nullptr && !FilterGeometry( poFeature->GetGeometryRef() ) ) ) { m_nFilteredOutShapes ++; delete poFeature; } else return poFeature; } } /************************************************************************/ /* GetNextFeature() */ /************************************************************************/ OGRFeature *OGROGDILayer::GetNextRawFeature() { /* -------------------------------------------------------------------- */ /* Retrieve object from OGDI server and create new feature */ /* -------------------------------------------------------------------- */ ecs_Result *psResult = cln_GetNextObject(m_nClientID); if (! ECSSUCCESS(psResult)) { if( ECSERROR( psResult ) && (psResult->message == nullptr || strstr(psResult->message, "End of selection") == nullptr) ) { CPLError( CE_Failure, CPLE_AppDefined, "Access to next object of layer '%s' failed: %s\n", m_pszOGDILayerName, psResult->message ? psResult->message : "(no error string)" ); } // We probably reached EOF... keep track of shape count. m_nTotalShapeCount = m_iNextShapeId - m_nFilteredOutShapes; return nullptr; } OGRFeature *poFeature = new OGRFeature(m_poFeatureDefn); poFeature->SetFID( m_iNextShapeId++ ); m_nFeaturesRead++; /* -------------------------------------------------------------------- */ /* Process geometry */ /* -------------------------------------------------------------------- */ if (m_eFamily == Point) { ecs_Point *psPoint = &(ECSGEOM(psResult).point); OGRPoint *poOGRPoint = new OGRPoint(psPoint->c.x, psPoint->c.y); poOGRPoint->assignSpatialReference(m_poSpatialRef); poFeature->SetGeometryDirectly(poOGRPoint); } else if (m_eFamily == Line) { ecs_Line *psLine = &(ECSGEOM(psResult).line); OGRLineString *poOGRLine = new OGRLineString(); poOGRLine->setNumPoints( psLine->c.c_len ); for( int i = 0; i < (int) psLine->c.c_len; i++ ) { poOGRLine->setPoint(i, psLine->c.c_val[i].x, psLine->c.c_val[i].y); } poOGRLine->assignSpatialReference(m_poSpatialRef); poFeature->SetGeometryDirectly(poOGRLine); } else if (m_eFamily == Area) { ecs_Area *psArea = &(ECSGEOM(psResult).area); OGRPolygon *poOGRPolygon = new OGRPolygon(); for( int iRing = 0; iRing < (int) psArea->ring.ring_len; iRing++ ) { ecs_FeatureRing *psRing = &(psArea->ring.ring_val[iRing]); OGRLinearRing *poOGRRing = new OGRLinearRing(); poOGRRing->setNumPoints( psRing->c.c_len ); for( int i = 0; i < (int) psRing->c.c_len; i++ ) { poOGRRing->setPoint(i, psRing->c.c_val[i].x, psRing->c.c_val[i].y); } poOGRPolygon->addRingDirectly(poOGRRing); } // __TODO__ // When OGR supports polygon centroids then we should carry them here poOGRPolygon->assignSpatialReference(m_poSpatialRef); poFeature->SetGeometryDirectly(poOGRPolygon); } else if (m_eFamily == Text) { // __TODO__ // For now text is treated as a point and string is lost // ecs_Text *psText = &(ECSGEOM(psResult).text); OGRPoint *poOGRPoint = new OGRPoint(psText->c.x, psText->c.y); poOGRPoint->assignSpatialReference(m_poSpatialRef); poFeature->SetGeometryDirectly(poOGRPoint); } else { CPLAssert(false); } /* -------------------------------------------------------------------- */ /* Set attributes */ /* -------------------------------------------------------------------- */ char *pszAttrList = ECSOBJECTATTR(psResult); for( int iField = 0; iField < m_poFeatureDefn->GetFieldCount(); iField++ ) { char *pszFieldStart = nullptr; int nNameLen = 0; /* parse out the next attribute value */ if( !ecs_FindElement( pszAttrList, &pszFieldStart, &pszAttrList, &nNameLen, nullptr ) ) { nNameLen = 0; pszFieldStart = pszAttrList; } /* Skip any trailing white space (for string constants). */ if( nNameLen > 0 && pszFieldStart[nNameLen-1] == ' ' ) nNameLen--; /* skip leading white space */ while( pszFieldStart[0] == ' ' && nNameLen > 0 ) { pszFieldStart++; nNameLen--; } /* zero terminate the single field value, but save the */ /* character we overwrote, so we can restore it when done. */ char chSavedChar = pszFieldStart[nNameLen]; pszFieldStart[nNameLen] = '\0'; /* OGR takes care of all field type conversions for us! */ poFeature->SetField(iField, pszFieldStart); pszFieldStart[nNameLen] = chSavedChar; } /* -------------------------------------------------------------------- */ /* Apply the text associated with text features if appropriate. */ /* -------------------------------------------------------------------- */ if( m_eFamily == Text ) { poFeature->SetField( "text", ECSGEOM(psResult).text.desc ); } return poFeature; } /************************************************************************/ /* GetFeature() */ /************************************************************************/ OGRFeature *OGROGDILayer::GetFeature( GIntBig nFeatureId ) { if (m_nTotalShapeCount != -1 && nFeatureId > m_nTotalShapeCount) return nullptr; /* Unset spatial filter */ OGRGeometry* poOldFilterGeom = ( m_poFilterGeom != nullptr ) ? m_poFilterGeom->clone() : nullptr; if( poOldFilterGeom != nullptr ) SetSpatialFilter(nullptr); /* Reset reading if we are not the current layer */ /* WARNING : this does not allow interleaved reading of layers */ if( m_poODS->GetCurrentLayer() != this ) { m_poODS->SetCurrentLayer(this); ResetReading(); } else if ( nFeatureId < m_iNextShapeId ) ResetReading(); while(m_iNextShapeId != nFeatureId) { ecs_Result *psResult = cln_GetNextObject(m_nClientID); if (ECSSUCCESS(psResult)) m_iNextShapeId++; else { // We probably reached EOF... keep track of shape count. m_nTotalShapeCount = m_iNextShapeId; if( poOldFilterGeom != nullptr ) { SetSpatialFilter(poOldFilterGeom); delete poOldFilterGeom; } return nullptr; } } // OK, we're ready to read the requested feature... OGRFeature* poFeature = GetNextRawFeature(); if( poOldFilterGeom != nullptr ) { SetSpatialFilter(poOldFilterGeom); delete poOldFilterGeom; } return poFeature; } /************************************************************************/ /* GetFeatureCount() */ /* */ /* If a spatial filter is in effect, we turn control over to */ /* the generic counter. Otherwise we return the total count. */ /* Eventually we should consider implementing a more efficient */ /* way of counting features matching a spatial query. */ /************************************************************************/ GIntBig OGROGDILayer::GetFeatureCount( int bForce ) { if( m_nTotalShapeCount == -1) { m_nTotalShapeCount = static_cast<int>(OGRLayer::GetFeatureCount( bForce )); } return m_nTotalShapeCount; } /************************************************************************/ /* TestCapability() */ /************************************************************************/ int OGROGDILayer::TestCapability( const char * pszCap ) { /* -------------------------------------------------------------------- */ /* Hummm... what are the proper capabilities... */ /* Does OGDI have any idea of capabilities??? */ /* For now just return FALSE for everything. */ /* -------------------------------------------------------------------- */ #ifdef __TODO__ if( EQUAL(pszCap,OLCFastFeatureCount) ) return m_poFilterGeom == NULL && m_poAttrQuery == NULL; else if( EQUAL(pszCap,OLCFastSpatialFilter) ) return FALSE; else return FALSE; #endif if( EQUAL(pszCap,OLCRandomRead) ) return TRUE; else return FALSE; } /************************************************************************/ /* BuildFeatureDefn() */ /* */ /* (private) Initializes the schema in m_poFeatureDefn */ /************************************************************************/ void OGROGDILayer::BuildFeatureDefn() { const char *pszGeomName = nullptr; OGRwkbGeometryType eLayerGeomType = wkbUnknown; /* -------------------------------------------------------------------- */ /* Feature Defn name will be "<OGDILyrName>_<FeatureFamily>" */ /* -------------------------------------------------------------------- */ switch( m_eFamily ) { case Point: pszGeomName = "point"; eLayerGeomType = wkbPoint; break; case Line: pszGeomName = "line"; eLayerGeomType = wkbLineString; break; case Area: pszGeomName = "area"; eLayerGeomType = wkbPolygon; break; case Text: pszGeomName = "text"; eLayerGeomType = wkbPoint; break; default: pszGeomName = "unknown"; eLayerGeomType = wkbUnknown; break; } char* pszFeatureDefnName = nullptr; if (m_poODS->LaunderLayerNames()) { pszFeatureDefnName = CPLStrdup(m_pszOGDILayerName); char* pszAt = strchr(pszFeatureDefnName, '@'); if (pszAt) *pszAt = '_'; char* pszLeftParenthesis = strchr(pszFeatureDefnName, '('); if (pszLeftParenthesis) *pszLeftParenthesis = '\0'; } else pszFeatureDefnName = CPLStrdup(CPLSPrintf("%s_%s", m_pszOGDILayerName, pszGeomName )); m_poFeatureDefn = new OGRFeatureDefn(pszFeatureDefnName); SetDescription( m_poFeatureDefn->GetName() ); CPLFree(pszFeatureDefnName); pszFeatureDefnName = nullptr; m_poFeatureDefn->SetGeomType(eLayerGeomType); m_poFeatureDefn->Reference(); m_poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(m_poSpatialRef); /* -------------------------------------------------------------------- */ /* Fetch schema from OGDI server and map to OGR types */ /* -------------------------------------------------------------------- */ ecs_Result *psResult = cln_GetAttributesFormat( m_nClientID ); if( ECSERROR( psResult ) ) { CPLError(CE_Failure, CPLE_AppDefined, "ECSERROR: %s\n", psResult->message ? psResult->message : "(no message string)"); return; } ecs_ObjAttributeFormat *oaf = &(ECSRESULT(psResult).oaf); const int numFields = oaf->oa.oa_len; for( int i = 0; i < numFields; i++ ) { OGRFieldDefn oField("", OFTInteger); oField.SetName( oaf->oa.oa_val[i].name ); oField.SetPrecision( 0 ); switch( oaf->oa.oa_val[i].type ) { case Decimal: case Smallint: case Integer: oField.SetType( OFTInteger ); // TODO: Fix spelling - lenght -> length if( oaf->oa.oa_val[i].lenght > 0 ) oField.SetWidth( oaf->oa.oa_val[i].lenght ); else oField.SetWidth( 11 ); break; case Numeric: case Real: case Float: case Double: oField.SetType( OFTReal ); if( oaf->oa.oa_val[i].lenght > 0 ) { oField.SetWidth( oaf->oa.oa_val[i].lenght ); oField.SetPrecision( oaf->oa.oa_val[i].precision ); } else { oField.SetWidth( 18 ); oField.SetPrecision( 7 ); } break; case Char: case Varchar: case Longvarchar: default: oField.SetType( OFTString ); if( oaf->oa.oa_val[i].lenght > 0 ) oField.SetWidth( oaf->oa.oa_val[i].lenght ); else oField.SetWidth( 64 ); break; } m_poFeatureDefn->AddFieldDefn( &oField ); } /* -------------------------------------------------------------------- */ /* Add a text attribute for text objects. */ /* -------------------------------------------------------------------- */ if( m_eFamily == Text ) { OGRFieldDefn oField("text", OFTString); m_poFeatureDefn->AddFieldDefn( &oField ); } }
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include <SystemManager/SystemManagerCommon.hpp> namespace sys { class AlarmActivationStatusChangeRequest; class SystemManager : public SystemManagerCommon { public: explicit SystemManager(std::vector<std::unique_ptr<BaseServiceCreator>> &&creators); private: auto InitHandler() -> ReturnCodes override; auto handleAlarmActivationStatusChangeRequest(AlarmActivationStatusChangeRequest *request) -> MessagePointer; void batteryShutdownLevelAction() override; }; } // namespace sys
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/base/win/mf_initializer.h" #include <mfapi.h> #include "base/lazy_instance.h" #include "base/macros.h" namespace media { namespace { // LazyInstance to initialize the Media Foundation Library. class MFInitializer { public: MFInitializer() : mf_started_(MFStartup(MF_VERSION, MFSTARTUP_LITE) == S_OK) {} ~MFInitializer() { if (mf_started_) MFShutdown(); } private: const bool mf_started_; DISALLOW_COPY_AND_ASSIGN(MFInitializer); }; base::LazyInstance<MFInitializer> g_mf_initializer = LAZY_INSTANCE_INITIALIZER; } // namespace void InitializeMediaFoundation() { g_mf_initializer.Get(); } } // namespace media
/*++ Copyright (c) 1999 Microsoft Corporation Abstract: @doc @module Provider.hxx | Declarations used by the Software Snapshot Provider interface @end Author: Brian Berkowitz [brianb] 05/01/2001 Revision History: Name Date Comments --*/ ///////////////////////////////////////////////////////////////////////////// // Includes #include "stdafx.hxx" #include <winnt.h> // Generated MIDL header #include "vss.h" #include "vdslun.h" #include "vsprov.h" #include "vscoordint.h" #include "hwprv.h" #include "resource.h" #include "vs_inc.hxx" #include "vs_sec.hxx" #include "vs_reg.hxx" #include "hwprv.hxx" #include "provider.hxx" //////////////////////////////////////////////////////////////////////// // Standard foo for file name aliasing. This code block must be after // all includes of VSS header files. // #ifdef VSS_FILE_ALIAS #undef VSS_FILE_ALIAS #endif #define VSS_FILE_ALIAS "TSTHWPRC" // //////////////////////////////////////////////////////////////////////// CHardwareTestProvider::CHardwareTestProvider () : m_SnapshotSetId(GUID_NULL), m_maskSnapshotDisks(0), m_cDiskIds(0), m_pDynamicDiskInfo(NULL) { for(UINT i = 0; i < 32; i++) { m_rgpSourceLuns[i] = NULL; m_rgpDestinationLuns[i] = NULL; } memset(m_rgDiskSignatures, 0, sizeof(m_rgDiskSignatures)); m_bRebuilt = false; } CHardwareTestProvider::~CHardwareTestProvider() { ClearConfiguration(); if (m_pDynamicDiskInfo) { do { DYNAMIC_DISK_INFO *pNext = m_pDynamicDiskInfo->m_next; delete m_pDynamicDiskInfo->m_wszVolumes; delete m_pDynamicDiskInfo; m_pDynamicDiskInfo = pNext; } while(m_pDynamicDiskInfo); } } STDMETHODIMP CHardwareTestProvider::OnLoad ( IN IUnknown* pCallback ) { UNREFERENCED_PARAMETER(pCallback); CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::OnLoad"); try { m_cs.Init(); CVssSafeAutomaticLock lock(m_cs); ClearConfiguration(); LoadConfigurationData(); // clear various bits of snapshot goo m_bHidden = false; m_SnapshotSetId = GUID_NULL; m_maskSnapshotDisks = 0; } VSS_STANDARD_CATCH(ft) return ft.hr; } STDMETHODIMP CHardwareTestProvider::OnUnload ( IN BOOL bForceUnload ) { UNREFERENCED_PARAMETER(bForceUnload); CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::OnUnload"); CVssSafeAutomaticLock lock(m_cs); ClearConfiguration(); return ft.hr; } // // IVssHardwareSnapshotProvider // STDMETHODIMP CHardwareTestProvider::FillInLunInfo ( IN VSS_PWSZ wszDevice, IN OUT VDS_LUN_INFORMATION *pLunInformation, OUT BOOL *pbIsSupported ) { CVssFunctionTracer ft(VSSDBG_COORD, L"CHardwareTestProvider::FillInLunInfo"); CVssSafeAutomaticLock lock(m_cs); m_bRebuilt = false; try { if (pbIsSupported == NULL || pLunInformation == NULL) throw(VSSDBG_VSSTEST, E_INVALIDARG, L"NULL output parameter"); *pbIsSupported = FALSE; bool bFound = false; RebuildLunInfo(); for(DWORD iDestLun = 0; iDestLun < m_cDiskIds; iDestLun++) { if (IsMatchLun(*pLunInformation, *(m_rgpDestinationLuns[iDestLun]))) { bFound = true; break; } } if (bFound) { pLunInformation->m_rgInterconnects = (VDS_INTERCONNECT *) CoTaskMemAlloc(sizeof(VDS_INTERCONNECT)); if (pLunInformation->m_rgInterconnects == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); memset(pLunInformation->m_rgInterconnects, 0, sizeof(VDS_INTERCONNECT)); pLunInformation->m_cInterconnects = 1; pLunInformation->m_rgInterconnects->m_pbAddress = (BYTE *) CoTaskMemAlloc(sizeof(ULONG)); if (pLunInformation->m_rgInterconnects->m_pbAddress == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); pLunInformation->m_rgInterconnects->m_cbAddress = sizeof(ULONG); pLunInformation->m_rgInterconnects->m_addressType = VDS_IA_FCPH; pLunInformation->m_rgInterconnects->m_pbPort = (BYTE *) CoTaskMemAlloc(sizeof(ULONG)); if (pLunInformation->m_rgInterconnects->m_pbPort == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); *((ULONG *) (pLunInformation->m_rgInterconnects->m_pbPort)) = 0x8828080; pLunInformation->m_rgInterconnects->m_cbPort = sizeof(ULONG); for(iDestLun = 0; iDestLun < m_cDiskIds; iDestLun++) { if (IsMatchLun(*pLunInformation, *(m_rgpDestinationLuns[iDestLun]))) { *(ULONG *) (pLunInformation->m_rgInterconnects->m_pbAddress) = iDestLun; break; } } *pbIsSupported = true; } } VSS_STANDARD_CATCH(ft) return ft.hr; } STDMETHODIMP CHardwareTestProvider::AreLunsSupported ( IN LONG lLunCount, IN LONG lContext, IN VSS_PWSZ *rgwszDevices, IN OUT VDS_LUN_INFORMATION *rgLunInformation, OUT BOOL *pbIsSupported ) { UNREFERENCED_PARAMETER(rgwszDevices); CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::AreLunsSupported"); CVssSafeAutomaticLock lock(m_cs); m_bRebuilt = false; try { if (pbIsSupported == NULL || rgLunInformation == NULL) throw(VSSDBG_VSSTEST, E_INVALIDARG, L"NULL output parameter"); *pbIsSupported = FALSE; VDS_LUN_INFORMATION *pLunInformation = rgLunInformation; bool bFound = false; RebuildLunInfo(); for(LONG iLun = 0; iLun < lLunCount; iLun++, pLunInformation++) { bFound = false; for(DWORD iSourceLun = 0; iSourceLun < m_cDiskIds; iSourceLun++) { if (IsMatchLun(*pLunInformation, *(m_rgpSourceLuns[iSourceLun]))) { bFound = true; break; } } if (!bFound) break; } if (bFound) { pLunInformation = rgLunInformation; for(LONG iLun = 0; iLun < lLunCount; iLun++, pLunInformation++) { pLunInformation->m_rgInterconnects = (VDS_INTERCONNECT *) CoTaskMemAlloc(sizeof(VDS_INTERCONNECT)); if (pLunInformation->m_rgInterconnects == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); memset(pLunInformation->m_rgInterconnects, 0, sizeof(VDS_INTERCONNECT)); pLunInformation->m_cInterconnects = 1; pLunInformation->m_rgInterconnects->m_pbAddress = (BYTE *) CoTaskMemAlloc(sizeof(ULONG)); if (pLunInformation->m_rgInterconnects->m_pbAddress == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); pLunInformation->m_rgInterconnects->m_cbAddress = sizeof(ULONG); pLunInformation->m_rgInterconnects->m_addressType = VDS_IA_FCPH; pLunInformation->m_rgInterconnects->m_pbPort = (BYTE *) CoTaskMemAlloc(sizeof(ULONG)); if (pLunInformation->m_rgInterconnects->m_pbPort == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); *((ULONG *) (pLunInformation->m_rgInterconnects->m_pbPort)) = 0x8828080; pLunInformation->m_rgInterconnects->m_cbPort = sizeof(ULONG); for(DWORD iSourceLun = 0; iSourceLun < m_cDiskIds; iSourceLun++) { if (IsMatchLun(*pLunInformation, *(m_rgpSourceLuns[iSourceLun]))) { *(ULONG *) (pLunInformation->m_rgInterconnects->m_pbAddress) = iSourceLun; break; } } } *pbIsSupported = true; } } VSS_STANDARD_CATCH(ft) return ft.hr; } STDMETHODIMP CHardwareTestProvider::BeginPrepareSnapshot ( IN VSS_ID SnapshotSetId, IN VSS_ID SnapshotId, IN LONG lContext, IN LONG lLunCount, IN OUT VSS_PWSZ *rgwszDevices, IN VDS_LUN_INFORMATION *rgLunInformation ) { UNREFERENCED_PARAMETER(SnapshotId); UNREFERENCED_PARAMETER(rgwszDevices); CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::BeginPrepareSnapshot"); CVssSafeAutomaticLock lock(m_cs); m_bRebuilt = false; try { if (m_SnapshotSetId == GUID_NULL) { m_lContext = lContext; m_SnapshotSetId = SnapshotSetId; m_maskSnapshotDisks = 0; } VDS_LUN_INFORMATION *pLunInformation = rgLunInformation; for(LONG iLun = 0; iLun < lLunCount; iLun++, pLunInformation++) { if (pLunInformation->m_cInterconnects != 1 || pLunInformation->m_rgInterconnects == NULL || pLunInformation->m_rgInterconnects[0].m_cbAddress != sizeof(ULONG) || pLunInformation->m_rgInterconnects[0].m_cbPort != sizeof(ULONG) || *(ULONG *) (pLunInformation->m_rgInterconnects[0].m_pbPort) != 0x8828080) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"Drive not supported"); ULONG iDisk = *(ULONG *) (pLunInformation->m_rgInterconnects[0].m_pbAddress); *(ULONG *) (pLunInformation->m_rgInterconnects[0].m_pbAddress) |= 0x80000000; m_maskSnapshotDisks |= 1 << iDisk; } } VSS_STANDARD_CATCH(ft) return ft.hr; } // free all the components of a VDS_LUN_INFO structure void CHardwareTestProvider::FreeLunInfo ( IN VDS_LUN_INFORMATION *rgLunInfo, UINT cLuns ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CVssTestHardwareProvider::FreeLunInfo"); // check if pointer is NULL if (rgLunInfo == NULL) return; // loop through individual luns for(DWORD iLun = 0; iLun < cLuns; iLun++) { // get lun info VDS_LUN_INFORMATION *pLun = &rgLunInfo[iLun]; // free up strings if (pLun->m_szVendorId) CoTaskMemFree(pLun->m_szVendorId); if (pLun->m_szProductId) CoTaskMemFree(pLun->m_szProductId); if (pLun->m_szProductRevision) CoTaskMemFree(pLun->m_szProductRevision); if (pLun->m_szSerialNumber) CoTaskMemFree(pLun->m_szSerialNumber); // point to VDS_STORAGE_DEVICE_ID_DESCRIPTOR // get number of VDS_STORAGE_IDENTIFIERs in the descriptor ULONG cIds = pLun->m_deviceIdDescriptor.m_cIdentifiers; // point to first VDS_STORAGE_IDENTIFIER VDS_STORAGE_IDENTIFIER *pvsi = pLun->m_deviceIdDescriptor.m_rgIdentifiers; for(ULONG iId = 0; iId < cIds; iId++, pvsi++) { // free up data for identifier if (pvsi->m_rgbIdentifier) CoTaskMemFree(pvsi->m_rgbIdentifier); } // free up array of identifiers if (pLun->m_deviceIdDescriptor.m_rgIdentifiers) CoTaskMemFree(pLun->m_deviceIdDescriptor.m_rgIdentifiers); // point to first VDS_INTERCONNECT VDS_INTERCONNECT *pInterconnect = pLun->m_rgInterconnects; for(ULONG iInterconnect = 0; iInterconnect < pLun->m_cInterconnects; iInterconnect++, pInterconnect++) { // free up address if there is one if (pInterconnect->m_pbAddress) CoTaskMemFree(pInterconnect->m_pbAddress); if (pInterconnect->m_pbPort) CoTaskMemFree(pInterconnect->m_pbPort); } // free up array of interconnects if (pLun->m_rgInterconnects) CoTaskMemFree(pLun->m_rgInterconnects); } // free up array of lun information CoTaskMemFree(rgLunInfo); } void CHardwareTestProvider::CopyString(LPSTR &szCopy, LPCSTR szSource) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::CopyString"); if (szSource == NULL) { szCopy = NULL; return; } szCopy = (LPSTR) CoTaskMemAlloc(strlen(szSource) + 1); if (szCopy == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); strcpy(szCopy, szSource); } void CHardwareTestProvider::CopyBinaryData ( LPBYTE &rgb, UINT cbSource, const BYTE *rgbSource ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::CopyBinaryData"); rgb = (BYTE *) CoTaskMemAlloc(cbSource); if (rgb == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); memcpy(rgb, rgbSource, cbSource); } STDMETHODIMP CHardwareTestProvider::GetTargetLuns ( IN LONG lLunCount, IN VSS_PWSZ *rgwszDevices, IN VDS_LUN_INFORMATION *rgSourceLuns, IN OUT VDS_LUN_INFORMATION *rgDestinationLuns ) { UNREFERENCED_PARAMETER(rgwszDevices); CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::GetTargetLuns"); CVssSafeAutomaticLock lock(m_cs); try { memset(rgDestinationLuns, 0, lLunCount * sizeof(VDS_LUN_INFORMATION)); for(LONG iLun = 0; iLun < lLunCount; iLun++) { VDS_LUN_INFORMATION *pLunInfo = NULL; for(DWORD iDisk = 0; iDisk < m_cDiskIds; iDisk++) { if (IsMatchLun(*m_rgpSourceLuns[iDisk], rgSourceLuns[iLun])) pLunInfo = m_rgpDestinationLuns[iDisk]; } if (pLunInfo == NULL) ft.Throw(VSSDBG_VSSTEST, E_UNEXPECTED, L"Can't find source lun"); VDS_LUN_INFORMATION *pDestLun = &rgDestinationLuns[iLun]; VDS_LUN_INFORMATION *pSourceLun = &rgSourceLuns[iLun]; pDestLun->m_BusType = pLunInfo->m_BusType; pDestLun->m_DeviceType = pLunInfo->m_DeviceType; pDestLun->m_DeviceTypeModifier = pLunInfo->m_DeviceTypeModifier; pDestLun->m_bCommandQueueing = pLunInfo->m_bCommandQueueing; pDestLun->m_diskSignature = pLunInfo->m_diskSignature; CopyString(pDestLun->m_szVendorId, pLunInfo->m_szVendorId); CopyString(pDestLun->m_szProductId, pLunInfo->m_szProductId); CopyString(pDestLun->m_szProductRevision, pLunInfo->m_szProductRevision); CopyString(pDestLun->m_szSerialNumber, pLunInfo->m_szSerialNumber); ULONG cIds = pLunInfo->m_deviceIdDescriptor.m_cIdentifiers; pDestLun->m_deviceIdDescriptor.m_version = pLunInfo->m_deviceIdDescriptor.m_version; pDestLun->m_deviceIdDescriptor.m_cIdentifiers = cIds; pDestLun->m_deviceIdDescriptor.m_rgIdentifiers = (VDS_STORAGE_IDENTIFIER *) CoTaskMemAlloc(cIds * sizeof(VDS_STORAGE_DEVICE_ID_DESCRIPTOR)); memset(pDestLun->m_deviceIdDescriptor.m_rgIdentifiers, 0, cIds * sizeof(VDS_STORAGE_DEVICE_ID_DESCRIPTOR)); VDS_STORAGE_IDENTIFIER *pSourceId = pLunInfo->m_deviceIdDescriptor.m_rgIdentifiers; VDS_STORAGE_IDENTIFIER *pDestId = pDestLun->m_deviceIdDescriptor.m_rgIdentifiers; for(ULONG iId = 0; iId < cIds; iId++, pSourceId++, pDestId++) { memcpy(pDestId, pSourceId, FIELD_OFFSET(VDS_STORAGE_IDENTIFIER, m_rgbIdentifier)); CopyBinaryData(pDestId->m_rgbIdentifier, pSourceId->m_cbIdentifier, pSourceId->m_rgbIdentifier); } pDestLun->m_cInterconnects = 1; pDestLun->m_rgInterconnects = (VDS_INTERCONNECT *) CoTaskMemAlloc(sizeof(VDS_INTERCONNECT)); memset(pDestLun->m_rgInterconnects, 0, sizeof(VDS_INTERCONNECT)); VDS_INTERCONNECT *pDestInterconnect = pDestLun->m_rgInterconnects; VDS_INTERCONNECT *pSourceInterconnect = pSourceLun->m_rgInterconnects; BS_ASSERT(((*(ULONG *) (pSourceInterconnect->m_pbAddress)) & 0x80000000) != 0) pDestInterconnect->m_addressType = VDS_IA_FCPH; pDestInterconnect->m_pbAddress = (BYTE *) CoTaskMemAlloc(sizeof(ULONG)); if (pDestInterconnect->m_pbAddress == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); pDestInterconnect->m_cbAddress = sizeof(ULONG); *(ULONG *) (pDestInterconnect->m_pbAddress) = iDisk; pDestInterconnect->m_pbPort = (BYTE *) CoTaskMemAlloc(sizeof(ULONG)); if (pDestInterconnect->m_pbPort == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Out of memory."); *(ULONGLONG *) (pDestInterconnect->m_pbPort) = 0x9364321; pDestInterconnect->m_cbPort = sizeof(ULONG); } } VSS_STANDARD_CATCH(ft) if (ft.HrFailed()) FreeLunInfo(rgDestinationLuns, lLunCount); return ft.hr; } STDMETHODIMP CHardwareTestProvider::LocateLuns ( IN LONG lLunCount, IN VDS_LUN_INFORMATION *rgSourceLuns ) { UNREFERENCED_PARAMETER(lLunCount); UNREFERENCED_PARAMETER(rgSourceLuns); CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::LocateLuns"); CVssSafeAutomaticLock lock(m_cs); m_bRebuilt = false; try { CVssAutoWin32Handle hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, L"Global\\VSNAP_START_IMPORT"); if (hEvent == NULL) { ft.hr = HRESULT_FROM_WIN32(GetLastError()); ft.CheckForError(VSSDBG_COORD, L"CreateEvent"); } CVssAutoWin32Handle hEventComplete = OpenEvent(EVENT_ALL_ACCESS, FALSE, L"Global\\VSNAP_START_IMPORT_COMPLETED"); if (hEventComplete == NULL) { ft.hr = HRESULT_FROM_WIN32(GetLastError()); ft.CheckForError(VSSDBG_COORD, L"CreateEvent"); } if (!SetEvent(hEvent)) { ft.hr = HRESULT_FROM_WIN32(GetLastError()); ft.CheckForError(VSSDBG_COORD, L"SetEvent"); } if (WaitForSingleObject(hEventComplete, INFINITE) == WAIT_FAILED) { ft.hr = HRESULT_FROM_WIN32(GetLastError()); ft.CheckForError(VSSDBG_COORD, L"WaitForSingleObject"); } } VSS_STANDARD_CATCH(ft) if (ft.HrFailed()) ft.hr = VSS_E_PROVIDER_VETO; return ft.hr; } // perform a device i/o control, growing the buffer if necessary BOOL CHardwareTestProvider::DoDeviceIoControl ( IN HANDLE hDevice, // handle IN DWORD ioctl, // device ioctl to perform IN const LPBYTE pbQuery, // input buffer IN DWORD cbQuery, // size of input buffer IN OUT LPBYTE *ppbOut, // pointer to output buffer IN OUT DWORD *pcbOut // pointer to size of output buffer ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::DoDeviceIoControl"); // loop in case buffer is too small for query result. while(TRUE) { DWORD dwSize; if (*ppbOut == NULL) { // allocate buffer for result of query *ppbOut = new BYTE[*pcbOut]; if (*ppbOut == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Couldn't allocate query results buffer"); } // do query if (!DeviceIoControl ( hDevice, ioctl, pbQuery, cbQuery, *ppbOut, *pcbOut, &dwSize, NULL )) { // query failed DWORD dwErr = GetLastError(); if (dwErr == ERROR_INVALID_FUNCTION || dwErr == ERROR_NOT_SUPPORTED || dwErr == ERROR_NOT_READY) return FALSE; if (dwErr == ERROR_INSUFFICIENT_BUFFER || dwErr == ERROR_MORE_DATA) { // buffer wasn't big enough allocate a new // buffer of the specified return size delete *ppbOut; *ppbOut = NULL; *pcbOut *= 2; continue; } // all other errors are remapped (and potentially logged) ft.hr = HRESULT_FROM_WIN32(dwErr); ft.CheckForError(VSSDBG_VSSTEST, L"DeviceIoControl %d"); } break; } return TRUE; } bool CHardwareTestProvider::BuildLunInfoFromDrive ( IN HANDLE hDrive, OUT VDS_LUN_INFORMATION **ppLun, OUT DWORD &cPartitions ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::BuildLunInfoFromDrive"); LPBYTE bufQuery = NULL; VDS_LUN_INFORMATION *pLun; try { BOOL b; // allocate lun information pLun = (VDS_LUN_INFORMATION *) CoTaskMemAlloc(sizeof(VDS_LUN_INFORMATION)); if (pLun == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Cannot allocate LUN information array"); // clear lun information in case we throw memset(pLun, 0, sizeof(VDS_LUN_INFORMATION)); // query to get STORAGE_DEVICE_OBJECT STORAGE_PROPERTY_QUERY query; DWORD cbQuery = 1024; query.PropertyId = StorageDeviceProperty; query.QueryType = PropertyStandardQuery; b = DoDeviceIoControl ( hDrive, IOCTL_STORAGE_QUERY_PROPERTY, (LPBYTE) &query, sizeof(query), (LPBYTE *) &bufQuery, &cbQuery ); if (!b) { delete bufQuery; CoTaskMemFree(pLun); return false; } // coerce to STORAGE_DEVICE_DESCRIPTOR STORAGE_DEVICE_DESCRIPTOR *pDesc = (STORAGE_DEVICE_DESCRIPTOR *) bufQuery; pLun->m_version = VER_VDS_LUN_INFORMATION; pLun->m_DeviceType = pDesc->DeviceType; pLun->m_DeviceTypeModifier = pDesc->DeviceTypeModifier; pLun->m_bCommandQueueing = pDesc->CommandQueueing; // copy bus type pLun->m_BusType = (VDS_STORAGE_BUS_TYPE) pDesc->BusType; // copy in various strings if (pDesc->VendorIdOffset) CopySDString(&pLun->m_szVendorId, pDesc, pDesc->VendorIdOffset); if (pDesc->ProductIdOffset) CopySDString(&pLun->m_szProductId, pDesc, pDesc->ProductIdOffset); if (pDesc->ProductRevisionOffset) CopySDString(&pLun->m_szProductRevision, pDesc, pDesc->ProductRevisionOffset); if (pDesc->SerialNumberOffset) CopySDString(&pLun->m_szSerialNumber, pDesc, pDesc->SerialNumberOffset); // query for STORAGE_DEVICE_ID_DESCRIPTOR query.PropertyId = StorageDeviceIdProperty; query.QueryType = PropertyStandardQuery; if (DoDeviceIoControl ( hDrive, IOCTL_STORAGE_QUERY_PROPERTY, (LPBYTE) &query, sizeof(query), (LPBYTE *) &bufQuery, &cbQuery )) { // coerce buffer to STORAGE_DEVICE_ID_DESCRIPTOR STORAGE_DEVICE_ID_DESCRIPTOR *pDevId = (STORAGE_DEVICE_ID_DESCRIPTOR *) bufQuery; CopyStorageDeviceIdDescriptorToLun(pDevId, pLun); } if (DoDeviceIoControl ( hDrive, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, NULL, 0, (LPBYTE *) &bufQuery, &cbQuery )) { // compute signature from layout DRIVE_LAYOUT_INFORMATION_EX *pLayout = (DRIVE_LAYOUT_INFORMATION_EX *) bufQuery; VSS_ID signature = GUID_NULL; cPartitions = pLayout->PartitionCount; switch(pLayout->PartitionStyle) { default: BS_ASSERT(FALSE); break; case PARTITION_STYLE_RAW: break; case PARTITION_STYLE_GPT: // use GPT DiskId as signature signature = pLayout->Gpt.DiskId; break; case PARTITION_STYLE_MBR: // use 32 bit Mbr signature as high part of guid. Remainder // of guid is 0. signature.Data1 = pLayout->Mbr.Signature; break; } // save disk signature pLun->m_diskSignature = signature; } } VSS_STANDARD_CATCH(ft) delete bufQuery; if (ft.HrFailed()) { FreeLunInfo(pLun, 1); ft.Throw(VSSDBG_VSSTEST, ft.hr, L"Rethrowing"); } *ppLun = pLun; return TRUE; } STDMETHODIMP CHardwareTestProvider::OnLunEmpty ( IN VSS_PWSZ wszDevice, IN VDS_LUN_INFORMATION *pInfo ) { UNREFERENCED_PARAMETER(wszDevice); CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::OnLunEmpty"); CVssSafeAutomaticLock lock(m_cs); try { for(DWORD iDisk = 0; iDisk < m_cDiskIds; iDisk++) { if (IsMatchLun(*(m_rgpDestinationLuns[iDisk]), *pInfo)) break; } if (iDisk == m_cDiskIds) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"Cannot locate lun"); // reexpose partitions after lun is freed so we see something change DWORD diskId; bool bIsDynamic; if (TranslateDisk(m_rgDestinationDiskIds[iDisk], diskId, bIsDynamic)) { if (bIsDynamic) HideAndExposeDynamicVolumes(m_rgDestinationDiskIds[iDisk], false, true); else HideAndExposePartitions(diskId, m_rgcDestinationPartitions[iDisk], false, true); } AddFreedLun(wszDevice); } VSS_STANDARD_CATCH(ft) return ft.hr; } // IVssProviderCreateSnapshotSet interface STDMETHODIMP CHardwareTestProvider::EndPrepareSnapshots ( IN VSS_ID SnapshotSetId ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::EndPrepareSnapshots"); try { if (SnapshotSetId != m_SnapshotSetId) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"snapshot set mismatch"); } VSS_STANDARD_CATCH(ft) return ft.hr; } STDMETHODIMP CHardwareTestProvider::PreCommitSnapshots ( IN VSS_ID SnapshotSetId ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::PreCommitSnapshots"); CVssSafeAutomaticLock lock(m_cs); try { if (SnapshotSetId != m_SnapshotSetId) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"snapshot set mismatch"); } VSS_STANDARD_CATCH(ft) return ft.hr; } STDMETHODIMP CHardwareTestProvider::PreFinalCommitSnapshots ( IN VSS_ID SnapshotSetId ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::PreFinalCommitSnapshots"); CVssSafeAutomaticLock lock(m_cs); try { if (SnapshotSetId != m_SnapshotSetId) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"snapshot set mismatch"); } VSS_STANDARD_CATCH(ft) return ft.hr; } STDMETHODIMP CHardwareTestProvider::PostFinalCommitSnapshots ( IN VSS_ID SnapshotSetId ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::PostFinalCommitSnapshots"); CVssSafeAutomaticLock lock(m_cs); try { if (SnapshotSetId != m_SnapshotSetId) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"snapshot set mismatch"); } VSS_STANDARD_CATCH(ft) return ft.hr; } STDMETHODIMP CHardwareTestProvider::CommitSnapshots ( IN VSS_ID SnapshotSetId ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::CommitSnapshots"); CVssSafeAutomaticLock lock(m_cs); try { if (SnapshotSetId != m_SnapshotSetId) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"snapshot set mismatch"); m_bHidden = true; LONG mask = 1; for(UINT Disk = 0; mask != 0; mask = mask << 1, Disk++) { if ((m_maskSnapshotDisks & mask) != 0) { DWORD diskId; bool bIsDynamic; if (!TranslateDisk(m_rgDestinationDiskIds[Disk], diskId, bIsDynamic)) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"Unexpected error"); if (bIsDynamic) HideAndExposeDynamicVolumes(m_rgDestinationDiskIds[Disk], true, false); else HideAndExposePartitions(diskId, m_rgcDestinationPartitions[Disk], true, false); } } } VSS_STANDARD_CATCH(ft) return ft.hr; } STDMETHODIMP CHardwareTestProvider::PostCommitSnapshots ( IN VSS_ID SnapshotSetId, IN LONG lSnapshotsCount ) { UNREFERENCED_PARAMETER(lSnapshotsCount); CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::PostCommitSnapshots"); CVssSafeAutomaticLock lock(m_cs); try { if (SnapshotSetId != m_SnapshotSetId) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"snapshot set mismatch"); } VSS_STANDARD_CATCH(ft) m_SnapshotSetId = GUID_NULL; m_maskSnapshotDisks = 0; m_bHidden = false; return ft.hr; } STDMETHODIMP CHardwareTestProvider::AbortSnapshots ( IN VSS_ID SnapshotSetId ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::AbortSnapshots"); try { if (SnapshotSetId != m_SnapshotSetId) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"snapshot set mismatch"); if (m_bHidden) { UINT Disk = 0; for(LONG mask = 1; mask != 0; mask = mask << 1) { if ((m_maskSnapshotDisks & mask) != 0) { DWORD diskId; bool bIsDynamic; if (!TranslateDisk(m_rgDestinationDiskIds[Disk], diskId, bIsDynamic)) ft.Throw(VSSDBG_VSSTEST, VSS_E_PROVIDER_VETO, L"Unexpected error"); if (bIsDynamic) HideAndExposeDynamicVolumes(m_rgDestinationDiskIds[Disk], false, true); else HideAndExposePartitions(diskId, m_rgcDestinationPartitions[Disk], false, true); } Disk++; } } m_bHidden = false; m_SnapshotSetId = GUID_NULL; m_maskSnapshotDisks = 0; } VSS_STANDARD_CATCH(ft) return ft.hr; } bool CHardwareTestProvider::cmp_str_eq(LPCSTR sz1, LPCSTR sz2) { if (sz1 == NULL && sz2 == NULL) return true; else if (sz1 != NULL && sz2 != NULL) { while(*sz1 == *sz2 && *sz1 != '\0') { sz1++; sz2++; } if (*sz1 == *sz2) return true; if (*sz1 == '\0' && *sz2 == ' ') { while(*sz2 != '\0') { if (*sz2 != ' ') return false; sz2++; } return true; } else if (*sz1 == ' ' && *sz2 == ' ') { while(*sz1 != '\0') { if (*sz1 != ' ') return false; sz1++; } return true; } return false; } else return false; } // determine if two VDS_LUN_INFORMATION structures match bool CHardwareTestProvider::IsMatchLun ( const VDS_LUN_INFORMATION &info1, const VDS_LUN_INFORMATION &info2 ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::IsMatchLun"); if (info1.m_DeviceType != info2.m_DeviceType) return false; if (info1.m_DeviceTypeModifier != info2.m_DeviceTypeModifier) return false; if (info1.m_BusType != info2.m_BusType) return false; if (!cmp_str_eq(info1.m_szSerialNumber, info2.m_szSerialNumber)) return false; if (!cmp_str_eq(info1.m_szVendorId, info2.m_szVendorId)) return false; if (!cmp_str_eq(info1.m_szProductId, info2.m_szProductId)) return false; if (!cmp_str_eq(info1.m_szProductRevision, info2.m_szProductRevision)) return false; if (info1.m_diskSignature != info2.m_diskSignature) return false; if (!IsMatchDeviceIdDescriptor(info1.m_deviceIdDescriptor, info2.m_deviceIdDescriptor)) return false; return true; } // make sure that the storage device id descriptors match bool CHardwareTestProvider::IsMatchDeviceIdDescriptor ( IN const VDS_STORAGE_DEVICE_ID_DESCRIPTOR &desc1, IN const VDS_STORAGE_DEVICE_ID_DESCRIPTOR &desc2 ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::IsMatchDeviceIdDescriptor"); VDS_STORAGE_IDENTIFIER *pId1 = desc1.m_rgIdentifiers; VDS_STORAGE_IDENTIFIER *rgId2 = desc2.m_rgIdentifiers; for(ULONG iIdentifier = 0; iIdentifier < desc1.m_cIdentifiers; iIdentifier++, pId1++) { if (IsConflictingIdentifier(pId1, rgId2, desc2.m_cIdentifiers)) return false; } return true; } // determine if there is a conflicting identifier in an array of storage // identifiers bool CHardwareTestProvider::IsConflictingIdentifier ( IN const VDS_STORAGE_IDENTIFIER *pId1, IN const VDS_STORAGE_IDENTIFIER *rgId2, IN ULONG cId2 ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::IsConflictingIdentifier"); const VDS_STORAGE_IDENTIFIER *pId2 = rgId2; for(UINT iid = 0; iid < cId2; iid++) { if (pId1->m_Type == pId2->m_Type) { if (pId1->m_CodeSet != pId2->m_CodeSet || pId1->m_cbIdentifier != pId2->m_cbIdentifier || memcmp(pId1->m_rgbIdentifier, pId2->m_rgbIdentifier, pId1->m_cbIdentifier) != 0) return true; } } return false; } // copy a string from a STORAGE_DEVICE_DESCRIPTOR. It is returned as a // CoTaskAllocated string. void CHardwareTestProvider::CopySDString ( LPSTR *ppszNew, STORAGE_DEVICE_DESCRIPTOR *pdesc, DWORD offset ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::CopySDString"); // point to start of string LPSTR szId = (LPSTR)((BYTE *) pdesc + offset); UINT cwc = (UINT) strlen(szId); while(cwc > 0 && szId[cwc-1] == ' ') cwc--; if (cwc == 0) *ppszNew = NULL; else { // allocate string *ppszNew = (LPSTR) CoTaskMemAlloc(cwc + 1); if (*ppszNew == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Cannot allocate string."); // copy value into string memcpy(*ppszNew, szId, cwc); (*ppszNew)[cwc] = L'\0'; } } void CHardwareTestProvider::HideAndExposePartitions ( UINT DiskNo, DWORD cPartitions, bool fHide, bool fExpose ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::HideAndExposePartitions"); HANDLE rgh[256]; BS_ASSERT(cPartitions < 256); for(UINT i = 0; i < cPartitions; i++) rgh[i] = INVALID_HANDLE_VALUE; try { WCHAR volName[128]; for(UINT i = 0; i < cPartitions; i++) { swprintf ( volName, L"\\\\?\\GlobalRoot\\Device\\Harddisk%d\\Partition%d", DiskNo, i ); rgh[i] = CreateFile ( volName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (rgh[i] == INVALID_HANDLE_VALUE) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_FILE_NOT_FOUND || dwErr == ERROR_PATH_NOT_FOUND) continue; ft.hr = HRESULT_FROM_WIN32(dwErr); ft.CheckForError(VSSDBG_VSSTEST, L"CreateFile(VOLUME)"); } } DoHideAndExpose(rgh, cPartitions, fHide, fExpose); } VSS_STANDARD_CATCH(ft) for(i = 0; i < cPartitions; i++) { if (rgh[i] != INVALID_HANDLE_VALUE) CloseHandle(rgh[i]); } } void CHardwareTestProvider::HideAndExposeDynamicVolumes ( DWORD signature, bool fHide, bool fExpose ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::HideAndExposeDynamicVolumes"); HANDLE rgh[256]; for(UINT i = 0; i < 256; i++) rgh[i] = INVALID_HANDLE_VALUE; UINT cVolumes = 0; try { DYNAMIC_DISK_INFO *pInfo = m_pDynamicDiskInfo; while(pInfo) { if (pInfo->m_signature == signature) break; pInfo = pInfo->m_next; } // if no information is found, then all volumes on the // disk are already hidden if (!pInfo) return; LPCWSTR wszVolumes = pInfo->m_wszVolumes; while(*wszVolumes) { BS_ASSERT(cVolumes < 256); rgh[cVolumes] = CreateFile ( wszVolumes, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (rgh[cVolumes] == INVALID_HANDLE_VALUE) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_FILE_NOT_FOUND || dwErr == ERROR_PATH_NOT_FOUND) { wszVolumes += wcslen(wszVolumes) + 1; continue; } ft.hr = HRESULT_FROM_WIN32(dwErr); ft.CheckForError(VSSDBG_VSSTEST, L"CreateFile(VOLUME)"); } wszVolumes += wcslen(wszVolumes) + 1; cVolumes++; } DoHideAndExpose(rgh, cVolumes, fHide, fExpose); } VSS_STANDARD_CATCH(ft) for(i = 0; i < cVolumes; i++) { if (rgh[i] != INVALID_HANDLE_VALUE) CloseHandle(rgh[i]); } } void CHardwareTestProvider::DoHideAndExpose ( HANDLE *rgh, UINT cHandles, bool fHide, bool fExpose ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::DoHideAndExpose"); DWORD size; VOLUME_GET_GPT_ATTRIBUTES_INFORMATION getAttributesInfo; for(UINT i = 0; i < cHandles; i++) { if (!DeviceIoControl ( rgh[i], IOCTL_VOLUME_GET_GPT_ATTRIBUTES, NULL, 0, &getAttributesInfo, sizeof(getAttributesInfo), &size, NULL )) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_INVALID_FUNCTION) continue; ft.hr = HRESULT_FROM_WIN32(dwErr); ft.CheckForError(VSSDBG_VSSTEST, L"DeviceIoControl(IOCTL_VOLUME_GET_GPT_ATTRIBUTES)"); } if (fHide && (getAttributesInfo.GptAttributes & GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY) == 0) { // dismount volume before seting read-only bits if (!DeviceIoControl ( rgh[i], FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &size, NULL )) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_INVALID_FUNCTION) continue; ft.hr = HRESULT_FROM_WIN32(dwErr); ft.CheckForError(VSSDBG_VSSTEST, L"DeviceIoControl(IOCTL_VOLUME_SET_GPT_ATTRIBUTES)"); } } } for(i = 0; i < cHandles; i++) { if (rgh[i] != INVALID_HANDLE_VALUE) { DWORD size; VOLUME_GET_GPT_ATTRIBUTES_INFORMATION getAttributesInfo; VOLUME_SET_GPT_ATTRIBUTES_INFORMATION setAttributesInfo; if (!DeviceIoControl ( rgh[i], IOCTL_VOLUME_GET_GPT_ATTRIBUTES, NULL, 0, &getAttributesInfo, sizeof(getAttributesInfo), &size, NULL )) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_INVALID_FUNCTION) continue; ft.hr = HRESULT_FROM_WIN32(dwErr); ft.CheckForError(VSSDBG_VSSTEST, L"DeviceIoControl(IOCTL_VOLUME_GET_GPT_ATTRIBUTES)"); } memset(&setAttributesInfo, 0, sizeof(setAttributesInfo)); setAttributesInfo.GptAttributes = getAttributesInfo.GptAttributes; setAttributesInfo.ApplyToAllConnectedVolumes = TRUE; if (fHide) { setAttributesInfo.GptAttributes |= GPT_BASIC_DATA_ATTRIBUTE_HIDDEN|GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY|GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER; if (!DeviceIoControl ( rgh[i], IOCTL_VOLUME_SET_GPT_ATTRIBUTES, &setAttributesInfo, sizeof(setAttributesInfo), NULL, 0, &size, NULL )) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_INVALID_FUNCTION) continue; ft.hr = HRESULT_FROM_WIN32(dwErr); ft.CheckForError(VSSDBG_VSSTEST, L"DeviceIoControl(IOCTL_VOLUME_SET_GPT_ATTRIBUTES)"); } } if (fExpose) { setAttributesInfo.GptAttributes &= ~GPT_BASIC_DATA_ATTRIBUTE_HIDDEN; if (!DeviceIoControl ( rgh[i], IOCTL_VOLUME_SET_GPT_ATTRIBUTES, &setAttributesInfo, sizeof(setAttributesInfo), NULL, 0, &size, NULL )) { ft.hr = HRESULT_FROM_WIN32(GetLastError()); ft.CheckForError(VSSDBG_VSSTEST, L"DeviceIoControl(IOCTL_VOLUME_SET_GPT_ATTRIBUTES)"); } } } } } // copy a storage device id descriptor to the VDS_LUN_INFORMATION structure. // note that lun is modified whether an execption occurs or not. FreeLunInfo // will free up any data allocated here. void CHardwareTestProvider::CopyStorageDeviceIdDescriptorToLun ( IN STORAGE_DEVICE_ID_DESCRIPTOR *pDevId, IN VDS_LUN_INFORMATION *pLun ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::CopyStorageDeviceIdDescriptorToLun"); BS_ASSERT(StorageIdTypeVendorSpecific == VDSStorageIdTypeVendorSpecific); BS_ASSERT(StorageIdTypeVendorId == VDSStorageIdTypeVendorId); BS_ASSERT(StorageIdTypeEUI64 == VDSStorageIdTypeEUI64); BS_ASSERT(StorageIdTypeFCPHName == VDSStorageIdTypeFCPHName); BS_ASSERT(StorageIdCodeSetAscii == VDSStorageIdCodeSetAscii); BS_ASSERT(StorageIdCodeSetBinary == VDSStorageIdCodeSetBinary); // get count of ids DWORD cIds = pDevId->NumberOfIdentifiers; // copy over version number and count of ids pLun->m_deviceIdDescriptor.m_version = pDevId->Version; pLun->m_deviceIdDescriptor.m_cIdentifiers = cIds; // allocate array of identifiers pLun->m_deviceIdDescriptor.m_rgIdentifiers = (VDS_STORAGE_IDENTIFIER *) CoTaskMemAlloc(sizeof(VDS_STORAGE_IDENTIFIER) * cIds); if (pLun->m_deviceIdDescriptor.m_rgIdentifiers == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Cannot allocate device id descriptors"); // clear descriptor. If we throw, we want to make sure that all pointers // are null memset(pLun->m_deviceIdDescriptor.m_rgIdentifiers, 0, sizeof(VDS_STORAGE_IDENTIFIER) * cIds); // get pointer to first identifier in both STORAGE_DEVICE_ID_DESCRIPTOR and // VDS_STORAGE_DEVICE_ID_DESCRIPTOR STORAGE_IDENTIFIER *pId = (STORAGE_IDENTIFIER *) pDevId->Identifiers; VDS_STORAGE_IDENTIFIER *pvsi = (VDS_STORAGE_IDENTIFIER *) pLun->m_deviceIdDescriptor.m_rgIdentifiers; for(UINT i = 0; i < cIds; i++) { // copy over size of identifier pvsi->m_cbIdentifier = pId->IdentifierSize; // allocate space for identifier pvsi->m_rgbIdentifier = (BYTE *) CoTaskMemAlloc(pvsi->m_cbIdentifier); if (pvsi->m_rgbIdentifier == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Cannot allocate storage identifier"); // copy type and code set over pvsi->m_Type = (VDS_STORAGE_IDENTIFIER_TYPE) pId->Type; pvsi->m_CodeSet = (VDS_STORAGE_IDENTIFIER_CODE_SET) pId->CodeSet; // copy identifier memcpy(pvsi->m_rgbIdentifier, pId->Identifier, pvsi->m_cbIdentifier); // move to next identifier pId = (STORAGE_IDENTIFIER *) ((BYTE *) pId + pId->NextOffset); pvsi++; } } void CHardwareTestProvider::RebuildLunInfo() { for(DWORD iDisk = 0; iDisk < m_cDiskIds; iDisk++) { DWORD diskId; bool bIsDynamic; if (m_rgpSourceLuns[iDisk] == NULL && TranslateDisk(m_rgSourceDiskIds[iDisk], diskId, bIsDynamic)) BuildLunInfoForDisk(diskId, &m_rgpSourceLuns[iDisk], &m_rgcSourcePartitions[iDisk]); if (m_rgpDestinationLuns[iDisk] == NULL && TranslateDisk(m_rgDestinationDiskIds[iDisk], diskId, bIsDynamic)) BuildLunInfoForDisk(diskId, &m_rgpDestinationLuns[iDisk], &m_rgcDestinationPartitions[iDisk]); } } DWORD hexconvert(LPCWSTR wsz) { DWORD dwRet = 0; while (*wsz != L'\0') { dwRet *= 16; if (*wsz >= L'0' && *wsz <= L'9') dwRet += *wsz - L'0'; else if (*wsz >= L'a' && *wsz <= L'f') dwRet += *wsz - L'a' + 10; else if (*wsz >= L'A' && *wsz <= L'F') dwRet += *wsz - L'A' + 10; wsz++; } return dwRet; } void CHardwareTestProvider::LoadConfigurationData() { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::LoadConfigurationData"); VSS_PWSZ wszSourceDisks = NULL; VSS_PWSZ wszDestinationDisks = NULL; m_cDiskIds = 0; try { CVssRegistryKey key; key.Open(HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Services\\HardwareTestProvider"); key.GetValue(L"SourceDisks", wszSourceDisks); key.GetValue(L"DestinationDisks", wszDestinationDisks); LPWSTR wszSource = wszSourceDisks; LPWSTR wszDestination = wszDestinationDisks; if (wszSource != NULL && wszDestination != NULL) { while(*wszSource != L'\0' && *wszDestination != L'\0') { WCHAR *wszSourceNext = wcschr(wszSource, L','); WCHAR *wszDestinationNext = wcschr(wszDestination, L','); if (wszSourceNext != NULL) *wszSourceNext = L'\0'; if (wszDestinationNext != NULL) *wszDestinationNext = L'\0'; int Source = hexconvert(wszSource); int Destination = hexconvert(wszDestination); m_rgSourceDiskIds[m_cDiskIds] = Source; m_rgDestinationDiskIds[m_cDiskIds] = Destination; m_cDiskIds++; if (m_cDiskIds == 32) break; if (wszSourceNext == NULL || wszDestinationNext == NULL) break; wszSource = wszSourceNext + 1; wszDestination = wszDestinationNext + 1; } } RebuildSignatures(); m_bRebuilt = true; RebuildLunInfo(); } VSS_STANDARD_CATCH(ft) if (ft.HrFailed()) ClearConfiguration(); if (wszSourceDisks) CoTaskMemFree(wszSourceDisks); if (wszDestinationDisks) CoTaskMemFree(wszDestinationDisks); } void CHardwareTestProvider::BuildLunInfoForDisk ( IN DWORD Drive, OUT VDS_LUN_INFORMATION **ppLunInfo, OUT DWORD *pcPartitions ) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::BuildLunInfoForDisk"); WCHAR wszbuf[32]; swprintf(wszbuf, L"\\\\.\\PHYSICALDRIVE%u", Drive); CVssAutoWin32Handle hDisk = CreateFile ( wszbuf, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if (hDisk != INVALID_HANDLE_VALUE) BuildLunInfoFromDrive(hDisk, ppLunInfo, *pcPartitions); } void CHardwareTestProvider::ClearConfiguration() { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::ClearConfiguration"); for(DWORD i = 0; i < m_cDiskIds; i++) { if (m_rgpSourceLuns[i] != NULL) { FreeLunInfo(m_rgpSourceLuns[i], 1); m_rgpSourceLuns[i] = NULL; } if (m_rgpDestinationLuns[i] != NULL) { FreeLunInfo(m_rgpDestinationLuns[i], 1); m_rgpDestinationLuns[i] = NULL; } } m_cDiskIds = 0; } // add a lun to a file indicating the luns that were freed void CHardwareTestProvider::AddFreedLun(LPCWSTR wsz) { DWORD Drive; swscanf(wsz, L"\\\\.\\PHYSICALDRIVE%u", &Drive); WCHAR buf[MAX_PATH * 2]; if (!GetSystemDirectory(buf, sizeof(buf)/sizeof(WCHAR))) { wprintf(L"GetSystemDirectory failed due to error %d.\n", GetLastError()); throw E_UNEXPECTED; } wcscat(buf, L"\\VSNAP_DELETED_LUNS"); HANDLE h = CreateFile ( buf, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL ); if (h == INVALID_HANDLE_VALUE) return; if (SetFilePointer(h, 0, NULL, FILE_END) != 0xffffffff) { DWORD dwWritten; WriteFile(h, &Drive, sizeof(DWORD), &dwWritten, NULL); } CloseHandle(h); } bool CHardwareTestProvider::TranslateDisk(DWORD signature, DWORD &DiskId, bool &bIsDynamic) { while(TRUE) { for(UINT iDisk = 0; iDisk < MAXDISKS; iDisk++) { if (m_rgDiskSignatures[iDisk] == signature) { if (GetDiskSignature(iDisk, bIsDynamic) != signature) break; DiskId = iDisk; return true; } } // rebuild signatures if we haven't done so already if (m_bRebuilt) break; RebuildSignatures(); m_bRebuilt = true; } return false; } DWORD CHardwareTestProvider::GetDiskSignature(DWORD iDisk, bool &bIsDynamic) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::GetDiskSignature"); LPBYTE buf = NULL; DWORD cbOut = 1024; bIsDynamic = false; WCHAR wszBuf[64]; swprintf(wszBuf, L"\\\\.\\PHYSICALDRIVE%u", iDisk); CVssAutoWin32Handle hDisk = CreateFile ( wszBuf, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if (hDisk == INVALID_HANDLE_VALUE) return 0; if (!DoDeviceIoControl ( hDisk, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, NULL, 0, &buf, &cbOut )) return 0; DRIVE_LAYOUT_INFORMATION_EX *pLayout = (DRIVE_LAYOUT_INFORMATION_EX *) buf; ULONG cPartitions = pLayout->PartitionCount; for(ULONG iPartition = 0; iPartition < cPartitions; iPartition++) { if (pLayout->PartitionEntry[iPartition].Mbr.PartitionType == PARTITION_LDM) bIsDynamic = true; } if (pLayout->PartitionStyle == PARTITION_STYLE_MBR) return pLayout->Mbr.Signature; else return 0; } void CHardwareTestProvider::RebuildSignatures() { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::RebuildSignatures"); for(UINT iDisk = 0; iDisk < MAXDISKS; iDisk++) { bool bIsDynamic; m_rgDiskSignatures[iDisk] = GetDiskSignature(iDisk, bIsDynamic); if (bIsDynamic) AddDynamicDiskInfo(m_rgDiskSignatures[iDisk], iDisk); } } void CHardwareTestProvider::AddDynamicDiskInfo(DWORD signature, DWORD disk) { CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CHardwareTestProvider::AddDynamicDiskInfo"); DYNAMIC_DISK_INFO *pInfo = m_pDynamicDiskInfo; while(pInfo != NULL) { if (pInfo->m_signature == signature) break; pInfo = pInfo->m_next; } // dynamic volumes already found, do nothing if (pInfo) return; LPBYTE bufExtents = NULL; DWORD cbBufExtents = 1024; LPWSTR buf = new WCHAR[8192]; if (buf == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Cannot allocate string"); LPWSTR wszVolumes = new WCHAR[256]; if (wszVolumes == NULL) { delete buf; ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Cannot allocate string"); } wszVolumes[0] = L'\0'; UINT cwcVolumes = 256; UINT iwcVolumes = 0; HANDLE hFind = FindFirstVolume(buf, 8192); try { if (hFind == INVALID_HANDLE_VALUE) { ft.hr = HRESULT_FROM_WIN32(GetLastError()); ft.CheckForError(VSSDBG_VSSTEST, L"FindVolume"); } while(TRUE) { // get rid of trailing backslash buf[wcslen(buf) - 1] = L'\0'; CVssAutoWin32Handle hVol = CreateFile ( buf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); DWORD dwErr = GetLastError(); if (hVol != INVALID_HANDLE_VALUE) { if (DoDeviceIoControl ( hVol, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &bufExtents, &cbBufExtents )) { VOLUME_DISK_EXTENTS *pDiskExtents = (VOLUME_DISK_EXTENTS *) bufExtents; DWORD cExtents = pDiskExtents->NumberOfDiskExtents; for(DWORD iExtent = 0; iExtent < cExtents; iExtent++) { if (pDiskExtents->Extents[iExtent].DiskNumber == disk) { UINT cwc = (UINT) wcslen(buf) + 1; if (cwc + iwcVolumes + 1 > cwcVolumes) { LPWSTR wszNew = new WCHAR[cwc + iwcVolumes + 256]; if (wszNew == NULL) ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"cannot grow string"); wcscpy(wszNew, wszVolumes); delete wszVolumes; wszNew = wszVolumes; cwcVolumes = iwcVolumes + cwc + 256; } wcscpy(wszVolumes + iwcVolumes, buf); iwcVolumes += cwc; // double null terminate MULTI_SZ string wszVolumes[iwcVolumes + 1] = L'\0'; break; } } } } if (!FindNextVolume(hFind, buf, 8192)) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_NO_MORE_FILES) break; ft.hr = HRESULT_FROM_WIN32(dwErr); ft.CheckForError(VSSDBG_VSSTEST, L"FindNextVolume"); } } } catch(...) { delete bufExtents; delete buf; delete wszVolumes; FindVolumeClose(hFind); throw; } delete bufExtents; delete buf; FindVolumeClose(hFind); if (wcslen(wszVolumes) == 0) delete wszVolumes; else { DYNAMIC_DISK_INFO *pInfo = new DYNAMIC_DISK_INFO; if (pInfo == NULL) { delete wszVolumes; ft.Throw(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"cannot allocate DYNAMIC_DISK_INFO"); } pInfo->m_signature = signature; pInfo->m_wszVolumes = wszVolumes; pInfo->m_next = m_pDynamicDiskInfo; m_pDynamicDiskInfo = pInfo; } }
#include <makeshift/experimental/type_traits.hpp> #include <gsl-lite/gsl-lite.hpp> #include <catch2/catch.hpp> namespace { namespace mk = ::makeshift; namespace gsl = ::gsl_lite; // TODO: add tests } // anonymous namespace
/** * @file print_help.cpp * @author Matthew Amidon * @author Ryan Curtin * * Print help for a given function. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include "print_help.hpp" #include <mlpack/core.hpp> #include <mlpack/core/util/hyphenate_string.hpp> namespace mlpack { namespace bindings { namespace cli { /* Prints the descriptions of the current hierarchy. */ void PrintHelp(const std::string& param) { std::string usedParam = param; const std::map<std::string, util::ParamData>& parameters = CLI::Parameters(); const std::map<char, std::string>& aliases = CLI::Aliases(); std::map<std::string, util::ParamData>::const_iterator iter; const util::ProgramDoc& docs = *CLI::GetSingleton().doc; // If we pass a single param, alias it if necessary. if (usedParam.length() == 1 && aliases.count(usedParam[0])) usedParam = aliases.at(usedParam[0]); // Do we only want to print out one value? if (usedParam != "" && parameters.count(usedParam)) { const util::ParamData& data = parameters.at(usedParam); std::string alias = (data.alias != '\0') ? " (-" + std::string(1, data.alias) + ")" : ""; // Figure out the name of the type. std::string printableType; CLI::GetSingleton().functionMap[data.tname]["StringTypeParam"](data, NULL, (void*) &printableType); std::string type = " [" + printableType + "]"; // Now, print the descriptions. std::string fullDesc = " --" + usedParam + alias + type + " "; if (fullDesc.length() <= 32) // It all fits on one line. std::cout << fullDesc << std::string(32 - fullDesc.length(), ' '); else // We need multiple lines. std::cout << fullDesc << std::endl << std::string(32, ' '); std::cout << util::HyphenateString(data.desc, 32) << std::endl; return; } else if (usedParam != "") { // User passed a single variable, but it doesn't exist. std::cerr << "Parameter --" << usedParam << " does not exist." << std::endl; exit(1); // Nothing left to do. } // Print out the descriptions. if (docs.programName != "") { std::cout << docs.programName << std::endl << std::endl; std::cout << " " << util::HyphenateString(docs.documentation(), 2) << std::endl << std::endl; } else std::cout << "[undocumented program]" << std::endl << std::endl; for (size_t pass = 0; pass < 3; ++pass) { bool printedHeader = false; // Print out the descriptions of everything else. for (iter = parameters.begin(); iter != parameters.end(); ++iter) { const util::ParamData& data = iter->second; const std::string key; CLI::GetSingleton().functionMap[data.tname]["MapParameterName"](data, NULL, (void*) &key); std::string desc = data.desc; std::string alias = (iter->second.alias != '\0') ? std::string(1, iter->second.alias) : ""; alias = alias.length() ? " (-" + alias + ")" : alias; // Filter un-printed options. if ((pass == 0) && !(data.required && data.input)) // Required input. continue; if ((pass == 1) && !(!data.required && data.input)) // Optional input. continue; if ((pass == 2) && data.input) // Output options only (always optional). continue; // For reverse compatibility: this can be removed when these options are // gone in mlpack 3.0.0. We don't want to print the deprecated options. if (data.name == "inputFile") continue; if (!printedHeader) { printedHeader = true; if (pass == 0) std::cout << "Required input options:" << std::endl << std::endl; else if (pass == 1) std::cout << "Optional input options: " << std::endl << std::endl; else if (pass == 2) std::cout << "Optional output options: " << std::endl << std::endl; } // Append default value to description. if (pass >= 1 && (data.cppType == "int" || data.cppType == "double" || data.cppType == "std::string" || data.cppType == "std::vector<int>" || data.cppType == "std::vector<double>" || data.cppType == "std::vector<std::string>")) { std::string defaultValue; CLI::GetSingleton().functionMap[data.tname]["DefaultParam"](data, NULL, (void*) &defaultValue); desc += " Default value " + defaultValue + "."; } // Now, print the descriptions. std::string printableType; CLI::GetSingleton().functionMap[data.tname]["StringTypeParam"](data, NULL, (void*) &printableType); std::string type = " [" + printableType + "]"; std::string fullDesc = " --" + key + alias + type + " "; if (fullDesc.length() <= 32) // It all fits on one line. std::cout << fullDesc << std::string(32 - fullDesc.length(), ' '); else // We need multiple lines. std::cout << fullDesc << std::endl << std::string(32, ' '); std::cout << util::HyphenateString(desc, 32) << std::endl; } if (printedHeader) std::cout << std::endl; } // Helpful information at the bottom of the help output, to point the user to // citations and better documentation (if necessary). See ticket #195. std::cout << util::HyphenateString("For further information, including " "relevant papers, citations, and theory, consult the documentation found " "at http://www.mlpack.org or included with your distribution of mlpack.", 0) << std::endl; } } // namespace cli } // namespace bindings } // namespace mlpack
//------------------------------------------------------------------------------------- // DirectXSHD3D12.cpp -- C++ Spherical Harmonics Math Library // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/p/?LinkId=262885 //------------------------------------------------------------------------------------- #pragma warning( disable : 4616 4619 4061 4265 4626 5039 ) // C4616/C4619 #pragma warning warnings // C4061 numerator 'identifier' in switch of enum 'enumeration' is not explicitly handled by a case label // C4265 class has virtual functions, but destructor is not virtual // C4626 assignment operator was implicitly defined as deleted // C5039 pointer or reference to potentially throwing function passed to extern C function under - EHc #include <d3d12.h> #include "DirectXSH.h" #include <DirectXPackedVector.h> #include <cassert> #include <memory> #include <malloc.h> #include <wrl/client.h> #ifdef __clang__ #pragma clang diagnostic ignored "-Wcovered-switch-default" #pragma clang diagnostic ignored "-Wswitch-enum" #endif using namespace DirectX; using Microsoft::WRL::ComPtr; namespace { struct aligned_deleter { void operator()(void* p) { _aligned_free(p); } }; using ScopedAlignedArrayXMVECTOR = std::unique_ptr<DirectX::XMVECTOR, aligned_deleter>; //------------------------------------------------------------------------------------- // This code is lifted from DirectXTex http://go.microsoft.com/fwlink/?LinkId=248926 // If you need additional DXGI format support, see DirectXTexConvert.cpp //------------------------------------------------------------------------------------- #define LOAD_SCANLINE( type, func )\ if ( size >= sizeof(type) )\ {\ const type * __restrict sPtr = reinterpret_cast<const type*>(pSource);\ for( size_t icount = 0; icount < ( size - sizeof(type) + 1 ); icount += sizeof(type) )\ {\ if ( dPtr >= ePtr ) break;\ *(dPtr++) = func( sPtr++ );\ }\ return true;\ }\ return false; #define LOAD_SCANLINE3( type, func, defvec )\ if ( size >= sizeof(type) )\ {\ const type * __restrict sPtr = reinterpret_cast<const type*>(pSource);\ for( size_t icount = 0; icount < ( size - sizeof(type) + 1 ); icount += sizeof(type) )\ {\ XMVECTOR v = func( sPtr++ );\ if ( dPtr >= ePtr ) break;\ *(dPtr++) = XMVectorSelect( defvec, v, g_XMSelect1110 );\ }\ return true;\ }\ return false; #define LOAD_SCANLINE2( type, func, defvec )\ if ( size >= sizeof(type) )\ {\ const type * __restrict sPtr = reinterpret_cast<const type*>(pSource);\ for( size_t icount = 0; icount < ( size - sizeof(type) + 1 ); icount += sizeof(type) )\ {\ XMVECTOR v = func( sPtr++ );\ if ( dPtr >= ePtr ) break;\ *(dPtr++) = XMVectorSelect( defvec, v, g_XMSelect1100 );\ }\ return true;\ }\ return false; #pragma warning(push) #pragma warning(disable : 6101) _Success_(return) bool _LoadScanline( _Out_writes_(count) DirectX::XMVECTOR* pDestination, size_t count, _In_reads_bytes_(size) LPCVOID pSource, size_t size, DXGI_FORMAT format) { assert(pDestination && count > 0 && ((reinterpret_cast<uintptr_t>(pDestination) & 0xF) == 0)); assert(pSource && size > 0); using namespace DirectX::PackedVector; XMVECTOR* __restrict dPtr = pDestination; if (!dPtr) return false; const XMVECTOR* ePtr = pDestination + count; switch (format) { case DXGI_FORMAT_R32G32B32A32_FLOAT: { size_t msize = (size > (sizeof(XMVECTOR)*count)) ? (sizeof(XMVECTOR)*count) : size; memcpy_s(dPtr, sizeof(XMVECTOR)*count, pSource, msize); } return true; case DXGI_FORMAT_R32G32B32_FLOAT: LOAD_SCANLINE3(XMFLOAT3, XMLoadFloat3, g_XMIdentityR3) case DXGI_FORMAT_R16G16B16A16_FLOAT: LOAD_SCANLINE(XMHALF4, XMLoadHalf4) case DXGI_FORMAT_R32G32_FLOAT: LOAD_SCANLINE2(XMFLOAT2, XMLoadFloat2, g_XMIdentityR3) case DXGI_FORMAT_R11G11B10_FLOAT: LOAD_SCANLINE3(XMFLOAT3PK, XMLoadFloat3PK, g_XMIdentityR3) case DXGI_FORMAT_R16G16_FLOAT: LOAD_SCANLINE2(XMHALF2, XMLoadHalf2, g_XMIdentityR3) case DXGI_FORMAT_R32_FLOAT: if (size >= sizeof(float)) { const float* __restrict sPtr = reinterpret_cast<const float*>(pSource); for (size_t icount = 0; icount < size; icount += sizeof(float)) { XMVECTOR v = XMLoadFloat(sPtr++); if (dPtr >= ePtr) break; *(dPtr++) = XMVectorSelect(g_XMIdentityR3, v, g_XMSelect1000); } return true; } return false; case DXGI_FORMAT_R16_FLOAT: if (size >= sizeof(HALF)) { const HALF * __restrict sPtr = reinterpret_cast<const HALF*>(pSource); for (size_t icount = 0; icount < size; icount += sizeof(HALF)) { if (dPtr >= ePtr) break; *(dPtr++) = XMVectorSet(XMConvertHalfToFloat(*sPtr++), 0.f, 0.f, 1.f); } return true; } return false; default: return false; } } #pragma warning(pop) } // namespace anonymous //------------------------------------------------------------------------------------- // Projects a function represented in a cube map into spherical harmonics. // // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476300.aspx //------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT DirectX::SHProjectCubeMap( size_t order, const D3D12_RESOURCE_DESC& desc, const D3D12_SUBRESOURCE_DATA cubeMap[6], float *resultR, float *resultG, float *resultB) noexcept { if (order < XM_SH_MINORDER || order > XM_SH_MAXORDER) return E_INVALIDARG; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || (desc.DepthOrArraySize != 6) || (desc.Width != desc.Height) || (desc.SampleDesc.Count > 1)) return E_FAIL; switch (desc.Format) { case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R16_FLOAT: // See _LoadScanline to support more pixel formats break; default: return E_FAIL; } //--- Setup for SH projection ScopedAlignedArrayXMVECTOR scanline(reinterpret_cast<XMVECTOR*>(_aligned_malloc(static_cast<size_t>(sizeof(XMVECTOR)*desc.Width), 16))); if (!scanline) return E_OUTOFMEMORY; assert(desc.Width > 0); float fSize = static_cast<float>(desc.Width); float fPicSize = 1.0f / fSize; // index from [0,W-1], f(0) maps to -1 + 1/W, f(W-1) maps to 1 - 1/w // linear function x*S +B, 1st constraint means B is (-1+1/W), plug into // second and solve for S: S = 2*(1-1/W)/(W-1). The old code that did // this was incorrect - but only for computing the differential solid // angle, where the final value was 1.0 instead of 1-1/w... float fB = -1.0f + 1.0f / fSize; float fS = (desc.Width > 1) ? (2.0f*(1.0f - 1.0f / fSize) / (fSize - 1.0f)) : 0.f; // clear out accumulation variables float fWt = 0.0f; if (resultR) memset(resultR, 0, sizeof(float)*order*order); if (resultG) memset(resultG, 0, sizeof(float)*order*order); if (resultB) memset(resultB, 0, sizeof(float)*order*order); float shBuff[XM_SH_MAXORDER*XM_SH_MAXORDER] = {}; float shBuffB[XM_SH_MAXORDER*XM_SH_MAXORDER] = {}; //--- Process each face of the cubemap for (UINT face = 0; face < 6; ++face) { if (!cubeMap[face].pData) return E_POINTER; const uint8_t *pSrc = reinterpret_cast<const uint8_t*>(cubeMap[face].pData); for (UINT y = 0; y < desc.Height; ++y) { XMVECTOR* ptr = scanline.get(); if (!_LoadScanline(ptr, static_cast<size_t>(desc.Width), pSrc, static_cast<size_t>(cubeMap[face].RowPitch), desc.Format)) { return E_FAIL; } const float v = float(y) * fS + fB; XMVECTOR* pixel = ptr; for (UINT x = 0; x < desc.Width; ++x, ++pixel) { const float u = float(x) * fS + fB; float ix, iy, iz; switch (face) { case 0: // Positive X iz = 1.0f - (2.0f * float(x) + 1.0f) * fPicSize; iy = 1.0f - (2.0f * float(y) + 1.0f) * fPicSize; ix = 1.0f; break; case 1: // Negative X iz = -1.0f + (2.0f * float(x) + 1.0f) * fPicSize; iy = 1.0f - (2.0f * float(y) + 1.0f) * fPicSize; ix = -1; break; case 2: // Positive Y iz = -1.0f + (2.0f * float(y) + 1.0f) * fPicSize; iy = 1.0f; ix = -1.0f + (2.0f * float(x) + 1.0f) * fPicSize; break; case 3: // Negative Y iz = 1.0f - (2.0f * float(y) + 1.0f) * fPicSize; iy = -1.0f; ix = -1.0f + (2.0f * float(x) + 1.0f) * fPicSize; break; case 4: // Positive Z iz = 1.0f; iy = 1.0f - (2.0f * float(y) + 1.0f) * fPicSize; ix = -1.0f + (2.0f * float(x) + 1.0f) * fPicSize; break; case 5: // Negative Z iz = -1.0f; iy = 1.0f - (2.0f * float(y) + 1.0f) * fPicSize; ix = 1.0f - (2.0f * float(x) + 1.0f) * fPicSize; break; default: ix = iy = iz = 0.f; assert(false); break; } XMVECTOR dir = XMVectorSet(ix, iy, iz, 0); dir = XMVector3Normalize(dir); const float fDiffSolid = 4.0f / ((1.0f + u * u + v * v)*sqrtf(1.0f + u * u + v * v)); fWt += fDiffSolid; XMSHEvalDirection(shBuff, order, dir); XMFLOAT3A clr; XMStoreFloat3A(&clr, *pixel); if (resultR) XMSHAdd(resultR, order, resultR, XMSHScale(shBuffB, order, shBuff, clr.x*fDiffSolid)); if (resultG) XMSHAdd(resultG, order, resultG, XMSHScale(shBuffB, order, shBuff, clr.y*fDiffSolid)); if (resultB) XMSHAdd(resultB, order, resultB, XMSHScale(shBuffB, order, shBuff, clr.z*fDiffSolid)); } pSrc += cubeMap[face].RowPitch; } } const float fNormProj = (4.0f*XM_PI) / fWt; if (resultR) XMSHScale(resultR, order, resultR, fNormProj); if (resultG) XMSHScale(resultG, order, resultG, fNormProj); if (resultB) XMSHScale(resultB, order, resultB, fNormProj); return S_OK; }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Michael Hackstein //////////////////////////////////////////////////////////////////////////////// #include "TraversalBlock.h" #include "Aql/AqlItemBlock.h" #include "Aql/ExecutionEngine.h" #include "Aql/ExecutionNode.h" #include "Aql/ExecutionPlan.h" #include "Aql/Functions.h" #include "Aql/Query.h" #include "Basics/StringRef.h" #include "Cluster/ClusterComm.h" #include "Cluster/ClusterTraverser.h" #ifdef USE_ENTERPRISE #include "Enterprise/Cluster/SmartGraphTraverser.h" #endif #include "Graph/SingleServerTraverser.h" #include "Transaction/Helpers.h" #include "Transaction/Methods.h" #include "Utils/OperationCursor.h" #include "V8/v8-globals.h" #include "VocBase/ManagedDocumentResult.h" #include "VocBase/ticks.h" #include <velocypack/Builder.h> #include <velocypack/Iterator.h> #include <velocypack/velocypack-aliases.h> using namespace arangodb; using namespace arangodb::aql; using namespace arangodb::traverser; TraversalBlock::TraversalBlock(ExecutionEngine* engine, TraversalNode const* ep) : ExecutionBlock(engine, ep), _posInPaths(0), _opts(nullptr), _traverser(nullptr), _reg(ExecutionNode::MaxRegisterId), _useRegister(false), _usedConstant(false), _vertexVar(nullptr), _vertexReg(0), _edgeVar(nullptr), _edgeReg(0), _pathVar(nullptr), _pathReg(0), _engines(nullptr) { auto const& registerPlan = ep->getRegisterPlan()->varInfo; ep->getConditionVariables(_inVars); for (auto const& v : _inVars) { auto it = registerPlan.find(v->id); TRI_ASSERT(it != registerPlan.end()); _inRegs.emplace_back(it->second.registerId); } _opts = static_cast<TraverserOptions*>(ep->options()); TRI_ASSERT(_opts != nullptr); _mmdr.reset(new ManagedDocumentResult); if (arangodb::ServerState::instance()->isCoordinator()) { #ifdef USE_ENTERPRISE if (ep->isSmart()) { _traverser.reset(new arangodb::traverser::SmartGraphTraverser( _opts, _mmdr.get(), ep->engines(), _trx->vocbase().name(), _trx)); } else { #endif _traverser.reset( new arangodb::traverser::ClusterTraverser(_opts, _mmdr.get(), ep->engines(), _trx->vocbase().name(), _trx)); #ifdef USE_ENTERPRISE } #endif } else { _traverser.reset( new arangodb::traverser::SingleServerTraverser(_opts, _trx, _mmdr.get())); } if (!ep->usesEdgeOutVariable() && !ep->usesPathOutVariable() && _opts->useBreadthFirst && _opts->uniqueVertices == traverser::TraverserOptions::UniquenessLevel::GLOBAL) { _traverser->allowOptimizedNeighbors(); } if (!ep->usesInVariable()) { _vertexId = ep->getStartVertex(); } else { auto it = ep->getRegisterPlan()->varInfo.find(ep->inVariable()->id); TRI_ASSERT(it != ep->getRegisterPlan()->varInfo.end()); _reg = it->second.registerId; _useRegister = true; } if (ep->usesVertexOutVariable()) { _vertexVar = ep->vertexOutVariable(); } if (ep->usesEdgeOutVariable()) { _edgeVar = ep->edgeOutVariable(); } if (ep->usesPathOutVariable()) { _pathVar = ep->pathOutVariable(); } if (arangodb::ServerState::instance()->isCoordinator()) { _engines = ep->engines(); } auto varInfo = getPlanNode()->getRegisterPlan()->varInfo; if (usesVertexOutput()) { TRI_ASSERT(_vertexVar != nullptr); auto it = varInfo.find(_vertexVar->id); TRI_ASSERT(it != varInfo.end()); TRI_ASSERT(it->second.registerId < ExecutionNode::MaxRegisterId); _vertexReg = it->second.registerId; } if (usesEdgeOutput()) { TRI_ASSERT(_edgeVar != nullptr); auto it = varInfo.find(_edgeVar->id); TRI_ASSERT(it != varInfo.end()); TRI_ASSERT(it->second.registerId < ExecutionNode::MaxRegisterId); _edgeReg = it->second.registerId; } if (usesPathOutput()) { TRI_ASSERT(_pathVar != nullptr); auto it = varInfo.find(_pathVar->id); TRI_ASSERT(it != varInfo.end()); TRI_ASSERT(it->second.registerId < ExecutionNode::MaxRegisterId); _pathReg = it->second.registerId; } } TraversalBlock::~TraversalBlock() { freeCaches(); } void TraversalBlock::freeCaches() { for (auto& v : _vertices) { v.destroy(); } _vertices.clear(); for (auto& e : _edges) { e.destroy(); } _edges.clear(); for (auto& p : _paths) { p.destroy(); } _paths.clear(); } std::pair<ExecutionState, arangodb::Result> TraversalBlock::initializeCursor(AqlItemBlock* items, size_t pos) { auto res = ExecutionBlock::initializeCursor(items, pos); if (res.first == ExecutionState::WAITING || !res.second.ok()) { // If we need to wait or get an error we return as is. return res; } _pos = 0; _posInPaths = 0; _usedConstant = false; freeCaches(); _traverser->done(); _skipped = 0; return res; } /// @brief shutdown: Inform all traverser Engines to destroy themselves std::pair<ExecutionState, Result> TraversalBlock::shutdown(int errorCode) { ExecutionState state; Result result; std::tie(state, result) = ExecutionBlock::shutdown(errorCode); if (state == ExecutionState::WAITING) { return {state, result}; } // We have to clean up the engines in Coordinator Case. if (arangodb::ServerState::instance()->isCoordinator()) { auto cc = arangodb::ClusterComm::instance(); if (cc != nullptr) { // nullptr only happens on controlled server shutdown std::string const url( "/_db/" + arangodb::basics::StringUtils::urlEncode(_trx->vocbase().name()) + "/_internal/traverser/"); for (auto const& it : *_engines) { arangodb::CoordTransactionID coordTransactionID = TRI_NewTickServer(); std::unordered_map<std::string, std::string> headers; auto res = cc->syncRequest(coordTransactionID, "server:" + it.first, RequestType::DELETE_REQ, url + arangodb::basics::StringUtils::itoa(it.second), "", headers, 30.0); if (res->status != CL_COMM_SENT) { // Note If there was an error on server side we do not have // CL_COMM_SENT std::string message("Could not destroy all traversal engines"); if (!res->errorMessage.empty()) { message += std::string(": ") + res->errorMessage; } LOG_TOPIC(ERR, arangodb::Logger::FIXME) << message; } } } } return {state, result}; } /// @brief read more paths from _traverser. returns true if there are more /// paths. bool TraversalBlock::getSomePaths(size_t hint) { freeCaches(); _posInPaths = 0; if (!_traverser->hasMore()) { _engine->_stats.scannedIndex += _traverser->getAndResetReadDocuments(); _engine->_stats.filtered += _traverser->getAndResetFilteredPaths(); return false; } if (usesVertexOutput()) { _vertices.reserve(hint); } if (usesEdgeOutput()) { _edges.reserve(hint); } if (usesPathOutput()) { _paths.reserve(hint); } transaction::BuilderLeaser tmp(_trx); for (size_t j = 0; j < hint; ++j) { if (!_traverser->next()) { // There are no further paths available. break; } if (usesVertexOutput()) { _vertices.emplace_back(_traverser->lastVertexToAqlValue()); } if (usesEdgeOutput()) { _edges.emplace_back(_traverser->lastEdgeToAqlValue()); } if (usesPathOutput()) { tmp->clear(); _paths.emplace_back(_traverser->pathToAqlValue(*tmp.builder())); } throwIfKilled(); // check if we were aborted } _engine->_stats.scannedIndex += _traverser->getAndResetReadDocuments(); _engine->_stats.filtered += _traverser->getAndResetFilteredPaths(); return !_vertices.empty(); } /// @brief skip the next paths size_t TraversalBlock::skipPaths(size_t hint) { freeCaches(); _posInPaths = 0; if (!_traverser->hasMore()) { return 0; } return _traverser->skip(hint); } void TraversalBlock::initializeExpressions(AqlItemBlock const* items, size_t pos) { // Initialize the Expressions within the options. // We need to find the variable and read its value here. Everything is // computed right now. _opts->clearVariableValues(); TRI_ASSERT(_inVars.size() == _inRegs.size()); for (size_t i = 0; i < _inVars.size(); ++i) { _opts->setVariableValue(_inVars[i], items->getValueReference(pos, _inRegs[i])); } // IF cluster => Transfer condition. } /// @brief initialize the list of paths void TraversalBlock::initializePaths(AqlItemBlock const* items, size_t pos) { if (!_vertices.empty()) { // No Initialization required. return; } initializeExpressions(items, pos); if (!_useRegister) { if (!_usedConstant) { _usedConstant = true; auto pos = _vertexId.find('/'); if (pos == std::string::npos) { _engine->getQuery()->registerWarning(TRI_ERROR_BAD_PARAMETER, "Invalid input for traversal: " "Only id strings or objects with " "_id are allowed"); } else { _traverser->setStartVertex(_vertexId); } } } else { AqlValue const& in = items->getValueReference(_pos, _reg); if (in.isObject()) { try { _traverser->setStartVertex(_trx->extractIdString(in.slice())); } catch (...) { // _id or _key not present... ignore this error and fall through } } else if (in.isString()) { _vertexId = in.slice().copyString(); _traverser->setStartVertex(_vertexId); } else { _engine->getQuery()->registerWarning(TRI_ERROR_BAD_PARAMETER, "Invalid input for traversal: Only " "id strings or objects with _id are " "allowed"); } } } /// @brief getSome std::pair<ExecutionState, std::unique_ptr<AqlItemBlock>> TraversalBlock::getSome(size_t atMost) { traceGetSomeBegin(atMost); RegisterId const nrOutRegs = getNrOutputRegisters(); RegisterId const nrInRegs = getNrInputRegisters(); while (!_done && _skipped < atMost) { size_t toFetch = (std::min)(DefaultBatchSize(), atMost); BufferState bufferState = getBlockIfNeeded(toFetch); if (bufferState == BufferState::WAITING) { return {ExecutionState::WAITING, nullptr}; } if (bufferState == BufferState::NO_MORE_BLOCKS) { break; } TRI_ASSERT(bufferState == BufferState::HAS_BLOCKS || bufferState == BufferState::HAS_NEW_BLOCK); TRI_ASSERT(!_buffer.empty()); // If we get here, we do have _buffer.front() AqlItemBlock* cur = _buffer.front(); TRI_ASSERT(cur != nullptr); TRI_ASSERT(nrInRegs == cur->getNrRegs()); // Initialization on the first row of each new block if (bufferState == BufferState::HAS_NEW_BLOCK) { // A new row (and therefore block) should only be fetched at the very // beginning, or after the traverser is completely processed; in either // case, the traverser should be done. TRI_ASSERT(_pos == 0 && !_traverser->hasMore()); initializePaths(cur, _pos); } if (!_vertices.empty()) { TRI_ASSERT(_posInPaths < _vertices.size()); size_t available = _vertices.size() - _posInPaths; size_t toSend = (std::min)(atMost - _skipped, available); // automatically freed if we throw std::unique_ptr<AqlItemBlock> res(requestBlock(toSend, nrOutRegs)); TRI_ASSERT(nrInRegs <= res->getNrRegs()); // only copy 1st row of registers inherited from previous frame(s) inheritRegisters(cur, res.get(), _pos); for (size_t j = 0; j < toSend; j++) { if (usesVertexOutput()) { res->setValue(j, _vertexReg, _vertices[_posInPaths].clone()); } if (usesEdgeOutput()) { res->setValue(j, _edgeReg, _edges[_posInPaths].clone()); } if (usesPathOutput()) { res->setValue(j, _pathReg, _paths[_posInPaths].clone()); } if (j > 0) { // re-use already copied AqlValues res->copyValuesFromFirstRow(j, nrInRegs); } ++_posInPaths; } _collector.add(std::move(res)); advanceCursor(0, toSend); } // if there are no more paths left, reset traverser (in getSomePaths), // move to the next input row and re-initialize the paths unless we // switched to the next input block. In case we processed the current block // fully, we can't initialize the paths yet as we need the row for this: // this will be done after the next block is fetched. if (_posInPaths >= _vertices.size() && !getSomePaths(atMost)) { _usedConstant = false; AqlItemBlock* removedBlock = advanceCursor(1, 0); if (removedBlock == nullptr) { initializePaths(cur, _pos); } returnBlockUnlessNull(removedBlock); } } std::unique_ptr<AqlItemBlock> result(_collector.steal()); _skipped = 0; // Clear out registers no longer needed later: clearRegisters(result.get()); traceGetSomeEnd(result.get(), getHasMoreState()); return {getHasMoreState(), std::move(result)}; } /// @brief skipSome std::pair<ExecutionState, size_t> TraversalBlock::skipSome(size_t atMost) { traceSkipSomeBegin(atMost); if (_done) { traceSkipSomeEnd(0, ExecutionState::DONE); return {ExecutionState::DONE, 0}; } // eat as much as possible from _vertices first if (_posInPaths < _vertices.size()) { size_t const skip = (std::min)(atMost, _vertices.size() - _posInPaths); advanceCursor(0, skip); _posInPaths += skip; } // now, _vertices is either empty, or _skipped == atMost. TRI_ASSERT(_vertices.empty() || _skipped == atMost); while (_skipped < atMost) { BufferState bufferState = getBlockIfNeeded(atMost); if (bufferState == BufferState::WAITING) { traceSkipSomeEnd(0, ExecutionState::WAITING); return {ExecutionState::WAITING, 0}; } if (bufferState == BufferState::NO_MORE_BLOCKS) { break; } TRI_ASSERT(bufferState == BufferState::HAS_BLOCKS || bufferState == BufferState::HAS_NEW_BLOCK); TRI_ASSERT(!_buffer.empty()); // If we get here, we do have _buffer.front() AqlItemBlock* cur = _buffer.front(); // Initialization on the first row of each new block if (bufferState == BufferState::HAS_NEW_BLOCK) { // A new row (and therefore block) should only be fetched at the very // beginning, or after the traverser is completely processed; in either // case, the traverser should be done. TRI_ASSERT(_pos == 0 && !_traverser->hasMore()); initializePaths(cur, _pos); } TRI_ASSERT(atMost >= _skipped); size_t const skip = skipPaths(atMost - _skipped); advanceCursor(0, skip); TRI_ASSERT(skip != 0 || !_traverser->hasMore()); if (!_traverser->hasMore()) { AqlItemBlock* removedBlock = advanceCursor(1, 0); if (removedBlock == nullptr) { initializePaths(cur, _pos); } returnBlockUnlessNull(removedBlock); } } size_t skipped = _skipped; _skipped = 0; ExecutionState state = getHasMoreState(); traceSkipSomeEnd(skipped, state); return {state, skipped}; }
#pragma once #include "task.hpp" #include <memory> void initializeTelnetSpawner(Task *(*spawner)(std::shared_ptr<TTY>));
// James Stanko // CS 33101 // Structure of Programming Languages // 5/3/2017 #include <iostream> #include <fstream> #include <sstream> #include <string> #include <iomanip> #include "ReadDATFile.h" int main(){ DATData tmp; unsigned char hold; int shold = 0; std::string READ_RESULT; std::ifstream inputfile("GrTMt.dat", std::ios::binary); //open file as binary std::stringstream StrStream; inputfile >> std::noskipws; //Dont skip whitespaces when reading! while ((!inputfile.eof())) {//put hex values into stringstream inputfile >> hold; StrStream << std::hex << std::setfill('0') << std::setw(2) << (int)hold; } std::cout << "File read completed.\n"; READ_RESULT = StrStream.str(); tmp.SEARCHFILE(READ_RESULT); tmp.PRINTRESULTS(); std::cin.get(); inputfile.close(); } //=====================================Definitions===================================== DATData::DATData(){ } DATData::~DATData(){ } void DATData::SEARCHFILE(const std::string &read){ int i = 0; int j = 0; int tmp_offset; //this will keep track of the offset; when position data found, //set the incremented offset to the current value held in this; int tmp_loc = 0; std::string tmp_hex; std::string PositionStart("3f8000003f8000003f800000"); //used to find position data; std::size_t loc = 0; while (i < read.capacity()){ if (i != loc){ //first search loc = read.find(PositionStart); } if (i == loc){ //subsequent searches loc = read.find(PositionStart, loc + 1); } if (loc != std::string::npos){//when position data found tmp_offset = loc; tmp_loc = loc; tmp_offset = ((tmp_offset)/2); //***convert to hex this->offset.push_back("0x" + std::to_string(tmp_offset)); for (int k = 0; k < 48; ++k){ tmp_hex.push_back(read[tmp_loc]); tmp_loc++; } this->hex.push_back(tmp_hex); tmp_hex = ""; } else{ std::cout << "Position data search completed.\n"; std::cout << std::endl; } i = loc; } return; } void DATData::PRINTRESULTS(){ for (int i = 0; i < this->hex.size(); ++i){ std::cout << "Offset: " << offset[i] << std::endl; std::cout << "X Pos: " << hex[i].substr(24, 8) << std::endl; std::cout << "Y Pos: " << hex[i].substr(32, 8) << std::endl; std::cout << "Z Pos: " << hex[i].substr(40, 8) << std::endl; std::cout << std::endl; } }
//M*////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ /************************************************************************************\ This is improved variant of chessboard corner detection algorithm that uses a graph of connected quads. It is based on the code contributed by Vladimir Vezhnevets and Philip Gruebele. Here is the copyright notice from the original Vladimir's code: =============================================================== The algorithms developed and implemented by Vezhnevets Vldimir aka Dead Moroz (vvp@graphics.cs.msu.ru) See http://graphics.cs.msu.su/en/research/calibration/opencv.html for detailed information. Reliability additions and modifications made by Philip Gruebele. <a href="mailto:pgruebele@cox.net">pgruebele@cox.net</a> Some further improvements for detection of partially ocluded boards at non-ideal lighting conditions have been made by Alex Bovyrin and Kurt Kolonige \************************************************************************************/ /************************************************************************************\ This version adds a new and improved variant of chessboard corner detection that works better in poor lighting condition. It is based on work from Oliver Schreer and Stefano Masneri. This method works faster than the previous one and reverts back to the older method in case no chessboard detection is possible. Overall performance improves also because now the method avoids performing the same computation multiple times when not necessary. \************************************************************************************/ #include "precomp.hpp" #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/calib3d/calib3d_c.h" #include "circlesgrid.hpp" #include <stdarg.h> #include <vector> using namespace cv; using namespace std; //#define ENABLE_TRIM_COL_ROW //#define DEBUG_CHESSBOARD #ifdef DEBUG_CHESSBOARD static int PRINTF( const char* fmt, ... ) { va_list args; va_start(args, fmt); return vprintf(fmt, args); } #else #define PRINTF(...) #endif //===================================================================================== // Implementation for the enhanced calibration object detection //===================================================================================== #define MAX_CONTOUR_APPROX 7 struct CvContourEx { CV_CONTOUR_FIELDS() int counter; }; //===================================================================================== /// Corner info structure /** This structure stores information about the chessboard corner.*/ struct CvCBCorner { CvPoint2D32f pt; // Coordinates of the corner int row; // Board row index int count; // Number of neighbor corners struct CvCBCorner* neighbors[4]; // Neighbor corners float meanDist(int *_n) const { float sum = 0; int n = 0; for( int i = 0; i < 4; i++ ) { if( neighbors[i] ) { float dx = neighbors[i]->pt.x - pt.x; float dy = neighbors[i]->pt.y - pt.y; sum += sqrt(dx*dx + dy*dy); n++; } } if(_n) *_n = n; return sum/MAX(n,1); } }; //===================================================================================== /// Quadrangle contour info structure /** This structure stores information about the chessboard quadrange.*/ struct CvCBQuad { int count; // Number of quad neighbors int group_idx; // quad group ID int row, col; // row and column of this quad bool ordered; // true if corners/neighbors are ordered counter-clockwise float edge_len; // quad edge len, in pix^2 // neighbors and corners are synced, i.e., neighbor 0 shares corner 0 CvCBCorner *corners[4]; // Coordinates of quad corners struct CvCBQuad *neighbors[4]; // Pointers of quad neighbors }; //===================================================================================== #ifdef DEBUG_CHESSBOARD #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" static void SHOW(const std::string & name, Mat & img) { imshow(name, img); while ((uchar)waitKey(0) != 'q') {} } static void SHOW_QUADS(const std::string & name, const Mat & img_, CvCBQuad * quads, int quads_count) { Mat img = img_.clone(); if (img.channels() == 1) cvtColor(img, img, COLOR_GRAY2BGR); for (int i = 0; i < quads_count; ++i) { CvCBQuad & quad = quads[i]; for (int j = 0; j < 4; ++j) { line(img, quad.corners[j]->pt, quad.corners[(j + 1) % 4]->pt, Scalar(0, 240, 0), 1, LINE_AA); } } imshow(name, img); while ((uchar)waitKey(0) != 'q') {} } #else #define SHOW(...) #define SHOW_QUADS(...) #endif //===================================================================================== static int icvGenerateQuads( CvCBQuad **quads, CvCBCorner **corners, CvMemStorage *storage, const Mat &image_, int flags, int *max_quad_buf_size); static bool processQuads(CvCBQuad *quads, int quad_count, CvSize pattern_size, int max_quad_buf_size, CvMemStorage * storage, CvCBCorner *corners, CvPoint2D32f *out_corners, int *out_corner_count, int & prev_sqr_size); /*static int icvGenerateQuadsEx( CvCBQuad **out_quads, CvCBCorner **out_corners, CvMemStorage *storage, CvMat *image, CvMat *thresh_img, int dilation, int flags );*/ static void icvFindQuadNeighbors( CvCBQuad *quads, int quad_count ); static int icvFindConnectedQuads( CvCBQuad *quads, int quad_count, CvCBQuad **quad_group, int group_idx, CvMemStorage* storage ); static int icvCheckQuadGroup( CvCBQuad **quad_group, int count, CvCBCorner **out_corners, CvSize pattern_size ); static int icvCleanFoundConnectedQuads( int quad_count, CvCBQuad **quads, CvSize pattern_size ); static int icvOrderFoundConnectedQuads( int quad_count, CvCBQuad **quads, int *all_count, CvCBQuad **all_quads, CvCBCorner **corners, CvSize pattern_size, int max_quad_buf_size, CvMemStorage* storage ); static void icvOrderQuad(CvCBQuad *quad, CvCBCorner *corner, int common); #ifdef ENABLE_TRIM_COL_ROW static int icvTrimCol(CvCBQuad **quads, int count, int col, int dir); static int icvTrimRow(CvCBQuad **quads, int count, int row, int dir); #endif static int icvAddOuterQuad(CvCBQuad *quad, CvCBQuad **quads, int quad_count, CvCBQuad **all_quads, int all_count, CvCBCorner **corners, int max_quad_buf_size); static void icvRemoveQuadFromGroup(CvCBQuad **quads, int count, CvCBQuad *q0); static int icvCheckBoardMonotony( CvPoint2D32f* corners, CvSize pattern_size ); /***************************************************************************************************/ //COMPUTE INTENSITY HISTOGRAM OF INPUT IMAGE static int icvGetIntensityHistogram( const Mat & img, std::vector<int>& piHist ) { // sum up all pixel in row direction and divide by number of columns for ( int j=0; j<img.rows; j++ ) { const uchar * row = img.ptr(j); for ( int i=0; i<img.cols; i++ ) { piHist[row[i]]++; } } return 0; } /***************************************************************************************************/ //SMOOTH HISTOGRAM USING WINDOW OF SIZE 2*iWidth+1 static int icvSmoothHistogram( const std::vector<int>& piHist, std::vector<int>& piHistSmooth, int iWidth ) { int iIdx; for ( int i=0; i<256; i++) { int iSmooth = 0; for ( int ii=-iWidth; ii<=iWidth; ii++) { iIdx = i+ii; if (iIdx > 0 && iIdx < 256) { iSmooth += piHist[iIdx]; } } piHistSmooth[i] = iSmooth/(2*iWidth+1); } return 0; } /***************************************************************************************************/ //COMPUTE FAST HISTOGRAM GRADIENT static int icvGradientOfHistogram( const std::vector<int>& piHist, std::vector<int>& piHistGrad ) { piHistGrad[0] = 0; for ( int i=1; i<255; i++) { piHistGrad[i] = piHist[i-1] - piHist[i+1]; if ( abs(piHistGrad[i]) < 100 ) { if ( piHistGrad[i-1] == 0) piHistGrad[i] = -100; else piHistGrad[i] = piHistGrad[i-1]; } } return 0; } /***************************************************************************************************/ //PERFORM SMART IMAGE THRESHOLDING BASED ON ANALYSIS OF INTENSTY HISTOGRAM static bool icvBinarizationHistogramBased( Mat & img ) { CV_Assert(img.channels() == 1 && img.depth() == CV_8U); int iCols = img.cols; int iRows = img.rows; int iMaxPix = iCols*iRows; int iMaxPix1 = iMaxPix/100; const int iNumBins = 256; std::vector<int> piHistIntensity(iNumBins, 0); std::vector<int> piHistSmooth(iNumBins, 0); std::vector<int> piHistGrad(iNumBins, 0); std::vector<int> piAccumSum(iNumBins, 0); std::vector<int> piMaxPos(20, 0); int iThresh = 0; int iIdx; int iWidth = 1; icvGetIntensityHistogram( img, piHistIntensity ); // get accumulated sum starting from bright piAccumSum[iNumBins-1] = piHistIntensity[iNumBins-1]; for ( int i=iNumBins-2; i>=0; i-- ) { piAccumSum[i] = piHistIntensity[i] + piAccumSum[i+1]; } // first smooth the distribution icvSmoothHistogram( piHistIntensity, piHistSmooth, iWidth ); // compute gradient icvGradientOfHistogram( piHistSmooth, piHistGrad ); // check for zeros int iCntMaxima = 0; for ( int i=iNumBins-2; (i>2) && (iCntMaxima<20); i--) { if ( (piHistGrad[i-1] < 0) && (piHistGrad[i] > 0) ) { piMaxPos[iCntMaxima] = i; iCntMaxima++; } } iIdx = 0; int iSumAroundMax = 0; for ( int i=0; i<iCntMaxima; i++ ) { iIdx = piMaxPos[i]; iSumAroundMax = piHistSmooth[iIdx-1] + piHistSmooth[iIdx] + piHistSmooth[iIdx+1]; if ( iSumAroundMax < iMaxPix1 && iIdx < 64 ) { for ( int j=i; j<iCntMaxima-1; j++ ) { piMaxPos[j] = piMaxPos[j+1]; } iCntMaxima--; i--; } } if ( iCntMaxima == 1) { iThresh = piMaxPos[0]/2; } else if ( iCntMaxima == 2) { iThresh = (piMaxPos[0] + piMaxPos[1])/2; } else // iCntMaxima >= 3 { // CHECKING THRESHOLD FOR WHITE int iIdxAccSum = 0, iAccum = 0; for (int i=iNumBins-1; i>0; i--) { iAccum += piHistIntensity[i]; // iMaxPix/18 is about 5,5%, minimum required number of pixels required for white part of chessboard if ( iAccum > (iMaxPix/18) ) { iIdxAccSum = i; break; } } int iIdxBGMax = 0; int iBrightMax = piMaxPos[0]; // printf("iBrightMax = %d\n", iBrightMax); for ( int n=0; n<iCntMaxima-1; n++) { iIdxBGMax = n+1; if ( piMaxPos[n] < iIdxAccSum ) { break; } iBrightMax = piMaxPos[n]; } // CHECKING THRESHOLD FOR BLACK int iMaxVal = piHistIntensity[piMaxPos[iIdxBGMax]]; //IF TOO CLOSE TO 255, jump to next maximum if ( piMaxPos[iIdxBGMax] >= 250 && iIdxBGMax < iCntMaxima ) { iIdxBGMax++; iMaxVal = piHistIntensity[piMaxPos[iIdxBGMax]]; } for ( int n=iIdxBGMax + 1; n<iCntMaxima; n++) { if ( piHistIntensity[piMaxPos[n]] >= iMaxVal ) { iMaxVal = piHistIntensity[piMaxPos[n]]; iIdxBGMax = n; } } //SETTING THRESHOLD FOR BINARIZATION int iDist2 = (iBrightMax - piMaxPos[iIdxBGMax])/2; iThresh = iBrightMax - iDist2; PRINTF("THRESHOLD SELECTED = %d, BRIGHTMAX = %d, DARKMAX = %d\n", iThresh, iBrightMax, piMaxPos[iIdxBGMax]); } if ( iThresh > 0 ) { for ( int jj=0; jj<iRows; jj++) { uchar * row = img.ptr(jj); for ( int ii=0; ii<iCols; ii++) { if ( row[ii] < iThresh ) row[ii] = 0; else row[ii] = 255; } } } return true; } CV_IMPL int cvFindChessboardCorners( const void* arr, CvSize pattern_size, CvPoint2D32f* out_corners, int* out_corner_count, int flags ) { int found = 0; CvCBQuad *quads = 0; CvCBCorner *corners = 0; cv::Ptr<CvMemStorage> storage; CV_TRY { int k = 0; const int min_dilations = 0; const int max_dilations = 7; if( out_corner_count ) *out_corner_count = 0; Mat img = cvarrToMat((CvMat*)arr).clone(); if( img.depth() != CV_8U || (img.channels() != 1 && img.channels() != 3 && img.channels() != 4) ) CV_Error( CV_StsUnsupportedFormat, "Only 8-bit grayscale or color images are supported" ); if( pattern_size.width <= 2 || pattern_size.height <= 2 ) CV_Error( CV_StsOutOfRange, "Both width and height of the pattern should have bigger than 2" ); if( !out_corners ) CV_Error( CV_StsNullPtr, "Null pointer to corners" ); if (img.channels() != 1) { cvtColor(img, img, COLOR_BGR2GRAY); } Mat thresh_img_new = img.clone(); icvBinarizationHistogramBased( thresh_img_new ); // process image in-place SHOW("New binarization", thresh_img_new); if( flags & CV_CALIB_CB_FAST_CHECK) { //perform new method for checking chessboard using a binary image. //image is binarised using a threshold dependent on the image histogram if (checkChessboardBinary(thresh_img_new, pattern_size) <= 0) //fall back to the old method { if (checkChessboard(img, pattern_size) <= 0) { return found; } } } storage.reset(cvCreateMemStorage(0)); int prev_sqr_size = 0; // Try our standard "1" dilation, but if the pattern is not found, iterate the whole procedure with higher dilations. // This is necessary because some squares simply do not separate properly with a single dilation. However, // we want to use the minimum number of dilations possible since dilations cause the squares to become smaller, // making it difficult to detect smaller squares. for( int dilations = min_dilations; dilations <= max_dilations; dilations++ ) { if (found) break; // already found it //USE BINARY IMAGE COMPUTED USING icvBinarizationHistogramBased METHOD dilate( thresh_img_new, thresh_img_new, Mat(), Point(-1, -1), 1 ); // So we can find rectangles that go to the edge, we draw a white line around the image edge. // Otherwise FindContours will miss those clipped rectangle contours. // The border color will be the image mean, because otherwise we risk screwing up filters like cvSmooth()... rectangle( thresh_img_new, Point(0,0), Point(thresh_img_new.cols-1, thresh_img_new.rows-1), Scalar(255,255,255), 3, LINE_8); int max_quad_buf_size = 0; cvFree(&quads); cvFree(&corners); int quad_count = icvGenerateQuads( &quads, &corners, storage, thresh_img_new, flags, &max_quad_buf_size ); PRINTF("Quad count: %d/%d\n", quad_count, (pattern_size.width/2+1)*(pattern_size.height/2+1)); SHOW_QUADS("New quads", thresh_img_new, quads, quad_count); if (processQuads(quads, quad_count, pattern_size, max_quad_buf_size, storage, corners, out_corners, out_corner_count, prev_sqr_size)) found = 1; } PRINTF("Chessboard detection result 0: %d\n", found); // revert to old, slower, method if detection failed if (!found) { if( flags & CV_CALIB_CB_NORMALIZE_IMAGE ) { equalizeHist( img, img ); } Mat thresh_img; prev_sqr_size = 0; PRINTF("Fallback to old algorithm\n"); const bool useAdaptive = flags & CV_CALIB_CB_ADAPTIVE_THRESH; if (!useAdaptive) { // empiric threshold level // thresholding performed here and not inside the cycle to save processing time double mean = cv::mean(img).val[0]; int thresh_level = MAX(cvRound( mean - 10 ), 10); threshold( img, thresh_img, thresh_level, 255, THRESH_BINARY ); } //if flag CV_CALIB_CB_ADAPTIVE_THRESH is not set it doesn't make sense to iterate over k int max_k = useAdaptive ? 6 : 1; for( k = 0; k < max_k; k++ ) { for( int dilations = min_dilations; dilations <= max_dilations; dilations++ ) { if (found) break; // already found it // convert the input grayscale image to binary (black-n-white) if (useAdaptive) { int block_size = cvRound(prev_sqr_size == 0 ? MIN(img.cols, img.rows) * (k % 2 == 0 ? 0.2 : 0.1) : prev_sqr_size * 2); block_size = block_size | 1; // convert to binary adaptiveThreshold( img, thresh_img, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, block_size, (k/2)*5 ); if (dilations > 0) dilate( thresh_img, thresh_img, Mat(), Point(-1, -1), dilations-1 ); } else { dilate( thresh_img, thresh_img, Mat(), Point(-1, -1), 1 ); } SHOW("Old binarization", thresh_img); // So we can find rectangles that go to the edge, we draw a white line around the image edge. // Otherwise FindContours will miss those clipped rectangle contours. // The border color will be the image mean, because otherwise we risk screwing up filters like cvSmooth()... rectangle( thresh_img, Point(0,0), Point(thresh_img.cols-1, thresh_img.rows-1), Scalar(255,255,255), 3, LINE_8); int max_quad_buf_size = 0; cvFree(&quads); cvFree(&corners); int quad_count = icvGenerateQuads( &quads, &corners, storage, thresh_img, flags, &max_quad_buf_size); PRINTF("Quad count: %d/%d\n", quad_count, (pattern_size.width/2+1)*(pattern_size.height/2+1)); SHOW_QUADS("Old quads", thresh_img, quads, quad_count); if (processQuads(quads, quad_count, pattern_size, max_quad_buf_size, storage, corners, out_corners, out_corner_count, prev_sqr_size)) found = 1; } } } PRINTF("Chessboard detection result 1: %d\n", found); if( found ) found = icvCheckBoardMonotony( out_corners, pattern_size ); PRINTF("Chessboard detection result 2: %d\n", found); // check that none of the found corners is too close to the image boundary if( found ) { const int BORDER = 8; for( k = 0; k < pattern_size.width*pattern_size.height; k++ ) { if( out_corners[k].x <= BORDER || out_corners[k].x > img.cols - BORDER || out_corners[k].y <= BORDER || out_corners[k].y > img.rows - BORDER ) break; } found = k == pattern_size.width*pattern_size.height; } PRINTF("Chessboard detection result 3: %d\n", found); if( found ) { if ( pattern_size.height % 2 == 0 && pattern_size.width % 2 == 0 ) { int last_row = (pattern_size.height-1)*pattern_size.width; double dy0 = out_corners[last_row].y - out_corners[0].y; if( dy0 < 0 ) { int n = pattern_size.width*pattern_size.height; for(int i = 0; i < n/2; i++ ) { CvPoint2D32f temp; CV_SWAP(out_corners[i], out_corners[n-i-1], temp); } } } int wsize = 2; CvMat old_img(img); cvFindCornerSubPix( &old_img, out_corners, pattern_size.width*pattern_size.height, cvSize(wsize, wsize), cvSize(-1,-1), cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 15, 0.1)); } } CV_CATCH_ALL { cvFree(&quads); cvFree(&corners); CV_RETHROW(); } cvFree(&quads); cvFree(&corners); return found; } // // Checks that each board row and column is pretty much monotonous curve: // It analyzes each row and each column of the chessboard as following: // for each corner c lying between end points in the same row/column it checks that // the point projection to the line segment (a,b) is lying between projections // of the neighbor corners in the same row/column. // // This function has been created as temporary workaround for the bug in current implementation // of cvFindChessboardCornes that produces absolutely unordered sets of corners. // static int icvCheckBoardMonotony( CvPoint2D32f* corners, CvSize pattern_size ) { int i, j, k; for( k = 0; k < 2; k++ ) { for( i = 0; i < (k == 0 ? pattern_size.height : pattern_size.width); i++ ) { CvPoint2D32f a = k == 0 ? corners[i*pattern_size.width] : corners[i]; CvPoint2D32f b = k == 0 ? corners[(i+1)*pattern_size.width-1] : corners[(pattern_size.height-1)*pattern_size.width + i]; float prevt = 0, dx0 = b.x - a.x, dy0 = b.y - a.y; if( fabs(dx0) + fabs(dy0) < FLT_EPSILON ) return 0; for( j = 1; j < (k == 0 ? pattern_size.width : pattern_size.height) - 1; j++ ) { CvPoint2D32f c = k == 0 ? corners[i*pattern_size.width + j] : corners[j*pattern_size.width + i]; float t = ((c.x - a.x)*dx0 + (c.y - a.y)*dy0)/(dx0*dx0 + dy0*dy0); if( t < prevt || t > 1 ) return 0; prevt = t; } } } return 1; } // // order a group of connected quads // order of corners: // 0 is top left // clockwise from there // note: "top left" is nominal, depends on initial ordering of starting quad // but all other quads are ordered consistently // // can change the number of quads in the group // can add quads, so we need to have quad/corner arrays passed in // static int icvOrderFoundConnectedQuads( int quad_count, CvCBQuad **quads, int *all_count, CvCBQuad **all_quads, CvCBCorner **corners, CvSize pattern_size, int max_quad_buf_size, CvMemStorage* storage ) { cv::Ptr<CvMemStorage> temp_storage(cvCreateChildMemStorage( storage )); CvSeq* stack = cvCreateSeq( 0, sizeof(*stack), sizeof(void*), temp_storage ); // first find an interior quad CvCBQuad *start = NULL; for (int i=0; i<quad_count; i++) { if (quads[i]->count == 4) { start = quads[i]; break; } } if (start == NULL) return 0; // no 4-connected quad // start with first one, assign rows/cols int row_min = 0, col_min = 0, row_max=0, col_max = 0; std::map<int, int> col_hist; std::map<int, int> row_hist; cvSeqPush(stack, &start); start->row = 0; start->col = 0; start->ordered = true; // Recursively order the quads so that all position numbers (e.g., // 0,1,2,3) are in the at the same relative corner (e.g., lower right). while( stack->total ) { CvCBQuad* q; cvSeqPop( stack, &q ); int col = q->col; int row = q->row; col_hist[col]++; row_hist[row]++; // check min/max if (row > row_max) row_max = row; if (row < row_min) row_min = row; if (col > col_max) col_max = col; if (col < col_min) col_min = col; for(int i = 0; i < 4; i++ ) { CvCBQuad *neighbor = q->neighbors[i]; switch(i) // adjust col, row for this quad { // start at top left, go clockwise case 0: row--; col--; break; case 1: col += 2; break; case 2: row += 2; break; case 3: col -= 2; break; } // just do inside quads if (neighbor && neighbor->ordered == false && neighbor->count == 4) { PRINTF("col: %d row: %d\n", col, row); icvOrderQuad(neighbor, q->corners[i], (i+2)%4); // set in order neighbor->ordered = true; neighbor->row = row; neighbor->col = col; cvSeqPush( stack, &neighbor ); } } } for (int i=col_min; i<=col_max; i++) PRINTF("HIST[%d] = %d\n", i, col_hist[i]); // analyze inner quad structure int w = pattern_size.width - 1; int h = pattern_size.height - 1; int drow = row_max - row_min + 1; int dcol = col_max - col_min + 1; // normalize pattern and found quad indices if ((w > h && dcol < drow) || (w < h && drow < dcol)) { h = pattern_size.width - 1; w = pattern_size.height - 1; } PRINTF("Size: %dx%d Pattern: %dx%d\n", dcol, drow, w, h); // check if there are enough inner quads if (dcol < w || drow < h) // found enough inner quads? { PRINTF("Too few inner quad rows/cols\n"); return 0; // no, return } #ifdef ENABLE_TRIM_COL_ROW // too many columns, not very common if (dcol == w+1) // too many, trim { PRINTF("Trimming cols\n"); if (col_hist[col_max] > col_hist[col_min]) { PRINTF("Trimming left col\n"); quad_count = icvTrimCol(quads,quad_count,col_min,-1); } else { PRINTF("Trimming right col\n"); quad_count = icvTrimCol(quads,quad_count,col_max,+1); } } // too many rows, not very common if (drow == h+1) // too many, trim { PRINTF("Trimming rows\n"); if (row_hist[row_max] > row_hist[row_min]) { PRINTF("Trimming top row\n"); quad_count = icvTrimRow(quads,quad_count,row_min,-1); } else { PRINTF("Trimming bottom row\n"); quad_count = icvTrimRow(quads,quad_count,row_max,+1); } } #endif // check edges of inner quads // if there is an outer quad missing, fill it in // first order all inner quads int found = 0; for (int i=0; i<quad_count; i++) { if (quads[i]->count == 4) { // ok, look at neighbors int col = quads[i]->col; int row = quads[i]->row; for (int j=0; j<4; j++) { switch(j) // adjust col, row for this quad { // start at top left, go clockwise case 0: row--; col--; break; case 1: col += 2; break; case 2: row += 2; break; case 3: col -= 2; break; } CvCBQuad *neighbor = quads[i]->neighbors[j]; if (neighbor && !neighbor->ordered && // is it an inner quad? col <= col_max && col >= col_min && row <= row_max && row >= row_min) { // if so, set in order PRINTF("Adding inner: col: %d row: %d\n", col, row); found++; icvOrderQuad(neighbor, quads[i]->corners[j], (j+2)%4); neighbor->ordered = true; neighbor->row = row; neighbor->col = col; } } } } // if we have found inner quads, add corresponding outer quads, // which are missing if (found > 0) { PRINTF("Found %d inner quads not connected to outer quads, repairing\n", found); for (int i=0; i<quad_count && *all_count < max_quad_buf_size; i++) { if (quads[i]->count < 4 && quads[i]->ordered) { int added = icvAddOuterQuad(quads[i],quads,quad_count,all_quads,*all_count,corners, max_quad_buf_size); *all_count += added; quad_count += added; } } if (*all_count >= max_quad_buf_size) return 0; } // final trimming of outer quads if (dcol == w && drow == h) // found correct inner quads { PRINTF("Inner bounds ok, check outer quads\n"); int rcount = quad_count; for (int i=quad_count-1; i>=0; i--) // eliminate any quad not connected to // an ordered quad { if (quads[i]->ordered == false) { bool outer = false; for (int j=0; j<4; j++) // any neighbors that are ordered? { if (quads[i]->neighbors[j] && quads[i]->neighbors[j]->ordered) outer = true; } if (!outer) // not an outer quad, eliminate { PRINTF("Removing quad %d\n", i); icvRemoveQuadFromGroup(quads,rcount,quads[i]); rcount--; } } } return rcount; } return 0; } // add an outer quad // looks for the neighbor of <quad> that isn't present, // tries to add it in. // <quad> is ordered static int icvAddOuterQuad( CvCBQuad *quad, CvCBQuad **quads, int quad_count, CvCBQuad **all_quads, int all_count, CvCBCorner **corners, int max_quad_buf_size ) { int added = 0; for (int i=0; i<4 && all_count < max_quad_buf_size; i++) // find no-neighbor corners { if (!quad->neighbors[i]) // ok, create and add neighbor { int j = (i+2)%4; PRINTF("Adding quad as neighbor 2\n"); CvCBQuad *q = &(*all_quads)[all_count]; memset( q, 0, sizeof(*q) ); added++; quads[quad_count] = q; quad_count++; // set neighbor and group id quad->neighbors[i] = q; quad->count += 1; q->neighbors[j] = quad; q->group_idx = quad->group_idx; q->count = 1; // number of neighbors q->ordered = false; q->edge_len = quad->edge_len; // make corners of new quad // same as neighbor quad, but offset CvPoint2D32f pt = quad->corners[i]->pt; CvCBCorner* corner; float dx = pt.x - quad->corners[j]->pt.x; float dy = pt.y - quad->corners[j]->pt.y; for (int k=0; k<4; k++) { corner = &(*corners)[all_count*4+k]; pt = quad->corners[k]->pt; memset( corner, 0, sizeof(*corner) ); corner->pt = pt; q->corners[k] = corner; corner->pt.x += dx; corner->pt.y += dy; } // have to set exact corner q->corners[j] = quad->corners[i]; // now find other neighbor and add it, if possible if (quad->neighbors[(i+3)%4] && quad->neighbors[(i+3)%4]->ordered && quad->neighbors[(i+3)%4]->neighbors[i] && quad->neighbors[(i+3)%4]->neighbors[i]->ordered ) { CvCBQuad *qn = quad->neighbors[(i+3)%4]->neighbors[i]; q->count = 2; q->neighbors[(j+1)%4] = qn; qn->neighbors[(i+1)%4] = q; qn->count += 1; // have to set exact corner q->corners[(j+1)%4] = qn->corners[(i+1)%4]; } all_count++; } } return added; } // trimming routines #ifdef ENABLE_TRIM_COL_ROW static int icvTrimCol(CvCBQuad **quads, int count, int col, int dir) { int rcount = count; // find the right quad(s) for (int i=0; i<count; i++) { #ifdef DEBUG_CHESSBOARD if (quads[i]->ordered) PRINTF("index: %d cur: %d\n", col, quads[i]->col); #endif if (quads[i]->ordered && quads[i]->col == col) { if (dir == 1) { if (quads[i]->neighbors[1]) { icvRemoveQuadFromGroup(quads,rcount,quads[i]->neighbors[1]); rcount--; } if (quads[i]->neighbors[2]) { icvRemoveQuadFromGroup(quads,rcount,quads[i]->neighbors[2]); rcount--; } } else { if (quads[i]->neighbors[0]) { icvRemoveQuadFromGroup(quads,rcount,quads[i]->neighbors[0]); rcount--; } if (quads[i]->neighbors[3]) { icvRemoveQuadFromGroup(quads,rcount,quads[i]->neighbors[3]); rcount--; } } } } return rcount; } static int icvTrimRow(CvCBQuad **quads, int count, int row, int dir) { int i, rcount = count; // find the right quad(s) for (i=0; i<count; i++) { #ifdef DEBUG_CHESSBOARD if (quads[i]->ordered) PRINTF("index: %d cur: %d\n", row, quads[i]->row); #endif if (quads[i]->ordered && quads[i]->row == row) { if (dir == 1) // remove from bottom { if (quads[i]->neighbors[2]) { icvRemoveQuadFromGroup(quads,rcount,quads[i]->neighbors[2]); rcount--; } if (quads[i]->neighbors[3]) { icvRemoveQuadFromGroup(quads,rcount,quads[i]->neighbors[3]); rcount--; } } else // remove from top { if (quads[i]->neighbors[0]) { icvRemoveQuadFromGroup(quads,rcount,quads[i]->neighbors[0]); rcount--; } if (quads[i]->neighbors[1]) { icvRemoveQuadFromGroup(quads,rcount,quads[i]->neighbors[1]); rcount--; } } } } return rcount; } #endif // // remove quad from quad group // static void icvRemoveQuadFromGroup(CvCBQuad **quads, int count, CvCBQuad *q0) { int i, j; // remove any references to this quad as a neighbor for(i = 0; i < count; i++ ) { CvCBQuad *q = quads[i]; for(j = 0; j < 4; j++ ) { if( q->neighbors[j] == q0 ) { q->neighbors[j] = 0; q->count--; for(int k = 0; k < 4; k++ ) if( q0->neighbors[k] == q ) { q0->neighbors[k] = 0; q0->count--; break; } break; } } } // remove the quad for(i = 0; i < count; i++ ) { CvCBQuad *q = quads[i]; if (q == q0) { quads[i] = quads[count-1]; break; } } } // // put quad into correct order, where <corner> has value <common> // static void icvOrderQuad(CvCBQuad *quad, CvCBCorner *corner, int common) { // find the corner int tc; for (tc=0; tc<4; tc++) if (quad->corners[tc]->pt.x == corner->pt.x && quad->corners[tc]->pt.y == corner->pt.y) break; // set corner order // shift while (tc != common) { // shift by one CvCBCorner *tempc; CvCBQuad *tempq; tempc = quad->corners[3]; tempq = quad->neighbors[3]; for (int i=3; i>0; i--) { quad->corners[i] = quad->corners[i-1]; quad->neighbors[i] = quad->neighbors[i-1]; } quad->corners[0] = tempc; quad->neighbors[0] = tempq; tc++; tc = tc%4; } } // if we found too many connect quads, remove those which probably do not belong. static int icvCleanFoundConnectedQuads( int quad_count, CvCBQuad **quad_group, CvSize pattern_size ) { CvPoint2D32f center; int i, j, k; // number of quads this pattern should contain int count = ((pattern_size.width + 1)*(pattern_size.height + 1) + 1)/2; // if we have more quadrangles than we should, // try to eliminate duplicates or ones which don't belong to the pattern rectangle... if( quad_count <= count ) return quad_count; // create an array of quadrangle centers cv::AutoBuffer<CvPoint2D32f> centers( quad_count ); cv::Ptr<CvMemStorage> temp_storage(cvCreateMemStorage(0)); for( i = 0; i < quad_count; i++ ) { CvPoint2D32f ci; CvCBQuad* q = quad_group[i]; for( j = 0; j < 4; j++ ) { CvPoint2D32f pt = q->corners[j]->pt; ci.x += pt.x; ci.y += pt.y; } ci.x *= 0.25f; ci.y *= 0.25f; centers[i] = ci; center.x += ci.x; center.y += ci.y; } center.x /= quad_count; center.y /= quad_count; // If we still have more quadrangles than we should, // we try to eliminate bad ones based on minimizing the bounding box. // We iteratively remove the point which reduces the size of // the bounding box of the blobs the most // (since we want the rectangle to be as small as possible) // remove the quadrange that causes the biggest reduction // in pattern size until we have the correct number for( ; quad_count > count; quad_count-- ) { double min_box_area = DBL_MAX; int skip, min_box_area_index = -1; // For each point, calculate box area without that point for( skip = 0; skip < quad_count; skip++ ) { // get bounding rectangle CvPoint2D32f temp = centers[skip]; // temporarily make index 'skip' the same as centers[skip] = center; // pattern center (so it is not counted for convex hull) CvMat pointMat = cvMat(1, quad_count, CV_32FC2, centers); CvSeq *hull = cvConvexHull2( &pointMat, temp_storage, CV_CLOCKWISE, 1 ); centers[skip] = temp; double hull_area = fabs(cvContourArea(hull, CV_WHOLE_SEQ)); // remember smallest box area if( hull_area < min_box_area ) { min_box_area = hull_area; min_box_area_index = skip; } cvClearMemStorage( temp_storage ); } CvCBQuad *q0 = quad_group[min_box_area_index]; // remove any references to this quad as a neighbor for( i = 0; i < quad_count; i++ ) { CvCBQuad *q = quad_group[i]; for( j = 0; j < 4; j++ ) { if( q->neighbors[j] == q0 ) { q->neighbors[j] = 0; q->count--; for( k = 0; k < 4; k++ ) if( q0->neighbors[k] == q ) { q0->neighbors[k] = 0; q0->count--; break; } break; } } } // remove the quad quad_count--; quad_group[min_box_area_index] = quad_group[quad_count]; centers[min_box_area_index] = centers[quad_count]; } return quad_count; } //===================================================================================== static int icvFindConnectedQuads( CvCBQuad *quad, int quad_count, CvCBQuad **out_group, int group_idx, CvMemStorage* storage ) { cv::Ptr<CvMemStorage> temp_storage(cvCreateChildMemStorage( storage )); CvSeq* stack = cvCreateSeq( 0, sizeof(*stack), sizeof(void*), temp_storage ); int i, count = 0; // Scan the array for a first unlabeled quad for( i = 0; i < quad_count; i++ ) { if( quad[i].count > 0 && quad[i].group_idx < 0) break; } // Recursively find a group of connected quads starting from the seed quad[i] if( i < quad_count ) { CvCBQuad* q = &quad[i]; cvSeqPush( stack, &q ); out_group[count++] = q; q->group_idx = group_idx; q->ordered = false; while( stack->total ) { cvSeqPop( stack, &q ); for( i = 0; i < 4; i++ ) { CvCBQuad *neighbor = q->neighbors[i]; if( neighbor && neighbor->count > 0 && neighbor->group_idx < 0 ) { cvSeqPush( stack, &neighbor ); out_group[count++] = neighbor; neighbor->group_idx = group_idx; neighbor->ordered = false; } } } } return count; } //===================================================================================== static int icvCheckQuadGroup( CvCBQuad **quad_group, int quad_count, CvCBCorner **out_corners, CvSize pattern_size ) { const int ROW1 = 1000000; const int ROW2 = 2000000; const int ROW_ = 3000000; int result = 0; int i, out_corner_count = 0, corner_count = 0; std::vector<CvCBCorner*> corners(quad_count*4); int j, k, kk; int width = 0, height = 0; int hist[5] = {0,0,0,0,0}; CvCBCorner* first = 0, *first2 = 0, *right, *cur, *below, *c; // build dual graph, which vertices are internal quad corners // and two vertices are connected iff they lie on the same quad edge for( i = 0; i < quad_count; i++ ) { CvCBQuad* q = quad_group[i]; /*CvScalar color = q->count == 0 ? cvScalar(0,255,255) : q->count == 1 ? cvScalar(0,0,255) : q->count == 2 ? cvScalar(0,255,0) : q->count == 3 ? cvScalar(255,255,0) : cvScalar(255,0,0);*/ for( j = 0; j < 4; j++ ) { //cvLine( debug_img, cvPointFrom32f(q->corners[j]->pt), cvPointFrom32f(q->corners[(j+1)&3]->pt), color, 1, CV_AA, 0 ); if( q->neighbors[j] ) { CvCBCorner *a = q->corners[j], *b = q->corners[(j+1)&3]; // mark internal corners that belong to: // - a quad with a single neighbor - with ROW1, // - a quad with two neighbors - with ROW2 // make the rest of internal corners with ROW_ int row_flag = q->count == 1 ? ROW1 : q->count == 2 ? ROW2 : ROW_; if( a->row == 0 ) { corners[corner_count++] = a; a->row = row_flag; } else if( a->row > row_flag ) a->row = row_flag; if( q->neighbors[(j+1)&3] ) { if( a->count >= 4 || b->count >= 4 ) goto finalize; for( k = 0; k < 4; k++ ) { if( a->neighbors[k] == b ) goto finalize; if( b->neighbors[k] == a ) goto finalize; } a->neighbors[a->count++] = b; b->neighbors[b->count++] = a; } } } } if( corner_count != pattern_size.width*pattern_size.height ) goto finalize; for( i = 0; i < corner_count; i++ ) { int n = corners[i]->count; assert( 0 <= n && n <= 4 ); hist[n]++; if( !first && n == 2 ) { if( corners[i]->row == ROW1 ) first = corners[i]; else if( !first2 && corners[i]->row == ROW2 ) first2 = corners[i]; } } // start with a corner that belongs to a quad with a signle neighbor. // if we do not have such, start with a corner of a quad with two neighbors. if( !first ) first = first2; if( !first || hist[0] != 0 || hist[1] != 0 || hist[2] != 4 || hist[3] != (pattern_size.width + pattern_size.height)*2 - 8 ) goto finalize; cur = first; right = below = 0; out_corners[out_corner_count++] = cur; for( k = 0; k < 4; k++ ) { c = cur->neighbors[k]; if( c ) { if( !right ) right = c; else if( !below ) below = c; } } if( !right || (right->count != 2 && right->count != 3) || !below || (below->count != 2 && below->count != 3) ) goto finalize; cur->row = 0; //cvCircle( debug_img, cvPointFrom32f(cur->pt), 3, cvScalar(0,255,0), -1, 8, 0 ); first = below; // remember the first corner in the next row // find and store the first row (or column) for(j=1;;j++) { right->row = 0; out_corners[out_corner_count++] = right; //cvCircle( debug_img, cvPointFrom32f(right->pt), 3, cvScalar(0,255-j*10,0), -1, 8, 0 ); if( right->count == 2 ) break; if( right->count != 3 || out_corner_count >= MAX(pattern_size.width,pattern_size.height) ) goto finalize; cur = right; for( k = 0; k < 4; k++ ) { c = cur->neighbors[k]; if( c && c->row > 0 ) { for( kk = 0; kk < 4; kk++ ) { if( c->neighbors[kk] == below ) break; } if( kk < 4 ) below = c; else right = c; } } } width = out_corner_count; if( width == pattern_size.width ) height = pattern_size.height; else if( width == pattern_size.height ) height = pattern_size.width; else goto finalize; // find and store all the other rows for( i = 1; ; i++ ) { if( !first ) break; cur = first; first = 0; for( j = 0;; j++ ) { cur->row = i; out_corners[out_corner_count++] = cur; //cvCircle( debug_img, cvPointFrom32f(cur->pt), 3, cvScalar(0,0,255-j*10), -1, 8, 0 ); if( cur->count == 2 + (i < height-1) && j > 0 ) break; right = 0; // find a neighbor that has not been processed yet // and that has a neighbor from the previous row for( k = 0; k < 4; k++ ) { c = cur->neighbors[k]; if( c && c->row > i ) { for( kk = 0; kk < 4; kk++ ) { if( c->neighbors[kk] && c->neighbors[kk]->row == i-1 ) break; } if( kk < 4 ) { right = c; if( j > 0 ) break; } else if( j == 0 ) first = c; } } if( !right ) goto finalize; cur = right; } if( j != width - 1 ) goto finalize; } if( out_corner_count != corner_count ) goto finalize; // check if we need to transpose the board if( width != pattern_size.width ) { CV_SWAP( width, height, k ); memcpy( &corners[0], out_corners, corner_count*sizeof(corners[0]) ); for( i = 0; i < height; i++ ) for( j = 0; j < width; j++ ) out_corners[i*width + j] = corners[j*height + i]; } // check if we need to revert the order in each row { CvPoint2D32f p0 = out_corners[0]->pt, p1 = out_corners[pattern_size.width-1]->pt, p2 = out_corners[pattern_size.width]->pt; if( (p1.x - p0.x)*(p2.y - p1.y) - (p1.y - p0.y)*(p2.x - p1.x) < 0 ) { if( width % 2 == 0 ) { for( i = 0; i < height; i++ ) for( j = 0; j < width/2; j++ ) CV_SWAP( out_corners[i*width+j], out_corners[i*width+width-j-1], c ); } else { for( j = 0; j < width; j++ ) for( i = 0; i < height/2; i++ ) CV_SWAP( out_corners[i*width+j], out_corners[(height - i - 1)*width+j], c ); } } } result = corner_count; finalize: if( result <= 0 ) { corner_count = MIN( corner_count, pattern_size.width*pattern_size.height ); for( i = 0; i < corner_count; i++ ) out_corners[i] = corners[i]; result = -corner_count; if (result == -pattern_size.width*pattern_size.height) result = -result; } return result; } //===================================================================================== static void icvFindQuadNeighbors( CvCBQuad *quads, int quad_count ) { const float thresh_scale = 1.f; int idx, i, k, j; float dx, dy, dist; // find quad neighbors for( idx = 0; idx < quad_count; idx++ ) { CvCBQuad* cur_quad = &quads[idx]; // choose the points of the current quadrangle that are close to // some points of the other quadrangles // (it can happen for split corners (due to dilation) of the // checker board). Search only in other quadrangles! // for each corner of this quadrangle for( i = 0; i < 4; i++ ) { CvPoint2D32f pt; float min_dist = FLT_MAX; int closest_corner_idx = -1; CvCBQuad *closest_quad = 0; CvCBCorner *closest_corner = 0; if( cur_quad->neighbors[i] ) continue; pt = cur_quad->corners[i]->pt; // find the closest corner in all other quadrangles for( k = 0; k < quad_count; k++ ) { if( k == idx ) continue; for( j = 0; j < 4; j++ ) { if( quads[k].neighbors[j] ) continue; dx = pt.x - quads[k].corners[j]->pt.x; dy = pt.y - quads[k].corners[j]->pt.y; dist = dx * dx + dy * dy; if( dist < min_dist && dist <= cur_quad->edge_len*thresh_scale && dist <= quads[k].edge_len*thresh_scale ) { // check edge lengths, make sure they're compatible // edges that are different by more than 1:4 are rejected float ediff = cur_quad->edge_len - quads[k].edge_len; if (ediff > 32*cur_quad->edge_len || ediff > 32*quads[k].edge_len) { PRINTF("Incompatible edge lengths\n"); continue; } closest_corner_idx = j; closest_quad = &quads[k]; min_dist = dist; } } } // we found a matching corner point? if( closest_corner_idx >= 0 && min_dist < FLT_MAX ) { // If another point from our current quad is closer to the found corner // than the current one, then we don't count this one after all. // This is necessary to support small squares where otherwise the wrong // corner will get matched to closest_quad; closest_corner = closest_quad->corners[closest_corner_idx]; for( j = 0; j < 4; j++ ) { if( cur_quad->neighbors[j] == closest_quad ) break; dx = closest_corner->pt.x - cur_quad->corners[j]->pt.x; dy = closest_corner->pt.y - cur_quad->corners[j]->pt.y; if( dx * dx + dy * dy < min_dist ) break; } if( j < 4 || cur_quad->count >= 4 || closest_quad->count >= 4 ) continue; // Check that each corner is a neighbor of different quads for( j = 0; j < closest_quad->count; j++ ) { if( closest_quad->neighbors[j] == cur_quad ) break; } if( j < closest_quad->count ) continue; // check whether the closest corner to closest_corner // is different from cur_quad->corners[i]->pt for( k = 0; k < quad_count; k++ ) { CvCBQuad* q = &quads[k]; if( k == idx || q == closest_quad ) continue; for( j = 0; j < 4; j++ ) if( !q->neighbors[j] ) { dx = closest_corner->pt.x - q->corners[j]->pt.x; dy = closest_corner->pt.y - q->corners[j]->pt.y; dist = dx*dx + dy*dy; if( dist < min_dist ) break; } if( j < 4 ) break; } if( k < quad_count ) continue; closest_corner->pt.x = (pt.x + closest_corner->pt.x) * 0.5f; closest_corner->pt.y = (pt.y + closest_corner->pt.y) * 0.5f; // We've found one more corner - remember it cur_quad->count++; cur_quad->neighbors[i] = closest_quad; cur_quad->corners[i] = closest_corner; closest_quad->count++; closest_quad->neighbors[closest_corner_idx] = cur_quad; } } } } //===================================================================================== // returns corners in clockwise order // corners don't necessarily start at same position on quad (e.g., // top left corner) static int icvGenerateQuads( CvCBQuad **out_quads, CvCBCorner **out_corners, CvMemStorage *storage, const cv::Mat & image_, int flags, int *max_quad_buf_size ) { CvMat image_old(image_), *image = &image_old; int quad_count = 0; cv::Ptr<CvMemStorage> temp_storage; if( out_quads ) *out_quads = 0; if( out_corners ) *out_corners = 0; CvSeq *src_contour = 0; CvSeq *root; CvContourEx* board = 0; CvContourScanner scanner; int i, idx, min_size; CV_Assert( out_corners && out_quads ); // empiric bound for minimal allowed perimeter for squares min_size = 25; //cvRound( image->cols * image->rows * .03 * 0.01 * 0.92 ); // create temporary storage for contours and the sequence of pointers to found quadrangles temp_storage.reset(cvCreateChildMemStorage( storage )); root = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvSeq*), temp_storage ); // initialize contour retrieving routine scanner = cvStartFindContours( image, temp_storage, sizeof(CvContourEx), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE ); // get all the contours one by one while( (src_contour = cvFindNextContour( scanner )) != 0 ) { CvSeq *dst_contour = 0; CvRect rect = ((CvContour*)src_contour)->rect; // reject contours with too small perimeter if( CV_IS_SEQ_HOLE(src_contour) && rect.width*rect.height >= min_size ) { const int min_approx_level = 1, max_approx_level = MAX_CONTOUR_APPROX; int approx_level; for( approx_level = min_approx_level; approx_level <= max_approx_level; approx_level++ ) { dst_contour = cvApproxPoly( src_contour, sizeof(CvContour), temp_storage, CV_POLY_APPROX_DP, (float)approx_level ); if( dst_contour->total == 4 ) break; // we call this again on its own output, because sometimes // cvApproxPoly() does not simplify as much as it should. dst_contour = cvApproxPoly( dst_contour, sizeof(CvContour), temp_storage, CV_POLY_APPROX_DP, (float)approx_level ); if( dst_contour->total == 4 ) break; } // reject non-quadrangles if( dst_contour->total == 4 && cvCheckContourConvexity(dst_contour) ) { CvPoint pt[4]; double d1, d2, p = cvContourPerimeter(dst_contour); double area = fabs(cvContourArea(dst_contour, CV_WHOLE_SEQ)); double dx, dy; for( i = 0; i < 4; i++ ) pt[i] = *(CvPoint*)cvGetSeqElem(dst_contour, i); dx = pt[0].x - pt[2].x; dy = pt[0].y - pt[2].y; d1 = sqrt(dx*dx + dy*dy); dx = pt[1].x - pt[3].x; dy = pt[1].y - pt[3].y; d2 = sqrt(dx*dx + dy*dy); // philipg. Only accept those quadrangles which are more square // than rectangular and which are big enough double d3, d4; dx = pt[0].x - pt[1].x; dy = pt[0].y - pt[1].y; d3 = sqrt(dx*dx + dy*dy); dx = pt[1].x - pt[2].x; dy = pt[1].y - pt[2].y; d4 = sqrt(dx*dx + dy*dy); if( !(flags & CV_CALIB_CB_FILTER_QUADS) || (d3*4 > d4 && d4*4 > d3 && d3*d4 < area*1.5 && area > min_size && d1 >= 0.15 * p && d2 >= 0.15 * p) ) { CvContourEx* parent = (CvContourEx*)(src_contour->v_prev); parent->counter++; if( !board || board->counter < parent->counter ) board = parent; dst_contour->v_prev = (CvSeq*)parent; //for( i = 0; i < 4; i++ ) cvLine( debug_img, pt[i], pt[(i+1)&3], cvScalar(200,255,255), 1, CV_AA, 0 ); cvSeqPush( root, &dst_contour ); } } } } // finish contour retrieving cvEndFindContours( &scanner ); // allocate quad & corner buffers *max_quad_buf_size = MAX(1, (root->total+root->total / 2)) * 2; *out_quads = (CvCBQuad*)cvAlloc(*max_quad_buf_size * sizeof((*out_quads)[0])); *out_corners = (CvCBCorner*)cvAlloc(*max_quad_buf_size * 4 * sizeof((*out_corners)[0])); // Create array of quads structures for( idx = 0; idx < root->total; idx++ ) { CvCBQuad* q = &(*out_quads)[quad_count]; src_contour = *(CvSeq**)cvGetSeqElem( root, idx ); if( (flags & CV_CALIB_CB_FILTER_QUADS) && src_contour->v_prev != (CvSeq*)board ) continue; // reset group ID memset( q, 0, sizeof(*q) ); q->group_idx = -1; assert( src_contour->total == 4 ); for( i = 0; i < 4; i++ ) { CvPoint * onePoint = (CvPoint*)cvGetSeqElem(src_contour, i); CV_Assert(onePoint != NULL); CvPoint2D32f pt = cvPointTo32f(*onePoint); CvCBCorner* corner = &(*out_corners)[quad_count*4 + i]; memset( corner, 0, sizeof(*corner) ); corner->pt = pt; q->corners[i] = corner; } q->edge_len = FLT_MAX; for( i = 0; i < 4; i++ ) { float dx = q->corners[i]->pt.x - q->corners[(i+1)&3]->pt.x; float dy = q->corners[i]->pt.y - q->corners[(i+1)&3]->pt.y; float d = dx*dx + dy*dy; if( q->edge_len > d ) q->edge_len = d; } quad_count++; } return quad_count; } static bool processQuads(CvCBQuad *quads, int quad_count, CvSize pattern_size, int max_quad_buf_size, CvMemStorage * storage, CvCBCorner *corners, CvPoint2D32f *out_corners, int *out_corner_count, int & prev_sqr_size) { if( quad_count <= 0 ) return false; bool found = false; // Find quad's neighbors icvFindQuadNeighbors( quads, quad_count ); // allocate extra for adding in icvOrderFoundQuads CvCBQuad **quad_group = 0; CvCBCorner **corner_group = 0; quad_group = (CvCBQuad**)cvAlloc( sizeof(quad_group[0]) * max_quad_buf_size); corner_group = (CvCBCorner**)cvAlloc( sizeof(corner_group[0]) * max_quad_buf_size * 4 ); for( int group_idx = 0; ; group_idx++ ) { int count = icvFindConnectedQuads( quads, quad_count, quad_group, group_idx, storage ); if( count == 0 ) break; // order the quad corners globally // maybe delete or add some PRINTF("Starting ordering of inner quads (%d)\n", count); count = icvOrderFoundConnectedQuads(count, quad_group, &quad_count, &quads, &corners, pattern_size, max_quad_buf_size, storage ); PRINTF("Finished ordering of inner quads (%d)\n", count); if (count == 0) continue; // haven't found inner quads // If count is more than it should be, this will remove those quads // which cause maximum deviation from a nice square pattern. count = icvCleanFoundConnectedQuads( count, quad_group, pattern_size ); PRINTF("Connected group: %d, count: %d\n", group_idx, count); count = icvCheckQuadGroup( quad_group, count, corner_group, pattern_size ); PRINTF("Connected group: %d, count: %d\n", group_idx, count); int n = count > 0 ? pattern_size.width * pattern_size.height : -count; n = MIN( n, pattern_size.width * pattern_size.height ); float sum_dist = 0; int total = 0; for(int i = 0; i < n; i++ ) { int ni = 0; float avgi = corner_group[i]->meanDist(&ni); sum_dist += avgi*ni; total += ni; } prev_sqr_size = cvRound(sum_dist/MAX(total, 1)); if( count > 0 || (out_corner_count && -count > *out_corner_count) ) { // copy corners to output array for(int i = 0; i < n; i++ ) out_corners[i] = corner_group[i]->pt; if( out_corner_count ) *out_corner_count = n; if( count == pattern_size.width*pattern_size.height && icvCheckBoardMonotony( out_corners, pattern_size )) { found = true; break; } } } cvFree(&quad_group); cvFree(&corner_group); return found; } //================================================================================================== CV_IMPL void cvDrawChessboardCorners( CvArr* _image, CvSize pattern_size, CvPoint2D32f* corners, int count, int found ) { const int shift = 0; const int radius = 4; const int r = radius*(1 << shift); int i; CvMat stub, *image; double scale = 1; int type, cn, line_type; image = cvGetMat( _image, &stub ); type = CV_MAT_TYPE(image->type); cn = CV_MAT_CN(type); if( cn != 1 && cn != 3 && cn != 4 ) CV_Error( CV_StsUnsupportedFormat, "Number of channels must be 1, 3 or 4" ); switch( CV_MAT_DEPTH(image->type) ) { case CV_8U: scale = 1; break; case CV_16U: scale = 256; break; case CV_32F: scale = 1./255; break; default: CV_Error( CV_StsUnsupportedFormat, "Only 8-bit, 16-bit or floating-point 32-bit images are supported" ); } line_type = type == CV_8UC1 || type == CV_8UC3 ? CV_AA : 8; if( !found ) { CvScalar color(0,0,255,0); if( cn == 1 ) color = cvScalarAll(200); color.val[0] *= scale; color.val[1] *= scale; color.val[2] *= scale; color.val[3] *= scale; for( i = 0; i < count; i++ ) { CvPoint pt; pt.x = cvRound(corners[i].x*(1 << shift)); pt.y = cvRound(corners[i].y*(1 << shift)); cvLine( image, cvPoint( pt.x - r, pt.y - r ), cvPoint( pt.x + r, pt.y + r ), color, 1, line_type, shift ); cvLine( image, cvPoint( pt.x - r, pt.y + r), cvPoint( pt.x + r, pt.y - r), color, 1, line_type, shift ); cvCircle( image, pt, r+(1<<shift), color, 1, line_type, shift ); } } else { int x, y; CvPoint prev_pt; const int line_max = 7; static const CvScalar line_colors[line_max] = { CvScalar(0,0,255), CvScalar(0,128,255), CvScalar(0,200,200), CvScalar(0,255,0), CvScalar(200,200,0), CvScalar(255,0,0), CvScalar(255,0,255) }; for( y = 0, i = 0; y < pattern_size.height; y++ ) { CvScalar color = line_colors[y % line_max]; if( cn == 1 ) color = cvScalarAll(200); color.val[0] *= scale; color.val[1] *= scale; color.val[2] *= scale; color.val[3] *= scale; for( x = 0; x < pattern_size.width; x++, i++ ) { CvPoint pt; pt.x = cvRound(corners[i].x*(1 << shift)); pt.y = cvRound(corners[i].y*(1 << shift)); if( i != 0 ) cvLine( image, prev_pt, pt, color, 1, line_type, shift ); cvLine( image, cvPoint(pt.x - r, pt.y - r), cvPoint(pt.x + r, pt.y + r), color, 1, line_type, shift ); cvLine( image, cvPoint(pt.x - r, pt.y + r), cvPoint(pt.x + r, pt.y - r), color, 1, line_type, shift ); cvCircle( image, pt, r+(1<<shift), color, 1, line_type, shift ); prev_pt = pt; } } } } bool cv::findChessboardCorners( InputArray _image, Size patternSize, OutputArray corners, int flags ) { CV_INSTRUMENT_REGION() int count = patternSize.area()*2; std::vector<Point2f> tmpcorners(count+1); Mat image = _image.getMat(); CvMat c_image = image; bool ok = cvFindChessboardCorners(&c_image, patternSize, (CvPoint2D32f*)&tmpcorners[0], &count, flags ) > 0; if( count > 0 ) { tmpcorners.resize(count); Mat(tmpcorners).copyTo(corners); } else corners.release(); return ok; } namespace { int quiet_error(int /*status*/, const char* /*func_name*/, const char* /*err_msg*/, const char* /*file_name*/, int /*line*/, void* /*userdata*/ ) { return 0; } } void cv::drawChessboardCorners( InputOutputArray _image, Size patternSize, InputArray _corners, bool patternWasFound ) { CV_INSTRUMENT_REGION() Mat corners = _corners.getMat(); if( corners.empty() ) return; Mat image = _image.getMat(); CvMat c_image = image; int nelems = corners.checkVector(2, CV_32F, true); CV_Assert(nelems >= 0); cvDrawChessboardCorners( &c_image, patternSize, corners.ptr<CvPoint2D32f>(), nelems, patternWasFound ); } bool cv::findCirclesGrid( InputArray image, Size patternSize, OutputArray centers, int flags, const Ptr<FeatureDetector> &blobDetector, CirclesGridFinderParameters parameters) { CirclesGridFinderParameters2 parameters2; *((CirclesGridFinderParameters*)&parameters2) = parameters; return cv::findCirclesGrid2(image, patternSize, centers, flags, blobDetector, parameters2); } bool cv::findCirclesGrid2( InputArray _image, Size patternSize, OutputArray _centers, int flags, const Ptr<FeatureDetector> &blobDetector, CirclesGridFinderParameters2 parameters) { CV_INSTRUMENT_REGION() bool isAsymmetricGrid = (flags & CALIB_CB_ASYMMETRIC_GRID) ? true : false; bool isSymmetricGrid = (flags & CALIB_CB_SYMMETRIC_GRID ) ? true : false; CV_Assert(isAsymmetricGrid ^ isSymmetricGrid); Mat image = _image.getMat(); std::vector<Point2f> centers; std::vector<KeyPoint> keypoints; blobDetector->detect(image, keypoints); std::vector<Point2f> points; for (size_t i = 0; i < keypoints.size(); i++) { points.push_back (keypoints[i].pt); } if(flags & CALIB_CB_ASYMMETRIC_GRID) parameters.gridType = CirclesGridFinderParameters::ASYMMETRIC_GRID; if(flags & CALIB_CB_SYMMETRIC_GRID) parameters.gridType = CirclesGridFinderParameters::SYMMETRIC_GRID; if(flags & CALIB_CB_CLUSTERING) { CirclesGridClusterFinder circlesGridClusterFinder(parameters); circlesGridClusterFinder.findGrid(points, patternSize, centers); Mat(centers).copyTo(_centers); return !centers.empty(); } const int attempts = 2; const size_t minHomographyPoints = 4; Mat H; for (int i = 0; i < attempts; i++) { centers.clear(); CirclesGridFinder boxFinder(patternSize, points, parameters); bool isFound = false; #define BE_QUIET 1 #if BE_QUIET void* oldCbkData; ErrorCallback oldCbk = redirectError(quiet_error, 0, &oldCbkData); #endif CV_TRY { isFound = boxFinder.findHoles(); } CV_CATCH(Exception, e) { CV_UNUSED(e); } #if BE_QUIET redirectError(oldCbk, oldCbkData); #endif if (isFound) { switch(parameters.gridType) { case CirclesGridFinderParameters::SYMMETRIC_GRID: boxFinder.getHoles(centers); break; case CirclesGridFinderParameters::ASYMMETRIC_GRID: boxFinder.getAsymmetricHoles(centers); break; default: CV_Error(CV_StsBadArg, "Unkown pattern type"); } if (i != 0) { Mat orgPointsMat; transform(centers, orgPointsMat, H.inv()); convertPointsFromHomogeneous(orgPointsMat, centers); } Mat(centers).copyTo(_centers); return true; } boxFinder.getHoles(centers); if (i != attempts - 1) { if (centers.size() < minHomographyPoints) break; H = CirclesGridFinder::rectifyGrid(boxFinder.getDetectedGridSize(), centers, points, points); } } Mat(centers).copyTo(_centers); return false; } bool cv::findCirclesGrid( InputArray _image, Size patternSize, OutputArray _centers, int flags, const Ptr<FeatureDetector> &blobDetector) { return cv::findCirclesGrid2(_image, patternSize, _centers, flags, blobDetector, CirclesGridFinderParameters2()); } /* End of file. */
using namespace std; #include<iostream> #include<stdio.h> int main() { int num; cin>>num; for(int i = 0;i<num;i++) { unsigned long long a, fact = 1; cin>>a; for(int i = 1;i<=a;i++) fact = fact*i; cout<<fact<<endl; } return 0; }
// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/tensor_game.h" #include <algorithm> #include <iomanip> #include <iostream> #include "open_spiel/spiel_utils.h" namespace open_spiel { namespace tensor_game { namespace { // Check the utilities to see if the game is constant-sum or identical // (cooperative). GameType::Utility GetUtilityType( const std::vector<std::vector<double>>& utils) { double util_sum = 0; // Assume both are true until proven otherwise. bool constant_sum = true; bool identical = true; for (int i = 0; i < utils[0].size(); ++i) { double util_sum_i = 0; for (int player = 0; player < utils.size(); ++player) { util_sum_i += utils[player][i]; } if (i == 0) { util_sum = util_sum_i; } else { if (constant_sum && !Near(util_sum_i, util_sum)) { constant_sum = false; } } if (identical) { for (int player = 1; player < utils.size(); ++player) { if (utils[0][i] != utils[player][i]) { identical = false; break; } } } } if (constant_sum && Near(util_sum, 0.0)) { return GameType::Utility::kZeroSum; } else if (constant_sum) { return GameType::Utility::kConstantSum; } else if (identical) { return GameType::Utility::kIdentical; } else { return GameType::Utility::kGeneralSum; } } } // namespace TensorState::TensorState(std::shared_ptr<const Game> game) : NFGState(game), tensor_game_(static_cast<const TensorGame*>(game.get())) {} std::string TensorState::ToString() const { std::string result = ""; absl::StrAppend(&result, "Terminal? ", IsTerminal() ? "true" : "false", "\n"); if (IsTerminal()) { absl::StrAppend(&result, "History: ", HistoryString(), "\n"); absl::StrAppend(&result, "Returns: ", absl::StrJoin(Returns(), ","), "\n"); } return result; } std::unique_ptr<State> TensorGame::NewInitialState() const { return std::unique_ptr<State>(new TensorState(shared_from_this())); } std::shared_ptr<const TensorGame> CreateTensorGame( const std::vector<std::vector<double>>& utils, const std::vector<int>& shape) { std::vector<std::vector<std::string>> action_names(shape.size()); for (Player player = 0; player < shape.size(); ++player) { for (int i = 0; i < shape[player]; ++i) { action_names[player].push_back(absl::StrCat("action", player, "_", i)); } } return CreateTensorGame("short_name", "Long Name", action_names, utils); } // Create a matrix game with the specified utilities and row/column names. // Utilities must be in row-major form. std::shared_ptr<const TensorGame> CreateTensorGame( const std::string& short_name, const std::string& long_name, const std::vector<std::vector<std::string>>& action_names, const std::vector<std::vector<double>>& utils) { const int size = std::accumulate(action_names.begin(), action_names.end(), 1, [](const int s, auto names) { return s * names.size(); }); SPIEL_CHECK_TRUE( std::all_of(utils.begin(), utils.end(), [size](const auto& player_utils) { return player_utils.size() == size; })); // Detect the utility type from the utilities. const GameType::Utility utility = GetUtilityType(utils); const GameType game_type{ /*short_name=*/short_name, /*long_name=*/long_name, GameType::Dynamics::kSimultaneous, GameType::ChanceMode::kDeterministic, GameType::Information::kOneShot, utility, GameType::RewardModel::kTerminal, /*max_num_players=*/static_cast<int>(utils.size()), /*min_num_players=*/static_cast<int>(utils.size()), /*provides_information_state_string=*/true, /*provides_information_state_tensor=*/true, /*provides_observation_string=*/false, /*provides_observation_tensor=*/false, /*parameter_specification=*/{} // no parameters }; return std::shared_ptr<const TensorGame>( new TensorGame(game_type, {}, action_names, utils)); } } // namespace tensor_game } // namespace open_spiel
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #include "ppl/cv/cuda/mean.h" #include <tuple> #include <sstream> #include "opencv2/core.hpp" #include "gtest/gtest.h" #include "infrastructure.hpp" enum MaskType { kUnmasked, kMasked, }; using Parameters = std::tuple<MaskType, cv::Size>; inline std::string convertToStringMean(const Parameters& parameters) { std::ostringstream formatted; MaskType is_masked = std::get<0>(parameters); if (is_masked == kUnmasked) { formatted << "Unmasked" << "_"; } else { formatted << "Masked" << "_"; } cv::Size size = std::get<1>(parameters); formatted << size.width << "x"; formatted << size.height; return formatted.str(); } template <typename T, int channels> class PplCvCudaMeanTest : public ::testing::TestWithParam<Parameters> { public: PplCvCudaMeanTest() { const Parameters& parameters = GetParam(); is_masked = std::get<0>(parameters); size = std::get<1>(parameters); } ~PplCvCudaMeanTest() { } bool apply(); private: MaskType is_masked; cv::Size size; }; template <typename T, int channels> bool PplCvCudaMeanTest<T, channels>::apply() { cv::Mat src, mask0; src = createSourceImage(size.height, size.width, CV_MAKETYPE(cv::DataType<T>::depth, channels)); mask0 = createSourceImage(size.height, size.width, CV_MAKETYPE(cv::DataType<uchar>::depth, 1)); cv::cuda::GpuMat gpu_src(src); cv::cuda::GpuMat gpu_mask0(mask0); int dst_size = channels * sizeof(float); float* dst = (float*)malloc(dst_size); float* gpu_dst; cudaMalloc((void**)&gpu_dst, dst_size); int src_size = size.height * size.width * channels * sizeof(T); int mask_size = size.height * size.width * sizeof(uchar); T* input = (T*)malloc(src_size); uchar* mask1 = (uchar*)malloc(mask_size); float* output = (float*)malloc(dst_size); T* gpu_input; uchar* gpu_mask1; float* gpu_output; cudaMalloc((void**)&gpu_input, src_size); cudaMalloc((void**)&gpu_mask1, mask_size); cudaMalloc((void**)&gpu_output, dst_size); copyMatToArray(src, input); copyMatToArray(mask0, mask1); cudaMemcpy(gpu_input, input, src_size, cudaMemcpyHostToDevice); cudaMemcpy(gpu_mask1, mask1, mask_size, cudaMemcpyHostToDevice); cv::Scalar cv_mean; if (is_masked == kUnmasked) { cv_mean = cv::mean(src); ppl::cv::cuda::Mean<T, channels>(0, gpu_src.rows, gpu_src.cols, gpu_src.step / sizeof(T), (T*)gpu_src.data, gpu_dst, 0, nullptr); cudaMemcpy(dst, gpu_dst, dst_size, cudaMemcpyDeviceToHost); ppl::cv::cuda::Mean<T, channels>(0, size.height, size.width, size.width * channels, gpu_input, gpu_output, 0, nullptr); cudaMemcpy(output, gpu_output, dst_size, cudaMemcpyDeviceToHost); } else { cv_mean = cv::mean(src, mask0); ppl::cv::cuda::Mean<T, channels>(0, gpu_src.rows, gpu_src.cols, gpu_src.step / sizeof(T), (T*)gpu_src.data, gpu_dst, gpu_mask0.step / sizeof(uchar), (uchar*)gpu_mask0.data); cudaMemcpy(dst, gpu_dst, dst_size, cudaMemcpyDeviceToHost); ppl::cv::cuda::Mean<T, channels>(0, size.height, size.width, size.width * channels, gpu_input, gpu_output, size.width, gpu_mask1); cudaMemcpy(output, gpu_output, dst_size, cudaMemcpyDeviceToHost); } float epsilon = EPSILON_1F; bool identity = true; for (int i = 0; i < channels; i++) { if (fabs(cv_mean.val[i] - dst[i]) > epsilon || fabs(cv_mean.val[i] - output[i]) > epsilon) { identity = false; } } free(dst); free(input); free(mask1); free(output); cudaFree(gpu_dst); cudaFree(gpu_input); cudaFree(gpu_mask1); cudaFree(gpu_output); return identity; } #define UNITTEST(T, channels) \ using PplCvCudaMeanTest ## T ## channels = PplCvCudaMeanTest<T, channels>; \ TEST_P(PplCvCudaMeanTest ## T ## channels, Standard) { \ bool identity = this->apply(); \ EXPECT_TRUE(identity); \ } \ \ INSTANTIATE_TEST_CASE_P(IsEqual, PplCvCudaMeanTest ## T ## channels, \ ::testing::Combine( \ ::testing::Values(kUnmasked, kMasked), \ ::testing::Values(cv::Size{321, 240}, cv::Size{642, 480}, \ cv::Size{1283, 720}, cv::Size{1934, 1080}, \ cv::Size{320, 240}, cv::Size{640, 480}, \ cv::Size{1280, 720}, cv::Size{1920, 1080})), \ [](const testing::TestParamInfo< \ PplCvCudaMeanTest ## T ## channels::ParamType>& info) { \ return convertToStringMean(info.param); \ } \ ); UNITTEST(uchar, 1) UNITTEST(uchar, 3) UNITTEST(uchar, 4) UNITTEST(float, 1) UNITTEST(float, 3) UNITTEST(float, 4)
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrAtlasTextContext.h" #include "GrContext.h" #include "GrDrawContext.h" #include "GrTextBlobCache.h" #include "GrTextUtils.h" #include "SkDraw.h" #include "SkDrawFilter.h" #include "SkGrPriv.h" GrAtlasTextContext::GrAtlasTextContext() : fDistanceAdjustTable(new GrDistanceFieldAdjustTable) { } GrAtlasTextContext* GrAtlasTextContext::Create() { return new GrAtlasTextContext(); } bool GrAtlasTextContext::canDraw(const SkPaint& skPaint, const SkMatrix& viewMatrix, const SkSurfaceProps& props, const GrShaderCaps& shaderCaps) { return GrTextUtils::CanDrawAsDistanceFields(skPaint, viewMatrix, props, shaderCaps) || !SkDraw::ShouldDrawTextAsPaths(skPaint, viewMatrix); } GrColor GrAtlasTextContext::ComputeCanonicalColor(const SkPaint& paint, bool lcd) { GrColor canonicalColor = paint.computeLuminanceColor(); if (lcd) { // This is the correct computation, but there are tons of cases where LCD can be overridden. // For now we just regenerate if any run in a textblob has LCD. // TODO figure out where all of these overrides are and see if we can incorporate that logic // at a higher level *OR* use sRGB SkASSERT(false); //canonicalColor = SkMaskGamma::CanonicalColor(canonicalColor); } else { // A8, though can have mixed BMP text but it shouldn't matter because BMP text won't have // gamma corrected masks anyways, nor color U8CPU lum = SkComputeLuminance(SkColorGetR(canonicalColor), SkColorGetG(canonicalColor), SkColorGetB(canonicalColor)); // reduce to our finite number of bits canonicalColor = SkMaskGamma::CanonicalColor(SkColorSetRGB(lum, lum, lum)); } return canonicalColor; } uint32_t GrAtlasTextContext::ComputeScalerContextFlags(GrDrawContext* dc) { // If we're doing gamma-correct rendering, then we can disable the gamma hacks. // Otherwise, leave them on. In either case, we still want the contrast boost: if (dc->isGammaCorrect()) { return SkPaint::kBoostContrast_ScalerContextFlag; } else { return SkPaint::kFakeGammaAndBoostContrast_ScalerContextFlags; } } // TODO if this function ever shows up in profiling, then we can compute this value when the // textblob is being built and cache it. However, for the time being textblobs mostly only have 1 // run so this is not a big deal to compute here. bool GrAtlasTextContext::HasLCD(const SkTextBlob* blob) { SkTextBlobRunIterator it(blob); for (; !it.done(); it.next()) { if (it.isLCD()) { return true; } } return false; } void GrAtlasTextContext::drawTextBlob(GrContext* context, GrDrawContext* dc, const GrClip& clip, const SkPaint& skPaint, const SkMatrix& viewMatrix, const SkSurfaceProps& props, const SkTextBlob* blob, SkScalar x, SkScalar y, SkDrawFilter* drawFilter, const SkIRect& clipBounds) { // If we have been abandoned, then don't draw if (context->abandoned()) { return; } SkAutoTUnref<GrAtlasTextBlob> cacheBlob; SkMaskFilter::BlurRec blurRec; GrAtlasTextBlob::Key key; // It might be worth caching these things, but its not clear at this time // TODO for animated mask filters, this will fill up our cache. We need a safeguard here const SkMaskFilter* mf = skPaint.getMaskFilter(); bool canCache = !(skPaint.getPathEffect() || (mf && !mf->asABlur(&blurRec)) || drawFilter); uint32_t scalerContextFlags = ComputeScalerContextFlags(dc); GrTextBlobCache* cache = context->getTextBlobCache(); if (canCache) { bool hasLCD = HasLCD(blob); // We canonicalize all non-lcd draws to use kUnknown_SkPixelGeometry SkPixelGeometry pixelGeometry = hasLCD ? props.pixelGeometry() : kUnknown_SkPixelGeometry; // TODO we want to figure out a way to be able to use the canonical color on LCD text, // see the note on ComputeCanonicalColor above. We pick a dummy value for LCD text to // ensure we always match the same key GrColor canonicalColor = hasLCD ? SK_ColorTRANSPARENT : ComputeCanonicalColor(skPaint, hasLCD); key.fPixelGeometry = pixelGeometry; key.fUniqueID = blob->uniqueID(); key.fStyle = skPaint.getStyle(); key.fHasBlur = SkToBool(mf); key.fCanonicalColor = canonicalColor; key.fScalerContextFlags = scalerContextFlags; cacheBlob.reset(SkSafeRef(cache->find(key))); } // Though for the time being runs in the textblob can override the paint, they only touch font // info. GrPaint grPaint; if (!SkPaintToGrPaint(context, skPaint, viewMatrix, props.isGammaCorrect(), &grPaint)) { return; } if (cacheBlob) { if (cacheBlob->mustRegenerate(skPaint, grPaint.getColor(), blurRec, viewMatrix, x, y)) { // We have to remake the blob because changes may invalidate our masks. // TODO we could probably get away reuse most of the time if the pointer is unique, // but we'd have to clear the subrun information cache->remove(cacheBlob); cacheBlob.reset(SkRef(cache->createCachedBlob(blob, key, blurRec, skPaint))); RegenerateTextBlob(cacheBlob, context->getBatchFontCache(), *context->caps()->shaderCaps(), skPaint, grPaint.getColor(), scalerContextFlags, viewMatrix, props, blob, x, y, drawFilter); } else { cache->makeMRU(cacheBlob); if (CACHE_SANITY_CHECK) { int glyphCount = 0; int runCount = 0; GrTextBlobCache::BlobGlyphCount(&glyphCount, &runCount, blob); SkAutoTUnref<GrAtlasTextBlob> sanityBlob(cache->createBlob(glyphCount, runCount)); sanityBlob->setupKey(key, blurRec, skPaint); RegenerateTextBlob(sanityBlob, context->getBatchFontCache(), *context->caps()->shaderCaps(), skPaint, grPaint.getColor(), scalerContextFlags, viewMatrix, props, blob, x, y, drawFilter); GrAtlasTextBlob::AssertEqual(*sanityBlob, *cacheBlob); } } } else { if (canCache) { cacheBlob.reset(SkRef(cache->createCachedBlob(blob, key, blurRec, skPaint))); } else { cacheBlob.reset(cache->createBlob(blob)); } RegenerateTextBlob(cacheBlob, context->getBatchFontCache(), *context->caps()->shaderCaps(), skPaint, grPaint.getColor(), scalerContextFlags, viewMatrix, props, blob, x, y, drawFilter); } cacheBlob->flushCached(context, dc, blob, props, fDistanceAdjustTable, skPaint, grPaint, drawFilter, clip, viewMatrix, clipBounds, x, y); } void GrAtlasTextContext::RegenerateTextBlob(GrAtlasTextBlob* cacheBlob, GrBatchFontCache* fontCache, const GrShaderCaps& shaderCaps, const SkPaint& skPaint, GrColor color, uint32_t scalerContextFlags, const SkMatrix& viewMatrix, const SkSurfaceProps& props, const SkTextBlob* blob, SkScalar x, SkScalar y, SkDrawFilter* drawFilter) { cacheBlob->initReusableBlob(color, viewMatrix, x, y); // Regenerate textblob SkPaint runPaint = skPaint; SkTextBlobRunIterator it(blob); for (int run = 0; !it.done(); it.next(), run++) { int glyphCount = it.glyphCount(); size_t textLen = glyphCount * sizeof(uint16_t); const SkPoint& offset = it.offset(); // applyFontToPaint() always overwrites the exact same attributes, // so it is safe to not re-seed the paint for this reason. it.applyFontToPaint(&runPaint); if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) { // A false return from filter() means we should abort the current draw. runPaint = skPaint; continue; } runPaint.setFlags(GrTextUtils::FilterTextFlags(props, runPaint)); cacheBlob->push_back_run(run); if (GrTextUtils::CanDrawAsDistanceFields(runPaint, viewMatrix, props, shaderCaps)) { switch (it.positioning()) { case SkTextBlob::kDefault_Positioning: { GrTextUtils::DrawDFText(cacheBlob, run, fontCache, props, runPaint, color, scalerContextFlags, viewMatrix, (const char *)it.glyphs(), textLen, x + offset.x(), y + offset.y()); break; } case SkTextBlob::kHorizontal_Positioning: { SkPoint dfOffset = SkPoint::Make(x, y + offset.y()); GrTextUtils::DrawDFPosText(cacheBlob, run, fontCache, props, runPaint, color, scalerContextFlags, viewMatrix, (const char*)it.glyphs(), textLen, it.pos(), 1, dfOffset); break; } case SkTextBlob::kFull_Positioning: { SkPoint dfOffset = SkPoint::Make(x, y); GrTextUtils::DrawDFPosText(cacheBlob, run, fontCache, props, runPaint, color, scalerContextFlags, viewMatrix, (const char*)it.glyphs(), textLen, it.pos(), 2, dfOffset); break; } } } else if (SkDraw::ShouldDrawTextAsPaths(runPaint, viewMatrix)) { cacheBlob->setRunDrawAsPaths(run); } else { switch (it.positioning()) { case SkTextBlob::kDefault_Positioning: GrTextUtils::DrawBmpText(cacheBlob, run, fontCache, props, runPaint, color, scalerContextFlags, viewMatrix, (const char *)it.glyphs(), textLen, x + offset.x(), y + offset.y()); break; case SkTextBlob::kHorizontal_Positioning: GrTextUtils::DrawBmpPosText(cacheBlob, run, fontCache, props, runPaint, color, scalerContextFlags, viewMatrix, (const char*)it.glyphs(), textLen, it.pos(), 1, SkPoint::Make(x, y + offset.y())); break; case SkTextBlob::kFull_Positioning: GrTextUtils::DrawBmpPosText(cacheBlob, run, fontCache, props, runPaint, color, scalerContextFlags, viewMatrix, (const char*)it.glyphs(), textLen, it.pos(), 2, SkPoint::Make(x, y)); break; } } if (drawFilter) { // A draw filter may change the paint arbitrarily, so we must re-seed in this case. runPaint = skPaint; } } } inline GrAtlasTextBlob* GrAtlasTextContext::CreateDrawTextBlob(GrTextBlobCache* blobCache, GrBatchFontCache* fontCache, const GrShaderCaps& shaderCaps, const GrPaint& paint, const SkPaint& skPaint, uint32_t scalerContextFlags, const SkMatrix& viewMatrix, const SkSurfaceProps& props, const char text[], size_t byteLength, SkScalar x, SkScalar y) { int glyphCount = skPaint.countText(text, byteLength); GrAtlasTextBlob* blob = blobCache->createBlob(glyphCount, 1); blob->initThrowawayBlob(viewMatrix, x, y); if (GrTextUtils::CanDrawAsDistanceFields(skPaint, viewMatrix, props, shaderCaps)) { GrTextUtils::DrawDFText(blob, 0, fontCache, props, skPaint, paint.getColor(), scalerContextFlags, viewMatrix, text, byteLength, x, y); } else { GrTextUtils::DrawBmpText(blob, 0, fontCache, props, skPaint, paint.getColor(), scalerContextFlags, viewMatrix, text, byteLength, x, y); } return blob; } inline GrAtlasTextBlob* GrAtlasTextContext::CreateDrawPosTextBlob(GrTextBlobCache* blobCache, GrBatchFontCache* fontCache, const GrShaderCaps& shaderCaps, const GrPaint& paint, const SkPaint& skPaint, uint32_t scalerContextFlags, const SkMatrix& viewMatrix, const SkSurfaceProps& props, const char text[], size_t byteLength, const SkScalar pos[], int scalarsPerPosition, const SkPoint& offset) { int glyphCount = skPaint.countText(text, byteLength); GrAtlasTextBlob* blob = blobCache->createBlob(glyphCount, 1); blob->initThrowawayBlob(viewMatrix, offset.x(), offset.y()); if (GrTextUtils::CanDrawAsDistanceFields(skPaint, viewMatrix, props, shaderCaps)) { GrTextUtils::DrawDFPosText(blob, 0, fontCache, props, skPaint, paint.getColor(), scalerContextFlags, viewMatrix, text, byteLength, pos, scalarsPerPosition, offset); } else { GrTextUtils::DrawBmpPosText(blob, 0, fontCache, props, skPaint, paint.getColor(), scalerContextFlags, viewMatrix, text, byteLength, pos, scalarsPerPosition, offset); } return blob; } void GrAtlasTextContext::drawText(GrContext* context, GrDrawContext* dc, const GrClip& clip, const GrPaint& paint, const SkPaint& skPaint, const SkMatrix& viewMatrix, const SkSurfaceProps& props, const char text[], size_t byteLength, SkScalar x, SkScalar y, const SkIRect& regionClipBounds) { if (context->abandoned()) { return; } else if (this->canDraw(skPaint, viewMatrix, props, *context->caps()->shaderCaps())) { SkAutoTUnref<GrAtlasTextBlob> blob( CreateDrawTextBlob(context->getTextBlobCache(), context->getBatchFontCache(), *context->caps()->shaderCaps(), paint, skPaint, ComputeScalerContextFlags(dc), viewMatrix, props, text, byteLength, x, y)); blob->flushThrowaway(context, dc, props, fDistanceAdjustTable, skPaint, paint, clip, viewMatrix, regionClipBounds, x, y); return; } // fall back to drawing as a path GrTextUtils::DrawTextAsPath(context, dc, clip, skPaint, viewMatrix, text, byteLength, x, y, regionClipBounds); } void GrAtlasTextContext::drawPosText(GrContext* context, GrDrawContext* dc, const GrClip& clip, const GrPaint& paint, const SkPaint& skPaint, const SkMatrix& viewMatrix, const SkSurfaceProps& props, const char text[], size_t byteLength, const SkScalar pos[], int scalarsPerPosition, const SkPoint& offset, const SkIRect& regionClipBounds) { if (context->abandoned()) { return; } else if (this->canDraw(skPaint, viewMatrix, props, *context->caps()->shaderCaps())) { SkAutoTUnref<GrAtlasTextBlob> blob( CreateDrawPosTextBlob(context->getTextBlobCache(), context->getBatchFontCache(), *context->caps()->shaderCaps(), paint, skPaint, ComputeScalerContextFlags(dc), viewMatrix, props, text, byteLength, pos, scalarsPerPosition, offset)); blob->flushThrowaway(context, dc, props, fDistanceAdjustTable, skPaint, paint, clip, viewMatrix, regionClipBounds, offset.fX, offset.fY); return; } // fall back to drawing as a path GrTextUtils::DrawPosTextAsPath(context, dc, props, clip, skPaint, viewMatrix, text, byteLength, pos, scalarsPerPosition, offset, regionClipBounds); } /////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef GR_TEST_UTILS DRAW_BATCH_TEST_DEFINE(TextBlobBatch) { static uint32_t gContextID = SK_InvalidGenID; static GrAtlasTextContext* gTextContext = nullptr; static SkSurfaceProps gSurfaceProps(SkSurfaceProps::kLegacyFontHost_InitType); if (context->uniqueID() != gContextID) { gContextID = context->uniqueID(); delete gTextContext; gTextContext = GrAtlasTextContext::Create(); } // Setup dummy SkPaint / GrPaint GrColor color = GrRandomColor(random); SkMatrix viewMatrix = GrTest::TestMatrixInvertible(random); SkPaint skPaint; skPaint.setColor(color); skPaint.setLCDRenderText(random->nextBool()); skPaint.setAntiAlias(skPaint.isLCDRenderText() ? true : random->nextBool()); skPaint.setSubpixelText(random->nextBool()); GrPaint grPaint; if (!SkPaintToGrPaint(context, skPaint, viewMatrix, gSurfaceProps.isGammaCorrect(), &grPaint)) { SkFAIL("couldn't convert paint\n"); } const char* text = "The quick brown fox jumps over the lazy dog."; int textLen = (int)strlen(text); // create some random x/y offsets, including negative offsets static const int kMaxTrans = 1024; int xPos = (random->nextU() % 2) * 2 - 1; int yPos = (random->nextU() % 2) * 2 - 1; int xInt = (random->nextU() % kMaxTrans) * xPos; int yInt = (random->nextU() % kMaxTrans) * yPos; SkScalar x = SkIntToScalar(xInt); SkScalar y = SkIntToScalar(yInt); // right now we don't handle textblobs, nor do we handle drawPosText. Since we only // intend to test the batch with this unit test, that is okay. SkAutoTUnref<GrAtlasTextBlob> blob( GrAtlasTextContext::CreateDrawTextBlob(context->getTextBlobCache(), context->getBatchFontCache(), *context->caps()->shaderCaps(), grPaint, skPaint, GrAtlasTextContext::kTextBlobBatchScalerContextFlags, viewMatrix, gSurfaceProps, text, static_cast<size_t>(textLen), x, y)); return blob->test_createBatch(textLen, 0, 0, viewMatrix, x, y, color, skPaint, gSurfaceProps, gTextContext->dfAdjustTable(), context->getBatchFontCache()); } #endif
/** * ============================================================================ * * Copyright (C) 2019, Huawei Technologies Co., Ltd. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1 Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2 Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3 Neither the names of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ============================================================================ */ #include "VDecEngine.h" #include "SampleMemory.h" #include "app_common.h" #include "hiaiengine/log.h" #include <sys/stat.h> #include <unistd.h> #include <hiaiengine/api.h> #include "dvpp/idvppapi.h" #include "dvpp/Vpc.h" HIAI_REGISTER_SERIALIZE_FUNC("EngineTransNewT", EngineTransNewT, GetTransSearPtr, GetTransDearPtr); HIAI_REGISTER_SERIALIZE_FUNC("StreamRawData", StreamRawData, GetStreamRawDataSearPtr, GetStreamRawDataDearPtr); using Stat = struct stat; const static int NUM_TWO = 2; const static int NUM_THREE = 3; const static int BIT_DEPTH8 = 8; HIAI_StatusT VDecEngine::Init(const hiai::AIConfig& config, const std::vector<hiai::AIModelDescription>& model_desc) { HIAI_ENGINE_LOG(HIAI_IDE_INFO, "[VDecEngine] init start."); if (pVdecHandle == NULL) { int ret = CreateVdecApi(pVdecHandle, 0); if (ret != 0 || pVdecHandle == NULL) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "pVdecHandle is null."); return HIAI_ERROR; } } if (pDvppHandle == NULL) { int ret = CreateDvppApi(pDvppHandle); if (ret != 0 || pDvppHandle == NULL) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "pDvppHandle is null."); } } vdecInMsg.call_back = VDecEngine::FrameCallback; HIAI_ENGINE_LOG(HIAI_IDE_INFO, "[VDecEngine] init is finished."); return HIAI_OK; } VDecEngine::~VDecEngine() { if (pVdecHandle != NULL) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "destroy dvpp api!"); DestroyVdecApi(pVdecHandle, 0); pVdecHandle = NULL; } if (pDvppHandle != NULL) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "destroy dvpp api!"); DestroyDvppApi(pDvppHandle); pDvppHandle = NULL; } } HIAI_StatusT VDecEngine::Hfbc2YuvNew(FRAME *frame, uint8_t *outputBuffer) { if (pDvppHandle == NULL) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "[VDecEngine::Hfbc2YuvNew] pDvppHandle is NULL\n"); return HIAI_ERROR; } std::shared_ptr<VpcUserImageConfigure> userImage(new VpcUserImageConfigure); userImage->bareDataAddr = nullptr; userImage->bareDataBufferSize = 0; userImage->widthStride = frame->width; userImage->heightStride = frame->height; string imageFormat(frame->image_format); if (frame->bitdepth == BIT_DEPTH8) { if (imageFormat == "nv12") { userImage->inputFormat = INPUT_YUV420_SEMI_PLANNER_UV; } else { userImage->inputFormat = INPUT_YUV420_SEMI_PLANNER_VU; } } else { if (imageFormat == "nv12") { userImage->inputFormat = INPUT_YUV420_SEMI_PLANNER_UV_10BIT; } else { userImage->inputFormat = INPUT_YUV420_SEMI_PLANNER_VU_10BIT; } } userImage->outputFormat = OUTPUT_YUV420SP_UV; userImage->isCompressData = true; VpcCompressDataConfigure* compressDataConfigure = &userImage->compressDataConfigure; uintptr_t baseAddr = (uintptr_t)frame->buffer; compressDataConfigure->lumaHeadAddr = baseAddr + frame->offset_head_y; compressDataConfigure->chromaHeadAddr = baseAddr + frame->offset_head_c; compressDataConfigure->lumaPayloadAddr = baseAddr + frame->offset_payload_y; compressDataConfigure->chromaPayloadAddr = baseAddr + frame->offset_payload_c; compressDataConfigure->lumaHeadStride = frame->stride_head; compressDataConfigure->chromaHeadStride = frame->stride_head; compressDataConfigure->lumaPayloadStride = frame->stride_payload; compressDataConfigure->chromaPayloadStride = frame->stride_payload; userImage->yuvSumEnable = false; userImage->cmdListBufferAddr = nullptr; userImage->cmdListBufferSize = 0; std::shared_ptr<VpcUserRoiConfigure> roiConfigure(new VpcUserRoiConfigure); roiConfigure->next = nullptr; userImage->roiConfigure = roiConfigure.get(); VpcUserRoiInputConfigure* roiInput = &roiConfigure->inputConfigure; roiInput->cropArea.leftOffset = 0; roiInput->cropArea.rightOffset = (frame->width % NUM_TWO) ? frame->width : (frame->width - 1); roiInput->cropArea.upOffset = 0; roiInput->cropArea.downOffset = (frame->height % NUM_TWO) ? frame->height : (frame->height - 1); VpcUserRoiOutputConfigure* roiOutput = &roiConfigure->outputConfigure; roiOutput->outputArea.leftOffset = 0; roiOutput->outputArea.rightOffset = (frame->width % NUM_TWO) ? frame->width : (frame->width - 1); roiOutput->outputArea.upOffset = 0; roiOutput->outputArea.downOffset = (frame->height % NUM_TWO) ? frame->height : (frame->height - 1); roiOutput->widthStride = ALIGN_UP(frame->width, DVPP_STRIDE_WIDTH); roiOutput->heightStride = ALIGN_UP(frame->height, DVPP_STRIDE_HEIGHT); roiOutput->bufferSize = roiOutput->widthStride * roiOutput->heightStride * NUM_THREE / NUM_TWO; roiOutput->addr = outputBuffer; roiInput->cropArea = roiConfigure->inputConfigure.cropArea; dvppapi_ctl_msg dvppApiCtlMsg; dvppApiCtlMsg.in = static_cast<void *>(userImage.get()); dvppApiCtlMsg.in_size = sizeof(VpcUserImageConfigure); int ret = DvppCtl(pDvppHandle, DVPP_CTL_VPC_PROC, &dvppApiCtlMsg); if (ret != 0) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "[VDecEngine::Hfbc2YuvNew] call dvppctl fail\n"); hiai::HIAIMemory::HIAI_DVPP_DFree(roiOutput->addr); DestroyDvppApi(pDvppHandle); return HIAI_ERROR; } return HIAI_OK; } void VDecEngine::FrameCallback(FRAME* frame, void* hiaiData) { VDecEngine* vedcPtr = NULL; if (hiaiData != NULL) { vedcPtr = static_cast<VDecEngine*>(hiaiData); } else { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "hiaiData is NULL"); return; } uint8_t *outputBuffer = nullptr; uint32_t widthStride = ALIGN_UP(frame->width, DVPP_STRIDE_WIDTH); uint32_t heightStride = ALIGN_UP(frame->height, DVPP_STRIDE_HEIGHT); uint32_t bufferSize = widthStride * heightStride * NUM_THREE / NUM_TWO; vedcPtr->inputInfo.width = widthStride; vedcPtr->inputInfo.height = heightStride; HIAI_StatusT ret = hiai::HIAIMemory::HIAI_DVPP_DMalloc(bufferSize, (void *&)outputBuffer); // call vpc interface to decompress hfbc vedcPtr->Hfbc2YuvNew(frame, outputBuffer); std::shared_ptr<StreamRawData> out = std::make_shared<StreamRawData>(); out->info = vedcPtr->inputInfo; out->info.isEOS = 0; out->buf.transBuff = std::shared_ptr<uint8_t>(reinterpret_cast<uint8_t*>(outputBuffer), Sample_DFree); out->buf.bufferSize = bufferSize; ret = vedcPtr->SendData(0, "StreamRawData", std::static_pointer_cast<void>(out)); if (ret != HIAI_OK) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "send_data failed! ret = %d", ret); return; } } HIAI_IMPL_ENGINE_PROCESS("VDecEngine", VDecEngine, VD_INPUT_SIZE) { HIAI_ENGINE_LOG(HIAI_IDE_INFO, "[VDecEngine] VDecEngine process start!"); std::shared_ptr<StreamRawData> inputArg = std::static_pointer_cast<StreamRawData>(arg0); // if use hiai vdecInMsg.hiai_data = this; inputInfo = inputArg->info; vdecInMsg.channelId = inputArg->info.channelId; if (inputArg->info.isEOS == 1) { vdecInMsg.isEOS = 1; } else { if (inputArg->info.format == H264) { strncpy_s(vdecInMsg.video_format, sizeof(vdecInMsg.video_format), "h264", 4); } else { strncpy_s(vdecInMsg.video_format, sizeof(vdecInMsg.video_format), "h265", 4); } vdecInMsg.in_buffer_size = inputArg->buf.bufferSize; vdecInMsg.in_buffer = reinterpret_cast<char*>(inputArg->buf.transBuff.get()); vdecInMsg.isEOS = 0; } dvppapi_ctl_msg MSG; MSG.in_size = sizeof(vdec_in_msg); MSG.in = reinterpret_cast<void*>(&vdecInMsg); int ret = VdecCtl(pVdecHandle, DVPP_CTL_VDEC_PROC, &MSG, 0); if (ret != 0) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "[VDecEngine] DVPP_CTL_VDEC_PROC failed! ret = %d", ret); return HIAI_ERROR; } // VdecCtl will be blocked if eos is 1 // just send end data here if (inputArg->info.isEOS == 1) { std::shared_ptr<StreamRawData> eos = std::make_shared<StreamRawData>(); eos->info.isEOS = 1; SendData(0, "StreamRawData", std::static_pointer_cast<void>(eos)); } HIAI_ENGINE_LOG(HIAI_IDE_INFO, "[VDecEngine] VDecEngine process end!"); return HIAI_OK; }
#ifndef __SERIALIZATION_H__ #define __SERIALIZATION_H__ #include <map> #include <unordered_map> #include <string> #include <cereal/cereal.hpp> #include <cereal/types/string.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/unordered_map.hpp> #include <cereal/archives/binary.hpp> template<typename Container> class Serialization { public : /** \brief This method serializes the container it received as parameter and returns it in the form of an std::string object. \param container An STL container to be serialized. \return An std::string object containing the serialized container. */ static std::string serialize(Container const& container){ std::stringstream ss; cereal::BinaryOutputArchive oarchive(ss); oarchive(container); return ss.str(); } /** \brief This method deserializes the content of an std::string representing a serialized container. \param serializedContainer An std::string object which contains a serialized container. \return The deserialized container of type 'Container' that was in the string. */ static Container deserialize(std::string const& serializedContainer){ std::stringstream ss(serializedContainer); Container container; cereal::BinaryInputArchive iarchive(ss); iarchive(container); return container; } }; #endif
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coincontroldialog.h" #include "ui_coincontroldialog.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "init.h" #include "optionsmodel.h" #include "walletmodel.h" #include "coincontrol.h" #include "main.h" #include "obfuscation.h" #include "wallet.h" #include "multisigdialog.h" #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <QApplication> #include <QCheckBox> #include <QCursor> #include <QDialogButtonBox> #include <QFlags> #include <QIcon> #include <QSettings> #include <QString> #include <QTreeWidget> #include <QTreeWidgetItem> using namespace std; QList<CAmount> CoinControlDialog::payAmounts; int CoinControlDialog::nSplitBlockDummy; CCoinControl* CoinControlDialog::coinControl = new CCoinControl(); CoinControlDialog::CoinControlDialog(QWidget* parent, bool fMultisigEnabled) : QDialog(parent), ui(new Ui::CoinControlDialog), model(0) { ui->setupUi(this); this->fMultisigEnabled = fMultisigEnabled; /* Open CSS when configured */ this->setStyleSheet(GUIUtil::loadStyleSheet()); // context menu actions QAction* copyAddressAction = new QAction(tr("Copy address"), this); QAction* copyLabelAction = new QAction(tr("Copy label"), this); QAction* copyAmountAction = new QAction(tr("Copy amount"), this); copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this // context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); contextMenu->addSeparator(); contextMenu->addAction(lockAction); contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin())); connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin())); // clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction* clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // toggle tree/list mode connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); // click on checkbox connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int))); // click on header #if QT_VERSION < 0x050000 ui->treeWidget->header()->setClickable(true); #else ui->treeWidget->header()->setSectionsClickable(true); #endif connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); // ok button connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*))); // (un)select all connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked())); // Toggle lock state connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked())); // change coin control first column label due Qt4 bug. // see https://github.com/bitcoin/bitcoin/issues/5716 ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 190); ui->treeWidget->setColumnWidth(COLUMN_DATE, 80); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100); ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100); ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but dont show it ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but dont show it ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but dont show it ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but dont show it ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true); // store date int64 in this column, but dont show it // default view is sorted by amount desc sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder); // restore list mode and sortorder as a convenience feature QSettings settings; if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool()) ui->radioTreeMode->click(); if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder")) sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt())); } CoinControlDialog::~CoinControlDialog() { QSettings settings; settings.setValue("nCoinControlMode", ui->radioListMode->isChecked()); settings.setValue("nCoinControlSortColumn", sortColumn); settings.setValue("nCoinControlSortOrder", (int)sortOrder); delete ui; } void CoinControlDialog::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel() && model->getAddressTableModel()) { updateView(); updateLabelLocked(); CoinControlDialog::updateLabels(model, this); updateDialogLabels(); } } // helper function str_pad QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding) { while (s.length() < nPadLength) s = sPadding + s; return s; } // ok button void CoinControlDialog::buttonBoxClicked(QAbstractButton* button) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) done(QDialog::Accepted); // closes the dialog } // (un)select all void CoinControlDialog::buttonSelectAllClicked() { Qt::CheckState state = Qt::Checked; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); ui->treeWidget->setEnabled(true); if (state == Qt::Unchecked) coinControl->UnSelectAll(); // just to be sure CoinControlDialog::updateLabels(model, this); updateDialogLabels(); } // Toggle lock state void CoinControlDialog::buttonToggleLockClicked() { QTreeWidgetItem* item; // Works in list-mode only if (ui->radioListMode->isChecked()) { ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { item = ui->treeWidget->topLevelItem(i); if (item->text(COLUMN_TYPE) == "MultiSig") continue; COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) { model->unlockCoin(outpt); item->setDisabled(false); item->setIcon(COLUMN_CHECKBOX, QIcon()); } else { model->lockCoin(outpt); item->setDisabled(true); item->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); } updateLabelLocked(); } ui->treeWidget->setEnabled(true); CoinControlDialog::updateLabels(model, this); updateDialogLabels(); } else { QMessageBox msgBox; msgBox.setObjectName("lockMessageBox"); msgBox.setStyleSheet(GUIUtil::loadStyleSheet()); msgBox.setText(tr("Please switch to \"List mode\" to use this function.")); msgBox.exec(); } } // context menu void CoinControlDialog::showMenu(const QPoint& point) { QTreeWidgetItem* item = ui->treeWidget->itemAt(point); if (item) { contextMenuItem = item; // disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { copyTransactionHashAction->setEnabled(true); if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) { lockAction->setEnabled(false); unlockAction->setEnabled(true); } else { lockAction->setEnabled(true); unlockAction->setEnabled(false); } } else // this means click on parent node in tree mode -> disable all { copyTransactionHashAction->setEnabled(false); lockAction->setEnabled(false); unlockAction->setEnabled(false); } // show context menu contextMenu->exec(QCursor::pos()); } } // context menu action: copy amount void CoinControlDialog::copyAmount() { GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT))); } // context menu action: copy label void CoinControlDialog::copyLabel() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL)); } // context menu action: copy address void CoinControlDialog::copyAddress() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS)); } // context menu action: copy transaction id void CoinControlDialog::copyTransactionHash() { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH)); } // context menu action: lock coin void CoinControlDialog::lockCoin() { if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked) contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->lockCoin(outpt); contextMenuItem->setDisabled(true); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); updateLabelLocked(); } // context menu action: unlock coin void CoinControlDialog::unlockCoin() { COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->unlockCoin(outpt); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); } // copy label "Quantity" to clipboard void CoinControlDialog::clipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // copy label "Amount" to clipboard void CoinControlDialog::clipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // copy label "Fee" to clipboard void CoinControlDialog::clipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", "")); } // copy label "After fee" to clipboard void CoinControlDialog::clipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "")); } // copy label "Bytes" to clipboard void CoinControlDialog::clipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", "")); } // copy label "Priority" to clipboard void CoinControlDialog::clipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // copy label "Dust" to clipboard void CoinControlDialog::clipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // copy label "Change" to clipboard void CoinControlDialog::clipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", "")); } // treeview: sort void CoinControlDialog::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder); } // treeview: clicked on header void CoinControlDialog::headerSectionClicked(int logicalIndex) { if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing { ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder); } else { logicalIndex = getMappedColumn(logicalIndex, false); if (sortColumn == logicalIndex) sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); else { sortColumn = logicalIndex; sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc } sortView(sortColumn, sortOrder); } } // toggle tree mode void CoinControlDialog::radioTreeMode(bool checked) { if (checked && model) updateView(); } // toggle list mode void CoinControlDialog::radioListMode(bool checked) { if (checked && model) updateView(); } // checkbox clicked by user void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) { if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) coinControl->UnSelect(outpt); else if (item->isDisabled()) // locked (this happens if "check all" through parent node) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else coinControl->Select(outpt); // selection changed -> update labels if (ui->treeWidget->isEnabled()){ // do not update on every click for (un)select all CoinControlDialog::updateLabels(model, this); updateDialogLabels(); } } // todo: this is a temporary qt5 fix: when clicking a parent node in tree mode, the parent node // including all childs are partially selected. But the parent node should be fully selected // as well as the childs. Childs should never be partially selected in the first place. // Please remove this ugly fix, once the bug is solved upstream. #if QT_VERSION >= 0x050000 else if (column == COLUMN_CHECKBOX && item->childCount() > 0) { if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) item->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } #endif } // return human readable label for priority number QString CoinControlDialog::getPriorityLabel(double dPriority, double mempoolEstimatePriority) { double dPriorityMedium = mempoolEstimatePriority; if (dPriorityMedium <= 0) dPriorityMedium = AllowFreeThreshold(); // not enough data, back to hard-coded if (dPriority / 1000000 > dPriorityMedium) return tr("highest"); else if (dPriority / 100000 > dPriorityMedium) return tr("higher"); else if (dPriority / 10000 > dPriorityMedium) return tr("high"); else if (dPriority / 1000 > dPriorityMedium) return tr("medium-high"); else if (dPriority > dPriorityMedium) return tr("medium"); else if (dPriority * 10 > dPriorityMedium) return tr("low-medium"); else if (dPriority * 100 > dPriorityMedium) return tr("low"); else if (dPriority * 1000 > dPriorityMedium) return tr("lower"); else return tr("lowest"); } // shows count of locked unspent outputs void CoinControlDialog::updateLabelLocked() { vector<COutPoint> vOutpts; model->listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); ui->labelLocked->setVisible(true); } else ui->labelLocked->setVisible(false); } void CoinControlDialog::updateDialogLabels() { if (this->parentWidget() == nullptr) { CoinControlDialog::updateLabels(model, this); return; } vector<COutPoint> vCoinControl; vector<COutput> vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); CAmount nAmount = 0; unsigned int nQuantity = 0; for (const COutput& out : vOutputs) { // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer uint256 txhash = out.tx->GetHash(); COutPoint outpt(txhash, out.i); if(model->isSpent(outpt)) { coinControl->UnSelect(outpt); continue; } // Quantity nQuantity++; // Amount nAmount += out.tx->vout[out.i].nValue; } MultisigDialog* multisigDialog = (MultisigDialog*)this->parentWidget(); multisigDialog->updateCoinControl(nAmount, nQuantity); } void CoinControlDialog::updateLabels(WalletModel* model, QDialog* dialog) { if (!model) return; // nPayAmount CAmount nPayAmount = 0; bool fDust = false; CMutableTransaction txDummy; foreach (const CAmount& amount, CoinControlDialog::payAmounts) { nPayAmount += amount; if (amount > 0) { CTxOut txout(amount, (CScript)vector<unsigned char>(24, 0)); txDummy.vout.push_back(txout); if (txout.IsDust(::minRelayTxFee)) fDust = true; } } QString sPriorityLabel = tr("none"); CAmount nAmount = 0; CAmount nPayFee = 0; CAmount nAfterFee = 0; CAmount nChange = 0; unsigned int nBytes = 0; unsigned int nBytesInputs = 0; double dPriority = 0; double dPriorityInputs = 0; unsigned int nQuantity = 0; int nQuantityUncompressed = 0; bool fAllowFree = false; vector<COutPoint> vCoinControl; vector<COutput> vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); BOOST_FOREACH (const COutput& out, vOutputs) { // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer uint256 txhash = out.tx->GetHash(); COutPoint outpt(txhash, out.i); if (model->isSpent(outpt)) { coinControl->UnSelect(outpt); continue; } // Quantity nQuantity++; // Amount nAmount += out.tx->vout[out.i].nValue; // Priority dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth + 1); // Bytes CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { CPubKey pubkey; CKeyID* keyid = boost::get<CKeyID>(&address); if (keyid && model->getPubKey(*keyid, pubkey)) { nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); if (!pubkey.IsCompressed()) nQuantityUncompressed++; } else nBytesInputs += 148; // in all error cases, simply assume 148 here } else nBytesInputs += 148; } // calculation if (nQuantity > 0) { // Bytes nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + max(1, CoinControlDialog::nSplitBlockDummy) : 2) * 34) + 10; // always assume +1 output for change here // Priority double mempoolEstimatePriority = mempool.estimatePriority(nTxConfirmTarget); dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority) sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority); // Fee nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool); // IX Fee if (coinControl->useSwiftTX) nPayFee = max(nPayFee, CENT); // Allow free? double dPriorityNeeded = mempoolEstimatePriority; if (dPriorityNeeded <= 0) dPriorityNeeded = AllowFreeThreshold(); // not enough data, back to hard-coded fAllowFree = (dPriority >= dPriorityNeeded); if (fSendFreeTransactions) if (fAllowFree && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) nPayFee = 0; if (nPayAmount > 0) { nChange = nAmount - nPayFee - nPayAmount; // Never create dust outputs; if we would, just add the dust to the fee. if (nChange > 0 && nChange < CENT) { CTxOut txout(nChange, (CScript)vector<unsigned char>(24, 0)); if (txout.IsDust(::minRelayTxFee)) { nPayFee += nChange; nChange = 0; } } if (nChange == 0) nBytes -= 34; } // after fee nAfterFee = nAmount - nPayFee; if (nAfterFee < 0) nAfterFee = 0; } // actually update labels int nDisplayUnit = BitcoinUnits::CCCoin; if (model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); QLabel* l1 = dialog->findChild<QLabel*>("labelCoinControlQuantity"); QLabel* l2 = dialog->findChild<QLabel*>("labelCoinControlAmount"); QLabel* l3 = dialog->findChild<QLabel*>("labelCoinControlFee"); QLabel* l4 = dialog->findChild<QLabel*>("labelCoinControlAfterFee"); QLabel* l5 = dialog->findChild<QLabel*>("labelCoinControlBytes"); QLabel* l6 = dialog->findChild<QLabel*>("labelCoinControlPriority"); QLabel* l7 = dialog->findChild<QLabel*>("labelCoinControlLowOutput"); QLabel* l8 = dialog->findChild<QLabel*>("labelCoinControlChange"); // enable/disable "dust" and "change" dialog->findChild<QLabel*>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel*>("labelCoinControlLowOutput")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel*>("labelCoinControlChangeText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel*>("labelCoinControlChange")->setEnabled(nPayAmount > 0); // stats l1->setText(QString::number(nQuantity)); // Quantity l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes)); // Bytes l6->setText(sPriorityLabel); // Priority l7->setText(fDust ? tr("yes") : tr("no")); // Dust l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change if (nPayFee > 0 && !(payTxFee.GetFeePerK() > 0 && fPayAtLeastCustomFee && nBytes < 1000)) { l3->setText("~" + l3->text()); l4->setText("~" + l4->text()); if (nChange > 0) l8->setText("~" + l8->text()); } // turn labels "red" l5->setStyleSheet((nBytes >= MAX_FREE_TRANSACTION_CREATE_SIZE) ? "color:red;" : ""); // Bytes >= 1000 l6->setStyleSheet((dPriority > 0 && !fAllowFree) ? "color:red;" : ""); // Priority < "medium" l7->setStyleSheet((fDust) ? "color:red;" : ""); // Dust = "yes" // tool tips QString toolTip1 = tr("This label turns red, if the transaction size is greater than 1000 bytes.") + "<br /><br />"; toolTip1 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CWallet::minTxFee.GetFeePerK())) + "<br /><br />"; toolTip1 += tr("Can vary +/- 1 byte per input."); QString toolTip2 = tr("Transactions with higher priority are more likely to get included into a block.") + "<br /><br />"; toolTip2 += tr("This label turns red, if the priority is smaller than \"medium\".") + "<br /><br />"; toolTip2 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CWallet::minTxFee.GetFeePerK())); QString toolTip3 = tr("This label turns red, if any recipient receives an amount smaller than %1.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, ::minRelayTxFee.GetFee(546))); // how many satoshis the estimated fee can vary per byte we guess wrong double dFeeVary; if (payTxFee.GetFeePerK() > 0) dFeeVary = (double)std::max(CWallet::minTxFee.GetFeePerK(), payTxFee.GetFeePerK()) / 1000; else dFeeVary = (double)std::max(CWallet::minTxFee.GetFeePerK(), mempool.estimateFee(nTxConfirmTarget).GetFeePerK()) / 1000; QString toolTip4 = tr("Can vary +/- %1 duff(s) per input.").arg(dFeeVary); l3->setToolTip(toolTip4); l4->setToolTip(toolTip4); l5->setToolTip(toolTip1); l6->setToolTip(toolTip2); l7->setToolTip(toolTip3); l8->setToolTip(toolTip4); dialog->findChild<QLabel*>("labelCoinControlFeeText")->setToolTip(l3->toolTip()); dialog->findChild<QLabel*>("labelCoinControlAfterFeeText")->setToolTip(l4->toolTip()); dialog->findChild<QLabel*>("labelCoinControlBytesText")->setToolTip(l5->toolTip()); dialog->findChild<QLabel*>("labelCoinControlPriorityText")->setToolTip(l6->toolTip()); dialog->findChild<QLabel*>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip()); dialog->findChild<QLabel*>("labelCoinControlChangeText")->setToolTip(l8->toolTip()); // Insufficient funds QLabel* label = dialog->findChild<QLabel*>("labelCoinControlInsuffFunds"); if (label) label->setVisible(nChange < 0); } void CoinControlDialog::updateView() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel()) return; bool treeMode = ui->radioTreeMode->isChecked(); ui->treeWidget->clear(); ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox ui->treeWidget->setAlternatingRowColors(!treeMode); QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); double mempoolEstimatePriority = mempool.estimatePriority(nTxConfirmTarget); map<QString, vector<COutput>> mapCoins; model->listCoins(mapCoins); BOOST_FOREACH (PAIRTYPE(QString, vector<COutput>) coins, mapCoins) { QTreeWidgetItem* itemWalletAddress = new QTreeWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); QString sWalletAddress = coins.first; QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); if (treeMode) { // wallet address ui->treeWidget->addTopLevelItem(itemWalletAddress); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); // label itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); itemWalletAddress->setToolTip(COLUMN_LABEL, sWalletLabel); // address itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); itemWalletAddress->setToolTip(COLUMN_ADDRESS, sWalletAddress); } CAmount nSum = 0; double dPrioritySum = 0; int nChildren = 0; int nInputSum = 0; for(const COutput& out: coins.second) { isminetype mine = pwalletMain->IsMine(out.tx->vout[out.i]); bool fMultiSigUTXO = (mine & ISMINE_MULTISIG); // when multisig is enabled, it will only display outputs from multisig addresses if (fMultisigEnabled && !fMultiSigUTXO) continue; int nInputSize = 0; nSum += out.tx->vout[out.i].nValue; nChildren++; QTreeWidgetItem* itemOutput; if (treeMode) itemOutput = new QTreeWidgetItem(itemWalletAddress); else itemOutput = new QTreeWidgetItem(ui->treeWidget); itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); //MultiSig if (fMultiSigUTXO) { itemOutput->setText(COLUMN_TYPE, "MultiSig"); if (!fMultisigEnabled) { COutPoint outpt(out.tx->GetHash(), out.i); coinControl->UnSelect(outpt); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); } } else { itemOutput->setText(COLUMN_TYPE, "Personal"); } // address CTxDestination outputAddress; QString sAddress = ""; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString()); // if listMode or change => show CCCoin address. In tree mode, address is not shown again for direct wallet address outputs if (!treeMode || (!(sAddress == sWalletAddress))) itemOutput->setText(COLUMN_ADDRESS, sAddress); itemOutput->setToolTip(COLUMN_ADDRESS, sAddress); CPubKey pubkey; CKeyID* keyid = boost::get<CKeyID>(&outputAddress); if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed()) nInputSize = 29; // 29 = 180 - 151 (public key is 180 bytes, priority free area is 151 bytes) } // label if (!(sAddress == sWalletAddress)) // change { // tooltip from where the change comes from itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if (!treeMode) { QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress); if (sLabel.isEmpty()) sLabel = tr("(no label)"); itemOutput->setText(COLUMN_LABEL, sLabel); } // amount itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly // date itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setToolTip(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setText(COLUMN_DATE_INT64, strPad(QString::number(out.tx->GetTxTime()), 20, " ")); // confirmations itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " ")); // priority double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth + 1); // 78 = 2 * 34 + 10 itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority)); itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPriority), 20, " ")); dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth + 1); nInputSum += nInputSize; // transaction hash uint256 txhash = out.tx->GetHash(); itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex())); // vout index itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); // disable locked coins if (model->isLockedCoin(txhash, out.i)) { COutPoint outpt(txhash, out.i); coinControl->UnSelect(outpt); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); } // set checkbox if (coinControl->IsSelected(txhash, out.i)) itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } // amount if (treeMode) { dPrioritySum = dPrioritySum / (nInputSum + 78); itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " ")); itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum, mempoolEstimatePriority)); itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPrioritySum), 20, " ")); } } // expand all partially selected if (treeMode) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) ui->treeWidget->topLevelItem(i)->setExpanded(true); } // sort view sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); }
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_TOOLBOX_CRLIBM_FUNCTIONS_SCALAR_TANPI_RD_HPP_INCLUDED #define NT2_TOOLBOX_CRLIBM_FUNCTIONS_SCALAR_TANPI_RD_HPP_INCLUDED #include <nt2/toolbox/crlibm/functions/tanpi_rd.hpp> #include <nt2/sdk/meta/upgrade.hpp> extern "C"{ extern double tanpi_rd ( double ); } ///////////////////////////////////////////////////////////////////////////// // Implementation when type A0 is arithmetic_ ///////////////////////////////////////////////////////////////////////////// namespace nt2 { namespace ext { NT2_FUNCTOR_IMPLEMENTATION(nt2::crlibm::tag::tanpi_rd_, tag::cpu_ , (A0) , (scalar_< arithmetic_<A0> >) ) { typedef typename boost::dispatch::meta::as_floating<A0>::type result_type; NT2_FUNCTOR_CALL(1) { typedef typename meta::upgrade<result_type>::type type; return nt2::crlibm::tanpi_rd(type(a0)); } }; } } ///////////////////////////////////////////////////////////////////////////// // Implementation when type A0 is double ///////////////////////////////////////////////////////////////////////////// namespace nt2 { namespace ext { NT2_FUNCTOR_IMPLEMENTATION(nt2::crlibm::tag::tanpi_rd_, tag::cpu_ , (A0) , (scalar_< double_<A0> >) ) { typedef typename boost::dispatch::meta::as_floating<A0>::type result_type; NT2_FUNCTOR_CALL(1) { return ::tanpi_rd(a0); } }; } } #endif
/* * Copyright 2010-2017 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/core/client/AWSError.h> #include <aws/eks/EKSErrorMarshaller.h> #include <aws/eks/EKSErrors.h> using namespace Aws::Client; using namespace Aws::EKS; AWSError<CoreErrors> EKSErrorMarshaller::FindErrorByName(const char* errorName) const { AWSError<CoreErrors> error = EKSErrorMapper::GetErrorForName(errorName); if(error.GetErrorType() != CoreErrors::UNKNOWN) { return error; } return AWSErrorMarshaller::FindErrorByName(errorName); }
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: int ans = 0; int diameterOfBinaryTree(TreeNode* root) { ans = 1; depth(root); return ans - 1; } int depth(TreeNode* rt){ if(rt == nullptr){ return 0; } int L = depth(rt->left); int R = depth(rt->right); ans = max(ans, L + R + 1); return max(L, R) + 1; } }; int main(){ }
//============================================================================ // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // //============================================================================ #include <fstream> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <boost/algorithm/string/predicate.hpp> #include "LogProvider.hpp" #include "FileWatcher.hpp" #include "VNode.hpp" #include "VReply.hpp" #include "ServerHandler.hpp" #include "File.hpp" LogProvider::LogProvider(InfoPresenter* owner,QObject* parent) : QObject(parent), InfoProvider(owner,VTask::HistoryTask), fileWatcher_(nullptr) { //NOTE: fileWatcher_'s parent (if it exists) will be "this", so //fileWatcher_ will be automatically deleted in the destructor! } void LogProvider::clear() { stopWatchFile(); InfoProvider::clear(); } void LogProvider::setAutoUpdate(bool autoUpdate) { InfoProvider::setAutoUpdate(autoUpdate); if(active_) { if(!autoUpdate_) { stopWatchFile(); } else { if(!inAutoUpdate_) fetchFile(); } } else { stopWatchFile(); } } void LogProvider::visit(VInfoServer* info) { fetchFile(); } void LogProvider::fetchFile() { if(!active_) return; stopWatchFile(); //Reset the reply reply_->reset(); if(!info_) { owner_->infoFailed(reply_); return; } ServerHandler* server=info_->server(); //Get the filename std::string fileName=server->vRoot()->genVariable("ECF_LOG"); fetchFile(server,fileName); } void LogProvider::fetchFile(ServerHandler *server,const std::string& fileName) { if(!server) { owner_->infoFailed(reply_); return; } //Set the filename in reply reply_->fileName(fileName); //No filename is available if(fileName.empty()) { reply_->setErrorText("Variable ECF_LOG is not defined!"); owner_->infoFailed(reply_); } //First we try to read the file directly from the disk //if(server->readFromDisk()) { size_t file_size = 0; std::string err_msg; reply_->text( ecf::File::get_last_n_lines(fileName,100,file_size,err_msg)); if(err_msg.empty()) { reply_->fileReadMode(VReply::LocalReadMode); if(autoUpdate_) inAutoUpdate_=true; owner_->infoReady(reply_); //Try to track the changes in the log file watchFile(fileName,file_size); return; } } //Finally we try the server reply_->fileReadMode(VReply::ServerReadMode); //Define a task for getting the info from the server. task_=VTask::create(taskType_,server->vRoot(),this); //Run the task in the server. When it finish taskFinished() is called. The text returned //in the reply will be prepended to the string we generated above. server->run(task_); #if 0 //If we are we could not get the file //owner_->infoFailed(reply_); #endif } void LogProvider::watchFile(const std::string& fileName,size_t offset) { if(autoUpdate_) { assert(fileWatcher_ == 0); fileWatcher_=new FileWatcher(fileName,offset,this); connect(fileWatcher_,SIGNAL(linesAppended(QStringList)), this,SLOT(slotLinesAppend(QStringList))); inAutoUpdate_=true; } } void LogProvider::stopWatchFile() { if(fileWatcher_) { delete fileWatcher_; fileWatcher_=nullptr; } inAutoUpdate_=false; } void LogProvider::slotLinesAppend(QStringList lst) { //Check if the task is already running if(task_) { task_->status(VTask::CANCELLED); task_.reset(); } //Reset the reply reply_->reset(); if(!info_) { owner_->infoFailed(reply_); } std::vector<std::string> vec; Q_FOREACH(QString s,lst) { vec.push_back(s.toStdString()); } reply_->setTextVec(vec); owner_->infoAppended(reply_); }
#include "idle.h" #include <IOKit/pwr_mgt/IOPMLib.h> namespace { IOPMAssertionID displayAssertionID = 0; IOReturn displayRes = 0; IOPMAssertionID systemAssertionID = 0; IOReturn systemRes = 0; } // namespace bool Idle::preventDisplaySleep(const QString &reason) { displayRes = IOPMAssertionCreateWithName(kIOPMAssertionTypePreventUserIdleDisplaySleep, kIOPMAssertionLevelOn, reason.toCFString(), &displayAssertionID); return displayRes == kIOReturnSuccess; } bool Idle::allowDisplaySleep() { displayRes = IOPMAssertionRelease(displayAssertionID); return displayRes == kIOReturnSuccess; } QString Idle::displayErrorMessage() { return QString(); // return QString::fromUtf8(IOService::stringFromReturn(displayRes)); } bool Idle::preventSystemSleep(const QString &reason) { systemRes = IOPMAssertionCreateWithName(kIOPMAssertionTypePreventUserIdleSystemSleep, kIOPMAssertionLevelOn, reason.toCFString(), &systemAssertionID); return systemRes == kIOReturnSuccess; } bool Idle::allowSystemSleep() { systemRes = IOPMAssertionRelease(systemAssertionID); return systemRes == kIOReturnSuccess; } QString Idle::systemErrorMessage() { return QString(); // return QString::fromUtf8(IOService::stringFromReturn(systemRes)); }
// // Created by HaruGakkaP on 2020-12-11. // #include "MemoryManageUnit.h" #include <utility> #include <stdexcept> MemoryManageUnit::MemoryManageUnit( std::shared_ptr<MemoryInterface> ptr_cartridge, std::shared_ptr<MemoryInterface> ptr_vram, std::shared_ptr<MemoryInterface> ptr_timer, std::shared_ptr<MemoryInterface> ptr_joypad) { mCartridge = std::move(ptr_cartridge); mVRAM = std::move( ptr_vram ); mTimer = std::move(ptr_timer); mJoypad = std::move(ptr_joypad); mBankNum = 0; mInterruptEnable = 0; mInterruptFlags = 0; } BYTE MemoryManageUnit::Get(size_t mem_addr) const { if ((mem_addr <= 0x7fffu) || (mem_addr >= 0xA000u && mem_addr <= 0xBFFF)) // CARTRIDGE ROM || RAM { if (mCartridge == nullptr) { throw std::logic_error("NOT LOADED CARTRIDGE."); } return mCartridge->Get(mem_addr); } // GPU else if (mem_addr >= 0x8000u && mem_addr <= 0x9fff || // VRAM (mem_addr >= 0xfe00 && mem_addr <= 0xfe9f) || // OAM (mem_addr >= 0xff40 && mem_addr <= 0xff7f)) // Interrupts { if (mVRAM == nullptr) { throw std::logic_error("NOT LOADED GPU"); } return mVRAM->Get(mem_addr); } // Work Ram BANK 0 else if (mem_addr >= 0xC000u && mem_addr <= 0xCFFF) { return mWorkRam[(mem_addr - 0xC000u)]; } else if (mem_addr >= 0xD000u && mem_addr <= 0xDFFF) { return mWorkRam[(mBankNum * 0x1000u) + (mem_addr - 0xC000u)]; } else if (mem_addr >= 0xE000 && mem_addr <= 0xEFFF) { return mWorkRam[(mem_addr - 0xE000)]; } else if (mem_addr >= 0xF000 && mem_addr <= 0xFDFF) { return mWorkRam[(mBankNum * 0x1000u) + (mem_addr - 0xE000)]; } else if (mem_addr == 0xff00u) { return mJoypad->Get( mem_addr ); } else if( mem_addr >= 0xff04u && mem_addr <= 0xff07u ) { if (mTimer == nullptr) { throw std::logic_error("NOT LOADED TIMER"); } return mTimer->Get( mem_addr ); } else if( mem_addr >= 0xff80u && mem_addr <= 0xfffe ) // HI RAM { return mHRAM[ mem_addr - 0xff80u ]; } else if( mem_addr == 0xff0f ) { return mInterruptFlags; } else if ( mem_addr == 0xffff ) { return mInterruptEnable; } return 0; } void MemoryManageUnit::Set(size_t mem_addr, BYTE value) { if( ( mem_addr <= 0x7fffu ) || ( mem_addr >= 0xA000u && mem_addr <= 0xBFFF ) ) // CARTRIDGE ROM || RAM { if ( mCartridge == nullptr ) { throw std::logic_error("NOT LOADED CARTRIDGE."); } mCartridge->Set( mem_addr, value ); } // GPU else if ( mem_addr >= 0x8000u && mem_addr <= 0x9fff || // VRAM ( mem_addr >= 0xfe00 && mem_addr <= 0xfe9f ) || // OAM ( mem_addr >= 0xff40 && mem_addr <= 0xff7f ) ) // Interrupts { if ( mVRAM == nullptr ) { throw std::logic_error("NOT LOADED GPU"); } return mVRAM->Set( mem_addr, value ); } // Work Ram BANK 0 else if ( mem_addr >= 0xC000u && mem_addr <= 0xCFFF ) { mWorkRam[ ( mem_addr - 0xC000u ) ] = value; } else if ( mem_addr >= 0xD000u && mem_addr <= 0xDFFF ) { mWorkRam[ ( mBankNum * 0x1000u ) + ( mem_addr - 0xC000u ) ] = value; } else if (mem_addr >= 0xE000 && mem_addr <= 0xEFFF) { mWorkRam[(mem_addr - 0xE000)] = value; } else if (mem_addr >= 0xF000 && mem_addr <= 0xFDFF) { mWorkRam[(mBankNum * 0x1000u) + (mem_addr - 0xE000)] = value; } else if (mem_addr == 0xff00u) { mJoypad->Set( mem_addr, value ); } else if( mem_addr >= 0xff04u && mem_addr <= 0xff07u ) { mTimer->Set( mem_addr, value ); } else if( mem_addr >= 0xff80u && mem_addr <= 0xfffe ) { mHRAM[ mem_addr - 0xff80u ] = value; } else if( mem_addr == 0xff0f ) { mInterruptFlags = value & 0x1fu; // 5비트만 씀 } else if ( mem_addr == 0xffff ) { mInterruptEnable = value & 0x1fu; // 5비트만 씀 } } void MemoryManageUnit::SetCartridge(std::shared_ptr<MemoryInterface> ptr_cartridge) { mCartridge = std::move(ptr_cartridge); }
#define _CRT_SECURE_NO_WARNINGS #include "stdio.h" #include "stdarg.h" #include "../includes/zs-logger.h" FILE* outfile; bool useFile = false; void ZSpire::close_outputFile(){ if (useFile == true) { fclose(outfile); } } void ZSpire::open_outputFile(const char* fpath) { useFile = true; outfile = fopen(fpath, "w"); } void ZSpire::Log(uint TYPE, const char *format, ...) { switch (TYPE) { case TYPE_ERROR: {printf("%s", "ERROR: "); if (useFile == true) { fprintf(outfile, "%s", "ERROR: "); } }break; case TYPE_OPENGL: {printf("%s", "OPENGL: "); if (useFile == true) { fprintf(outfile, "%s", "OPENGL: "); } }break; case TYPE_LOG: {printf("%s", "LOG: "); if (useFile == true) { fprintf(outfile, "%s", "LOG: "); } }break; case TYPE_ENGINE: {printf("%s", "ENGINE: "); if (useFile == true) { fprintf(outfile, "%s", "ENGINE: "); } }break; case TYPE_SCRIPTERROR: {printf("%s", "LUA ERROR: "); if (useFile == true) { fprintf(outfile, "%s", "LUA ERROR: "); } }break; } va_list arglist; va_start(arglist, format); int i; for (i = 0; format[i]; i++) { if (format[i] == '%') { i++; switch (format[i]) { case 'i': { int i = va_arg(arglist, int); printf("%i", i); if (useFile == true) { fprintf(outfile, "%i", i); } }; break; case 'd': { double d = va_arg(arglist, double); printf("%f", d); }; break; case 'c': { char c = va_arg(arglist, int); printf("%c", c); }; break; case 'p': { void *p = va_arg(arglist, void*); printf("%p", p); }; break; case 'm': { printf(" "); }; break; case 'k': { printf("\n"); }; break; case 's': { char *p = va_arg(arglist, char*); printf("%s", p); if (useFile == true) { fprintf(outfile, "%s", p); } }; break; default: break; } } } printf("%s", "\n"); if (useFile == true) { fprintf(outfile, "%s", "\n"); } }
#include <vector> #include <algorithm> #include <unordered_set> class Solution { public: std::vector<int> findDuplicates(std::vector<int> &nums) { return findDuplicatesOpt(nums); } std::vector<int> findDuplicatesOpt(std::vector<int> &nums) // space: O(1), time: O(n) { std::vector<int> res; for (int i = 0; i < nums.size(); i++) { int temp = std::abs(nums[i]) - 1; if (nums[temp] > 0) // first appearance nums[temp] *= -1; else if (nums[temp] < 0) // second appearance res.push_back(temp + 1); } return res; } std::vector<int> findDuplicatesSort(std::vector<int> &nums) // space: O(1), time: O(n logn) { std::sort(nums.begin(), nums.end()); std::vector<int> res; for (int i = 1; i < nums.size(); i++) if (nums[i] == nums[i - 1]) res.push_back(nums[i]); return res; } std::vector<int> findDuplicatesHashset(std::vector<int> &nums) // time: O(n) { std::unordered_set<int> set; std::vector<int> res; for (const int num : nums) if (auto i = set.find(num); i != set.end()) res.push_back(*i); else set.insert(num); return res; } };
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdarg.h> #include <stdlib.h> #include <cmath> #if V8_TARGET_ARCH_PPC #include "src/assembler.h" #include "src/base/bits.h" #include "src/codegen.h" #include "src/disasm.h" #include "src/macro-assembler.h" #include "src/ostreams.h" #include "src/ppc/constants-ppc.h" #include "src/ppc/frame-constants-ppc.h" #include "src/ppc/simulator-ppc.h" #include "src/runtime/runtime-utils.h" #if defined(USE_SIMULATOR) // Only build the simulator if not compiling for real PPC hardware. namespace v8 { namespace internal { const auto GetRegConfig = RegisterConfiguration::Default; // static base::LazyInstance<Simulator::GlobalMonitor>::type Simulator::global_monitor_ = LAZY_INSTANCE_INITIALIZER; // This macro provides a platform independent use of sscanf. The reason for // SScanF not being implemented in a platform independent way through // ::v8::internal::OS in the same way as SNPrintF is that the // Windows C Run-Time Library does not provide vsscanf. #define SScanF sscanf // NOLINT // The PPCDebugger class is used by the simulator while debugging simulated // PowerPC code. class PPCDebugger { public: explicit PPCDebugger(Simulator* sim) : sim_(sim) {} void Stop(Instruction* instr); void Debug(); private: static const Instr kBreakpointInstr = (TWI | 0x1f * B21); static const Instr kNopInstr = (ORI); // ori, 0,0,0 Simulator* sim_; intptr_t GetRegisterValue(int regnum); double GetRegisterPairDoubleValue(int regnum); double GetFPDoubleRegisterValue(int regnum); bool GetValue(const char* desc, intptr_t* value); bool GetFPDoubleValue(const char* desc, double* value); // Set or delete a breakpoint. Returns true if successful. bool SetBreakpoint(Instruction* break_pc); bool DeleteBreakpoint(Instruction* break_pc); // Undo and redo all breakpoints. This is needed to bracket disassembly and // execution to skip past breakpoints when run from the debugger. void UndoBreakpoints(); void RedoBreakpoints(); }; void PPCDebugger::Stop(Instruction* instr) { // Get the stop code. // use of kStopCodeMask not right on PowerPC uint32_t code = instr->SvcValue() & kStopCodeMask; // Retrieve the encoded address, which comes just after this stop. char* msg = *reinterpret_cast<char**>(sim_->get_pc() + Instruction::kInstrSize); // Update this stop description. if (sim_->isWatchedStop(code) && !sim_->watched_stops_[code].desc) { sim_->watched_stops_[code].desc = msg; } // Print the stop message and code if it is not the default code. if (code != kMaxStopCode) { PrintF("Simulator hit stop %u: %s\n", code, msg); } else { PrintF("Simulator hit %s\n", msg); } sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize + kPointerSize); Debug(); } intptr_t PPCDebugger::GetRegisterValue(int regnum) { return sim_->get_register(regnum); } double PPCDebugger::GetRegisterPairDoubleValue(int regnum) { return sim_->get_double_from_register_pair(regnum); } double PPCDebugger::GetFPDoubleRegisterValue(int regnum) { return sim_->get_double_from_d_register(regnum); } bool PPCDebugger::GetValue(const char* desc, intptr_t* value) { int regnum = Registers::Number(desc); if (regnum != kNoRegister) { *value = GetRegisterValue(regnum); return true; } else { if (strncmp(desc, "0x", 2) == 0) { return SScanF(desc + 2, "%" V8PRIxPTR, reinterpret_cast<uintptr_t*>(value)) == 1; } else { return SScanF(desc, "%" V8PRIuPTR, reinterpret_cast<uintptr_t*>(value)) == 1; } } return false; } bool PPCDebugger::GetFPDoubleValue(const char* desc, double* value) { int regnum = DoubleRegisters::Number(desc); if (regnum != kNoRegister) { *value = sim_->get_double_from_d_register(regnum); return true; } return false; } bool PPCDebugger::SetBreakpoint(Instruction* break_pc) { // Check if a breakpoint can be set. If not return without any side-effects. if (sim_->break_pc_ != nullptr) { return false; } // Set the breakpoint. sim_->break_pc_ = break_pc; sim_->break_instr_ = break_pc->InstructionBits(); // Not setting the breakpoint instruction in the code itself. It will be set // when the debugger shell continues. return true; } bool PPCDebugger::DeleteBreakpoint(Instruction* break_pc) { if (sim_->break_pc_ != nullptr) { sim_->break_pc_->SetInstructionBits(sim_->break_instr_); } sim_->break_pc_ = nullptr; sim_->break_instr_ = 0; return true; } void PPCDebugger::UndoBreakpoints() { if (sim_->break_pc_ != nullptr) { sim_->break_pc_->SetInstructionBits(sim_->break_instr_); } } void PPCDebugger::RedoBreakpoints() { if (sim_->break_pc_ != nullptr) { sim_->break_pc_->SetInstructionBits(kBreakpointInstr); } } void PPCDebugger::Debug() { intptr_t last_pc = -1; bool done = false; #define COMMAND_SIZE 63 #define ARG_SIZE 255 #define STR(a) #a #define XSTR(a) STR(a) char cmd[COMMAND_SIZE + 1]; char arg1[ARG_SIZE + 1]; char arg2[ARG_SIZE + 1]; char* argv[3] = {cmd, arg1, arg2}; // make sure to have a proper terminating character if reaching the limit cmd[COMMAND_SIZE] = 0; arg1[ARG_SIZE] = 0; arg2[ARG_SIZE] = 0; // Undo all set breakpoints while running in the debugger shell. This will // make them invisible to all commands. UndoBreakpoints(); // Disable tracing while simulating bool trace = ::v8::internal::FLAG_trace_sim; ::v8::internal::FLAG_trace_sim = false; while (!done && !sim_->has_bad_pc()) { if (last_pc != sim_->get_pc()) { disasm::NameConverter converter; disasm::Disassembler dasm(converter); // use a reasonably large buffer v8::internal::EmbeddedVector<char, 256> buffer; dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(sim_->get_pc())); PrintF(" 0x%08" V8PRIxPTR " %s\n", sim_->get_pc(), buffer.start()); last_pc = sim_->get_pc(); } char* line = ReadLine("sim> "); if (line == nullptr) { break; } else { char* last_input = sim_->last_debugger_input(); if (strcmp(line, "\n") == 0 && last_input != nullptr) { line = last_input; } else { // Ownership is transferred to sim_; sim_->set_last_debugger_input(line); } // Use sscanf to parse the individual parts of the command line. At the // moment no command expects more than two parameters. int argc = SScanF(line, "%" XSTR(COMMAND_SIZE) "s " "%" XSTR(ARG_SIZE) "s " "%" XSTR(ARG_SIZE) "s", cmd, arg1, arg2); if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) { intptr_t value; // If at a breakpoint, proceed past it. if ((reinterpret_cast<Instruction*>(sim_->get_pc())) ->InstructionBits() == 0x7d821008) { sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize); } else { sim_->ExecuteInstruction( reinterpret_cast<Instruction*>(sim_->get_pc())); } if (argc == 2 && last_pc != sim_->get_pc() && GetValue(arg1, &value)) { for (int i = 1; i < value; i++) { disasm::NameConverter converter; disasm::Disassembler dasm(converter); // use a reasonably large buffer v8::internal::EmbeddedVector<char, 256> buffer; dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(sim_->get_pc())); PrintF(" 0x%08" V8PRIxPTR " %s\n", sim_->get_pc(), buffer.start()); sim_->ExecuteInstruction( reinterpret_cast<Instruction*>(sim_->get_pc())); } } } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) { // If at a breakpoint, proceed past it. if ((reinterpret_cast<Instruction*>(sim_->get_pc())) ->InstructionBits() == 0x7d821008) { sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize); } else { // Execute the one instruction we broke at with breakpoints disabled. sim_->ExecuteInstruction( reinterpret_cast<Instruction*>(sim_->get_pc())); } // Leave the debugger shell. done = true; } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) { if (argc == 2 || (argc == 3 && strcmp(arg2, "fp") == 0)) { intptr_t value; double dvalue; if (strcmp(arg1, "all") == 0) { for (int i = 0; i < kNumRegisters; i++) { value = GetRegisterValue(i); PrintF(" %3s: %08" V8PRIxPTR, GetRegConfig()->GetGeneralRegisterName(i), value); if ((argc == 3 && strcmp(arg2, "fp") == 0) && i < 8 && (i % 2) == 0) { dvalue = GetRegisterPairDoubleValue(i); PrintF(" (%f)\n", dvalue); } else if (i != 0 && !((i + 1) & 3)) { PrintF("\n"); } } PrintF(" pc: %08" V8PRIxPTR " lr: %08" V8PRIxPTR " " "ctr: %08" V8PRIxPTR " xer: %08x cr: %08x\n", sim_->special_reg_pc_, sim_->special_reg_lr_, sim_->special_reg_ctr_, sim_->special_reg_xer_, sim_->condition_reg_); } else if (strcmp(arg1, "alld") == 0) { for (int i = 0; i < kNumRegisters; i++) { value = GetRegisterValue(i); PrintF(" %3s: %08" V8PRIxPTR " %11" V8PRIdPTR, GetRegConfig()->GetGeneralRegisterName(i), value, value); if ((argc == 3 && strcmp(arg2, "fp") == 0) && i < 8 && (i % 2) == 0) { dvalue = GetRegisterPairDoubleValue(i); PrintF(" (%f)\n", dvalue); } else if (!((i + 1) % 2)) { PrintF("\n"); } } PrintF(" pc: %08" V8PRIxPTR " lr: %08" V8PRIxPTR " " "ctr: %08" V8PRIxPTR " xer: %08x cr: %08x\n", sim_->special_reg_pc_, sim_->special_reg_lr_, sim_->special_reg_ctr_, sim_->special_reg_xer_, sim_->condition_reg_); } else if (strcmp(arg1, "allf") == 0) { for (int i = 0; i < DoubleRegister::kNumRegisters; i++) { dvalue = GetFPDoubleRegisterValue(i); uint64_t as_words = bit_cast<uint64_t>(dvalue); PrintF("%3s: %f 0x%08x %08x\n", GetRegConfig()->GetDoubleRegisterName(i), dvalue, static_cast<uint32_t>(as_words >> 32), static_cast<uint32_t>(as_words & 0xffffffff)); } } else if (arg1[0] == 'r' && (arg1[1] >= '0' && arg1[1] <= '9' && (arg1[2] == '\0' || (arg1[2] >= '0' && arg1[2] <= '9' && arg1[3] == '\0')))) { int regnum = strtoul(&arg1[1], 0, 10); if (regnum != kNoRegister) { value = GetRegisterValue(regnum); PrintF("%s: 0x%08" V8PRIxPTR " %" V8PRIdPTR "\n", arg1, value, value); } else { PrintF("%s unrecognized\n", arg1); } } else { if (GetValue(arg1, &value)) { PrintF("%s: 0x%08" V8PRIxPTR " %" V8PRIdPTR "\n", arg1, value, value); } else if (GetFPDoubleValue(arg1, &dvalue)) { uint64_t as_words = bit_cast<uint64_t>(dvalue); PrintF("%s: %f 0x%08x %08x\n", arg1, dvalue, static_cast<uint32_t>(as_words >> 32), static_cast<uint32_t>(as_words & 0xffffffff)); } else { PrintF("%s unrecognized\n", arg1); } } } else { PrintF("print <register>\n"); } } else if ((strcmp(cmd, "po") == 0) || (strcmp(cmd, "printobject") == 0)) { if (argc == 2) { intptr_t value; OFStream os(stdout); if (GetValue(arg1, &value)) { Object* obj = reinterpret_cast<Object*>(value); os << arg1 << ": \n"; #ifdef DEBUG obj->Print(os); os << "\n"; #else os << Brief(obj) << "\n"; #endif } else { os << arg1 << " unrecognized\n"; } } else { PrintF("printobject <value>\n"); } } else if (strcmp(cmd, "setpc") == 0) { intptr_t value; if (!GetValue(arg1, &value)) { PrintF("%s unrecognized\n", arg1); continue; } sim_->set_pc(value); } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) { intptr_t* cur = nullptr; intptr_t* end = nullptr; int next_arg = 1; if (strcmp(cmd, "stack") == 0) { cur = reinterpret_cast<intptr_t*>(sim_->get_register(Simulator::sp)); } else { // "mem" intptr_t value; if (!GetValue(arg1, &value)) { PrintF("%s unrecognized\n", arg1); continue; } cur = reinterpret_cast<intptr_t*>(value); next_arg++; } intptr_t words; // likely inaccurate variable name for 64bit if (argc == next_arg) { words = 10; } else { if (!GetValue(argv[next_arg], &words)) { words = 10; } } end = cur + words; while (cur < end) { PrintF(" 0x%08" V8PRIxPTR ": 0x%08" V8PRIxPTR " %10" V8PRIdPTR, reinterpret_cast<intptr_t>(cur), *cur, *cur); HeapObject* obj = reinterpret_cast<HeapObject*>(*cur); intptr_t value = *cur; Heap* current_heap = sim_->isolate_->heap(); if (((value & 1) == 0) || current_heap->ContainsSlow(obj->address())) { PrintF(" ("); if ((value & 1) == 0) { PrintF("smi %d", PlatformSmiTagging::SmiToInt(obj)); } else { obj->ShortPrint(); } PrintF(")"); } PrintF("\n"); cur++; } } else if (strcmp(cmd, "disasm") == 0 || strcmp(cmd, "di") == 0) { disasm::NameConverter converter; disasm::Disassembler dasm(converter); // use a reasonably large buffer v8::internal::EmbeddedVector<char, 256> buffer; byte* prev = nullptr; byte* cur = nullptr; byte* end = nullptr; if (argc == 1) { cur = reinterpret_cast<byte*>(sim_->get_pc()); end = cur + (10 * Instruction::kInstrSize); } else if (argc == 2) { int regnum = Registers::Number(arg1); if (regnum != kNoRegister || strncmp(arg1, "0x", 2) == 0) { // The argument is an address or a register name. intptr_t value; if (GetValue(arg1, &value)) { cur = reinterpret_cast<byte*>(value); // Disassemble 10 instructions at <arg1>. end = cur + (10 * Instruction::kInstrSize); } } else { // The argument is the number of instructions. intptr_t value; if (GetValue(arg1, &value)) { cur = reinterpret_cast<byte*>(sim_->get_pc()); // Disassemble <arg1> instructions. end = cur + (value * Instruction::kInstrSize); } } } else { intptr_t value1; intptr_t value2; if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) { cur = reinterpret_cast<byte*>(value1); end = cur + (value2 * Instruction::kInstrSize); } } while (cur < end) { prev = cur; cur += dasm.InstructionDecode(buffer, cur); PrintF(" 0x%08" V8PRIxPTR " %s\n", reinterpret_cast<intptr_t>(prev), buffer.start()); } } else if (strcmp(cmd, "gdb") == 0) { PrintF("relinquishing control to gdb\n"); v8::base::OS::DebugBreak(); PrintF("regaining control from gdb\n"); } else if (strcmp(cmd, "break") == 0) { if (argc == 2) { intptr_t value; if (GetValue(arg1, &value)) { if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) { PrintF("setting breakpoint failed\n"); } } else { PrintF("%s unrecognized\n", arg1); } } else { PrintF("break <address>\n"); } } else if (strcmp(cmd, "del") == 0) { if (!DeleteBreakpoint(nullptr)) { PrintF("deleting breakpoint failed\n"); } } else if (strcmp(cmd, "cr") == 0) { PrintF("Condition reg: %08x\n", sim_->condition_reg_); } else if (strcmp(cmd, "lr") == 0) { PrintF("Link reg: %08" V8PRIxPTR "\n", sim_->special_reg_lr_); } else if (strcmp(cmd, "ctr") == 0) { PrintF("Ctr reg: %08" V8PRIxPTR "\n", sim_->special_reg_ctr_); } else if (strcmp(cmd, "xer") == 0) { PrintF("XER: %08x\n", sim_->special_reg_xer_); } else if (strcmp(cmd, "fpscr") == 0) { PrintF("FPSCR: %08x\n", sim_->fp_condition_reg_); } else if (strcmp(cmd, "stop") == 0) { intptr_t value; intptr_t stop_pc = sim_->get_pc() - (Instruction::kInstrSize + kPointerSize); Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc); Instruction* msg_address = reinterpret_cast<Instruction*>(stop_pc + Instruction::kInstrSize); if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) { // Remove the current stop. if (sim_->isStopInstruction(stop_instr)) { stop_instr->SetInstructionBits(kNopInstr); msg_address->SetInstructionBits(kNopInstr); } else { PrintF("Not at debugger stop.\n"); } } else if (argc == 3) { // Print information about all/the specified breakpoint(s). if (strcmp(arg1, "info") == 0) { if (strcmp(arg2, "all") == 0) { PrintF("Stop information:\n"); for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) { sim_->PrintStopInfo(i); } } else if (GetValue(arg2, &value)) { sim_->PrintStopInfo(value); } else { PrintF("Unrecognized argument.\n"); } } else if (strcmp(arg1, "enable") == 0) { // Enable all/the specified breakpoint(s). if (strcmp(arg2, "all") == 0) { for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) { sim_->EnableStop(i); } } else if (GetValue(arg2, &value)) { sim_->EnableStop(value); } else { PrintF("Unrecognized argument.\n"); } } else if (strcmp(arg1, "disable") == 0) { // Disable all/the specified breakpoint(s). if (strcmp(arg2, "all") == 0) { for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) { sim_->DisableStop(i); } } else if (GetValue(arg2, &value)) { sim_->DisableStop(value); } else { PrintF("Unrecognized argument.\n"); } } } else { PrintF("Wrong usage. Use help command for more information.\n"); } } else if ((strcmp(cmd, "t") == 0) || strcmp(cmd, "trace") == 0) { ::v8::internal::FLAG_trace_sim = !::v8::internal::FLAG_trace_sim; PrintF("Trace of executed instructions is %s\n", ::v8::internal::FLAG_trace_sim ? "on" : "off"); } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) { PrintF("cont\n"); PrintF(" continue execution (alias 'c')\n"); PrintF("stepi [num instructions]\n"); PrintF(" step one/num instruction(s) (alias 'si')\n"); PrintF("print <register>\n"); PrintF(" print register content (alias 'p')\n"); PrintF(" use register name 'all' to display all integer registers\n"); PrintF( " use register name 'alld' to display integer registers " "with decimal values\n"); PrintF(" use register name 'rN' to display register number 'N'\n"); PrintF(" add argument 'fp' to print register pair double values\n"); PrintF( " use register name 'allf' to display floating-point " "registers\n"); PrintF("printobject <register>\n"); PrintF(" print an object from a register (alias 'po')\n"); PrintF("cr\n"); PrintF(" print condition register\n"); PrintF("lr\n"); PrintF(" print link register\n"); PrintF("ctr\n"); PrintF(" print ctr register\n"); PrintF("xer\n"); PrintF(" print XER\n"); PrintF("fpscr\n"); PrintF(" print FPSCR\n"); PrintF("stack [<num words>]\n"); PrintF(" dump stack content, default dump 10 words)\n"); PrintF("mem <address> [<num words>]\n"); PrintF(" dump memory content, default dump 10 words)\n"); PrintF("disasm [<instructions>]\n"); PrintF("disasm [<address/register>]\n"); PrintF("disasm [[<address/register>] <instructions>]\n"); PrintF(" disassemble code, default is 10 instructions\n"); PrintF(" from pc (alias 'di')\n"); PrintF("gdb\n"); PrintF(" enter gdb\n"); PrintF("break <address>\n"); PrintF(" set a break point on the address\n"); PrintF("del\n"); PrintF(" delete the breakpoint\n"); PrintF("trace (alias 't')\n"); PrintF(" toogle the tracing of all executed statements\n"); PrintF("stop feature:\n"); PrintF(" Description:\n"); PrintF(" Stops are debug instructions inserted by\n"); PrintF(" the Assembler::stop() function.\n"); PrintF(" When hitting a stop, the Simulator will\n"); PrintF(" stop and and give control to the PPCDebugger.\n"); PrintF(" The first %d stop codes are watched:\n", Simulator::kNumOfWatchedStops); PrintF(" - They can be enabled / disabled: the Simulator\n"); PrintF(" will / won't stop when hitting them.\n"); PrintF(" - The Simulator keeps track of how many times they \n"); PrintF(" are met. (See the info command.) Going over a\n"); PrintF(" disabled stop still increases its counter. \n"); PrintF(" Commands:\n"); PrintF(" stop info all/<code> : print infos about number <code>\n"); PrintF(" or all stop(s).\n"); PrintF(" stop enable/disable all/<code> : enables / disables\n"); PrintF(" all or number <code> stop(s)\n"); PrintF(" stop unstop\n"); PrintF(" ignore the stop instruction at the current location\n"); PrintF(" from now on\n"); } else { PrintF("Unknown command: %s\n", cmd); } } } // Add all the breakpoints back to stop execution and enter the debugger // shell when hit. RedoBreakpoints(); // Restore tracing ::v8::internal::FLAG_trace_sim = trace; #undef COMMAND_SIZE #undef ARG_SIZE #undef STR #undef XSTR } static bool ICacheMatch(void* one, void* two) { DCHECK_EQ(reinterpret_cast<intptr_t>(one) & CachePage::kPageMask, 0); DCHECK_EQ(reinterpret_cast<intptr_t>(two) & CachePage::kPageMask, 0); return one == two; } static uint32_t ICacheHash(void* key) { return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key)) >> 2; } static bool AllOnOnePage(uintptr_t start, int size) { intptr_t start_page = (start & ~CachePage::kPageMask); intptr_t end_page = ((start + size) & ~CachePage::kPageMask); return start_page == end_page; } void Simulator::set_last_debugger_input(char* input) { DeleteArray(last_debugger_input_); last_debugger_input_ = input; } void Simulator::FlushICache(base::CustomMatcherHashMap* i_cache, void* start_addr, size_t size) { intptr_t start = reinterpret_cast<intptr_t>(start_addr); int intra_line = (start & CachePage::kLineMask); start -= intra_line; size += intra_line; size = ((size - 1) | CachePage::kLineMask) + 1; int offset = (start & CachePage::kPageMask); while (!AllOnOnePage(start, size - 1)) { int bytes_to_flush = CachePage::kPageSize - offset; FlushOnePage(i_cache, start, bytes_to_flush); start += bytes_to_flush; size -= bytes_to_flush; DCHECK_EQ(0, static_cast<int>(start & CachePage::kPageMask)); offset = 0; } if (size != 0) { FlushOnePage(i_cache, start, size); } } CachePage* Simulator::GetCachePage(base::CustomMatcherHashMap* i_cache, void* page) { base::HashMap::Entry* entry = i_cache->LookupOrInsert(page, ICacheHash(page)); if (entry->value == nullptr) { CachePage* new_page = new CachePage(); entry->value = new_page; } return reinterpret_cast<CachePage*>(entry->value); } // Flush from start up to and not including start + size. void Simulator::FlushOnePage(base::CustomMatcherHashMap* i_cache, intptr_t start, int size) { DCHECK_LE(size, CachePage::kPageSize); DCHECK(AllOnOnePage(start, size - 1)); DCHECK_EQ(start & CachePage::kLineMask, 0); DCHECK_EQ(size & CachePage::kLineMask, 0); void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask)); int offset = (start & CachePage::kPageMask); CachePage* cache_page = GetCachePage(i_cache, page); char* valid_bytemap = cache_page->ValidityByte(offset); memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift); } void Simulator::CheckICache(base::CustomMatcherHashMap* i_cache, Instruction* instr) { intptr_t address = reinterpret_cast<intptr_t>(instr); void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask)); void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask)); int offset = (address & CachePage::kPageMask); CachePage* cache_page = GetCachePage(i_cache, page); char* cache_valid_byte = cache_page->ValidityByte(offset); bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID); char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask); if (cache_hit) { // Check that the data in memory matches the contents of the I-cache. CHECK_EQ(0, memcmp(reinterpret_cast<void*>(instr), cache_page->CachedData(offset), Instruction::kInstrSize)); } else { // Cache miss. Load memory into the cache. memcpy(cached_line, line, CachePage::kLineLength); *cache_valid_byte = CachePage::LINE_VALID; } } void Simulator::Initialize(Isolate* isolate) { if (isolate->simulator_initialized()) return; isolate->set_simulator_initialized(true); ::v8::internal::ExternalReference::set_redirector(isolate, &RedirectExternalReference); } Simulator::Simulator(Isolate* isolate) : isolate_(isolate) { i_cache_ = isolate_->simulator_i_cache(); if (i_cache_ == nullptr) { i_cache_ = new base::CustomMatcherHashMap(&ICacheMatch); isolate_->set_simulator_i_cache(i_cache_); } Initialize(isolate); // Set up simulator support first. Some of this information is needed to // setup the architecture state. #if V8_TARGET_ARCH_PPC64 size_t stack_size = FLAG_sim_stack_size * KB; #else size_t stack_size = MB; // allocate 1MB for stack #endif stack_size += 2 * stack_protection_size_; stack_ = reinterpret_cast<char*>(malloc(stack_size)); pc_modified_ = false; icount_ = 0; break_pc_ = nullptr; break_instr_ = 0; // Set up architecture state. // All registers are initialized to zero to start with. for (int i = 0; i < kNumGPRs; i++) { registers_[i] = 0; } condition_reg_ = 0; fp_condition_reg_ = 0; special_reg_pc_ = 0; special_reg_lr_ = 0; special_reg_ctr_ = 0; // Initializing FP registers. for (int i = 0; i < kNumFPRs; i++) { fp_registers_[i] = 0.0; } // The sp is initialized to point to the bottom (high address) of the // allocated stack area. To be safe in potential stack underflows we leave // some buffer below. registers_[sp] = reinterpret_cast<intptr_t>(stack_) + stack_size - stack_protection_size_; last_debugger_input_ = nullptr; } Simulator::~Simulator() { global_monitor_.Pointer()->RemoveProcessor(&global_monitor_processor_); free(stack_); } // When the generated code calls an external reference we need to catch that in // the simulator. The external reference will be a function compiled for the // host architecture. We need to call that function instead of trying to // execute it with the simulator. We do that by redirecting the external // reference to a svc (Supervisor Call) instruction that is handled by // the simulator. We write the original destination of the jump just at a known // offset from the svc instruction so the simulator knows what to call. class Redirection { public: Redirection(Isolate* isolate, void* external_function, ExternalReference::Type type) : external_function_(external_function), swi_instruction_(rtCallRedirInstr | kCallRtRedirected), type_(type), next_(nullptr) { next_ = isolate->simulator_redirection(); Simulator::current(isolate)->FlushICache( isolate->simulator_i_cache(), reinterpret_cast<void*>(&swi_instruction_), Instruction::kInstrSize); isolate->set_simulator_redirection(this); if (ABI_USES_FUNCTION_DESCRIPTORS) { function_descriptor_[0] = reinterpret_cast<intptr_t>(&swi_instruction_); function_descriptor_[1] = 0; function_descriptor_[2] = 0; } } void* address() { if (ABI_USES_FUNCTION_DESCRIPTORS) { return reinterpret_cast<void*>(function_descriptor_); } else { return reinterpret_cast<void*>(&swi_instruction_); } } void* external_function() { return external_function_; } ExternalReference::Type type() { return type_; } static Redirection* Get(Isolate* isolate, void* external_function, ExternalReference::Type type) { Redirection* current = isolate->simulator_redirection(); for (; current != nullptr; current = current->next_) { if (current->external_function_ == external_function && current->type_ == type) { return current; } } return new Redirection(isolate, external_function, type); } static Redirection* FromSwiInstruction(Instruction* swi_instruction) { char* addr_of_swi = reinterpret_cast<char*>(swi_instruction); char* addr_of_redirection = addr_of_swi - offsetof(Redirection, swi_instruction_); return reinterpret_cast<Redirection*>(addr_of_redirection); } static Redirection* FromAddress(void* address) { int delta = ABI_USES_FUNCTION_DESCRIPTORS ? offsetof(Redirection, function_descriptor_) : offsetof(Redirection, swi_instruction_); char* addr_of_redirection = reinterpret_cast<char*>(address) - delta; return reinterpret_cast<Redirection*>(addr_of_redirection); } static void* ReverseRedirection(intptr_t reg) { Redirection* redirection = FromAddress(reinterpret_cast<void*>(reg)); return redirection->external_function(); } static void DeleteChain(Redirection* redirection) { while (redirection != nullptr) { Redirection* next = redirection->next_; delete redirection; redirection = next; } } private: void* external_function_; uint32_t swi_instruction_; ExternalReference::Type type_; Redirection* next_; intptr_t function_descriptor_[3]; }; // static void Simulator::TearDown(base::CustomMatcherHashMap* i_cache, Redirection* first) { Redirection::DeleteChain(first); if (i_cache != nullptr) { for (base::HashMap::Entry* entry = i_cache->Start(); entry != nullptr; entry = i_cache->Next(entry)) { delete static_cast<CachePage*>(entry->value); } delete i_cache; } } void* Simulator::RedirectExternalReference(Isolate* isolate, void* external_function, ExternalReference::Type type) { base::LockGuard<base::Mutex> lock_guard( isolate->simulator_redirection_mutex()); Redirection* redirection = Redirection::Get(isolate, external_function, type); return redirection->address(); } // Get the active Simulator for the current thread. Simulator* Simulator::current(Isolate* isolate) { v8::internal::Isolate::PerIsolateThreadData* isolate_data = isolate->FindOrAllocatePerThreadDataForThisThread(); DCHECK_NOT_NULL(isolate_data); Simulator* sim = isolate_data->simulator(); if (sim == nullptr) { // TODO(146): delete the simulator object when a thread/isolate goes away. sim = new Simulator(isolate); isolate_data->set_simulator(sim); } return sim; } // Sets the register in the architecture state. void Simulator::set_register(int reg, intptr_t value) { DCHECK((reg >= 0) && (reg < kNumGPRs)); registers_[reg] = value; } // Get the register from the architecture state. intptr_t Simulator::get_register(int reg) const { DCHECK((reg >= 0) && (reg < kNumGPRs)); // Stupid code added to avoid bug in GCC. // See: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43949 if (reg >= kNumGPRs) return 0; // End stupid code. return registers_[reg]; } double Simulator::get_double_from_register_pair(int reg) { DCHECK((reg >= 0) && (reg < kNumGPRs) && ((reg % 2) == 0)); double dm_val = 0.0; #if !V8_TARGET_ARCH_PPC64 // doesn't make sense in 64bit mode // Read the bits from the unsigned integer register_[] array // into the double precision floating point value and return it. char buffer[sizeof(fp_registers_[0])]; memcpy(buffer, &registers_[reg], 2 * sizeof(registers_[0])); memcpy(&dm_val, buffer, 2 * sizeof(registers_[0])); #endif return (dm_val); } // Raw access to the PC register. void Simulator::set_pc(intptr_t value) { pc_modified_ = true; special_reg_pc_ = value; } bool Simulator::has_bad_pc() const { return ((special_reg_pc_ == bad_lr) || (special_reg_pc_ == end_sim_pc)); } // Raw access to the PC register without the special adjustment when reading. intptr_t Simulator::get_pc() const { return special_reg_pc_; } // Runtime FP routines take: // - two double arguments // - one double argument and zero or one integer arguments. // All are consructed here from d1, d2 and r3. void Simulator::GetFpArgs(double* x, double* y, intptr_t* z) { *x = get_double_from_d_register(1); *y = get_double_from_d_register(2); *z = get_register(3); } // The return value is in d1. void Simulator::SetFpResult(const double& result) { set_d_register_from_double(1, result); } void Simulator::TrashCallerSaveRegisters() { // We don't trash the registers with the return value. #if 0 // A good idea to trash volatile registers, needs to be done registers_[2] = 0x50Bad4U; registers_[3] = 0x50Bad4U; registers_[12] = 0x50Bad4U; #endif } uint32_t Simulator::ReadWU(intptr_t addr, Instruction* instr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoad(addr); uint32_t* ptr = reinterpret_cast<uint32_t*>(addr); return *ptr; } uint32_t Simulator::ReadExWU(intptr_t addr, Instruction* instr) { base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoadExcl(addr, TransactionSize::Word); global_monitor_.Pointer()->NotifyLoadExcl_Locked(addr, &global_monitor_processor_); uint32_t* ptr = reinterpret_cast<uint32_t*>(addr); return *ptr; } int32_t Simulator::ReadW(intptr_t addr, Instruction* instr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoad(addr); int32_t* ptr = reinterpret_cast<int32_t*>(addr); return *ptr; } void Simulator::WriteW(intptr_t addr, uint32_t value, Instruction* instr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyStore(addr); global_monitor_.Pointer()->NotifyStore_Locked(addr, &global_monitor_processor_); uint32_t* ptr = reinterpret_cast<uint32_t*>(addr); *ptr = value; return; } int Simulator::WriteExW(intptr_t addr, uint32_t value, Instruction* instr) { base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); if (local_monitor_.NotifyStoreExcl(addr, TransactionSize::Word) && global_monitor_.Pointer()->NotifyStoreExcl_Locked( addr, &global_monitor_processor_)) { uint32_t* ptr = reinterpret_cast<uint32_t*>(addr); *ptr = value; return 0; } else { return 1; } } void Simulator::WriteW(intptr_t addr, int32_t value, Instruction* instr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyStore(addr); global_monitor_.Pointer()->NotifyStore_Locked(addr, &global_monitor_processor_); int32_t* ptr = reinterpret_cast<int32_t*>(addr); *ptr = value; return; } uint16_t Simulator::ReadHU(intptr_t addr, Instruction* instr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoad(addr); uint16_t* ptr = reinterpret_cast<uint16_t*>(addr); return *ptr; } uint16_t Simulator::ReadExHU(intptr_t addr, Instruction* instr) { base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoadExcl(addr, TransactionSize::HalfWord); global_monitor_.Pointer()->NotifyLoadExcl_Locked(addr, &global_monitor_processor_); uint16_t* ptr = reinterpret_cast<uint16_t*>(addr); return *ptr; } int16_t Simulator::ReadH(intptr_t addr, Instruction* instr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoad(addr); int16_t* ptr = reinterpret_cast<int16_t*>(addr); return *ptr; } void Simulator::WriteH(intptr_t addr, uint16_t value, Instruction* instr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyStore(addr); global_monitor_.Pointer()->NotifyStore_Locked(addr, &global_monitor_processor_); uint16_t* ptr = reinterpret_cast<uint16_t*>(addr); *ptr = value; return; } void Simulator::WriteH(intptr_t addr, int16_t value, Instruction* instr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyStore(addr); global_monitor_.Pointer()->NotifyStore_Locked(addr, &global_monitor_processor_); int16_t* ptr = reinterpret_cast<int16_t*>(addr); *ptr = value; return; } int Simulator::WriteExH(intptr_t addr, uint16_t value, Instruction* instr) { base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); if (local_monitor_.NotifyStoreExcl(addr, TransactionSize::HalfWord) && global_monitor_.Pointer()->NotifyStoreExcl_Locked( addr, &global_monitor_processor_)) { uint16_t* ptr = reinterpret_cast<uint16_t*>(addr); *ptr = value; return 0; } else { return 1; } } uint8_t Simulator::ReadBU(intptr_t addr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoad(addr); uint8_t* ptr = reinterpret_cast<uint8_t*>(addr); return *ptr; } int8_t Simulator::ReadB(intptr_t addr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoad(addr); int8_t* ptr = reinterpret_cast<int8_t*>(addr); return *ptr; } uint8_t Simulator::ReadExBU(intptr_t addr) { base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoadExcl(addr, TransactionSize::Byte); global_monitor_.Pointer()->NotifyLoadExcl_Locked(addr, &global_monitor_processor_); uint8_t* ptr = reinterpret_cast<uint8_t*>(addr); return *ptr; } void Simulator::WriteB(intptr_t addr, uint8_t value) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyStore(addr); global_monitor_.Pointer()->NotifyStore_Locked(addr, &global_monitor_processor_); uint8_t* ptr = reinterpret_cast<uint8_t*>(addr); *ptr = value; } void Simulator::WriteB(intptr_t addr, int8_t value) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyStore(addr); global_monitor_.Pointer()->NotifyStore_Locked(addr, &global_monitor_processor_); int8_t* ptr = reinterpret_cast<int8_t*>(addr); *ptr = value; } int Simulator::WriteExB(intptr_t addr, uint8_t value) { base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); if (local_monitor_.NotifyStoreExcl(addr, TransactionSize::Byte) && global_monitor_.Pointer()->NotifyStoreExcl_Locked( addr, &global_monitor_processor_)) { uint8_t* ptr = reinterpret_cast<uint8_t*>(addr); *ptr = value; return 0; } else { return 1; } } intptr_t* Simulator::ReadDW(intptr_t addr) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyLoad(addr); intptr_t* ptr = reinterpret_cast<intptr_t*>(addr); return ptr; } void Simulator::WriteDW(intptr_t addr, int64_t value) { // All supported PPC targets allow unaligned accesses, so we don't need to // check the alignment here. base::LockGuard<base::Mutex> lock_guard(&global_monitor_.Pointer()->mutex); local_monitor_.NotifyStore(addr); global_monitor_.Pointer()->NotifyStore_Locked(addr, &global_monitor_processor_); int64_t* ptr = reinterpret_cast<int64_t*>(addr); *ptr = value; return; } // Returns the limit of the stack area to enable checking for stack overflows. uintptr_t Simulator::StackLimit(uintptr_t c_limit) const { // The simulator uses a separate JS stack. If we have exhausted the C stack, // we also drop down the JS limit to reflect the exhaustion on the JS stack. if (GetCurrentStackPosition() < c_limit) { return reinterpret_cast<uintptr_t>(get_sp()); } // Otherwise the limit is the JS stack. Leave a safety margin to prevent // overrunning the stack when pushing values. return reinterpret_cast<uintptr_t>(stack_) + stack_protection_size_; } // Unsupported instructions use Format to print an error and stop execution. void Simulator::Format(Instruction* instr, const char* format) { PrintF("Simulator found unsupported instruction:\n 0x%08" V8PRIxPTR ": %s\n", reinterpret_cast<intptr_t>(instr), format); UNIMPLEMENTED(); } // Calculate C flag value for additions. bool Simulator::CarryFrom(int32_t left, int32_t right, int32_t carry) { uint32_t uleft = static_cast<uint32_t>(left); uint32_t uright = static_cast<uint32_t>(right); uint32_t urest = 0xffffffffU - uleft; return (uright > urest) || (carry && (((uright + 1) > urest) || (uright > (urest - 1)))); } // Calculate C flag value for subtractions. bool Simulator::BorrowFrom(int32_t left, int32_t right) { uint32_t uleft = static_cast<uint32_t>(left); uint32_t uright = static_cast<uint32_t>(right); return (uright > uleft); } // Calculate V flag value for additions and subtractions. bool Simulator::OverflowFrom(int32_t alu_out, int32_t left, int32_t right, bool addition) { bool overflow; if (addition) { // operands have the same sign overflow = ((left >= 0 && right >= 0) || (left < 0 && right < 0)) // and operands and result have different sign && ((left < 0 && alu_out >= 0) || (left >= 0 && alu_out < 0)); } else { // operands have different signs overflow = ((left < 0 && right >= 0) || (left >= 0 && right < 0)) // and first operand and result have different signs && ((left < 0 && alu_out >= 0) || (left >= 0 && alu_out < 0)); } return overflow; } #if V8_TARGET_ARCH_PPC64 static void decodeObjectPair(ObjectPair* pair, intptr_t* x, intptr_t* y) { *x = reinterpret_cast<intptr_t>(pair->x); *y = reinterpret_cast<intptr_t>(pair->y); } #else static void decodeObjectPair(ObjectPair* pair, intptr_t* x, intptr_t* y) { #if V8_TARGET_BIG_ENDIAN *x = static_cast<int32_t>(*pair >> 32); *y = static_cast<int32_t>(*pair); #else *x = static_cast<int32_t>(*pair); *y = static_cast<int32_t>(*pair >> 32); #endif } #endif // Calls into the V8 runtime. typedef intptr_t (*SimulatorRuntimeCall)(intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, intptr_t arg7, intptr_t arg8); typedef ObjectPair (*SimulatorRuntimePairCall)(intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5); // These prototypes handle the four types of FP calls. typedef int (*SimulatorRuntimeCompareCall)(double darg0, double darg1); typedef double (*SimulatorRuntimeFPFPCall)(double darg0, double darg1); typedef double (*SimulatorRuntimeFPCall)(double darg0); typedef double (*SimulatorRuntimeFPIntCall)(double darg0, intptr_t arg0); // This signature supports direct call in to API function native callback // (refer to InvocationCallback in v8.h). typedef void (*SimulatorRuntimeDirectApiCall)(intptr_t arg0); typedef void (*SimulatorRuntimeProfilingApiCall)(intptr_t arg0, void* arg1); // This signature supports direct call to accessor getter callback. typedef void (*SimulatorRuntimeDirectGetterCall)(intptr_t arg0, intptr_t arg1); typedef void (*SimulatorRuntimeProfilingGetterCall)(intptr_t arg0, intptr_t arg1, void* arg2); // Software interrupt instructions are used by the simulator to call into the // C-based V8 runtime. void Simulator::SoftwareInterrupt(Instruction* instr) { int svc = instr->SvcValue(); switch (svc) { case kCallRtRedirected: { // Check if stack is aligned. Error if not aligned is reported below to // include information on the function called. bool stack_aligned = (get_register(sp) & (::v8::internal::FLAG_sim_stack_alignment - 1)) == 0; Redirection* redirection = Redirection::FromSwiInstruction(instr); const int kArgCount = 9; const int kRegisterArgCount = 8; int arg0_regnum = 3; intptr_t result_buffer = 0; bool uses_result_buffer = (redirection->type() == ExternalReference::BUILTIN_CALL_PAIR && !ABI_RETURNS_OBJECT_PAIRS_IN_REGS); if (uses_result_buffer) { result_buffer = get_register(r3); arg0_regnum++; } intptr_t arg[kArgCount]; // First eight arguments in registers r3-r10. for (int i = 0; i < kRegisterArgCount; i++) { arg[i] = get_register(arg0_regnum + i); } intptr_t* stack_pointer = reinterpret_cast<intptr_t*>(get_register(sp)); // Remaining argument on stack arg[kRegisterArgCount] = stack_pointer[kStackFrameExtraParamSlot]; STATIC_ASSERT(kArgCount == kRegisterArgCount + 1); STATIC_ASSERT(kMaxCParameters == 9); bool fp_call = (redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) || (redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) || (redirection->type() == ExternalReference::BUILTIN_FP_CALL) || (redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL); // This is dodgy but it works because the C entry stubs are never moved. // See comment in codegen-arm.cc and bug 1242173. intptr_t saved_lr = special_reg_lr_; intptr_t external = reinterpret_cast<intptr_t>(redirection->external_function()); if (fp_call) { double dval0, dval1; // one or two double parameters intptr_t ival; // zero or one integer parameters int iresult = 0; // integer return value double dresult = 0; // double return value GetFpArgs(&dval0, &dval1, &ival); if (::v8::internal::FLAG_trace_sim || !stack_aligned) { SimulatorRuntimeCall generic_target = reinterpret_cast<SimulatorRuntimeCall>(external); switch (redirection->type()) { case ExternalReference::BUILTIN_FP_FP_CALL: case ExternalReference::BUILTIN_COMPARE_CALL: PrintF("Call to host function at %p with args %f, %f", static_cast<void*>(FUNCTION_ADDR(generic_target)), dval0, dval1); break; case ExternalReference::BUILTIN_FP_CALL: PrintF("Call to host function at %p with arg %f", static_cast<void*>(FUNCTION_ADDR(generic_target)), dval0); break; case ExternalReference::BUILTIN_FP_INT_CALL: PrintF("Call to host function at %p with args %f, %" V8PRIdPTR, static_cast<void*>(FUNCTION_ADDR(generic_target)), dval0, ival); break; default: UNREACHABLE(); break; } if (!stack_aligned) { PrintF(" with unaligned stack %08" V8PRIxPTR "\n", get_register(sp)); } PrintF("\n"); } CHECK(stack_aligned); switch (redirection->type()) { case ExternalReference::BUILTIN_COMPARE_CALL: { SimulatorRuntimeCompareCall target = reinterpret_cast<SimulatorRuntimeCompareCall>(external); iresult = target(dval0, dval1); set_register(r3, iresult); break; } case ExternalReference::BUILTIN_FP_FP_CALL: { SimulatorRuntimeFPFPCall target = reinterpret_cast<SimulatorRuntimeFPFPCall>(external); dresult = target(dval0, dval1); SetFpResult(dresult); break; } case ExternalReference::BUILTIN_FP_CALL: { SimulatorRuntimeFPCall target = reinterpret_cast<SimulatorRuntimeFPCall>(external); dresult = target(dval0); SetFpResult(dresult); break; } case ExternalReference::BUILTIN_FP_INT_CALL: { SimulatorRuntimeFPIntCall target = reinterpret_cast<SimulatorRuntimeFPIntCall>(external); dresult = target(dval0, ival); SetFpResult(dresult); break; } default: UNREACHABLE(); break; } if (::v8::internal::FLAG_trace_sim || !stack_aligned) { switch (redirection->type()) { case ExternalReference::BUILTIN_COMPARE_CALL: PrintF("Returned %08x\n", iresult); break; case ExternalReference::BUILTIN_FP_FP_CALL: case ExternalReference::BUILTIN_FP_CALL: case ExternalReference::BUILTIN_FP_INT_CALL: PrintF("Returned %f\n", dresult); break; default: UNREACHABLE(); break; } } } else if (redirection->type() == ExternalReference::DIRECT_API_CALL) { // See callers of MacroAssembler::CallApiFunctionAndReturn for // explanation of register usage. if (::v8::internal::FLAG_trace_sim || !stack_aligned) { PrintF("Call to host function at %p args %08" V8PRIxPTR, reinterpret_cast<void*>(external), arg[0]); if (!stack_aligned) { PrintF(" with unaligned stack %08" V8PRIxPTR "\n", get_register(sp)); } PrintF("\n"); } CHECK(stack_aligned); SimulatorRuntimeDirectApiCall target = reinterpret_cast<SimulatorRuntimeDirectApiCall>(external); target(arg[0]); } else if (redirection->type() == ExternalReference::PROFILING_API_CALL) { // See callers of MacroAssembler::CallApiFunctionAndReturn for // explanation of register usage. if (::v8::internal::FLAG_trace_sim || !stack_aligned) { PrintF("Call to host function at %p args %08" V8PRIxPTR " %08" V8PRIxPTR, reinterpret_cast<void*>(external), arg[0], arg[1]); if (!stack_aligned) { PrintF(" with unaligned stack %08" V8PRIxPTR "\n", get_register(sp)); } PrintF("\n"); } CHECK(stack_aligned); SimulatorRuntimeProfilingApiCall target = reinterpret_cast<SimulatorRuntimeProfilingApiCall>(external); target(arg[0], Redirection::ReverseRedirection(arg[1])); } else if (redirection->type() == ExternalReference::DIRECT_GETTER_CALL) { // See callers of MacroAssembler::CallApiFunctionAndReturn for // explanation of register usage. if (::v8::internal::FLAG_trace_sim || !stack_aligned) { PrintF("Call to host function at %p args %08" V8PRIxPTR " %08" V8PRIxPTR, reinterpret_cast<void*>(external), arg[0], arg[1]); if (!stack_aligned) { PrintF(" with unaligned stack %08" V8PRIxPTR "\n", get_register(sp)); } PrintF("\n"); } CHECK(stack_aligned); SimulatorRuntimeDirectGetterCall target = reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external); if (!ABI_PASSES_HANDLES_IN_REGS) { arg[0] = *(reinterpret_cast<intptr_t*>(arg[0])); } target(arg[0], arg[1]); } else if (redirection->type() == ExternalReference::PROFILING_GETTER_CALL) { if (::v8::internal::FLAG_trace_sim || !stack_aligned) { PrintF("Call to host function at %p args %08" V8PRIxPTR " %08" V8PRIxPTR " %08" V8PRIxPTR, reinterpret_cast<void*>(external), arg[0], arg[1], arg[2]); if (!stack_aligned) { PrintF(" with unaligned stack %08" V8PRIxPTR "\n", get_register(sp)); } PrintF("\n"); } CHECK(stack_aligned); SimulatorRuntimeProfilingGetterCall target = reinterpret_cast<SimulatorRuntimeProfilingGetterCall>(external); if (!ABI_PASSES_HANDLES_IN_REGS) { arg[0] = *(reinterpret_cast<intptr_t*>(arg[0])); } target(arg[0], arg[1], Redirection::ReverseRedirection(arg[2])); } else { // builtin call. if (::v8::internal::FLAG_trace_sim || !stack_aligned) { SimulatorRuntimeCall target = reinterpret_cast<SimulatorRuntimeCall>(external); PrintF( "Call to host function at %p,\n" "\t\t\t\targs %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR ", %08" V8PRIxPTR, static_cast<void*>(FUNCTION_ADDR(target)), arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8]); if (!stack_aligned) { PrintF(" with unaligned stack %08" V8PRIxPTR "\n", get_register(sp)); } PrintF("\n"); } CHECK(stack_aligned); if (redirection->type() == ExternalReference::BUILTIN_CALL_PAIR) { SimulatorRuntimePairCall target = reinterpret_cast<SimulatorRuntimePairCall>(external); ObjectPair result = target(arg[0], arg[1], arg[2], arg[3], arg[4], arg[5]); intptr_t x; intptr_t y; decodeObjectPair(&result, &x, &y); if (::v8::internal::FLAG_trace_sim) { PrintF("Returned {%08" V8PRIxPTR ", %08" V8PRIxPTR "}\n", x, y); } if (ABI_RETURNS_OBJECT_PAIRS_IN_REGS) { set_register(r3, x); set_register(r4, y); } else { memcpy(reinterpret_cast<void*>(result_buffer), &result, sizeof(ObjectPair)); set_register(r3, result_buffer); } } else { DCHECK(redirection->type() == ExternalReference::BUILTIN_CALL); SimulatorRuntimeCall target = reinterpret_cast<SimulatorRuntimeCall>(external); intptr_t result = target(arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8]); if (::v8::internal::FLAG_trace_sim) { PrintF("Returned %08" V8PRIxPTR "\n", result); } set_register(r3, result); } } set_pc(saved_lr); break; } case kBreakpoint: { PPCDebugger dbg(this); dbg.Debug(); break; } // stop uses all codes greater than 1 << 23. default: { if (svc >= (1 << 23)) { uint32_t code = svc & kStopCodeMask; if (isWatchedStop(code)) { IncreaseStopCounter(code); } // Stop if it is enabled, otherwise go on jumping over the stop // and the message address. if (isEnabledStop(code)) { PPCDebugger dbg(this); dbg.Stop(instr); } else { set_pc(get_pc() + Instruction::kInstrSize + kPointerSize); } } else { // This is not a valid svc code. UNREACHABLE(); break; } } } } // Stop helper functions. bool Simulator::isStopInstruction(Instruction* instr) { return (instr->Bits(27, 24) == 0xF) && (instr->SvcValue() >= kStopCode); } bool Simulator::isWatchedStop(uint32_t code) { DCHECK_LE(code, kMaxStopCode); return code < kNumOfWatchedStops; } bool Simulator::isEnabledStop(uint32_t code) { DCHECK_LE(code, kMaxStopCode); // Unwatched stops are always enabled. return !isWatchedStop(code) || !(watched_stops_[code].count & kStopDisabledBit); } void Simulator::EnableStop(uint32_t code) { DCHECK(isWatchedStop(code)); if (!isEnabledStop(code)) { watched_stops_[code].count &= ~kStopDisabledBit; } } void Simulator::DisableStop(uint32_t code) { DCHECK(isWatchedStop(code)); if (isEnabledStop(code)) { watched_stops_[code].count |= kStopDisabledBit; } } void Simulator::IncreaseStopCounter(uint32_t code) { DCHECK_LE(code, kMaxStopCode); DCHECK(isWatchedStop(code)); if ((watched_stops_[code].count & ~(1 << 31)) == 0x7fffffff) { PrintF( "Stop counter for code %i has overflowed.\n" "Enabling this code and reseting the counter to 0.\n", code); watched_stops_[code].count = 0; EnableStop(code); } else { watched_stops_[code].count++; } } // Print a stop status. void Simulator::PrintStopInfo(uint32_t code) { DCHECK_LE(code, kMaxStopCode); if (!isWatchedStop(code)) { PrintF("Stop not watched."); } else { const char* state = isEnabledStop(code) ? "Enabled" : "Disabled"; int32_t count = watched_stops_[code].count & ~kStopDisabledBit; // Don't print the state of unused breakpoints. if (count != 0) { if (watched_stops_[code].desc) { PrintF("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n", code, code, state, count, watched_stops_[code].desc); } else { PrintF("stop %i - 0x%x: \t%s, \tcounter = %i\n", code, code, state, count); } } } } void Simulator::SetCR0(intptr_t result, bool setSO) { int bf = 0; if (result < 0) { bf |= 0x80000000; } if (result > 0) { bf |= 0x40000000; } if (result == 0) { bf |= 0x20000000; } if (setSO) { bf |= 0x10000000; } condition_reg_ = (condition_reg_ & ~0xF0000000) | bf; } void Simulator::ExecuteBranchConditional(Instruction* instr, BCType type) { int bo = instr->Bits(25, 21) << 21; int condition_bit = instr->Bits(20, 16); int condition_mask = 0x80000000 >> condition_bit; switch (bo) { case DCBNZF: // Decrement CTR; branch if CTR != 0 and condition false case DCBEZF: // Decrement CTR; branch if CTR == 0 and condition false UNIMPLEMENTED(); case BF: { // Branch if condition false if (condition_reg_ & condition_mask) return; break; } case DCBNZT: // Decrement CTR; branch if CTR != 0 and condition true case DCBEZT: // Decrement CTR; branch if CTR == 0 and condition true UNIMPLEMENTED(); case BT: { // Branch if condition true if (!(condition_reg_ & condition_mask)) return; break; } case DCBNZ: // Decrement CTR; branch if CTR != 0 case DCBEZ: // Decrement CTR; branch if CTR == 0 special_reg_ctr_ -= 1; if ((special_reg_ctr_ == 0) != (bo == DCBEZ)) return; break; case BA: { // Branch always break; } default: UNIMPLEMENTED(); // Invalid encoding } intptr_t old_pc = get_pc(); switch (type) { case BC_OFFSET: { int offset = (instr->Bits(15, 2) << 18) >> 16; set_pc(old_pc + offset); break; } case BC_LINK_REG: set_pc(special_reg_lr_); break; case BC_CTR_REG: set_pc(special_reg_ctr_); break; } if (instr->Bit(0) == 1) { // LK flag set special_reg_lr_ = old_pc + 4; } } void Simulator::ExecuteGeneric(Instruction* instr) { uint32_t opcode = instr->OpcodeBase(); switch (opcode) { case SUBFIC: { int rt = instr->RTValue(); int ra = instr->RAValue(); intptr_t ra_val = get_register(ra); int32_t im_val = instr->Bits(15, 0); im_val = SIGN_EXT_IMM16(im_val); intptr_t alu_out = im_val - ra_val; set_register(rt, alu_out); // todo - handle RC bit break; } case CMPLI: { int ra = instr->RAValue(); uint32_t im_val = instr->Bits(15, 0); int cr = instr->Bits(25, 23); uint32_t bf = 0; #if V8_TARGET_ARCH_PPC64 int L = instr->Bit(21); if (L) { #endif uintptr_t ra_val = get_register(ra); if (ra_val < im_val) { bf |= 0x80000000; } if (ra_val > im_val) { bf |= 0x40000000; } if (ra_val == im_val) { bf |= 0x20000000; } #if V8_TARGET_ARCH_PPC64 } else { uint32_t ra_val = get_register(ra); if (ra_val < im_val) { bf |= 0x80000000; } if (ra_val > im_val) { bf |= 0x40000000; } if (ra_val == im_val) { bf |= 0x20000000; } } #endif uint32_t condition_mask = 0xF0000000U >> (cr * 4); uint32_t condition = bf >> (cr * 4); condition_reg_ = (condition_reg_ & ~condition_mask) | condition; break; } case CMPI: { int ra = instr->RAValue(); int32_t im_val = instr->Bits(15, 0); im_val = SIGN_EXT_IMM16(im_val); int cr = instr->Bits(25, 23); uint32_t bf = 0; #if V8_TARGET_ARCH_PPC64 int L = instr->Bit(21); if (L) { #endif intptr_t ra_val = get_register(ra); if (ra_val < im_val) { bf |= 0x80000000; } if (ra_val > im_val) { bf |= 0x40000000; } if (ra_val == im_val) { bf |= 0x20000000; } #if V8_TARGET_ARCH_PPC64 } else { int32_t ra_val = get_register(ra); if (ra_val < im_val) { bf |= 0x80000000; } if (ra_val > im_val) { bf |= 0x40000000; } if (ra_val == im_val) { bf |= 0x20000000; } } #endif uint32_t condition_mask = 0xF0000000U >> (cr * 4); uint32_t condition = bf >> (cr * 4); condition_reg_ = (condition_reg_ & ~condition_mask) | condition; break; } case ADDIC: { int rt = instr->RTValue(); int ra = instr->RAValue(); uintptr_t ra_val = get_register(ra); uintptr_t im_val = SIGN_EXT_IMM16(instr->Bits(15, 0)); uintptr_t alu_out = ra_val + im_val; // Check overflow if (~ra_val < im_val) { special_reg_xer_ = (special_reg_xer_ & ~0xF0000000) | 0x20000000; } else { special_reg_xer_ &= ~0xF0000000; } set_register(rt, alu_out); break; } case ADDI: { int rt = instr->RTValue(); int ra = instr->RAValue(); int32_t im_val = SIGN_EXT_IMM16(instr->Bits(15, 0)); intptr_t alu_out; if (ra == 0) { alu_out = im_val; } else { intptr_t ra_val = get_register(ra); alu_out = ra_val + im_val; } set_register(rt, alu_out); // todo - handle RC bit break; } case ADDIS: { int rt = instr->RTValue(); int ra = instr->RAValue(); int32_t im_val = (instr->Bits(15, 0) << 16); intptr_t alu_out; if (ra == 0) { // treat r0 as zero alu_out = im_val; } else { intptr_t ra_val = get_register(ra); alu_out = ra_val + im_val; } set_register(rt, alu_out); break; } case BCX: { ExecuteBranchConditional(instr, BC_OFFSET); break; } case BX: { int offset = (instr->Bits(25, 2) << 8) >> 6; if (instr->Bit(0) == 1) { // LK flag set special_reg_lr_ = get_pc() + 4; } set_pc(get_pc() + offset); // todo - AA flag break; } case MCRF: UNIMPLEMENTED(); // Not used by V8. case BCLRX: ExecuteBranchConditional(instr, BC_LINK_REG); break; case BCCTRX: ExecuteBranchConditional(instr, BC_CTR_REG); break; case CRNOR: case RFI: case CRANDC: UNIMPLEMENTED(); case ISYNC: { // todo - simulate isync break; } case CRXOR: { int bt = instr->Bits(25, 21); int ba = instr->Bits(20, 16); int bb = instr->Bits(15, 11); int ba_val = ((0x80000000 >> ba) & condition_reg_) == 0 ? 0 : 1; int bb_val = ((0x80000000 >> bb) & condition_reg_) == 0 ? 0 : 1; int bt_val = ba_val ^ bb_val; bt_val = bt_val << (31 - bt); // shift bit to correct destination condition_reg_ &= ~(0x80000000 >> bt); condition_reg_ |= bt_val; break; } case CREQV: { int bt = instr->Bits(25, 21); int ba = instr->Bits(20, 16); int bb = instr->Bits(15, 11); int ba_val = ((0x80000000 >> ba) & condition_reg_) == 0 ? 0 : 1; int bb_val = ((0x80000000 >> bb) & condition_reg_) == 0 ? 0 : 1; int bt_val = 1 - (ba_val ^ bb_val); bt_val = bt_val << (31 - bt); // shift bit to correct destination condition_reg_ &= ~(0x80000000 >> bt); condition_reg_ |= bt_val; break; } case CRNAND: case CRAND: case CRORC: case CROR: { UNIMPLEMENTED(); // Not used by V8. break; } case RLWIMIX: { int ra = instr->RAValue(); int rs = instr->RSValue(); uint32_t rs_val = get_register(rs); int32_t ra_val = get_register(ra); int sh = instr->Bits(15, 11); int mb = instr->Bits(10, 6); int me = instr->Bits(5, 1); uint32_t result = base::bits::RotateLeft32(rs_val, sh); int mask = 0; if (mb < me + 1) { int bit = 0x80000000 >> mb; for (; mb <= me; mb++) { mask |= bit; bit >>= 1; } } else if (mb == me + 1) { mask = 0xffffffff; } else { // mb > me+1 int bit = 0x80000000 >> (me + 1); // needs to be tested mask = 0xffffffff; for (; me < mb; me++) { mask ^= bit; bit >>= 1; } } result &= mask; ra_val &= ~mask; result |= ra_val; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } case RLWINMX: case RLWNMX: { int ra = instr->RAValue(); int rs = instr->RSValue(); uint32_t rs_val = get_register(rs); int sh = 0; if (opcode == RLWINMX) { sh = instr->Bits(15, 11); } else { int rb = instr->RBValue(); uint32_t rb_val = get_register(rb); sh = (rb_val & 0x1f); } int mb = instr->Bits(10, 6); int me = instr->Bits(5, 1); uint32_t result = base::bits::RotateLeft32(rs_val, sh); int mask = 0; if (mb < me + 1) { int bit = 0x80000000 >> mb; for (; mb <= me; mb++) { mask |= bit; bit >>= 1; } } else if (mb == me + 1) { mask = 0xffffffff; } else { // mb > me+1 int bit = 0x80000000 >> (me + 1); // needs to be tested mask = 0xffffffff; for (; me < mb; me++) { mask ^= bit; bit >>= 1; } } result &= mask; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } case ORI: { int rs = instr->RSValue(); int ra = instr->RAValue(); intptr_t rs_val = get_register(rs); uint32_t im_val = instr->Bits(15, 0); intptr_t alu_out = rs_val | im_val; set_register(ra, alu_out); break; } case ORIS: { int rs = instr->RSValue(); int ra = instr->RAValue(); intptr_t rs_val = get_register(rs); uint32_t im_val = instr->Bits(15, 0); intptr_t alu_out = rs_val | (im_val << 16); set_register(ra, alu_out); break; } case XORI: { int rs = instr->RSValue(); int ra = instr->RAValue(); intptr_t rs_val = get_register(rs); uint32_t im_val = instr->Bits(15, 0); intptr_t alu_out = rs_val ^ im_val; set_register(ra, alu_out); // todo - set condition based SO bit break; } case XORIS: { int rs = instr->RSValue(); int ra = instr->RAValue(); intptr_t rs_val = get_register(rs); uint32_t im_val = instr->Bits(15, 0); intptr_t alu_out = rs_val ^ (im_val << 16); set_register(ra, alu_out); break; } case ANDIx: { int rs = instr->RSValue(); int ra = instr->RAValue(); intptr_t rs_val = get_register(rs); uint32_t im_val = instr->Bits(15, 0); intptr_t alu_out = rs_val & im_val; set_register(ra, alu_out); SetCR0(alu_out); break; } case ANDISx: { int rs = instr->RSValue(); int ra = instr->RAValue(); intptr_t rs_val = get_register(rs); uint32_t im_val = instr->Bits(15, 0); intptr_t alu_out = rs_val & (im_val << 16); set_register(ra, alu_out); SetCR0(alu_out); break; } case SRWX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uint32_t rs_val = get_register(rs); uintptr_t rb_val = get_register(rb) & 0x3f; intptr_t result = (rb_val > 31) ? 0 : rs_val >> rb_val; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } #if V8_TARGET_ARCH_PPC64 case SRDX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uintptr_t rs_val = get_register(rs); uintptr_t rb_val = get_register(rb) & 0x7f; intptr_t result = (rb_val > 63) ? 0 : rs_val >> rb_val; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } #endif case MODUW: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uint32_t ra_val = get_register(ra); uint32_t rb_val = get_register(rb); uint32_t alu_out = (rb_val == 0) ? -1 : ra_val % rb_val; set_register(rt, alu_out); break; } #if V8_TARGET_ARCH_PPC64 case MODUD: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uint64_t ra_val = get_register(ra); uint64_t rb_val = get_register(rb); uint64_t alu_out = (rb_val == 0) ? -1 : ra_val % rb_val; set_register(rt, alu_out); break; } #endif case MODSW: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int32_t ra_val = get_register(ra); int32_t rb_val = get_register(rb); bool overflow = (ra_val == kMinInt && rb_val == -1); // result is undefined if divisor is zero or if operation // is 0x80000000 / -1. int32_t alu_out = (rb_val == 0 || overflow) ? -1 : ra_val % rb_val; set_register(rt, alu_out); break; } #if V8_TARGET_ARCH_PPC64 case MODSD: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int64_t ra_val = get_register(ra); int64_t rb_val = get_register(rb); int64_t one = 1; // work-around gcc int64_t kMinLongLong = (one << 63); // result is undefined if divisor is zero or if operation // is 0x80000000_00000000 / -1. int64_t alu_out = (rb_val == 0 || (ra_val == kMinLongLong && rb_val == -1)) ? -1 : ra_val % rb_val; set_register(rt, alu_out); break; } #endif case SRAW: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int32_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb) & 0x3f; intptr_t result = (rb_val > 31) ? rs_val >> 31 : rs_val >> rb_val; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } #if V8_TARGET_ARCH_PPC64 case SRAD: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb) & 0x7f; intptr_t result = (rb_val > 63) ? rs_val >> 63 : rs_val >> rb_val; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } #endif case SRAWIX: { int ra = instr->RAValue(); int rs = instr->RSValue(); int sh = instr->Bits(15, 11); int32_t rs_val = get_register(rs); intptr_t result = rs_val >> sh; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } #if V8_TARGET_ARCH_PPC64 case EXTSW: { const int shift = kBitsPerPointer - 32; int ra = instr->RAValue(); int rs = instr->RSValue(); intptr_t rs_val = get_register(rs); intptr_t ra_val = (rs_val << shift) >> shift; set_register(ra, ra_val); if (instr->Bit(0)) { // RC bit set SetCR0(ra_val); } break; } #endif case EXTSH: { const int shift = kBitsPerPointer - 16; int ra = instr->RAValue(); int rs = instr->RSValue(); intptr_t rs_val = get_register(rs); intptr_t ra_val = (rs_val << shift) >> shift; set_register(ra, ra_val); if (instr->Bit(0)) { // RC bit set SetCR0(ra_val); } break; } case EXTSB: { const int shift = kBitsPerPointer - 8; int ra = instr->RAValue(); int rs = instr->RSValue(); intptr_t rs_val = get_register(rs); intptr_t ra_val = (rs_val << shift) >> shift; set_register(ra, ra_val); if (instr->Bit(0)) { // RC bit set SetCR0(ra_val); } break; } case LFSUX: case LFSX: { int frt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); int32_t val = ReadW(ra_val + rb_val, instr); float* fptr = reinterpret_cast<float*>(&val); #if V8_HOST_ARCH_IA32 || V8_HOST_ARCH_X64 // Conversion using double changes sNan to qNan on ia32/x64 if ((val & 0x7f800000) == 0x7f800000) { int64_t dval = static_cast<int64_t>(val); dval = ((dval & 0xc0000000) << 32) | ((dval & 0x40000000) << 31) | ((dval & 0x40000000) << 30) | ((dval & 0x7fffffff) << 29) | 0x0; set_d_register(frt, dval); } else { set_d_register_from_double(frt, static_cast<double>(*fptr)); } #else set_d_register_from_double(frt, static_cast<double>(*fptr)); #endif if (opcode == LFSUX) { DCHECK_NE(ra, 0); set_register(ra, ra_val + rb_val); } break; } case LFDUX: case LFDX: { int frt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); int64_t* dptr = reinterpret_cast<int64_t*>(ReadDW(ra_val + rb_val)); set_d_register(frt, *dptr); if (opcode == LFDUX) { DCHECK_NE(ra, 0); set_register(ra, ra_val + rb_val); } break; } case STFSUX: { case STFSX: int frs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); float frs_val = static_cast<float>(get_double_from_d_register(frs)); int32_t* p = reinterpret_cast<int32_t*>(&frs_val); #if V8_HOST_ARCH_IA32 || V8_HOST_ARCH_X64 // Conversion using double changes sNan to qNan on ia32/x64 int32_t sval = 0; int64_t dval = get_d_register(frs); if ((dval & 0x7ff0000000000000) == 0x7ff0000000000000) { sval = ((dval & 0xc000000000000000) >> 32) | ((dval & 0x07ffffffe0000000) >> 29); p = &sval; } else { p = reinterpret_cast<int32_t*>(&frs_val); } #else p = reinterpret_cast<int32_t*>(&frs_val); #endif WriteW(ra_val + rb_val, *p, instr); if (opcode == STFSUX) { DCHECK_NE(ra, 0); set_register(ra, ra_val + rb_val); } break; } case STFDUX: { case STFDX: int frs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); int64_t frs_val = get_d_register(frs); WriteDW(ra_val + rb_val, frs_val); if (opcode == STFDUX) { DCHECK_NE(ra, 0); set_register(ra, ra_val + rb_val); } break; } case POPCNTW: { int rs = instr->RSValue(); int ra = instr->RAValue(); uintptr_t rs_val = get_register(rs); uintptr_t count = 0; int n = 0; uintptr_t bit = 0x80000000; for (; n < 32; n++) { if (bit & rs_val) count++; bit >>= 1; } set_register(ra, count); break; } #if V8_TARGET_ARCH_PPC64 case POPCNTD: { int rs = instr->RSValue(); int ra = instr->RAValue(); uintptr_t rs_val = get_register(rs); uintptr_t count = 0; int n = 0; uintptr_t bit = 0x8000000000000000UL; for (; n < 64; n++) { if (bit & rs_val) count++; bit >>= 1; } set_register(ra, count); break; } #endif case SYNC: { // todo - simulate sync break; } case ICBI: { // todo - simulate icbi break; } case LWZU: case LWZ: { int ra = instr->RAValue(); int rt = instr->RTValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); set_register(rt, ReadWU(ra_val + offset, instr)); if (opcode == LWZU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case LBZU: case LBZ: { int ra = instr->RAValue(); int rt = instr->RTValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); set_register(rt, ReadB(ra_val + offset) & 0xFF); if (opcode == LBZU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case STWU: case STW: { int ra = instr->RAValue(); int rs = instr->RSValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int32_t rs_val = get_register(rs); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); WriteW(ra_val + offset, rs_val, instr); if (opcode == STWU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case SRADIX: { int ra = instr->RAValue(); int rs = instr->RSValue(); int sh = (instr->Bits(15, 11) | (instr->Bit(1) << 5)); intptr_t rs_val = get_register(rs); intptr_t result = rs_val >> sh; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } case STBCX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int8_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); SetCR0(WriteExB(ra_val + rb_val, rs_val)); break; } case STHCX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int16_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); SetCR0(WriteExH(ra_val + rb_val, rs_val, instr)); break; } case STWCX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int32_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); SetCR0(WriteExW(ra_val + rb_val, rs_val, instr)); break; } case TW: { // used for call redirection in simulation mode SoftwareInterrupt(instr); break; } case CMP: { int ra = instr->RAValue(); int rb = instr->RBValue(); int cr = instr->Bits(25, 23); uint32_t bf = 0; #if V8_TARGET_ARCH_PPC64 int L = instr->Bit(21); if (L) { #endif intptr_t ra_val = get_register(ra); intptr_t rb_val = get_register(rb); if (ra_val < rb_val) { bf |= 0x80000000; } if (ra_val > rb_val) { bf |= 0x40000000; } if (ra_val == rb_val) { bf |= 0x20000000; } #if V8_TARGET_ARCH_PPC64 } else { int32_t ra_val = get_register(ra); int32_t rb_val = get_register(rb); if (ra_val < rb_val) { bf |= 0x80000000; } if (ra_val > rb_val) { bf |= 0x40000000; } if (ra_val == rb_val) { bf |= 0x20000000; } } #endif uint32_t condition_mask = 0xF0000000U >> (cr * 4); uint32_t condition = bf >> (cr * 4); condition_reg_ = (condition_reg_ & ~condition_mask) | condition; break; } case SUBFCX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); // int oe = instr->Bit(10); uintptr_t ra_val = get_register(ra); uintptr_t rb_val = get_register(rb); uintptr_t alu_out = ~ra_val + rb_val + 1; // Set carry if (ra_val <= rb_val) { special_reg_xer_ = (special_reg_xer_ & ~0xF0000000) | 0x20000000; } else { special_reg_xer_ &= ~0xF0000000; } set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } // todo - handle OE bit break; } case SUBFEX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); // int oe = instr->Bit(10); uintptr_t ra_val = get_register(ra); uintptr_t rb_val = get_register(rb); uintptr_t alu_out = ~ra_val + rb_val; if (special_reg_xer_ & 0x20000000) { alu_out += 1; } set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(static_cast<intptr_t>(alu_out)); } // todo - handle OE bit break; } case ADDCX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); // int oe = instr->Bit(10); uintptr_t ra_val = get_register(ra); uintptr_t rb_val = get_register(rb); uintptr_t alu_out = ra_val + rb_val; // Set carry if (~ra_val < rb_val) { special_reg_xer_ = (special_reg_xer_ & ~0xF0000000) | 0x20000000; } else { special_reg_xer_ &= ~0xF0000000; } set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(static_cast<intptr_t>(alu_out)); } // todo - handle OE bit break; } case ADDEX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); // int oe = instr->Bit(10); uintptr_t ra_val = get_register(ra); uintptr_t rb_val = get_register(rb); uintptr_t alu_out = ra_val + rb_val; if (special_reg_xer_ & 0x20000000) { alu_out += 1; } set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(static_cast<intptr_t>(alu_out)); } // todo - handle OE bit break; } case MULHWX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int32_t ra_val = (get_register(ra) & 0xFFFFFFFF); int32_t rb_val = (get_register(rb) & 0xFFFFFFFF); int64_t alu_out = (int64_t)ra_val * (int64_t)rb_val; alu_out >>= 32; set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(static_cast<intptr_t>(alu_out)); } break; } case MULHWUX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uint32_t ra_val = (get_register(ra) & 0xFFFFFFFF); uint32_t rb_val = (get_register(rb) & 0xFFFFFFFF); uint64_t alu_out = (uint64_t)ra_val * (uint64_t)rb_val; alu_out >>= 32; set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(static_cast<intptr_t>(alu_out)); } break; } case NEGX: { int rt = instr->RTValue(); int ra = instr->RAValue(); intptr_t ra_val = get_register(ra); intptr_t alu_out = 1 + ~ra_val; #if V8_TARGET_ARCH_PPC64 intptr_t one = 1; // work-around gcc intptr_t kOverflowVal = (one << 63); #else intptr_t kOverflowVal = kMinInt; #endif set_register(rt, alu_out); if (instr->Bit(10)) { // OE bit set if (ra_val == kOverflowVal) { special_reg_xer_ |= 0xC0000000; // set SO,OV } else { special_reg_xer_ &= ~0x40000000; // clear OV } } if (instr->Bit(0)) { // RC bit set bool setSO = (special_reg_xer_ & 0x80000000); SetCR0(alu_out, setSO); } break; } case SLWX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uint32_t rs_val = get_register(rs); uintptr_t rb_val = get_register(rb) & 0x3f; uint32_t result = (rb_val > 31) ? 0 : rs_val << rb_val; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } #if V8_TARGET_ARCH_PPC64 case SLDX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uintptr_t rs_val = get_register(rs); uintptr_t rb_val = get_register(rb) & 0x7f; uintptr_t result = (rb_val > 63) ? 0 : rs_val << rb_val; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } break; } case MFVSRD: { DCHECK(!instr->Bit(0)); int frt = instr->RTValue(); int ra = instr->RAValue(); int64_t frt_val = get_d_register(frt); set_register(ra, frt_val); break; } case MFVSRWZ: { DCHECK(!instr->Bit(0)); int frt = instr->RTValue(); int ra = instr->RAValue(); int64_t frt_val = get_d_register(frt); set_register(ra, static_cast<uint32_t>(frt_val)); break; } case MTVSRD: { DCHECK(!instr->Bit(0)); int frt = instr->RTValue(); int ra = instr->RAValue(); int64_t ra_val = get_register(ra); set_d_register(frt, ra_val); break; } case MTVSRWA: { DCHECK(!instr->Bit(0)); int frt = instr->RTValue(); int ra = instr->RAValue(); int64_t ra_val = static_cast<int32_t>(get_register(ra)); set_d_register(frt, ra_val); break; } case MTVSRWZ: { DCHECK(!instr->Bit(0)); int frt = instr->RTValue(); int ra = instr->RAValue(); uint64_t ra_val = static_cast<uint32_t>(get_register(ra)); set_d_register(frt, ra_val); break; } #endif case CNTLZWX: { int rs = instr->RSValue(); int ra = instr->RAValue(); uintptr_t rs_val = get_register(rs); uintptr_t count = 0; int n = 0; uintptr_t bit = 0x80000000; for (; n < 32; n++) { if (bit & rs_val) break; count++; bit >>= 1; } set_register(ra, count); if (instr->Bit(0)) { // RC Bit set int bf = 0; if (count > 0) { bf |= 0x40000000; } if (count == 0) { bf |= 0x20000000; } condition_reg_ = (condition_reg_ & ~0xF0000000) | bf; } break; } #if V8_TARGET_ARCH_PPC64 case CNTLZDX: { int rs = instr->RSValue(); int ra = instr->RAValue(); uintptr_t rs_val = get_register(rs); uintptr_t count = 0; int n = 0; uintptr_t bit = 0x8000000000000000UL; for (; n < 64; n++) { if (bit & rs_val) break; count++; bit >>= 1; } set_register(ra, count); if (instr->Bit(0)) { // RC Bit set int bf = 0; if (count > 0) { bf |= 0x40000000; } if (count == 0) { bf |= 0x20000000; } condition_reg_ = (condition_reg_ & ~0xF0000000) | bf; } break; } #endif case ANDX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); intptr_t alu_out = rs_val & rb_val; set_register(ra, alu_out); if (instr->Bit(0)) { // RC Bit set SetCR0(alu_out); } break; } case ANDCX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); intptr_t alu_out = rs_val & ~rb_val; set_register(ra, alu_out); if (instr->Bit(0)) { // RC Bit set SetCR0(alu_out); } break; } case CMPL: { int ra = instr->RAValue(); int rb = instr->RBValue(); int cr = instr->Bits(25, 23); uint32_t bf = 0; #if V8_TARGET_ARCH_PPC64 int L = instr->Bit(21); if (L) { #endif uintptr_t ra_val = get_register(ra); uintptr_t rb_val = get_register(rb); if (ra_val < rb_val) { bf |= 0x80000000; } if (ra_val > rb_val) { bf |= 0x40000000; } if (ra_val == rb_val) { bf |= 0x20000000; } #if V8_TARGET_ARCH_PPC64 } else { uint32_t ra_val = get_register(ra); uint32_t rb_val = get_register(rb); if (ra_val < rb_val) { bf |= 0x80000000; } if (ra_val > rb_val) { bf |= 0x40000000; } if (ra_val == rb_val) { bf |= 0x20000000; } } #endif uint32_t condition_mask = 0xF0000000U >> (cr * 4); uint32_t condition = bf >> (cr * 4); condition_reg_ = (condition_reg_ & ~condition_mask) | condition; break; } case SUBFX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); // int oe = instr->Bit(10); intptr_t ra_val = get_register(ra); intptr_t rb_val = get_register(rb); intptr_t alu_out = rb_val - ra_val; // todo - figure out underflow set_register(rt, alu_out); if (instr->Bit(0)) { // RC Bit set SetCR0(alu_out); } // todo - handle OE bit break; } case ADDZEX: { int rt = instr->RTValue(); int ra = instr->RAValue(); intptr_t ra_val = get_register(ra); if (special_reg_xer_ & 0x20000000) { ra_val += 1; } set_register(rt, ra_val); if (instr->Bit(0)) { // RC bit set SetCR0(ra_val); } // todo - handle OE bit break; } case NORX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); intptr_t alu_out = ~(rs_val | rb_val); set_register(ra, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } break; } case MULLW: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int32_t ra_val = (get_register(ra) & 0xFFFFFFFF); int32_t rb_val = (get_register(rb) & 0xFFFFFFFF); int32_t alu_out = ra_val * rb_val; set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } // todo - handle OE bit break; } #if V8_TARGET_ARCH_PPC64 case MULLD: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int64_t ra_val = get_register(ra); int64_t rb_val = get_register(rb); int64_t alu_out = ra_val * rb_val; set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } // todo - handle OE bit break; } #endif case DIVW: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int32_t ra_val = get_register(ra); int32_t rb_val = get_register(rb); bool overflow = (ra_val == kMinInt && rb_val == -1); // result is undefined if divisor is zero or if operation // is 0x80000000 / -1. int32_t alu_out = (rb_val == 0 || overflow) ? -1 : ra_val / rb_val; set_register(rt, alu_out); if (instr->Bit(10)) { // OE bit set if (overflow) { special_reg_xer_ |= 0xC0000000; // set SO,OV } else { special_reg_xer_ &= ~0x40000000; // clear OV } } if (instr->Bit(0)) { // RC bit set bool setSO = (special_reg_xer_ & 0x80000000); SetCR0(alu_out, setSO); } break; } case DIVWU: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uint32_t ra_val = get_register(ra); uint32_t rb_val = get_register(rb); bool overflow = (rb_val == 0); // result is undefined if divisor is zero uint32_t alu_out = (overflow) ? -1 : ra_val / rb_val; set_register(rt, alu_out); if (instr->Bit(10)) { // OE bit set if (overflow) { special_reg_xer_ |= 0xC0000000; // set SO,OV } else { special_reg_xer_ &= ~0x40000000; // clear OV } } if (instr->Bit(0)) { // RC bit set bool setSO = (special_reg_xer_ & 0x80000000); SetCR0(alu_out, setSO); } break; } #if V8_TARGET_ARCH_PPC64 case DIVD: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int64_t ra_val = get_register(ra); int64_t rb_val = get_register(rb); int64_t one = 1; // work-around gcc int64_t kMinLongLong = (one << 63); // result is undefined if divisor is zero or if operation // is 0x80000000_00000000 / -1. int64_t alu_out = (rb_val == 0 || (ra_val == kMinLongLong && rb_val == -1)) ? -1 : ra_val / rb_val; set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } // todo - handle OE bit break; } case DIVDU: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); uint64_t ra_val = get_register(ra); uint64_t rb_val = get_register(rb); // result is undefined if divisor is zero uint64_t alu_out = (rb_val == 0) ? -1 : ra_val / rb_val; set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } // todo - handle OE bit break; } #endif case ADDX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); // int oe = instr->Bit(10); intptr_t ra_val = get_register(ra); intptr_t rb_val = get_register(rb); intptr_t alu_out = ra_val + rb_val; set_register(rt, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } // todo - handle OE bit break; } case XORX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); intptr_t alu_out = rs_val ^ rb_val; set_register(ra, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } break; } case ORX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); intptr_t alu_out = rs_val | rb_val; set_register(ra, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } break; } case ORC: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); intptr_t alu_out = rs_val | ~rb_val; set_register(ra, alu_out); if (instr->Bit(0)) { // RC bit set SetCR0(alu_out); } break; } case MFSPR: { int rt = instr->RTValue(); int spr = instr->Bits(20, 11); if (spr != 256) { UNIMPLEMENTED(); // Only LRLR supported } set_register(rt, special_reg_lr_); break; } case MTSPR: { int rt = instr->RTValue(); intptr_t rt_val = get_register(rt); int spr = instr->Bits(20, 11); if (spr == 256) { special_reg_lr_ = rt_val; } else if (spr == 288) { special_reg_ctr_ = rt_val; } else if (spr == 32) { special_reg_xer_ = rt_val; } else { UNIMPLEMENTED(); // Only LR supported } break; } case MFCR: { int rt = instr->RTValue(); set_register(rt, condition_reg_); break; } case STWUX: case STWX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int32_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); WriteW(ra_val + rb_val, rs_val, instr); if (opcode == STWUX) { DCHECK_NE(ra, 0); set_register(ra, ra_val + rb_val); } break; } case STBUX: case STBX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int8_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); WriteB(ra_val + rb_val, rs_val); if (opcode == STBUX) { DCHECK_NE(ra, 0); set_register(ra, ra_val + rb_val); } break; } case STHUX: case STHX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int16_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); WriteH(ra_val + rb_val, rs_val, instr); if (opcode == STHUX) { DCHECK_NE(ra, 0); set_register(ra, ra_val + rb_val); } break; } case LWZX: case LWZUX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); set_register(rt, ReadWU(ra_val + rb_val, instr)); if (opcode == LWZUX) { DCHECK(ra != 0 && ra != rt); set_register(ra, ra_val + rb_val); } break; } #if V8_TARGET_ARCH_PPC64 case LWAX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); set_register(rt, ReadW(ra_val + rb_val, instr)); break; } case LDX: case LDUX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); intptr_t* result = ReadDW(ra_val + rb_val); set_register(rt, *result); if (opcode == LDUX) { DCHECK(ra != 0 && ra != rt); set_register(ra, ra_val + rb_val); } break; } case STDX: case STDUX: { int rs = instr->RSValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rs_val = get_register(rs); intptr_t rb_val = get_register(rb); WriteDW(ra_val + rb_val, rs_val); if (opcode == STDUX) { DCHECK_NE(ra, 0); set_register(ra, ra_val + rb_val); } break; } #endif case LBZX: case LBZUX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); set_register(rt, ReadBU(ra_val + rb_val) & 0xFF); if (opcode == LBZUX) { DCHECK(ra != 0 && ra != rt); set_register(ra, ra_val + rb_val); } break; } case LHZX: case LHZUX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); set_register(rt, ReadHU(ra_val + rb_val, instr) & 0xFFFF); if (opcode == LHZUX) { DCHECK(ra != 0 && ra != rt); set_register(ra, ra_val + rb_val); } break; } case LHAX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); set_register(rt, ReadH(ra_val + rb_val, instr)); break; } case LBARX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); set_register(rt, ReadExBU(ra_val + rb_val) & 0xFF); break; } case LHARX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); set_register(rt, ReadExHU(ra_val + rb_val, instr)); break; } case LWARX: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); set_register(rt, ReadExWU(ra_val + rb_val, instr)); break; } case DCBF: { // todo - simulate dcbf break; } case ISEL: { int rt = instr->RTValue(); int ra = instr->RAValue(); int rb = instr->RBValue(); int condition_bit = instr->RCValue(); int condition_mask = 0x80000000 >> condition_bit; intptr_t ra_val = (ra == 0) ? 0 : get_register(ra); intptr_t rb_val = get_register(rb); intptr_t value = (condition_reg_ & condition_mask) ? ra_val : rb_val; set_register(rt, value); break; } case STBU: case STB: { int ra = instr->RAValue(); int rs = instr->RSValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int8_t rs_val = get_register(rs); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); WriteB(ra_val + offset, rs_val); if (opcode == STBU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case LHZU: case LHZ: { int ra = instr->RAValue(); int rt = instr->RTValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); uintptr_t result = ReadHU(ra_val + offset, instr) & 0xffff; set_register(rt, result); if (opcode == LHZU) { set_register(ra, ra_val + offset); } break; } case LHA: case LHAU: { int ra = instr->RAValue(); int rt = instr->RTValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); intptr_t result = ReadH(ra_val + offset, instr); set_register(rt, result); if (opcode == LHAU) { set_register(ra, ra_val + offset); } break; } case STHU: case STH: { int ra = instr->RAValue(); int rs = instr->RSValue(); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int16_t rs_val = get_register(rs); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); WriteH(ra_val + offset, rs_val, instr); if (opcode == STHU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case LMW: case STMW: { UNIMPLEMENTED(); break; } case LFSU: case LFS: { int frt = instr->RTValue(); int ra = instr->RAValue(); int32_t offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int32_t val = ReadW(ra_val + offset, instr); float* fptr = reinterpret_cast<float*>(&val); #if V8_HOST_ARCH_IA32 || V8_HOST_ARCH_X64 // Conversion using double changes sNan to qNan on ia32/x64 if ((val & 0x7f800000) == 0x7f800000) { int64_t dval = static_cast<int64_t>(val); dval = ((dval & 0xc0000000) << 32) | ((dval & 0x40000000) << 31) | ((dval & 0x40000000) << 30) | ((dval & 0x7fffffff) << 29) | 0x0; set_d_register(frt, dval); } else { set_d_register_from_double(frt, static_cast<double>(*fptr)); } #else set_d_register_from_double(frt, static_cast<double>(*fptr)); #endif if (opcode == LFSU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case LFDU: case LFD: { int frt = instr->RTValue(); int ra = instr->RAValue(); int32_t offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int64_t* dptr = reinterpret_cast<int64_t*>(ReadDW(ra_val + offset)); set_d_register(frt, *dptr); if (opcode == LFDU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case STFSU: { case STFS: int frs = instr->RSValue(); int ra = instr->RAValue(); int32_t offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); float frs_val = static_cast<float>(get_double_from_d_register(frs)); int32_t* p; #if V8_HOST_ARCH_IA32 || V8_HOST_ARCH_X64 // Conversion using double changes sNan to qNan on ia32/x64 int32_t sval = 0; int64_t dval = get_d_register(frs); if ((dval & 0x7ff0000000000000) == 0x7ff0000000000000) { sval = ((dval & 0xc000000000000000) >> 32) | ((dval & 0x07ffffffe0000000) >> 29); p = &sval; } else { p = reinterpret_cast<int32_t*>(&frs_val); } #else p = reinterpret_cast<int32_t*>(&frs_val); #endif WriteW(ra_val + offset, *p, instr); if (opcode == STFSU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case STFDU: case STFD: { int frs = instr->RSValue(); int ra = instr->RAValue(); int32_t offset = SIGN_EXT_IMM16(instr->Bits(15, 0)); intptr_t ra_val = ra == 0 ? 0 : get_register(ra); int64_t frs_val = get_d_register(frs); WriteDW(ra_val + offset, frs_val); if (opcode == STFDU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } case FCFIDS: { // fcfids int frt = instr->RTValue(); int frb = instr->RBValue(); int64_t frb_val = get_d_register(frb); double frt_val = static_cast<float>(frb_val); set_d_register_from_double(frt, frt_val); return; } case FCFIDUS: { // fcfidus int frt = instr->RTValue(); int frb = instr->RBValue(); uint64_t frb_val = get_d_register(frb); double frt_val = static_cast<float>(frb_val); set_d_register_from_double(frt, frt_val); return; } case FDIV: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frt_val = fra_val / frb_val; set_d_register_from_double(frt, frt_val); return; } case FSUB: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frt_val = fra_val - frb_val; set_d_register_from_double(frt, frt_val); return; } case FADD: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frt_val = fra_val + frb_val; set_d_register_from_double(frt, frt_val); return; } case FSQRT: { lazily_initialize_fast_sqrt(isolate_); int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); double frt_val = fast_sqrt(frb_val, isolate_); set_d_register_from_double(frt, frt_val); return; } case FSEL: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); int frc = instr->RCValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frc_val = get_double_from_d_register(frc); double frt_val = ((fra_val >= 0.0) ? frc_val : frb_val); set_d_register_from_double(frt, frt_val); return; } case FMUL: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frc = instr->RCValue(); double fra_val = get_double_from_d_register(fra); double frc_val = get_double_from_d_register(frc); double frt_val = fra_val * frc_val; set_d_register_from_double(frt, frt_val); return; } case FMSUB: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); int frc = instr->RCValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frc_val = get_double_from_d_register(frc); double frt_val = (fra_val * frc_val) - frb_val; set_d_register_from_double(frt, frt_val); return; } case FMADD: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); int frc = instr->RCValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frc_val = get_double_from_d_register(frc); double frt_val = (fra_val * frc_val) + frb_val; set_d_register_from_double(frt, frt_val); return; } case FCMPU: { int fra = instr->RAValue(); int frb = instr->RBValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); int cr = instr->Bits(25, 23); int bf = 0; if (fra_val < frb_val) { bf |= 0x80000000; } if (fra_val > frb_val) { bf |= 0x40000000; } if (fra_val == frb_val) { bf |= 0x20000000; } if (std::isunordered(fra_val, frb_val)) { bf |= 0x10000000; } int condition_mask = 0xF0000000 >> (cr * 4); int condition = bf >> (cr * 4); condition_reg_ = (condition_reg_ & ~condition_mask) | condition; return; } case FRIN: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); double frt_val = std::round(frb_val); set_d_register_from_double(frt, frt_val); if (instr->Bit(0)) { // RC bit set // UNIMPLEMENTED(); } return; } case FRIZ: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); double frt_val = std::trunc(frb_val); set_d_register_from_double(frt, frt_val); if (instr->Bit(0)) { // RC bit set // UNIMPLEMENTED(); } return; } case FRIP: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); double frt_val = std::ceil(frb_val); set_d_register_from_double(frt, frt_val); if (instr->Bit(0)) { // RC bit set // UNIMPLEMENTED(); } return; } case FRIM: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); double frt_val = std::floor(frb_val); set_d_register_from_double(frt, frt_val); if (instr->Bit(0)) { // RC bit set // UNIMPLEMENTED(); } return; } case FRSP: { int frt = instr->RTValue(); int frb = instr->RBValue(); // frsp round 8-byte double-precision value to // single-precision value double frb_val = get_double_from_d_register(frb); double frt_val = static_cast<float>(frb_val); set_d_register_from_double(frt, frt_val); if (instr->Bit(0)) { // RC bit set // UNIMPLEMENTED(); } return; } case FCFID: { int frt = instr->RTValue(); int frb = instr->RBValue(); int64_t frb_val = get_d_register(frb); double frt_val = static_cast<double>(frb_val); set_d_register_from_double(frt, frt_val); return; } case FCFIDU: { int frt = instr->RTValue(); int frb = instr->RBValue(); uint64_t frb_val = get_d_register(frb); double frt_val = static_cast<double>(frb_val); set_d_register_from_double(frt, frt_val); return; } case FCTID: case FCTIDZ: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); int mode = (opcode == FCTIDZ) ? kRoundToZero : (fp_condition_reg_ & kFPRoundingModeMask); int64_t frt_val; int64_t one = 1; // work-around gcc int64_t kMinVal = (one << 63); int64_t kMaxVal = kMinVal - 1; bool invalid_convert = false; if (std::isnan(frb_val)) { frt_val = kMinVal; invalid_convert = true; } else { switch (mode) { case kRoundToZero: frb_val = std::trunc(frb_val); break; case kRoundToPlusInf: frb_val = std::ceil(frb_val); break; case kRoundToMinusInf: frb_val = std::floor(frb_val); break; default: UNIMPLEMENTED(); // Not used by V8. break; } if (frb_val < static_cast<double>(kMinVal)) { frt_val = kMinVal; invalid_convert = true; } else if (frb_val >= static_cast<double>(kMaxVal)) { frt_val = kMaxVal; invalid_convert = true; } else { frt_val = (int64_t)frb_val; } } set_d_register(frt, frt_val); if (invalid_convert) SetFPSCR(VXCVI); return; } case FCTIDU: case FCTIDUZ: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); int mode = (opcode == FCTIDUZ) ? kRoundToZero : (fp_condition_reg_ & kFPRoundingModeMask); uint64_t frt_val; uint64_t kMinVal = 0; uint64_t kMaxVal = kMinVal - 1; bool invalid_convert = false; if (std::isnan(frb_val)) { frt_val = kMinVal; invalid_convert = true; } else { switch (mode) { case kRoundToZero: frb_val = std::trunc(frb_val); break; case kRoundToPlusInf: frb_val = std::ceil(frb_val); break; case kRoundToMinusInf: frb_val = std::floor(frb_val); break; default: UNIMPLEMENTED(); // Not used by V8. break; } if (frb_val < static_cast<double>(kMinVal)) { frt_val = kMinVal; invalid_convert = true; } else if (frb_val >= static_cast<double>(kMaxVal)) { frt_val = kMaxVal; invalid_convert = true; } else { frt_val = (uint64_t)frb_val; } } set_d_register(frt, frt_val); if (invalid_convert) SetFPSCR(VXCVI); return; } case FCTIW: case FCTIWZ: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); int mode = (opcode == FCTIWZ) ? kRoundToZero : (fp_condition_reg_ & kFPRoundingModeMask); int64_t frt_val; int64_t kMinVal = kMinInt; int64_t kMaxVal = kMaxInt; if (std::isnan(frb_val)) { frt_val = kMinVal; } else { switch (mode) { case kRoundToZero: frb_val = std::trunc(frb_val); break; case kRoundToPlusInf: frb_val = std::ceil(frb_val); break; case kRoundToMinusInf: frb_val = std::floor(frb_val); break; case kRoundToNearest: { double orig = frb_val; frb_val = lround(frb_val); // Round to even if exactly halfway. (lround rounds up) if (std::fabs(frb_val - orig) == 0.5 && ((int64_t)frb_val % 2)) { frb_val += ((frb_val > 0) ? -1.0 : 1.0); } break; } default: UNIMPLEMENTED(); // Not used by V8. break; } if (frb_val < kMinVal) { frt_val = kMinVal; } else if (frb_val > kMaxVal) { frt_val = kMaxVal; } else { frt_val = (int64_t)frb_val; } } set_d_register(frt, frt_val); return; } case FNEG: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); double frt_val = -frb_val; set_d_register_from_double(frt, frt_val); return; } case FMR: { int frt = instr->RTValue(); int frb = instr->RBValue(); int64_t frb_val = get_d_register(frb); set_d_register(frt, frb_val); return; } case MTFSFI: { int bf = instr->Bits(25, 23); int imm = instr->Bits(15, 12); int fp_condition_mask = 0xF0000000 >> (bf * 4); fp_condition_reg_ &= ~fp_condition_mask; fp_condition_reg_ |= (imm << (28 - (bf * 4))); if (instr->Bit(0)) { // RC bit set condition_reg_ &= 0xF0FFFFFF; condition_reg_ |= (imm << 23); } return; } case MTFSF: { int frb = instr->RBValue(); int64_t frb_dval = get_d_register(frb); int32_t frb_ival = static_cast<int32_t>((frb_dval)&0xffffffff); int l = instr->Bits(25, 25); if (l == 1) { fp_condition_reg_ = frb_ival; } else { UNIMPLEMENTED(); } if (instr->Bit(0)) { // RC bit set UNIMPLEMENTED(); // int w = instr->Bits(16, 16); // int flm = instr->Bits(24, 17); } return; } case MFFS: { int frt = instr->RTValue(); int64_t lval = static_cast<int64_t>(fp_condition_reg_); set_d_register(frt, lval); return; } case MCRFS: { int bf = instr->Bits(25, 23); int bfa = instr->Bits(20, 18); int cr_shift = (7 - bf) * CRWIDTH; int fp_shift = (7 - bfa) * CRWIDTH; int field_val = (fp_condition_reg_ >> fp_shift) & 0xf; condition_reg_ &= ~(0x0f << cr_shift); condition_reg_ |= (field_val << cr_shift); // Clear copied exception bits switch (bfa) { case 5: ClearFPSCR(VXSOFT); ClearFPSCR(VXSQRT); ClearFPSCR(VXCVI); break; default: UNIMPLEMENTED(); break; } return; } case MTFSB0: { int bt = instr->Bits(25, 21); ClearFPSCR(bt); if (instr->Bit(0)) { // RC bit set UNIMPLEMENTED(); } return; } case MTFSB1: { int bt = instr->Bits(25, 21); SetFPSCR(bt); if (instr->Bit(0)) { // RC bit set UNIMPLEMENTED(); } return; } case FABS: { int frt = instr->RTValue(); int frb = instr->RBValue(); double frb_val = get_double_from_d_register(frb); double frt_val = std::fabs(frb_val); set_d_register_from_double(frt, frt_val); return; } #if V8_TARGET_ARCH_PPC64 case RLDICL: { int ra = instr->RAValue(); int rs = instr->RSValue(); uintptr_t rs_val = get_register(rs); int sh = (instr->Bits(15, 11) | (instr->Bit(1) << 5)); int mb = (instr->Bits(10, 6) | (instr->Bit(5) << 5)); DCHECK(sh >= 0 && sh <= 63); DCHECK(mb >= 0 && mb <= 63); uintptr_t result = base::bits::RotateLeft64(rs_val, sh); uintptr_t mask = 0xffffffffffffffff >> mb; result &= mask; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } return; } case RLDICR: { int ra = instr->RAValue(); int rs = instr->RSValue(); uintptr_t rs_val = get_register(rs); int sh = (instr->Bits(15, 11) | (instr->Bit(1) << 5)); int me = (instr->Bits(10, 6) | (instr->Bit(5) << 5)); DCHECK(sh >= 0 && sh <= 63); DCHECK(me >= 0 && me <= 63); uintptr_t result = base::bits::RotateLeft64(rs_val, sh); uintptr_t mask = 0xffffffffffffffff << (63 - me); result &= mask; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } return; } case RLDIC: { int ra = instr->RAValue(); int rs = instr->RSValue(); uintptr_t rs_val = get_register(rs); int sh = (instr->Bits(15, 11) | (instr->Bit(1) << 5)); int mb = (instr->Bits(10, 6) | (instr->Bit(5) << 5)); DCHECK(sh >= 0 && sh <= 63); DCHECK(mb >= 0 && mb <= 63); uintptr_t result = base::bits::RotateLeft64(rs_val, sh); uintptr_t mask = (0xffffffffffffffff >> mb) & (0xffffffffffffffff << sh); result &= mask; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } return; } case RLDIMI: { int ra = instr->RAValue(); int rs = instr->RSValue(); uintptr_t rs_val = get_register(rs); intptr_t ra_val = get_register(ra); int sh = (instr->Bits(15, 11) | (instr->Bit(1) << 5)); int mb = (instr->Bits(10, 6) | (instr->Bit(5) << 5)); int me = 63 - sh; uintptr_t result = base::bits::RotateLeft64(rs_val, sh); uintptr_t mask = 0; if (mb < me + 1) { uintptr_t bit = 0x8000000000000000 >> mb; for (; mb <= me; mb++) { mask |= bit; bit >>= 1; } } else if (mb == me + 1) { mask = 0xffffffffffffffff; } else { // mb > me+1 uintptr_t bit = 0x8000000000000000 >> (me + 1); // needs to be tested mask = 0xffffffffffffffff; for (; me < mb; me++) { mask ^= bit; bit >>= 1; } } result &= mask; ra_val &= ~mask; result |= ra_val; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } return; } case RLDCL: { int ra = instr->RAValue(); int rs = instr->RSValue(); int rb = instr->RBValue(); uintptr_t rs_val = get_register(rs); uintptr_t rb_val = get_register(rb); int sh = (rb_val & 0x3f); int mb = (instr->Bits(10, 6) | (instr->Bit(5) << 5)); DCHECK(sh >= 0 && sh <= 63); DCHECK(mb >= 0 && mb <= 63); uintptr_t result = base::bits::RotateLeft64(rs_val, sh); uintptr_t mask = 0xffffffffffffffff >> mb; result &= mask; set_register(ra, result); if (instr->Bit(0)) { // RC bit set SetCR0(result); } return; } case LD: case LDU: case LWA: { int ra = instr->RAValue(); int rt = instr->RTValue(); int64_t ra_val = ra == 0 ? 0 : get_register(ra); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0) & ~3); switch (instr->Bits(1, 0)) { case 0: { // ld intptr_t* result = ReadDW(ra_val + offset); set_register(rt, *result); break; } case 1: { // ldu intptr_t* result = ReadDW(ra_val + offset); set_register(rt, *result); DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); break; } case 2: { // lwa intptr_t result = ReadW(ra_val + offset, instr); set_register(rt, result); break; } } break; } case STD: case STDU: { int ra = instr->RAValue(); int rs = instr->RSValue(); int64_t ra_val = ra == 0 ? 0 : get_register(ra); int64_t rs_val = get_register(rs); int offset = SIGN_EXT_IMM16(instr->Bits(15, 0) & ~3); WriteDW(ra_val + offset, rs_val); if (opcode == STDU) { DCHECK_NE(ra, 0); set_register(ra, ra_val + offset); } break; } #endif case XSADDDP: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frt_val = fra_val + frb_val; set_d_register_from_double(frt, frt_val); return; } case XSSUBDP: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frt_val = fra_val - frb_val; set_d_register_from_double(frt, frt_val); return; } case XSMULDP: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frt_val = fra_val * frb_val; set_d_register_from_double(frt, frt_val); return; } case XSDIVDP: { int frt = instr->RTValue(); int fra = instr->RAValue(); int frb = instr->RBValue(); double fra_val = get_double_from_d_register(fra); double frb_val = get_double_from_d_register(frb); double frt_val = fra_val / frb_val; set_d_register_from_double(frt, frt_val); return; } default: { UNIMPLEMENTED(); break; } } } // NOLINT void Simulator::Trace(Instruction* instr) { disasm::NameConverter converter; disasm::Disassembler dasm(converter); // use a reasonably large buffer v8::internal::EmbeddedVector<char, 256> buffer; dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr)); PrintF("%05d %08" V8PRIxPTR " %s\n", icount_, reinterpret_cast<intptr_t>(instr), buffer.start()); } // Executes the current instruction. void Simulator::ExecuteInstruction(Instruction* instr) { if (v8::internal::FLAG_check_icache) { CheckICache(isolate_->simulator_i_cache(), instr); } pc_modified_ = false; if (::v8::internal::FLAG_trace_sim) { Trace(instr); } uint32_t opcode = instr->OpcodeField(); if (opcode == TWI) { SoftwareInterrupt(instr); } else { ExecuteGeneric(instr); } if (!pc_modified_) { set_pc(reinterpret_cast<intptr_t>(instr) + Instruction::kInstrSize); } } void Simulator::Execute() { // Get the PC to simulate. Cannot use the accessor here as we need the // raw PC value and not the one used as input to arithmetic instructions. intptr_t program_counter = get_pc(); if (::v8::internal::FLAG_stop_sim_at == 0) { // Fast version of the dispatch loop without checking whether the simulator // should be stopping at a particular executed instruction. while (program_counter != end_sim_pc) { Instruction* instr = reinterpret_cast<Instruction*>(program_counter); icount_++; ExecuteInstruction(instr); program_counter = get_pc(); } } else { // FLAG_stop_sim_at is at the non-default value. Stop in the debugger when // we reach the particular instruction count. while (program_counter != end_sim_pc) { Instruction* instr = reinterpret_cast<Instruction*>(program_counter); icount_++; if (icount_ == ::v8::internal::FLAG_stop_sim_at) { PPCDebugger dbg(this); dbg.Debug(); } else { ExecuteInstruction(instr); } program_counter = get_pc(); } } } void Simulator::CallInternal(byte* entry) { // Adjust JS-based stack limit to C-based stack limit. isolate_->stack_guard()->AdjustStackLimitForSimulator(); // Prepare to execute the code at entry if (ABI_USES_FUNCTION_DESCRIPTORS) { // entry is the function descriptor set_pc(*(reinterpret_cast<intptr_t*>(entry))); } else { // entry is the instruction address set_pc(reinterpret_cast<intptr_t>(entry)); } if (ABI_CALL_VIA_IP) { // Put target address in ip (for JS prologue). set_register(r12, get_pc()); } // Put down marker for end of simulation. The simulator will stop simulation // when the PC reaches this value. By saving the "end simulation" value into // the LR the simulation stops when returning to this call point. special_reg_lr_ = end_sim_pc; // Remember the values of non-volatile registers. intptr_t r2_val = get_register(r2); intptr_t r13_val = get_register(r13); intptr_t r14_val = get_register(r14); intptr_t r15_val = get_register(r15); intptr_t r16_val = get_register(r16); intptr_t r17_val = get_register(r17); intptr_t r18_val = get_register(r18); intptr_t r19_val = get_register(r19); intptr_t r20_val = get_register(r20); intptr_t r21_val = get_register(r21); intptr_t r22_val = get_register(r22); intptr_t r23_val = get_register(r23); intptr_t r24_val = get_register(r24); intptr_t r25_val = get_register(r25); intptr_t r26_val = get_register(r26); intptr_t r27_val = get_register(r27); intptr_t r28_val = get_register(r28); intptr_t r29_val = get_register(r29); intptr_t r30_val = get_register(r30); intptr_t r31_val = get_register(fp); // Set up the non-volatile registers with a known value. To be able to check // that they are preserved properly across JS execution. intptr_t callee_saved_value = icount_; set_register(r2, callee_saved_value); set_register(r13, callee_saved_value); set_register(r14, callee_saved_value); set_register(r15, callee_saved_value); set_register(r16, callee_saved_value); set_register(r17, callee_saved_value); set_register(r18, callee_saved_value); set_register(r19, callee_saved_value); set_register(r20, callee_saved_value); set_register(r21, callee_saved_value); set_register(r22, callee_saved_value); set_register(r23, callee_saved_value); set_register(r24, callee_saved_value); set_register(r25, callee_saved_value); set_register(r26, callee_saved_value); set_register(r27, callee_saved_value); set_register(r28, callee_saved_value); set_register(r29, callee_saved_value); set_register(r30, callee_saved_value); set_register(fp, callee_saved_value); // Start the simulation Execute(); // Check that the non-volatile registers have been preserved. if (ABI_TOC_REGISTER != 2) { CHECK_EQ(callee_saved_value, get_register(r2)); } if (ABI_TOC_REGISTER != 13) { CHECK_EQ(callee_saved_value, get_register(r13)); } CHECK_EQ(callee_saved_value, get_register(r14)); CHECK_EQ(callee_saved_value, get_register(r15)); CHECK_EQ(callee_saved_value, get_register(r16)); CHECK_EQ(callee_saved_value, get_register(r17)); CHECK_EQ(callee_saved_value, get_register(r18)); CHECK_EQ(callee_saved_value, get_register(r19)); CHECK_EQ(callee_saved_value, get_register(r20)); CHECK_EQ(callee_saved_value, get_register(r21)); CHECK_EQ(callee_saved_value, get_register(r22)); CHECK_EQ(callee_saved_value, get_register(r23)); CHECK_EQ(callee_saved_value, get_register(r24)); CHECK_EQ(callee_saved_value, get_register(r25)); CHECK_EQ(callee_saved_value, get_register(r26)); CHECK_EQ(callee_saved_value, get_register(r27)); CHECK_EQ(callee_saved_value, get_register(r28)); CHECK_EQ(callee_saved_value, get_register(r29)); CHECK_EQ(callee_saved_value, get_register(r30)); CHECK_EQ(callee_saved_value, get_register(fp)); // Restore non-volatile registers with the original value. set_register(r2, r2_val); set_register(r13, r13_val); set_register(r14, r14_val); set_register(r15, r15_val); set_register(r16, r16_val); set_register(r17, r17_val); set_register(r18, r18_val); set_register(r19, r19_val); set_register(r20, r20_val); set_register(r21, r21_val); set_register(r22, r22_val); set_register(r23, r23_val); set_register(r24, r24_val); set_register(r25, r25_val); set_register(r26, r26_val); set_register(r27, r27_val); set_register(r28, r28_val); set_register(r29, r29_val); set_register(r30, r30_val); set_register(fp, r31_val); } intptr_t Simulator::Call(byte* entry, int argument_count, ...) { va_list parameters; va_start(parameters, argument_count); // Set up arguments // First eight arguments passed in registers r3-r10. int reg_arg_count = (argument_count > 8) ? 8 : argument_count; int stack_arg_count = argument_count - reg_arg_count; for (int i = 0; i < reg_arg_count; i++) { set_register(i + 3, va_arg(parameters, intptr_t)); } // Remaining arguments passed on stack. intptr_t original_stack = get_register(sp); // Compute position of stack on entry to generated code. intptr_t entry_stack = (original_stack - (kNumRequiredStackFrameSlots + stack_arg_count) * sizeof(intptr_t)); if (base::OS::ActivationFrameAlignment() != 0) { entry_stack &= -base::OS::ActivationFrameAlignment(); } // Store remaining arguments on stack, from low to high memory. // +2 is a hack for the LR slot + old SP on PPC intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack) + kStackFrameExtraParamSlot; for (int i = 0; i < stack_arg_count; i++) { stack_argument[i] = va_arg(parameters, intptr_t); } va_end(parameters); set_register(sp, entry_stack); CallInternal(entry); // Pop stack passed arguments. CHECK_EQ(entry_stack, get_register(sp)); set_register(sp, original_stack); intptr_t result = get_register(r3); return result; } void Simulator::CallFP(byte* entry, double d0, double d1) { set_d_register_from_double(1, d0); set_d_register_from_double(2, d1); CallInternal(entry); } int32_t Simulator::CallFPReturnsInt(byte* entry, double d0, double d1) { CallFP(entry, d0, d1); int32_t result = get_register(r3); return result; } double Simulator::CallFPReturnsDouble(byte* entry, double d0, double d1) { CallFP(entry, d0, d1); return get_double_from_d_register(1); } uintptr_t Simulator::PushAddress(uintptr_t address) { uintptr_t new_sp = get_register(sp) - sizeof(uintptr_t); uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp); *stack_slot = address; set_register(sp, new_sp); return new_sp; } uintptr_t Simulator::PopAddress() { uintptr_t current_sp = get_register(sp); uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp); uintptr_t address = *stack_slot; set_register(sp, current_sp + sizeof(uintptr_t)); return address; } Simulator::LocalMonitor::LocalMonitor() : access_state_(MonitorAccess::Open), tagged_addr_(0), size_(TransactionSize::None) {} void Simulator::LocalMonitor::Clear() { access_state_ = MonitorAccess::Open; tagged_addr_ = 0; size_ = TransactionSize::None; } void Simulator::LocalMonitor::NotifyLoad(int32_t addr) { if (access_state_ == MonitorAccess::Exclusive) { // A load could cause a cache eviction which will affect the monitor. As a // result, it's most strict to unconditionally clear the local monitor on // load. Clear(); } } void Simulator::LocalMonitor::NotifyLoadExcl(int32_t addr, TransactionSize size) { access_state_ = MonitorAccess::Exclusive; tagged_addr_ = addr; size_ = size; } void Simulator::LocalMonitor::NotifyStore(int32_t addr) { if (access_state_ == MonitorAccess::Exclusive) { // A store could cause a cache eviction which will affect the // monitor. As a result, it's most strict to unconditionally clear the // local monitor on store. Clear(); } } bool Simulator::LocalMonitor::NotifyStoreExcl(int32_t addr, TransactionSize size) { if (access_state_ == MonitorAccess::Exclusive) { if (addr == tagged_addr_ && size_ == size) { Clear(); return true; } else { Clear(); return false; } } else { DCHECK(access_state_ == MonitorAccess::Open); return false; } } Simulator::GlobalMonitor::Processor::Processor() : access_state_(MonitorAccess::Open), tagged_addr_(0), next_(nullptr), prev_(nullptr) {} void Simulator::GlobalMonitor::Processor::Clear_Locked() { access_state_ = MonitorAccess::Open; tagged_addr_ = 0; } void Simulator::GlobalMonitor::Processor::NotifyLoadExcl_Locked(int32_t addr) { access_state_ = MonitorAccess::Exclusive; tagged_addr_ = addr; } void Simulator::GlobalMonitor::Processor::NotifyStore_Locked( int32_t addr, bool is_requesting_processor) { if (access_state_ == MonitorAccess::Exclusive) { // It is possible that a store caused a cache eviction, // which can affect the montior, so conservatively, // we always clear the monitor. Clear_Locked(); } } bool Simulator::GlobalMonitor::Processor::NotifyStoreExcl_Locked( int32_t addr, bool is_requesting_processor) { if (access_state_ == MonitorAccess::Exclusive) { if (is_requesting_processor) { if (addr == tagged_addr_) { Clear_Locked(); return true; } } else if (addr == tagged_addr_) { Clear_Locked(); return false; } } return false; } Simulator::GlobalMonitor::GlobalMonitor() : head_(nullptr) {} void Simulator::GlobalMonitor::NotifyLoadExcl_Locked(int32_t addr, Processor* processor) { processor->NotifyLoadExcl_Locked(addr); PrependProcessor_Locked(processor); } void Simulator::GlobalMonitor::NotifyStore_Locked(int32_t addr, Processor* processor) { // Notify each processor of the store operation. for (Processor* iter = head_; iter; iter = iter->next_) { bool is_requesting_processor = iter == processor; iter->NotifyStore_Locked(addr, is_requesting_processor); } } bool Simulator::GlobalMonitor::NotifyStoreExcl_Locked(int32_t addr, Processor* processor) { DCHECK(IsProcessorInLinkedList_Locked(processor)); if (processor->NotifyStoreExcl_Locked(addr, true)) { // Notify the other processors that this StoreExcl succeeded. for (Processor* iter = head_; iter; iter = iter->next_) { if (iter != processor) { iter->NotifyStoreExcl_Locked(addr, false); } } return true; } else { return false; } } bool Simulator::GlobalMonitor::IsProcessorInLinkedList_Locked( Processor* processor) const { return head_ == processor || processor->next_ || processor->prev_; } void Simulator::GlobalMonitor::PrependProcessor_Locked(Processor* processor) { if (IsProcessorInLinkedList_Locked(processor)) { return; } if (head_) { head_->prev_ = processor; } processor->prev_ = nullptr; processor->next_ = head_; head_ = processor; } void Simulator::GlobalMonitor::RemoveProcessor(Processor* processor) { base::LockGuard<base::Mutex> lock_guard(&mutex); if (!IsProcessorInLinkedList_Locked(processor)) { return; } if (processor->prev_) { processor->prev_->next_ = processor->next_; } else { head_ = processor->next_; } if (processor->next_) { processor->next_->prev_ = processor->prev_; } processor->prev_ = nullptr; processor->next_ = nullptr; } } // namespace internal } // namespace v8 #endif // USE_SIMULATOR #endif // V8_TARGET_ARCH_PPC
#include <mbgl/geometry/glyph_atlas.hpp> #include <mbgl/gl/gl.hpp> #include <mbgl/gl/object_store.hpp> #include <mbgl/gl/gl_config.hpp> #include <mbgl/platform/log.hpp> #include <mbgl/platform/platform.hpp> #include <cassert> #include <algorithm> namespace mbgl { GlyphAtlas::GlyphAtlas(uint16_t width_, uint16_t height_) : width(width_), height(height_), bin(width_, height_), data(std::make_unique<uint8_t[]>(width_ * height_)), dirty(true) { } GlyphAtlas::~GlyphAtlas() = default; void GlyphAtlas::addGlyphs(uintptr_t tileUID, const std::u32string& text, const FontStack& fontStack, const GlyphSet& glyphSet, GlyphPositions& face) { std::lock_guard<std::mutex> lock(mtx); const std::map<uint32_t, SDFGlyph>& sdfs = glyphSet.getSDFs(); for (uint32_t chr : text) { auto sdf_it = sdfs.find(chr); if (sdf_it == sdfs.end()) { continue; } const SDFGlyph& sdf = sdf_it->second; Rect<uint16_t> rect = addGlyph(tileUID, fontStack, sdf); face.emplace(chr, Glyph{rect, sdf.metrics}); } } Rect<uint16_t> GlyphAtlas::addGlyph(uintptr_t tileUID, const FontStack& fontStack, const SDFGlyph& glyph) { // Use constant value for now. const uint8_t buffer = 3; std::map<uint32_t, GlyphValue>& face = index[fontStack]; auto it = face.find(glyph.id); // The glyph is already in this texture. if (it != face.end()) { GlyphValue& value = it->second; value.ids.insert(tileUID); return value.rect; } // The glyph bitmap has zero width. if (glyph.bitmap.empty()) { return Rect<uint16_t>{ 0, 0, 0, 0 }; } uint16_t buffered_width = glyph.metrics.width + buffer * 2; uint16_t buffered_height = glyph.metrics.height + buffer * 2; // Add a 1px border around every image. const uint16_t padding = 1; uint16_t pack_width = buffered_width + 2 * padding; uint16_t pack_height = buffered_height + 2 * padding; // Increase to next number divisible by 4, but at least 1. // This is so we can scale down the texture coordinates and pack them // into 2 bytes rather than 4 bytes. pack_width += (4 - pack_width % 4); pack_height += (4 - pack_height % 4); Rect<uint16_t> rect = bin.allocate(pack_width, pack_height); if (rect.w == 0) { Log::Error(Event::OpenGL, "glyph bitmap overflow"); return rect; } assert(rect.x + rect.w <= width); assert(rect.y + rect.h <= height); face.emplace(glyph.id, GlyphValue { rect, tileUID }); // Copy the bitmap const uint8_t* source = reinterpret_cast<const uint8_t*>(glyph.bitmap.data()); for (uint32_t y = 0; y < buffered_height; y++) { uint32_t y1 = width * (rect.y + y + padding) + rect.x + padding; uint32_t y2 = buffered_width * y; for (uint32_t x = 0; x < buffered_width; x++) { data[y1 + x] = source[y2 + x]; } } dirty = true; return rect; } void GlyphAtlas::removeGlyphs(uintptr_t tileUID) { std::lock_guard<std::mutex> lock(mtx); for (auto& faces : index) { std::map<uint32_t, GlyphValue>& face = faces.second; for (auto it = face.begin(); it != face.end(); /* we advance in the body */) { GlyphValue& value = it->second; value.ids.erase(tileUID); if (value.ids.empty()) { const Rect<uint16_t>& rect = value.rect; // Clear out the bitmap. uint8_t *target = data.get(); for (uint32_t y = 0; y < rect.h; y++) { uint32_t y1 = width * (rect.y + y) + rect.x; for (uint32_t x = 0; x < rect.w; x++) { target[y1 + x] = 0; } } bin.release(rect); // Make sure to post-increment the iterator: This will return the // current iterator, but will go to the next position before we // erase the element from the map. That way, the iterator stays // valid. face.erase(it++); } else { ++it; } } } } void GlyphAtlas::upload(gl::ObjectStore& store, gl::Config& config, uint32_t unit) { if (dirty) { const bool first = !texture; bind(store, config, unit); std::lock_guard<std::mutex> lock(mtx); config.activeTexture = unit; if (first) { MBGL_CHECK_ERROR(glTexImage2D( GL_TEXTURE_2D, // GLenum target 0, // GLint level GL_ALPHA, // GLint internalformat width, // GLsizei width height, // GLsizei height 0, // GLint border GL_ALPHA, // GLenum format GL_UNSIGNED_BYTE, // GLenum type data.get() // const GLvoid* data )); } else { MBGL_CHECK_ERROR(glTexSubImage2D( GL_TEXTURE_2D, // GLenum target 0, // GLint level 0, // GLint xoffset 0, // GLint yoffset width, // GLsizei width height, // GLsizei height GL_ALPHA, // GLenum format GL_UNSIGNED_BYTE, // GLenum type data.get() // const GLvoid* data )); } dirty = false; } } void GlyphAtlas::bind(gl::ObjectStore& store, gl::Config& config, uint32_t unit) { if (!texture) { texture = store.createTexture(); config.activeTexture = unit; config.texture[unit] = *texture; #ifndef GL_ES_VERSION_2_0 MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)); #endif MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); } else if (config.texture[unit] != *texture) { config.activeTexture = unit; config.texture[unit] = *texture; } } } // namespace mbgl
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/profiler/utils/tf_op_utils.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace profiler { namespace { TEST(TfOpUtilsTest, TfOpTest) { const absl::string_view kName = "OpName:OpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, "OpName"); EXPECT_EQ(tf_op.type, "OpType"); EXPECT_EQ(TfOpEventName(kName), "OpType"); // type only } TEST(TfOpUtilsTest, InternalTfOpTest) { const absl::string_view kName = "OpName:_InternalOpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, "OpName"); EXPECT_EQ(tf_op.type, "_InternalOpType"); EXPECT_EQ(TfOpEventName(kName), "_InternalOpType"); // type only } TEST(TfOpUtilsTest, TfOpWithPathTest) { const absl::string_view kName = "path/to/name:OpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, "path/to/name"); EXPECT_EQ(tf_op.type, "OpType"); EXPECT_EQ(TfOpEventName(kName), "OpType"); // type only } TEST(TfOpUtilsTest, ShortDatasetOpTest) { const absl::string_view kName = "Iterator::Batch"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, kName); EXPECT_TRUE(IsDatasetOp(tf_op.type)); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, LongDatasetOpTest) { const absl::string_view kName = "Iterator::Batch::Map::TfRecord"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, kName); EXPECT_TRUE(IsDatasetOp(tf_op.type)); EXPECT_EQ(TfOpEventName(kName), "Iterator::TfRecord"); // shorter name } TEST(TfOpUtilsTest, TraceMeTest) { const absl::string_view kName = "MyTraceMe"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, kName); EXPECT_TRUE(IsUnknownOp(tf_op.type)); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithColonTest) { // "12345" is not a valid op type. const absl::string_view kName = "RunStep/Server:54635"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, kName); EXPECT_TRUE(IsUnknownOp(tf_op.type)); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithDoubleColonTest) { const absl::string_view kName = "XLA::StartProgram"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, kName); EXPECT_TRUE(IsUnknownOp(tf_op.type)); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithTrailingWhitespaceTest) { const absl::string_view kName = "SessionRun "; const absl::string_view kNameTrimmed = "SessionRun"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.name, kName); EXPECT_TRUE(IsUnknownOp(tf_op.type)); EXPECT_EQ(TfOpEventName(kName), kNameTrimmed); } } // namespace } // namespace profiler } // namespace tensorflow
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // Note: The results do not include the pre-processing in the prepare function that is // necessary for SetLookup but not Iterate. None of the values searched for are in the // fabricated IN list (i.e. hit rate is 0). //Machine Info: Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz //tinyInt n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 3.29e+03 3.34e+03 3.38e+03 1X 1X 1X // Iterate n=1 9.48e+03 9.56e+03 9.64e+03 2.88X 2.87X 2.85X // //tinyInt n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 2.91e+03 2.99e+03 3.02e+03 1X 1X 1X // Iterate n=2 6.95e+03 7.08e+03 7.14e+03 2.39X 2.37X 2.37X // //tinyInt n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 2.54e+03 2.6e+03 2.65e+03 1X 1X 1X // Iterate n=3 4.89e+03 5.01e+03 5.08e+03 1.93X 1.93X 1.92X // //tinyInt n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 2.89e+03 3e+03 3.04e+03 1X 1X 1X // Iterate n=4 3.71e+03 3.79e+03 3.84e+03 1.28X 1.26X 1.26X // //tinyInt n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 2.64e+03 2.74e+03 2.78e+03 1X 1X 1X // Iterate n=5 3.5e+03 3.57e+03 3.61e+03 1.32X 1.3X 1.3X // //tinyInt n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 2.62e+03 2.67e+03 2.69e+03 1X 1X 1X // Iterate n=6 2.73e+03 2.76e+03 2.79e+03 1.04X 1.04X 1.04X // //tinyInt n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 2.39e+03 2.44e+03 2.46e+03 1X 1X 1X // Iterate n=7 2.48e+03 2.51e+03 2.54e+03 1.04X 1.03X 1.03X // //tinyInt n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 2.81e+03 2.85e+03 2.89e+03 1X 1X 1X // Iterate n=8 2.08e+03 2.12e+03 2.14e+03 0.741X 0.743X 0.741X // //tinyInt n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 2.66e+03 2.75e+03 2.8e+03 1X 1X 1X // Iterate n=9 1.69e+03 1.71e+03 1.73e+03 0.635X 0.624X 0.617X // //tinyInt n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 2.8e+03 2.89e+03 2.92e+03 1X 1X 1X // Iterate n=10 1.54e+03 1.57e+03 1.58e+03 0.548X 0.543X 0.542X // //tinyInt n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 2.51e+03 2.61e+03 2.64e+03 1X 1X 1X // Iterate n=400 84 84.2 85.7 0.0335X 0.0323X 0.0325X // //smallInt n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 3.16e+03 3.28e+03 3.33e+03 1X 1X 1X // Iterate n=1 1.03e+04 1.04e+04 1.05e+04 3.27X 3.18X 3.16X // //smallInt n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 2.94e+03 3.02e+03 3.06e+03 1X 1X 1X // Iterate n=2 7.03e+03 7.12e+03 7.18e+03 2.39X 2.36X 2.35X // //smallInt n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 2.64e+03 2.73e+03 2.78e+03 1X 1X 1X // Iterate n=3 5.33e+03 5.4e+03 5.45e+03 2.02X 1.98X 1.96X // //smallInt n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 2.96e+03 3.04e+03 3.08e+03 1X 1X 1X // Iterate n=4 4.06e+03 4.09e+03 4.14e+03 1.37X 1.34X 1.35X // //smallInt n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 2.72e+03 2.81e+03 2.86e+03 1X 1X 1X // Iterate n=5 3.59e+03 3.63e+03 3.66e+03 1.32X 1.29X 1.28X // //smallInt n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 2.68e+03 2.79e+03 2.85e+03 1X 1X 1X // Iterate n=6 2.9e+03 2.98e+03 3.02e+03 1.08X 1.07X 1.06X // //smallInt n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 2.35e+03 2.56e+03 2.6e+03 1X 1X 1X // Iterate n=7 2.63e+03 2.73e+03 2.76e+03 1.12X 1.07X 1.06X // //smallInt n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 2.78e+03 2.88e+03 2.91e+03 1X 1X 1X // Iterate n=8 2.33e+03 2.36e+03 2.38e+03 0.839X 0.818X 0.816X // //smallInt n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 2.76e+03 2.83e+03 2.87e+03 1X 1X 1X // Iterate n=9 1.79e+03 1.82e+03 1.85e+03 0.648X 0.642X 0.644X // //smallInt n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 2.83e+03 2.88e+03 2.91e+03 1X 1X 1X // Iterate n=10 1.61e+03 1.64e+03 1.66e+03 0.567X 0.57X 0.57X // //smallInt n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 2.62e+03 2.68e+03 2.71e+03 1X 1X 1X // Iterate n=400 48.7 49.4 49.9 0.0186X 0.0185X 0.0184X // //int n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 4.66e+03 4.75e+03 4.85e+03 1X 1X 1X // Iterate n=1 1.03e+04 1.04e+04 1.05e+04 2.21X 2.19X 2.17X // //int n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 4.1e+03 4.27e+03 4.34e+03 1X 1X 1X // Iterate n=2 6.62e+03 6.94e+03 7.02e+03 1.61X 1.62X 1.62X // //int n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 3.78e+03 3.89e+03 3.94e+03 1X 1X 1X // Iterate n=3 5.21e+03 5.29e+03 5.34e+03 1.38X 1.36X 1.35X // //int n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 3.16e+03 3.28e+03 3.35e+03 1X 1X 1X // Iterate n=4 3.9e+03 4e+03 4.07e+03 1.23X 1.22X 1.22X // //int n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 3.29e+03 3.39e+03 3.45e+03 1X 1X 1X // Iterate n=5 3.39e+03 3.5e+03 3.53e+03 1.03X 1.03X 1.02X // //int n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 3.3e+03 3.39e+03 3.44e+03 1X 1X 1X // Iterate n=6 2.9e+03 2.97e+03 2.99e+03 0.881X 0.874X 0.869X // //int n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 3.06e+03 3.18e+03 3.21e+03 1X 1X 1X // Iterate n=7 2.67e+03 2.72e+03 2.74e+03 0.872X 0.855X 0.853X // //int n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 2.69e+03 2.72e+03 2.75e+03 1X 1X 1X // Iterate n=8 2.32e+03 2.34e+03 2.36e+03 0.863X 0.862X 0.86X // //int n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 2.59e+03 2.65e+03 2.7e+03 1X 1X 1X // Iterate n=9 1.69e+03 1.71e+03 1.73e+03 0.652X 0.647X 0.642X // //int n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 2.76e+03 2.82e+03 2.85e+03 1X 1X 1X // Iterate n=10 1.54e+03 1.56e+03 1.58e+03 0.557X 0.554X 0.555X // //int n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 1.45e+03 1.55e+03 1.57e+03 1X 1X 1X // Iterate n=400 48.4 48.6 49.3 0.0334X 0.0314X 0.0314X // //bigInt n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 4.08e+03 4.16e+03 4.23e+03 1X 1X 1X // Iterate n=1 9.06e+03 9.14e+03 9.24e+03 2.22X 2.2X 2.19X // //bigInt n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 4.02e+03 4.15e+03 4.24e+03 1X 1X 1X // Iterate n=2 6.44e+03 6.51e+03 6.58e+03 1.6X 1.57X 1.55X // //bigInt n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 3.86e+03 3.97e+03 4.03e+03 1X 1X 1X // Iterate n=3 4.63e+03 4.7e+03 4.76e+03 1.2X 1.18X 1.18X // //bigInt n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 3.54e+03 3.62e+03 3.7e+03 1X 1X 1X // Iterate n=4 4.04e+03 4.11e+03 4.13e+03 1.14X 1.13X 1.12X // //bigInt n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 2.73e+03 2.76e+03 2.79e+03 1X 1X 1X // Iterate n=5 3.27e+03 3.3e+03 3.34e+03 1.2X 1.19X 1.2X // //bigInt n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 2.98e+03 3.01e+03 3.04e+03 1X 1X 1X // Iterate n=6 2.96e+03 2.98e+03 3.02e+03 0.992X 0.991X 0.992X // //bigInt n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 2.63e+03 2.67e+03 2.7e+03 1X 1X 1X // Iterate n=7 2.52e+03 2.54e+03 2.57e+03 0.957X 0.951X 0.951X // //bigInt n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 2.69e+03 2.77e+03 2.81e+03 1X 1X 1X // Iterate n=8 2.33e+03 2.35e+03 2.38e+03 0.865X 0.849X 0.846X // //bigInt n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 2.62e+03 2.67e+03 2.7e+03 1X 1X 1X // Iterate n=9 1.84e+03 1.86e+03 1.88e+03 0.701X 0.695X 0.696X // //bigInt n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 2.54e+03 2.58e+03 2.62e+03 1X 1X 1X // Iterate n=10 1.64e+03 1.68e+03 1.69e+03 0.645X 0.65X 0.646X // //bigInt n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 1.35e+03 1.4e+03 1.42e+03 1X 1X 1X // Iterate n=400 47.7 48.6 48.8 0.0352X 0.0348X 0.0344X // //float n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 3.36e+03 3.39e+03 3.42e+03 1X 1X 1X // Iterate n=1 7.22e+03 7.27e+03 7.34e+03 2.15X 2.14X 2.14X // //float n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 4.08e+03 4.14e+03 4.19e+03 1X 1X 1X // Iterate n=2 4.7e+03 4.74e+03 4.77e+03 1.15X 1.14X 1.14X // //float n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 2.92e+03 2.95e+03 2.98e+03 1X 1X 1X // Iterate n=3 3.63e+03 3.66e+03 3.7e+03 1.24X 1.24X 1.24X // //float n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 2.81e+03 2.84e+03 2.87e+03 1X 1X 1X // Iterate n=4 2.9e+03 2.94e+03 2.97e+03 1.03X 1.03X 1.03X // //float n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 2.97e+03 3.03e+03 3.07e+03 1X 1X 1X // Iterate n=5 2.35e+03 2.37e+03 2.4e+03 0.792X 0.782X 0.782X // //float n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 2.77e+03 2.85e+03 2.88e+03 1X 1X 1X // Iterate n=6 2.01e+03 2.03e+03 2.04e+03 0.724X 0.71X 0.707X // //float n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 2.45e+03 2.52e+03 2.61e+03 1X 1X 1X // Iterate n=7 1.67e+03 1.75e+03 1.77e+03 0.683X 0.696X 0.679X // //float n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 2.45e+03 2.53e+03 2.56e+03 1X 1X 1X // Iterate n=8 1.45e+03 1.54e+03 1.56e+03 0.59X 0.607X 0.607X // //float n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 2.45e+03 2.53e+03 2.56e+03 1X 1X 1X // Iterate n=9 1.32e+03 1.38e+03 1.4e+03 0.538X 0.547X 0.546X // //float n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 2.29e+03 2.32e+03 2.35e+03 1X 1X 1X // Iterate n=10 1.21e+03 1.24e+03 1.25e+03 0.529X 0.535X 0.533X // //float n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 1.01e+03 1.04e+03 1.08e+03 1X 1X 1X // Iterate n=400 32.4 32.6 33 0.0321X 0.0313X 0.0305X // //double n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 2.49e+03 2.52e+03 2.54e+03 1X 1X 1X // Iterate n=1 7.15e+03 7.26e+03 7.31e+03 2.87X 2.88X 2.88X // //double n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 2.05e+03 2.08e+03 2.09e+03 1X 1X 1X // Iterate n=2 4.82e+03 4.97e+03 5.03e+03 2.36X 2.39X 2.4X // //double n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 2.1e+03 2.14e+03 2.16e+03 1X 1X 1X // Iterate n=3 3.62e+03 3.67e+03 3.7e+03 1.72X 1.71X 1.71X // //double n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 2.27e+03 2.29e+03 2.31e+03 1X 1X 1X // Iterate n=4 2.91e+03 2.94e+03 2.97e+03 1.29X 1.28X 1.29X // //double n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 2.17e+03 2.2e+03 2.22e+03 1X 1X 1X // Iterate n=5 2.34e+03 2.37e+03 2.4e+03 1.08X 1.08X 1.08X // //double n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 1.85e+03 2.04e+03 2.09e+03 1X 1X 1X // Iterate n=6 1.94e+03 2.02e+03 2.04e+03 1.05X 0.988X 0.976X // //double n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 2.04e+03 2.06e+03 2.08e+03 1X 1X 1X // Iterate n=7 1.74e+03 1.75e+03 1.77e+03 0.852X 0.85X 0.851X // //double n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 2.2e+03 2.23e+03 2.25e+03 1X 1X 1X // Iterate n=8 1.53e+03 1.55e+03 1.56e+03 0.694X 0.697X 0.695X // //double n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 2.16e+03 2.23e+03 2.25e+03 1X 1X 1X // Iterate n=9 1.34e+03 1.38e+03 1.4e+03 0.621X 0.621X 0.619X // //double n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 2.12e+03 2.18e+03 2.2e+03 1X 1X 1X // Iterate n=10 1.21e+03 1.24e+03 1.25e+03 0.573X 0.571X 0.569X // //double n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 1.97e+03 2.01e+03 2.03e+03 1X 1X 1X // Iterate n=400 31.8 32.5 33 0.0161X 0.0162X 0.0162X // //string n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 1.69e+03 1.71e+03 1.73e+03 1X 1X 1X // Iterate n=1 2.25e+03 2.26e+03 2.28e+03 1.33X 1.32X 1.32X // //string n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 1.5e+03 1.52e+03 1.53e+03 1X 1X 1X // Iterate n=2 1.19e+03 1.21e+03 1.22e+03 0.795X 0.796X 0.796X // //string n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 1.42e+03 1.44e+03 1.46e+03 1X 1X 1X // Iterate n=3 771 797 805 0.544X 0.552X 0.553X // //string n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 1.5e+03 1.57e+03 1.58e+03 1X 1X 1X // Iterate n=4 695 706 712 0.464X 0.45X 0.45X // //string n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 1.43e+03 1.49e+03 1.5e+03 1X 1X 1X // Iterate n=5 553 563 568 0.386X 0.378X 0.378X // //string n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 1.28e+03 1.31e+03 1.34e+03 1X 1X 1X // Iterate n=6 435 441 445 0.341X 0.337X 0.333X // //string n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 1.33e+03 1.4e+03 1.42e+03 1X 1X 1X // Iterate n=7 414 420 424 0.311X 0.299X 0.299X // //string n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 1.52e+03 1.57e+03 1.59e+03 1X 1X 1X // Iterate n=8 366 371 374 0.241X 0.236X 0.235X // //string n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 1.49e+03 1.53e+03 1.55e+03 1X 1X 1X // Iterate n=9 302 304 307 0.202X 0.199X 0.199X // //string n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 1.4e+03 1.42e+03 1.44e+03 1X 1X 1X // Iterate n=10 317 320 323 0.226X 0.225X 0.224X // //string n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 1.36e+03 1.39e+03 1.42e+03 1X 1X 1X // Iterate n=400 5.38 5.38 5.39 0.00396X 0.00388X 0.0038X // //timestamp n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 1.79e+03 1.87e+03 1.89e+03 1X 1X 1X // Iterate n=1 4.33e+03 4.55e+03 4.71e+03 2.41X 2.44X 2.49X // //timestamp n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 1.69e+03 1.73e+03 1.76e+03 1X 1X 1X // Iterate n=2 3.42e+03 3.54e+03 3.61e+03 2.02X 2.04X 2.05X // //timestamp n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 1.54e+03 1.58e+03 1.6e+03 1X 1X 1X // Iterate n=3 2.49e+03 2.54e+03 2.57e+03 1.61X 1.6X 1.6X // //timestamp n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 1.53e+03 1.6e+03 1.63e+03 1X 1X 1X // Iterate n=4 1.9e+03 1.95e+03 1.96e+03 1.24X 1.21X 1.21X // //timestamp n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 1.61e+03 1.68e+03 1.7e+03 1X 1X 1X // Iterate n=5 1.57e+03 1.59e+03 1.6e+03 0.976X 0.943X 0.939X // //timestamp n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 1.47e+03 1.49e+03 1.51e+03 1X 1X 1X // Iterate n=6 1.32e+03 1.34e+03 1.35e+03 0.893X 0.895X 0.893X // //timestamp n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 1.44e+03 1.51e+03 1.54e+03 1X 1X 1X // Iterate n=7 1.12e+03 1.15e+03 1.16e+03 0.776X 0.758X 0.755X // //timestamp n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 1.65e+03 1.67e+03 1.69e+03 1X 1X 1X // Iterate n=8 992 1.01e+03 1.02e+03 0.602X 0.604X 0.606X // //timestamp n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 1.56e+03 1.57e+03 1.59e+03 1X 1X 1X // Iterate n=9 894 902 912 0.575X 0.573X 0.575X // //timestamp n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 1.55e+03 1.59e+03 1.61e+03 1X 1X 1X // Iterate n=10 789 814 824 0.51X 0.511X 0.51X // //timestamp n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 1.4e+03 1.48e+03 1.5e+03 1X 1X 1X // Iterate n=400 20.5 20.9 20.9 0.0146X 0.0141X 0.0139X // //decimal(4,0) n=1: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=1 1.82e+03 1.89e+03 1.91e+03 1X 1X 1X // Iterate n=1 6.26e+03 6.43e+03 6.5e+03 3.44X 3.4X 3.4X // //decimal(4,0) n=2: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=2 1.69e+03 1.76e+03 1.77e+03 1X 1X 1X // Iterate n=2 3.99e+03 4.07e+03 4.1e+03 2.36X 2.32X 2.31X // //decimal(4,0) n=3: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=3 1.63e+03 1.66e+03 1.68e+03 1X 1X 1X // Iterate n=3 3.19e+03 3.22e+03 3.26e+03 1.95X 1.94X 1.94X // //decimal(4,0) n=4: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=4 1.76e+03 1.81e+03 1.84e+03 1X 1X 1X // Iterate n=4 2.46e+03 2.52e+03 2.56e+03 1.4X 1.39X 1.39X // //decimal(4,0) n=5: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=5 1.64e+03 1.69e+03 1.7e+03 1X 1X 1X // Iterate n=5 1.93e+03 1.96e+03 1.98e+03 1.17X 1.16X 1.16X // //decimal(4,0) n=6: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=6 1.61e+03 1.65e+03 1.67e+03 1X 1X 1X // Iterate n=6 1.71e+03 1.74e+03 1.76e+03 1.06X 1.06X 1.06X // //decimal(4,0) n=7: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=7 1.53e+03 1.56e+03 1.57e+03 1X 1X 1X // Iterate n=7 1.53e+03 1.57e+03 1.59e+03 1X 1X 1.01X // //decimal(4,0) n=8: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=8 1.69e+03 1.73e+03 1.76e+03 1X 1X 1X // Iterate n=8 1.4e+03 1.43e+03 1.46e+03 0.829X 0.828X 0.83X // //decimal(4,0) n=9: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=9 1.69e+03 1.72e+03 1.74e+03 1X 1X 1X // Iterate n=9 1.28e+03 1.32e+03 1.34e+03 0.756X 0.766X 0.769X // //decimal(4,0) n=10: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=10 1.65e+03 1.69e+03 1.71e+03 1X 1X 1X // Iterate n=10 1.16e+03 1.22e+03 1.25e+03 0.707X 0.723X 0.729X // //decimal(4,0) n=400: Function iters/ms 10%ile 50%ile 90%ile 10%ile 50%ile 90%ile // (relative) (relative) (relative) //--------------------------------------------------------------------------------------------------------- // SetLookup n=400 1.52e+03 1.58e+03 1.6e+03 1X 1X 1X // Iterate n=400 30.6 31.3 31.3 0.0202X 0.0197X 0.0195X #include <boost/lexical_cast.hpp> #include <gutil/strings/substitute.h> #include "exprs/in-predicate.h" #include "runtime/decimal-value.h" #include "runtime/string-value.h" #include "udf/udf-test-harness.h" #include "util/benchmark.h" #include "util/cpu-info.h" #include "common/names.h" using namespace impala; using namespace impala_udf; using namespace strings; using std::move; namespace impala { template<typename T> T MakeAnyVal(int v) { return T(v); } template<> StringVal MakeAnyVal(int v) { // Leak these strings so we don't have to worry about them going out of scope string* s = new string(); *s = lexical_cast<string>(v); return StringVal(reinterpret_cast<uint8_t*>(const_cast<char*>(s->c_str())), s->size()); } class InPredicateBenchmark { public: template<typename T, typename SetType> struct TestData { vector<T> anyvals; vector<AnyVal*> anyval_ptrs; InPredicate::SetLookupState<SetType> state; vector<T> search_vals; int total_found_set; int total_set; int total_found_iter; int total_iter; }; template<typename T, typename SetType> static TestData<T, SetType> CreateTestData(int num_values, const FunctionContext::TypeDesc& type, int num_search_vals = 100) { srand(time(NULL)); TestData<T, SetType> data; data.anyvals.resize(num_values); data.anyval_ptrs.resize(num_values); for (int i = 0; i < num_values; ++i) { data.anyvals[i] = MakeAnyVal<T>(rand()); data.anyval_ptrs[i] = &data.anyvals[i]; } for (int i = 0; i < num_search_vals; ++i) { data.search_vals.push_back(MakeAnyVal<T>(rand())); } FunctionContext* ctx = CreateContext(num_values, type); vector<AnyVal*> constant_args; constant_args.push_back(NULL); for (AnyVal* p : data.anyval_ptrs) constant_args.push_back(p); UdfTestHarness::SetConstantArgs(ctx, move(constant_args)); InPredicate::SetLookupPrepare<T, SetType>(ctx, FunctionContext::FRAGMENT_LOCAL); data.state = *reinterpret_cast<InPredicate::SetLookupState<SetType>*>( ctx->GetFunctionState(FunctionContext::FRAGMENT_LOCAL)); data.total_found_set = data.total_set = data.total_found_iter = data.total_iter = 0; return data; } template<typename T, typename SetType> static void TestSetLookup(int batch_size, void* d) { TestData<T, SetType>* data = reinterpret_cast<TestData<T, SetType>*>(d); for (int i = 0; i < batch_size; ++i) { for (const T& search_val: data->search_vals) { BooleanVal found = InPredicate::SetLookup(&data->state, search_val); if (found.val) ++data->total_found_set; ++data->total_set; } } } template<typename T, typename SetType> static void TestIterate(int batch_size, void* d) { TestData<T, SetType>* data = reinterpret_cast<TestData<T, SetType>*>(d); for (int i = 0; i < batch_size; ++i) { for (const T& search_val: data->search_vals) { BooleanVal found = InPredicate::Iterate( data->state.type, search_val, data->anyvals.size(), &data->anyvals[0]); if (found.val) ++data->total_found_iter; ++data->total_iter; } } } template <typename AnyValType, typename SetType, FunctionContext::Type TypeDesc> static void RunBenchmark(int n) { Benchmark suite(Substitute("$0 n=$1", GetTypeName(TypeDesc), n)); FunctionContext::TypeDesc type; type.type = TypeDesc; InPredicateBenchmark::TestData<AnyValType, SetType> data = InPredicateBenchmark::CreateTestData<AnyValType, SetType>(n, type); suite.AddBenchmark(Substitute("SetLookup n=$0", n), InPredicateBenchmark::TestSetLookup<AnyValType, SetType>, &data); suite.AddBenchmark(Substitute("Iterate n=$0", n), InPredicateBenchmark::TestIterate<AnyValType, SetType>, &data); cout << suite.Measure() << endl; } private: static FunctionContext* CreateContext( int num_args, const FunctionContext::TypeDesc& type) { // Types don't matter (but number of args do) FunctionContext::TypeDesc ret_type; vector<FunctionContext::TypeDesc> arg_types(num_args + 1, type); return UdfTestHarness::CreateTestContext(ret_type, arg_types); } static string GetTypeName(FunctionContext::Type type){ switch (type) { case FunctionContext::TYPE_TINYINT: return "tinyInt"; case FunctionContext::TYPE_SMALLINT: return "smallInt"; case FunctionContext::TYPE_INT: return "int"; case FunctionContext::TYPE_BIGINT: return "bigInt"; case FunctionContext::TYPE_FLOAT: return "float"; case FunctionContext::TYPE_DOUBLE: return "double"; case FunctionContext::TYPE_STRING: return "string"; case FunctionContext::TYPE_TIMESTAMP: return "timestamp"; default: return "Unsupported Type"; } } }; template <> void InPredicateBenchmark::RunBenchmark<DecimalVal, Decimal16Value, FunctionContext::TYPE_DECIMAL>(int n) { Benchmark suite(Substitute("decimal(4,0) n=$0", n)); FunctionContext::TypeDesc type; type.type = FunctionContext::TYPE_DECIMAL; type.precision = 4; type.scale = 0; InPredicateBenchmark::TestData<DecimalVal, Decimal16Value> data = InPredicateBenchmark::CreateTestData<DecimalVal, Decimal16Value>(n, type); suite.AddBenchmark(Substitute("SetLookup n=$0", n), InPredicateBenchmark::TestSetLookup<DecimalVal, Decimal16Value>, &data); suite.AddBenchmark(Substitute("Iterate n=$0", n), InPredicateBenchmark::TestIterate<DecimalVal, Decimal16Value>, &data); cout << suite.Measure() << endl; } } #define RUN_BENCHMARK(AnyValType, SetType, type_desc) \ for (int i = 1; i <= 10; ++i) { \ InPredicateBenchmark::RunBenchmark<AnyValType, SetType, type_desc>(i); \ } \ InPredicateBenchmark::RunBenchmark<AnyValType, SetType, type_desc>(400); int main(int argc, char **argv) { CpuInfo::Init(); cout << Benchmark::GetMachineInfo() << endl; RUN_BENCHMARK(TinyIntVal, int8_t, FunctionContext::TYPE_TINYINT) RUN_BENCHMARK(SmallIntVal, int16_t, FunctionContext::TYPE_SMALLINT) RUN_BENCHMARK(IntVal, int32_t, FunctionContext::TYPE_INT) RUN_BENCHMARK(BigIntVal, int64_t, FunctionContext::TYPE_BIGINT) RUN_BENCHMARK(FloatVal, float, FunctionContext::TYPE_FLOAT) RUN_BENCHMARK(DoubleVal, double, FunctionContext::TYPE_DOUBLE) RUN_BENCHMARK(StringVal, StringValue, FunctionContext::TYPE_STRING) RUN_BENCHMARK(TimestampVal, TimestampValue, FunctionContext::TYPE_TIMESTAMP) RUN_BENCHMARK(DecimalVal, Decimal16Value, FunctionContext::TYPE_DECIMAL) return 0; }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <random> #include <math.h> /* Simulates two attractor dynamic system * * Code inspired by code of A. I. Gafos * http://www.ling.uni-potsdam.de/~gafos/code/inc_neut.m * * Author: Simon Ritter * Date: September 26 2018 * * Arguments: * 1. control parameter k * 2. noise scaler * 3. range of x values for simulation */ int main(int argc, char *argv[]) { double k, s; double xlim; double t = 10; int N = 10000; int n = 2500; double dt = t / (double)N; double dX[N]; double X[n]; double sols[n]; sscanf(argv[1],"%lf",&k); // control parameter sscanf(argv[2],"%lf",&s); // noise scaler sscanf(argv[3],"%lf",&xlim); // range of x std::random_device rd; std::mt19937 gen(rd()); std::normal_distribution<double> d(0.0, 1); std::uniform_real_distribution<> uni(-xlim, xlim); int i; int j; for (i = 0; i < n; i++) { X[0] = uni(gen); for (j = 1; j < N; j++) { dX[j-1] = dt * (-4 * 18 * pow(X[j-1], 3) + k * 3 * pow(X[j-1], 2) + 2 * 7.5 * X[j-1]) + s * d(gen) * sqrt(dt); X[j] = X[j-1] + dX[j-1]; } sols[i] = X[N-1]; printf("%lf\n", sols[i]); } return 0; }
#include "sandbox.h" #include <sys/stat.h> // stat #include <algorithm> // std::find #include <fstream> #include <math.h> #include <memory> #include "tools/text.h" #include "ada/window.h" #include "ada/tools/text.h" #include "ada/tools/geom.h" #include "ada/tools/pixels.h" #include "ada/tools/holoplay.h" #include "ada/shaders/defaultShaders.h" #include "glm/gtx/matrix_transform_2d.hpp" #include "glm/gtx/rotate_vector.hpp" #define TRACK_BEGIN(A) if (uniforms.tracker.isRunning()) uniforms.tracker.begin(A); #define TRACK_END(A) if (uniforms.tracker.isRunning()) uniforms.tracker.end(A); // ------------------------------------------------------------------------- CONTRUCTOR Sandbox::Sandbox(): frag_index(-1), vert_index(-1), geom_index(-1), holoplay(-1), verbose(false), cursor(true), fxaa(false), // Main Vert/Frag/Geom m_frag_source(""), m_vert_source(""), // Buffers m_buffers_total(0), // Poisson Fill m_convolution_pyramid_total(0), // PostProcessing m_postprocessing(false), // Geometry helpers m_billboard_vbo(nullptr), m_cross_vbo(nullptr), // Record m_record_fdelta(0.04166666667), m_record_counter(0), m_record_sec_start(0.0f), m_record_sec_head(0.0f), m_record_sec_end(0.0f), m_record_sec(false), m_record_frame_start(0), m_record_frame_head(0), m_record_frame_end(0), m_record_frame(false), // Histogram m_histogram_texture(nullptr), m_histogram(false), // Scene m_view2d(1.0), m_time_offset(0.0), m_lat(180.0), m_lon(0.0), m_frame(0), m_change(true), m_initialized(false), m_error_screen(true), #ifdef SUPPORT_MULTITHREAD_RECORDING m_task_count(0), /** allow 500 MB to be used for the image save queue **/ m_max_mem_in_queue(500 * 1024 * 1024), m_save_threads(std::max(1, static_cast<int>(std::thread::hardware_concurrency()) - 1)), #endif // Debug m_showTextures(false), m_showPasses(false) { // TIME UNIFORMS // uniforms.functions["u_frame"] = UniformFunction( "int", [this](ada::Shader& _shader) { if (m_record_sec) _shader.setUniform("u_frame", (int)(m_record_sec_start / m_record_fdelta) + m_record_counter); else if (m_record_frame) _shader.setUniform("u_frame", m_record_frame_head); _shader.setUniform("u_frame", (int)m_frame); }, [this]() { return ada::toString(m_frame); } ); uniforms.functions["u_time"] = UniformFunction( "float", [this](ada::Shader& _shader) { if (m_record_sec) _shader.setUniform("u_time", m_record_sec_head); else if (m_record_frame) _shader.setUniform("u_time", m_record_frame_head * m_record_fdelta); else _shader.setUniform("u_time", float(ada::getTime()) - m_time_offset); }, [this]() { return ada::toString(ada::getTime() - m_time_offset); } ); uniforms.functions["u_delta"] = UniformFunction("float", [this](ada::Shader& _shader) { if (m_record_sec || m_record_frame) _shader.setUniform("u_delta", float(m_record_fdelta)); else _shader.setUniform("u_delta", float(ada::getDelta())); }, []() { return ada::toString(ada::getDelta()); }); uniforms.functions["u_date"] = UniformFunction("vec4", [](ada::Shader& _shader) { _shader.setUniform("u_date", ada::getDate()); }, []() { return ada::toString(ada::getDate(), ','); }); // MOUSE uniforms.functions["u_mouse"] = UniformFunction("vec2", [](ada::Shader& _shader) { _shader.setUniform("u_mouse", float(ada::getMouseX()), float(ada::getMouseY())); }, []() { return ada::toString(ada::getMouseX()) + "," + ada::toString(ada::getMouseY()); } ); // VIEWPORT uniforms.functions["u_resolution"]= UniformFunction("vec2", [](ada::Shader& _shader) { _shader.setUniform("u_resolution", float(ada::getWindowWidth()), float(ada::getWindowHeight())); }, []() { return ada::toString(ada::getWindowWidth()) + "," + ada::toString(ada::getWindowHeight()); }); // SCENE uniforms.functions["u_scene"] = UniformFunction("sampler2D", [this](ada::Shader& _shader) { if (m_postprocessing && m_scene_fbo.getTextureId()) { _shader.setUniformTexture("u_scene", &m_scene_fbo, _shader.textureIndex++ ); } }); uniforms.functions["u_sceneDepth"] = UniformFunction("sampler2D", [this](ada::Shader& _shader) { if (m_postprocessing && m_scene_fbo.getTextureId()) { _shader.setUniformDepthTexture("u_sceneDepth", &m_scene_fbo, _shader.textureIndex++ ); } }); uniforms.functions["u_view2d"] = UniformFunction("mat3", [this](ada::Shader& _shader) { _shader.setUniform("u_view2d", m_view2d); }); uniforms.functions["u_modelViewProjectionMatrix"] = UniformFunction("mat4"); } Sandbox::~Sandbox() { #ifdef SUPPORT_MULTITHREAD_RECORDING /** make sure every frame is saved before exiting **/ if (m_task_count > 0) std::cout << "saving remaining frames to disk, this might take a while ..." << std::endl; while (m_task_count > 0) std::this_thread::sleep_for(std::chrono::milliseconds{10}); #endif } // ------------------------------------------------------------------------- SET void Sandbox::setup( WatchFileList &_files, CommandList &_commands ) { // Add Sandbox Commands // ---------------------------------------- _commands.push_back(Command("debug", [&](const std::string& _line){ if (_line == "debug") { std::string rta = m_showPasses ? "on" : "off"; std::cout << "buffers," << rta << std::endl; rta = m_showTextures ? "on" : "off"; std::cout << "textures," << rta << std::endl; if (geom_index != -1) { rta = m_scene.showGrid ? "on" : "off"; std::cout << "grid," << rta << std::endl; rta = m_scene.showAxis ? "on" : "off"; std::cout << "axis," << rta << std::endl; rta = m_scene.showBBoxes ? "on" : "off"; std::cout << "bboxes," << rta << std::endl; } return true; } else { std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { m_showPasses = (values[1] == "on"); m_showTextures = (values[1] == "on"); // m_histogram = (values[1] == "on"); if (geom_index != -1) { m_scene.showGrid = (values[1] == "on"); m_scene.showAxis = (values[1] == "on"); m_scene.showBBoxes = (values[1] == "on"); if (values[1] == "on") { m_scene.addDefine("DEBUG", values[1]); } else { m_scene.delDefine("DEBUG"); } } } } return false; }, "debug[,on|off] show/hide passes and textures elements", false)); _commands.push_back(Command("track", [&](const std::string& _line){ if (_line == "track") { std::cout << "track," << (uniforms.tracker.isRunning() ? "on" : "off") << std::endl; return true; } else { std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { if ((values[1] == "on" || values[1] == "start" | values[1] == "begin") && !uniforms.tracker.isRunning() ) uniforms.tracker.start(); else if ( (values[1] == "off" || values[1] == "stop" | values[1] == "end") && uniforms.tracker.isRunning() ) uniforms.tracker.stop(); else if (values[1] == "average") std::cout << uniforms.tracker.logAverage(); else if (values[1] == "samples") std::cout << uniforms.tracker.logSamples(); else if (values[1] == "framerate") std::cout << uniforms.tracker.logFramerate(); } else if (values.size() == 3) { if (values[1] == "average" && ada::haveExt(values[2],"csv") ) { std::ofstream out(values[2]); out << uniforms.tracker.logAverage(); out.close(); } else if (values[1] == "average") std::cout << uniforms.tracker.logAverage( values[2] ); else if ( values[1] == "samples" && ada::haveExt(values[2],"csv") ) { std::ofstream out(values[2]); out << "track,timeStampMs,durationMs\n"; out << uniforms.tracker.logSamples(); out.close(); } else if (values[1] == "samples") std::cout << uniforms.tracker.logSamples(values[2]); } else if (values.size() == 4) { if (values[1] == "average" && ada::haveExt(values[3],"csv") ) { std::ofstream out( values[3] ); out << uniforms.tracker.logAverage( values[2] ); out.close(); } else if ( values[1] == "samples" && ada::haveExt(values[3],"csv") ) { std::ofstream out( values[3] ); out << uniforms.tracker.logSamples( values[2] ); out.close(); } } } return false; }, "track[,on|off|average|samples] start/stop tracking rendering time", false)); _commands.push_back(Command("reset", [&](const std::string& _line){ if (_line == "reset") { m_time_offset = ada::getTime(); return true; } return false; }, "reset reset timestamp back to zero", false)); _commands.push_back(Command("time", [&](const std::string& _line){ if (_line == "time") { // Force the output in floats printf("%f\n", ada::getTime() - m_time_offset); return true; } return false; }, "time return u_time, the elapsed time.", false)); _commands.push_back(Command("glsl_version", [&](const std::string& _line){ if (_line == "glsl_version") { // Force the output in floats printf("%i\n", ada::getVersion()); return true; } return false; }, "glsl_version return GLSL Version", false)); _commands.push_back(Command("histogram", [&](const std::string& _line){ if (_line == "histogram") { std::string rta = m_histogram ? "on" : "off"; std::cout << "histogram," << rta << std::endl; return true; } else { std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { m_histogram = (values[1] == "on"); } } return false; }, "histogram[,on|off] show/hide histogram", false)); _commands.push_back(Command("defines", [&](const std::string& _line){ if (_line == "defines") { if (geom_index == -1) m_canvas_shader.printDefines(); else m_scene.printDefines(); return true; } return false; }, "defines return a list of active defines", false)); _commands.push_back(Command("uniforms", [&](const std::string& _line){ uniforms.print(_line == "uniforms,all"); return true; }, "uniforms[,all|active] return a list of all or active uniforms and their values.", false)); _commands.push_back(Command("textures", [&](const std::string& _line){ if (_line == "textures") { uniforms.printTextures(); return true; } else { std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { m_showTextures = (values[1] == "on"); } } return false; }, "textures return a list of textures as their uniform name and path.", false)); _commands.push_back(Command("buffers", [&](const std::string& _line){ if (_line == "buffers") { uniforms.printBuffers(); if (m_postprocessing) { if (holoplay >= 0) std::cout << "HOLO"; else if (fxaa) std::cout << "FXAA"; else std::cout << "Custom"; std::cout << " postProcessing pass" << std::endl; } return true; } else { std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { m_showPasses = (values[1] == "on"); } } return false; }, "buffers return a list of buffers as their uniform name.", false)); _commands.push_back(Command("error_screen", [&](const std::string& _line){ if (_line == "error_screen") { std::string rta = m_error_screen ? "on" : "off"; std::cout << "error_screen," << rta << std::endl; return true; } else { std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { m_error_screen = (values[1] == "on"); } } return false; }, "error_screen display magenta screen on errors", false)); // LIGTH _commands.push_back(Command("lights", [&](const std::string& _line){ if (_line == "lights") { uniforms.printLights(); return true; } return false; }, "lights get all light data.")); _commands.push_back(Command("light_position", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 4) { if (uniforms.lights.size() > 0) uniforms.lights[0].setPosition(glm::vec3(ada::toFloat(values[1]), ada::toFloat(values[2]), ada::toFloat(values[3]))); return true; } else if (values.size() == 5) { size_t i = ada::toInt(values[1]); if (uniforms.lights.size() > i) uniforms.lights[i].setPosition(glm::vec3(ada::toFloat(values[2]), ada::toFloat(values[3]), ada::toFloat(values[4]))); return true; } else { if (uniforms.lights.size() > 0) { glm::vec3 pos = uniforms.lights[0].getPosition(); std::cout << ',' << pos.x << ',' << pos.y << ',' << pos.z << std::endl; } return true; } return false; }, "light_position[,<x>,<y>,<z>] get or set the light position.")); _commands.push_back(Command("light_color", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 4) { if (uniforms.lights.size() > 0) { uniforms.lights[0].color = glm::vec3(ada::toFloat(values[1]), ada::toFloat(values[2]), ada::toFloat(values[3])); uniforms.lights[0].bChange = true; } return true; } else if (values.size() == 5) { size_t i = ada::toInt(values[1]); if (uniforms.lights.size() > i) { uniforms.lights[i].color = glm::vec3(ada::toFloat(values[2]), ada::toFloat(values[3]), ada::toFloat(values[4])); uniforms.lights[i].bChange = true; } return true; } else { if (uniforms.lights.size() > 0) { glm::vec3 color = uniforms.lights[0].color; std::cout << color.x << ',' << color.y << ',' << color.z << std::endl; } return true; } return false; }, "light_color[,<r>,<g>,<b>] get or set the light color.")); _commands.push_back(Command("light_falloff", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { if (uniforms.lights.size() > 0) { uniforms.lights[0].falloff = ada::toFloat(values[1]); uniforms.lights[0].bChange = true; } return true; } else if (values.size() == 5) { size_t i = ada::toInt(values[1]); if (uniforms.lights.size() > i) { uniforms.lights[i].falloff = ada::toFloat(values[2]); uniforms.lights[i].bChange = true; } return true; } else { if (uniforms.lights.size() > 0) { std::cout << uniforms.lights[0].falloff << std::endl; } return true; } return false; }, "light_falloff[,<value>] get or set the light falloff distance.")); _commands.push_back(Command("light_intensity", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { if (uniforms.lights.size() > 0) { uniforms.lights[0].intensity = ada::toFloat(values[1]); uniforms.lights[0].bChange = true; } return true; } else if (values.size() == 5) { size_t i = ada::toInt(values[1]); if (uniforms.lights.size() > i) { uniforms.lights[i].intensity = ada::toFloat(values[2]); uniforms.lights[i].bChange = true; } return true; } else { if (uniforms.lights.size() > 0) { std::cout << uniforms.lights[0].intensity << std::endl; } return true; } return false; }, "light_intensity[,<value>] get or set the light intensity.")); // CAMERA _commands.push_back(Command("camera_distance", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { uniforms.getCamera().setDistance(ada::toFloat(values[1])); return true; } else { std::cout << uniforms.getCamera().getDistance() << std::endl; return true; } return false; }, "camera_distance[,<dist>] get or set the camera distance to the target.")); _commands.push_back(Command("camera_type", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { if (values[1] == "ortho") uniforms.getCamera().setType(ada::CameraType::ORTHO); else if (values[1] == "perspective") uniforms.getCamera().setType(ada::CameraType::PERSPECTIVE); return true; } else { ada::CameraType type = uniforms.getCamera().getType(); if (type == ada::CameraType::ORTHO) std::cout << "ortho" << std::endl; else std::cout << "perspective" << std::endl; return true; } return false; }, "camera_type[,<ortho|perspective>] get or set the camera type")); _commands.push_back(Command("camera_fov", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 2) { uniforms.getCamera().setFOV( ada::toFloat(values[1]) ); return true; } else { std::cout << uniforms.getCamera().getFOV() << std::endl; return true; } return false; }, "camera_fov[,<field_of_view>] get or set the camera field of view.")); _commands.push_back(Command("camera_position", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 4) { uniforms.getCamera().setPosition(glm::vec3(ada::toFloat(values[1]), ada::toFloat(values[2]), ada::toFloat(values[3]))); uniforms.getCamera().lookAt(uniforms.getCamera().getTarget()); return true; } else { glm::vec3 pos = uniforms.getCamera().getPosition(); std::cout << pos.x << ',' << pos.y << ',' << pos.z << std::endl; return true; } return false; }, "camera_position[,<x>,<y>,<z>] get or set the camera position.")); _commands.push_back(Command("camera_exposure", [&](const std::string& _line){ std::vector<std::string> values = ada::split(_line,','); if (values.size() == 4) { uniforms.getCamera().setExposure( ada::toFloat(values[1]), ada::toFloat(values[2]), ada::toFloat(values[3])); return true; } else { std::cout << uniforms.getCamera().getExposure() << std::endl; return true; } return false; }, "camera_exposure[,<aper.>,<shutter>,<sensit.>] get or set the camera exposure values.")); #ifdef SUPPORT_MULTITHREAD_RECORDING _commands.push_back(Command("max_mem_in_queue", [&](const std::string & line) { std::vector<std::string> values = ada::split(line,','); if (values.size() == 2) { m_max_mem_in_queue = std::stoll(values[1]); } else { std::cout << m_max_mem_in_queue.load() << std::endl; } return false; }, "max_mem_in_queue[,<bytes>] set the maximum amount of memory used by a queue to export images to disk")); #endif // LOAD SHACER // ----------------------------------------------- if (frag_index != -1) { // If there is a Fragment shader load it m_frag_source = ""; m_frag_dependencies.clear(); if ( !ada::loadSrcFrom(_files[frag_index].path, &m_frag_source, include_folders, &m_frag_dependencies) ) return; ada::setVersionFromCode(m_frag_source); } else { // If there is no use the default one if (geom_index == -1) m_frag_source = ada::getDefaultSrc(ada::FRAG_DEFAULT); else m_frag_source = ada::getDefaultSrc(ada::FRAG_DEFAULT_SCENE); } if (vert_index != -1) { // If there is a Vertex shader load it m_vert_source = ""; m_vert_dependencies.clear(); ada::loadSrcFrom(_files[vert_index].path, &m_vert_source, include_folders, &m_vert_dependencies); } else { // If there is no use the default one if (geom_index == -1) m_vert_source = ada::getDefaultSrc(ada::VERT_DEFAULT); else m_vert_source = ada::getDefaultSrc(ada::VERT_DEFAULT_SCENE); } // Init Scene elements m_billboard_vbo = ada::rect(0.0,0.0,1.0,1.0).getVbo(); // LOAD GEOMETRY // ----------------------------------------------- if (geom_index == -1) { m_canvas_shader.addDefine("MODEL_VERTEX_TEXCOORD"); uniforms.getCamera().orbit(m_lat, m_lon, 2.0); } else { m_scene.setup( _commands, uniforms); m_scene.loadGeometry( uniforms, _files, geom_index, verbose ); uniforms.getCamera().orbit(m_lat, m_lon, m_scene.getArea() * 2.0); } // FINISH SCENE SETUP // ------------------------------------------------- uniforms.getCamera().setViewport(ada::getWindowWidth(), ada::getWindowHeight()); if (holoplay >= 0) { ada::setHoloplayResolution(holoplay); addDefine("HOLOPLAY", ada::toString(holoplay)); uniforms.getCamera().setFOV(glm::radians(14.0f)); uniforms.getCamera().setType(ada::CameraType::PERSPECTIVE_VIRTUAL_OFFSET); // uniforms.getCamera().setClipping(0.01, 100.0); if (geom_index != -1) uniforms.getCamera().orbit(m_lat, m_lon, m_scene.getArea() * 8.5); } // Prepare viewport glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glFrontFace(GL_CCW); // Turn on Alpha blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA); // Clear the background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // LOAD SHADERS reloadShaders( _files ); // TODO: // - this seams to solve the problem of buffers not properly initialize // - digg deeper // uniforms.buffers.clear(); uniforms.doubleBuffers.clear(); _updateBuffers(); flagChange(); } void Sandbox::addDefine(const std::string &_define, const std::string &_value) { for (int i = 0; i < m_buffers_total; i++) m_buffers_shaders[i].addDefine(_define, _value); if (geom_index == -1) m_canvas_shader.addDefine(_define, _value); else m_scene.addDefine(_define, _value); m_postprocessing_shader.addDefine(_define, _value); } void Sandbox::delDefine(const std::string &_define) { for (int i = 0; i < m_buffers_total; i++) m_buffers_shaders[i].delDefine(_define); if (geom_index == -1) m_canvas_shader.delDefine(_define); else m_scene.delDefine(_define); m_postprocessing_shader.delDefine(_define); } // ------------------------------------------------------------------------- GET bool Sandbox::isReady() { return m_initialized; } void Sandbox::flagChange() { m_change = true; } void Sandbox::unflagChange() { m_change = false; m_scene.unflagChange(); uniforms.unflagChange(); } bool Sandbox::haveChange() { // std::cout << "CHANGE " << m_change << std::endl; // std::cout << "RECORD " << m_record << std::endl; // std::cout << "SCENE " << m_scene.haveChange() << std::endl; // std::cout << "UNIFORMS " << uniforms.haveChange() << std::endl; // std::cout << std::endl; return m_change || m_record_sec || m_record_frame || screenshotFile != "" || m_scene.haveChange() || uniforms.haveChange(); } const std::string& Sandbox::getSource(ShaderType _type) const { return (_type == FRAGMENT)? m_frag_source : m_vert_source; } int Sandbox::getRecordedPercentage() { if (m_record_sec) return ((m_record_sec_head - m_record_sec_start) / (m_record_sec_end - m_record_sec_start)) * 100; else if (m_record_frame) return ( (float)(m_record_frame_head - m_record_frame_start) / (float)(m_record_frame_end - m_record_frame_start)) * 100; else return 100; } // ------------------------------------------------------------------------- RELOAD SHADER void Sandbox::_updateSceneBuffer(int _width, int _height) { ada::FboType type = uniforms.functions["u_sceneDepth"].present ? ada::COLOR_DEPTH_TEXTURES : ada::COLOR_TEXTURE_DEPTH_BUFFER; if (holoplay >= 0) { _width = ada::getHoloplayWidth(); _height= ada::getHoloplayHeight(); } if (!m_scene_fbo.isAllocated() || m_scene_fbo.getType() != type || m_scene_fbo.getWidth() != _width || m_scene_fbo.getHeight() != _height ) m_scene_fbo.allocate(_width, _height, type); } bool Sandbox::setSource(ShaderType _type, const std::string& _source) { if (_type == FRAGMENT) m_frag_source = _source; else m_vert_source = _source; return true; }; bool Sandbox::reloadShaders( WatchFileList &_files ) { flagChange(); // UPDATE scene shaders of models (materials) if (geom_index == -1) { if (verbose) std::cout << "// Reload 2D shaders" << std::endl; // Reload the shader m_canvas_shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER); m_canvas_shader.load(m_frag_source, m_vert_source, verbose, m_error_screen); } else { if (verbose) std::cout << "// Reload 3D scene shaders" << std::endl; m_scene.loadShaders(m_frag_source, m_vert_source, verbose); } // UPDATE shaders dependencies { ada::List new_dependencies = ada::merge(m_frag_dependencies, m_vert_dependencies); // remove old dependencies for (int i = _files.size() - 1; i >= 0; i--) if (_files[i].type == GLSL_DEPENDENCY) _files.erase( _files.begin() + i); // Add new dependencies struct stat st; for (size_t i = 0; i < new_dependencies.size(); i++) { WatchFile file; file.type = GLSL_DEPENDENCY; file.path = new_dependencies[i]; stat( file.path.c_str(), &st ); file.lastChange = st.st_mtime; _files.push_back(file); if (verbose) std::cout << " Watching file " << new_dependencies[i] << " as a dependency " << std::endl; } } // UPDATE uniforms uniforms.checkPresenceIn(m_vert_source, m_frag_source); // Check active native uniforms uniforms.flagChange(); // Flag all user defined uniforms as changed if (uniforms.cubemap) { addDefine("SCENE_SH_ARRAY", "u_SH"); addDefine("SCENE_CUBEMAP", "u_cubeMap"); } // UPDATE Buffers m_buffers_total = countBuffers(m_frag_source); m_doubleBuffers_total = countDoubleBuffers(m_frag_source); _updateBuffers(); // Convolution Pyramids m_convolution_pyramid_total = countConvolutionPyramid( getSource(FRAGMENT) ); _updateConvolutionPyramids(); // UPDATE Postprocessing bool havePostprocessing = checkPostprocessing( getSource(FRAGMENT) ); if (havePostprocessing) { // Specific defines for this buffer m_postprocessing_shader.addDefine("POSTPROCESSING"); m_postprocessing_shader.load(m_frag_source, ada::getDefaultSrc(ada::VERT_BILLBOARD), false); m_postprocessing = havePostprocessing; } else if (holoplay >= 0) { m_postprocessing_shader.load(ada::getHoloplayFragShader(ada::getVersion()), ada::getDefaultSrc(ada::VERT_BILLBOARD), false); uniforms.functions["u_scene"].present = true; m_postprocessing = true; } else if (fxaa) { m_postprocessing_shader.load(ada::getDefaultSrc(ada::FRAG_FXAA), ada::getDefaultSrc(ada::VERT_BILLBOARD), false); uniforms.functions["u_scene"].present = true; m_postprocessing = true; } else m_postprocessing = false; if (m_postprocessing || m_histogram) _updateSceneBuffer(ada::getWindowWidth(), ada::getWindowHeight()); return true; } // ------------------------------------------------------------------------- UPDATE void Sandbox::_updateBuffers() { if ( m_buffers_total != int(uniforms.buffers.size()) ) { if (verbose) std::cout << "// Creating/Removing " << uniforms.buffers.size() << " buffers to " << m_buffers_total << std::endl; uniforms.buffers.clear(); m_buffers_shaders.clear(); for (int i = 0; i < m_buffers_total; i++) { // New FBO uniforms.buffers.push_back( ada::Fbo() ); glm::vec2 size = glm::vec2(ada::getWindowWidth(), ada::getWindowHeight()); uniforms.buffers[i].fixed = getBufferSize(m_frag_source, i, size); uniforms.buffers[i].allocate(size.x, size.y, ada::COLOR_FLOAT_TEXTURE); // New Shader m_buffers_shaders.push_back( ada::Shader() ); m_buffers_shaders[i].addDefine("BUFFER_" + ada::toString(i)); m_buffers_shaders[i].load(m_frag_source, ada::getDefaultSrc(ada::VERT_BILLBOARD), false); } } else { for (size_t i = 0; i < m_buffers_shaders.size(); i++) { // Reload shader code m_buffers_shaders[i].addDefine("BUFFER_" + ada::toString(i)); m_buffers_shaders[i].load(m_frag_source, ada::getDefaultSrc(ada::VERT_BILLBOARD), false); } } if ( m_doubleBuffers_total != int(uniforms.doubleBuffers.size()) ) { if (verbose) std::cout << "// Creating/Removing " << uniforms.doubleBuffers.size() << " double buffers to " << m_doubleBuffers_total << std::endl; uniforms.doubleBuffers.clear(); m_doubleBuffers_shaders.clear(); for (int i = 0; i < m_doubleBuffers_total; i++) { // New FBO uniforms.doubleBuffers.push_back( ada::PingPong() ); glm::vec2 size = glm::vec2(ada::getWindowWidth(), ada::getWindowHeight()); bool fixed = getDoubleBufferSize(m_frag_source, i, size); uniforms.doubleBuffers[i][0].fixed = fixed; uniforms.doubleBuffers[i][1].fixed = fixed; uniforms.doubleBuffers[i].allocate(size.x, size.y, ada::COLOR_FLOAT_TEXTURE); // New Shader m_doubleBuffers_shaders.push_back( ada::Shader() ); m_doubleBuffers_shaders[i].addDefine("DOUBLE_BUFFER_" + ada::toString(i)); m_doubleBuffers_shaders[i].load(m_frag_source, ada::getDefaultSrc(ada::VERT_BILLBOARD), false); } } else { for (size_t i = 0; i < m_doubleBuffers_shaders.size(); i++) { // Reload shader code m_doubleBuffers_shaders[i].addDefine("DOUBLE_BUFFER_" + ada::toString(i)); m_doubleBuffers_shaders[i].load(m_frag_source, ada::getDefaultSrc(ada::VERT_BILLBOARD), false); } } } void Sandbox::_updateConvolutionPyramids() { if ( m_convolution_pyramid_total != int(uniforms.convolution_pyramids.size()) ) { if (verbose) std::cout << "Removing " << uniforms.convolution_pyramids.size() << " convolution pyramids to create " << m_convolution_pyramid_total << std::endl; uniforms.convolution_pyramids.clear(); m_convolution_pyramid_fbos.clear(); m_convolution_pyramid_subshaders.clear(); for (int i = 0; i < m_convolution_pyramid_total; i++) { uniforms.convolution_pyramids.push_back( ada::ConvolutionPyramid() ); uniforms.convolution_pyramids[i].allocate(ada::getWindowWidth(), ada::getWindowHeight()); uniforms.convolution_pyramids[i].pass = [this](ada::Fbo *_target, const ada::Fbo *_tex0, const ada::Fbo *_tex1, int _depth) { _target->bind(); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); m_convolution_pyramid_shader.use(); uniforms.feedTo(m_convolution_pyramid_shader); m_convolution_pyramid_shader.setUniform("u_convolutionPyramidDepth", _depth); m_convolution_pyramid_shader.setUniform("u_convolutionPyramidTotalDepth", (int)uniforms.convolution_pyramids[0].getDepth()); m_convolution_pyramid_shader.setUniform("u_convolutionPyramidUpscaling", _tex1 != NULL); m_convolution_pyramid_shader.textureIndex = geom_index == -1 ? 1 : 0; m_convolution_pyramid_shader.setUniformTexture("u_convolutionPyramidTex0", _tex0); if (_tex1 != NULL) m_convolution_pyramid_shader.setUniformTexture("u_convolutionPyramidTex1", _tex1); m_convolution_pyramid_shader.setUniform("u_resolution", ((float)_target->getWidth()), ((float)_target->getHeight())); m_convolution_pyramid_shader.setUniform("u_pixel", 1.0f/((float)_target->getWidth()), 1.0f/((float)_target->getHeight())); m_billboard_vbo->render( &m_convolution_pyramid_shader ); _target->unbind(); }; m_convolution_pyramid_fbos.push_back( ada::Fbo() ); m_convolution_pyramid_fbos[i].allocate(ada::getWindowWidth(), ada::getWindowHeight(), ada::COLOR_TEXTURE); m_convolution_pyramid_subshaders.push_back( ada::Shader() ); } } if ( checkConvolutionPyramid( getSource(FRAGMENT) ) ) { m_convolution_pyramid_shader.addDefine("CONVOLUTION_PYRAMID_ALGORITHM"); m_convolution_pyramid_shader.load(m_frag_source, ada::getDefaultSrc(ada::VERT_BILLBOARD), false); } else m_convolution_pyramid_shader.load(ada::getDefaultSrc(ada::FRAG_POISSON), ada::getDefaultSrc(ada::VERT_BILLBOARD), false); for (size_t i = 0; i < m_convolution_pyramid_subshaders.size(); i++) { m_convolution_pyramid_subshaders[i].addDefine("CONVOLUTION_PYRAMID_" + ada::toString(i)); m_convolution_pyramid_subshaders[i].load(m_frag_source, ada::getDefaultSrc(ada::VERT_BILLBOARD), false); } } // ------------------------------------------------------------------------- DRAW void Sandbox::_renderBuffers() { glDisable(GL_BLEND); bool reset_viewport = false; for (size_t i = 0; i < uniforms.buffers.size(); i++) { TRACK_BEGIN("render:buffer" + ada::toString(i)) reset_viewport += uniforms.buffers[i].fixed; uniforms.buffers[i].bind(); m_buffers_shaders[i].use(); // Pass textures for the other buffers for (size_t j = 0; j < uniforms.buffers.size(); j++) if (i != j) m_buffers_shaders[i].setUniformTexture("u_buffer" + ada::toString(j), &uniforms.buffers[j] ); for (size_t j = 0; j < uniforms.doubleBuffers.size(); j++) m_buffers_shaders[i].setUniformTexture("u_doubleBuffer" + ada::toString(j), uniforms.doubleBuffers[j].src ); // Update uniforms and textures uniforms.feedTo( m_buffers_shaders[i], true, false); m_billboard_vbo->render( &m_buffers_shaders[i] ); uniforms.buffers[i].unbind(); TRACK_END("render:buffer" + ada::toString(i)) } for (size_t i = 0; i < uniforms.doubleBuffers.size(); i++) { TRACK_BEGIN("render:doubleBuffer" + ada::toString(i)) reset_viewport += uniforms.doubleBuffers[i].src->fixed; uniforms.doubleBuffers[i].dst->bind(); m_doubleBuffers_shaders[i].use(); // Pass textures for the other buffers for (size_t j = 0; j < uniforms.buffers.size(); j++) m_doubleBuffers_shaders[i].setUniformTexture("u_buffer" + ada::toString(j), &uniforms.buffers[j] ); for (size_t j = 0; j < uniforms.doubleBuffers.size(); j++) m_doubleBuffers_shaders[i].setUniformTexture("u_doubleBuffer" + ada::toString(j), uniforms.doubleBuffers[j].src ); // Update uniforms and textures uniforms.feedTo( m_doubleBuffers_shaders[i], true, false); m_billboard_vbo->render( &m_doubleBuffers_shaders[i] ); uniforms.doubleBuffers[i].dst->unbind(); uniforms.doubleBuffers[i].swap(); TRACK_END("render:doubleBuffer" + ada::toString(i)) } #if defined(__EMSCRIPTEN__) if (ada::getWebGLVersionNumber() == 1) reset_viewport = true; #endif if (reset_viewport) glViewport(0.0f, 0.0f, ada::getWindowWidth(), ada::getWindowHeight()); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void Sandbox::_renderConvolutionPyramids() { // // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); for (size_t i = 0; i < m_convolution_pyramid_subshaders.size(); i++) { TRACK_BEGIN("render:convolution_pyramid" + ada::toString(i)) glDisable(GL_BLEND); m_convolution_pyramid_fbos[i].bind(); m_convolution_pyramid_subshaders[i].use(); // Clear the background glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Update uniforms and textures uniforms.feedTo( m_convolution_pyramid_subshaders[i] ); m_billboard_vbo->render( &m_convolution_pyramid_subshaders[i] ); m_convolution_pyramid_fbos[i].unbind(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); uniforms.convolution_pyramids[i].process(&m_convolution_pyramid_fbos[i]); TRACK_END("render:convolution_pyramid" + ada::toString(i)) } } void Sandbox::render() { TRACK_BEGIN("render") // UPDATE STREAMING TEXTURES // ----------------------------------------------- if (m_initialized) uniforms.updateStreammingTextures(); // RENDER SHADOW MAP // ----------------------------------------------- if (geom_index != -1) m_scene.renderShadowMap(uniforms); // BUFFERS // ----------------------------------------------- if (uniforms.buffers.size() > 0 || uniforms.doubleBuffers.size() > 0) _renderBuffers(); if (m_convolution_pyramid_total > 0) _renderConvolutionPyramids(); // MAIN SCENE // ----------------------------------------------- < main scene start if (screenshotFile != "" || m_record_sec || m_record_frame) if (!m_record_fbo.isAllocated()) m_record_fbo.allocate(ada::getWindowWidth(), ada::getWindowHeight(), ada::COLOR_TEXTURE_DEPTH_BUFFER); if (m_postprocessing || m_histogram ) { _updateSceneBuffer(ada::getWindowWidth(), ada::getWindowHeight()); m_scene_fbo.bind(); } else if (screenshotFile != "" || m_record_sec || m_record_frame ) m_record_fbo.bind(); // Clear the background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // RENDER CONTENT if (geom_index == -1) { TRACK_BEGIN("render:billboard") // Load main shader m_canvas_shader.use(); if (holoplay >= 0) { ada::holoplayQuilt([&](const ada::HoloplayProperties& holoplay, glm::vec4& viewport, int &viewIndex){ // set up the camera rotation and position for current view uniforms.getCamera().setVirtualOffset(5.0, viewIndex, holoplay.totalViews); uniforms.set("u_holoPlayTile", float(holoplay.columns), float(holoplay.rows), float(holoplay.totalViews)); uniforms.set("u_holoPlayViewport", float(viewport.x), float(viewport.y), float(viewport.z), float(viewport.w)); // Update Uniforms and textures variables uniforms.feedTo( m_canvas_shader ); // Pass special uniforms m_canvas_shader.setUniform("u_modelViewProjectionMatrix", glm::mat4(1.)); m_billboard_vbo->render( &m_canvas_shader ); }); } else { // Update Uniforms and textures variables uniforms.feedTo( m_canvas_shader ); // Pass special uniforms m_canvas_shader.setUniform("u_modelViewProjectionMatrix", glm::mat4(1.)); m_billboard_vbo->render( &m_canvas_shader ); } TRACK_END("render:billboard") } else { TRACK_BEGIN("render:scene") if (holoplay >= 0) { ada::holoplayQuilt([&](const ada::HoloplayProperties& holoplay, glm::vec4& viewport, int &viewIndex){ // set up the camera rotation and position for current view uniforms.getCamera().setVirtualOffset(m_scene.getArea(), viewIndex, holoplay.totalViews); uniforms.set("u_holoPlayTile", float(holoplay.columns), float(holoplay.rows), float(holoplay.totalViews)); uniforms.set("u_holoPlayViewport", float(viewport.x), float(viewport.y), float(viewport.z), float(viewport.w)); m_scene.render(uniforms); if (m_scene.showGrid || m_scene.showAxis || m_scene.showBBoxes) m_scene.renderDebug(uniforms); }); } else { m_scene.render(uniforms); if (m_scene.showGrid || m_scene.showAxis || m_scene.showBBoxes) m_scene.renderDebug(uniforms); } TRACK_END("render:scene") } // ----------------------------------------------- < main scene end // POST PROCESSING if (m_postprocessing) { TRACK_BEGIN("render:postprocessing") m_scene_fbo.unbind(); if (screenshotFile != "" || m_record_sec || m_record_frame) m_record_fbo.bind(); m_postprocessing_shader.use(); // Update uniforms and textures uniforms.feedTo( m_postprocessing_shader ); if (holoplay >= 0) holoplayFeedUniforms(m_postprocessing_shader); // // Pass textures of buffers // for (size_t i = 0; i < uniforms.buffers.size(); i++) // m_postprocessing_shader.setUniformTexture("u_buffer" + ada::toString(i), &uniforms.buffers[i]); // // Pass textures of buffers // for (size_t i = 0; i < uniforms.doubleBuffers.size(); i++) // m_postprocessing_shader.setUniformTexture("u_doubleBuffer" + ada::toString(i), &uniforms.doubleBuffers[i]); m_billboard_vbo->render( &m_postprocessing_shader ); TRACK_END("render:postprocessing") } else if (m_histogram) { m_scene_fbo.unbind(); if (screenshotFile != "" || m_record_sec || m_record_frame) m_record_fbo.bind(); if (!m_billboard_shader.isLoaded()) m_billboard_shader.load(ada::getDefaultSrc(ada::FRAG_DYNAMIC_BILLBOARD), ada::getDefaultSrc(ada::VERT_DYNAMIC_BILLBOARD), false); m_billboard_shader.use(); m_billboard_shader.setUniform("u_depth", 0.0f); m_billboard_shader.setUniform("u_scale", 1.0f, 1.0f); m_billboard_shader.setUniform("u_translate", 0.0f, 0.0f); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", glm::mat4(1.0) ); m_billboard_shader.setUniformTexture("u_tex0", &m_scene_fbo, 0); m_billboard_vbo->render( &m_billboard_shader ); } if (screenshotFile != "" || m_record_sec || m_record_frame) { m_record_fbo.unbind(); if (!m_billboard_shader.isLoaded()) m_billboard_shader.load(ada::getDefaultSrc(ada::FRAG_DYNAMIC_BILLBOARD), ada::getDefaultSrc(ada::VERT_DYNAMIC_BILLBOARD), false); m_billboard_shader.use(); m_billboard_shader.setUniform("u_depth", 0.0f); m_billboard_shader.setUniform("u_scale", 1.0f, 1.0f); m_billboard_shader.setUniform("u_translate", 0.0f, 0.0f); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", glm::mat4(1.0) ); m_billboard_shader.setUniformTexture("u_tex0", &m_record_fbo, 0); m_billboard_vbo->render( &m_billboard_shader ); } TRACK_END("render") } void Sandbox::renderUI() { // TRACK_BEGIN("renderUI") // IN PUT TEXTURES if (m_showTextures) { int nTotal = uniforms.textures.size(); if (nTotal > 0) { glDisable(GL_DEPTH_TEST); // TRACK_BEGIN("textures") float w = (float)(ada::getWindowWidth()); float h = (float)(ada::getWindowHeight()); float scale = fmin(1.0f / (float)(nTotal), 0.25) * 0.5; float xStep = w * scale; float yStep = h * scale; float xOffset = xStep; float yOffset = h - yStep; if (!m_billboard_shader.isLoaded()) m_billboard_shader.load(ada::getDefaultSrc(ada::FRAG_DYNAMIC_BILLBOARD), ada::getDefaultSrc(ada::VERT_DYNAMIC_BILLBOARD), false); m_billboard_shader.use(); for (std::map<std::string, ada::Texture*>::iterator it = uniforms.textures.begin(); it != uniforms.textures.end(); it++) { m_billboard_shader.setUniform("u_depth", 0.0f); m_billboard_shader.setUniform("u_scale", xStep, yStep); m_billboard_shader.setUniform("u_translate", xOffset, yOffset); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_billboard_shader.setUniformTexture("u_tex0", it->second, 0); m_billboard_vbo->render(&m_billboard_shader); yOffset -= yStep * 2.0; } // TRACK_END("textures") } } // RESULTING BUFFERS if (m_showPasses) { glDisable(GL_DEPTH_TEST); // TRACK_BEGIN("buffers") // DEBUG BUFFERS int nTotal = uniforms.buffers.size(); if (m_doubleBuffers_total > 0) nTotal += uniforms.doubleBuffers.size(); if (m_convolution_pyramid_total > 0) nTotal += uniforms.convolution_pyramids.size(); nTotal += uniforms.functions["u_scene"].present; nTotal += uniforms.functions["u_sceneDepth"].present; nTotal += (geom_index != -1); if (nTotal > 0) { float w = (float)(ada::getWindowWidth()); float h = (float)(ada::getWindowHeight()); float scale = fmin(1.0f / (float)(nTotal), 0.25) * 0.5; float xStep = w * scale; float yStep = h * scale; float xOffset = w - xStep; float yOffset = h - yStep; if (!m_billboard_shader.isLoaded()) m_billboard_shader.load(ada::getDefaultSrc(ada::FRAG_DYNAMIC_BILLBOARD), ada::getDefaultSrc(ada::VERT_DYNAMIC_BILLBOARD), false); m_billboard_shader.use(); for (size_t i = 0; i < uniforms.buffers.size(); i++) { m_billboard_shader.setUniform("u_depth", 0.0f); m_billboard_shader.setUniform("u_scale", xStep, yStep); m_billboard_shader.setUniform("u_translate", xOffset, yOffset); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_billboard_shader.setUniformTexture("u_tex0", &uniforms.buffers[i]); m_billboard_vbo->render(&m_billboard_shader); yOffset -= yStep * 2.0; } for (size_t i = 0; i < uniforms.doubleBuffers.size(); i++) { m_billboard_shader.setUniform("u_depth", 0.0f); m_billboard_shader.setUniform("u_scale", xStep, yStep); m_billboard_shader.setUniform("u_translate", xOffset, yOffset); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_billboard_shader.setUniformTexture("u_tex0", uniforms.doubleBuffers[i].src); m_billboard_vbo->render(&m_billboard_shader); yOffset -= yStep * 2.0; } for (size_t i = 0; i < uniforms.convolution_pyramids.size(); i++) { float _x = 0; float _sw = xStep; float _sh = yStep; for (size_t j = 0; j < uniforms.convolution_pyramids[i].getDepth() * 2; j++ ) { m_billboard_shader.setUniform("u_depth", 0.0f); m_billboard_shader.setUniform("u_scale", _sw, _sh); m_billboard_shader.setUniform("u_translate", xOffset + _x, yOffset); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_billboard_shader.setUniformTexture("u_tex0", uniforms.convolution_pyramids[i].getResult(j), 0); m_billboard_vbo->render(&m_billboard_shader); _x -= _sw; if (j < uniforms.convolution_pyramids[i].getDepth()) { _sw *= 0.5; _sh *= 0.5; } else { _sw *= 2.0; _sh *= 2.0; } _x -= _sw; } yOffset -= yStep * 2.0; } if (m_postprocessing) { if (uniforms.functions["u_scene"].present) { m_billboard_shader.setUniform("u_depth", 0.0f); m_billboard_shader.setUniform("u_scale", xStep, yStep); m_billboard_shader.setUniform("u_translate", xOffset, yOffset); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_billboard_shader.setUniformTexture("u_tex0", &m_scene_fbo, 0); m_billboard_vbo->render(&m_billboard_shader); yOffset -= yStep * 2.0; } if (uniforms.functions["u_sceneDepth"].present) { m_billboard_shader.setUniform("u_scale", xStep, yStep); m_billboard_shader.setUniform("u_translate", xOffset, yOffset); m_billboard_shader.setUniform("u_depth", 1.0f); uniforms.functions["u_cameraNearClip"].assign(m_billboard_shader); uniforms.functions["u_cameraFarClip"].assign(m_billboard_shader); uniforms.functions["u_cameraDistance"].assign(m_billboard_shader); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_billboard_shader.setUniformDepthTexture("u_tex0", &m_scene_fbo); m_billboard_vbo->render(&m_billboard_shader); yOffset -= yStep * 2.0; } } if (geom_index != -1) { for (size_t i = 0; i < uniforms.lights.size(); i++) { if ( uniforms.lights[i].getShadowMap()->getDepthTextureId() ) { m_billboard_shader.setUniform("u_scale", xStep, yStep); m_billboard_shader.setUniform("u_translate", xOffset, yOffset); m_billboard_shader.setUniform("u_depth", 0.0f); m_billboard_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_billboard_shader.setUniformDepthTexture("u_tex0", uniforms.lights[i].getShadowMap()); m_billboard_vbo->render(&m_billboard_shader); yOffset -= yStep * 2.0; } } } } // TRACK_END("buffers") } if (m_histogram && m_histogram_texture) { glDisable(GL_DEPTH_TEST); TRACK_BEGIN("histogram") float w = 100; float h = 50; float x = (float)(ada::getWindowWidth()) * 0.5; float y = h; if (!m_histogram_shader.isLoaded()) m_histogram_shader.load(ada::getDefaultSrc(ada::FRAG_HISTOGRAM), ada::getDefaultSrc(ada::VERT_DYNAMIC_BILLBOARD), false); m_histogram_shader.use(); for (std::map<std::string, ada::Texture*>::iterator it = uniforms.textures.begin(); it != uniforms.textures.end(); it++) { m_histogram_shader.setUniform("u_scale", w, h); m_histogram_shader.setUniform("u_translate", x, y); m_histogram_shader.setUniform("u_resolution", (float)ada::getWindowWidth(), (float)ada::getWindowHeight()); m_histogram_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_histogram_shader.setUniformTexture("u_sceneHistogram", m_histogram_texture, 0); m_billboard_vbo->render(&m_histogram_shader); } // TRACK_END("histogram") } if (cursor && ada::getMouseEntered()) { // TRACK_BEGIN("cursor") if (m_cross_vbo == nullptr) m_cross_vbo = ada::cross(glm::vec3(0.0, 0.0, 0.0), 10.).getVbo(); if (!m_wireframe2D_shader.isLoaded()) m_wireframe2D_shader.load(ada::getDefaultSrc(ada::FRAG_WIREFRAME_2D), ada::getDefaultSrc(ada::VERT_WIREFRAME_2D), false); glLineWidth(2.0f); m_wireframe2D_shader.use(); m_wireframe2D_shader.setUniform("u_color", glm::vec4(1.0)); m_wireframe2D_shader.setUniform("u_scale", 1.0f, 1.0f); m_wireframe2D_shader.setUniform("u_translate", (float)ada::getMouseX(), (float)ada::getMouseY()); m_wireframe2D_shader.setUniform("u_modelViewProjectionMatrix", ada::getOrthoMatrix()); m_cross_vbo->render(&m_wireframe2D_shader); glLineWidth(1.0f); // TRACK_END("cursor") } // TRACK_END("renderUI") } void Sandbox::renderDone() { // TRACK_BEGIN("update") // RECORD if (m_record_sec || m_record_frame) { onScreenshot( ada::toString(m_record_counter, 0, 5, '0') + ".png"); m_record_counter++; if (m_record_sec) { m_record_sec_head += m_record_fdelta; if (m_record_sec_head >= m_record_sec_end) m_record_sec = false; } else { m_record_frame_head++; if (m_record_frame_head >= m_record_frame_end) m_record_frame = false; } } // SCREENSHOT else if (screenshotFile != "") { onScreenshot(screenshotFile); screenshotFile = ""; } if (m_histogram) onHistogram(); unflagChange(); // if (!m_initialized) { m_initialized = true; ada::updateViewport(); flagChange(); } else { m_frame++; } // TRACK_END("update") } // ------------------------------------------------------------------------- ACTIONS void Sandbox::clear() { uniforms.clear(); if (geom_index != -1) m_scene.clear(); if (m_billboard_vbo) delete m_billboard_vbo; if (m_cross_vbo) delete m_cross_vbo; } void Sandbox::recordSecs(float _start, float _end, float fps) { m_record_fdelta = 1.0/fps; m_record_counter = 0; m_record_sec_start = _start; m_record_sec_head = _start; m_record_sec_end = _end; m_record_sec = true; } void Sandbox::recordFrames(int _start, int _end, float fps) { m_record_fdelta = 1.0/fps; m_record_counter = 0; m_record_frame_start = _start; m_record_frame_head = _start; m_record_frame_end = _end; m_record_frame = true; } void Sandbox::printDependencies(ShaderType _type) const { if (_type == FRAGMENT) { for (size_t i = 0; i < m_frag_dependencies.size(); i++) { std::cout << m_frag_dependencies[i] << std::endl; } } else { for (size_t i = 0; i < m_vert_dependencies.size(); i++) { std::cout << m_vert_dependencies[i] << std::endl; } } } // ------------------------------------------------------------------------- EVENTS void Sandbox::onFileChange(WatchFileList &_files, int index) { FileType type = _files[index].type; std::string filename = _files[index].path; // IF the change is on a dependency file, re route to the correct shader that need to be reload if (type == GLSL_DEPENDENCY) { if (std::find(m_frag_dependencies.begin(), m_frag_dependencies.end(), filename) != m_frag_dependencies.end()) { type = FRAG_SHADER; filename = _files[frag_index].path; } else if(std::find(m_vert_dependencies.begin(), m_vert_dependencies.end(), filename) != m_vert_dependencies.end()) { type = VERT_SHADER; filename = _files[vert_index].path; } } if (type == FRAG_SHADER) { m_frag_source = ""; m_frag_dependencies.clear(); if ( ada::loadSrcFrom(filename, &m_frag_source, include_folders, &m_frag_dependencies) ) reloadShaders(_files); } else if (type == VERT_SHADER) { m_vert_source = ""; m_vert_dependencies.clear(); if ( ada::loadSrcFrom(filename, &m_vert_source, include_folders, &m_vert_dependencies) ) reloadShaders(_files); } else if (type == GEOMETRY) { // TODO } else if (type == IMAGE) { for (TextureList::iterator it = uniforms.textures.begin(); it!=uniforms.textures.end(); it++) { if (filename == it->second->getFilePath()) { std::cout << filename << std::endl; it->second->load(filename, _files[index].vFlip); break; } } } else if (type == CUBEMAP) { if (uniforms.cubemap) uniforms.cubemap->load(filename, _files[index].vFlip); } flagChange(); } void Sandbox::onScroll(float _yoffset) { // Vertical scroll button zooms u_view2d and view3d. /* zoomfactor 2^(1/4): 4 scroll wheel clicks to double in size. */ constexpr float zoomfactor = 1.1892; if (_yoffset != 0) { float z = pow(zoomfactor, _yoffset); // zoom view2d glm::vec2 zoom = glm::vec2(z,z); glm::vec2 origin = {ada::getWindowWidth()/2, ada::getWindowHeight()/2}; m_view2d = glm::translate(m_view2d, origin); m_view2d = glm::scale(m_view2d, zoom); m_view2d = glm::translate(m_view2d, -origin); flagChange(); } } void Sandbox::onMouseDrag(float _x, float _y, int _button) { if (holoplay < 0) { // If it's not playing on the HOLOPLAY // produce continue draging like blender // float x = _x; float y = _y; if (x <= 0) x = ada::getWindowWidth(); else if (x > ada::getWindowWidth()) x = 0; if (y <= 0) y = ada::getWindowHeight() - 2; else if (y >= ada::getWindowHeight()) y = 2; if (x != _x || y != _y) ada::setMousePosition(x, y); } if (_button == 1) { // Left-button drag is used to pan u_view2d. m_view2d = glm::translate(m_view2d, -ada::getMouseVelocity()); // Left-button drag is used to rotate geometry. float dist = uniforms.getCamera().getDistance(); float vel_x = ada::getMouseVelX(); float vel_y = ada::getMouseVelY(); if (fabs(vel_x) < 50.0 && fabs(vel_y) < 50.0) { m_lat -= vel_x; m_lon -= vel_y * 0.5; uniforms.getCamera().orbit(m_lat, m_lon, dist); uniforms.getCamera().lookAt(glm::vec3(0.0)); } } else { // Right-button drag is used to zoom geometry. float dist = uniforms.getCamera().getDistance(); dist += (-.008f * ada::getMouseVelY()); if (dist > 0.0f) { uniforms.getCamera().orbit(m_lat, m_lon, dist); uniforms.getCamera().lookAt(glm::vec3(0.0)); } } } void Sandbox::onViewportResize(int _newWidth, int _newHeight) { uniforms.getCamera().setViewport(_newWidth, _newHeight); for (size_t i = 0; i < uniforms.buffers.size(); i++) if (!uniforms.buffers[i].fixed) uniforms.buffers[i].allocate(_newWidth, _newHeight, ada::COLOR_TEXTURE); if (m_convolution_pyramid_fbos.size() > 0) { for (size_t i = 0; i < uniforms.convolution_pyramids.size(); i++) { m_convolution_pyramid_fbos[i].allocate(_newWidth, _newHeight, ada::COLOR_TEXTURE); uniforms.convolution_pyramids[i].allocate(ada::getWindowWidth(), ada::getWindowHeight()); } } if (m_postprocessing || m_histogram) _updateSceneBuffer(_newWidth, _newHeight); if (screenshotFile != "" || m_record_sec || m_record_frame) m_record_fbo.allocate(_newWidth, _newHeight, ada::COLOR_TEXTURE_DEPTH_BUFFER); flagChange(); } void Sandbox::onScreenshot(std::string _file) { if (_file != "" && ada::isGL()) { // TRACK_BEGIN("screenshot") glBindFramebuffer(GL_FRAMEBUFFER, m_record_fbo.getId()); if (ada::getExt(_file) == "hdr") { float* pixels = new float[ada::getWindowWidth() * ada::getWindowHeight()*4]; glReadPixels(0, 0, ada::getWindowWidth(), ada::getWindowHeight(), GL_RGBA, GL_FLOAT, pixels); ada::savePixelsHDR(_file, pixels, ada::getWindowWidth(), ada::getWindowHeight()); } else { int width = ada::getWindowWidth(); int height = ada::getWindowHeight(); #ifdef SUPPORT_MULTITHREAD_RECORDING auto pixels = std::unique_ptr<unsigned char[]>(new unsigned char [width * height * 4]); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.get()); /** Just a small helper that captures all the relevant data to save an image **/ class Job { std::string m_file_name; int m_width; int m_height; std::unique_ptr<unsigned char[]> m_pixels; std::atomic<int> * m_task_count; std::atomic<long long> * m_max_mem_in_queue; long mem_consumed_by_pixels() const { return m_width * m_height * 4; } /** the function that is being invoked when the task is done **/ public: void operator()() { if (m_pixels) { ada::savePixels(m_file_name, m_pixels.get(), m_width, m_height); m_pixels = nullptr; (*m_task_count)--; (*m_max_mem_in_queue) += mem_consumed_by_pixels(); } } Job (const Job& ) = delete; Job (Job && ) = default; Job(std::string file_name, int width, int height, std::unique_ptr<unsigned char[]>&& pixels, std::atomic<int>& task_count, std::atomic<long long>& max_mem_in_queue): m_file_name(std::move(file_name)), m_width(width), m_height(height), m_pixels(std::move(pixels)), m_task_count(&task_count), m_max_mem_in_queue(&max_mem_in_queue) { if (m_pixels) { task_count++; max_mem_in_queue -= mem_consumed_by_pixels(); } } }; std::shared_ptr<Job> saverPtr = std::make_shared<Job>(std::move(_file), width, height, std::move(pixels), m_task_count, m_max_mem_in_queue); /** In the case that we render faster than we can safe frames, more and more frames * have to be stored temporary in the save queue. That means that more and more ram is used. * If to much is memory is used, we save the current frame directly to prevent that the system * is running out of memory. Otherwise we put the frame in to the thread queue, so that we can utilize * multilple cpu cores */ if (m_max_mem_in_queue <= 0) { Job& saver = *saverPtr; saver(); } else { auto func = [saverPtr]() { Job& saver = *saverPtr; saver(); }; m_save_threads.Submit(std::move(func)); } #else unsigned char* pixels = new unsigned char[width * height*4]; glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); ada::savePixels(_file, pixels, width, height); delete[] pixels; #endif } if (!m_record_sec && !m_record_frame) { std::cout << "// Screenshot saved to " << _file << std::endl; std::cout << "// > "; } glBindFramebuffer(GL_FRAMEBUFFER, 0); // TRACK_END("screenshot") } } void Sandbox::onHistogram() { if ( ada::isGL() && haveChange() ) { // TRACK_BEGIN("histogram") // Extract pixels glBindFramebuffer(GL_FRAMEBUFFER, m_scene_fbo.getId()); int w = ada::getWindowWidth(); int h = ada::getWindowHeight(); int c = 4; int total = w * h * c; unsigned char* pixels = new unsigned char[total]; glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Count frequencies of appearances float max_rgb_freq = 0; float max_luma_freq = 0; glm::vec4 freqs[256]; for (int i = 0; i < total; i += c) { freqs[pixels[i]].r++; if (freqs[pixels[i]].r > max_rgb_freq) max_rgb_freq = freqs[pixels[i]].r; freqs[pixels[i+1]].g++; if (freqs[pixels[i+1]].g > max_rgb_freq) max_rgb_freq = freqs[pixels[i+1]].g; freqs[pixels[i+2]].b++; if (freqs[pixels[i+2]].b > max_rgb_freq) max_rgb_freq = freqs[pixels[i+2]].b; int luma = 0.299 * pixels[i] + 0.587 * pixels[i+1] + 0.114 * pixels[i+2]; freqs[luma].a++; if (freqs[luma].a > max_luma_freq) max_luma_freq = freqs[luma].a; } delete[] pixels; // Normalize frequencies for (int i = 0; i < 255; i ++) freqs[i] = freqs[i] / glm::vec4(max_rgb_freq, max_rgb_freq, max_rgb_freq, max_luma_freq); if (m_histogram_texture == nullptr) m_histogram_texture = new ada::Texture(); m_histogram_texture->load(256, 1, 4, 32, &freqs[0]); uniforms.textures["u_sceneHistogram"] = m_histogram_texture; // TRACK_END("histogram") } }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 by EMC Corporation, All Rights Reserved /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is EMC Corporation /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #ifndef IRESEARCH_DOCUMENT_GENERATOR_H #define IRESEARCH_DOCUMENT_GENERATOR_H #include "analysis/analyzer.hpp" #include "analysis/token_streams.hpp" #include "utils/iterator.hpp" #include "utils/utf8_path.hpp" #include "store/store_utils.hpp" #include "index/index_writer.hpp" #include <fstream> #include <atomic> #include <functional> namespace iresearch { struct data_output; class token_stream; } // namespace iresearch { namespace tests { ////////////////////////////////////////////////////////////////////////////// /// @class ifield /// @brief base interface for all fields ////////////////////////////////////////////////////////////////////////////// struct ifield { using ptr = std::shared_ptr<ifield>; virtual ~ifield() = default; virtual irs::features_t features() const = 0; virtual irs::IndexFeatures index_features() const = 0; virtual irs::token_stream& get_tokens() const = 0; virtual irs::string_ref name() const = 0; virtual bool write(irs::data_output& out) const = 0; }; // ifield ////////////////////////////////////////////////////////////////////////////// /// @class field /// @brief base class for field implementations ////////////////////////////////////////////////////////////////////////////// class field_base : public ifield { public: field_base() = default; field_base(field_base&& rhs) noexcept; field_base& operator=(field_base&& rhs) noexcept; field_base(const field_base&) = default; field_base& operator=(const field_base&) = default; virtual irs::features_t features() const noexcept override { return { features_.data(), features_.size() }; } virtual irs::IndexFeatures index_features() const noexcept override { return index_features_; } virtual irs::string_ref name() const noexcept override { return name_; } void name(std::string name) noexcept { name_ = std::move(name); } std::vector<irs::type_info::type_id> features_; std::string name_; irs::IndexFeatures index_features_{irs::IndexFeatures::NONE}; }; // field_base ////////////////////////////////////////////////////////////////////////////// /// @class long_field /// @brief provides capabilities for storing & indexing int64_t values ////////////////////////////////////////////////////////////////////////////// class long_field: public field_base { public: typedef int64_t value_t; long_field() = default; irs::token_stream& get_tokens() const override; void value(value_t value) { value_ = value; } value_t value() const { return value_; } bool write(irs::data_output& out) const override; private: mutable irs::numeric_token_stream stream_; int64_t value_{}; }; // long_field ////////////////////////////////////////////////////////////////////////////// /// @class long_field /// @brief provides capabilities for storing & indexing int32_t values ////////////////////////////////////////////////////////////////////////////// class int_field : public field_base { public: typedef int32_t value_t; int_field() : stream_(std::make_shared<irs::numeric_token_stream>()) { } int_field(int_field&& other) = default; irs::token_stream& get_tokens() const override; void value(value_t value) { value_ = value; } value_t value() const { return value_; } bool write(irs::data_output& out) const override; private: mutable std::shared_ptr<irs::numeric_token_stream> stream_; int32_t value_{}; }; // int_field ////////////////////////////////////////////////////////////////////////////// /// @class long_field /// @brief provides capabilities for storing & indexing double_t values ////////////////////////////////////////////////////////////////////////////// class double_field: public field_base { public: typedef double_t value_t; double_field() = default; irs::token_stream& get_tokens() const override; void value(value_t value) { value_ = value; } value_t value() const { return value_; } bool write(irs::data_output& out) const override; private: mutable irs::numeric_token_stream stream_; double_t value_{}; }; // double_field ////////////////////////////////////////////////////////////////////////////// /// @class long_field /// @brief provides capabilities for storing & indexing double_t values ////////////////////////////////////////////////////////////////////////////// class float_field: public field_base { public: typedef float_t value_t; float_field() = default; irs::token_stream& get_tokens() const override; void value(value_t value) { value_ = value; } value_t value() const { return value_; } bool write(irs::data_output& out) const override; private: mutable irs::numeric_token_stream stream_; float_t value_{}; }; // float_field ////////////////////////////////////////////////////////////////////////////// /// @class binary_field /// @brief provides capabilities for storing & indexing binary values ////////////////////////////////////////////////////////////////////////////// class binary_field: public field_base { public: binary_field() = default; irs::token_stream& get_tokens() const override; const irs::bstring& value() const { return value_; } void value(const irs::bytes_ref& value) { value_ = value; } void value(irs::bstring&& value) { value_ = std::move(value); } template<typename Iterator> void value(Iterator first, Iterator last) { value_ = bytes(first, last); } bool write(irs::data_output& out) const override; private: mutable irs::string_token_stream stream_; irs::bstring value_; }; // binary_field /* ------------------------------------------------------------------- * document * ------------------------------------------------------------------*/ class particle: irs::util::noncopyable { public: typedef std::vector<ifield::ptr> fields_t; typedef irs::ptr_iterator<fields_t::const_iterator> const_iterator; typedef irs::ptr_iterator<fields_t::iterator> iterator; particle() = default; particle(particle&& rhs) noexcept; particle& operator=(particle&& rhs) noexcept; virtual ~particle() = default; size_t size() const { return fields_.size(); } void clear() { fields_.clear(); } void reserve(size_t size) { fields_.reserve(size); } void push_back(const ifield::ptr& fld) { fields_.emplace_back(fld); } ifield& back() const { return *fields_.back(); } bool contains(const irs::string_ref& name) const; std::vector<ifield::ptr> find(const irs::string_ref& name) const; template<typename T> T& back() const { typedef typename std::enable_if< std::is_base_of<tests::ifield, T>::value, T >::type type; return static_cast<type&>(*fields_.back()); } ifield* get(const irs::string_ref& name) const; template<typename T> T& get(size_t i) const { typedef typename std::enable_if< std::is_base_of<tests::ifield, T>::value, T >::type type; return static_cast<type&>(*fields_[i]); } template<typename T> T* get(const irs::string_ref& name) const { typedef typename std::enable_if< std::is_base_of<tests::ifield, T>::value, T >::type type; return static_cast<type*>(get(name)); } void remove(const irs::string_ref& name); iterator begin() { return iterator(fields_.begin()); } iterator end() { return iterator(fields_.end()); } const_iterator begin() const { return const_iterator(fields_.begin()); } const_iterator end() const { return const_iterator(fields_.end()); } protected: fields_t fields_; }; // particle struct document: irs::util::noncopyable { document() = default; document(document&& rhs) noexcept; virtual ~document() = default; void insert(const ifield::ptr& field, bool indexed = true, bool stored = true) { if (indexed) this->indexed.push_back(field); if (stored) this->stored.push_back(field); } void reserve(size_t size) { indexed.reserve(size); stored.reserve(size); } void clear() { indexed.clear(); stored.clear(); } particle indexed; particle stored; ifield::ptr sorted; }; // document /* ------------------------------------------------------------------- * GENERATORS * ------------------------------------------------------------------*/ /* Base class for document generators */ struct doc_generator_base { using ptr = std::unique_ptr<doc_generator_base>; virtual const tests::document* next() = 0; virtual void reset() = 0; virtual ~doc_generator_base() = default; }; class limiting_doc_generator : public doc_generator_base { public: limiting_doc_generator(doc_generator_base& gen, size_t offset, size_t limit) : gen_(&gen), begin_(offset), end_(offset + limit) { } virtual const tests::document* next() override { while (pos_ < begin_) { if (!gen_->next()) { // exhausted pos_ = end_; return nullptr; } ++pos_; } if (pos_ < end_) { auto* doc = gen_->next(); if (!doc) { // exhausted pos_ = end_; return nullptr; } ++pos_; return doc; } return nullptr; } virtual void reset() override { pos_ = 0; gen_->reset(); } private: doc_generator_base* gen_; size_t pos_{0}; const size_t begin_; const size_t end_; }; /* Generates documents from UTF-8 encoded file * with strings of the following format: * <title>;<date>:<body> */ class delim_doc_generator : public doc_generator_base { public: struct doc_template : document { virtual void init() = 0; virtual void value(size_t idx, const std::string& value) = 0; virtual void end() {} virtual void reset() {} }; // doc_template delim_doc_generator( const irs::utf8_path& file, doc_template& doc, uint32_t delim = 0x0009); virtual const tests::document* next() override; virtual void reset() override; private: std::string str_; std::ifstream ifs_; doc_template* doc_; uint32_t delim_; }; // delim_doc_generator // Generates documents from a CSV file class csv_doc_generator: public doc_generator_base { public: struct doc_template: document { virtual void init() = 0; virtual void value(size_t idx, const irs::string_ref& value) = 0; virtual void end() {} virtual void reset() {} }; // doc_template csv_doc_generator(const irs::utf8_path& file, doc_template& doc); virtual const tests::document* next() override; virtual void reset() override; bool skip(); // skip a single document, return if anything was skiped, false == EOF private: doc_template& doc_; std::ifstream ifs_; std::string line_; irs::analysis::analyzer::ptr stream_; }; /* Generates documents from json file based on type of JSON value */ class json_doc_generator: public doc_generator_base { public: enum class ValueType { NIL, BOOL, INT, UINT, INT64, UINT64, DBL, STRING, RAWNUM }; // ValueType // an irs::string_ref for union inclusion without a user-defined constructor // and non-trivial default constructor for compatibility with MSVC 2013 struct json_string { const char* data; size_t size; json_string& operator=(const irs::string_ref& ref) { data = ref.c_str(); size = ref.size(); return *this; } operator irs::string_ref() const { return irs::string_ref(data, size); } operator std::string() const { return std::string(data, size); } }; struct json_value { union { bool b; int i; unsigned ui; int64_t i64; uint64_t ui64; double_t dbl; json_string str; }; ValueType vt{ ValueType::NIL }; json_value() noexcept { } bool is_bool() const noexcept { return ValueType::BOOL == vt; } bool is_null() const noexcept { return ValueType::NIL == vt; } bool is_string() const noexcept { return ValueType::STRING == vt; } bool is_number() const noexcept { return ValueType::INT == vt || ValueType::INT64 == vt || ValueType::UINT == vt || ValueType::UINT64 == vt || ValueType::DBL == vt; } template<typename T> T as_number() const noexcept { assert(is_number()); switch (vt) { case ValueType::NIL: break; case ValueType::BOOL: break; case ValueType::INT: return static_cast<T>(i); case ValueType::UINT: return static_cast<T>(ui); case ValueType::INT64: return static_cast<T>(i64); case ValueType::UINT64: return static_cast<T>(ui64); case ValueType::DBL: return static_cast<T>(dbl); case ValueType::STRING: break; case ValueType::RAWNUM: break; } assert(false); return T(0.); } }; // json_value typedef std::function<void( tests::document&, const std::string&, const json_value& )> factory_f; json_doc_generator( const irs::utf8_path& file, const factory_f& factory ); json_doc_generator( const char* data, const factory_f& factory ); json_doc_generator(json_doc_generator&& rhs) noexcept; virtual const tests::document* next() override; virtual void reset() override; private: json_doc_generator(const json_doc_generator&) = delete; std::vector<document> docs_; std::vector<document>::const_iterator prev_; std::vector<document>::const_iterator next_; }; // json_doc_generator template<typename Indexed> bool insert( irs::index_writer& writer, Indexed ibegin, Indexed iend) { auto ctx = writer.documents(); auto doc = ctx.insert(); return doc.insert<irs::Action::INDEX>(ibegin, iend); } template<typename Indexed, typename Stored> bool insert( irs::index_writer& writer, Indexed ibegin, Indexed iend, Stored sbegin, Stored send) { auto ctx = writer.documents(); auto doc = ctx.insert(); return doc.insert<irs::Action::INDEX>(ibegin, iend) && doc.insert<irs::Action::STORE>(sbegin, send); } template<typename Indexed, typename Stored, typename Sorted> bool insert( irs::index_writer& writer, Indexed ibegin, Indexed iend, Stored sbegin, Stored send, Sorted sorted = nullptr) { auto ctx = writer.documents(); auto doc = ctx.insert(); if (sorted && !doc.insert<irs::Action::STORE_SORTED>(*sorted)) { return false; } return doc.insert<irs::Action::INDEX>(ibegin, iend) && doc.insert<irs::Action::STORE>(sbegin, send); } template<typename Indexed> bool update( irs::index_writer& writer, const irs::filter& filter, Indexed ibegin, Indexed iend) { auto ctx = writer.documents(); auto doc = ctx.replace(filter); return doc.insert<irs::Action::INDEX>(ibegin, iend); } template<typename Indexed, typename Stored> bool update( irs::index_writer& writer, const irs::filter& filter, Indexed ibegin, Indexed iend, Stored sbegin, Stored send) { auto ctx = writer.documents(); auto doc = ctx.replace(filter); return doc.insert<irs::Action::INDEX>(ibegin, iend) && doc.insert<irs::Action::STORE>(sbegin, send); } template<typename Indexed> bool update( irs::index_writer& writer, irs::filter::ptr&& filter, Indexed ibegin, Indexed iend) { auto ctx = writer.documents(); auto doc = ctx.replace(std::move(filter)); return doc.insert<irs::Action::INDEX>(ibegin, iend); } template<typename Indexed, typename Stored> bool update( irs::index_writer& writer, irs::filter::ptr&& filter, Indexed ibegin, Indexed iend, Stored sbegin, Stored send) { auto ctx = writer.documents(); auto doc = ctx.replace(std::move(filter)); return doc.insert<irs::Action::INDEX>(ibegin, iend) && doc.insert<irs::Action::STORE>(sbegin, send); } template<typename Indexed> bool update( irs::index_writer& writer, const std::shared_ptr<irs::filter>& filter, Indexed ibegin, Indexed iend) { auto ctx = writer.documents(); auto doc = ctx.replace(filter); return doc.insert<irs::Action::INDEX>(ibegin, iend); } template<typename Indexed, typename Stored> bool update( irs::index_writer& writer, const std::shared_ptr<irs::filter>& filter, Indexed ibegin, Indexed iend, Stored sbegin, Stored send) { auto ctx = writer.documents(); auto doc = ctx.replace(filter); return doc.insert<irs::Action::INDEX>(ibegin, iend) && doc.insert<irs::Action::STORE>(sbegin, send); } } // tests #endif
/* * AbstractResourceStream.hpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement * with RStudio, then this program is licensed to you under the following terms: * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include <api/stream/AbstractResourceStream.hpp> namespace rstudio { namespace launcher_plugins { namespace api { typedef std::shared_ptr<AbstractResourceStream> SharedThis; typedef std::weak_ptr<AbstractResourceStream> WeakThis; struct AbstractResourceStream::Impl { bool hasData() const { return LastData.CpuPercent || LastData.CpuSeconds || LastData.ResidentMem || LastData.VirtualMem; } bool IsComplete = false; ResourceUtilData LastData; }; PRIVATE_IMPL_DELETER_IMPL(AbstractResourceStream); AbstractResourceStream::AbstractResourceStream( const ConstJobPtr& in_job, comms::AbstractLauncherCommunicatorPtr in_launcherCommunicator) : AbstractMultiStream(in_launcherCommunicator), m_job(in_job), m_resBaseImpl(new Impl()) { } void AbstractResourceStream::addRequest(uint64_t in_requestId, const system::User&) { LOCK_MUTEX(m_mutex) { onAddRequest(in_requestId); if (m_resBaseImpl->hasData() || m_resBaseImpl->IsComplete) sendResponse({ in_requestId } , m_resBaseImpl->LastData, m_resBaseImpl->IsComplete); } END_LOCK_MUTEX } void AbstractResourceStream::setStreamComplete() { LOCK_MUTEX(m_mutex) { if (!m_resBaseImpl->IsComplete) sendResponse(ResourceUtilData(), m_resBaseImpl->IsComplete = true); } END_LOCK_MUTEX } void AbstractResourceStream::reportData(const ResourceUtilData& in_data) { LOCK_MUTEX(m_mutex) { if (!m_resBaseImpl->IsComplete) sendResponse(in_data, m_resBaseImpl->IsComplete); } END_LOCK_MUTEX } void AbstractResourceStream::reportError(const Error& in_error) { LOCK_MUTEX(m_mutex) { if (!m_resBaseImpl->IsComplete) { Error error = in_error; error.addProperty("Job ID", m_job->Id); logging::logError(error, ERROR_LOCATION); sendResponse(ResourceUtilData(), m_resBaseImpl->IsComplete = true); } } END_LOCK_MUTEX } } // namespace api } // namespace launcher_plugins } // namespace rstudio
/* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ // First include (the generated) my_config.h, to get correct platform defines, // then gtest.h (before any other MySQL headers), to avoid min() macros etc ... #include "my_config.h" #include <gtest/gtest.h> #include <gmock/gmock.h> #include "mock_field_timestamp.h" #include "fake_table.h" #include "test_utils.h" #include "sql_data_change.h" namespace copy_info_unittest { using my_testing::Server_initializer; using my_testing::Mock_error_handler; using ::testing::StrictMock; using ::testing::_; /* Tests for the functionality of the COPY_INFO class. We test all public interfaces, and some of the protected parts: - COPY_INFO::get_function_default_columns, and - COPY_INFO::get_cached_bitmap */ class CopyInfoTest : public ::testing::Test { protected: virtual void SetUp() { initializer.SetUp(); } virtual void TearDown() { initializer.TearDown(); } Server_initializer initializer; }; /** This is a simple mock Field class, which verifies that store_timestamp is called. We inherit Field_long, but the data type does not matter. */ class Mock_field : public Field_long { uchar null_byte; public: Mock_field(utype unireg) : Field_long(NULL, 0, &null_byte, 0, unireg, "", false, false) {} MOCK_METHOD1(store_timestamp, void(const timeval*)); }; /* Compares two COPY_INFO::Statistics and makes sure they are equal. */ void check_equality(const COPY_INFO::Statistics a, const COPY_INFO::Statistics b) { EXPECT_EQ(a.records, b.records); EXPECT_EQ(a.deleted, b.deleted); EXPECT_EQ(a.updated, b.updated); EXPECT_EQ(a.copied, b.copied); EXPECT_EQ(a.error_count, b.error_count); EXPECT_EQ(a.touched, b.touched); } /* Convenience class for creating a COPY_INFO to represent an insert operation. */ class Mock_COPY_INFO: public COPY_INFO { public: Mock_COPY_INFO(operation_type optype, List<Item> *inserted_columns, enum_duplicates duplicate_handling) : COPY_INFO(optype, inserted_columns, true, // manage_defaults duplicate_handling) {} // Import protected member functions, so we can test them. using COPY_INFO::get_function_default_columns; using COPY_INFO::get_cached_bitmap; }; /* Convenience class for creating a COPY_INFO to represent an insert operation. */ class Mock_COPY_INFO_insert : public COPY_INFO { public: Mock_COPY_INFO_insert() : COPY_INFO(COPY_INFO::INSERT_OPERATION, static_cast<List<Item>*>(NULL), true, // manage_defaults DUP_UPDATE) {} Mock_COPY_INFO_insert(List<Item> *fields) : COPY_INFO(COPY_INFO::INSERT_OPERATION, fields, true, // manage_defaults DUP_UPDATE) {} // Import protected member functions, so we can test them. using COPY_INFO::get_function_default_columns; using COPY_INFO::get_cached_bitmap; }; /* Convenience class for creating a COPY_INFO to represent an update operation. */ class Mock_COPY_INFO_update : public COPY_INFO { public: Mock_COPY_INFO_update() : COPY_INFO(COPY_INFO::UPDATE_OPERATION, NULL, NULL) {} // Import protected member functions, so we can test them. using COPY_INFO::get_function_default_columns; using COPY_INFO::get_cached_bitmap; }; /* Tests that constuctors initialize the stats object properly. */ TEST_F(CopyInfoTest, constructors) { List<Item> inserted_columns; COPY_INFO insert(COPY_INFO::INSERT_OPERATION, &inserted_columns, true, // manage_defaults DUP_UPDATE); EXPECT_EQ(0U, insert.stats.records); EXPECT_EQ(0U, insert.stats.deleted); EXPECT_EQ(0U, insert.stats.updated); EXPECT_EQ(0U, insert.stats.copied); EXPECT_EQ(0U, insert.stats.error_count); EXPECT_EQ(0U, insert.stats.touched); List<Item> columns; List<Item> values; COPY_INFO update(COPY_INFO::UPDATE_OPERATION, &columns, &values); EXPECT_EQ(0U, update.stats.records); EXPECT_EQ(0U, update.stats.deleted); EXPECT_EQ(0U, update.stats.updated); EXPECT_EQ(0U, update.stats.copied); EXPECT_EQ(0U, update.stats.error_count); EXPECT_EQ(0U, update.stats.touched); } /* Tests the accessors when the COPY_INFO represents an insert operation. */ TEST_F(CopyInfoTest, insertAccessors) { List<Item> inserted_columns; COPY_INFO insert(COPY_INFO::INSERT_OPERATION, &inserted_columns, true, // manage_defaults DUP_REPLACE); EXPECT_EQ(COPY_INFO::INSERT_OPERATION, insert.get_operation_type()); EXPECT_EQ(&inserted_columns, insert.get_changed_columns()); EXPECT_EQ(static_cast<List<Item>*>(NULL), insert.get_changed_columns2()); EXPECT_TRUE(insert.get_manage_defaults()); EXPECT_EQ(DUP_REPLACE, insert.get_duplicate_handling()); } /* Tests the accessors when the COPY_INFO represents a load data infile operation. */ TEST_F(CopyInfoTest, loadDataAccessors) { List<Item> inserted_columns; List<Item> inserted_columns2; COPY_INFO load_data(COPY_INFO::INSERT_OPERATION, &inserted_columns, &inserted_columns2, true, // manage_defaults DUP_UPDATE, 123); EXPECT_EQ(COPY_INFO::INSERT_OPERATION, load_data.get_operation_type()); EXPECT_EQ(&inserted_columns, load_data.get_changed_columns()); EXPECT_EQ(&inserted_columns2, load_data.get_changed_columns2()); EXPECT_TRUE(load_data.get_manage_defaults()); EXPECT_EQ(DUP_UPDATE, load_data.get_duplicate_handling()); } /* Tests the accessors when the COPY_INFO represents an update operation. */ TEST_F(CopyInfoTest, updateAccessors) { List<Item> columns; List<Item> values; COPY_INFO update(COPY_INFO::UPDATE_OPERATION, &columns, &values); EXPECT_EQ(COPY_INFO::UPDATE_OPERATION, update.get_operation_type()); EXPECT_EQ(&columns, update.get_changed_columns()); EXPECT_EQ(static_cast<List<Item>*>(NULL), update.get_changed_columns2()); EXPECT_TRUE(update.get_manage_defaults()); EXPECT_EQ(DUP_ERROR, update.get_duplicate_handling()); } Field_long make_field() { static uchar unused_null_byte; Field_long a(NULL, 0, &unused_null_byte, 0, Field::TIMESTAMP_DN_FIELD, "a", false, false); return a; } /* Test of the lazy instantiation performed by get_function_default_columns(). - The bitmap pointer is initially NULL. - That calling get_function_default_columns() indeed points the member to a lazily instantiated bitmap. - That on a second call to get_function_default_columns(), a new bitmap is not allocated. We repeat the test for insert and update operations. */ TEST_F(CopyInfoTest, getFunctionDefaultColumns) { Mock_COPY_INFO_insert insert; Mock_COPY_INFO_update update; Field_long a= make_field(); Fake_TABLE table(&a); MY_BITMAP *initial_value= NULL; EXPECT_EQ(initial_value, insert.get_cached_bitmap()); insert.get_function_default_columns(&table); EXPECT_NE(initial_value, insert.get_cached_bitmap()) << "The output parameter must be set!"; const MY_BITMAP *function_default_columns= insert.get_cached_bitmap(); insert.get_function_default_columns(&table); EXPECT_EQ(function_default_columns, insert.get_cached_bitmap()) << "Not supposed to allocate a new bitmap on second call."; EXPECT_EQ(initial_value, update.get_cached_bitmap()); update.get_function_default_columns(&table); EXPECT_NE(initial_value, update.get_cached_bitmap()) << "The output parameter must be set!"; function_default_columns= update.get_cached_bitmap(); update.get_function_default_columns(&table); EXPECT_EQ(function_default_columns, update.get_cached_bitmap()) << "Not supposed to allocate a new bitmap on second call."; } /* Here we test that calling COPY_INFO::set_function_defaults() indeed causes store_timestamp to be called on the columns that are not on the list of assigned_columns. We seize the opportunity to test COPY_INFO::function_defaults_apply() since we have to call it anyways in order for set_function_defaults() not to assert. */ TEST_F(CopyInfoTest, setFunctionDefaults) { StrictMock<Mock_field> a(Field::TIMESTAMP_UN_FIELD); StrictMock<Mock_field> b(Field::TIMESTAMP_DNUN_FIELD); StrictMock<Mock_field> c(Field::TIMESTAMP_DNUN_FIELD); EXPECT_TRUE(a.has_update_default_function()); EXPECT_TRUE(b.has_update_default_function()); EXPECT_TRUE(c.has_update_default_function()); Fake_TABLE table(&a, &b, &c); List<Item> assigned_columns; assigned_columns.push_front(new Item_field(&a)); Mock_COPY_INFO insert(COPY_INFO::INSERT_OPERATION, &assigned_columns, DUP_ERROR); ASSERT_FALSE(insert.get_function_default_columns(&table)) << "Out of memory"; insert.ignore_last_columns(&table, 1); // 'c' insert.add_function_default_columns(&table, table.write_set); EXPECT_FALSE(bitmap_is_set(table.write_set, 0)); EXPECT_TRUE (bitmap_is_set(table.write_set, 1)); EXPECT_FALSE(bitmap_is_set(table.write_set, 2)); EXPECT_TRUE(insert.function_defaults_apply(&table)) << "They do apply"; // We expect store_timestamp() to be called for b and not for c. // We do not care about the argument to store_timestamp(). EXPECT_CALL(b, store_timestamp(_)).Times(1); EXPECT_CALL(c, store_timestamp(_)).Times(0); insert.set_function_defaults(&table); } }
/** * @file talker.cpp * @brief Publisher node that emits a simple string with a counter. * @author Ryan Cunningham * @copyright 2019 * Distributed under the BSD License (license terms found in LICENSE or at https://www.freebsd.org/copyright/freebsd-license.html) */ #include <sstream> #include "ros/ros.h" #include "std_msgs/String.h" #include "tf/transform_broadcaster.h" #include "set_msg_service.hpp" /** * This tutorial demonstrates simple sending of messages over the ROS system. */ int main(int argc, char **argv) { try { ROS_INFO_STREAM("Talker started"); /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command * line. For programmatic remappings you can use a different version of init() * which takes remappings directly, but for most command-line programs, * passing argc and argv is the easiest way to do it. The third argument to * init() is the name of the node. * * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "talker"); /// create transformation to broadcast tf::Transform transform; /// set translation transform.setOrigin(tf::Vector3(1.0, 0.0, 0.0)); /// set rotation tf::Quaternion q; q.setRPY(0, 0, 0.35); transform.setRotation(q); /// initialize tf broadcaster with created transformation tf::TransformBroadcaster br; /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the * last NodeHandle destructed will close down the node. */ ros::NodeHandle n; SetMsgService setMsgService("Ryan Cunningham's custom message"); /** * The advertiseService() function tells ROS about the service. Service * requests are passed to a callback function which processes the request and * forms the response. The callback in this case is a function of a class. */ ros::ServiceServer server = n.advertiseService("set_msg", &SetMsgService::setMsg, &setMsgService); /** * The advertise() function is how you tell ROS that you want to publish on a * given topic name. This invokes a call to the ROS master node, which keeps a * registry of who is publishing and who is subscribing. After this * advertise() call is made, the master node will notify anyone who is trying * to subscribe to this topic name, and they will in turn negotiate a * peer-to-peer connection with this node. advertise() returns a Publisher * object which allows you to publish messages on that topic through a call to * publish(). Once all copies of the returned Publisher object are destroyed, * the topic will be automatically unadvertised. * * The second parameter to advertise() is the size of the message queue used * for publishing messages. If messages are published more quickly than we * can send them, the number here specifies how many messages to buffer up * before throwing some away. */ ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); double rate = 1.0; /// create separate nodehandle for talker to get arguments from launch file ros::NodeHandle talkerNH("~"); /// get the rate parameter from the command line, if it was provided double rateParam; if (talkerNH.getParam("rate", rateParam)) { ROS_DEBUG_STREAM("/talker/rate param value: [" << rateParam << "]"); /// check to make sure the rate parameter passed in is greater than 0 if (rateParam <= 0) { ROS_ERROR_STREAM("Rate must be greater than 0! Using default rate of " << rate); } else { /// set the provided rate parameter to the rate rate = rateParam; } } ros::Rate loop_rate(rate); /** * A count of how many messages we have sent. This is used to create a unique * string for each message. */ int count = 0; while (ros::ok()) { /// broadcast a transform with parent "world" br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", "talk")); /** * This is a message object. You stuff it with data, and then publish it. */ std_msgs::String msg; std::stringstream ss; ss << setMsgService.getMsg() << " " << count; msg.data = ss.str(); ROS_INFO_STREAM("I published: [" << msg.data.c_str() << "]"); /** * The publish() function is how you send messages. The parameter is the * message object. The type of this object must agree with the type given * as a template parameter to the advertise<>() call, as was done in the * constructor above. */ chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++count; } } catch(...) { ROS_FATAL_STREAM("beginner_tutorials publisher encountered fatal exception!"); } return 0; }