keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerInternal.h
.h
5,518
183
//===- FuzzerInternal.h - Internal header for the Fuzzer --------*- C++ -* ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Define the main class fuzzer::Fuzzer and most functions. //===----------------------------------------------------------------------===// #ifndef LLVM_FUZZER_INTERNAL_H #define LLVM_FUZZER_INTERNAL_H #include "FuzzerDefs.h" #include "FuzzerExtFunctions.h" #include "FuzzerInterface.h" #include "FuzzerOptions.h" #include "FuzzerSHA1.h" #include "FuzzerValueBitMap.h" #include <algorithm> #include <atomic> #include <chrono> #include <climits> #include <cstdlib> #include <string.h> namespace fuzzer { using namespace std::chrono; class Fuzzer { public: // Aggregates all available coverage measurements. struct Coverage { Coverage() { Reset(); } void Reset() { BlockCoverage = 0; CallerCalleeCoverage = 0; CounterBitmapBits = 0; CounterBitmap.clear(); VPMap.Reset(); } size_t BlockCoverage; size_t CallerCalleeCoverage; // Precalculated number of bits in CounterBitmap. size_t CounterBitmapBits; std::vector<uint8_t> CounterBitmap; ValueBitMap VPMap; }; Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD, FuzzingOptions Options); ~Fuzzer(); void Loop(); void MinimizeCrashLoop(const Unit &U); void ShuffleAndMinimize(UnitVector *V); void InitializeTraceState(); void RereadOutputCorpus(size_t MaxSize); size_t secondsSinceProcessStartUp() { return duration_cast<seconds>(system_clock::now() - ProcessStartTime) .count(); } bool TimedOut() { return Options.MaxTotalTimeSec > 0 && secondsSinceProcessStartUp() > static_cast<size_t>(Options.MaxTotalTimeSec); } size_t execPerSec() { size_t Seconds = secondsSinceProcessStartUp(); return Seconds ? TotalNumberOfRuns / Seconds : 0; } size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; } static void StaticAlarmCallback(); static void StaticCrashSignalCallback(); static void StaticInterruptCallback(); void ExecuteCallback(const uint8_t *Data, size_t Size); size_t RunOne(const uint8_t *Data, size_t Size); // Merge Corpora[1:] into Corpora[0]. void Merge(const std::vector<std::string> &Corpora); void CrashResistantMerge(const std::vector<std::string> &Args, const std::vector<std::string> &Corpora); void CrashResistantMergeInternalStep(const std::string &ControlFilePath); // Returns a subset of 'Extra' that adds coverage to 'Initial'. UnitVector FindExtraUnits(const UnitVector &Initial, const UnitVector &Extra); MutationDispatcher &GetMD() { return MD; } void PrintFinalStats(); void SetMaxInputLen(size_t MaxInputLen); void SetMaxMutationLen(size_t MaxMutationLen); void RssLimitCallback(); // Public for tests. void ResetCoverage(); bool InFuzzingThread() const { return IsMyThread; } size_t GetCurrentUnitInFuzzingThead(const uint8_t **Data) const; void TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size, bool DuringInitialCorpusExecution); void HandleMalloc(size_t Size); private: void AlarmCallback(); void CrashCallback(); void InterruptCallback(); void MutateAndTestOne(); void ReportNewCoverage(InputInfo *II, const Unit &U); size_t RunOne(const Unit &U) { return RunOne(U.data(), U.size()); } void WriteToOutputCorpus(const Unit &U); void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix); void PrintStats(const char *Where, const char *End = "\n", size_t Units = 0); void PrintStatusForNewUnit(const Unit &U); void ShuffleCorpus(UnitVector *V); void AddToCorpus(const Unit &U); void CheckExitOnSrcPosOrItem(); // Trace-based fuzzing: we run a unit with some kind of tracing // enabled and record potentially useful mutations. Then // We apply these mutations one by one to the unit and run it again. // Start tracing; forget all previously proposed mutations. void StartTraceRecording(); // Stop tracing. void StopTraceRecording(); void SetDeathCallback(); static void StaticDeathCallback(); void DumpCurrentUnit(const char *Prefix); void DeathCallback(); void ResetEdgeCoverage(); void ResetCounters(); void PrepareCounters(Fuzzer::Coverage *C); bool RecordMaxCoverage(Fuzzer::Coverage *C); void AllocateCurrentUnitData(); uint8_t *CurrentUnitData = nullptr; std::atomic<size_t> CurrentUnitSize; uint8_t BaseSha1[kSHA1NumBytes]; // Checksum of the base unit. bool RunningCB = false; size_t TotalNumberOfRuns = 0; size_t NumberOfNewUnitsAdded = 0; bool HasMoreMallocsThanFrees = false; size_t NumberOfLeakDetectionAttempts = 0; UserCallback CB; InputCorpus &Corpus; MutationDispatcher &MD; FuzzingOptions Options; system_clock::time_point ProcessStartTime = system_clock::now(); system_clock::time_point UnitStartTime, UnitStopTime; long TimeOfLongestUnitInSeconds = 0; long EpochOfLastReadOfOutputCorpus = 0; // Maximum recorded coverage. Coverage MaxCoverage; size_t MaxInputLen = 0; size_t MaxMutationLen = 0; // Need to know our own thread. static thread_local bool IsMyThread; bool InMergeMode = false; }; }; // namespace fuzzer #endif // LLVM_FUZZER_INTERNAL_H
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerMutate.h
.h
6,033
146
//===- FuzzerMutate.h - Internal header for the Fuzzer ----------*- C++ -* ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // fuzzer::MutationDispatcher //===----------------------------------------------------------------------===// #ifndef LLVM_FUZZER_MUTATE_H #define LLVM_FUZZER_MUTATE_H #include "FuzzerDefs.h" #include "FuzzerDictionary.h" #include "FuzzerRandom.h" namespace fuzzer { class MutationDispatcher { public: MutationDispatcher(Random &Rand, const FuzzingOptions &Options); ~MutationDispatcher() {} /// Indicate that we are about to start a new sequence of mutations. void StartMutationSequence(); /// Print the current sequence of mutations. void PrintMutationSequence(); /// Indicate that the current sequence of mutations was successfull. void RecordSuccessfulMutationSequence(); /// Mutates data by invoking user-provided mutator. size_t Mutate_Custom(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by invoking user-provided crossover. size_t Mutate_CustomCrossOver(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by shuffling bytes. size_t Mutate_ShuffleBytes(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by erasing bytes. size_t Mutate_EraseBytes(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by inserting a byte. size_t Mutate_InsertByte(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by inserting several repeated bytes. size_t Mutate_InsertRepeatedBytes(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by chanding one byte. size_t Mutate_ChangeByte(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by chanding one bit. size_t Mutate_ChangeBit(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by copying/inserting a part of data into a different place. size_t Mutate_CopyPart(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by adding a word from the manual dictionary. size_t Mutate_AddWordFromManualDictionary(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by adding a word from the temporary automatic dictionary. size_t Mutate_AddWordFromTemporaryAutoDictionary(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by adding a word from the TORC. size_t Mutate_AddWordFromTORC(uint8_t *Data, size_t Size, size_t MaxSize); /// Mutates data by adding a word from the persistent automatic dictionary. size_t Mutate_AddWordFromPersistentAutoDictionary(uint8_t *Data, size_t Size, size_t MaxSize); /// Tries to find an ASCII integer in Data, changes it to another ASCII int. size_t Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size, size_t MaxSize); /// Change a 1-, 2-, 4-, or 8-byte integer in interesting ways. size_t Mutate_ChangeBinaryInteger(uint8_t *Data, size_t Size, size_t MaxSize); /// CrossOver Data with some other element of the corpus. size_t Mutate_CrossOver(uint8_t *Data, size_t Size, size_t MaxSize); /// Applies one of the configured mutations. /// Returns the new size of data which could be up to MaxSize. size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize); /// Applies one of the default mutations. Provided as a service /// to mutation authors. size_t DefaultMutate(uint8_t *Data, size_t Size, size_t MaxSize); /// Creates a cross-over of two pieces of Data, returns its size. size_t CrossOver(const uint8_t *Data1, size_t Size1, const uint8_t *Data2, size_t Size2, uint8_t *Out, size_t MaxOutSize); void AddWordToManualDictionary(const Word &W); void AddWordToAutoDictionary(DictionaryEntry DE); void ClearAutoDictionary(); void PrintRecommendedDictionary(); void SetCorpus(const InputCorpus *Corpus) { this->Corpus = Corpus; } Random &GetRand() { return Rand; } private: struct Mutator { size_t (MutationDispatcher::*Fn)(uint8_t *Data, size_t Size, size_t Max); const char *Name; }; size_t AddWordFromDictionary(Dictionary &D, uint8_t *Data, size_t Size, size_t MaxSize); size_t MutateImpl(uint8_t *Data, size_t Size, size_t MaxSize, const std::vector<Mutator> &Mutators); size_t InsertPartOf(const uint8_t *From, size_t FromSize, uint8_t *To, size_t ToSize, size_t MaxToSize); size_t CopyPartOf(const uint8_t *From, size_t FromSize, uint8_t *To, size_t ToSize); size_t ApplyDictionaryEntry(uint8_t *Data, size_t Size, size_t MaxSize, DictionaryEntry &DE); template <class T> DictionaryEntry MakeDictionaryEntryFromCMP(T Arg1, T Arg2, const uint8_t *Data, size_t Size); Random &Rand; const FuzzingOptions &Options; // Dictionary provided by the user via -dict=DICT_FILE. Dictionary ManualDictionary; // Temporary dictionary modified by the fuzzer itself, // recreated periodically. Dictionary TempAutoDictionary; // Persistent dictionary modified by the fuzzer, consists of // entries that led to successfull discoveries in the past mutations. Dictionary PersistentAutoDictionary; std::vector<Mutator> CurrentMutatorSequence; std::vector<DictionaryEntry *> CurrentDictionaryEntrySequence; static const size_t kCmpDictionaryEntriesDequeSize = 16; DictionaryEntry CmpDictionaryEntriesDeque[kCmpDictionaryEntriesDequeSize]; size_t CmpDictionaryEntriesDequeIdx = 0; const InputCorpus *Corpus = nullptr; std::vector<uint8_t> MutateInPlaceHere; std::vector<Mutator> Mutators; std::vector<Mutator> DefaultMutators; }; } // namespace fuzzer #endif // LLVM_FUZZER_MUTATE_H
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerSHA1.h
.h
950
34
//===- FuzzerSHA1.h - Internal header for the SHA1 utils --------*- C++ -* ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // SHA1 utils. //===----------------------------------------------------------------------===// #ifndef LLVM_FUZZER_SHA1_H #define LLVM_FUZZER_SHA1_H #include "FuzzerDefs.h" #include <cstddef> #include <stdint.h> namespace fuzzer { // Private copy of SHA1 implementation. static const int kSHA1NumBytes = 20; // Computes SHA1 hash of 'Len' bytes in 'Data', writes kSHA1NumBytes to 'Out'. void ComputeSHA1(const uint8_t *Data, size_t Len, uint8_t *Out); std::string Sha1ToString(const uint8_t Sha1[kSHA1NumBytes]); std::string Hash(const Unit &U); } // namespace fuzzer #endif // LLVM_FUZZER_SHA1_H
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerTracePC.cpp
.cpp
12,124
340
//===- FuzzerTracePC.cpp - PC tracing--------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Trace PCs. // This module implements __sanitizer_cov_trace_pc_guard[_init], // the callback required for -fsanitize-coverage=trace-pc-guard instrumentation. // //===----------------------------------------------------------------------===// #include "FuzzerCorpus.h" #include "FuzzerDefs.h" #include "FuzzerDictionary.h" #include "FuzzerExtFunctions.h" #include "FuzzerIO.h" #include "FuzzerTracePC.h" #include "FuzzerValueBitMap.h" #include <map> #include <sanitizer/coverage_interface.h> #include <set> #include <sstream> namespace fuzzer { TracePC TPC; void TracePC::HandleTrace(uint32_t *Guard, uintptr_t PC) { uint32_t Idx = *Guard; if (!Idx) return; PCs[Idx % kNumPCs] = PC; Counters[Idx % kNumCounters]++; } size_t TracePC::GetTotalPCCoverage() { size_t Res = 0; for (size_t i = 1; i < GetNumPCs(); i++) if (PCs[i]) Res++; return Res; } void TracePC::HandleInit(uint32_t *Start, uint32_t *Stop) { if (Start == Stop || *Start) return; assert(NumModules < sizeof(Modules) / sizeof(Modules[0])); for (uint32_t *P = Start; P < Stop; P++) *P = ++NumGuards; Modules[NumModules].Start = Start; Modules[NumModules].Stop = Stop; NumModules++; } void TracePC::PrintModuleInfo() { Printf("INFO: Loaded %zd modules (%zd guards): ", NumModules, NumGuards); for (size_t i = 0; i < NumModules; i++) Printf("[%p, %p), ", Modules[i].Start, Modules[i].Stop); Printf("\n"); } void TracePC::HandleCallerCallee(uintptr_t Caller, uintptr_t Callee) { const uintptr_t kBits = 12; const uintptr_t kMask = (1 << kBits) - 1; uintptr_t Idx = (Caller & kMask) | ((Callee & kMask) << kBits); HandleValueProfile(Idx); } static bool IsInterestingCoverageFile(std::string &File) { if (File.find("compiler-rt/lib/") != std::string::npos) return false; // sanitizer internal. if (File.find("/usr/lib/") != std::string::npos) return false; if (File.find("/usr/include/") != std::string::npos) return false; if (File == "<null>") return false; return true; } void TracePC::PrintNewPCs() { if (DoPrintNewPCs) { if (!PrintedPCs) PrintedPCs = new std::set<uintptr_t>; for (size_t i = 1; i < GetNumPCs(); i++) if (PCs[i] && PrintedPCs->insert(PCs[i]).second) PrintPC("\tNEW_PC: %p %F %L\n", "\tNEW_PC: %p\n", PCs[i]); } } void TracePC::PrintCoverage() { if (!EF->__sanitizer_symbolize_pc || !EF->__sanitizer_get_module_and_offset_for_pc) { Printf("INFO: __sanitizer_symbolize_pc or " "__sanitizer_get_module_and_offset_for_pc is not available," " not printing coverage\n"); return; } std::map<std::string, std::vector<uintptr_t>> CoveredPCsPerModule; std::map<std::string, uintptr_t> ModuleOffsets; std::set<std::string> CoveredDirs, CoveredFiles, CoveredFunctions, CoveredLines; Printf("COVERAGE:\n"); for (size_t i = 1; i < GetNumPCs(); i++) { if (!PCs[i]) continue; std::string FileStr = DescribePC("%s", PCs[i]); if (!IsInterestingCoverageFile(FileStr)) continue; std::string FixedPCStr = DescribePC("%p", PCs[i]); std::string FunctionStr = DescribePC("%F", PCs[i]); std::string LineStr = DescribePC("%l", PCs[i]); char ModulePathRaw[4096] = ""; // What's PATH_MAX in portable C++? void *OffsetRaw = nullptr; if (!EF->__sanitizer_get_module_and_offset_for_pc( reinterpret_cast<void *>(PCs[i]), ModulePathRaw, sizeof(ModulePathRaw), &OffsetRaw)) continue; std::string Module = ModulePathRaw; uintptr_t FixedPC = std::stol(FixedPCStr, 0, 16); uintptr_t PcOffset = reinterpret_cast<uintptr_t>(OffsetRaw); ModuleOffsets[Module] = FixedPC - PcOffset; CoveredPCsPerModule[Module].push_back(PcOffset); CoveredFunctions.insert(FunctionStr); CoveredFiles.insert(FileStr); CoveredDirs.insert(DirName(FileStr)); if (!CoveredLines.insert(FileStr + ":" + LineStr).second) continue; Printf("COVERED: %s %s:%s\n", FunctionStr.c_str(), FileStr.c_str(), LineStr.c_str()); } std::string CoveredDirsStr; for (auto &Dir : CoveredDirs) { if (!CoveredDirsStr.empty()) CoveredDirsStr += ","; CoveredDirsStr += Dir; } Printf("COVERED_DIRS: %s\n", CoveredDirsStr.c_str()); for (auto &M : CoveredPCsPerModule) { std::set<std::string> UncoveredFiles, UncoveredFunctions; std::map<std::string, std::set<int> > UncoveredLines; // Func+File => lines auto &ModuleName = M.first; auto &CoveredOffsets = M.second; uintptr_t ModuleOffset = ModuleOffsets[ModuleName]; std::sort(CoveredOffsets.begin(), CoveredOffsets.end()); Printf("MODULE_WITH_COVERAGE: %s\n", ModuleName.c_str()); // sancov does not yet fully support DSOs. // std::string Cmd = "sancov -print-coverage-pcs " + ModuleName; std::string Cmd = "objdump -d " + ModuleName + " | grep 'call.*__sanitizer_cov_trace_pc_guard' | awk -F: '{print $1}'"; std::string SanCovOutput; if (!ExecuteCommandAndReadOutput(Cmd, &SanCovOutput)) { Printf("INFO: Command failed: %s\n", Cmd.c_str()); continue; } std::istringstream ISS(SanCovOutput); std::string S; while (std::getline(ISS, S, '\n')) { uintptr_t PcOffset = std::stol(S, 0, 16); if (!std::binary_search(CoveredOffsets.begin(), CoveredOffsets.end(), PcOffset)) { uintptr_t PC = ModuleOffset + PcOffset; auto FileStr = DescribePC("%s", PC); if (!IsInterestingCoverageFile(FileStr)) continue; if (CoveredFiles.count(FileStr) == 0) { UncoveredFiles.insert(FileStr); continue; } auto FunctionStr = DescribePC("%F", PC); if (CoveredFunctions.count(FunctionStr) == 0) { UncoveredFunctions.insert(FunctionStr); continue; } std::string LineStr = DescribePC("%l", PC); uintptr_t Line = std::stoi(LineStr); std::string FileLineStr = FileStr + ":" + LineStr; if (CoveredLines.count(FileLineStr) == 0) UncoveredLines[FunctionStr + " " + FileStr].insert(Line); } } for (auto &FileLine: UncoveredLines) for (int Line : FileLine.second) Printf("UNCOVERED_LINE: %s:%d\n", FileLine.first.c_str(), Line); for (auto &Func : UncoveredFunctions) Printf("UNCOVERED_FUNC: %s\n", Func.c_str()); for (auto &File : UncoveredFiles) Printf("UNCOVERED_FILE: %s\n", File.c_str()); } } void TracePC::DumpCoverage() { __sanitizer_dump_coverage(PCs, GetNumPCs()); } // Value profile. // We keep track of various values that affect control flow. // These values are inserted into a bit-set-based hash map. // Every new bit in the map is treated as a new coverage. // // For memcmp/strcmp/etc the interesting value is the length of the common // prefix of the parameters. // For cmp instructions the interesting value is a XOR of the parameters. // The interesting value is mixed up with the PC and is then added to the map. ATTRIBUTE_NO_SANITIZE_MEMORY void TracePC::AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2, size_t n) { if (!n) return; size_t Len = std::min(n, (size_t)32); const uint8_t *A1 = reinterpret_cast<const uint8_t *>(s1); const uint8_t *A2 = reinterpret_cast<const uint8_t *>(s2); size_t I = 0; for (; I < Len; I++) if (A1[I] != A2[I]) break; size_t PC = reinterpret_cast<size_t>(caller_pc); size_t Idx = I; // if (I < Len) // Idx += __builtin_popcountl((A1[I] ^ A2[I])) - 1; TPC.HandleValueProfile((PC & 4095) | (Idx << 12)); } ATTRIBUTE_NO_SANITIZE_MEMORY void TracePC::AddValueForStrcmp(void *caller_pc, const char *s1, const char *s2, size_t n) { if (!n) return; size_t Len = std::min(n, (size_t)32); const uint8_t *A1 = reinterpret_cast<const uint8_t *>(s1); const uint8_t *A2 = reinterpret_cast<const uint8_t *>(s2); size_t I = 0; for (; I < Len; I++) if (A1[I] != A2[I] || A1[I] == 0) break; size_t PC = reinterpret_cast<size_t>(caller_pc); size_t Idx = I; // if (I < Len && A1[I]) // Idx += __builtin_popcountl((A1[I] ^ A2[I])) - 1; TPC.HandleValueProfile((PC & 4095) | (Idx << 12)); } template <class T> ATTRIBUTE_TARGET_POPCNT #ifdef __clang__ // g++ can't handle this __attribute__ here :( __attribute__((always_inline)) #endif // __clang__ void TracePC::HandleCmp(void *PC, T Arg1, T Arg2) { uintptr_t PCuint = reinterpret_cast<uintptr_t>(PC); uint64_t ArgXor = Arg1 ^ Arg2; uint64_t ArgDistance = __builtin_popcountl(ArgXor) + 1; // [1,65] uintptr_t Idx = ((PCuint & 4095) + 1) * ArgDistance; if (sizeof(T) == 4) TORC4.Insert(ArgXor, Arg1, Arg2); else if (sizeof(T) == 8) TORC8.Insert(ArgXor, Arg1, Arg2); HandleValueProfile(Idx); } } // namespace fuzzer extern "C" { __attribute__((visibility("default"))) void __sanitizer_cov_trace_pc_guard(uint32_t *Guard) { uintptr_t PC = (uintptr_t)__builtin_return_address(0); fuzzer::TPC.HandleTrace(Guard, PC); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_pc_guard_init(uint32_t *Start, uint32_t *Stop) { fuzzer::TPC.HandleInit(Start, Stop); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_pc_indir(uintptr_t Callee) { uintptr_t PC = (uintptr_t)__builtin_return_address(0); fuzzer::TPC.HandleCallerCallee(PC, Callee); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_cmp8(uint64_t Arg1, uint64_t Arg2) { fuzzer::TPC.HandleCmp(__builtin_return_address(0), Arg1, Arg2); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_cmp4(uint32_t Arg1, uint32_t Arg2) { fuzzer::TPC.HandleCmp(__builtin_return_address(0), Arg1, Arg2); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_cmp2(uint16_t Arg1, uint16_t Arg2) { fuzzer::TPC.HandleCmp(__builtin_return_address(0), Arg1, Arg2); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_cmp1(uint8_t Arg1, uint8_t Arg2) { fuzzer::TPC.HandleCmp(__builtin_return_address(0), Arg1, Arg2); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases) { // Updates the value profile based on the relative position of Val and Cases. // We want to handle one random case at every call (handling all is slow). // Since none of the arguments contain any random bits we use a thread-local // counter to choose the random case to handle. static thread_local size_t Counter; Counter++; uint64_t N = Cases[0]; uint64_t *Vals = Cases + 2; char *PC = (char*)__builtin_return_address(0); // We need a random number < N using Counter as a seed. But w/o DIV. // * find a power of two >= N // * mask Counter with this power of two. // * maybe subtract N. size_t Nlog = sizeof(long) * 8 - __builtin_clzl((long)N); size_t PowerOfTwoGeN = 1U << Nlog; assert(PowerOfTwoGeN >= N); size_t Idx = Counter & (PowerOfTwoGeN - 1); if (Idx >= N) Idx -= N; assert(Idx < N); uint64_t TwoIn32 = 1ULL << 32; if ((Val | Vals[Idx]) < TwoIn32) fuzzer::TPC.HandleCmp(PC + Idx, static_cast<uint32_t>(Val), static_cast<uint32_t>(Vals[Idx])); else fuzzer::TPC.HandleCmp(PC + Idx, Val, Vals[Idx]); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_div4(uint32_t Val) { fuzzer::TPC.HandleCmp(__builtin_return_address(0), Val, (uint32_t)0); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_div8(uint64_t Val) { fuzzer::TPC.HandleCmp(__builtin_return_address(0), Val, (uint64_t)0); } __attribute__((visibility("default"))) void __sanitizer_cov_trace_gep(uintptr_t Idx) { fuzzer::TPC.HandleCmp(__builtin_return_address(0), Idx, (uintptr_t)0); } } // extern "C"
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerDefs.h
.h
2,366
90
//===- FuzzerDefs.h - Internal header for the Fuzzer ------------*- C++ -* ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Basic definitions. //===----------------------------------------------------------------------===// #ifndef LLVM_FUZZER_DEFS_H #define LLVM_FUZZER_DEFS_H #include <cassert> #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include <vector> // Platform detection. #ifdef __linux__ #define LIBFUZZER_APPLE 0 #define LIBFUZZER_LINUX 1 #define LIBFUZZER_WINDOWS 0 #elif __APPLE__ #define LIBFUZZER_APPLE 1 #define LIBFUZZER_LINUX 0 #define LIBFUZZER_WINDOWS 0 #elif _WIN32 #define LIBFUZZER_APPLE 0 #define LIBFUZZER_LINUX 0 #define LIBFUZZER_WINDOWS 1 #else #error "Support for your platform has not been implemented" #endif #define LIBFUZZER_POSIX LIBFUZZER_APPLE || LIBFUZZER_LINUX #ifdef __x86_64 #define ATTRIBUTE_TARGET_POPCNT __attribute__((target("popcnt"))) #else #define ATTRIBUTE_TARGET_POPCNT #endif #ifdef __clang__ // avoid gcc warning. # define ATTRIBUTE_NO_SANITIZE_MEMORY __attribute__((no_sanitize("memory"))) #else # define ATTRIBUTE_NO_SANITIZE_MEMORY #endif namespace fuzzer { template <class T> T Min(T a, T b) { return a < b ? a : b; } template <class T> T Max(T a, T b) { return a > b ? a : b; } class Random; class Dictionary; class DictionaryEntry; class MutationDispatcher; struct FuzzingOptions; class InputCorpus; struct InputInfo; struct ExternalFunctions; // Global interface to functions that may or may not be available. extern ExternalFunctions *EF; typedef std::vector<uint8_t> Unit; typedef std::vector<Unit> UnitVector; typedef int (*UserCallback)(const uint8_t *Data, size_t Size); int FuzzerDriver(int *argc, char ***argv, UserCallback Callback); struct ScopedDoingMyOwnMemmem { ScopedDoingMyOwnMemmem(); ~ScopedDoingMyOwnMemmem(); }; inline uint8_t Bswap(uint8_t x) { return x; } inline uint16_t Bswap(uint16_t x) { return __builtin_bswap16(x); } inline uint32_t Bswap(uint32_t x) { return __builtin_bswap32(x); } inline uint64_t Bswap(uint64_t x) { return __builtin_bswap64(x); } } // namespace fuzzer #endif // LLVM_FUZZER_DEFS_H
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerExtFunctionsDlsym.cpp
.cpp
1,639
53
//===- FuzzerExtFunctionsDlsym.cpp - Interface to external functions ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Implementation for operating systems that support dlsym(). We only use it on // Apple platforms for now. We don't use this approach on Linux because it // requires that clients of LibFuzzer pass ``--export-dynamic`` to the linker. // That is a complication we don't wish to expose to clients right now. //===----------------------------------------------------------------------===// #include "FuzzerDefs.h" #if LIBFUZZER_APPLE #include "FuzzerExtFunctions.h" #include "FuzzerIO.h" #include <dlfcn.h> using namespace fuzzer; template <typename T> static T GetFnPtr(const char *FnName, bool WarnIfMissing) { dlerror(); // Clear any previous errors. void *Fn = dlsym(RTLD_DEFAULT, FnName); if (Fn == nullptr) { if (WarnIfMissing) { const char *ErrorMsg = dlerror(); Printf("WARNING: Failed to find function \"%s\".", FnName); if (ErrorMsg) Printf(" Reason %s.", ErrorMsg); Printf("\n"); } } return reinterpret_cast<T>(Fn); } namespace fuzzer { ExternalFunctions::ExternalFunctions() { #define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \ this->NAME = GetFnPtr<decltype(ExternalFunctions::NAME)>(#NAME, WARN) #include "FuzzerExtFunctions.def" #undef EXT_FUNC } } // namespace fuzzer #endif // LIBFUZZER_APPLE
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerMerge.cpp
.cpp
8,793
262
//===- FuzzerMerge.cpp - merging corpora ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Merging corpora. //===----------------------------------------------------------------------===// #include "FuzzerInternal.h" #include "FuzzerIO.h" #include "FuzzerMerge.h" #include "FuzzerTracePC.h" #include "FuzzerUtil.h" #include <fstream> #include <iterator> #include <sstream> namespace fuzzer { bool Merger::Parse(const std::string &Str, bool ParseCoverage) { std::istringstream SS(Str); return Parse(SS, ParseCoverage); } void Merger::ParseOrExit(std::istream &IS, bool ParseCoverage) { if (!Parse(IS, ParseCoverage)) { Printf("MERGE: failed to parse the control file (unexpected error)\n"); exit(1); } } // The control file example: // // 3 # The number of inputs // 1 # The number of inputs in the first corpus, <= the previous number // file0 // file1 // file2 # One file name per line. // STARTED 0 123 # FileID, file size // DONE 0 1 4 6 8 # FileID COV1 COV2 ... // STARTED 1 456 # If DONE is missing, the input crashed while processing. // STARTED 2 567 // DONE 2 8 9 bool Merger::Parse(std::istream &IS, bool ParseCoverage) { LastFailure.clear(); std::string Line; // Parse NumFiles. if (!std::getline(IS, Line, '\n')) return false; std::istringstream L1(Line); size_t NumFiles = 0; L1 >> NumFiles; if (NumFiles == 0 || NumFiles > 10000000) return false; // Parse NumFilesInFirstCorpus. if (!std::getline(IS, Line, '\n')) return false; std::istringstream L2(Line); NumFilesInFirstCorpus = NumFiles + 1; L2 >> NumFilesInFirstCorpus; if (NumFilesInFirstCorpus > NumFiles) return false; // Parse file names. Files.resize(NumFiles); for (size_t i = 0; i < NumFiles; i++) if (!std::getline(IS, Files[i].Name, '\n')) return false; // Parse STARTED and DONE lines. size_t ExpectedStartMarker = 0; const size_t kInvalidStartMarker = -1; size_t LastSeenStartMarker = kInvalidStartMarker; while (std::getline(IS, Line, '\n')) { std::istringstream ISS1(Line); std::string Marker; size_t N; ISS1 >> Marker; ISS1 >> N; if (Marker == "STARTED") { // STARTED FILE_ID FILE_SIZE if (ExpectedStartMarker != N) return false; ISS1 >> Files[ExpectedStartMarker].Size; LastSeenStartMarker = ExpectedStartMarker; assert(ExpectedStartMarker < Files.size()); ExpectedStartMarker++; } else if (Marker == "DONE") { // DONE FILE_SIZE COV1 COV2 COV3 ... size_t CurrentFileIdx = N; if (CurrentFileIdx != LastSeenStartMarker) return false; LastSeenStartMarker = kInvalidStartMarker; if (ParseCoverage) { auto &V = Files[CurrentFileIdx].Features; V.clear(); while (ISS1 >> std::hex >> N) V.push_back(N); std::sort(V.begin(), V.end()); } } else { return false; } } if (LastSeenStartMarker != kInvalidStartMarker) LastFailure = Files[LastSeenStartMarker].Name; FirstNotProcessedFile = ExpectedStartMarker; return true; } // Decides which files need to be merged (add thost to NewFiles). // Returns the number of new features added. size_t Merger::Merge(std::vector<std::string> *NewFiles) { NewFiles->clear(); assert(NumFilesInFirstCorpus <= Files.size()); std::set<uint32_t> AllFeatures; // What features are in the initial corpus? for (size_t i = 0; i < NumFilesInFirstCorpus; i++) { auto &Cur = Files[i].Features; AllFeatures.insert(Cur.begin(), Cur.end()); } size_t InitialNumFeatures = AllFeatures.size(); // Remove all features that we already know from all other inputs. for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) { auto &Cur = Files[i].Features; std::vector<uint32_t> Tmp; std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(), AllFeatures.end(), std::inserter(Tmp, Tmp.begin())); Cur.swap(Tmp); } // Sort. Give preference to // * smaller files // * files with more features. std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(), [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool { if (a.Size != b.Size) return a.Size < b.Size; return a.Features.size() > b.Features.size(); }); // One greedy pass: add the file's features to AllFeatures. // If new features were added, add this file to NewFiles. for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) { auto &Cur = Files[i].Features; // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(), // Files[i].Size, Cur.size()); size_t OldSize = AllFeatures.size(); AllFeatures.insert(Cur.begin(), Cur.end()); if (AllFeatures.size() > OldSize) NewFiles->push_back(Files[i].Name); } return AllFeatures.size() - InitialNumFeatures; } // Inner process. May crash if the target crashes. void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) { Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str()); Merger M; std::ifstream IF(CFPath); M.ParseOrExit(IF, false); IF.close(); if (!M.LastFailure.empty()) Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n", M.LastFailure.c_str()); Printf("MERGE-INNER: %zd total files;" " %zd processed earlier; will process %zd files now\n", M.Files.size(), M.FirstNotProcessedFile, M.Files.size() - M.FirstNotProcessedFile); std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app); for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) { auto U = FileToVector(M.Files[i].Name); if (U.size() > MaxInputLen) { U.resize(MaxInputLen); U.shrink_to_fit(); } std::ostringstream StartedLine; // Write the pre-run marker. OF << "STARTED " << std::dec << i << " " << U.size() << "\n"; OF.flush(); // Flush is important since ExecuteCommand may crash. // Run. TPC.ResetMaps(); ExecuteCallback(U.data(), U.size()); // Collect coverage. std::set<size_t> Features; TPC.CollectFeatures([&](size_t Feature) -> bool { Features.insert(Feature); return true; }); // Show stats. TotalNumberOfRuns++; if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1))) PrintStats("pulse "); // Write the post-run marker and the coverage. OF << "DONE " << i; for (size_t F : Features) OF << " " << std::hex << F; OF << "\n"; } } // Outer process. Does not call the target code and thus sohuld not fail. void Fuzzer::CrashResistantMerge(const std::vector<std::string> &Args, const std::vector<std::string> &Corpora) { if (Corpora.size() <= 1) { Printf("Merge requires two or more corpus dirs\n"); return; } std::vector<std::string> AllFiles; ListFilesInDirRecursive(Corpora[0], nullptr, &AllFiles, /*TopDir*/true); size_t NumFilesInFirstCorpus = AllFiles.size(); for (size_t i = 1; i < Corpora.size(); i++) ListFilesInDirRecursive(Corpora[i], nullptr, &AllFiles, /*TopDir*/true); Printf("MERGE-OUTER: %zd files, %zd in the initial corpus\n", AllFiles.size(), NumFilesInFirstCorpus); std::string CFPath = "libFuzzerTemp." + std::to_string(GetPid()) + ".txt"; // Write the control file. RemoveFile(CFPath); std::ofstream ControlFile(CFPath); ControlFile << AllFiles.size() << "\n"; ControlFile << NumFilesInFirstCorpus << "\n"; for (auto &Path: AllFiles) ControlFile << Path << "\n"; ControlFile.close(); // Execute the inner process untill it passes. // Every inner process should execute at least one input. std::string BaseCmd = CloneArgsWithoutX(Args, "keep-all-flags"); for (size_t i = 1; i <= AllFiles.size(); i++) { Printf("MERGE-OUTER: attempt %zd\n", i); auto ExitCode = ExecuteCommand(BaseCmd + " -merge_control_file=" + CFPath); if (!ExitCode) { Printf("MERGE-OUTER: succesfull in %zd attempt(s)\n", i); break; } } // Read the control file and do the merge. Merger M; std::ifstream IF(CFPath); M.ParseOrExit(IF, true); IF.close(); std::vector<std::string> NewFiles; size_t NumNewFeatures = M.Merge(&NewFiles); Printf("MERGE-OUTER: %zd new files with %zd new features added\n", NewFiles.size(), NumNewFeatures); for (auto &F: NewFiles) WriteToOutputCorpus(FileToVector(F)); // We are done, delete the control file. RemoveFile(CFPath); } } // namespace fuzzer
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerCorpus.h
.h
6,788
218
//===- FuzzerCorpus.h - Internal header for the Fuzzer ----------*- C++ -* ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // fuzzer::InputCorpus //===----------------------------------------------------------------------===// #ifndef LLVM_FUZZER_CORPUS #define LLVM_FUZZER_CORPUS #include "FuzzerDefs.h" #include "FuzzerIO.h" #include "FuzzerRandom.h" #include "FuzzerSHA1.h" #include "FuzzerTracePC.h" #include <numeric> #include <random> #include <unordered_set> namespace fuzzer { struct InputInfo { Unit U; // The actual input data. uint8_t Sha1[kSHA1NumBytes]; // Checksum. // Number of features that this input has and no smaller input has. size_t NumFeatures = 0; size_t Tmp = 0; // Used by ValidateFeatureSet. // Stats. size_t NumExecutedMutations = 0; size_t NumSuccessfullMutations = 0; bool MayDeleteFile = false; }; class InputCorpus { public: static const size_t kFeatureSetSize = 1 << 16; InputCorpus(const std::string &OutputCorpus) : OutputCorpus(OutputCorpus) { memset(InputSizesPerFeature, 0, sizeof(InputSizesPerFeature)); memset(SmallestElementPerFeature, 0, sizeof(SmallestElementPerFeature)); } ~InputCorpus() { for (auto II : Inputs) delete II; } size_t size() const { return Inputs.size(); } size_t SizeInBytes() const { size_t Res = 0; for (auto II : Inputs) Res += II->U.size(); return Res; } size_t NumActiveUnits() const { size_t Res = 0; for (auto II : Inputs) Res += !II->U.empty(); return Res; } bool empty() const { return Inputs.empty(); } const Unit &operator[] (size_t Idx) const { return Inputs[Idx]->U; } void AddToCorpus(const Unit &U, size_t NumFeatures, bool MayDeleteFile = false) { assert(!U.empty()); uint8_t Hash[kSHA1NumBytes]; if (FeatureDebug) Printf("ADD_TO_CORPUS %zd NF %zd\n", Inputs.size(), NumFeatures); ComputeSHA1(U.data(), U.size(), Hash); Hashes.insert(Sha1ToString(Hash)); Inputs.push_back(new InputInfo()); InputInfo &II = *Inputs.back(); II.U = U; II.NumFeatures = NumFeatures; II.MayDeleteFile = MayDeleteFile; memcpy(II.Sha1, Hash, kSHA1NumBytes); UpdateCorpusDistribution(); ValidateFeatureSet(); } bool HasUnit(const Unit &U) { return Hashes.count(Hash(U)); } bool HasUnit(const std::string &H) { return Hashes.count(H); } InputInfo &ChooseUnitToMutate(Random &Rand) { InputInfo &II = *Inputs[ChooseUnitIdxToMutate(Rand)]; assert(!II.U.empty()); return II; }; // Returns an index of random unit from the corpus to mutate. // Hypothesis: units added to the corpus last are more likely to be // interesting. This function gives more weight to the more recent units. size_t ChooseUnitIdxToMutate(Random &Rand) { size_t Idx = static_cast<size_t>(CorpusDistribution(Rand.Get_mt19937())); assert(Idx < Inputs.size()); return Idx; } void PrintStats() { for (size_t i = 0; i < Inputs.size(); i++) { const auto &II = *Inputs[i]; Printf(" [%zd %s]\tsz: %zd\truns: %zd\tsucc: %zd\n", i, Sha1ToString(II.Sha1).c_str(), II.U.size(), II.NumExecutedMutations, II.NumSuccessfullMutations); } } void PrintFeatureSet() { for (size_t i = 0; i < kFeatureSetSize; i++) { if(size_t Sz = GetFeature(i)) Printf("[%zd: id %zd sz%zd] ", i, SmallestElementPerFeature[i], Sz); } Printf("\n\t"); for (size_t i = 0; i < Inputs.size(); i++) if (size_t N = Inputs[i]->NumFeatures) Printf(" %zd=>%zd ", i, N); Printf("\n"); } void DeleteInput(size_t Idx) { InputInfo &II = *Inputs[Idx]; if (!OutputCorpus.empty() && II.MayDeleteFile) RemoveFile(DirPlusFile(OutputCorpus, Sha1ToString(II.Sha1))); Unit().swap(II.U); if (FeatureDebug) Printf("EVICTED %zd\n", Idx); } bool AddFeature(size_t Idx, uint32_t NewSize, bool Shrink) { assert(NewSize); Idx = Idx % kFeatureSetSize; uint32_t OldSize = GetFeature(Idx); if (OldSize == 0 || (Shrink && OldSize > NewSize)) { if (OldSize > 0) { size_t OldIdx = SmallestElementPerFeature[Idx]; InputInfo &II = *Inputs[OldIdx]; assert(II.NumFeatures > 0); II.NumFeatures--; if (II.NumFeatures == 0) DeleteInput(OldIdx); } if (FeatureDebug) Printf("ADD FEATURE %zd sz %d\n", Idx, NewSize); SmallestElementPerFeature[Idx] = Inputs.size(); InputSizesPerFeature[Idx] = NewSize; CountingFeatures = true; return true; } return false; } size_t NumFeatures() const { size_t Res = 0; for (size_t i = 0; i < kFeatureSetSize; i++) Res += GetFeature(i) != 0; return Res; } void ResetFeatureSet() { assert(Inputs.empty()); memset(InputSizesPerFeature, 0, sizeof(InputSizesPerFeature)); memset(SmallestElementPerFeature, 0, sizeof(SmallestElementPerFeature)); } private: static const bool FeatureDebug = false; size_t GetFeature(size_t Idx) const { return InputSizesPerFeature[Idx]; } void ValidateFeatureSet() { if (!CountingFeatures) return; if (FeatureDebug) PrintFeatureSet(); for (size_t Idx = 0; Idx < kFeatureSetSize; Idx++) if (GetFeature(Idx)) Inputs[SmallestElementPerFeature[Idx]]->Tmp++; for (auto II: Inputs) { if (II->Tmp != II->NumFeatures) Printf("ZZZ %zd %zd\n", II->Tmp, II->NumFeatures); assert(II->Tmp == II->NumFeatures); II->Tmp = 0; } } // Updates the probability distribution for the units in the corpus. // Must be called whenever the corpus or unit weights are changed. void UpdateCorpusDistribution() { size_t N = Inputs.size(); Intervals.resize(N + 1); Weights.resize(N); std::iota(Intervals.begin(), Intervals.end(), 0); if (CountingFeatures) for (size_t i = 0; i < N; i++) Weights[i] = Inputs[i]->NumFeatures * (i + 1); else std::iota(Weights.begin(), Weights.end(), 1); CorpusDistribution = std::piecewise_constant_distribution<double>( Intervals.begin(), Intervals.end(), Weights.begin()); } std::piecewise_constant_distribution<double> CorpusDistribution; std::vector<double> Intervals; std::vector<double> Weights; std::unordered_set<std::string> Hashes; std::vector<InputInfo*> Inputs; bool CountingFeatures = false; uint32_t InputSizesPerFeature[kFeatureSetSize]; uint32_t SmallestElementPerFeature[kFeatureSetSize]; std::string OutputCorpus; }; } // namespace fuzzer #endif // LLVM_FUZZER_CORPUS
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/FuzzerExtFunctions.h
.h
1,041
36
//===- FuzzerExtFunctions.h - Interface to external functions ---*- C++ -* ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Defines an interface to (possibly optional) functions. //===----------------------------------------------------------------------===// #ifndef LLVM_FUZZER_EXT_FUNCTIONS_H #define LLVM_FUZZER_EXT_FUNCTIONS_H #include <stddef.h> #include <stdint.h> namespace fuzzer { struct ExternalFunctions { // Initialize function pointers. Functions that are not available will be set // to nullptr. Do not call this constructor before ``main()`` has been // entered. ExternalFunctions(); #define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \ RETURN_TYPE(*NAME) FUNC_SIG = nullptr #include "FuzzerExtFunctions.def" #undef EXT_FUNC }; } // namespace fuzzer #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/standalone/StandaloneFuzzTargetMain.c
.c
1,702
42
/*===- StandaloneFuzzTargetMain.c - standalone main() for fuzz targets. ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // This main() function can be linked to a fuzz target (i.e. a library // that exports LLVMFuzzerTestOneInput() and possibly LLVMFuzzerInitialize()) // instead of libFuzzer. This main() function will not perform any fuzzing // but will simply feed all input files one by one to the fuzz target. // // Use this file to provide reproducers for bugs when linking against libFuzzer // or other fuzzing engine is undesirable. //===----------------------------------------------------------------------===*/ #include <assert.h> #include <stdio.h> #include <stdlib.h> extern int LLVMFuzzerTestOneInput(const unsigned char *data, size_t size); __attribute__((weak)) extern int LLVMFuzzerInitialize(int *argc, char ***argv); int main(int argc, char **argv) { fprintf(stderr, "StandaloneFuzzTargetMain: running %d inputs\n", argc - 1); if (LLVMFuzzerInitialize) LLVMFuzzerInitialize(&argc, &argv); for (int i = 1; i < argc; i++) { fprintf(stderr, "Running: %s\n", argv[i]); FILE *f = fopen(argv[i], "r"); assert(f); fseek(f, 0, SEEK_END); size_t len = ftell(f); fseek(f, 0, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(len); size_t n_read = fread(buf, 1, len, f); assert(n_read == len); LLVMFuzzerTestOneInput(buf, len); free(buf); fprintf(stderr, "Done: %s: (%zd bytes)\n", argv[i], n_read); } }
C
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/afl/afl_driver.cpp
.cpp
11,187
296
//===- afl_driver.cpp - a glue between AFL and libFuzzer --------*- C++ -* ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. //===----------------------------------------------------------------------===// /* This file allows to fuzz libFuzzer-style target functions (LLVMFuzzerTestOneInput) with AFL using AFL's persistent (in-process) mode. Usage: ################################################################################ cat << EOF > test_fuzzer.cc #include <stdint.h> #include <stddef.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { if (size > 0 && data[0] == 'H') if (size > 1 && data[1] == 'I') if (size > 2 && data[2] == '!') __builtin_trap(); return 0; } EOF # Build your target with -fsanitize-coverage=trace-pc using fresh clang. clang -g -fsanitize-coverage=trace-pc test_fuzzer.cc -c # Build afl-llvm-rt.o.c from the AFL distribution. clang -c -w $AFL_HOME/llvm_mode/afl-llvm-rt.o.c # Build this file, link it with afl-llvm-rt.o.o and the target code. clang++ afl_driver.cpp test_fuzzer.o afl-llvm-rt.o.o # Run AFL: rm -rf IN OUT; mkdir IN OUT; echo z > IN/z; $AFL_HOME/afl-fuzz -i IN -o OUT ./a.out ################################################################################ Environment Variables: There are a few environment variables that can be set to use features that afl-fuzz doesn't have. AFL_DRIVER_STDERR_DUPLICATE_FILENAME: Setting this *appends* stderr to the file specified. If the file does not exist, it is created. This is useful for getting stack traces (when using ASAN for example) or original error messages on hard to reproduce bugs. AFL_DRIVER_EXTRA_STATS_FILENAME: Setting this causes afl_driver to write extra statistics to the file specified. Currently these are peak_rss_mb (the peak amount of virtual memory used in MB) and slowest_unit_time_secs. If the file does not exist it is created. If the file does exist then afl_driver assumes it was restarted by afl-fuzz and will try to read old statistics from the file. If that fails then the process will quit. */ #include <assert.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <signal.h> #include <sys/resource.h> #include <sys/time.h> // Platform detection. Copied from FuzzerInternal.h #ifdef __linux__ #define LIBFUZZER_LINUX 1 #define LIBFUZZER_APPLE 0 #elif __APPLE__ #define LIBFUZZER_LINUX 0 #define LIBFUZZER_APPLE 1 #else #error "Support for your platform has not been implemented" #endif // Used to avoid repeating error checking boilerplate. If cond is false, a // fatal error has occured in the program. In this event print error_message // to stderr and abort(). Otherwise do nothing. Note that setting // AFL_DRIVER_STDERR_DUPLICATE_FILENAME may cause error_message to be appended // to the file as well, if the error occurs after the duplication is performed. #define CHECK_ERROR(cond, error_message) \ if (!(cond)) { \ fprintf(stderr, (error_message)); \ abort(); \ } // libFuzzer interface is thin, so we don't include any libFuzzer headers. extern "C" { int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size); __attribute__((weak)) int LLVMFuzzerInitialize(int *argc, char ***argv); } // Notify AFL about persistent mode. static volatile char AFL_PERSISTENT[] = "##SIG_AFL_PERSISTENT##"; extern "C" int __afl_persistent_loop(unsigned int); static volatile char suppress_warning2 = AFL_PERSISTENT[0]; // Notify AFL about deferred forkserver. static volatile char AFL_DEFER_FORKSVR[] = "##SIG_AFL_DEFER_FORKSRV##"; extern "C" void __afl_manual_init(); static volatile char suppress_warning1 = AFL_DEFER_FORKSVR[0]; // Input buffer. static const size_t kMaxAflInputSize = 1 << 20; static uint8_t AflInputBuf[kMaxAflInputSize]; // Variables we need for writing to the extra stats file. static FILE *extra_stats_file = NULL; static uint32_t previous_peak_rss = 0; static time_t slowest_unit_time_secs = 0; static const int kNumExtraStats = 2; static const char *kExtraStatsFormatString = "peak_rss_mb : %u\n" "slowest_unit_time_sec : %u\n"; // Copied from FuzzerUtil.cpp. size_t GetPeakRSSMb() { struct rusage usage; if (getrusage(RUSAGE_SELF, &usage)) return 0; if (LIBFUZZER_LINUX) { // ru_maxrss is in KiB return usage.ru_maxrss >> 10; } else if (LIBFUZZER_APPLE) { // ru_maxrss is in bytes return usage.ru_maxrss >> 20; } assert(0 && "GetPeakRSSMb() is not implemented for your platform"); return 0; } // Based on SetSigaction in FuzzerUtil.cpp static void SetSigaction(int signum, void (*callback)(int, siginfo_t *, void *)) { struct sigaction sigact; memset(&sigact, 0, sizeof(sigact)); sigact.sa_sigaction = callback; if (sigaction(signum, &sigact, 0)) { fprintf(stderr, "libFuzzer: sigaction failed with %d\n", errno); exit(1); } } // Write extra stats to the file specified by the user. If none is specified // this function will never be called. static void write_extra_stats() { uint32_t peak_rss = GetPeakRSSMb(); if (peak_rss < previous_peak_rss) peak_rss = previous_peak_rss; int chars_printed = fprintf(extra_stats_file, kExtraStatsFormatString, peak_rss, slowest_unit_time_secs); CHECK_ERROR(chars_printed != 0, "Failed to write extra_stats_file"); CHECK_ERROR(fclose(extra_stats_file) == 0, "Failed to close extra_stats_file"); } // Call write_extra_stats before we exit. static void crash_handler(int, siginfo_t *, void *) { // Make sure we don't try calling write_extra_stats again if we crashed while // trying to call it. static bool first_crash = true; CHECK_ERROR(first_crash, "Crashed in crash signal handler. This is a bug in the fuzzer."); first_crash = false; write_extra_stats(); } // If the user has specified an extra_stats_file through the environment // variable AFL_DRIVER_EXTRA_STATS_FILENAME, then perform necessary set up // to write stats to it on exit. If no file is specified, do nothing. Otherwise // install signal and exit handlers to write to the file when the process exits. // Then if the file doesn't exist create it and set extra stats to 0. But if it // does exist then read the initial values of the extra stats from the file // and check that the file is writable. static void maybe_initialize_extra_stats() { // If AFL_DRIVER_EXTRA_STATS_FILENAME isn't set then we have nothing to do. char *extra_stats_filename = getenv("AFL_DRIVER_EXTRA_STATS_FILENAME"); if (!extra_stats_filename) return; // Open the file and find the previous peak_rss_mb value. // This is necessary because the fuzzing process is restarted after N // iterations are completed. So we may need to get this value from a previous // process to be accurate. extra_stats_file = fopen(extra_stats_filename, "r"); // If extra_stats_file already exists: read old stats from it. if (extra_stats_file) { int matches = fscanf(extra_stats_file, kExtraStatsFormatString, &previous_peak_rss, &slowest_unit_time_secs); // Make sure we have read a real extra stats file and that we have used it // to set slowest_unit_time_secs and previous_peak_rss. CHECK_ERROR(matches == kNumExtraStats, "Extra stats file is corrupt"); CHECK_ERROR(fclose(extra_stats_file) == 0, "Failed to close file"); // Now open the file for writing. extra_stats_file = fopen(extra_stats_filename, "w"); CHECK_ERROR(extra_stats_file, "Failed to open extra stats file for writing"); } else { // Looks like this is the first time in a fuzzing job this is being called. extra_stats_file = fopen(extra_stats_filename, "w+"); CHECK_ERROR(extra_stats_file, "failed to create extra stats file"); } // Make sure that crash_handler gets called on any kind of fatal error. int crash_signals[] = {SIGSEGV, SIGBUS, SIGABRT, SIGILL, SIGFPE, SIGINT, SIGTERM}; const size_t num_signals = sizeof(crash_signals) / sizeof(crash_signals[0]); for (size_t idx = 0; idx < num_signals; idx++) SetSigaction(crash_signals[idx], crash_handler); // Make sure it gets called on other kinds of exits. atexit(write_extra_stats); } // If the user asks us to duplicate stderr, then do it. static void maybe_duplicate_stderr() { char* stderr_duplicate_filename = getenv("AFL_DRIVER_STDERR_DUPLICATE_FILENAME"); if (!stderr_duplicate_filename) return; FILE* stderr_duplicate_stream = freopen(stderr_duplicate_filename, "a+", stderr); if (!stderr_duplicate_stream) { fprintf( stderr, "Failed to duplicate stderr to AFL_DRIVER_STDERR_DUPLICATE_FILENAME"); abort(); } } int main(int argc, char **argv) { fprintf(stderr, "======================= INFO =========================\n" "This binary is built for AFL-fuzz.\n" "To run the target function on a single input execute this:\n" " %s < INPUT_FILE\n" "To run the fuzzing execute this:\n" " afl-fuzz [afl-flags] %s [N] " "-- run N fuzzing iterations before " "re-spawning the process (default: 1000)\n" "======================================================\n", argv[0], argv[0]); if (LLVMFuzzerInitialize) LLVMFuzzerInitialize(&argc, &argv); // Do any other expensive one-time initialization here. maybe_duplicate_stderr(); maybe_initialize_extra_stats(); __afl_manual_init(); int N = 1000; if (argc >= 2) N = atoi(argv[1]); assert(N > 0); time_t unit_time_secs; int num_runs = 0; while (__afl_persistent_loop(N)) { ssize_t n_read = read(0, AflInputBuf, kMaxAflInputSize); if (n_read > 0) { // Copy AflInputBuf into a separate buffer to let asan find buffer // overflows. Don't use unique_ptr/etc to avoid extra dependencies. uint8_t *copy = new uint8_t[n_read]; memcpy(copy, AflInputBuf, n_read); struct timeval unit_start_time; CHECK_ERROR(gettimeofday(&unit_start_time, NULL) == 0, "Calling gettimeofday failed"); num_runs++; LLVMFuzzerTestOneInput(copy, n_read); struct timeval unit_stop_time; CHECK_ERROR(gettimeofday(&unit_stop_time, NULL) == 0, "Calling gettimeofday failed"); // Update slowest_unit_time_secs if we see a new max. unit_time_secs = unit_stop_time.tv_sec - unit_start_time.tv_sec; if (slowest_unit_time_secs < unit_time_secs) slowest_unit_time_secs = unit_time_secs; delete[] copy; } } fprintf(stderr, "%s: successfully executed %d input(s)\n", argv[0], num_runs); }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SimpleCmpTest.cpp
.cpp
1,329
47
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find several narrow ranges. #include <cstdint> #include <cstdlib> #include <cstring> #include <cstdio> extern int AllLines[]; bool PrintOnce(int Line) { if (!AllLines[Line]) fprintf(stderr, "Seen line %d\n", Line); AllLines[Line] = 1; return true; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size != 22) return 0; uint64_t x = 0; int64_t y = 0; int32_t z = 0; uint16_t a = 0; memcpy(&x, Data, 8); // 8 memcpy(&y, Data + 8, 8); // 16 memcpy(&z, Data + 16, sizeof(z)); // 20 memcpy(&a, Data + 20, sizeof(a)); // 22 if (x > 1234567890 && PrintOnce(__LINE__) && x < 1234567895 && PrintOnce(__LINE__) && a == 0x4242 && PrintOnce(__LINE__) && y >= 987654321 && PrintOnce(__LINE__) && y <= 987654325 && PrintOnce(__LINE__) && z < -10000 && PrintOnce(__LINE__) && z >= -10005 && PrintOnce(__LINE__) && z != -10003 && PrintOnce(__LINE__) && true) { fprintf(stderr, "BINGO; Found the target: size %zd (%zd, %zd, %d, %d), exiting.\n", Size, x, y, z, a); exit(1); } return 0; } int AllLines[__LINE__ + 1]; // Must be the last line.
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/NthRunCrashTest.cpp
.cpp
415
19
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Crash on the N-th execution. #include <cstdint> #include <cstddef> #include <iostream> static int Counter; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Counter++ == 1000) { std::cout << "BINGO; Found the target, exiting\n"; exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SwapCmpTest.cpp
.cpp
844
35
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // The fuzzer must find several constants with swapped bytes. #include <cstdint> #include <cstdlib> #include <cstring> #include <cstdio> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 14) return 0; uint64_t x = 0; uint32_t y = 0; uint16_t z = 0; memcpy(&x, Data, sizeof(x)); memcpy(&y, Data + Size / 2, sizeof(y)); memcpy(&z, Data + Size - sizeof(z), sizeof(z)); x = __builtin_bswap64(x); y = __builtin_bswap32(y); z = __builtin_bswap16(z); if (x == 0x46555A5A5A5A5546ULL && z == 0x4F4B && y == 0x66757A7A && true ) { if (Data[Size - 3] == 'z') { fprintf(stderr, "BINGO; Found the target\n"); exit(1); } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SimpleHashTest.cpp
.cpp
1,252
41
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // This test computes a checksum of the data (all but the last 4 bytes), // and then compares the last 4 bytes with the computed value. // A fuzzer with cmp traces is expected to defeat this check. #include <cstdint> #include <cstdlib> #include <cstring> #include <cstdio> // A modified jenkins_one_at_a_time_hash initialized by non-zero, // so that simple_hash(0) != 0. See also // https://en.wikipedia.org/wiki/Jenkins_hash_function static uint32_t simple_hash(const uint8_t *Data, size_t Size) { uint32_t Hash = 0x12039854; for (uint32_t i = 0; i < Size; i++) { Hash += Data[i]; Hash += (Hash << 10); Hash ^= (Hash >> 6); } Hash += (Hash << 3); Hash ^= (Hash >> 11); Hash += (Hash << 15); return Hash; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 14) return 0; uint32_t Hash = simple_hash(&Data[0], Size - 4); uint32_t Want = reinterpret_cast<const uint32_t *>(&Data[Size - 4])[0]; if (Hash != Want) return 0; fprintf(stderr, "BINGO; simple_hash defeated: %x == %x\n", (unsigned int)Hash, (unsigned int)Want); exit(1); return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/DivTest.cpp
.cpp
489
21
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer: find the interesting argument for div. #include <assert.h> #include <cstdint> #include <cstring> #include <cstddef> #include <iostream> static volatile int Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 4) return 0; int a; memcpy(&a, Data, 4); Sink = 12345678 / (987654 - a); return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/AFLDriverTest.cpp
.cpp
607
23
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Contains dummy functions used to avoid dependency on AFL. #include <stdint.h> #include <stdlib.h> extern "C" void __afl_manual_init() {} extern "C" int __afl_persistent_loop(unsigned int) { return 0; } // This declaration exists to prevent the Darwin linker // from complaining about this being a missing weak symbol. extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) { return 0; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/BufferOverflowOnInput.cpp
.cpp
594
24
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the string "Hi!". #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> static volatile bool SeedLargeBuffer; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { assert(Data); if (Size >= 4) SeedLargeBuffer = true; if (Size == 3 && SeedLargeBuffer && Data[3]) { std::cout << "Woops, reading Data[3] w/o crashing\n"; exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/TimeoutTest.cpp
.cpp
590
27
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the string "Hi!". #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> static volatile int Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size > 0 && Data[0] == 'H') { Sink = 1; if (Size > 1 && Data[1] == 'i') { Sink = 2; if (Size > 2 && Data[2] == '!') { Sink = 2; while (Sink) ; } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/MemcmpTest.cpp
.cpp
1,008
32
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find a particular string. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { // TODO: check other sizes. if (Size >= 8 && memcmp(Data, "01234567", 8) == 0) { if (Size >= 12 && memcmp(Data + 8, "ABCD", 4) == 0) { if (Size >= 14 && memcmp(Data + 12, "XY", 2) == 0) { if (Size >= 17 && memcmp(Data + 14, "KLM", 3) == 0) { if (Size >= 27 && memcmp(Data + 17, "ABCDE-GHIJ", 10) == 0){ fprintf(stderr, "BINGO %zd\n", Size); for (size_t i = 0; i < Size; i++) { uint8_t C = Data[i]; if (C >= 32 && C < 127) fprintf(stderr, "%c", C); } fprintf(stderr, "\n"); exit(1); } } } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/LoadTest.cpp
.cpp
555
23
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer: find interesting value of array index. #include <assert.h> #include <cstdint> #include <cstring> #include <cstddef> #include <iostream> static volatile int Sink; const int kArraySize = 1234567; int array[kArraySize]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 8) return 0; size_t a = 0; memcpy(&a, Data, 8); Sink = array[a % (kArraySize + 1)]; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/TraceMallocTest.cpp
.cpp
542
28
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Tests -trace_malloc #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> int *Ptr; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (!Size) return 0; if (*Data == 1) { delete Ptr; Ptr = nullptr; } else if (*Data == 2) { delete Ptr; Ptr = new int; } else if (*Data == 3) { if (!Ptr) Ptr = new int; } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/OneHugeAllocTest.cpp
.cpp
694
29
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Tests OOM handling when there is a single large allocation. #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstring> #include <iostream> static volatile char *SinkPtr; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size > 0 && Data[0] == 'H') { if (Size > 1 && Data[1] == 'i') { if (Size > 2 && Data[2] == '!') { size_t kSize = (size_t)1 << 31; char *p = new char[kSize]; memset(p, 0, kSize); SinkPtr = p; delete [] p; } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/DSOTestMain.cpp
.cpp
809
32
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Source code for a simple DSO. #include <cstdint> #include <cstdlib> #include <cstring> #include <cstdio> extern int DSO1(int a); extern int DSO2(int a); extern int DSOTestExtra(int a); static volatile int *nil = 0; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int x, y, z; if (Size < sizeof(int) * 3) { x = y = z = 0; } else { memcpy(&x, Data + 0 * sizeof(int), sizeof(int)); memcpy(&y, Data + 1 * sizeof(int), sizeof(int)); memcpy(&z, Data + 2 * sizeof(int), sizeof(int)); } int sum = DSO1(x) + DSO2(y) + (z ? DSOTestExtra(z) : 0); if (sum == 3) { fprintf(stderr, "BINGO %d %d %d\n", x, y, z); *nil = 0; } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/InitializeTest.cpp
.cpp
721
29
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Make sure LLVMFuzzerInitialize is called. #include <assert.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static char *argv0; extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) { assert(*argc > 0); argv0 = **argv; fprintf(stderr, "LLVMFuzzerInitialize: %s\n", argv0); return 0; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size == strlen(argv0) && !strncmp(reinterpret_cast<const char *>(Data), argv0, Size)) { fprintf(stderr, "BINGO %s\n", argv0); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/ThreadedLeakTest.cpp
.cpp
457
19
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // The fuzzer should find a leak in a non-main thread. #include <cstdint> #include <cstddef> #include <thread> static volatile int *Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size == 0) return 0; if (Data[0] != 'F') return 0; std::thread T([&] { Sink = new int; }); T.join(); return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SingleMemcmpTest.cpp
.cpp
470
18
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find a particular string. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { char *S = (char*)Data; if (Size >= 6 && !memcmp(S, "qwerty", 6)) { fprintf(stderr, "BINGO\n"); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SingleStrcmpTest.cpp
.cpp
467
18
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find a particular string. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { char *S = (char*)Data; if (Size >= 7 && !strcmp(S, "qwerty")) { fprintf(stderr, "BINGO\n"); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SignedIntOverflowTest.cpp
.cpp
626
29
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test for signed-integer-overflow. #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> #include <climits> static volatile int Sink; static int Large = INT_MAX; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { assert(Data); if (Size > 0 && Data[0] == 'H') { Sink = 1; if (Size > 1 && Data[1] == 'i') { Sink = 2; if (Size > 2 && Data[2] == '!') { Large++; // int overflow. } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/ThreadedTest.cpp
.cpp
722
27
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Threaded test for a fuzzer. The fuzzer should not crash. #include <assert.h> #include <cstdint> #include <cstddef> #include <cstring> #include <thread> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 8) return 0; assert(Data); auto C = [&] { size_t Res = 0; for (size_t i = 0; i < Size / 2; i++) Res += memcmp(Data, Data + Size / 2, 4); return Res; }; std::thread T[] = {std::thread(C), std::thread(C), std::thread(C), std::thread(C), std::thread(C), std::thread(C)}; for (auto &X : T) X.join(); return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/NullDerefOnEmptyTest.cpp
.cpp
479
20
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the empty string. #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> static volatile int *Null = 0; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size == 0) { std::cout << "Found the target, dereferencing NULL\n"; *Null = 1; } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/OutOfMemoryTest.cpp
.cpp
748
32
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Tests OOM handling. #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstring> #include <iostream> #include <thread> static volatile char *SinkPtr; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size > 0 && Data[0] == 'H') { if (Size > 1 && Data[1] == 'i') { if (Size > 2 && Data[2] == '!') { while (true) { size_t kSize = 1 << 28; char *p = new char[kSize]; memset(p, 0, kSize); SinkPtr = p; std::this_thread::sleep_for(std::chrono::seconds(1)); } } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/NullDerefTest.cpp
.cpp
652
27
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the string "Hi!". #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> static volatile int Sink; static volatile int *Null = 0; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size > 0 && Data[0] == 'H') { Sink = 1; if (Size > 1 && Data[1] == 'i') { Sink = 2; if (Size > 2 && Data[2] == '!') { std::cout << "Found the target, dereferencing NULL\n"; *Null = 1; } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/RepeatedMemcmp.cpp
.cpp
517
23
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int Matches = 0; for (size_t i = 0; i + 2 < Size; i += 3) { const char *Pat = i % 2 ? "foo" : "bar"; if (!memcmp(Data + i, Pat, 3)) Matches++; } if (Matches > 20) { fprintf(stderr, "BINGO!\n"); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/DSOTestExtra.cpp
.cpp
222
12
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Source code for a simple DSO. int DSOTestExtra(int a) { if (a < 452345) return 0; return 1; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/EmptyTest.cpp
.cpp
285
12
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // // A fuzzer with empty target function. #include <cstdint> #include <cstdlib> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SimpleTest.cpp
.cpp
651
28
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the string "Hi!". #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> static volatile int Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { assert(Data); if (Size > 0 && Data[0] == 'H') { Sink = 1; if (Size > 1 && Data[1] == 'i') { Sink = 2; if (Size > 2 && Data[2] == '!') { std::cout << "BINGO; Found the target, exiting\n"; exit(0); } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/LeakTest.cpp
.cpp
371
18
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test with a leak. #include <cstdint> #include <cstddef> static volatile void *Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size > 0 && *Data == 'H') { Sink = new int; Sink = nullptr; } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/AbsNegAndConstant64Test.cpp
.cpp
622
24
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // abs(x) < 0 and y == Const puzzle, 64-bit variant. #include <cstring> #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstdio> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 16) return 0; int64_t x; uint64_t y; memcpy(&x, Data, sizeof(x)); memcpy(&y, Data + sizeof(x), sizeof(y)); if (labs(x) < 0 && y == 0xbaddcafedeadbeefUL) { printf("BINGO; Found the target, exiting; x = 0x%lx y 0x%lx\n", x, y); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/StrncmpOOBTest.cpp
.cpp
566
22
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test that libFuzzer itself does not read out of bounds. #include <assert.h> #include <cstdint> #include <cstring> #include <cstdlib> #include <cstddef> #include <iostream> static volatile int Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 5) return 0; const char *Ch = reinterpret_cast<const char *>(Data); if (Ch[Size - 3] == 'a') Sink = strncmp(Ch + Size - 3, "abcdefg", 6); return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/AccumulateAllocationsTest.cpp
.cpp
527
18
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test with a more mallocs than frees, but no leak. #include <cstdint> #include <cstddef> const int kAllocatedPointersSize = 10000; int NumAllocatedPointers = 0; int *AllocatedPointers[kAllocatedPointersSize]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (NumAllocatedPointers < kAllocatedPointersSize) AllocatedPointers[NumAllocatedPointers++] = new int; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/DSO2.cpp
.cpp
236
13
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Source code for a simple DSO. int DSO2(int a) { if (a < 3598235) return 0; return 1; } void Uncovered2() {}
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/RepeatedBytesTest.cpp
.cpp
845
30
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find repeated bytes. #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { assert(Data); // Looking for AAAAAAAAAAAAAAAAAAAAAA or some such. size_t CurA = 0, MaxA = 0; for (size_t i = 0; i < Size; i++) { // Make sure there are no conditionals in the loop so that // coverage can't help the fuzzer. int EQ = Data[i] == 'A'; CurA = EQ * (CurA + 1); int GT = CurA > MaxA; MaxA = GT * CurA + (!GT) * MaxA; } if (MaxA >= 20) { std::cout << "BINGO; Found the target (Max: " << MaxA << "), exiting\n"; exit(0); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/CounterTest.cpp
.cpp
480
19
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test for a fuzzer: must find the case where a particular basic block is // executed many times. #include <iostream> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int Num = 0; for (size_t i = 0; i < Size; i++) if (Data[i] == 'A' + i) Num++; if (Num >= 4) { std::cerr << "BINGO!\n"; exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/ShrinkValueProfileTest.cpp
.cpp
610
23
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test that we can find the minimal item in the corpus (3 bytes: "FUZ"). #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstring> #include <cstdio> static volatile uint32_t Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < sizeof(uint32_t)) return 0; uint32_t X, Y; size_t Offset = Size < 8 ? 0 : Size / 2; memcpy(&X, Data + Offset, sizeof(uint32_t)); memcpy(&Y, "FUZZ", sizeof(uint32_t)); Sink = X == Y; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/ShrinkControlFlowTest.cpp
.cpp
745
29
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test that we can find the minimal item in the corpus (3 bytes: "FUZ"). #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstring> #include <cstdio> static volatile int Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int8_t Ids[256]; memset(Ids, -1, sizeof(Ids)); for (size_t i = 0; i < Size; i++) if (Ids[Data[i]] == -1) Ids[Data[i]] = i; int F = Ids[(unsigned char)'F']; int U = Ids[(unsigned char)'U']; int Z = Ids[(unsigned char)'Z']; if (F >= 0 && U > F && Z > U) { Sink++; //fprintf(stderr, "IDS: %d %d %d\n", F, U, Z); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/OutOfMemorySingleLargeMallocTest.cpp
.cpp
629
28
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Tests OOM handling. #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstring> #include <iostream> static volatile char *SinkPtr; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size > 0 && Data[0] == 'H') { if (Size > 1 && Data[1] == 'i') { if (Size > 2 && Data[2] == '!') { size_t kSize = 0xff000000U; char *p = new char[kSize]; SinkPtr = p; delete [] p; } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/FullCoverageSetTest.cpp
.cpp
708
25
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the string "FUZZER". #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int bits = 0; if (Size > 0 && Data[0] == 'F') bits |= 1; if (Size > 1 && Data[1] == 'U') bits |= 2; if (Size > 2 && Data[2] == 'Z') bits |= 4; if (Size > 3 && Data[3] == 'Z') bits |= 8; if (Size > 4 && Data[4] == 'E') bits |= 16; if (Size > 5 && Data[5] == 'R') bits |= 32; if (bits == 63) { std::cerr << "BINGO!\n"; exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SwitchTest.cpp
.cpp
1,617
59
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the interesting switch value. #include <cstdint> #include <cstdlib> #include <cstdio> #include <cstring> #include <cstddef> static volatile int Sink; template<class T> bool Switch(const uint8_t *Data, size_t Size) { T X; if (Size < sizeof(X)) return false; memcpy(&X, Data, sizeof(X)); switch (X) { case 1: Sink = __LINE__; break; case 101: Sink = __LINE__; break; case 1001: Sink = __LINE__; break; case 10001: Sink = __LINE__; break; // case 100001: Sink = __LINE__; break; // case 1000001: Sink = __LINE__; break; case 10000001: Sink = __LINE__; break; case 100000001: return true; } return false; } bool ShortSwitch(const uint8_t *Data, size_t Size) { short X; if (Size < sizeof(short)) return false; memcpy(&X, Data, sizeof(short)); switch(X) { case 42: Sink = __LINE__; break; case 402: Sink = __LINE__; break; case 4002: Sink = __LINE__; break; case 5002: Sink = __LINE__; break; case 7002: Sink = __LINE__; break; case 9002: Sink = __LINE__; break; case 14002: Sink = __LINE__; break; case 21402: return true; } return false; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size >= 4 && Switch<int>(Data, Size) && Size >= 12 && Switch<uint64_t>(Data + 4, Size - 4) && Size >= 14 && ShortSwitch(Data + 12, 2) ) { fprintf(stderr, "BINGO; Found the target, exiting\n"); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/StrstrTest.cpp
.cpp
754
29
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test strstr and strcasestr hooks. #include <string> #include <string.h> #include <cstdint> #include <cstdio> #include <cstdlib> // Windows does not have strcasestr and memmem, so we are not testing them. #ifdef _WIN32 #define strcasestr strstr #define memmem(a, b, c, d) true #endif extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 4) return 0; std::string s(reinterpret_cast<const char*>(Data), Size); if (strstr(s.c_str(), "FUZZ") && strcasestr(s.c_str(), "aBcD") && memmem(s.data(), s.size(), "kuku", 4) ) { fprintf(stderr, "BINGO\n"); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/FourIndependentBranchesTest.cpp
.cpp
614
23
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the string "FUZZ". #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int bits = 0; if (Size > 0 && Data[0] == 'F') bits |= 1; if (Size > 1 && Data[1] == 'U') bits |= 2; if (Size > 2 && Data[2] == 'Z') bits |= 4; if (Size > 3 && Data[3] == 'Z') bits |= 8; if (bits == 15) { std::cerr << "BINGO!\n"; exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/CustomCrossOverTest.cpp
.cpp
1,745
64
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a cutom mutator. #include <assert.h> #include <cstddef> #include <cstdint> #include <cstdlib> #include <iostream> #include <random> #include <string.h> #include "FuzzerInterface.h" static const char *Separator = "-_^_-"; static const char *Target = "012-_^_-abc"; static volatile int sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { assert(Data); std::string Str(reinterpret_cast<const char *>(Data), Size); // Ensure that two different elements exist in the corpus. if (Size && Data[0] == '0') sink++; if (Size && Data[0] == 'a') sink--; if (Str.find(Target) != std::string::npos) { std::cout << "BINGO; Found the target, exiting\n"; exit(1); } return 0; } extern "C" size_t LLVMFuzzerCustomCrossOver(const uint8_t *Data1, size_t Size1, const uint8_t *Data2, size_t Size2, uint8_t *Out, size_t MaxOutSize, unsigned int Seed) { static bool Printed; static size_t SeparatorLen = strlen(Separator); if (!Printed) { std::cerr << "In LLVMFuzzerCustomCrossover\n"; Printed = true; } std::mt19937 R(Seed); size_t Offset1 = 0; size_t Len1 = R() % (Size1 - Offset1); size_t Offset2 = 0; size_t Len2 = R() % (Size2 - Offset2); size_t Size = Len1 + Len2 + SeparatorLen; if (Size > MaxOutSize) return 0; memcpy(Out, Data1 + Offset1, Len1); memcpy(Out + Len1, Separator, SeparatorLen); memcpy(Out + Len1 + SeparatorLen, Data2 + Offset2, Len2); return Len1 + Len2 + SeparatorLen; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SimpleThreadedTest.cpp
.cpp
694
26
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Threaded test for a fuzzer. The fuzzer should find "H" #include <assert.h> #include <cstdint> #include <cstddef> #include <cstring> #include <iostream> #include <thread> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { auto C = [&] { if (Size >= 2 && Data[0] == 'H') { std::cout << "BINGO; Found the target, exiting\n"; abort(); } }; std::thread T[] = {std::thread(C), std::thread(C), std::thread(C), std::thread(C), std::thread(C), std::thread(C)}; for (auto &X : T) X.join(); return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SingleStrncmpTest.cpp
.cpp
471
18
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find a particular string. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { char *S = (char*)Data; if (Size >= 6 && !strncmp(S, "qwerty", 6)) { fprintf(stderr, "BINGO\n"); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/TimeoutEmptyTest.cpp
.cpp
380
15
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the empty string. #include <cstdint> #include <cstddef> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { static volatile int Zero = 0; if (!Size) while(!Zero) ; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/FuzzerUnittest.cpp
.cpp
28,308
739
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Avoid ODR violations (LibFuzzer is built without ASan and this test is built // with ASan) involving C++ standard library types when using libcxx. #define _LIBCPP_HAS_NO_ASAN #include "FuzzerCorpus.h" #include "FuzzerInternal.h" #include "FuzzerDictionary.h" #include "FuzzerMerge.h" #include "FuzzerMutate.h" #include "FuzzerRandom.h" #include "gtest/gtest.h" #include <memory> #include <set> using namespace fuzzer; // For now, have LLVMFuzzerTestOneInput just to make it link. // Later we may want to make unittests that actually call LLVMFuzzerTestOneInput. extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { abort(); } TEST(Fuzzer, CrossOver) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); Unit A({0, 1, 2}), B({5, 6, 7}); Unit C; Unit Expected[] = { { 0 }, { 0, 1 }, { 0, 5 }, { 0, 1, 2 }, { 0, 1, 5 }, { 0, 5, 1 }, { 0, 5, 6 }, { 0, 1, 2, 5 }, { 0, 1, 5, 2 }, { 0, 1, 5, 6 }, { 0, 5, 1, 2 }, { 0, 5, 1, 6 }, { 0, 5, 6, 1 }, { 0, 5, 6, 7 }, { 0, 1, 2, 5, 6 }, { 0, 1, 5, 2, 6 }, { 0, 1, 5, 6, 2 }, { 0, 1, 5, 6, 7 }, { 0, 5, 1, 2, 6 }, { 0, 5, 1, 6, 2 }, { 0, 5, 1, 6, 7 }, { 0, 5, 6, 1, 2 }, { 0, 5, 6, 1, 7 }, { 0, 5, 6, 7, 1 }, { 0, 1, 2, 5, 6, 7 }, { 0, 1, 5, 2, 6, 7 }, { 0, 1, 5, 6, 2, 7 }, { 0, 1, 5, 6, 7, 2 }, { 0, 5, 1, 2, 6, 7 }, { 0, 5, 1, 6, 2, 7 }, { 0, 5, 1, 6, 7, 2 }, { 0, 5, 6, 1, 2, 7 }, { 0, 5, 6, 1, 7, 2 }, { 0, 5, 6, 7, 1, 2 } }; for (size_t Len = 1; Len < 8; Len++) { std::set<Unit> FoundUnits, ExpectedUnitsWitThisLength; for (int Iter = 0; Iter < 3000; Iter++) { C.resize(Len); size_t NewSize = MD.CrossOver(A.data(), A.size(), B.data(), B.size(), C.data(), C.size()); C.resize(NewSize); FoundUnits.insert(C); } for (const Unit &U : Expected) if (U.size() <= Len) ExpectedUnitsWitThisLength.insert(U); EXPECT_EQ(ExpectedUnitsWitThisLength, FoundUnits); } } TEST(Fuzzer, Hash) { uint8_t A[] = {'a', 'b', 'c'}; fuzzer::Unit U(A, A + sizeof(A)); EXPECT_EQ("a9993e364706816aba3e25717850c26c9cd0d89d", fuzzer::Hash(U)); U.push_back('d'); EXPECT_EQ("81fe8bfe87576c3ecb22426f8e57847382917acf", fuzzer::Hash(U)); } typedef size_t (MutationDispatcher::*Mutator)(uint8_t *Data, size_t Size, size_t MaxSize); void TestEraseBytes(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); uint8_t REM0[8] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t REM1[8] = {0x00, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t REM2[8] = {0x00, 0x11, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t REM3[8] = {0x00, 0x11, 0x22, 0x44, 0x55, 0x66, 0x77}; uint8_t REM4[8] = {0x00, 0x11, 0x22, 0x33, 0x55, 0x66, 0x77}; uint8_t REM5[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x66, 0x77}; uint8_t REM6[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x77}; uint8_t REM7[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; uint8_t REM8[6] = {0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t REM9[6] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55}; uint8_t REM10[6] = {0x00, 0x11, 0x22, 0x55, 0x66, 0x77}; uint8_t REM11[5] = {0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t REM12[5] = {0x00, 0x11, 0x22, 0x33, 0x44}; uint8_t REM13[5] = {0x00, 0x44, 0x55, 0x66, 0x77}; Random Rand(0); MutationDispatcher MD(Rand, {}); int FoundMask = 0; for (int i = 0; i < NumIter; i++) { uint8_t T[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; size_t NewSize = (MD.*M)(T, sizeof(T), sizeof(T)); if (NewSize == 7 && !memcmp(REM0, T, 7)) FoundMask |= 1 << 0; if (NewSize == 7 && !memcmp(REM1, T, 7)) FoundMask |= 1 << 1; if (NewSize == 7 && !memcmp(REM2, T, 7)) FoundMask |= 1 << 2; if (NewSize == 7 && !memcmp(REM3, T, 7)) FoundMask |= 1 << 3; if (NewSize == 7 && !memcmp(REM4, T, 7)) FoundMask |= 1 << 4; if (NewSize == 7 && !memcmp(REM5, T, 7)) FoundMask |= 1 << 5; if (NewSize == 7 && !memcmp(REM6, T, 7)) FoundMask |= 1 << 6; if (NewSize == 7 && !memcmp(REM7, T, 7)) FoundMask |= 1 << 7; if (NewSize == 6 && !memcmp(REM8, T, 6)) FoundMask |= 1 << 8; if (NewSize == 6 && !memcmp(REM9, T, 6)) FoundMask |= 1 << 9; if (NewSize == 6 && !memcmp(REM10, T, 6)) FoundMask |= 1 << 10; if (NewSize == 5 && !memcmp(REM11, T, 5)) FoundMask |= 1 << 11; if (NewSize == 5 && !memcmp(REM12, T, 5)) FoundMask |= 1 << 12; if (NewSize == 5 && !memcmp(REM13, T, 5)) FoundMask |= 1 << 13; } EXPECT_EQ(FoundMask, (1 << 14) - 1); } TEST(FuzzerMutate, EraseBytes1) { TestEraseBytes(&MutationDispatcher::Mutate_EraseBytes, 200); } TEST(FuzzerMutate, EraseBytes2) { TestEraseBytes(&MutationDispatcher::Mutate, 2000); } void TestInsertByte(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); int FoundMask = 0; uint8_t INS0[8] = {0xF1, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; uint8_t INS1[8] = {0x00, 0xF2, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; uint8_t INS2[8] = {0x00, 0x11, 0xF3, 0x22, 0x33, 0x44, 0x55, 0x66}; uint8_t INS3[8] = {0x00, 0x11, 0x22, 0xF4, 0x33, 0x44, 0x55, 0x66}; uint8_t INS4[8] = {0x00, 0x11, 0x22, 0x33, 0xF5, 0x44, 0x55, 0x66}; uint8_t INS5[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0xF6, 0x55, 0x66}; uint8_t INS6[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xF7, 0x66}; uint8_t INS7[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0xF8}; for (int i = 0; i < NumIter; i++) { uint8_t T[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; size_t NewSize = (MD.*M)(T, 7, 8); if (NewSize == 8 && !memcmp(INS0, T, 8)) FoundMask |= 1 << 0; if (NewSize == 8 && !memcmp(INS1, T, 8)) FoundMask |= 1 << 1; if (NewSize == 8 && !memcmp(INS2, T, 8)) FoundMask |= 1 << 2; if (NewSize == 8 && !memcmp(INS3, T, 8)) FoundMask |= 1 << 3; if (NewSize == 8 && !memcmp(INS4, T, 8)) FoundMask |= 1 << 4; if (NewSize == 8 && !memcmp(INS5, T, 8)) FoundMask |= 1 << 5; if (NewSize == 8 && !memcmp(INS6, T, 8)) FoundMask |= 1 << 6; if (NewSize == 8 && !memcmp(INS7, T, 8)) FoundMask |= 1 << 7; } EXPECT_EQ(FoundMask, 255); } TEST(FuzzerMutate, InsertByte1) { TestInsertByte(&MutationDispatcher::Mutate_InsertByte, 1 << 15); } TEST(FuzzerMutate, InsertByte2) { TestInsertByte(&MutationDispatcher::Mutate, 1 << 17); } void TestInsertRepeatedBytes(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); int FoundMask = 0; uint8_t INS0[7] = {0x00, 0x11, 0x22, 0x33, 'a', 'a', 'a'}; uint8_t INS1[7] = {0x00, 0x11, 0x22, 'a', 'a', 'a', 0x33}; uint8_t INS2[7] = {0x00, 0x11, 'a', 'a', 'a', 0x22, 0x33}; uint8_t INS3[7] = {0x00, 'a', 'a', 'a', 0x11, 0x22, 0x33}; uint8_t INS4[7] = {'a', 'a', 'a', 0x00, 0x11, 0x22, 0x33}; uint8_t INS5[8] = {0x00, 0x11, 0x22, 0x33, 'b', 'b', 'b', 'b'}; uint8_t INS6[8] = {0x00, 0x11, 0x22, 'b', 'b', 'b', 'b', 0x33}; uint8_t INS7[8] = {0x00, 0x11, 'b', 'b', 'b', 'b', 0x22, 0x33}; uint8_t INS8[8] = {0x00, 'b', 'b', 'b', 'b', 0x11, 0x22, 0x33}; uint8_t INS9[8] = {'b', 'b', 'b', 'b', 0x00, 0x11, 0x22, 0x33}; for (int i = 0; i < NumIter; i++) { uint8_t T[8] = {0x00, 0x11, 0x22, 0x33}; size_t NewSize = (MD.*M)(T, 4, 8); if (NewSize == 7 && !memcmp(INS0, T, 7)) FoundMask |= 1 << 0; if (NewSize == 7 && !memcmp(INS1, T, 7)) FoundMask |= 1 << 1; if (NewSize == 7 && !memcmp(INS2, T, 7)) FoundMask |= 1 << 2; if (NewSize == 7 && !memcmp(INS3, T, 7)) FoundMask |= 1 << 3; if (NewSize == 7 && !memcmp(INS4, T, 7)) FoundMask |= 1 << 4; if (NewSize == 8 && !memcmp(INS5, T, 8)) FoundMask |= 1 << 5; if (NewSize == 8 && !memcmp(INS6, T, 8)) FoundMask |= 1 << 6; if (NewSize == 8 && !memcmp(INS7, T, 8)) FoundMask |= 1 << 7; if (NewSize == 8 && !memcmp(INS8, T, 8)) FoundMask |= 1 << 8; if (NewSize == 8 && !memcmp(INS9, T, 8)) FoundMask |= 1 << 9; } EXPECT_EQ(FoundMask, (1 << 10) - 1); } TEST(FuzzerMutate, InsertRepeatedBytes1) { TestInsertRepeatedBytes(&MutationDispatcher::Mutate_InsertRepeatedBytes, 10000); } TEST(FuzzerMutate, InsertRepeatedBytes2) { TestInsertRepeatedBytes(&MutationDispatcher::Mutate, 300000); } void TestChangeByte(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); int FoundMask = 0; uint8_t CH0[8] = {0xF0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t CH1[8] = {0x00, 0xF1, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t CH2[8] = {0x00, 0x11, 0xF2, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t CH3[8] = {0x00, 0x11, 0x22, 0xF3, 0x44, 0x55, 0x66, 0x77}; uint8_t CH4[8] = {0x00, 0x11, 0x22, 0x33, 0xF4, 0x55, 0x66, 0x77}; uint8_t CH5[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0xF5, 0x66, 0x77}; uint8_t CH6[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xF5, 0x77}; uint8_t CH7[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0xF7}; for (int i = 0; i < NumIter; i++) { uint8_t T[9] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; size_t NewSize = (MD.*M)(T, 8, 9); if (NewSize == 8 && !memcmp(CH0, T, 8)) FoundMask |= 1 << 0; if (NewSize == 8 && !memcmp(CH1, T, 8)) FoundMask |= 1 << 1; if (NewSize == 8 && !memcmp(CH2, T, 8)) FoundMask |= 1 << 2; if (NewSize == 8 && !memcmp(CH3, T, 8)) FoundMask |= 1 << 3; if (NewSize == 8 && !memcmp(CH4, T, 8)) FoundMask |= 1 << 4; if (NewSize == 8 && !memcmp(CH5, T, 8)) FoundMask |= 1 << 5; if (NewSize == 8 && !memcmp(CH6, T, 8)) FoundMask |= 1 << 6; if (NewSize == 8 && !memcmp(CH7, T, 8)) FoundMask |= 1 << 7; } EXPECT_EQ(FoundMask, 255); } TEST(FuzzerMutate, ChangeByte1) { TestChangeByte(&MutationDispatcher::Mutate_ChangeByte, 1 << 15); } TEST(FuzzerMutate, ChangeByte2) { TestChangeByte(&MutationDispatcher::Mutate, 1 << 17); } void TestChangeBit(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); int FoundMask = 0; uint8_t CH0[8] = {0x01, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t CH1[8] = {0x00, 0x13, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t CH2[8] = {0x00, 0x11, 0x02, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t CH3[8] = {0x00, 0x11, 0x22, 0x37, 0x44, 0x55, 0x66, 0x77}; uint8_t CH4[8] = {0x00, 0x11, 0x22, 0x33, 0x54, 0x55, 0x66, 0x77}; uint8_t CH5[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x54, 0x66, 0x77}; uint8_t CH6[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x76, 0x77}; uint8_t CH7[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0xF7}; for (int i = 0; i < NumIter; i++) { uint8_t T[9] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; size_t NewSize = (MD.*M)(T, 8, 9); if (NewSize == 8 && !memcmp(CH0, T, 8)) FoundMask |= 1 << 0; if (NewSize == 8 && !memcmp(CH1, T, 8)) FoundMask |= 1 << 1; if (NewSize == 8 && !memcmp(CH2, T, 8)) FoundMask |= 1 << 2; if (NewSize == 8 && !memcmp(CH3, T, 8)) FoundMask |= 1 << 3; if (NewSize == 8 && !memcmp(CH4, T, 8)) FoundMask |= 1 << 4; if (NewSize == 8 && !memcmp(CH5, T, 8)) FoundMask |= 1 << 5; if (NewSize == 8 && !memcmp(CH6, T, 8)) FoundMask |= 1 << 6; if (NewSize == 8 && !memcmp(CH7, T, 8)) FoundMask |= 1 << 7; } EXPECT_EQ(FoundMask, 255); } TEST(FuzzerMutate, ChangeBit1) { TestChangeBit(&MutationDispatcher::Mutate_ChangeBit, 1 << 16); } TEST(FuzzerMutate, ChangeBit2) { TestChangeBit(&MutationDispatcher::Mutate, 1 << 18); } void TestShuffleBytes(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); int FoundMask = 0; uint8_t CH0[7] = {0x00, 0x22, 0x11, 0x33, 0x44, 0x55, 0x66}; uint8_t CH1[7] = {0x11, 0x00, 0x33, 0x22, 0x44, 0x55, 0x66}; uint8_t CH2[7] = {0x00, 0x33, 0x11, 0x22, 0x44, 0x55, 0x66}; uint8_t CH3[7] = {0x00, 0x11, 0x22, 0x44, 0x55, 0x66, 0x33}; uint8_t CH4[7] = {0x00, 0x11, 0x22, 0x33, 0x55, 0x44, 0x66}; for (int i = 0; i < NumIter; i++) { uint8_t T[7] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; size_t NewSize = (MD.*M)(T, 7, 7); if (NewSize == 7 && !memcmp(CH0, T, 7)) FoundMask |= 1 << 0; if (NewSize == 7 && !memcmp(CH1, T, 7)) FoundMask |= 1 << 1; if (NewSize == 7 && !memcmp(CH2, T, 7)) FoundMask |= 1 << 2; if (NewSize == 7 && !memcmp(CH3, T, 7)) FoundMask |= 1 << 3; if (NewSize == 7 && !memcmp(CH4, T, 7)) FoundMask |= 1 << 4; } EXPECT_EQ(FoundMask, 31); } TEST(FuzzerMutate, ShuffleBytes1) { TestShuffleBytes(&MutationDispatcher::Mutate_ShuffleBytes, 1 << 16); } TEST(FuzzerMutate, ShuffleBytes2) { TestShuffleBytes(&MutationDispatcher::Mutate, 1 << 20); } void TestCopyPart(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); int FoundMask = 0; uint8_t CH0[7] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x00, 0x11}; uint8_t CH1[7] = {0x55, 0x66, 0x22, 0x33, 0x44, 0x55, 0x66}; uint8_t CH2[7] = {0x00, 0x55, 0x66, 0x33, 0x44, 0x55, 0x66}; uint8_t CH3[7] = {0x00, 0x11, 0x22, 0x00, 0x11, 0x22, 0x66}; uint8_t CH4[7] = {0x00, 0x11, 0x11, 0x22, 0x33, 0x55, 0x66}; for (int i = 0; i < NumIter; i++) { uint8_t T[7] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; size_t NewSize = (MD.*M)(T, 7, 7); if (NewSize == 7 && !memcmp(CH0, T, 7)) FoundMask |= 1 << 0; if (NewSize == 7 && !memcmp(CH1, T, 7)) FoundMask |= 1 << 1; if (NewSize == 7 && !memcmp(CH2, T, 7)) FoundMask |= 1 << 2; if (NewSize == 7 && !memcmp(CH3, T, 7)) FoundMask |= 1 << 3; if (NewSize == 7 && !memcmp(CH4, T, 7)) FoundMask |= 1 << 4; } uint8_t CH5[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x00, 0x11, 0x22}; uint8_t CH6[8] = {0x22, 0x33, 0x44, 0x00, 0x11, 0x22, 0x33, 0x44}; uint8_t CH7[8] = {0x00, 0x11, 0x22, 0x00, 0x11, 0x22, 0x33, 0x44}; uint8_t CH8[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x22, 0x33, 0x44}; uint8_t CH9[8] = {0x00, 0x11, 0x22, 0x22, 0x33, 0x44, 0x33, 0x44}; for (int i = 0; i < NumIter; i++) { uint8_t T[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; size_t NewSize = (MD.*M)(T, 5, 8); if (NewSize == 8 && !memcmp(CH5, T, 8)) FoundMask |= 1 << 5; if (NewSize == 8 && !memcmp(CH6, T, 8)) FoundMask |= 1 << 6; if (NewSize == 8 && !memcmp(CH7, T, 8)) FoundMask |= 1 << 7; if (NewSize == 8 && !memcmp(CH8, T, 8)) FoundMask |= 1 << 8; if (NewSize == 8 && !memcmp(CH9, T, 8)) FoundMask |= 1 << 9; } EXPECT_EQ(FoundMask, 1023); } TEST(FuzzerMutate, CopyPart1) { TestCopyPart(&MutationDispatcher::Mutate_CopyPart, 1 << 10); } TEST(FuzzerMutate, CopyPart2) { TestCopyPart(&MutationDispatcher::Mutate, 1 << 13); } void TestAddWordFromDictionary(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); uint8_t Word1[4] = {0xAA, 0xBB, 0xCC, 0xDD}; uint8_t Word2[3] = {0xFF, 0xEE, 0xEF}; MD.AddWordToManualDictionary(Word(Word1, sizeof(Word1))); MD.AddWordToManualDictionary(Word(Word2, sizeof(Word2))); int FoundMask = 0; uint8_t CH0[7] = {0x00, 0x11, 0x22, 0xAA, 0xBB, 0xCC, 0xDD}; uint8_t CH1[7] = {0x00, 0x11, 0xAA, 0xBB, 0xCC, 0xDD, 0x22}; uint8_t CH2[7] = {0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0x11, 0x22}; uint8_t CH3[7] = {0xAA, 0xBB, 0xCC, 0xDD, 0x00, 0x11, 0x22}; uint8_t CH4[6] = {0x00, 0x11, 0x22, 0xFF, 0xEE, 0xEF}; uint8_t CH5[6] = {0x00, 0x11, 0xFF, 0xEE, 0xEF, 0x22}; uint8_t CH6[6] = {0x00, 0xFF, 0xEE, 0xEF, 0x11, 0x22}; uint8_t CH7[6] = {0xFF, 0xEE, 0xEF, 0x00, 0x11, 0x22}; for (int i = 0; i < NumIter; i++) { uint8_t T[7] = {0x00, 0x11, 0x22}; size_t NewSize = (MD.*M)(T, 3, 7); if (NewSize == 7 && !memcmp(CH0, T, 7)) FoundMask |= 1 << 0; if (NewSize == 7 && !memcmp(CH1, T, 7)) FoundMask |= 1 << 1; if (NewSize == 7 && !memcmp(CH2, T, 7)) FoundMask |= 1 << 2; if (NewSize == 7 && !memcmp(CH3, T, 7)) FoundMask |= 1 << 3; if (NewSize == 6 && !memcmp(CH4, T, 6)) FoundMask |= 1 << 4; if (NewSize == 6 && !memcmp(CH5, T, 6)) FoundMask |= 1 << 5; if (NewSize == 6 && !memcmp(CH6, T, 6)) FoundMask |= 1 << 6; if (NewSize == 6 && !memcmp(CH7, T, 6)) FoundMask |= 1 << 7; } EXPECT_EQ(FoundMask, 255); } TEST(FuzzerMutate, AddWordFromDictionary1) { TestAddWordFromDictionary( &MutationDispatcher::Mutate_AddWordFromManualDictionary, 1 << 15); } TEST(FuzzerMutate, AddWordFromDictionary2) { TestAddWordFromDictionary(&MutationDispatcher::Mutate, 1 << 15); } void TestAddWordFromDictionaryWithHint(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); uint8_t W[] = {0xAA, 0xBB, 0xCC, 0xDD, 0xFF, 0xEE, 0xEF}; size_t PosHint = 7777; MD.AddWordToAutoDictionary({Word(W, sizeof(W)), PosHint}); int FoundMask = 0; for (int i = 0; i < NumIter; i++) { uint8_t T[10000]; memset(T, 0, sizeof(T)); size_t NewSize = (MD.*M)(T, 9000, 10000); if (NewSize >= PosHint + sizeof(W) && !memcmp(W, T + PosHint, sizeof(W))) FoundMask = 1; } EXPECT_EQ(FoundMask, 1); } TEST(FuzzerMutate, AddWordFromDictionaryWithHint1) { TestAddWordFromDictionaryWithHint( &MutationDispatcher::Mutate_AddWordFromTemporaryAutoDictionary, 1 << 5); } TEST(FuzzerMutate, AddWordFromDictionaryWithHint2) { TestAddWordFromDictionaryWithHint(&MutationDispatcher::Mutate, 1 << 10); } void TestChangeASCIIInteger(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); uint8_t CH0[8] = {'1', '2', '3', '4', '5', '6', '7', '7'}; uint8_t CH1[8] = {'1', '2', '3', '4', '5', '6', '7', '9'}; uint8_t CH2[8] = {'2', '4', '6', '9', '1', '3', '5', '6'}; uint8_t CH3[8] = {'0', '6', '1', '7', '2', '8', '3', '9'}; int FoundMask = 0; for (int i = 0; i < NumIter; i++) { uint8_t T[8] = {'1', '2', '3', '4', '5', '6', '7', '8'}; size_t NewSize = (MD.*M)(T, 8, 8); /**/ if (NewSize == 8 && !memcmp(CH0, T, 8)) FoundMask |= 1 << 0; else if (NewSize == 8 && !memcmp(CH1, T, 8)) FoundMask |= 1 << 1; else if (NewSize == 8 && !memcmp(CH2, T, 8)) FoundMask |= 1 << 2; else if (NewSize == 8 && !memcmp(CH3, T, 8)) FoundMask |= 1 << 3; else if (NewSize == 8) FoundMask |= 1 << 4; } EXPECT_EQ(FoundMask, 31); } TEST(FuzzerMutate, ChangeASCIIInteger1) { TestChangeASCIIInteger(&MutationDispatcher::Mutate_ChangeASCIIInteger, 1 << 15); } TEST(FuzzerMutate, ChangeASCIIInteger2) { TestChangeASCIIInteger(&MutationDispatcher::Mutate, 1 << 15); } void TestChangeBinaryInteger(Mutator M, int NumIter) { std::unique_ptr<ExternalFunctions> t(new ExternalFunctions()); fuzzer::EF = t.get(); Random Rand(0); MutationDispatcher MD(Rand, {}); uint8_t CH0[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x79}; uint8_t CH1[8] = {0x00, 0x11, 0x22, 0x31, 0x44, 0x55, 0x66, 0x77}; uint8_t CH2[8] = {0xff, 0x10, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t CH3[8] = {0x00, 0x11, 0x2a, 0x33, 0x44, 0x55, 0x66, 0x77}; uint8_t CH4[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x4f, 0x66, 0x77}; uint8_t CH5[8] = {0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88}; uint8_t CH6[8] = {0x00, 0x11, 0x22, 0x00, 0x00, 0x00, 0x08, 0x77}; // Size uint8_t CH7[8] = {0x00, 0x08, 0x00, 0x33, 0x44, 0x55, 0x66, 0x77}; // Sw(Size) int FoundMask = 0; for (int i = 0; i < NumIter; i++) { uint8_t T[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; size_t NewSize = (MD.*M)(T, 8, 8); /**/ if (NewSize == 8 && !memcmp(CH0, T, 8)) FoundMask |= 1 << 0; else if (NewSize == 8 && !memcmp(CH1, T, 8)) FoundMask |= 1 << 1; else if (NewSize == 8 && !memcmp(CH2, T, 8)) FoundMask |= 1 << 2; else if (NewSize == 8 && !memcmp(CH3, T, 8)) FoundMask |= 1 << 3; else if (NewSize == 8 && !memcmp(CH4, T, 8)) FoundMask |= 1 << 4; else if (NewSize == 8 && !memcmp(CH5, T, 8)) FoundMask |= 1 << 5; else if (NewSize == 8 && !memcmp(CH6, T, 8)) FoundMask |= 1 << 6; else if (NewSize == 8 && !memcmp(CH7, T, 8)) FoundMask |= 1 << 7; } EXPECT_EQ(FoundMask, 255); } TEST(FuzzerMutate, ChangeBinaryInteger1) { TestChangeBinaryInteger(&MutationDispatcher::Mutate_ChangeBinaryInteger, 1 << 12); } TEST(FuzzerMutate, ChangeBinaryInteger2) { TestChangeBinaryInteger(&MutationDispatcher::Mutate, 1 << 15); } TEST(FuzzerDictionary, ParseOneDictionaryEntry) { Unit U; EXPECT_FALSE(ParseOneDictionaryEntry("", &U)); EXPECT_FALSE(ParseOneDictionaryEntry(" ", &U)); EXPECT_FALSE(ParseOneDictionaryEntry("\t ", &U)); EXPECT_FALSE(ParseOneDictionaryEntry(" \" ", &U)); EXPECT_FALSE(ParseOneDictionaryEntry(" zz\" ", &U)); EXPECT_FALSE(ParseOneDictionaryEntry(" \"zz ", &U)); EXPECT_FALSE(ParseOneDictionaryEntry(" \"\" ", &U)); EXPECT_TRUE(ParseOneDictionaryEntry("\"a\"", &U)); EXPECT_EQ(U, Unit({'a'})); EXPECT_TRUE(ParseOneDictionaryEntry("\"abc\"", &U)); EXPECT_EQ(U, Unit({'a', 'b', 'c'})); EXPECT_TRUE(ParseOneDictionaryEntry("abc=\"abc\"", &U)); EXPECT_EQ(U, Unit({'a', 'b', 'c'})); EXPECT_FALSE(ParseOneDictionaryEntry("\"\\\"", &U)); EXPECT_TRUE(ParseOneDictionaryEntry("\"\\\\\"", &U)); EXPECT_EQ(U, Unit({'\\'})); EXPECT_TRUE(ParseOneDictionaryEntry("\"\\xAB\"", &U)); EXPECT_EQ(U, Unit({0xAB})); EXPECT_TRUE(ParseOneDictionaryEntry("\"\\xABz\\xDE\"", &U)); EXPECT_EQ(U, Unit({0xAB, 'z', 0xDE})); EXPECT_TRUE(ParseOneDictionaryEntry("\"#\"", &U)); EXPECT_EQ(U, Unit({'#'})); EXPECT_TRUE(ParseOneDictionaryEntry("\"\\\"\"", &U)); EXPECT_EQ(U, Unit({'"'})); } TEST(FuzzerDictionary, ParseDictionaryFile) { std::vector<Unit> Units; EXPECT_FALSE(ParseDictionaryFile("zzz\n", &Units)); EXPECT_FALSE(ParseDictionaryFile("", &Units)); EXPECT_TRUE(ParseDictionaryFile("\n", &Units)); EXPECT_EQ(Units.size(), 0U); EXPECT_TRUE(ParseDictionaryFile("#zzzz a b c d\n", &Units)); EXPECT_EQ(Units.size(), 0U); EXPECT_TRUE(ParseDictionaryFile(" #zzzz\n", &Units)); EXPECT_EQ(Units.size(), 0U); EXPECT_TRUE(ParseDictionaryFile(" #zzzz\n", &Units)); EXPECT_EQ(Units.size(), 0U); EXPECT_TRUE(ParseDictionaryFile(" #zzzz\naaa=\"aa\"", &Units)); EXPECT_EQ(Units, std::vector<Unit>({Unit({'a', 'a'})})); EXPECT_TRUE( ParseDictionaryFile(" #zzzz\naaa=\"aa\"\n\nabc=\"abc\"", &Units)); EXPECT_EQ(Units, std::vector<Unit>({Unit({'a', 'a'}), Unit({'a', 'b', 'c'})})); } TEST(FuzzerUtil, Base64) { EXPECT_EQ("", Base64({})); EXPECT_EQ("YQ==", Base64({'a'})); EXPECT_EQ("eA==", Base64({'x'})); EXPECT_EQ("YWI=", Base64({'a', 'b'})); EXPECT_EQ("eHk=", Base64({'x', 'y'})); EXPECT_EQ("YWJj", Base64({'a', 'b', 'c'})); EXPECT_EQ("eHl6", Base64({'x', 'y', 'z'})); EXPECT_EQ("YWJjeA==", Base64({'a', 'b', 'c', 'x'})); EXPECT_EQ("YWJjeHk=", Base64({'a', 'b', 'c', 'x', 'y'})); EXPECT_EQ("YWJjeHl6", Base64({'a', 'b', 'c', 'x', 'y', 'z'})); } TEST(Corpus, Distribution) { Random Rand(0); InputCorpus C(""); size_t N = 10; size_t TriesPerUnit = 1<<16; for (size_t i = 0; i < N; i++) C.AddToCorpus(Unit{ static_cast<uint8_t>(i) }, 0); std::vector<size_t> Hist(N); for (size_t i = 0; i < N * TriesPerUnit; i++) { Hist[C.ChooseUnitIdxToMutate(Rand)]++; } for (size_t i = 0; i < N; i++) { // A weak sanity check that every unit gets invoked. EXPECT_GT(Hist[i], TriesPerUnit / N / 3); } } TEST(Merge, Bad) { const char *kInvalidInputs[] = { "", "x", "3\nx", "2\n3", "2\n2", "2\n2\nA\n", "2\n2\nA\nB\nC\n", "0\n0\n", "1\n1\nA\nDONE 0", "1\n1\nA\nSTARTED 1", }; Merger M; for (auto S : kInvalidInputs) { // fprintf(stderr, "TESTING:\n%s\n", S); EXPECT_FALSE(M.Parse(S, false)); } } void EQ(const std::vector<uint32_t> &A, const std::vector<uint32_t> &B) { EXPECT_EQ(A, B); } void EQ(const std::vector<std::string> &A, const std::vector<std::string> &B) { std::set<std::string> a(A.begin(), A.end()); std::set<std::string> b(B.begin(), B.end()); EXPECT_EQ(a, b); } static void Merge(const std::string &Input, const std::vector<std::string> Result, size_t NumNewFeatures) { Merger M; std::vector<std::string> NewFiles; EXPECT_TRUE(M.Parse(Input, true)); EXPECT_EQ(NumNewFeatures, M.Merge(&NewFiles)); EQ(NewFiles, Result); } TEST(Merge, Good) { Merger M; EXPECT_TRUE(M.Parse("1\n0\nAA\n", false)); EXPECT_EQ(M.Files.size(), 1U); EXPECT_EQ(M.NumFilesInFirstCorpus, 0U); EXPECT_EQ(M.Files[0].Name, "AA"); EXPECT_TRUE(M.LastFailure.empty()); EXPECT_EQ(M.FirstNotProcessedFile, 0U); EXPECT_TRUE(M.Parse("2\n1\nAA\nBB\nSTARTED 0 42\n", false)); EXPECT_EQ(M.Files.size(), 2U); EXPECT_EQ(M.NumFilesInFirstCorpus, 1U); EXPECT_EQ(M.Files[0].Name, "AA"); EXPECT_EQ(M.Files[1].Name, "BB"); EXPECT_EQ(M.LastFailure, "AA"); EXPECT_EQ(M.FirstNotProcessedFile, 1U); EXPECT_TRUE(M.Parse("3\n1\nAA\nBB\nC\n" "STARTED 0 1000\n" "DONE 0 1 2 3\n" "STARTED 1 1001\n" "DONE 1 4 5 6 \n" "STARTED 2 1002\n" "", true)); EXPECT_EQ(M.Files.size(), 3U); EXPECT_EQ(M.NumFilesInFirstCorpus, 1U); EXPECT_EQ(M.Files[0].Name, "AA"); EXPECT_EQ(M.Files[0].Size, 1000U); EXPECT_EQ(M.Files[1].Name, "BB"); EXPECT_EQ(M.Files[1].Size, 1001U); EXPECT_EQ(M.Files[2].Name, "C"); EXPECT_EQ(M.Files[2].Size, 1002U); EXPECT_EQ(M.LastFailure, "C"); EXPECT_EQ(M.FirstNotProcessedFile, 3U); EQ(M.Files[0].Features, {1, 2, 3}); EQ(M.Files[1].Features, {4, 5, 6}); std::vector<std::string> NewFiles; EXPECT_TRUE(M.Parse("3\n2\nAA\nBB\nC\n" "STARTED 0 1000\nDONE 0 1 2 3\n" "STARTED 1 1001\nDONE 1 4 5 6 \n" "STARTED 2 1002\nDONE 2 6 1 3 \n" "", true)); EXPECT_EQ(M.Files.size(), 3U); EXPECT_EQ(M.NumFilesInFirstCorpus, 2U); EXPECT_TRUE(M.LastFailure.empty()); EXPECT_EQ(M.FirstNotProcessedFile, 3U); EQ(M.Files[0].Features, {1, 2, 3}); EQ(M.Files[1].Features, {4, 5, 6}); EQ(M.Files[2].Features, {1, 3, 6}); EXPECT_EQ(0U, M.Merge(&NewFiles)); EQ(NewFiles, {}); EXPECT_TRUE(M.Parse("3\n1\nA\nB\nC\n" "STARTED 0 1000\nDONE 0 1 2 3\n" "STARTED 1 1001\nDONE 1 4 5 6 \n" "STARTED 2 1002\nDONE 2 6 1 3\n" "", true)); EQ(M.Files[0].Features, {1, 2, 3}); EQ(M.Files[1].Features, {4, 5, 6}); EQ(M.Files[2].Features, {1, 3, 6}); EXPECT_EQ(3U, M.Merge(&NewFiles)); EQ(NewFiles, {"B"}); } TEST(Merge, Merge) { Merge("3\n1\nA\nB\nC\n" "STARTED 0 1000\nDONE 0 1 2 3\n" "STARTED 1 1001\nDONE 1 4 5 6 \n" "STARTED 2 1002\nDONE 2 6 1 3 \n", {"B"}, 3); Merge("3\n0\nA\nB\nC\n" "STARTED 0 2000\nDONE 0 1 2 3\n" "STARTED 1 1001\nDONE 1 4 5 6 \n" "STARTED 2 1002\nDONE 2 6 1 3 \n", {"A", "B", "C"}, 6); Merge("4\n0\nA\nB\nC\nD\n" "STARTED 0 2000\nDONE 0 1 2 3\n" "STARTED 1 1101\nDONE 1 4 5 6 \n" "STARTED 2 1102\nDONE 2 6 1 3 100 \n" "STARTED 3 1000\nDONE 3 1 \n", {"A", "B", "C", "D"}, 7); Merge("4\n1\nA\nB\nC\nD\n" "STARTED 0 2000\nDONE 0 4 5 6 7 8\n" "STARTED 1 1100\nDONE 1 1 2 3 \n" "STARTED 2 1100\nDONE 2 2 3 \n" "STARTED 3 1000\nDONE 3 1 \n", {"B", "D"}, 3); }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SpamyTest.cpp
.cpp
527
22
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // The test spams to stderr and stdout. #include <assert.h> #include <cstdint> #include <cstdio> #include <cstddef> #include <iostream> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { assert(Data); printf("PRINTF_STDOUT\n"); fflush(stdout); fprintf(stderr, "PRINTF_STDERR\n"); std::cout << "STREAM_COUT\n"; std::cout.flush(); std::cerr << "STREAM_CERR\n"; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/LeakTimeoutTest.cpp
.cpp
396
18
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Test with a leak. #include <cstdint> #include <cstddef> static volatile int *Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (!Size) return 0; Sink = new int; Sink = new int; while (Sink) *Sink = 0; // Infinite loop. return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/Switch2Test.cpp
.cpp
852
36
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find the interesting switch value. #include <cstdint> #include <cstdlib> #include <cstdio> #include <cstring> #include <cstddef> int Switch(int a) { switch(a) { case 100001: return 1; case 100002: return 2; case 100003: return 4; } return 0; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { const int N = 3; if (Size < N * sizeof(int)) return 0; int Res = 0; for (int i = 0; i < N; i++) { int X; memcpy(&X, Data + i * sizeof(int), sizeof(int)); Res += Switch(X); } if (Res == 5 || Res == 3 || Res == 6 || Res == 7) { fprintf(stderr, "BINGO; Found the target, exiting; Res=%d\n", Res); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/SimpleDictionaryTest.cpp
.cpp
751
30
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. // The fuzzer must find a string based on dictionary words: // "Elvis" // "Presley" #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstring> #include <iostream> static volatile int Zero = 0; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { const char *Expected = "ElvisPresley"; if (Size < strlen(Expected)) return 0; size_t Match = 0; for (size_t i = 0; Expected[i]; i++) if (Expected[i] + Zero == Data[i]) Match++; if (Match == strlen(Expected)) { std::cout << "BINGO; Found the target, exiting\n"; exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/CustomMutatorTest.cpp
.cpp
962
39
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a cutom mutator. #include <assert.h> #include <cstdint> #include <cstdlib> #include <cstddef> #include <iostream> #include "FuzzerInterface.h" static volatile int Sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { assert(Data); if (Size > 0 && Data[0] == 'H') { Sink = 1; if (Size > 1 && Data[1] == 'i') { Sink = 2; if (Size > 2 && Data[2] == '!') { std::cout << "BINGO; Found the target, exiting\n"; exit(1); } } } return 0; } extern "C" size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) { static bool Printed; if (!Printed) { std::cerr << "In LLVMFuzzerCustomMutator\n"; Printed = true; } return LLVMFuzzerMutate(Data, Size, MaxSize); }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/StrcmpTest.cpp
.cpp
850
33
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Break through a series of strcmp. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cassert> bool Eq(const uint8_t *Data, size_t Size, const char *Str) { char Buff[1024]; size_t Len = strlen(Str); if (Size < Len) return false; if (Len >= sizeof(Buff)) return false; memcpy(Buff, (char*)Data, Len); Buff[Len] = 0; int res = strcmp(Buff, Str); return res == 0; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Eq(Data, Size, "ABC") && Size >= 3 && Eq(Data + 3, Size - 3, "QWER") && Size >= 7 && Eq(Data + 7, Size - 7, "ZXCVN") && Size >= 14 && Data[13] == 42 ) { fprintf(stderr, "BINGO\n"); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/UninstrumentedTest.cpp
.cpp
284
12
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // This test should not be instrumented. #include <cstdint> #include <cstddef> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/DSO1.cpp
.cpp
236
13
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Source code for a simple DSO. int DSO1(int a) { if (a < 123456) return 0; return 1; } void Uncovered1() { }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/CallerCalleeTest.cpp
.cpp
2,193
60
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. // Try to find the target using the indirect caller-callee pairs. #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstring> #include <iostream> typedef void (*F)(); static F t[256]; void f34() { std::cerr << "BINGO\n"; exit(1); } void f23() { t[(unsigned)'d'] = f34;} void f12() { t[(unsigned)'c'] = f23;} void f01() { t[(unsigned)'b'] = f12;} void f00() {} static F t0[256] = { f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, f00, }; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 4) return 0; // Spoof the counters. for (int i = 0; i < 200; i++) { f23(); f12(); f01(); } memcpy(t, t0, sizeof(t)); t[(unsigned)'a'] = f01; t[Data[0]](); t[Data[1]](); t[Data[2]](); t[Data[3]](); return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/StrncmpTest.cpp
.cpp
798
29
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. The fuzzer must find a particular string. #include <cstring> #include <cstdint> #include <cstdio> #include <cstdlib> static volatile int sink; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { // TODO: check other sizes. char *S = (char*)Data; if (Size >= 8 && strncmp(S, "123", 8)) sink = 1; if (Size >= 8 && strncmp(S, "01234567", 8) == 0) { if (Size >= 12 && strncmp(S + 8, "ABCD", 4) == 0) { if (Size >= 14 && strncmp(S + 12, "XY", 2) == 0) { if (Size >= 17 && strncmp(S + 14, "KLM", 3) == 0) { fprintf(stderr, "BINGO\n"); exit(1); } } } } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/Fuzzer/test/AbsNegAndConstantTest.cpp
.cpp
588
24
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // abs(x) < 0 and y == Const puzzle. #include <cstring> #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstdio> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 8) return 0; int x; unsigned y; memcpy(&x, Data, sizeof(x)); memcpy(&y, Data + sizeof(x), sizeof(y)); if (abs(x) < 0 && y == 0xbaddcafe) { printf("BINGO; Found the target, exiting; x = 0x%x y 0x%x\n", x, y); exit(1); } return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/doctest/doctest_compatibility.h
.h
1,789
38
#ifndef DOCTEST_COMPATIBILITY #define DOCTEST_COMPATIBILITY #define DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS #define DOCTEST_THREAD_LOCAL // enable single-threaded builds on XCode 6/7 - https://github.com/onqtam/doctest/issues/172 #include "doctest.h" // Catch doesn't require a semicolon after CAPTURE but doctest does #undef CAPTURE #define CAPTURE(x) DOCTEST_CAPTURE(x); // Sections from Catch are called Subcases in doctest and don't work with std::string by default #undef SUBCASE #define SECTION(x) DOCTEST_SUBCASE(x) // convenience macro around INFO since it doesn't support temporaries (it is optimized to avoid allocations for runtime speed) #define INFO_WITH_TEMP_IMPL(x, var_name) const auto var_name = x; INFO(var_name) // lvalue! #define INFO_WITH_TEMP(x) INFO_WITH_TEMP_IMPL(x, DOCTEST_ANONYMOUS(DOCTEST_STD_STRING_)) // doctest doesn't support THROWS_WITH for std::string out of the box (has to include <string>...) #define CHECK_THROWS_WITH_STD_STR_IMPL(expr, str, var_name) \ do { \ const std::string var_name = str; \ CHECK_THROWS_WITH(expr, var_name.c_str()); \ } while (false) #define CHECK_THROWS_WITH_STD_STR(expr, str) \ CHECK_THROWS_WITH_STD_STR_IMPL(expr, str, DOCTEST_ANONYMOUS(DOCTEST_STD_STRING_)) // included here because for some tests in the json repository private is defined as // public and if no STL header is included before that then in the json include when STL // stuff is included the MSVC STL complains (errors) that C++ keywords are being redefined #include <iosfwd> // Catch does this by default using doctest::Approx; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/thirdparty/doctest/doctest.h
.h
321,644
7,107
// ====================================================================== lgtm [cpp/missing-header-guard] // == DO NOT MODIFY THIS FILE BY HAND - IT IS AUTO GENERATED BY CMAKE! == // ====================================================================== // // doctest.h - the lightest feature-rich C++ single-header testing framework for unit tests and TDD // // Copyright (c) 2016-2023 Viktor Kirilov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // // The documentation can be found at the library's page: // https://github.com/doctest/doctest/blob/master/doc/markdown/readme.md // // ================================================================================================= // ================================================================================================= // ================================================================================================= // // The library is heavily influenced by Catch - https://github.com/catchorg/Catch2 // which uses the Boost Software License - Version 1.0 // see here - https://github.com/catchorg/Catch2/blob/master/LICENSE.txt // // The concept of subcases (sections in Catch) and expression decomposition are from there. // Some parts of the code are taken directly: // - stringification - the detection of "ostream& operator<<(ostream&, const T&)" and StringMaker<> // - the Approx() helper class for floating point comparison // - colors in the console // - breaking into a debugger // - signal / SEH handling // - timer // - XmlWriter class - thanks to Phil Nash for allowing the direct reuse (AKA copy/paste) // // The expression decomposing templates are taken from lest - https://github.com/martinmoene/lest // which uses the Boost Software License - Version 1.0 // see here - https://github.com/martinmoene/lest/blob/master/LICENSE.txt // // ================================================================================================= // ================================================================================================= // ================================================================================================= #ifndef DOCTEST_LIBRARY_INCLUDED #define DOCTEST_LIBRARY_INCLUDED // ================================================================================================= // == VERSION ====================================================================================== // ================================================================================================= #define DOCTEST_VERSION_MAJOR 2 #define DOCTEST_VERSION_MINOR 4 #define DOCTEST_VERSION_PATCH 11 // util we need here #define DOCTEST_TOSTR_IMPL(x) #x #define DOCTEST_TOSTR(x) DOCTEST_TOSTR_IMPL(x) #define DOCTEST_VERSION_STR \ DOCTEST_TOSTR(DOCTEST_VERSION_MAJOR) "." \ DOCTEST_TOSTR(DOCTEST_VERSION_MINOR) "." \ DOCTEST_TOSTR(DOCTEST_VERSION_PATCH) #define DOCTEST_VERSION \ (DOCTEST_VERSION_MAJOR * 10000 + DOCTEST_VERSION_MINOR * 100 + DOCTEST_VERSION_PATCH) // ================================================================================================= // == COMPILER VERSION ============================================================================= // ================================================================================================= // ideas for the version stuff are taken from here: https://github.com/cxxstuff/cxx_detect #ifdef _MSC_VER #define DOCTEST_CPLUSPLUS _MSVC_LANG #else #define DOCTEST_CPLUSPLUS __cplusplus #endif #define DOCTEST_COMPILER(MAJOR, MINOR, PATCH) ((MAJOR)*10000000 + (MINOR)*100000 + (PATCH)) // GCC/Clang and GCC/MSVC are mutually exclusive, but Clang/MSVC are not because of clang-cl... #if defined(_MSC_VER) && defined(_MSC_FULL_VER) #if _MSC_VER == _MSC_FULL_VER / 10000 #define DOCTEST_MSVC DOCTEST_COMPILER(_MSC_VER / 100, _MSC_VER % 100, _MSC_FULL_VER % 10000) #else // MSVC #define DOCTEST_MSVC \ DOCTEST_COMPILER(_MSC_VER / 100, (_MSC_FULL_VER / 100000) % 100, _MSC_FULL_VER % 100000) #endif // MSVC #endif // MSVC #if defined(__clang__) && defined(__clang_minor__) && defined(__clang_patchlevel__) #define DOCTEST_CLANG DOCTEST_COMPILER(__clang_major__, __clang_minor__, __clang_patchlevel__) #elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && \ !defined(__INTEL_COMPILER) #define DOCTEST_GCC DOCTEST_COMPILER(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #endif // GCC #if defined(__INTEL_COMPILER) #define DOCTEST_ICC DOCTEST_COMPILER(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) #endif // ICC #ifndef DOCTEST_MSVC #define DOCTEST_MSVC 0 #endif // DOCTEST_MSVC #ifndef DOCTEST_CLANG #define DOCTEST_CLANG 0 #endif // DOCTEST_CLANG #ifndef DOCTEST_GCC #define DOCTEST_GCC 0 #endif // DOCTEST_GCC #ifndef DOCTEST_ICC #define DOCTEST_ICC 0 #endif // DOCTEST_ICC // ================================================================================================= // == COMPILER WARNINGS HELPERS ==================================================================== // ================================================================================================= #if DOCTEST_CLANG && !DOCTEST_ICC #define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) #define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH _Pragma("clang diagnostic push") #define DOCTEST_CLANG_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(clang diagnostic ignored w) #define DOCTEST_CLANG_SUPPRESS_WARNING_POP _Pragma("clang diagnostic pop") #define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) \ DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING(w) #else // DOCTEST_CLANG #define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH #define DOCTEST_CLANG_SUPPRESS_WARNING(w) #define DOCTEST_CLANG_SUPPRESS_WARNING_POP #define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) #endif // DOCTEST_CLANG #if DOCTEST_GCC #define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) #define DOCTEST_GCC_SUPPRESS_WARNING_PUSH _Pragma("GCC diagnostic push") #define DOCTEST_GCC_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(GCC diagnostic ignored w) #define DOCTEST_GCC_SUPPRESS_WARNING_POP _Pragma("GCC diagnostic pop") #define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) \ DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING(w) #else // DOCTEST_GCC #define DOCTEST_GCC_SUPPRESS_WARNING_PUSH #define DOCTEST_GCC_SUPPRESS_WARNING(w) #define DOCTEST_GCC_SUPPRESS_WARNING_POP #define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) #endif // DOCTEST_GCC #if DOCTEST_MSVC #define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH __pragma(warning(push)) #define DOCTEST_MSVC_SUPPRESS_WARNING(w) __pragma(warning(disable : w)) #define DOCTEST_MSVC_SUPPRESS_WARNING_POP __pragma(warning(pop)) #define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) \ DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(w) #else // DOCTEST_MSVC #define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH #define DOCTEST_MSVC_SUPPRESS_WARNING(w) #define DOCTEST_MSVC_SUPPRESS_WARNING_POP #define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) #endif // DOCTEST_MSVC // ================================================================================================= // == COMPILER WARNINGS ============================================================================ // ================================================================================================= // both the header and the implementation suppress all of these, // so it only makes sense to aggregate them like so #define DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH \ DOCTEST_CLANG_SUPPRESS_WARNING_PUSH \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wunknown-pragmas") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wweak-vtables") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wpadded") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-prototypes") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic") \ \ DOCTEST_GCC_SUPPRESS_WARNING_PUSH \ DOCTEST_GCC_SUPPRESS_WARNING("-Wunknown-pragmas") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wpragmas") \ DOCTEST_GCC_SUPPRESS_WARNING("-Weffc++") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-overflow") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-aliasing") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-declarations") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wuseless-cast") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wnoexcept") \ \ DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ /* these 4 also disabled globally via cmake: */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4514) /* unreferenced inline function has been removed */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4571) /* SEH related */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4710) /* function not inlined */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4711) /* function selected for inline expansion*/ \ /* common ones */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4616) /* invalid compiler warning */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4619) /* invalid compiler warning */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4996) /* The compiler encountered a deprecated declaration */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4706) /* assignment within conditional expression */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4512) /* 'class' : assignment operator could not be generated */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4127) /* conditional expression is constant */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4820) /* padding */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4625) /* copy constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4626) /* assignment operator was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5027) /* move assignment operator implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5026) /* move constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4640) /* construction of local static object not thread-safe */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5045) /* Spectre mitigation for memory load */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5264) /* 'variable-name': 'const' variable is not used */ \ /* static analysis */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26439) /* Function may not throw. Declare it 'noexcept' */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26495) /* Always initialize a member variable */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26451) /* Arithmetic overflow ... */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26444) /* Avoid unnamed objects with custom ctor and dtor... */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26812) /* Prefer 'enum class' over 'enum' */ #define DOCTEST_SUPPRESS_COMMON_WARNINGS_POP \ DOCTEST_CLANG_SUPPRESS_WARNING_POP \ DOCTEST_GCC_SUPPRESS_WARNING_POP \ DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wnon-virtual-dtor") DOCTEST_CLANG_SUPPRESS_WARNING("-Wdeprecated") DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wctor-dtor-privacy") DOCTEST_GCC_SUPPRESS_WARNING("-Wnon-virtual-dtor") DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-promo") DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(4623) // default constructor was implicitly defined as deleted #define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN \ DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ DOCTEST_MSVC_SUPPRESS_WARNING(4548) /* before comma no effect; expected side - effect */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4265) /* virtual functions, but destructor is not virtual */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4986) /* exception specification does not match previous */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4350) /* 'member1' called instead of 'member2' */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4668) /* not defined as a preprocessor macro */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4365) /* signed/unsigned mismatch */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4774) /* format string not a string literal */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4820) /* padding */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4625) /* copy constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4626) /* assignment operator was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5027) /* move assignment operator implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5026) /* move constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4623) /* default constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5039) /* pointer to pot. throwing function passed to extern C */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5045) /* Spectre mitigation for memory load */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5105) /* macro producing 'defined' has undefined behavior */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4738) /* storing float result in memory, loss of performance */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5262) /* implicit fall-through */ #define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END DOCTEST_MSVC_SUPPRESS_WARNING_POP // ================================================================================================= // == FEATURE DETECTION ============================================================================ // ================================================================================================= // general compiler feature support table: https://en.cppreference.com/w/cpp/compiler_support // MSVC C++11 feature support table: https://msdn.microsoft.com/en-us/library/hh567368.aspx // GCC C++11 feature support table: https://gcc.gnu.org/projects/cxx-status.html // MSVC version table: // https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering // MSVC++ 14.3 (17) _MSC_VER == 1930 (Visual Studio 2022) // MSVC++ 14.2 (16) _MSC_VER == 1920 (Visual Studio 2019) // MSVC++ 14.1 (15) _MSC_VER == 1910 (Visual Studio 2017) // MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) // MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) // MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) // MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) // MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) // MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) // Universal Windows Platform support #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) #define DOCTEST_CONFIG_NO_WINDOWS_SEH #endif // WINAPI_FAMILY #if DOCTEST_MSVC && !defined(DOCTEST_CONFIG_WINDOWS_SEH) #define DOCTEST_CONFIG_WINDOWS_SEH #endif // MSVC #if defined(DOCTEST_CONFIG_NO_WINDOWS_SEH) && defined(DOCTEST_CONFIG_WINDOWS_SEH) #undef DOCTEST_CONFIG_WINDOWS_SEH #endif // DOCTEST_CONFIG_NO_WINDOWS_SEH #if !defined(_WIN32) && !defined(__QNX__) && !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && \ !defined(__EMSCRIPTEN__) && !defined(__wasi__) #define DOCTEST_CONFIG_POSIX_SIGNALS #endif // _WIN32 #if defined(DOCTEST_CONFIG_NO_POSIX_SIGNALS) && defined(DOCTEST_CONFIG_POSIX_SIGNALS) #undef DOCTEST_CONFIG_POSIX_SIGNALS #endif // DOCTEST_CONFIG_NO_POSIX_SIGNALS #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #if !defined(__cpp_exceptions) && !defined(__EXCEPTIONS) && !defined(_CPPUNWIND) \ || defined(__wasi__) #define DOCTEST_CONFIG_NO_EXCEPTIONS #endif // no exceptions #endif // DOCTEST_CONFIG_NO_EXCEPTIONS #ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #define DOCTEST_CONFIG_NO_EXCEPTIONS #endif // DOCTEST_CONFIG_NO_EXCEPTIONS #endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #if defined(DOCTEST_CONFIG_NO_EXCEPTIONS) && !defined(DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS) #define DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #endif // DOCTEST_CONFIG_NO_EXCEPTIONS && !DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #ifdef __wasi__ #define DOCTEST_CONFIG_NO_MULTITHREADING #endif #if defined(DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN) && !defined(DOCTEST_CONFIG_IMPLEMENT) #define DOCTEST_CONFIG_IMPLEMENT #endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #if defined(_WIN32) || defined(__CYGWIN__) #if DOCTEST_MSVC #define DOCTEST_SYMBOL_EXPORT __declspec(dllexport) #define DOCTEST_SYMBOL_IMPORT __declspec(dllimport) #else // MSVC #define DOCTEST_SYMBOL_EXPORT __attribute__((dllexport)) #define DOCTEST_SYMBOL_IMPORT __attribute__((dllimport)) #endif // MSVC #else // _WIN32 #define DOCTEST_SYMBOL_EXPORT __attribute__((visibility("default"))) #define DOCTEST_SYMBOL_IMPORT #endif // _WIN32 #ifdef DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL #ifdef DOCTEST_CONFIG_IMPLEMENT #define DOCTEST_INTERFACE DOCTEST_SYMBOL_EXPORT #else // DOCTEST_CONFIG_IMPLEMENT #define DOCTEST_INTERFACE DOCTEST_SYMBOL_IMPORT #endif // DOCTEST_CONFIG_IMPLEMENT #else // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL #define DOCTEST_INTERFACE #endif // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL // needed for extern template instantiations // see https://github.com/fmtlib/fmt/issues/2228 #if DOCTEST_MSVC #define DOCTEST_INTERFACE_DECL #define DOCTEST_INTERFACE_DEF DOCTEST_INTERFACE #else // DOCTEST_MSVC #define DOCTEST_INTERFACE_DECL DOCTEST_INTERFACE #define DOCTEST_INTERFACE_DEF #endif // DOCTEST_MSVC #define DOCTEST_EMPTY #if DOCTEST_MSVC #define DOCTEST_NOINLINE __declspec(noinline) #define DOCTEST_UNUSED #define DOCTEST_ALIGNMENT(x) #elif DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 5, 0) #define DOCTEST_NOINLINE #define DOCTEST_UNUSED #define DOCTEST_ALIGNMENT(x) #else #define DOCTEST_NOINLINE __attribute__((noinline)) #define DOCTEST_UNUSED __attribute__((unused)) #define DOCTEST_ALIGNMENT(x) __attribute__((aligned(x))) #endif #ifdef DOCTEST_CONFIG_NO_CONTRADICTING_INLINE #define DOCTEST_INLINE_NOINLINE inline #else #define DOCTEST_INLINE_NOINLINE inline DOCTEST_NOINLINE #endif #ifndef DOCTEST_NORETURN #if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) #define DOCTEST_NORETURN #else // DOCTEST_MSVC #define DOCTEST_NORETURN [[noreturn]] #endif // DOCTEST_MSVC #endif // DOCTEST_NORETURN #ifndef DOCTEST_NOEXCEPT #if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) #define DOCTEST_NOEXCEPT #else // DOCTEST_MSVC #define DOCTEST_NOEXCEPT noexcept #endif // DOCTEST_MSVC #endif // DOCTEST_NOEXCEPT #ifndef DOCTEST_CONSTEXPR #if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) #define DOCTEST_CONSTEXPR const #define DOCTEST_CONSTEXPR_FUNC inline #else // DOCTEST_MSVC #define DOCTEST_CONSTEXPR constexpr #define DOCTEST_CONSTEXPR_FUNC constexpr #endif // DOCTEST_MSVC #endif // DOCTEST_CONSTEXPR #ifndef DOCTEST_NO_SANITIZE_INTEGER #if DOCTEST_CLANG >= DOCTEST_COMPILER(3, 7, 0) #define DOCTEST_NO_SANITIZE_INTEGER __attribute__((no_sanitize("integer"))) #else #define DOCTEST_NO_SANITIZE_INTEGER #endif #endif // DOCTEST_NO_SANITIZE_INTEGER // ================================================================================================= // == FEATURE DETECTION END ======================================================================== // ================================================================================================= #define DOCTEST_DECLARE_INTERFACE(name) \ virtual ~name(); \ name() = default; \ name(const name&) = delete; \ name(name&&) = delete; \ name& operator=(const name&) = delete; \ name& operator=(name&&) = delete; #define DOCTEST_DEFINE_INTERFACE(name) \ name::~name() = default; // internal macros for string concatenation and anonymous variable name generation #define DOCTEST_CAT_IMPL(s1, s2) s1##s2 #define DOCTEST_CAT(s1, s2) DOCTEST_CAT_IMPL(s1, s2) #ifdef __COUNTER__ // not standard and may be missing for some compilers #define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __COUNTER__) #else // __COUNTER__ #define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __LINE__) #endif // __COUNTER__ #ifndef DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE #define DOCTEST_REF_WRAP(x) x& #else // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE #define DOCTEST_REF_WRAP(x) x #endif // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE // not using __APPLE__ because... this is how Catch does it #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED #define DOCTEST_PLATFORM_MAC #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #define DOCTEST_PLATFORM_IPHONE #elif defined(_WIN32) #define DOCTEST_PLATFORM_WINDOWS #elif defined(__wasi__) #define DOCTEST_PLATFORM_WASI #else // DOCTEST_PLATFORM #define DOCTEST_PLATFORM_LINUX #endif // DOCTEST_PLATFORM namespace doctest { namespace detail { static DOCTEST_CONSTEXPR int consume(const int*, int) noexcept { return 0; } }} #define DOCTEST_GLOBAL_NO_WARNINGS(var, ...) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wglobal-constructors") \ static const int var = doctest::detail::consume(&var, __VA_ARGS__); \ DOCTEST_CLANG_SUPPRESS_WARNING_POP #ifndef DOCTEST_BREAK_INTO_DEBUGGER // should probably take a look at https://github.com/scottt/debugbreak #ifdef DOCTEST_PLATFORM_LINUX #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) // Break at the location of the failing check if possible #define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT(hicpp-no-assembler) #else #include <signal.h> #define DOCTEST_BREAK_INTO_DEBUGGER() raise(SIGTRAP) #endif #elif defined(DOCTEST_PLATFORM_MAC) #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) #define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT(hicpp-no-assembler) #elif defined(__ppc__) || defined(__ppc64__) // https://www.cocoawithlove.com/2008/03/break-into-debugger.html #define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n": : : "memory","r0","r3","r4") // NOLINT(hicpp-no-assembler) #else #define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("brk #0"); // NOLINT(hicpp-no-assembler) #endif #elif DOCTEST_MSVC #define DOCTEST_BREAK_INTO_DEBUGGER() __debugbreak() #elif defined(__MINGW32__) DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wredundant-decls") extern "C" __declspec(dllimport) void __stdcall DebugBreak(); DOCTEST_GCC_SUPPRESS_WARNING_POP #define DOCTEST_BREAK_INTO_DEBUGGER() ::DebugBreak() #else // linux #define DOCTEST_BREAK_INTO_DEBUGGER() (static_cast<void>(0)) #endif // linux #endif // DOCTEST_BREAK_INTO_DEBUGGER // this is kept here for backwards compatibility since the config option was changed #ifdef DOCTEST_CONFIG_USE_IOSFWD #ifndef DOCTEST_CONFIG_USE_STD_HEADERS #define DOCTEST_CONFIG_USE_STD_HEADERS #endif #endif // DOCTEST_CONFIG_USE_IOSFWD // for clang - always include ciso646 (which drags some std stuff) because // we want to check if we are using libc++ with the _LIBCPP_VERSION macro in // which case we don't want to forward declare stuff from std - for reference: // https://github.com/doctest/doctest/issues/126 // https://github.com/doctest/doctest/issues/356 #if DOCTEST_CLANG #include <ciso646> #endif // clang #ifdef _LIBCPP_VERSION #ifndef DOCTEST_CONFIG_USE_STD_HEADERS #define DOCTEST_CONFIG_USE_STD_HEADERS #endif #endif // _LIBCPP_VERSION #ifdef DOCTEST_CONFIG_USE_STD_HEADERS #ifndef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS #define DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN #include <cstddef> #include <ostream> #include <istream> DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END #else // DOCTEST_CONFIG_USE_STD_HEADERS // Forward declaring 'X' in namespace std is not permitted by the C++ Standard. DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4643) namespace std { // NOLINT(cert-dcl58-cpp) typedef decltype(nullptr) nullptr_t; // NOLINT(modernize-use-using) typedef decltype(sizeof(void*)) size_t; // NOLINT(modernize-use-using) template <class charT> struct char_traits; template <> struct char_traits<char>; template <class charT, class traits> class basic_ostream; // NOLINT(fuchsia-virtual-inheritance) typedef basic_ostream<char, char_traits<char>> ostream; // NOLINT(modernize-use-using) template<class traits> // NOLINTNEXTLINE basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const char*); template <class charT, class traits> class basic_istream; typedef basic_istream<char, char_traits<char>> istream; // NOLINT(modernize-use-using) template <class... Types> class tuple; #if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) // see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 template <class Ty> class allocator; template <class Elem, class Traits, class Alloc> class basic_string; using string = basic_string<char, char_traits<char>, allocator<char>>; #endif // VS 2019 } // namespace std DOCTEST_MSVC_SUPPRESS_WARNING_POP #endif // DOCTEST_CONFIG_USE_STD_HEADERS #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS #include <type_traits> #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS namespace doctest { using std::size_t; DOCTEST_INTERFACE extern bool is_running_in_test; #ifndef DOCTEST_CONFIG_STRING_SIZE_TYPE #define DOCTEST_CONFIG_STRING_SIZE_TYPE unsigned #endif // A 24 byte string class (can be as small as 17 for x64 and 13 for x86) that can hold strings with length // of up to 23 chars on the stack before going on the heap - the last byte of the buffer is used for: // - "is small" bit - the highest bit - if "0" then it is small - otherwise its "1" (128) // - if small - capacity left before going on the heap - using the lowest 5 bits // - if small - 2 bits are left unused - the second and third highest ones // - if small - acts as a null terminator if strlen() is 23 (24 including the null terminator) // and the "is small" bit remains "0" ("as well as the capacity left") so its OK // Idea taken from this lecture about the string implementation of facebook/folly - fbstring // https://www.youtube.com/watch?v=kPR8h4-qZdk // TODO: // - optimizations - like not deleting memory unnecessarily in operator= and etc. // - resize/reserve/clear // - replace // - back/front // - iterator stuff // - find & friends // - push_back/pop_back // - assign/insert/erase // - relational operators as free functions - taking const char* as one of the params class DOCTEST_INTERFACE String { public: using size_type = DOCTEST_CONFIG_STRING_SIZE_TYPE; private: static DOCTEST_CONSTEXPR size_type len = 24; //!OCLINT avoid private static members static DOCTEST_CONSTEXPR size_type last = len - 1; //!OCLINT avoid private static members struct view // len should be more than sizeof(view) - because of the final byte for flags { char* ptr; size_type size; size_type capacity; }; union { char buf[len]; // NOLINT(*-avoid-c-arrays) view data; }; char* allocate(size_type sz); bool isOnStack() const noexcept { return (buf[last] & 128) == 0; } void setOnHeap() noexcept; void setLast(size_type in = last) noexcept; void setSize(size_type sz) noexcept; void copy(const String& other); public: static DOCTEST_CONSTEXPR size_type npos = static_cast<size_type>(-1); String() noexcept; ~String(); // cppcheck-suppress noExplicitConstructor String(const char* in); String(const char* in, size_type in_size); String(std::istream& in, size_type in_size); String(const String& other); String& operator=(const String& other); String& operator+=(const String& other); String(String&& other) noexcept; String& operator=(String&& other) noexcept; char operator[](size_type i) const; char& operator[](size_type i); // the only functions I'm willing to leave in the interface - available for inlining const char* c_str() const { return const_cast<String*>(this)->c_str(); } // NOLINT char* c_str() { if (isOnStack()) { return reinterpret_cast<char*>(buf); } return data.ptr; } size_type size() const; size_type capacity() const; String substr(size_type pos, size_type cnt = npos) &&; String substr(size_type pos, size_type cnt = npos) const &; size_type find(char ch, size_type pos = 0) const; size_type rfind(char ch, size_type pos = npos) const; int compare(const char* other, bool no_case = false) const; int compare(const String& other, bool no_case = false) const; friend DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, const String& in); }; DOCTEST_INTERFACE String operator+(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator==(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator!=(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator<(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator>(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator<=(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator>=(const String& lhs, const String& rhs); class DOCTEST_INTERFACE Contains { public: explicit Contains(const String& string); bool checkWith(const String& other) const; String string; }; DOCTEST_INTERFACE String toString(const Contains& in); DOCTEST_INTERFACE bool operator==(const String& lhs, const Contains& rhs); DOCTEST_INTERFACE bool operator==(const Contains& lhs, const String& rhs); DOCTEST_INTERFACE bool operator!=(const String& lhs, const Contains& rhs); DOCTEST_INTERFACE bool operator!=(const Contains& lhs, const String& rhs); namespace Color { enum Enum { None = 0, White, Red, Green, Blue, Cyan, Yellow, Grey, Bright = 0x10, BrightRed = Bright | Red, BrightGreen = Bright | Green, LightGrey = Bright | Grey, BrightWhite = Bright | White }; DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, Color::Enum code); } // namespace Color namespace assertType { enum Enum { // macro traits is_warn = 1, is_check = 2 * is_warn, is_require = 2 * is_check, is_normal = 2 * is_require, is_throws = 2 * is_normal, is_throws_as = 2 * is_throws, is_throws_with = 2 * is_throws_as, is_nothrow = 2 * is_throws_with, is_false = 2 * is_nothrow, is_unary = 2 * is_false, // not checked anywhere - used just to distinguish the types is_eq = 2 * is_unary, is_ne = 2 * is_eq, is_lt = 2 * is_ne, is_gt = 2 * is_lt, is_ge = 2 * is_gt, is_le = 2 * is_ge, // macro types DT_WARN = is_normal | is_warn, DT_CHECK = is_normal | is_check, DT_REQUIRE = is_normal | is_require, DT_WARN_FALSE = is_normal | is_false | is_warn, DT_CHECK_FALSE = is_normal | is_false | is_check, DT_REQUIRE_FALSE = is_normal | is_false | is_require, DT_WARN_THROWS = is_throws | is_warn, DT_CHECK_THROWS = is_throws | is_check, DT_REQUIRE_THROWS = is_throws | is_require, DT_WARN_THROWS_AS = is_throws_as | is_warn, DT_CHECK_THROWS_AS = is_throws_as | is_check, DT_REQUIRE_THROWS_AS = is_throws_as | is_require, DT_WARN_THROWS_WITH = is_throws_with | is_warn, DT_CHECK_THROWS_WITH = is_throws_with | is_check, DT_REQUIRE_THROWS_WITH = is_throws_with | is_require, DT_WARN_THROWS_WITH_AS = is_throws_with | is_throws_as | is_warn, DT_CHECK_THROWS_WITH_AS = is_throws_with | is_throws_as | is_check, DT_REQUIRE_THROWS_WITH_AS = is_throws_with | is_throws_as | is_require, DT_WARN_NOTHROW = is_nothrow | is_warn, DT_CHECK_NOTHROW = is_nothrow | is_check, DT_REQUIRE_NOTHROW = is_nothrow | is_require, DT_WARN_EQ = is_normal | is_eq | is_warn, DT_CHECK_EQ = is_normal | is_eq | is_check, DT_REQUIRE_EQ = is_normal | is_eq | is_require, DT_WARN_NE = is_normal | is_ne | is_warn, DT_CHECK_NE = is_normal | is_ne | is_check, DT_REQUIRE_NE = is_normal | is_ne | is_require, DT_WARN_GT = is_normal | is_gt | is_warn, DT_CHECK_GT = is_normal | is_gt | is_check, DT_REQUIRE_GT = is_normal | is_gt | is_require, DT_WARN_LT = is_normal | is_lt | is_warn, DT_CHECK_LT = is_normal | is_lt | is_check, DT_REQUIRE_LT = is_normal | is_lt | is_require, DT_WARN_GE = is_normal | is_ge | is_warn, DT_CHECK_GE = is_normal | is_ge | is_check, DT_REQUIRE_GE = is_normal | is_ge | is_require, DT_WARN_LE = is_normal | is_le | is_warn, DT_CHECK_LE = is_normal | is_le | is_check, DT_REQUIRE_LE = is_normal | is_le | is_require, DT_WARN_UNARY = is_normal | is_unary | is_warn, DT_CHECK_UNARY = is_normal | is_unary | is_check, DT_REQUIRE_UNARY = is_normal | is_unary | is_require, DT_WARN_UNARY_FALSE = is_normal | is_false | is_unary | is_warn, DT_CHECK_UNARY_FALSE = is_normal | is_false | is_unary | is_check, DT_REQUIRE_UNARY_FALSE = is_normal | is_false | is_unary | is_require, }; } // namespace assertType DOCTEST_INTERFACE const char* assertString(assertType::Enum at); DOCTEST_INTERFACE const char* failureString(assertType::Enum at); DOCTEST_INTERFACE const char* skipPathFromFilename(const char* file); struct DOCTEST_INTERFACE TestCaseData { String m_file; // the file in which the test was registered (using String - see #350) unsigned m_line; // the line where the test was registered const char* m_name; // name of the test case const char* m_test_suite; // the test suite in which the test was added const char* m_description; bool m_skip; bool m_no_breaks; bool m_no_output; bool m_may_fail; bool m_should_fail; int m_expected_failures; double m_timeout; }; struct DOCTEST_INTERFACE AssertData { // common - for all asserts const TestCaseData* m_test_case; assertType::Enum m_at; const char* m_file; int m_line; const char* m_expr; bool m_failed; // exception-related - for all asserts bool m_threw; String m_exception; // for normal asserts String m_decomp; // for specific exception-related asserts bool m_threw_as; const char* m_exception_type; class DOCTEST_INTERFACE StringContains { private: Contains content; bool isContains; public: StringContains(const String& str) : content(str), isContains(false) { } StringContains(Contains cntn) : content(static_cast<Contains&&>(cntn)), isContains(true) { } bool check(const String& str) { return isContains ? (content == str) : (content.string == str); } operator const String&() const { return content.string; } const char* c_str() const { return content.string.c_str(); } } m_exception_string; AssertData(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const StringContains& exception_string); }; struct DOCTEST_INTERFACE MessageData { String m_string; const char* m_file; int m_line; assertType::Enum m_severity; }; struct DOCTEST_INTERFACE SubcaseSignature { String m_name; const char* m_file; int m_line; bool operator==(const SubcaseSignature& other) const; bool operator<(const SubcaseSignature& other) const; }; struct DOCTEST_INTERFACE IContextScope { DOCTEST_DECLARE_INTERFACE(IContextScope) virtual void stringify(std::ostream*) const = 0; }; namespace detail { struct DOCTEST_INTERFACE TestCase; } // namespace detail struct ContextOptions //!OCLINT too many fields { std::ostream* cout = nullptr; // stdout stream String binary_name; // the test binary name const detail::TestCase* currentTest = nullptr; // == parameters from the command line String out; // output filename String order_by; // how tests should be ordered unsigned rand_seed; // the seed for rand ordering unsigned first; // the first (matching) test to be executed unsigned last; // the last (matching) test to be executed int abort_after; // stop tests after this many failed assertions int subcase_filter_levels; // apply the subcase filters for the first N levels bool success; // include successful assertions in output bool case_sensitive; // if filtering should be case sensitive bool exit; // if the program should be exited after the tests are ran/whatever bool duration; // print the time duration of each test case bool minimal; // minimal console output (only test failures) bool quiet; // no console output bool no_throw; // to skip exceptions-related assertion macros bool no_exitcode; // if the framework should return 0 as the exitcode bool no_run; // to not run the tests at all (can be done with an "*" exclude) bool no_intro; // to not print the intro of the framework bool no_version; // to not print the version of the framework bool no_colors; // if output to the console should be colorized bool force_colors; // forces the use of colors even when a tty cannot be detected bool no_breaks; // to not break into the debugger bool no_skip; // don't skip test cases which are marked to be skipped bool gnu_file_line; // if line numbers should be surrounded with :x: and not (x): bool no_path_in_filenames; // if the path to files should be removed from the output bool no_line_numbers; // if source code line numbers should be omitted from the output bool no_debug_output; // no output in the debug console when a debugger is attached bool no_skipped_summary; // don't print "skipped" in the summary !!! UNDOCUMENTED !!! bool no_time_in_output; // omit any time/timestamps from output !!! UNDOCUMENTED !!! bool help; // to print the help bool version; // to print the version bool count; // if only the count of matching tests is to be retrieved bool list_test_cases; // to list all tests matching the filters bool list_test_suites; // to list all suites matching the filters bool list_reporters; // lists all registered reporters }; namespace detail { namespace types { #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS using namespace std; #else template <bool COND, typename T = void> struct enable_if { }; template <typename T> struct enable_if<true, T> { using type = T; }; struct true_type { static DOCTEST_CONSTEXPR bool value = true; }; struct false_type { static DOCTEST_CONSTEXPR bool value = false; }; template <typename T> struct remove_reference { using type = T; }; template <typename T> struct remove_reference<T&> { using type = T; }; template <typename T> struct remove_reference<T&&> { using type = T; }; template <typename T> struct is_rvalue_reference : false_type { }; template <typename T> struct is_rvalue_reference<T&&> : true_type { }; template<typename T> struct remove_const { using type = T; }; template <typename T> struct remove_const<const T> { using type = T; }; // Compiler intrinsics template <typename T> struct is_enum { static DOCTEST_CONSTEXPR bool value = __is_enum(T); }; template <typename T> struct underlying_type { using type = __underlying_type(T); }; template <typename T> struct is_pointer : false_type { }; template <typename T> struct is_pointer<T*> : true_type { }; template <typename T> struct is_array : false_type { }; // NOLINTNEXTLINE(*-avoid-c-arrays) template <typename T, size_t SIZE> struct is_array<T[SIZE]> : true_type { }; #endif } // <utility> template <typename T> T&& declval(); template <class T> DOCTEST_CONSTEXPR_FUNC T&& forward(typename types::remove_reference<T>::type& t) DOCTEST_NOEXCEPT { return static_cast<T&&>(t); } template <class T> DOCTEST_CONSTEXPR_FUNC T&& forward(typename types::remove_reference<T>::type&& t) DOCTEST_NOEXCEPT { return static_cast<T&&>(t); } template <typename T> struct deferred_false : types::false_type { }; // MSVS 2015 :( #if !DOCTEST_CLANG && defined(_MSC_VER) && _MSC_VER <= 1900 template <typename T, typename = void> struct has_global_insertion_operator : types::false_type { }; template <typename T> struct has_global_insertion_operator<T, decltype(::operator<<(declval<std::ostream&>(), declval<const T&>()), void())> : types::true_type { }; template <typename T, typename = void> struct has_insertion_operator { static DOCTEST_CONSTEXPR bool value = has_global_insertion_operator<T>::value; }; template <typename T, bool global> struct insert_hack; template <typename T> struct insert_hack<T, true> { static void insert(std::ostream& os, const T& t) { ::operator<<(os, t); } }; template <typename T> struct insert_hack<T, false> { static void insert(std::ostream& os, const T& t) { operator<<(os, t); } }; template <typename T> using insert_hack_t = insert_hack<T, has_global_insertion_operator<T>::value>; #else template <typename T, typename = void> struct has_insertion_operator : types::false_type { }; #endif template <typename T> struct has_insertion_operator<T, decltype(operator<<(declval<std::ostream&>(), declval<const T&>()), void())> : types::true_type { }; template <typename T> struct should_stringify_as_underlying_type { static DOCTEST_CONSTEXPR bool value = detail::types::is_enum<T>::value && !doctest::detail::has_insertion_operator<T>::value; }; DOCTEST_INTERFACE std::ostream* tlssPush(); DOCTEST_INTERFACE String tlssPop(); template <bool C> struct StringMakerBase { template <typename T> static String convert(const DOCTEST_REF_WRAP(T)) { #ifdef DOCTEST_CONFIG_REQUIRE_STRINGIFICATION_FOR_ALL_USED_TYPES static_assert(deferred_false<T>::value, "No stringification detected for type T. See string conversion manual"); #endif return "{?}"; } }; template <typename T> struct filldata; template <typename T> void filloss(std::ostream* stream, const T& in) { filldata<T>::fill(stream, in); } template <typename T, size_t N> void filloss(std::ostream* stream, const T (&in)[N]) { // NOLINT(*-avoid-c-arrays) // T[N], T(&)[N], T(&&)[N] have same behaviour. // Hence remove reference. filloss<typename types::remove_reference<decltype(in)>::type>(stream, in); } template <typename T> String toStream(const T& in) { std::ostream* stream = tlssPush(); filloss(stream, in); return tlssPop(); } template <> struct StringMakerBase<true> { template <typename T> static String convert(const DOCTEST_REF_WRAP(T) in) { return toStream(in); } }; } // namespace detail template <typename T> struct StringMaker : public detail::StringMakerBase< detail::has_insertion_operator<T>::value || detail::types::is_pointer<T>::value || detail::types::is_array<T>::value> {}; #ifndef DOCTEST_STRINGIFY #ifdef DOCTEST_CONFIG_DOUBLE_STRINGIFY #define DOCTEST_STRINGIFY(...) toString(toString(__VA_ARGS__)) #else #define DOCTEST_STRINGIFY(...) toString(__VA_ARGS__) #endif #endif template <typename T> String toString() { #if DOCTEST_CLANG == 0 && DOCTEST_GCC == 0 && DOCTEST_ICC == 0 String ret = __FUNCSIG__; // class doctest::String __cdecl doctest::toString<TYPE>(void) String::size_type beginPos = ret.find('<'); return ret.substr(beginPos + 1, ret.size() - beginPos - static_cast<String::size_type>(sizeof(">(void)"))); #else String ret = __PRETTY_FUNCTION__; // doctest::String toString() [with T = TYPE] String::size_type begin = ret.find('=') + 2; return ret.substr(begin, ret.size() - begin - 1); #endif } template <typename T, typename detail::types::enable_if<!detail::should_stringify_as_underlying_type<T>::value, bool>::type = true> String toString(const DOCTEST_REF_WRAP(T) value) { return StringMaker<T>::convert(value); } #ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING DOCTEST_INTERFACE String toString(const char* in); #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) // see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 DOCTEST_INTERFACE String toString(const std::string& in); #endif // VS 2019 DOCTEST_INTERFACE String toString(String in); DOCTEST_INTERFACE String toString(std::nullptr_t); DOCTEST_INTERFACE String toString(bool in); DOCTEST_INTERFACE String toString(float in); DOCTEST_INTERFACE String toString(double in); DOCTEST_INTERFACE String toString(double long in); DOCTEST_INTERFACE String toString(char in); DOCTEST_INTERFACE String toString(char signed in); DOCTEST_INTERFACE String toString(char unsigned in); DOCTEST_INTERFACE String toString(short in); DOCTEST_INTERFACE String toString(short unsigned in); DOCTEST_INTERFACE String toString(signed in); DOCTEST_INTERFACE String toString(unsigned in); DOCTEST_INTERFACE String toString(long in); DOCTEST_INTERFACE String toString(long unsigned in); DOCTEST_INTERFACE String toString(long long in); DOCTEST_INTERFACE String toString(long long unsigned in); template <typename T, typename detail::types::enable_if<detail::should_stringify_as_underlying_type<T>::value, bool>::type = true> String toString(const DOCTEST_REF_WRAP(T) value) { using UT = typename detail::types::underlying_type<T>::type; return (DOCTEST_STRINGIFY(static_cast<UT>(value))); } namespace detail { template <typename T> struct filldata { static void fill(std::ostream* stream, const T& in) { #if defined(_MSC_VER) && _MSC_VER <= 1900 insert_hack_t<T>::insert(*stream, in); #else operator<<(*stream, in); #endif } }; DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4866) // NOLINTBEGIN(*-avoid-c-arrays) template <typename T, size_t N> struct filldata<T[N]> { static void fill(std::ostream* stream, const T(&in)[N]) { *stream << "["; for (size_t i = 0; i < N; i++) { if (i != 0) { *stream << ", "; } *stream << (DOCTEST_STRINGIFY(in[i])); } *stream << "]"; } }; // NOLINTEND(*-avoid-c-arrays) DOCTEST_MSVC_SUPPRESS_WARNING_POP // Specialized since we don't want the terminating null byte! // NOLINTBEGIN(*-avoid-c-arrays) template <size_t N> struct filldata<const char[N]> { static void fill(std::ostream* stream, const char (&in)[N]) { *stream << String(in, in[N - 1] ? N : N - 1); } // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) }; // NOLINTEND(*-avoid-c-arrays) template <> struct filldata<const void*> { static void fill(std::ostream* stream, const void* in); }; template <typename T> struct filldata<T*> { DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4180) static void fill(std::ostream* stream, const T* in) { DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wmicrosoft-cast") filldata<const void*>::fill(stream, #if DOCTEST_GCC == 0 || DOCTEST_GCC >= DOCTEST_COMPILER(4, 9, 0) reinterpret_cast<const void*>(in) #else *reinterpret_cast<const void* const*>(&in) #endif ); DOCTEST_CLANG_SUPPRESS_WARNING_POP } }; } struct DOCTEST_INTERFACE Approx { Approx(double value); Approx operator()(double value) const; #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS template <typename T> explicit Approx(const T& value, typename detail::types::enable_if<std::is_constructible<double, T>::value>::type* = static_cast<T*>(nullptr)) { *this = static_cast<double>(value); } #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS Approx& epsilon(double newEpsilon); #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS template <typename T> typename std::enable_if<std::is_constructible<double, T>::value, Approx&>::type epsilon( const T& newEpsilon) { m_epsilon = static_cast<double>(newEpsilon); return *this; } #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS Approx& scale(double newScale); #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS template <typename T> typename std::enable_if<std::is_constructible<double, T>::value, Approx&>::type scale( const T& newScale) { m_scale = static_cast<double>(newScale); return *this; } #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS // clang-format off DOCTEST_INTERFACE friend bool operator==(double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator==(const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator!=(double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator!=(const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator<=(double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator<=(const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator>=(double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator>=(const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator< (double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator< (const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator> (double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator> (const Approx & lhs, double rhs); #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS #define DOCTEST_APPROX_PREFIX \ template <typename T> friend typename std::enable_if<std::is_constructible<double, T>::value, bool>::type DOCTEST_APPROX_PREFIX operator==(const T& lhs, const Approx& rhs) { return operator==(static_cast<double>(lhs), rhs); } DOCTEST_APPROX_PREFIX operator==(const Approx& lhs, const T& rhs) { return operator==(rhs, lhs); } DOCTEST_APPROX_PREFIX operator!=(const T& lhs, const Approx& rhs) { return !operator==(lhs, rhs); } DOCTEST_APPROX_PREFIX operator!=(const Approx& lhs, const T& rhs) { return !operator==(rhs, lhs); } DOCTEST_APPROX_PREFIX operator<=(const T& lhs, const Approx& rhs) { return static_cast<double>(lhs) < rhs.m_value || lhs == rhs; } DOCTEST_APPROX_PREFIX operator<=(const Approx& lhs, const T& rhs) { return lhs.m_value < static_cast<double>(rhs) || lhs == rhs; } DOCTEST_APPROX_PREFIX operator>=(const T& lhs, const Approx& rhs) { return static_cast<double>(lhs) > rhs.m_value || lhs == rhs; } DOCTEST_APPROX_PREFIX operator>=(const Approx& lhs, const T& rhs) { return lhs.m_value > static_cast<double>(rhs) || lhs == rhs; } DOCTEST_APPROX_PREFIX operator< (const T& lhs, const Approx& rhs) { return static_cast<double>(lhs) < rhs.m_value && lhs != rhs; } DOCTEST_APPROX_PREFIX operator< (const Approx& lhs, const T& rhs) { return lhs.m_value < static_cast<double>(rhs) && lhs != rhs; } DOCTEST_APPROX_PREFIX operator> (const T& lhs, const Approx& rhs) { return static_cast<double>(lhs) > rhs.m_value && lhs != rhs; } DOCTEST_APPROX_PREFIX operator> (const Approx& lhs, const T& rhs) { return lhs.m_value > static_cast<double>(rhs) && lhs != rhs; } #undef DOCTEST_APPROX_PREFIX #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS // clang-format on double m_epsilon; double m_scale; double m_value; }; DOCTEST_INTERFACE String toString(const Approx& in); DOCTEST_INTERFACE const ContextOptions* getContextOptions(); template <typename F> struct DOCTEST_INTERFACE_DECL IsNaN { F value; bool flipped; IsNaN(F f, bool flip = false) : value(f), flipped(flip) { } IsNaN<F> operator!() const { return { value, !flipped }; } operator bool() const; }; #ifndef __MINGW32__ extern template struct DOCTEST_INTERFACE_DECL IsNaN<float>; extern template struct DOCTEST_INTERFACE_DECL IsNaN<double>; extern template struct DOCTEST_INTERFACE_DECL IsNaN<long double>; #endif DOCTEST_INTERFACE String toString(IsNaN<float> in); DOCTEST_INTERFACE String toString(IsNaN<double> in); DOCTEST_INTERFACE String toString(IsNaN<double long> in); #ifndef DOCTEST_CONFIG_DISABLE namespace detail { // clang-format off #ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING template<class T> struct decay_array { using type = T; }; template<class T, unsigned N> struct decay_array<T[N]> { using type = T*; }; template<class T> struct decay_array<T[]> { using type = T*; }; template<class T> struct not_char_pointer { static DOCTEST_CONSTEXPR int value = 1; }; template<> struct not_char_pointer<char*> { static DOCTEST_CONSTEXPR int value = 0; }; template<> struct not_char_pointer<const char*> { static DOCTEST_CONSTEXPR int value = 0; }; template<class T> struct can_use_op : public not_char_pointer<typename decay_array<T>::type> {}; #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING // clang-format on struct DOCTEST_INTERFACE TestFailureException { }; DOCTEST_INTERFACE bool checkIfShouldThrow(assertType::Enum at); #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS DOCTEST_NORETURN #endif // DOCTEST_CONFIG_NO_EXCEPTIONS DOCTEST_INTERFACE void throwException(); struct DOCTEST_INTERFACE Subcase { SubcaseSignature m_signature; bool m_entered = false; Subcase(const String& name, const char* file, int line); Subcase(const Subcase&) = delete; Subcase(Subcase&&) = delete; Subcase& operator=(const Subcase&) = delete; Subcase& operator=(Subcase&&) = delete; ~Subcase(); operator bool() const; private: bool checkFilters(); }; template <typename L, typename R> String stringifyBinaryExpr(const DOCTEST_REF_WRAP(L) lhs, const char* op, const DOCTEST_REF_WRAP(R) rhs) { return (DOCTEST_STRINGIFY(lhs)) + op + (DOCTEST_STRINGIFY(rhs)); } #if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-comparison") #endif // This will check if there is any way it could find a operator like member or friend and uses it. // If not it doesn't find the operator or if the operator at global scope is defined after // this template, the template won't be instantiated due to SFINAE. Once the template is not // instantiated it can look for global operator using normal conversions. #ifdef __NVCC__ #define SFINAE_OP(ret,op) ret #else #define SFINAE_OP(ret,op) decltype((void)(doctest::detail::declval<L>() op doctest::detail::declval<R>()),ret{}) #endif #define DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(op, op_str, op_macro) \ template <typename R> \ DOCTEST_NOINLINE SFINAE_OP(Result,op) operator op(R&& rhs) { \ bool res = op_macro(doctest::detail::forward<const L>(lhs), doctest::detail::forward<R>(rhs)); \ if(m_at & assertType::is_false) \ res = !res; \ if(!res || doctest::getContextOptions()->success) \ return Result(res, stringifyBinaryExpr(lhs, op_str, rhs)); \ return Result(res); \ } // more checks could be added - like in Catch: // https://github.com/catchorg/Catch2/pull/1480/files // https://github.com/catchorg/Catch2/pull/1481/files #define DOCTEST_FORBIT_EXPRESSION(rt, op) \ template <typename R> \ rt& operator op(const R&) { \ static_assert(deferred_false<R>::value, \ "Expression Too Complex Please Rewrite As Binary Comparison!"); \ return *this; \ } struct DOCTEST_INTERFACE Result // NOLINT(*-member-init) { bool m_passed; String m_decomp; Result() = default; // TODO: Why do we need this? (To remove NOLINT) Result(bool passed, const String& decomposition = String()); // forbidding some expressions based on this table: https://en.cppreference.com/w/cpp/language/operator_precedence DOCTEST_FORBIT_EXPRESSION(Result, &) DOCTEST_FORBIT_EXPRESSION(Result, ^) DOCTEST_FORBIT_EXPRESSION(Result, |) DOCTEST_FORBIT_EXPRESSION(Result, &&) DOCTEST_FORBIT_EXPRESSION(Result, ||) DOCTEST_FORBIT_EXPRESSION(Result, ==) DOCTEST_FORBIT_EXPRESSION(Result, !=) DOCTEST_FORBIT_EXPRESSION(Result, <) DOCTEST_FORBIT_EXPRESSION(Result, >) DOCTEST_FORBIT_EXPRESSION(Result, <=) DOCTEST_FORBIT_EXPRESSION(Result, >=) DOCTEST_FORBIT_EXPRESSION(Result, =) DOCTEST_FORBIT_EXPRESSION(Result, +=) DOCTEST_FORBIT_EXPRESSION(Result, -=) DOCTEST_FORBIT_EXPRESSION(Result, *=) DOCTEST_FORBIT_EXPRESSION(Result, /=) DOCTEST_FORBIT_EXPRESSION(Result, %=) DOCTEST_FORBIT_EXPRESSION(Result, <<=) DOCTEST_FORBIT_EXPRESSION(Result, >>=) DOCTEST_FORBIT_EXPRESSION(Result, &=) DOCTEST_FORBIT_EXPRESSION(Result, ^=) DOCTEST_FORBIT_EXPRESSION(Result, |=) }; #ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-compare") //DOCTEST_CLANG_SUPPRESS_WARNING("-Wdouble-promotion") //DOCTEST_CLANG_SUPPRESS_WARNING("-Wconversion") //DOCTEST_CLANG_SUPPRESS_WARNING("-Wfloat-equal") DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-compare") //DOCTEST_GCC_SUPPRESS_WARNING("-Wdouble-promotion") //DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") //DOCTEST_GCC_SUPPRESS_WARNING("-Wfloat-equal") DOCTEST_MSVC_SUPPRESS_WARNING_PUSH // https://stackoverflow.com/questions/39479163 what's the difference between 4018 and 4389 DOCTEST_MSVC_SUPPRESS_WARNING(4388) // signed/unsigned mismatch DOCTEST_MSVC_SUPPRESS_WARNING(4389) // 'operator' : signed/unsigned mismatch DOCTEST_MSVC_SUPPRESS_WARNING(4018) // 'expression' : signed/unsigned mismatch //DOCTEST_MSVC_SUPPRESS_WARNING(4805) // 'operation' : unsafe mix of type 'type' and type 'type' in operation #endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION // clang-format off #ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #define DOCTEST_COMPARISON_RETURN_TYPE bool #else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #define DOCTEST_COMPARISON_RETURN_TYPE typename types::enable_if<can_use_op<L>::value || can_use_op<R>::value, bool>::type inline bool eq(const char* lhs, const char* rhs) { return String(lhs) == String(rhs); } inline bool ne(const char* lhs, const char* rhs) { return String(lhs) != String(rhs); } inline bool lt(const char* lhs, const char* rhs) { return String(lhs) < String(rhs); } inline bool gt(const char* lhs, const char* rhs) { return String(lhs) > String(rhs); } inline bool le(const char* lhs, const char* rhs) { return String(lhs) <= String(rhs); } inline bool ge(const char* lhs, const char* rhs) { return String(lhs) >= String(rhs); } #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING // clang-format on #define DOCTEST_RELATIONAL_OP(name, op) \ template <typename L, typename R> \ DOCTEST_COMPARISON_RETURN_TYPE name(const DOCTEST_REF_WRAP(L) lhs, \ const DOCTEST_REF_WRAP(R) rhs) { \ return lhs op rhs; \ } DOCTEST_RELATIONAL_OP(eq, ==) DOCTEST_RELATIONAL_OP(ne, !=) DOCTEST_RELATIONAL_OP(lt, <) DOCTEST_RELATIONAL_OP(gt, >) DOCTEST_RELATIONAL_OP(le, <=) DOCTEST_RELATIONAL_OP(ge, >=) #ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #define DOCTEST_CMP_EQ(l, r) l == r #define DOCTEST_CMP_NE(l, r) l != r #define DOCTEST_CMP_GT(l, r) l > r #define DOCTEST_CMP_LT(l, r) l < r #define DOCTEST_CMP_GE(l, r) l >= r #define DOCTEST_CMP_LE(l, r) l <= r #else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #define DOCTEST_CMP_EQ(l, r) eq(l, r) #define DOCTEST_CMP_NE(l, r) ne(l, r) #define DOCTEST_CMP_GT(l, r) gt(l, r) #define DOCTEST_CMP_LT(l, r) lt(l, r) #define DOCTEST_CMP_GE(l, r) ge(l, r) #define DOCTEST_CMP_LE(l, r) le(l, r) #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING template <typename L> // cppcheck-suppress copyCtorAndEqOperator struct Expression_lhs { L lhs; assertType::Enum m_at; explicit Expression_lhs(L&& in, assertType::Enum at) : lhs(static_cast<L&&>(in)) , m_at(at) {} DOCTEST_NOINLINE operator Result() { // this is needed only for MSVC 2015 DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4800) // 'int': forcing value to bool bool res = static_cast<bool>(lhs); DOCTEST_MSVC_SUPPRESS_WARNING_POP if(m_at & assertType::is_false) { //!OCLINT bitwise operator in conditional res = !res; } if(!res || getContextOptions()->success) { return { res, (DOCTEST_STRINGIFY(lhs)) }; } return { res }; } /* This is required for user-defined conversions from Expression_lhs to L */ operator L() const { return lhs; } // clang-format off DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(==, " == ", DOCTEST_CMP_EQ) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(!=, " != ", DOCTEST_CMP_NE) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>, " > ", DOCTEST_CMP_GT) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<, " < ", DOCTEST_CMP_LT) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>=, " >= ", DOCTEST_CMP_GE) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<=, " <= ", DOCTEST_CMP_LE) //!OCLINT bitwise operator in conditional // clang-format on // forbidding some expressions based on this table: https://en.cppreference.com/w/cpp/language/operator_precedence DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &&) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ||) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, =) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, +=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, -=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, *=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, /=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, %=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |=) // these 2 are unfortunate because they should be allowed - they have higher precedence over the comparisons, but the // ExpressionDecomposer class uses the left shift operator to capture the left operand of the binary expression... DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>) }; #ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP #endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION #if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) DOCTEST_CLANG_SUPPRESS_WARNING_POP #endif struct DOCTEST_INTERFACE ExpressionDecomposer { assertType::Enum m_at; ExpressionDecomposer(assertType::Enum at); // The right operator for capturing expressions is "<=" instead of "<<" (based on the operator precedence table) // but then there will be warnings from GCC about "-Wparentheses" and since "_Pragma()" is problematic this will stay for now... // https://github.com/catchorg/Catch2/issues/870 // https://github.com/catchorg/Catch2/issues/565 template <typename L> Expression_lhs<L> operator<<(L&& operand) { return Expression_lhs<L>(static_cast<L&&>(operand), m_at); } template <typename L,typename types::enable_if<!doctest::detail::types::is_rvalue_reference<L>::value,void >::type* = nullptr> Expression_lhs<const L&> operator<<(const L &operand) { return Expression_lhs<const L&>(operand, m_at); } }; struct DOCTEST_INTERFACE TestSuite { const char* m_test_suite = nullptr; const char* m_description = nullptr; bool m_skip = false; bool m_no_breaks = false; bool m_no_output = false; bool m_may_fail = false; bool m_should_fail = false; int m_expected_failures = 0; double m_timeout = 0; TestSuite& operator*(const char* in); template <typename T> TestSuite& operator*(const T& in) { in.fill(*this); return *this; } }; using funcType = void (*)(); struct DOCTEST_INTERFACE TestCase : public TestCaseData { funcType m_test; // a function pointer to the test case String m_type; // for templated test cases - gets appended to the real name int m_template_id; // an ID used to distinguish between the different versions of a templated test case String m_full_name; // contains the name (only for templated test cases!) + the template type TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, const String& type = String(), int template_id = -1); TestCase(const TestCase& other); TestCase(TestCase&&) = delete; DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function TestCase& operator=(const TestCase& other); DOCTEST_MSVC_SUPPRESS_WARNING_POP TestCase& operator=(TestCase&&) = delete; TestCase& operator*(const char* in); template <typename T> TestCase& operator*(const T& in) { in.fill(*this); return *this; } bool operator<(const TestCase& other) const; ~TestCase() = default; }; // forward declarations of functions used by the macros DOCTEST_INTERFACE int regTest(const TestCase& tc); DOCTEST_INTERFACE int setTestSuite(const TestSuite& ts); DOCTEST_INTERFACE bool isDebuggerActive(); template<typename T> int instantiationHelper(const T&) { return 0; } namespace binaryAssertComparison { enum Enum { eq = 0, ne, gt, lt, ge, le }; } // namespace binaryAssertComparison // clang-format off template <int, class L, class R> struct RelationalComparator { bool operator()(const DOCTEST_REF_WRAP(L), const DOCTEST_REF_WRAP(R) ) const { return false; } }; #define DOCTEST_BINARY_RELATIONAL_OP(n, op) \ template <class L, class R> struct RelationalComparator<n, L, R> { bool operator()(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) const { return op(lhs, rhs); } }; // clang-format on DOCTEST_BINARY_RELATIONAL_OP(0, doctest::detail::eq) DOCTEST_BINARY_RELATIONAL_OP(1, doctest::detail::ne) DOCTEST_BINARY_RELATIONAL_OP(2, doctest::detail::gt) DOCTEST_BINARY_RELATIONAL_OP(3, doctest::detail::lt) DOCTEST_BINARY_RELATIONAL_OP(4, doctest::detail::ge) DOCTEST_BINARY_RELATIONAL_OP(5, doctest::detail::le) struct DOCTEST_INTERFACE ResultBuilder : public AssertData { ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type = "", const String& exception_string = ""); ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const Contains& exception_string); void setResult(const Result& res); template <int comparison, typename L, typename R> DOCTEST_NOINLINE bool binary_assert(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) { m_failed = !RelationalComparator<comparison, L, R>()(lhs, rhs); if (m_failed || getContextOptions()->success) { m_decomp = stringifyBinaryExpr(lhs, ", ", rhs); } return !m_failed; } template <typename L> DOCTEST_NOINLINE bool unary_assert(const DOCTEST_REF_WRAP(L) val) { m_failed = !val; if (m_at & assertType::is_false) { //!OCLINT bitwise operator in conditional m_failed = !m_failed; } if (m_failed || getContextOptions()->success) { m_decomp = (DOCTEST_STRINGIFY(val)); } return !m_failed; } void translateException(); bool log(); void react() const; }; namespace assertAction { enum Enum { nothing = 0, dbgbreak = 1, shouldthrow = 2 }; } // namespace assertAction DOCTEST_INTERFACE void failed_out_of_a_testing_context(const AssertData& ad); DOCTEST_INTERFACE bool decomp_assert(assertType::Enum at, const char* file, int line, const char* expr, const Result& result); #define DOCTEST_ASSERT_OUT_OF_TESTS(decomp) \ do { \ if(!is_running_in_test) { \ if(failed) { \ ResultBuilder rb(at, file, line, expr); \ rb.m_failed = failed; \ rb.m_decomp = decomp; \ failed_out_of_a_testing_context(rb); \ if(isDebuggerActive() && !getContextOptions()->no_breaks) \ DOCTEST_BREAK_INTO_DEBUGGER(); \ if(checkIfShouldThrow(at)) \ throwException(); \ } \ return !failed; \ } \ } while(false) #define DOCTEST_ASSERT_IN_TESTS(decomp) \ ResultBuilder rb(at, file, line, expr); \ rb.m_failed = failed; \ if(rb.m_failed || getContextOptions()->success) \ rb.m_decomp = decomp; \ if(rb.log()) \ DOCTEST_BREAK_INTO_DEBUGGER(); \ if(rb.m_failed && checkIfShouldThrow(at)) \ throwException() template <int comparison, typename L, typename R> DOCTEST_NOINLINE bool binary_assert(assertType::Enum at, const char* file, int line, const char* expr, const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) { bool failed = !RelationalComparator<comparison, L, R>()(lhs, rhs); // ################################################################################### // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED // ################################################################################### DOCTEST_ASSERT_OUT_OF_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); DOCTEST_ASSERT_IN_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); return !failed; } template <typename L> DOCTEST_NOINLINE bool unary_assert(assertType::Enum at, const char* file, int line, const char* expr, const DOCTEST_REF_WRAP(L) val) { bool failed = !val; if(at & assertType::is_false) //!OCLINT bitwise operator in conditional failed = !failed; // ################################################################################### // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED // ################################################################################### DOCTEST_ASSERT_OUT_OF_TESTS((DOCTEST_STRINGIFY(val))); DOCTEST_ASSERT_IN_TESTS((DOCTEST_STRINGIFY(val))); return !failed; } struct DOCTEST_INTERFACE IExceptionTranslator { DOCTEST_DECLARE_INTERFACE(IExceptionTranslator) virtual bool translate(String&) const = 0; }; template <typename T> class ExceptionTranslator : public IExceptionTranslator //!OCLINT destructor of virtual class { public: explicit ExceptionTranslator(String (*translateFunction)(T)) : m_translateFunction(translateFunction) {} bool translate(String& res) const override { #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS try { throw; // lgtm [cpp/rethrow-no-exception] // cppcheck-suppress catchExceptionByValue } catch(const T& ex) { res = m_translateFunction(ex); //!OCLINT parameter reassignment return true; } catch(...) {} //!OCLINT - empty catch statement #endif // DOCTEST_CONFIG_NO_EXCEPTIONS static_cast<void>(res); // to silence -Wunused-parameter return false; } private: String (*m_translateFunction)(T); }; DOCTEST_INTERFACE void registerExceptionTranslatorImpl(const IExceptionTranslator* et); // ContextScope base class used to allow implementing methods of ContextScope // that don't depend on the template parameter in doctest.cpp. struct DOCTEST_INTERFACE ContextScopeBase : public IContextScope { ContextScopeBase(const ContextScopeBase&) = delete; ContextScopeBase& operator=(const ContextScopeBase&) = delete; ContextScopeBase& operator=(ContextScopeBase&&) = delete; ~ContextScopeBase() override = default; protected: ContextScopeBase(); ContextScopeBase(ContextScopeBase&& other) noexcept; void destroy(); bool need_to_destroy{true}; }; template <typename L> class ContextScope : public ContextScopeBase { L lambda_; public: explicit ContextScope(const L &lambda) : lambda_(lambda) {} explicit ContextScope(L&& lambda) : lambda_(static_cast<L&&>(lambda)) { } ContextScope(const ContextScope&) = delete; ContextScope(ContextScope&&) noexcept = default; ContextScope& operator=(const ContextScope&) = delete; ContextScope& operator=(ContextScope&&) = delete; void stringify(std::ostream* s) const override { lambda_(s); } ~ContextScope() override { if (need_to_destroy) { destroy(); } } }; struct DOCTEST_INTERFACE MessageBuilder : public MessageData { std::ostream* m_stream; bool logged = false; MessageBuilder(const char* file, int line, assertType::Enum severity); MessageBuilder(const MessageBuilder&) = delete; MessageBuilder(MessageBuilder&&) = delete; MessageBuilder& operator=(const MessageBuilder&) = delete; MessageBuilder& operator=(MessageBuilder&&) = delete; ~MessageBuilder(); // the preferred way of chaining parameters for stringification DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4866) template <typename T> MessageBuilder& operator,(const T& in) { *m_stream << (DOCTEST_STRINGIFY(in)); return *this; } DOCTEST_MSVC_SUPPRESS_WARNING_POP // kept here just for backwards-compatibility - the comma operator should be preferred now template <typename T> MessageBuilder& operator<<(const T& in) { return this->operator,(in); } // the `,` operator has the lowest operator precedence - if `<<` is used by the user then // the `,` operator will be called last which is not what we want and thus the `*` operator // is used first (has higher operator precedence compared to `<<`) so that we guarantee that // an operator of the MessageBuilder class is called first before the rest of the parameters template <typename T> MessageBuilder& operator*(const T& in) { return this->operator,(in); } bool log(); void react(); }; template <typename L> ContextScope<L> MakeContextScope(const L &lambda) { return ContextScope<L>(lambda); } } // namespace detail #define DOCTEST_DEFINE_DECORATOR(name, type, def) \ struct name \ { \ type data; \ name(type in = def) \ : data(in) {} \ void fill(detail::TestCase& state) const { state.DOCTEST_CAT(m_, name) = data; } \ void fill(detail::TestSuite& state) const { state.DOCTEST_CAT(m_, name) = data; } \ } DOCTEST_DEFINE_DECORATOR(test_suite, const char*, ""); DOCTEST_DEFINE_DECORATOR(description, const char*, ""); DOCTEST_DEFINE_DECORATOR(skip, bool, true); DOCTEST_DEFINE_DECORATOR(no_breaks, bool, true); DOCTEST_DEFINE_DECORATOR(no_output, bool, true); DOCTEST_DEFINE_DECORATOR(timeout, double, 0); DOCTEST_DEFINE_DECORATOR(may_fail, bool, true); DOCTEST_DEFINE_DECORATOR(should_fail, bool, true); DOCTEST_DEFINE_DECORATOR(expected_failures, int, 0); template <typename T> int registerExceptionTranslator(String (*translateFunction)(T)) { DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") static detail::ExceptionTranslator<T> exceptionTranslator(translateFunction); DOCTEST_CLANG_SUPPRESS_WARNING_POP detail::registerExceptionTranslatorImpl(&exceptionTranslator); return 0; } } // namespace doctest // in a separate namespace outside of doctest because the DOCTEST_TEST_SUITE macro // introduces an anonymous namespace in which getCurrentTestSuite gets overridden namespace doctest_detail_test_suite_ns { DOCTEST_INTERFACE doctest::detail::TestSuite& getCurrentTestSuite(); } // namespace doctest_detail_test_suite_ns namespace doctest { #else // DOCTEST_CONFIG_DISABLE template <typename T> int registerExceptionTranslator(String (*)(T)) { return 0; } #endif // DOCTEST_CONFIG_DISABLE namespace detail { using assert_handler = void (*)(const AssertData&); struct ContextState; } // namespace detail class DOCTEST_INTERFACE Context { detail::ContextState* p; void parseArgs(int argc, const char* const* argv, bool withDefaults = false); public: explicit Context(int argc = 0, const char* const* argv = nullptr); Context(const Context&) = delete; Context(Context&&) = delete; Context& operator=(const Context&) = delete; Context& operator=(Context&&) = delete; ~Context(); // NOLINT(performance-trivially-destructible) void applyCommandLine(int argc, const char* const* argv); void addFilter(const char* filter, const char* value); void clearFilters(); void setOption(const char* option, bool value); void setOption(const char* option, int value); void setOption(const char* option, const char* value); bool shouldExit(); void setAsDefaultForAssertsOutOfTestCases(); void setAssertHandler(detail::assert_handler ah); void setCout(std::ostream* out); int run(); }; namespace TestCaseFailureReason { enum Enum { None = 0, AssertFailure = 1, // an assertion has failed in the test case Exception = 2, // test case threw an exception Crash = 4, // a crash... TooManyFailedAsserts = 8, // the abort-after option Timeout = 16, // see the timeout decorator ShouldHaveFailedButDidnt = 32, // see the should_fail decorator ShouldHaveFailedAndDid = 64, // see the should_fail decorator DidntFailExactlyNumTimes = 128, // see the expected_failures decorator FailedExactlyNumTimes = 256, // see the expected_failures decorator CouldHaveFailedAndDid = 512 // see the may_fail decorator }; } // namespace TestCaseFailureReason struct DOCTEST_INTERFACE CurrentTestCaseStats { int numAssertsCurrentTest; int numAssertsFailedCurrentTest; double seconds; int failure_flags; // use TestCaseFailureReason::Enum bool testCaseSuccess; }; struct DOCTEST_INTERFACE TestCaseException { String error_string; bool is_crash; }; struct DOCTEST_INTERFACE TestRunStats { unsigned numTestCases; unsigned numTestCasesPassingFilters; unsigned numTestSuitesPassingFilters; unsigned numTestCasesFailed; int numAsserts; int numAssertsFailed; }; struct QueryData { const TestRunStats* run_stats = nullptr; const TestCaseData** data = nullptr; unsigned num_data = 0; }; struct DOCTEST_INTERFACE IReporter { // The constructor has to accept "const ContextOptions&" as a single argument // which has most of the options for the run + a pointer to the stdout stream // Reporter(const ContextOptions& in) // called when a query should be reported (listing test cases, printing the version, etc.) virtual void report_query(const QueryData&) = 0; // called when the whole test run starts virtual void test_run_start() = 0; // called when the whole test run ends (caching a pointer to the input doesn't make sense here) virtual void test_run_end(const TestRunStats&) = 0; // called when a test case is started (safe to cache a pointer to the input) virtual void test_case_start(const TestCaseData&) = 0; // called when a test case is reentered because of unfinished subcases (safe to cache a pointer to the input) virtual void test_case_reenter(const TestCaseData&) = 0; // called when a test case has ended virtual void test_case_end(const CurrentTestCaseStats&) = 0; // called when an exception is thrown from the test case (or it crashes) virtual void test_case_exception(const TestCaseException&) = 0; // called whenever a subcase is entered (don't cache pointers to the input) virtual void subcase_start(const SubcaseSignature&) = 0; // called whenever a subcase is exited (don't cache pointers to the input) virtual void subcase_end() = 0; // called for each assert (don't cache pointers to the input) virtual void log_assert(const AssertData&) = 0; // called for each message (don't cache pointers to the input) virtual void log_message(const MessageData&) = 0; // called when a test case is skipped either because it doesn't pass the filters, has a skip decorator // or isn't in the execution range (between first and last) (safe to cache a pointer to the input) virtual void test_case_skipped(const TestCaseData&) = 0; DOCTEST_DECLARE_INTERFACE(IReporter) // can obtain all currently active contexts and stringify them if one wishes to do so static int get_num_active_contexts(); static const IContextScope* const* get_active_contexts(); // can iterate through contexts which have been stringified automatically in their destructors when an exception has been thrown static int get_num_stringified_contexts(); static const String* get_stringified_contexts(); }; namespace detail { using reporterCreatorFunc = IReporter* (*)(const ContextOptions&); DOCTEST_INTERFACE void registerReporterImpl(const char* name, int prio, reporterCreatorFunc c, bool isReporter); template <typename Reporter> IReporter* reporterCreator(const ContextOptions& o) { return new Reporter(o); } } // namespace detail template <typename Reporter> int registerReporter(const char* name, int priority, bool isReporter) { detail::registerReporterImpl(name, priority, detail::reporterCreator<Reporter>, isReporter); return 0; } } // namespace doctest #ifdef DOCTEST_CONFIG_ASSERTS_RETURN_VALUES #define DOCTEST_FUNC_EMPTY [] { return false; }() #else #define DOCTEST_FUNC_EMPTY (void)0 #endif // if registering is not disabled #ifndef DOCTEST_CONFIG_DISABLE #ifdef DOCTEST_CONFIG_ASSERTS_RETURN_VALUES #define DOCTEST_FUNC_SCOPE_BEGIN [&] #define DOCTEST_FUNC_SCOPE_END () #define DOCTEST_FUNC_SCOPE_RET(v) return v #else #define DOCTEST_FUNC_SCOPE_BEGIN do #define DOCTEST_FUNC_SCOPE_END while(false) #define DOCTEST_FUNC_SCOPE_RET(v) (void)0 #endif // common code in asserts - for convenience #define DOCTEST_ASSERT_LOG_REACT_RETURN(b) \ if(b.log()) DOCTEST_BREAK_INTO_DEBUGGER(); \ b.react(); \ DOCTEST_FUNC_SCOPE_RET(!b.m_failed) #ifdef DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #define DOCTEST_WRAP_IN_TRY(x) x; #else // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #define DOCTEST_WRAP_IN_TRY(x) \ try { \ x; \ } catch(...) { DOCTEST_RB.translateException(); } #endif // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #ifdef DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS #define DOCTEST_CAST_TO_VOID(...) \ DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wuseless-cast") \ static_cast<void>(__VA_ARGS__); \ DOCTEST_GCC_SUPPRESS_WARNING_POP #else // DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS #define DOCTEST_CAST_TO_VOID(...) __VA_ARGS__; #endif // DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS // registers the test by initializing a dummy var with a function #define DOCTEST_REGISTER_FUNCTION(global_prefix, f, decorators) \ global_prefix DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT */ \ doctest::detail::regTest( \ doctest::detail::TestCase( \ f, __FILE__, __LINE__, \ doctest_detail_test_suite_ns::getCurrentTestSuite()) * \ decorators)) #define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, decorators) \ namespace { /* NOLINT */ \ struct der : public base \ { \ void f(); \ }; \ static DOCTEST_INLINE_NOINLINE void func() { \ der v; \ v.f(); \ } \ DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, func, decorators) \ } \ DOCTEST_INLINE_NOINLINE void der::f() // NOLINT(misc-definitions-in-headers) #define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, decorators) \ static void f(); \ DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, f, decorators) \ static void f() #define DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(f, proxy, decorators) \ static doctest::detail::funcType proxy() { return f; } \ DOCTEST_REGISTER_FUNCTION(inline, proxy(), decorators) \ static void f() // for registering tests #define DOCTEST_TEST_CASE(decorators) \ DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), decorators) // for registering tests in classes - requires C++17 for inline variables! #if DOCTEST_CPLUSPLUS >= 201703L #define DOCTEST_TEST_CASE_CLASS(decorators) \ DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), \ DOCTEST_ANONYMOUS(DOCTEST_ANON_PROXY_), \ decorators) #else // DOCTEST_TEST_CASE_CLASS #define DOCTEST_TEST_CASE_CLASS(...) \ TEST_CASES_CAN_BE_REGISTERED_IN_CLASSES_ONLY_IN_CPP17_MODE_OR_WITH_VS_2017_OR_NEWER #endif // DOCTEST_TEST_CASE_CLASS // for registering tests with a fixture #define DOCTEST_TEST_CASE_FIXTURE(c, decorators) \ DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(DOCTEST_ANON_CLASS_), c, \ DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), decorators) // for converting types to strings without the <typeinfo> header and demangling #define DOCTEST_TYPE_TO_STRING_AS(str, ...) \ namespace doctest { \ template <> \ inline String toString<__VA_ARGS__>() { \ return str; \ } \ } \ static_assert(true, "") #define DOCTEST_TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING_AS(#__VA_ARGS__, __VA_ARGS__) #define DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, iter, func) \ template <typename T> \ static void func(); \ namespace { /* NOLINT */ \ template <typename Tuple> \ struct iter; \ template <typename Type, typename... Rest> \ struct iter<std::tuple<Type, Rest...>> \ { \ iter(const char* file, unsigned line, int index) { \ doctest::detail::regTest(doctest::detail::TestCase(func<Type>, file, line, \ doctest_detail_test_suite_ns::getCurrentTestSuite(), \ doctest::toString<Type>(), \ int(line) * 1000 + index) \ * dec); \ iter<std::tuple<Rest...>>(file, line, index + 1); \ } \ }; \ template <> \ struct iter<std::tuple<>> \ { \ iter(const char*, unsigned, int) {} \ }; \ } \ template <typename T> \ static void func() #define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(dec, T, id) \ DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(id, ITERATOR), \ DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)) #define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, anon, ...) \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_CAT(anon, DUMMY), /* NOLINT(cert-err58-cpp, fuchsia-statically-constructed-objects) */ \ doctest::detail::instantiationHelper( \ DOCTEST_CAT(id, ITERATOR)<__VA_ARGS__>(__FILE__, __LINE__, 0))) #define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) \ DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), std::tuple<__VA_ARGS__>) \ static_assert(true, "") #define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) \ DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), __VA_ARGS__) \ static_assert(true, "") #define DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, anon, ...) \ DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(anon, ITERATOR), anon); \ DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(anon, anon, std::tuple<__VA_ARGS__>) \ template <typename T> \ static void anon() #define DOCTEST_TEST_CASE_TEMPLATE(dec, T, ...) \ DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), __VA_ARGS__) // for subcases #define DOCTEST_SUBCASE(name) \ if(const doctest::detail::Subcase & DOCTEST_ANONYMOUS(DOCTEST_ANON_SUBCASE_) DOCTEST_UNUSED = \ doctest::detail::Subcase(name, __FILE__, __LINE__)) // for grouping tests in test suites by using code blocks #define DOCTEST_TEST_SUITE_IMPL(decorators, ns_name) \ namespace ns_name { namespace doctest_detail_test_suite_ns { \ static DOCTEST_NOINLINE doctest::detail::TestSuite& getCurrentTestSuite() noexcept { \ DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4640) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") \ DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmissing-field-initializers") \ static doctest::detail::TestSuite data{}; \ static bool inited = false; \ DOCTEST_MSVC_SUPPRESS_WARNING_POP \ DOCTEST_CLANG_SUPPRESS_WARNING_POP \ DOCTEST_GCC_SUPPRESS_WARNING_POP \ if(!inited) { \ data* decorators; \ inited = true; \ } \ return data; \ } \ } \ } \ namespace ns_name #define DOCTEST_TEST_SUITE(decorators) \ DOCTEST_TEST_SUITE_IMPL(decorators, DOCTEST_ANONYMOUS(DOCTEST_ANON_SUITE_)) // for starting a testsuite block #define DOCTEST_TEST_SUITE_BEGIN(decorators) \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT(cert-err58-cpp) */ \ doctest::detail::setTestSuite(doctest::detail::TestSuite() * decorators)) \ static_assert(true, "") // for ending a testsuite block #define DOCTEST_TEST_SUITE_END \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT(cert-err58-cpp) */ \ doctest::detail::setTestSuite(doctest::detail::TestSuite() * "")) \ using DOCTEST_ANONYMOUS(DOCTEST_ANON_FOR_SEMICOLON_) = int // for registering exception translators #define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(translatorName, signature) \ inline doctest::String translatorName(signature); \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_), /* NOLINT(cert-err58-cpp) */ \ doctest::registerExceptionTranslator(translatorName)) \ doctest::String translatorName(signature) #define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_), \ signature) // for registering reporters #define DOCTEST_REGISTER_REPORTER(name, priority, reporter) \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_REPORTER_), /* NOLINT(cert-err58-cpp) */ \ doctest::registerReporter<reporter>(name, priority, true)) \ static_assert(true, "") // for registering listeners #define DOCTEST_REGISTER_LISTENER(name, priority, reporter) \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_REPORTER_), /* NOLINT(cert-err58-cpp) */ \ doctest::registerReporter<reporter>(name, priority, false)) \ static_assert(true, "") // clang-format off // for logging - disabling formatting because it's important to have these on 2 separate lines - see PR #557 #define DOCTEST_INFO(...) \ DOCTEST_INFO_IMPL(DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_), \ DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_OTHER_), \ __VA_ARGS__) // clang-format on #define DOCTEST_INFO_IMPL(mb_name, s_name, ...) \ auto DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_) = doctest::detail::MakeContextScope( \ [&](std::ostream* s_name) { \ doctest::detail::MessageBuilder mb_name(__FILE__, __LINE__, doctest::assertType::is_warn); \ mb_name.m_stream = s_name; \ mb_name * __VA_ARGS__; \ }) #define DOCTEST_CAPTURE(x) DOCTEST_INFO(#x " := ", x) #define DOCTEST_ADD_AT_IMPL(type, file, line, mb, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ doctest::detail::MessageBuilder mb(file, line, doctest::assertType::type); \ mb * __VA_ARGS__; \ if(mb.log()) \ DOCTEST_BREAK_INTO_DEBUGGER(); \ mb.react(); \ } DOCTEST_FUNC_SCOPE_END // clang-format off #define DOCTEST_ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_warn, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) #define DOCTEST_ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_check, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) #define DOCTEST_ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_require, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) // clang-format on #define DOCTEST_MESSAGE(...) DOCTEST_ADD_MESSAGE_AT(__FILE__, __LINE__, __VA_ARGS__) #define DOCTEST_FAIL_CHECK(...) DOCTEST_ADD_FAIL_CHECK_AT(__FILE__, __LINE__, __VA_ARGS__) #define DOCTEST_FAIL(...) DOCTEST_ADD_FAIL_AT(__FILE__, __LINE__, __VA_ARGS__) #define DOCTEST_TO_LVALUE(...) __VA_ARGS__ // Not removed to keep backwards compatibility. #ifndef DOCTEST_CONFIG_SUPER_FAST_ASSERTS #define DOCTEST_ASSERT_IMPLEMENT_2(assert_type, ...) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ /* NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) */ \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #__VA_ARGS__); \ DOCTEST_WRAP_IN_TRY(DOCTEST_RB.setResult( \ doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ << __VA_ARGS__)) /* NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) */ \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB) \ DOCTEST_CLANG_SUPPRESS_WARNING_POP #define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ DOCTEST_ASSERT_IMPLEMENT_2(assert_type, __VA_ARGS__); \ } DOCTEST_FUNC_SCOPE_END // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) #define DOCTEST_BINARY_ASSERT(assert_type, comp, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #__VA_ARGS__); \ DOCTEST_WRAP_IN_TRY( \ DOCTEST_RB.binary_assert<doctest::detail::binaryAssertComparison::comp>( \ __VA_ARGS__)) \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } DOCTEST_FUNC_SCOPE_END #define DOCTEST_UNARY_ASSERT(assert_type, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #__VA_ARGS__); \ DOCTEST_WRAP_IN_TRY(DOCTEST_RB.unary_assert(__VA_ARGS__)) \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } DOCTEST_FUNC_SCOPE_END #else // DOCTEST_CONFIG_SUPER_FAST_ASSERTS // necessary for <ASSERT>_MESSAGE #define DOCTEST_ASSERT_IMPLEMENT_2 DOCTEST_ASSERT_IMPLEMENT_1 #define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ doctest::detail::decomp_assert( \ doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, \ doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ << __VA_ARGS__) DOCTEST_CLANG_SUPPRESS_WARNING_POP #define DOCTEST_BINARY_ASSERT(assert_type, comparison, ...) \ doctest::detail::binary_assert<doctest::detail::binaryAssertComparison::comparison>( \ doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, __VA_ARGS__) #define DOCTEST_UNARY_ASSERT(assert_type, ...) \ doctest::detail::unary_assert(doctest::assertType::assert_type, __FILE__, __LINE__, \ #__VA_ARGS__, __VA_ARGS__) #endif // DOCTEST_CONFIG_SUPER_FAST_ASSERTS #define DOCTEST_WARN(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN, __VA_ARGS__) #define DOCTEST_CHECK(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK, __VA_ARGS__) #define DOCTEST_REQUIRE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE, __VA_ARGS__) #define DOCTEST_WARN_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN_FALSE, __VA_ARGS__) #define DOCTEST_CHECK_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK_FALSE, __VA_ARGS__) #define DOCTEST_REQUIRE_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE_FALSE, __VA_ARGS__) // clang-format off #define DOCTEST_WARN_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN_FALSE, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK_FALSE, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE_FALSE, cond); } DOCTEST_FUNC_SCOPE_END // clang-format on #define DOCTEST_WARN_EQ(...) DOCTEST_BINARY_ASSERT(DT_WARN_EQ, eq, __VA_ARGS__) #define DOCTEST_CHECK_EQ(...) DOCTEST_BINARY_ASSERT(DT_CHECK_EQ, eq, __VA_ARGS__) #define DOCTEST_REQUIRE_EQ(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_EQ, eq, __VA_ARGS__) #define DOCTEST_WARN_NE(...) DOCTEST_BINARY_ASSERT(DT_WARN_NE, ne, __VA_ARGS__) #define DOCTEST_CHECK_NE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_NE, ne, __VA_ARGS__) #define DOCTEST_REQUIRE_NE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_NE, ne, __VA_ARGS__) #define DOCTEST_WARN_GT(...) DOCTEST_BINARY_ASSERT(DT_WARN_GT, gt, __VA_ARGS__) #define DOCTEST_CHECK_GT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GT, gt, __VA_ARGS__) #define DOCTEST_REQUIRE_GT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GT, gt, __VA_ARGS__) #define DOCTEST_WARN_LT(...) DOCTEST_BINARY_ASSERT(DT_WARN_LT, lt, __VA_ARGS__) #define DOCTEST_CHECK_LT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LT, lt, __VA_ARGS__) #define DOCTEST_REQUIRE_LT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LT, lt, __VA_ARGS__) #define DOCTEST_WARN_GE(...) DOCTEST_BINARY_ASSERT(DT_WARN_GE, ge, __VA_ARGS__) #define DOCTEST_CHECK_GE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GE, ge, __VA_ARGS__) #define DOCTEST_REQUIRE_GE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GE, ge, __VA_ARGS__) #define DOCTEST_WARN_LE(...) DOCTEST_BINARY_ASSERT(DT_WARN_LE, le, __VA_ARGS__) #define DOCTEST_CHECK_LE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LE, le, __VA_ARGS__) #define DOCTEST_REQUIRE_LE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LE, le, __VA_ARGS__) #define DOCTEST_WARN_UNARY(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY, __VA_ARGS__) #define DOCTEST_CHECK_UNARY(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY, __VA_ARGS__) #define DOCTEST_REQUIRE_UNARY(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY, __VA_ARGS__) #define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY_FALSE, __VA_ARGS__) #define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY_FALSE, __VA_ARGS__) #define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY_FALSE, __VA_ARGS__) #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #define DOCTEST_ASSERT_THROWS_AS(expr, assert_type, message, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ if(!doctest::getContextOptions()->no_throw) { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #expr, #__VA_ARGS__, message); \ try { \ DOCTEST_CAST_TO_VOID(expr) \ } catch(const typename doctest::detail::types::remove_const< \ typename doctest::detail::types::remove_reference<__VA_ARGS__>::type>::type&) {\ DOCTEST_RB.translateException(); \ DOCTEST_RB.m_threw_as = true; \ } catch(...) { DOCTEST_RB.translateException(); } \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } else { /* NOLINT(*-else-after-return) */ \ DOCTEST_FUNC_SCOPE_RET(false); \ } \ } DOCTEST_FUNC_SCOPE_END #define DOCTEST_ASSERT_THROWS_WITH(expr, expr_str, assert_type, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ if(!doctest::getContextOptions()->no_throw) { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, expr_str, "", __VA_ARGS__); \ try { \ DOCTEST_CAST_TO_VOID(expr) \ } catch(...) { DOCTEST_RB.translateException(); } \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } else { /* NOLINT(*-else-after-return) */ \ DOCTEST_FUNC_SCOPE_RET(false); \ } \ } DOCTEST_FUNC_SCOPE_END #define DOCTEST_ASSERT_NOTHROW(assert_type, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #__VA_ARGS__); \ try { \ DOCTEST_CAST_TO_VOID(__VA_ARGS__) \ } catch(...) { DOCTEST_RB.translateException(); } \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } DOCTEST_FUNC_SCOPE_END // clang-format off #define DOCTEST_WARN_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_WARN_THROWS, "") #define DOCTEST_CHECK_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_CHECK_THROWS, "") #define DOCTEST_REQUIRE_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_REQUIRE_THROWS, "") #define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_AS, "", __VA_ARGS__) #define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_AS, "", __VA_ARGS__) #define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_AS, "", __VA_ARGS__) #define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_WARN_THROWS_WITH, __VA_ARGS__) #define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_CHECK_THROWS_WITH, __VA_ARGS__) #define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_REQUIRE_THROWS_WITH, __VA_ARGS__) #define DOCTEST_WARN_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_WITH_AS, message, __VA_ARGS__) #define DOCTEST_CHECK_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_WITH_AS, message, __VA_ARGS__) #define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_WITH_AS, message, __VA_ARGS__) #define DOCTEST_WARN_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_WARN_NOTHROW, __VA_ARGS__) #define DOCTEST_CHECK_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_CHECK_NOTHROW, __VA_ARGS__) #define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_REQUIRE_NOTHROW, __VA_ARGS__) #define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END // clang-format on #endif // DOCTEST_CONFIG_NO_EXCEPTIONS // ================================================================================================= // == WHAT FOLLOWS IS VERSIONS OF THE MACROS THAT DO NOT DO ANY REGISTERING! == // == THIS CAN BE ENABLED BY DEFINING DOCTEST_CONFIG_DISABLE GLOBALLY! == // ================================================================================================= #else // DOCTEST_CONFIG_DISABLE #define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, name) \ namespace /* NOLINT */ { \ template <typename DOCTEST_UNUSED_TEMPLATE_TYPE> \ struct der : public base \ { void f(); }; \ } \ template <typename DOCTEST_UNUSED_TEMPLATE_TYPE> \ inline void der<DOCTEST_UNUSED_TEMPLATE_TYPE>::f() #define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, name) \ template <typename DOCTEST_UNUSED_TEMPLATE_TYPE> \ static inline void f() // for registering tests #define DOCTEST_TEST_CASE(name) \ DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) // for registering tests in classes #define DOCTEST_TEST_CASE_CLASS(name) \ DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) // for registering tests with a fixture #define DOCTEST_TEST_CASE_FIXTURE(x, name) \ DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(DOCTEST_ANON_CLASS_), x, \ DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) // for converting types to strings without the <typeinfo> header and demangling #define DOCTEST_TYPE_TO_STRING_AS(str, ...) static_assert(true, "") #define DOCTEST_TYPE_TO_STRING(...) static_assert(true, "") // for typed tests #define DOCTEST_TEST_CASE_TEMPLATE(name, type, ...) \ template <typename type> \ inline void DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)() #define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, type, id) \ template <typename type> \ inline void DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)() #define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) static_assert(true, "") #define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) static_assert(true, "") // for subcases #define DOCTEST_SUBCASE(name) // for a testsuite block #define DOCTEST_TEST_SUITE(name) namespace // NOLINT // for starting a testsuite block #define DOCTEST_TEST_SUITE_BEGIN(name) static_assert(true, "") // for ending a testsuite block #define DOCTEST_TEST_SUITE_END using DOCTEST_ANONYMOUS(DOCTEST_ANON_FOR_SEMICOLON_) = int #define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ template <typename DOCTEST_UNUSED_TEMPLATE_TYPE> \ static inline doctest::String DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_)(signature) #define DOCTEST_REGISTER_REPORTER(name, priority, reporter) #define DOCTEST_REGISTER_LISTENER(name, priority, reporter) #define DOCTEST_INFO(...) (static_cast<void>(0)) #define DOCTEST_CAPTURE(x) (static_cast<void>(0)) #define DOCTEST_ADD_MESSAGE_AT(file, line, ...) (static_cast<void>(0)) #define DOCTEST_ADD_FAIL_CHECK_AT(file, line, ...) (static_cast<void>(0)) #define DOCTEST_ADD_FAIL_AT(file, line, ...) (static_cast<void>(0)) #define DOCTEST_MESSAGE(...) (static_cast<void>(0)) #define DOCTEST_FAIL_CHECK(...) (static_cast<void>(0)) #define DOCTEST_FAIL(...) (static_cast<void>(0)) #if defined(DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED) \ && defined(DOCTEST_CONFIG_ASSERTS_RETURN_VALUES) #define DOCTEST_WARN(...) [&] { return __VA_ARGS__; }() #define DOCTEST_CHECK(...) [&] { return __VA_ARGS__; }() #define DOCTEST_REQUIRE(...) [&] { return __VA_ARGS__; }() #define DOCTEST_WARN_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_CHECK_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_REQUIRE_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_WARN_MESSAGE(cond, ...) [&] { return cond; }() #define DOCTEST_CHECK_MESSAGE(cond, ...) [&] { return cond; }() #define DOCTEST_REQUIRE_MESSAGE(cond, ...) [&] { return cond; }() #define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() #define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() #define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() namespace doctest { namespace detail { #define DOCTEST_RELATIONAL_OP(name, op) \ template <typename L, typename R> \ bool name(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) { return lhs op rhs; } DOCTEST_RELATIONAL_OP(eq, ==) DOCTEST_RELATIONAL_OP(ne, !=) DOCTEST_RELATIONAL_OP(lt, <) DOCTEST_RELATIONAL_OP(gt, >) DOCTEST_RELATIONAL_OP(le, <=) DOCTEST_RELATIONAL_OP(ge, >=) } // namespace detail } // namespace doctest #define DOCTEST_WARN_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() #define DOCTEST_CHECK_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() #define DOCTEST_REQUIRE_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() #define DOCTEST_WARN_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() #define DOCTEST_CHECK_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() #define DOCTEST_REQUIRE_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() #define DOCTEST_WARN_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() #define DOCTEST_CHECK_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() #define DOCTEST_REQUIRE_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() #define DOCTEST_WARN_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() #define DOCTEST_CHECK_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() #define DOCTEST_REQUIRE_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() #define DOCTEST_WARN_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() #define DOCTEST_CHECK_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() #define DOCTEST_REQUIRE_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() #define DOCTEST_WARN_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() #define DOCTEST_CHECK_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() #define DOCTEST_REQUIRE_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() #define DOCTEST_WARN_UNARY(...) [&] { return __VA_ARGS__; }() #define DOCTEST_CHECK_UNARY(...) [&] { return __VA_ARGS__; }() #define DOCTEST_REQUIRE_UNARY(...) [&] { return __VA_ARGS__; }() #define DOCTEST_WARN_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_CHECK_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_REQUIRE_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #define DOCTEST_WARN_THROWS_WITH(expr, with, ...) [] { static_assert(false, "Exception translation is not available when doctest is disabled."); return false; }() #define DOCTEST_CHECK_THROWS_WITH(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_REQUIRE_THROWS_WITH(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_WARN_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_CHECK_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_REQUIRE_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_WARN_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_CHECK_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_REQUIRE_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_WARN_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_CHECK_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_REQUIRE_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #endif // DOCTEST_CONFIG_NO_EXCEPTIONS #else // DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED #define DOCTEST_WARN(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_EQ(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_EQ(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_EQ(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_NE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_NE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_NE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_GT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_GT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_GT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_LT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_LT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_LT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_GE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_GE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_GE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_LE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_LE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_LE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_UNARY(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_UNARY(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_UNARY(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #define DOCTEST_WARN_THROWS(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_NOTHROW(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_NOTHROW(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #endif // DOCTEST_CONFIG_NO_EXCEPTIONS #endif // DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED #endif // DOCTEST_CONFIG_DISABLE #ifdef DOCTEST_CONFIG_NO_EXCEPTIONS #ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #define DOCTEST_EXCEPTION_EMPTY_FUNC DOCTEST_FUNC_EMPTY #else // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #define DOCTEST_EXCEPTION_EMPTY_FUNC [] { static_assert(false, "Exceptions are disabled! " \ "Use DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS if you want to compile with exceptions disabled."); return false; }() #undef DOCTEST_REQUIRE #undef DOCTEST_REQUIRE_FALSE #undef DOCTEST_REQUIRE_MESSAGE #undef DOCTEST_REQUIRE_FALSE_MESSAGE #undef DOCTEST_REQUIRE_EQ #undef DOCTEST_REQUIRE_NE #undef DOCTEST_REQUIRE_GT #undef DOCTEST_REQUIRE_LT #undef DOCTEST_REQUIRE_GE #undef DOCTEST_REQUIRE_LE #undef DOCTEST_REQUIRE_UNARY #undef DOCTEST_REQUIRE_UNARY_FALSE #define DOCTEST_REQUIRE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_FALSE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_MESSAGE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_FALSE_MESSAGE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_EQ DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_NE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_GT DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_LT DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_GE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_LE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_UNARY DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_UNARY_FALSE DOCTEST_EXCEPTION_EMPTY_FUNC #endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #define DOCTEST_WARN_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #endif // DOCTEST_CONFIG_NO_EXCEPTIONS // clang-format off // KEPT FOR BACKWARDS COMPATIBILITY - FORWARDING TO THE RIGHT MACROS #define DOCTEST_FAST_WARN_EQ DOCTEST_WARN_EQ #define DOCTEST_FAST_CHECK_EQ DOCTEST_CHECK_EQ #define DOCTEST_FAST_REQUIRE_EQ DOCTEST_REQUIRE_EQ #define DOCTEST_FAST_WARN_NE DOCTEST_WARN_NE #define DOCTEST_FAST_CHECK_NE DOCTEST_CHECK_NE #define DOCTEST_FAST_REQUIRE_NE DOCTEST_REQUIRE_NE #define DOCTEST_FAST_WARN_GT DOCTEST_WARN_GT #define DOCTEST_FAST_CHECK_GT DOCTEST_CHECK_GT #define DOCTEST_FAST_REQUIRE_GT DOCTEST_REQUIRE_GT #define DOCTEST_FAST_WARN_LT DOCTEST_WARN_LT #define DOCTEST_FAST_CHECK_LT DOCTEST_CHECK_LT #define DOCTEST_FAST_REQUIRE_LT DOCTEST_REQUIRE_LT #define DOCTEST_FAST_WARN_GE DOCTEST_WARN_GE #define DOCTEST_FAST_CHECK_GE DOCTEST_CHECK_GE #define DOCTEST_FAST_REQUIRE_GE DOCTEST_REQUIRE_GE #define DOCTEST_FAST_WARN_LE DOCTEST_WARN_LE #define DOCTEST_FAST_CHECK_LE DOCTEST_CHECK_LE #define DOCTEST_FAST_REQUIRE_LE DOCTEST_REQUIRE_LE #define DOCTEST_FAST_WARN_UNARY DOCTEST_WARN_UNARY #define DOCTEST_FAST_CHECK_UNARY DOCTEST_CHECK_UNARY #define DOCTEST_FAST_REQUIRE_UNARY DOCTEST_REQUIRE_UNARY #define DOCTEST_FAST_WARN_UNARY_FALSE DOCTEST_WARN_UNARY_FALSE #define DOCTEST_FAST_CHECK_UNARY_FALSE DOCTEST_CHECK_UNARY_FALSE #define DOCTEST_FAST_REQUIRE_UNARY_FALSE DOCTEST_REQUIRE_UNARY_FALSE #define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id,__VA_ARGS__) // clang-format on // BDD style macros // clang-format off #define DOCTEST_SCENARIO(name) DOCTEST_TEST_CASE(" Scenario: " name) #define DOCTEST_SCENARIO_CLASS(name) DOCTEST_TEST_CASE_CLASS(" Scenario: " name) #define DOCTEST_SCENARIO_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(" Scenario: " name, T, __VA_ARGS__) #define DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(" Scenario: " name, T, id) #define DOCTEST_GIVEN(name) DOCTEST_SUBCASE(" Given: " name) #define DOCTEST_WHEN(name) DOCTEST_SUBCASE(" When: " name) #define DOCTEST_AND_WHEN(name) DOCTEST_SUBCASE("And when: " name) #define DOCTEST_THEN(name) DOCTEST_SUBCASE(" Then: " name) #define DOCTEST_AND_THEN(name) DOCTEST_SUBCASE(" And: " name) // clang-format on // == SHORT VERSIONS OF THE MACROS #ifndef DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES #define TEST_CASE(name) DOCTEST_TEST_CASE(name) #define TEST_CASE_CLASS(name) DOCTEST_TEST_CASE_CLASS(name) #define TEST_CASE_FIXTURE(x, name) DOCTEST_TEST_CASE_FIXTURE(x, name) #define TYPE_TO_STRING_AS(str, ...) DOCTEST_TYPE_TO_STRING_AS(str, __VA_ARGS__) #define TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING(__VA_ARGS__) #define TEST_CASE_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(name, T, __VA_ARGS__) #define TEST_CASE_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, T, id) #define TEST_CASE_TEMPLATE_INVOKE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, __VA_ARGS__) #define TEST_CASE_TEMPLATE_APPLY(id, ...) DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, __VA_ARGS__) #define SUBCASE(name) DOCTEST_SUBCASE(name) #define TEST_SUITE(decorators) DOCTEST_TEST_SUITE(decorators) #define TEST_SUITE_BEGIN(name) DOCTEST_TEST_SUITE_BEGIN(name) #define TEST_SUITE_END DOCTEST_TEST_SUITE_END #define REGISTER_EXCEPTION_TRANSLATOR(signature) DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) #define REGISTER_REPORTER(name, priority, reporter) DOCTEST_REGISTER_REPORTER(name, priority, reporter) #define REGISTER_LISTENER(name, priority, reporter) DOCTEST_REGISTER_LISTENER(name, priority, reporter) #define INFO(...) DOCTEST_INFO(__VA_ARGS__) #define CAPTURE(x) DOCTEST_CAPTURE(x) #define ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_MESSAGE_AT(file, line, __VA_ARGS__) #define ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_FAIL_CHECK_AT(file, line, __VA_ARGS__) #define ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_FAIL_AT(file, line, __VA_ARGS__) #define MESSAGE(...) DOCTEST_MESSAGE(__VA_ARGS__) #define FAIL_CHECK(...) DOCTEST_FAIL_CHECK(__VA_ARGS__) #define FAIL(...) DOCTEST_FAIL(__VA_ARGS__) #define TO_LVALUE(...) DOCTEST_TO_LVALUE(__VA_ARGS__) #define WARN(...) DOCTEST_WARN(__VA_ARGS__) #define WARN_FALSE(...) DOCTEST_WARN_FALSE(__VA_ARGS__) #define WARN_THROWS(...) DOCTEST_WARN_THROWS(__VA_ARGS__) #define WARN_THROWS_AS(expr, ...) DOCTEST_WARN_THROWS_AS(expr, __VA_ARGS__) #define WARN_THROWS_WITH(expr, ...) DOCTEST_WARN_THROWS_WITH(expr, __VA_ARGS__) #define WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_WARN_THROWS_WITH_AS(expr, with, __VA_ARGS__) #define WARN_NOTHROW(...) DOCTEST_WARN_NOTHROW(__VA_ARGS__) #define CHECK(...) DOCTEST_CHECK(__VA_ARGS__) #define CHECK_FALSE(...) DOCTEST_CHECK_FALSE(__VA_ARGS__) #define CHECK_THROWS(...) DOCTEST_CHECK_THROWS(__VA_ARGS__) #define CHECK_THROWS_AS(expr, ...) DOCTEST_CHECK_THROWS_AS(expr, __VA_ARGS__) #define CHECK_THROWS_WITH(expr, ...) DOCTEST_CHECK_THROWS_WITH(expr, __VA_ARGS__) #define CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_AS(expr, with, __VA_ARGS__) #define CHECK_NOTHROW(...) DOCTEST_CHECK_NOTHROW(__VA_ARGS__) #define REQUIRE(...) DOCTEST_REQUIRE(__VA_ARGS__) #define REQUIRE_FALSE(...) DOCTEST_REQUIRE_FALSE(__VA_ARGS__) #define REQUIRE_THROWS(...) DOCTEST_REQUIRE_THROWS(__VA_ARGS__) #define REQUIRE_THROWS_AS(expr, ...) DOCTEST_REQUIRE_THROWS_AS(expr, __VA_ARGS__) #define REQUIRE_THROWS_WITH(expr, ...) DOCTEST_REQUIRE_THROWS_WITH(expr, __VA_ARGS__) #define REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, __VA_ARGS__) #define REQUIRE_NOTHROW(...) DOCTEST_REQUIRE_NOTHROW(__VA_ARGS__) #define WARN_MESSAGE(cond, ...) DOCTEST_WARN_MESSAGE(cond, __VA_ARGS__) #define WARN_FALSE_MESSAGE(cond, ...) DOCTEST_WARN_FALSE_MESSAGE(cond, __VA_ARGS__) #define WARN_THROWS_MESSAGE(expr, ...) DOCTEST_WARN_THROWS_MESSAGE(expr, __VA_ARGS__) #define WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) #define WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) #define WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) #define WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_WARN_NOTHROW_MESSAGE(expr, __VA_ARGS__) #define CHECK_MESSAGE(cond, ...) DOCTEST_CHECK_MESSAGE(cond, __VA_ARGS__) #define CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_CHECK_FALSE_MESSAGE(cond, __VA_ARGS__) #define CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_CHECK_THROWS_MESSAGE(expr, __VA_ARGS__) #define CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) #define CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) #define CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) #define CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_CHECK_NOTHROW_MESSAGE(expr, __VA_ARGS__) #define REQUIRE_MESSAGE(cond, ...) DOCTEST_REQUIRE_MESSAGE(cond, __VA_ARGS__) #define REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_REQUIRE_FALSE_MESSAGE(cond, __VA_ARGS__) #define REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_REQUIRE_THROWS_MESSAGE(expr, __VA_ARGS__) #define REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) #define REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) #define REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) #define REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, __VA_ARGS__) #define SCENARIO(name) DOCTEST_SCENARIO(name) #define SCENARIO_CLASS(name) DOCTEST_SCENARIO_CLASS(name) #define SCENARIO_TEMPLATE(name, T, ...) DOCTEST_SCENARIO_TEMPLATE(name, T, __VA_ARGS__) #define SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) #define GIVEN(name) DOCTEST_GIVEN(name) #define WHEN(name) DOCTEST_WHEN(name) #define AND_WHEN(name) DOCTEST_AND_WHEN(name) #define THEN(name) DOCTEST_THEN(name) #define AND_THEN(name) DOCTEST_AND_THEN(name) #define WARN_EQ(...) DOCTEST_WARN_EQ(__VA_ARGS__) #define CHECK_EQ(...) DOCTEST_CHECK_EQ(__VA_ARGS__) #define REQUIRE_EQ(...) DOCTEST_REQUIRE_EQ(__VA_ARGS__) #define WARN_NE(...) DOCTEST_WARN_NE(__VA_ARGS__) #define CHECK_NE(...) DOCTEST_CHECK_NE(__VA_ARGS__) #define REQUIRE_NE(...) DOCTEST_REQUIRE_NE(__VA_ARGS__) #define WARN_GT(...) DOCTEST_WARN_GT(__VA_ARGS__) #define CHECK_GT(...) DOCTEST_CHECK_GT(__VA_ARGS__) #define REQUIRE_GT(...) DOCTEST_REQUIRE_GT(__VA_ARGS__) #define WARN_LT(...) DOCTEST_WARN_LT(__VA_ARGS__) #define CHECK_LT(...) DOCTEST_CHECK_LT(__VA_ARGS__) #define REQUIRE_LT(...) DOCTEST_REQUIRE_LT(__VA_ARGS__) #define WARN_GE(...) DOCTEST_WARN_GE(__VA_ARGS__) #define CHECK_GE(...) DOCTEST_CHECK_GE(__VA_ARGS__) #define REQUIRE_GE(...) DOCTEST_REQUIRE_GE(__VA_ARGS__) #define WARN_LE(...) DOCTEST_WARN_LE(__VA_ARGS__) #define CHECK_LE(...) DOCTEST_CHECK_LE(__VA_ARGS__) #define REQUIRE_LE(...) DOCTEST_REQUIRE_LE(__VA_ARGS__) #define WARN_UNARY(...) DOCTEST_WARN_UNARY(__VA_ARGS__) #define CHECK_UNARY(...) DOCTEST_CHECK_UNARY(__VA_ARGS__) #define REQUIRE_UNARY(...) DOCTEST_REQUIRE_UNARY(__VA_ARGS__) #define WARN_UNARY_FALSE(...) DOCTEST_WARN_UNARY_FALSE(__VA_ARGS__) #define CHECK_UNARY_FALSE(...) DOCTEST_CHECK_UNARY_FALSE(__VA_ARGS__) #define REQUIRE_UNARY_FALSE(...) DOCTEST_REQUIRE_UNARY_FALSE(__VA_ARGS__) // KEPT FOR BACKWARDS COMPATIBILITY #define FAST_WARN_EQ(...) DOCTEST_FAST_WARN_EQ(__VA_ARGS__) #define FAST_CHECK_EQ(...) DOCTEST_FAST_CHECK_EQ(__VA_ARGS__) #define FAST_REQUIRE_EQ(...) DOCTEST_FAST_REQUIRE_EQ(__VA_ARGS__) #define FAST_WARN_NE(...) DOCTEST_FAST_WARN_NE(__VA_ARGS__) #define FAST_CHECK_NE(...) DOCTEST_FAST_CHECK_NE(__VA_ARGS__) #define FAST_REQUIRE_NE(...) DOCTEST_FAST_REQUIRE_NE(__VA_ARGS__) #define FAST_WARN_GT(...) DOCTEST_FAST_WARN_GT(__VA_ARGS__) #define FAST_CHECK_GT(...) DOCTEST_FAST_CHECK_GT(__VA_ARGS__) #define FAST_REQUIRE_GT(...) DOCTEST_FAST_REQUIRE_GT(__VA_ARGS__) #define FAST_WARN_LT(...) DOCTEST_FAST_WARN_LT(__VA_ARGS__) #define FAST_CHECK_LT(...) DOCTEST_FAST_CHECK_LT(__VA_ARGS__) #define FAST_REQUIRE_LT(...) DOCTEST_FAST_REQUIRE_LT(__VA_ARGS__) #define FAST_WARN_GE(...) DOCTEST_FAST_WARN_GE(__VA_ARGS__) #define FAST_CHECK_GE(...) DOCTEST_FAST_CHECK_GE(__VA_ARGS__) #define FAST_REQUIRE_GE(...) DOCTEST_FAST_REQUIRE_GE(__VA_ARGS__) #define FAST_WARN_LE(...) DOCTEST_FAST_WARN_LE(__VA_ARGS__) #define FAST_CHECK_LE(...) DOCTEST_FAST_CHECK_LE(__VA_ARGS__) #define FAST_REQUIRE_LE(...) DOCTEST_FAST_REQUIRE_LE(__VA_ARGS__) #define FAST_WARN_UNARY(...) DOCTEST_FAST_WARN_UNARY(__VA_ARGS__) #define FAST_CHECK_UNARY(...) DOCTEST_FAST_CHECK_UNARY(__VA_ARGS__) #define FAST_REQUIRE_UNARY(...) DOCTEST_FAST_REQUIRE_UNARY(__VA_ARGS__) #define FAST_WARN_UNARY_FALSE(...) DOCTEST_FAST_WARN_UNARY_FALSE(__VA_ARGS__) #define FAST_CHECK_UNARY_FALSE(...) DOCTEST_FAST_CHECK_UNARY_FALSE(__VA_ARGS__) #define FAST_REQUIRE_UNARY_FALSE(...) DOCTEST_FAST_REQUIRE_UNARY_FALSE(__VA_ARGS__) #define TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, __VA_ARGS__) #endif // DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES #ifndef DOCTEST_CONFIG_DISABLE // this is here to clear the 'current test suite' for the current translation unit - at the top DOCTEST_TEST_SUITE_END(); #endif // DOCTEST_CONFIG_DISABLE DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP DOCTEST_SUPPRESS_COMMON_WARNINGS_POP #endif // DOCTEST_LIBRARY_INCLUDED #ifndef DOCTEST_SINGLE_HEADER #define DOCTEST_SINGLE_HEADER #endif // DOCTEST_SINGLE_HEADER #if defined(DOCTEST_CONFIG_IMPLEMENT) || !defined(DOCTEST_SINGLE_HEADER) #ifndef DOCTEST_SINGLE_HEADER #include "doctest_fwd.h" #endif // DOCTEST_SINGLE_HEADER DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-macros") #ifndef DOCTEST_LIBRARY_IMPLEMENTATION #define DOCTEST_LIBRARY_IMPLEMENTATION DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wglobal-constructors") DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors") DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") DOCTEST_CLANG_SUPPRESS_WARNING("-Wshorten-64-to-32") DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-variable-declarations") DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch") DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch-enum") DOCTEST_CLANG_SUPPRESS_WARNING("-Wcovered-switch-default") DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-noreturn") DOCTEST_CLANG_SUPPRESS_WARNING("-Wdisabled-macro-expansion") DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-braces") DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-field-initializers") DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-member-function") DOCTEST_CLANG_SUPPRESS_WARNING("-Wnonportable-system-include-path") DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-field-initializers") DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-braces") DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch") DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-enum") DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-default") DOCTEST_GCC_SUPPRESS_WARNING("-Wunsafe-loop-optimizations") DOCTEST_GCC_SUPPRESS_WARNING("-Wold-style-cast") DOCTEST_GCC_SUPPRESS_WARNING("-Wunused-function") DOCTEST_GCC_SUPPRESS_WARNING("-Wmultiple-inheritance") DOCTEST_GCC_SUPPRESS_WARNING("-Wsuggest-attribute") DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(4267) // 'var' : conversion from 'x' to 'y', possible loss of data DOCTEST_MSVC_SUPPRESS_WARNING(4530) // C++ exception handler used, but unwind semantics not enabled DOCTEST_MSVC_SUPPRESS_WARNING(4577) // 'noexcept' used with no exception handling mode specified DOCTEST_MSVC_SUPPRESS_WARNING(4774) // format string expected in argument is not a string literal DOCTEST_MSVC_SUPPRESS_WARNING(4365) // conversion from 'int' to 'unsigned', signed/unsigned mismatch DOCTEST_MSVC_SUPPRESS_WARNING(5039) // pointer to potentially throwing function passed to extern C DOCTEST_MSVC_SUPPRESS_WARNING(4800) // forcing value to bool 'true' or 'false' (performance warning) DOCTEST_MSVC_SUPPRESS_WARNING(5245) // unreferenced function with internal linkage has been removed DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN // required includes - will go only in one translation unit! #include <ctime> #include <cmath> #include <climits> // borland (Embarcadero) compiler requires math.h and not cmath - https://github.com/doctest/doctest/pull/37 #ifdef __BORLANDC__ #include <math.h> #endif // __BORLANDC__ #include <new> #include <cstdio> #include <cstdlib> #include <cstring> #include <limits> #include <utility> #include <fstream> #include <sstream> #ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM #include <iostream> #endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM #include <algorithm> #include <iomanip> #include <vector> #ifndef DOCTEST_CONFIG_NO_MULTITHREADING #include <atomic> #include <mutex> #define DOCTEST_DECLARE_MUTEX(name) std::mutex name; #define DOCTEST_DECLARE_STATIC_MUTEX(name) static DOCTEST_DECLARE_MUTEX(name) #define DOCTEST_LOCK_MUTEX(name) std::lock_guard<std::mutex> DOCTEST_ANONYMOUS(DOCTEST_ANON_LOCK_)(name); #else // DOCTEST_CONFIG_NO_MULTITHREADING #define DOCTEST_DECLARE_MUTEX(name) #define DOCTEST_DECLARE_STATIC_MUTEX(name) #define DOCTEST_LOCK_MUTEX(name) #endif // DOCTEST_CONFIG_NO_MULTITHREADING #include <set> #include <map> #include <unordered_set> #include <exception> #include <stdexcept> #include <csignal> #include <cfloat> #include <cctype> #include <cstdint> #include <string> #ifdef DOCTEST_PLATFORM_MAC #include <sys/types.h> #include <unistd.h> #include <sys/sysctl.h> #endif // DOCTEST_PLATFORM_MAC #ifdef DOCTEST_PLATFORM_WINDOWS // defines for a leaner windows.h #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN #endif // WIN32_LEAN_AND_MEAN #ifndef NOMINMAX #define NOMINMAX #define DOCTEST_UNDEF_NOMINMAX #endif // NOMINMAX // not sure what AfxWin.h is for - here I do what Catch does #ifdef __AFXDLL #include <AfxWin.h> #else #include <windows.h> #endif #include <io.h> #else // DOCTEST_PLATFORM_WINDOWS #include <sys/time.h> #include <unistd.h> #endif // DOCTEST_PLATFORM_WINDOWS // this is a fix for https://github.com/doctest/doctest/issues/348 // https://mail.gnome.org/archives/xml/2012-January/msg00000.html #if !defined(HAVE_UNISTD_H) && !defined(STDOUT_FILENO) #define STDOUT_FILENO fileno(stdout) #endif // HAVE_UNISTD_H DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END // counts the number of elements in a C array #define DOCTEST_COUNTOF(x) (sizeof(x) / sizeof(x[0])) #ifdef DOCTEST_CONFIG_DISABLE #define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_disabled #else // DOCTEST_CONFIG_DISABLE #define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_not_disabled #endif // DOCTEST_CONFIG_DISABLE #ifndef DOCTEST_CONFIG_OPTIONS_PREFIX #define DOCTEST_CONFIG_OPTIONS_PREFIX "dt-" #endif #ifndef DOCTEST_THREAD_LOCAL #if defined(DOCTEST_CONFIG_NO_MULTITHREADING) || DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) #define DOCTEST_THREAD_LOCAL #else // DOCTEST_MSVC #define DOCTEST_THREAD_LOCAL thread_local #endif // DOCTEST_MSVC #endif // DOCTEST_THREAD_LOCAL #ifndef DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES #define DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES 32 #endif #ifndef DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE #define DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE 64 #endif #ifdef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS #define DOCTEST_OPTIONS_PREFIX_DISPLAY DOCTEST_CONFIG_OPTIONS_PREFIX #else #define DOCTEST_OPTIONS_PREFIX_DISPLAY "" #endif #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) #define DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS #endif #ifndef DOCTEST_CDECL #define DOCTEST_CDECL __cdecl #endif namespace doctest { bool is_running_in_test = false; namespace { using namespace detail; template <typename Ex> DOCTEST_NORETURN void throw_exception(Ex const& e) { #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS throw e; #else // DOCTEST_CONFIG_NO_EXCEPTIONS #ifdef DOCTEST_CONFIG_HANDLE_EXCEPTION DOCTEST_CONFIG_HANDLE_EXCEPTION(e); #else // DOCTEST_CONFIG_HANDLE_EXCEPTION #ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM std::cerr << "doctest will terminate because it needed to throw an exception.\n" << "The message was: " << e.what() << '\n'; #endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM #endif // DOCTEST_CONFIG_HANDLE_EXCEPTION std::terminate(); #endif // DOCTEST_CONFIG_NO_EXCEPTIONS } #ifndef DOCTEST_INTERNAL_ERROR #define DOCTEST_INTERNAL_ERROR(msg) \ throw_exception(std::logic_error( \ __FILE__ ":" DOCTEST_TOSTR(__LINE__) ": Internal doctest error: " msg)) #endif // DOCTEST_INTERNAL_ERROR // case insensitive strcmp int stricmp(const char* a, const char* b) { for(;; a++, b++) { const int d = tolower(*a) - tolower(*b); if(d != 0 || !*a) return d; } } struct Endianness { enum Arch { Big, Little }; static Arch which() { int x = 1; // casting any data pointer to char* is allowed auto ptr = reinterpret_cast<char*>(&x); if(*ptr) return Little; return Big; } }; } // namespace namespace detail { DOCTEST_THREAD_LOCAL class { std::vector<std::streampos> stack; std::stringstream ss; public: std::ostream* push() { stack.push_back(ss.tellp()); return &ss; } String pop() { if (stack.empty()) DOCTEST_INTERNAL_ERROR("TLSS was empty when trying to pop!"); std::streampos pos = stack.back(); stack.pop_back(); unsigned sz = static_cast<unsigned>(ss.tellp() - pos); ss.rdbuf()->pubseekpos(pos, std::ios::in | std::ios::out); return String(ss, sz); } } g_oss; std::ostream* tlssPush() { return g_oss.push(); } String tlssPop() { return g_oss.pop(); } #ifndef DOCTEST_CONFIG_DISABLE namespace timer_large_integer { #if defined(DOCTEST_PLATFORM_WINDOWS) using type = ULONGLONG; #else // DOCTEST_PLATFORM_WINDOWS using type = std::uint64_t; #endif // DOCTEST_PLATFORM_WINDOWS } using ticks_t = timer_large_integer::type; #ifdef DOCTEST_CONFIG_GETCURRENTTICKS ticks_t getCurrentTicks() { return DOCTEST_CONFIG_GETCURRENTTICKS(); } #elif defined(DOCTEST_PLATFORM_WINDOWS) ticks_t getCurrentTicks() { static LARGE_INTEGER hz = { {0} }, hzo = { {0} }; if(!hz.QuadPart) { QueryPerformanceFrequency(&hz); QueryPerformanceCounter(&hzo); } LARGE_INTEGER t; QueryPerformanceCounter(&t); return ((t.QuadPart - hzo.QuadPart) * LONGLONG(1000000)) / hz.QuadPart; } #else // DOCTEST_PLATFORM_WINDOWS ticks_t getCurrentTicks() { timeval t; gettimeofday(&t, nullptr); return static_cast<ticks_t>(t.tv_sec) * 1000000 + static_cast<ticks_t>(t.tv_usec); } #endif // DOCTEST_PLATFORM_WINDOWS struct Timer { void start() { m_ticks = getCurrentTicks(); } unsigned int getElapsedMicroseconds() const { return static_cast<unsigned int>(getCurrentTicks() - m_ticks); } //unsigned int getElapsedMilliseconds() const { // return static_cast<unsigned int>(getElapsedMicroseconds() / 1000); //} double getElapsedSeconds() const { return static_cast<double>(getCurrentTicks() - m_ticks) / 1000000.0; } private: ticks_t m_ticks = 0; }; #ifdef DOCTEST_CONFIG_NO_MULTITHREADING template <typename T> using Atomic = T; #else // DOCTEST_CONFIG_NO_MULTITHREADING template <typename T> using Atomic = std::atomic<T>; #endif // DOCTEST_CONFIG_NO_MULTITHREADING #if defined(DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS) || defined(DOCTEST_CONFIG_NO_MULTITHREADING) template <typename T> using MultiLaneAtomic = Atomic<T>; #else // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS // Provides a multilane implementation of an atomic variable that supports add, sub, load, // store. Instead of using a single atomic variable, this splits up into multiple ones, // each sitting on a separate cache line. The goal is to provide a speedup when most // operations are modifying. It achieves this with two properties: // // * Multiple atomics are used, so chance of congestion from the same atomic is reduced. // * Each atomic sits on a separate cache line, so false sharing is reduced. // // The disadvantage is that there is a small overhead due to the use of TLS, and load/store // is slower because all atomics have to be accessed. template <typename T> class MultiLaneAtomic { struct CacheLineAlignedAtomic { Atomic<T> atomic{}; char padding[DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE - sizeof(Atomic<T>)]; }; CacheLineAlignedAtomic m_atomics[DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES]; static_assert(sizeof(CacheLineAlignedAtomic) == DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE, "guarantee one atomic takes exactly one cache line"); public: T operator++() DOCTEST_NOEXCEPT { return fetch_add(1) + 1; } T operator++(int) DOCTEST_NOEXCEPT { return fetch_add(1); } T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { return myAtomic().fetch_add(arg, order); } T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { return myAtomic().fetch_sub(arg, order); } operator T() const DOCTEST_NOEXCEPT { return load(); } T load(std::memory_order order = std::memory_order_seq_cst) const DOCTEST_NOEXCEPT { auto result = T(); for(auto const& c : m_atomics) { result += c.atomic.load(order); } return result; } T operator=(T desired) DOCTEST_NOEXCEPT { // lgtm [cpp/assignment-does-not-return-this] store(desired); return desired; } void store(T desired, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { // first value becomes desired", all others become 0. for(auto& c : m_atomics) { c.atomic.store(desired, order); desired = {}; } } private: // Each thread has a different atomic that it operates on. If more than NumLanes threads // use this, some will use the same atomic. So performance will degrade a bit, but still // everything will work. // // The logic here is a bit tricky. The call should be as fast as possible, so that there // is minimal to no overhead in determining the correct atomic for the current thread. // // 1. A global static counter laneCounter counts continuously up. // 2. Each successive thread will use modulo operation of that counter so it gets an atomic // assigned in a round-robin fashion. // 3. This tlsLaneIdx is stored in the thread local data, so it is directly available with // little overhead. Atomic<T>& myAtomic() DOCTEST_NOEXCEPT { static Atomic<size_t> laneCounter; DOCTEST_THREAD_LOCAL size_t tlsLaneIdx = laneCounter++ % DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES; return m_atomics[tlsLaneIdx].atomic; } }; #endif // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS // this holds both parameters from the command line and runtime data for tests struct ContextState : ContextOptions, TestRunStats, CurrentTestCaseStats { MultiLaneAtomic<int> numAssertsCurrentTest_atomic; MultiLaneAtomic<int> numAssertsFailedCurrentTest_atomic; std::vector<std::vector<String>> filters = decltype(filters)(9); // 9 different filters std::vector<IReporter*> reporters_currently_used; assert_handler ah = nullptr; Timer timer; std::vector<String> stringifiedContexts; // logging from INFO() due to an exception // stuff for subcases bool reachedLeaf; std::vector<SubcaseSignature> subcaseStack; std::vector<SubcaseSignature> nextSubcaseStack; std::unordered_set<unsigned long long> fullyTraversedSubcases; size_t currentSubcaseDepth; Atomic<bool> shouldLogCurrentException; void resetRunData() { numTestCases = 0; numTestCasesPassingFilters = 0; numTestSuitesPassingFilters = 0; numTestCasesFailed = 0; numAsserts = 0; numAssertsFailed = 0; numAssertsCurrentTest = 0; numAssertsFailedCurrentTest = 0; } void finalizeTestCaseData() { seconds = timer.getElapsedSeconds(); // update the non-atomic counters numAsserts += numAssertsCurrentTest_atomic; numAssertsFailed += numAssertsFailedCurrentTest_atomic; numAssertsCurrentTest = numAssertsCurrentTest_atomic; numAssertsFailedCurrentTest = numAssertsFailedCurrentTest_atomic; if(numAssertsFailedCurrentTest) failure_flags |= TestCaseFailureReason::AssertFailure; if(Approx(currentTest->m_timeout).epsilon(DBL_EPSILON) != 0 && Approx(seconds).epsilon(DBL_EPSILON) > currentTest->m_timeout) failure_flags |= TestCaseFailureReason::Timeout; if(currentTest->m_should_fail) { if(failure_flags) { failure_flags |= TestCaseFailureReason::ShouldHaveFailedAndDid; } else { failure_flags |= TestCaseFailureReason::ShouldHaveFailedButDidnt; } } else if(failure_flags && currentTest->m_may_fail) { failure_flags |= TestCaseFailureReason::CouldHaveFailedAndDid; } else if(currentTest->m_expected_failures > 0) { if(numAssertsFailedCurrentTest == currentTest->m_expected_failures) { failure_flags |= TestCaseFailureReason::FailedExactlyNumTimes; } else { failure_flags |= TestCaseFailureReason::DidntFailExactlyNumTimes; } } bool ok_to_fail = (TestCaseFailureReason::ShouldHaveFailedAndDid & failure_flags) || (TestCaseFailureReason::CouldHaveFailedAndDid & failure_flags) || (TestCaseFailureReason::FailedExactlyNumTimes & failure_flags); // if any subcase has failed - the whole test case has failed testCaseSuccess = !(failure_flags && !ok_to_fail); if(!testCaseSuccess) numTestCasesFailed++; } }; ContextState* g_cs = nullptr; // used to avoid locks for the debug output // TODO: figure out if this is indeed necessary/correct - seems like either there still // could be a race or that there wouldn't be a race even if using the context directly DOCTEST_THREAD_LOCAL bool g_no_colors; #endif // DOCTEST_CONFIG_DISABLE } // namespace detail char* String::allocate(size_type sz) { if (sz <= last) { buf[sz] = '\0'; setLast(last - sz); return buf; } else { setOnHeap(); data.size = sz; data.capacity = data.size + 1; data.ptr = new char[data.capacity]; data.ptr[sz] = '\0'; return data.ptr; } } void String::setOnHeap() noexcept { *reinterpret_cast<unsigned char*>(&buf[last]) = 128; } void String::setLast(size_type in) noexcept { buf[last] = char(in); } void String::setSize(size_type sz) noexcept { if (isOnStack()) { buf[sz] = '\0'; setLast(last - sz); } else { data.ptr[sz] = '\0'; data.size = sz; } } void String::copy(const String& other) { if(other.isOnStack()) { memcpy(buf, other.buf, len); } else { memcpy(allocate(other.data.size), other.data.ptr, other.data.size); } } String::String() noexcept { buf[0] = '\0'; setLast(); } String::~String() { if(!isOnStack()) delete[] data.ptr; } // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) String::String(const char* in) : String(in, strlen(in)) {} String::String(const char* in, size_type in_size) { memcpy(allocate(in_size), in, in_size); } String::String(std::istream& in, size_type in_size) { in.read(allocate(in_size), in_size); } String::String(const String& other) { copy(other); } String& String::operator=(const String& other) { if(this != &other) { if(!isOnStack()) delete[] data.ptr; copy(other); } return *this; } String& String::operator+=(const String& other) { const size_type my_old_size = size(); const size_type other_size = other.size(); const size_type total_size = my_old_size + other_size; if(isOnStack()) { if(total_size < len) { // append to the current stack space memcpy(buf + my_old_size, other.c_str(), other_size + 1); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) setLast(last - total_size); } else { // alloc new chunk char* temp = new char[total_size + 1]; // copy current data to new location before writing in the union memcpy(temp, buf, my_old_size); // skip the +1 ('\0') for speed // update data in union setOnHeap(); data.size = total_size; data.capacity = data.size + 1; data.ptr = temp; // transfer the rest of the data memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); } } else { if(data.capacity > total_size) { // append to the current heap block data.size = total_size; memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); } else { // resize data.capacity *= 2; if(data.capacity <= total_size) data.capacity = total_size + 1; // alloc new chunk char* temp = new char[data.capacity]; // copy current data to new location before releasing it memcpy(temp, data.ptr, my_old_size); // skip the +1 ('\0') for speed // release old chunk delete[] data.ptr; // update the rest of the union members data.size = total_size; data.ptr = temp; // transfer the rest of the data memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); } } return *this; } String::String(String&& other) noexcept { memcpy(buf, other.buf, len); other.buf[0] = '\0'; other.setLast(); } String& String::operator=(String&& other) noexcept { if(this != &other) { if(!isOnStack()) delete[] data.ptr; memcpy(buf, other.buf, len); other.buf[0] = '\0'; other.setLast(); } return *this; } char String::operator[](size_type i) const { return const_cast<String*>(this)->operator[](i); } char& String::operator[](size_type i) { if(isOnStack()) return reinterpret_cast<char*>(buf)[i]; return data.ptr[i]; } DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmaybe-uninitialized") String::size_type String::size() const { if(isOnStack()) return last - (size_type(buf[last]) & 31); // using "last" would work only if "len" is 32 return data.size; } DOCTEST_GCC_SUPPRESS_WARNING_POP String::size_type String::capacity() const { if(isOnStack()) return len; return data.capacity; } String String::substr(size_type pos, size_type cnt) && { cnt = std::min(cnt, size() - 1 - pos); char* cptr = c_str(); memmove(cptr, cptr + pos, cnt); setSize(cnt); return std::move(*this); } String String::substr(size_type pos, size_type cnt) const & { cnt = std::min(cnt, size() - 1 - pos); return String{ c_str() + pos, cnt }; } String::size_type String::find(char ch, size_type pos) const { const char* begin = c_str(); const char* end = begin + size(); const char* it = begin + pos; for (; it < end && *it != ch; it++); if (it < end) { return static_cast<size_type>(it - begin); } else { return npos; } } String::size_type String::rfind(char ch, size_type pos) const { const char* begin = c_str(); const char* it = begin + std::min(pos, size() - 1); for (; it >= begin && *it != ch; it--); if (it >= begin) { return static_cast<size_type>(it - begin); } else { return npos; } } int String::compare(const char* other, bool no_case) const { if(no_case) return doctest::stricmp(c_str(), other); return std::strcmp(c_str(), other); } int String::compare(const String& other, bool no_case) const { return compare(other.c_str(), no_case); } String operator+(const String& lhs, const String& rhs) { return String(lhs) += rhs; } bool operator==(const String& lhs, const String& rhs) { return lhs.compare(rhs) == 0; } bool operator!=(const String& lhs, const String& rhs) { return lhs.compare(rhs) != 0; } bool operator< (const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; } bool operator> (const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; } bool operator<=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) < 0 : true; } bool operator>=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) > 0 : true; } std::ostream& operator<<(std::ostream& s, const String& in) { return s << in.c_str(); } Contains::Contains(const String& str) : string(str) { } bool Contains::checkWith(const String& other) const { return strstr(other.c_str(), string.c_str()) != nullptr; } String toString(const Contains& in) { return "Contains( " + in.string + " )"; } bool operator==(const String& lhs, const Contains& rhs) { return rhs.checkWith(lhs); } bool operator==(const Contains& lhs, const String& rhs) { return lhs.checkWith(rhs); } bool operator!=(const String& lhs, const Contains& rhs) { return !rhs.checkWith(lhs); } bool operator!=(const Contains& lhs, const String& rhs) { return !lhs.checkWith(rhs); } namespace { void color_to_stream(std::ostream&, Color::Enum) DOCTEST_BRANCH_ON_DISABLED({}, ;) } // namespace namespace Color { std::ostream& operator<<(std::ostream& s, Color::Enum code) { color_to_stream(s, code); return s; } } // namespace Color // clang-format off const char* assertString(assertType::Enum at) { DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4061) // enum 'x' in switch of enum 'y' is not explicitly handled #define DOCTEST_GENERATE_ASSERT_TYPE_CASE(assert_type) case assertType::DT_ ## assert_type: return #assert_type #define DOCTEST_GENERATE_ASSERT_TYPE_CASES(assert_type) \ DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN_ ## assert_type); \ DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK_ ## assert_type); \ DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE_ ## assert_type) switch(at) { DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN); DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK); DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(FALSE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS); DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_AS); DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH); DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH_AS); DOCTEST_GENERATE_ASSERT_TYPE_CASES(NOTHROW); DOCTEST_GENERATE_ASSERT_TYPE_CASES(EQ); DOCTEST_GENERATE_ASSERT_TYPE_CASES(NE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(GT); DOCTEST_GENERATE_ASSERT_TYPE_CASES(LT); DOCTEST_GENERATE_ASSERT_TYPE_CASES(GE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(LE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY); DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY_FALSE); default: DOCTEST_INTERNAL_ERROR("Tried stringifying invalid assert type!"); } DOCTEST_MSVC_SUPPRESS_WARNING_POP } // clang-format on const char* failureString(assertType::Enum at) { if(at & assertType::is_warn) //!OCLINT bitwise operator in conditional return "WARNING"; if(at & assertType::is_check) //!OCLINT bitwise operator in conditional return "ERROR"; if(at & assertType::is_require) //!OCLINT bitwise operator in conditional return "FATAL ERROR"; return ""; } DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") // depending on the current options this will remove the path of filenames const char* skipPathFromFilename(const char* file) { #ifndef DOCTEST_CONFIG_DISABLE if(getContextOptions()->no_path_in_filenames) { auto back = std::strrchr(file, '\\'); auto forward = std::strrchr(file, '/'); if(back || forward) { if(back > forward) forward = back; return forward + 1; } } #endif // DOCTEST_CONFIG_DISABLE return file; } DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP bool SubcaseSignature::operator==(const SubcaseSignature& other) const { return m_line == other.m_line && std::strcmp(m_file, other.m_file) == 0 && m_name == other.m_name; } bool SubcaseSignature::operator<(const SubcaseSignature& other) const { if(m_line != other.m_line) return m_line < other.m_line; if(std::strcmp(m_file, other.m_file) != 0) return std::strcmp(m_file, other.m_file) < 0; return m_name.compare(other.m_name) < 0; } DOCTEST_DEFINE_INTERFACE(IContextScope) namespace detail { void filldata<const void*>::fill(std::ostream* stream, const void* in) { if (in) { *stream << in; } else { *stream << "nullptr"; } } template <typename T> String toStreamLit(T t) { std::ostream* os = tlssPush(); os->operator<<(t); return tlssPop(); } } #ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING String toString(const char* in) { return String("\"") + (in ? in : "{null string}") + "\""; } #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) // see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 String toString(const std::string& in) { return in.c_str(); } #endif // VS 2019 String toString(String in) { return in; } String toString(std::nullptr_t) { return "nullptr"; } String toString(bool in) { return in ? "true" : "false"; } String toString(float in) { return toStreamLit(in); } String toString(double in) { return toStreamLit(in); } String toString(double long in) { return toStreamLit(in); } String toString(char in) { return toStreamLit(static_cast<signed>(in)); } String toString(char signed in) { return toStreamLit(static_cast<signed>(in)); } String toString(char unsigned in) { return toStreamLit(static_cast<unsigned>(in)); } String toString(short in) { return toStreamLit(in); } String toString(short unsigned in) { return toStreamLit(in); } String toString(signed in) { return toStreamLit(in); } String toString(unsigned in) { return toStreamLit(in); } String toString(long in) { return toStreamLit(in); } String toString(long unsigned in) { return toStreamLit(in); } String toString(long long in) { return toStreamLit(in); } String toString(long long unsigned in) { return toStreamLit(in); } Approx::Approx(double value) : m_epsilon(static_cast<double>(std::numeric_limits<float>::epsilon()) * 100) , m_scale(1.0) , m_value(value) {} Approx Approx::operator()(double value) const { Approx approx(value); approx.epsilon(m_epsilon); approx.scale(m_scale); return approx; } Approx& Approx::epsilon(double newEpsilon) { m_epsilon = newEpsilon; return *this; } Approx& Approx::scale(double newScale) { m_scale = newScale; return *this; } bool operator==(double lhs, const Approx& rhs) { // Thanks to Richard Harris for his help refining this formula return std::fabs(lhs - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + std::max<double>(std::fabs(lhs), std::fabs(rhs.m_value))); } bool operator==(const Approx& lhs, double rhs) { return operator==(rhs, lhs); } bool operator!=(double lhs, const Approx& rhs) { return !operator==(lhs, rhs); } bool operator!=(const Approx& lhs, double rhs) { return !operator==(rhs, lhs); } bool operator<=(double lhs, const Approx& rhs) { return lhs < rhs.m_value || lhs == rhs; } bool operator<=(const Approx& lhs, double rhs) { return lhs.m_value < rhs || lhs == rhs; } bool operator>=(double lhs, const Approx& rhs) { return lhs > rhs.m_value || lhs == rhs; } bool operator>=(const Approx& lhs, double rhs) { return lhs.m_value > rhs || lhs == rhs; } bool operator<(double lhs, const Approx& rhs) { return lhs < rhs.m_value && lhs != rhs; } bool operator<(const Approx& lhs, double rhs) { return lhs.m_value < rhs && lhs != rhs; } bool operator>(double lhs, const Approx& rhs) { return lhs > rhs.m_value && lhs != rhs; } bool operator>(const Approx& lhs, double rhs) { return lhs.m_value > rhs && lhs != rhs; } String toString(const Approx& in) { return "Approx( " + doctest::toString(in.m_value) + " )"; } const ContextOptions* getContextOptions() { return DOCTEST_BRANCH_ON_DISABLED(nullptr, g_cs); } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4738) template <typename F> IsNaN<F>::operator bool() const { return std::isnan(value) ^ flipped; } DOCTEST_MSVC_SUPPRESS_WARNING_POP template struct DOCTEST_INTERFACE_DEF IsNaN<float>; template struct DOCTEST_INTERFACE_DEF IsNaN<double>; template struct DOCTEST_INTERFACE_DEF IsNaN<long double>; template <typename F> String toString(IsNaN<F> in) { return String(in.flipped ? "! " : "") + "IsNaN( " + doctest::toString(in.value) + " )"; } String toString(IsNaN<float> in) { return toString<float>(in); } String toString(IsNaN<double> in) { return toString<double>(in); } String toString(IsNaN<double long> in) { return toString<double long>(in); } } // namespace doctest #ifdef DOCTEST_CONFIG_DISABLE namespace doctest { Context::Context(int, const char* const*) {} Context::~Context() = default; void Context::applyCommandLine(int, const char* const*) {} void Context::addFilter(const char*, const char*) {} void Context::clearFilters() {} void Context::setOption(const char*, bool) {} void Context::setOption(const char*, int) {} void Context::setOption(const char*, const char*) {} bool Context::shouldExit() { return false; } void Context::setAsDefaultForAssertsOutOfTestCases() {} void Context::setAssertHandler(detail::assert_handler) {} void Context::setCout(std::ostream*) {} int Context::run() { return 0; } int IReporter::get_num_active_contexts() { return 0; } const IContextScope* const* IReporter::get_active_contexts() { return nullptr; } int IReporter::get_num_stringified_contexts() { return 0; } const String* IReporter::get_stringified_contexts() { return nullptr; } int registerReporter(const char*, int, IReporter*) { return 0; } } // namespace doctest #else // DOCTEST_CONFIG_DISABLE #if !defined(DOCTEST_CONFIG_COLORS_NONE) #if !defined(DOCTEST_CONFIG_COLORS_WINDOWS) && !defined(DOCTEST_CONFIG_COLORS_ANSI) #ifdef DOCTEST_PLATFORM_WINDOWS #define DOCTEST_CONFIG_COLORS_WINDOWS #else // linux #define DOCTEST_CONFIG_COLORS_ANSI #endif // platform #endif // DOCTEST_CONFIG_COLORS_WINDOWS && DOCTEST_CONFIG_COLORS_ANSI #endif // DOCTEST_CONFIG_COLORS_NONE namespace doctest_detail_test_suite_ns { // holds the current test suite doctest::detail::TestSuite& getCurrentTestSuite() { static doctest::detail::TestSuite data{}; return data; } } // namespace doctest_detail_test_suite_ns namespace doctest { namespace { // the int (priority) is part of the key for automatic sorting - sadly one can register a // reporter with a duplicate name and a different priority but hopefully that won't happen often :| using reporterMap = std::map<std::pair<int, String>, reporterCreatorFunc>; reporterMap& getReporters() { static reporterMap data; return data; } reporterMap& getListeners() { static reporterMap data; return data; } } // namespace namespace detail { #define DOCTEST_ITERATE_THROUGH_REPORTERS(function, ...) \ for(auto& curr_rep : g_cs->reporters_currently_used) \ curr_rep->function(__VA_ARGS__) bool checkIfShouldThrow(assertType::Enum at) { if(at & assertType::is_require) //!OCLINT bitwise operator in conditional return true; if((at & assertType::is_check) //!OCLINT bitwise operator in conditional && getContextOptions()->abort_after > 0 && (g_cs->numAssertsFailed + g_cs->numAssertsFailedCurrentTest_atomic) >= getContextOptions()->abort_after) return true; return false; } #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS DOCTEST_NORETURN void throwException() { g_cs->shouldLogCurrentException = false; throw TestFailureException(); // NOLINT(hicpp-exception-baseclass) } #else // DOCTEST_CONFIG_NO_EXCEPTIONS void throwException() {} #endif // DOCTEST_CONFIG_NO_EXCEPTIONS } // namespace detail namespace { using namespace detail; // matching of a string against a wildcard mask (case sensitivity configurable) taken from // https://www.codeproject.com/Articles/1088/Wildcard-string-compare-globbing int wildcmp(const char* str, const char* wild, bool caseSensitive) { const char* cp = str; const char* mp = wild; while((*str) && (*wild != '*')) { if((caseSensitive ? (*wild != *str) : (tolower(*wild) != tolower(*str))) && (*wild != '?')) { return 0; } wild++; str++; } while(*str) { if(*wild == '*') { if(!*++wild) { return 1; } mp = wild; cp = str + 1; } else if((caseSensitive ? (*wild == *str) : (tolower(*wild) == tolower(*str))) || (*wild == '?')) { wild++; str++; } else { wild = mp; //!OCLINT parameter reassignment str = cp++; //!OCLINT parameter reassignment } } while(*wild == '*') { wild++; } return !*wild; } // checks if the name matches any of the filters (and can be configured what to do when empty) bool matchesAny(const char* name, const std::vector<String>& filters, bool matchEmpty, bool caseSensitive) { if (filters.empty() && matchEmpty) return true; for (auto& curr : filters) if (wildcmp(name, curr.c_str(), caseSensitive)) return true; return false; } DOCTEST_NO_SANITIZE_INTEGER unsigned long long hash(unsigned long long a, unsigned long long b) { return (a << 5) + b; } // C string hash function (djb2) - taken from http://www.cse.yorku.ca/~oz/hash.html DOCTEST_NO_SANITIZE_INTEGER unsigned long long hash(const char* str) { unsigned long long hash = 5381; char c; while ((c = *str++)) hash = ((hash << 5) + hash) + c; // hash * 33 + c return hash; } unsigned long long hash(const SubcaseSignature& sig) { return hash(hash(hash(sig.m_file), hash(sig.m_name.c_str())), sig.m_line); } unsigned long long hash(const std::vector<SubcaseSignature>& sigs, size_t count) { unsigned long long running = 0; auto end = sigs.begin() + count; for (auto it = sigs.begin(); it != end; it++) { running = hash(running, hash(*it)); } return running; } unsigned long long hash(const std::vector<SubcaseSignature>& sigs) { unsigned long long running = 0; for (const SubcaseSignature& sig : sigs) { running = hash(running, hash(sig)); } return running; } } // namespace namespace detail { bool Subcase::checkFilters() { if (g_cs->subcaseStack.size() < size_t(g_cs->subcase_filter_levels)) { if (!matchesAny(m_signature.m_name.c_str(), g_cs->filters[6], true, g_cs->case_sensitive)) return true; if (matchesAny(m_signature.m_name.c_str(), g_cs->filters[7], false, g_cs->case_sensitive)) return true; } return false; } Subcase::Subcase(const String& name, const char* file, int line) : m_signature({name, file, line}) { if (!g_cs->reachedLeaf) { if (g_cs->nextSubcaseStack.size() <= g_cs->subcaseStack.size() || g_cs->nextSubcaseStack[g_cs->subcaseStack.size()] == m_signature) { // Going down. if (checkFilters()) { return; } g_cs->subcaseStack.push_back(m_signature); g_cs->currentSubcaseDepth++; m_entered = true; DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); } } else { if (g_cs->subcaseStack[g_cs->currentSubcaseDepth] == m_signature) { // This subcase is reentered via control flow. g_cs->currentSubcaseDepth++; m_entered = true; DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); } else if (g_cs->nextSubcaseStack.size() <= g_cs->currentSubcaseDepth && g_cs->fullyTraversedSubcases.find(hash(hash(g_cs->subcaseStack, g_cs->currentSubcaseDepth), hash(m_signature))) == g_cs->fullyTraversedSubcases.end()) { if (checkFilters()) { return; } // This subcase is part of the one to be executed next. g_cs->nextSubcaseStack.clear(); g_cs->nextSubcaseStack.insert(g_cs->nextSubcaseStack.end(), g_cs->subcaseStack.begin(), g_cs->subcaseStack.begin() + g_cs->currentSubcaseDepth); g_cs->nextSubcaseStack.push_back(m_signature); } } } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") Subcase::~Subcase() { if (m_entered) { g_cs->currentSubcaseDepth--; if (!g_cs->reachedLeaf) { // Leaf. g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack)); g_cs->nextSubcaseStack.clear(); g_cs->reachedLeaf = true; } else if (g_cs->nextSubcaseStack.empty()) { // All children are finished. g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack)); } #if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) if(std::uncaught_exceptions() > 0 #else if(std::uncaught_exception() #endif && g_cs->shouldLogCurrentException) { DOCTEST_ITERATE_THROUGH_REPORTERS( test_case_exception, {"exception thrown in subcase - will translate later " "when the whole test case has been exited (cannot " "translate while there is an active exception)", false}); g_cs->shouldLogCurrentException = false; } DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); } } DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP Subcase::operator bool() const { return m_entered; } Result::Result(bool passed, const String& decomposition) : m_passed(passed) , m_decomp(decomposition) {} ExpressionDecomposer::ExpressionDecomposer(assertType::Enum at) : m_at(at) {} TestSuite& TestSuite::operator*(const char* in) { m_test_suite = in; return *this; } TestCase::TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, const String& type, int template_id) { m_file = file; m_line = line; m_name = nullptr; // will be later overridden in operator* m_test_suite = test_suite.m_test_suite; m_description = test_suite.m_description; m_skip = test_suite.m_skip; m_no_breaks = test_suite.m_no_breaks; m_no_output = test_suite.m_no_output; m_may_fail = test_suite.m_may_fail; m_should_fail = test_suite.m_should_fail; m_expected_failures = test_suite.m_expected_failures; m_timeout = test_suite.m_timeout; m_test = test; m_type = type; m_template_id = template_id; } TestCase::TestCase(const TestCase& other) : TestCaseData() { *this = other; } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function TestCase& TestCase::operator=(const TestCase& other) { TestCaseData::operator=(other); m_test = other.m_test; m_type = other.m_type; m_template_id = other.m_template_id; m_full_name = other.m_full_name; if(m_template_id != -1) m_name = m_full_name.c_str(); return *this; } DOCTEST_MSVC_SUPPRESS_WARNING_POP TestCase& TestCase::operator*(const char* in) { m_name = in; // make a new name with an appended type for templated test case if(m_template_id != -1) { m_full_name = String(m_name) + "<" + m_type + ">"; // redirect the name to point to the newly constructed full name m_name = m_full_name.c_str(); } return *this; } bool TestCase::operator<(const TestCase& other) const { // this will be used only to differentiate between test cases - not relevant for sorting if(m_line != other.m_line) return m_line < other.m_line; const int name_cmp = strcmp(m_name, other.m_name); if(name_cmp != 0) return name_cmp < 0; const int file_cmp = m_file.compare(other.m_file); if(file_cmp != 0) return file_cmp < 0; return m_template_id < other.m_template_id; } // all the registered tests std::set<TestCase>& getRegisteredTests() { static std::set<TestCase> data; return data; } } // namespace detail namespace { using namespace detail; // for sorting tests by file/line bool fileOrderComparator(const TestCase* lhs, const TestCase* rhs) { // this is needed because MSVC gives different case for drive letters // for __FILE__ when evaluated in a header and a source file const int res = lhs->m_file.compare(rhs->m_file, bool(DOCTEST_MSVC)); if(res != 0) return res < 0; if(lhs->m_line != rhs->m_line) return lhs->m_line < rhs->m_line; return lhs->m_template_id < rhs->m_template_id; } // for sorting tests by suite/file/line bool suiteOrderComparator(const TestCase* lhs, const TestCase* rhs) { const int res = std::strcmp(lhs->m_test_suite, rhs->m_test_suite); if(res != 0) return res < 0; return fileOrderComparator(lhs, rhs); } // for sorting tests by name/suite/file/line bool nameOrderComparator(const TestCase* lhs, const TestCase* rhs) { const int res = std::strcmp(lhs->m_name, rhs->m_name); if(res != 0) return res < 0; return suiteOrderComparator(lhs, rhs); } DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") void color_to_stream(std::ostream& s, Color::Enum code) { static_cast<void>(s); // for DOCTEST_CONFIG_COLORS_NONE or DOCTEST_CONFIG_COLORS_WINDOWS static_cast<void>(code); // for DOCTEST_CONFIG_COLORS_NONE #ifdef DOCTEST_CONFIG_COLORS_ANSI if(g_no_colors || (isatty(STDOUT_FILENO) == false && getContextOptions()->force_colors == false)) return; auto col = ""; // clang-format off switch(code) { //!OCLINT missing break in switch statement / unnecessary default statement in covered switch statement case Color::Red: col = "[0;31m"; break; case Color::Green: col = "[0;32m"; break; case Color::Blue: col = "[0;34m"; break; case Color::Cyan: col = "[0;36m"; break; case Color::Yellow: col = "[0;33m"; break; case Color::Grey: col = "[1;30m"; break; case Color::LightGrey: col = "[0;37m"; break; case Color::BrightRed: col = "[1;31m"; break; case Color::BrightGreen: col = "[1;32m"; break; case Color::BrightWhite: col = "[1;37m"; break; case Color::Bright: // invalid case Color::None: case Color::White: default: col = "[0m"; } // clang-format on s << "\033" << col; #endif // DOCTEST_CONFIG_COLORS_ANSI #ifdef DOCTEST_CONFIG_COLORS_WINDOWS if(g_no_colors || (_isatty(_fileno(stdout)) == false && getContextOptions()->force_colors == false)) return; static struct ConsoleHelper { HANDLE stdoutHandle; WORD origFgAttrs; WORD origBgAttrs; ConsoleHelper() { stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbiInfo; GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo); origFgAttrs = csbiInfo.wAttributes & ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY); origBgAttrs = csbiInfo.wAttributes & ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY); } } ch; #define DOCTEST_SET_ATTR(x) SetConsoleTextAttribute(ch.stdoutHandle, x | ch.origBgAttrs) // clang-format off switch (code) { case Color::White: DOCTEST_SET_ATTR(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; case Color::Red: DOCTEST_SET_ATTR(FOREGROUND_RED); break; case Color::Green: DOCTEST_SET_ATTR(FOREGROUND_GREEN); break; case Color::Blue: DOCTEST_SET_ATTR(FOREGROUND_BLUE); break; case Color::Cyan: DOCTEST_SET_ATTR(FOREGROUND_BLUE | FOREGROUND_GREEN); break; case Color::Yellow: DOCTEST_SET_ATTR(FOREGROUND_RED | FOREGROUND_GREEN); break; case Color::Grey: DOCTEST_SET_ATTR(0); break; case Color::LightGrey: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY); break; case Color::BrightRed: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_RED); break; case Color::BrightGreen: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN); break; case Color::BrightWhite: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; case Color::None: case Color::Bright: // invalid default: DOCTEST_SET_ATTR(ch.origFgAttrs); } // clang-format on #endif // DOCTEST_CONFIG_COLORS_WINDOWS } DOCTEST_CLANG_SUPPRESS_WARNING_POP std::vector<const IExceptionTranslator*>& getExceptionTranslators() { static std::vector<const IExceptionTranslator*> data; return data; } String translateActiveException() { #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS String res; auto& translators = getExceptionTranslators(); for(auto& curr : translators) if(curr->translate(res)) return res; // clang-format off DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wcatch-value") try { throw; } catch(std::exception& ex) { return ex.what(); } catch(std::string& msg) { return msg.c_str(); } catch(const char* msg) { return msg; } catch(...) { return "unknown exception"; } DOCTEST_GCC_SUPPRESS_WARNING_POP // clang-format on #else // DOCTEST_CONFIG_NO_EXCEPTIONS return ""; #endif // DOCTEST_CONFIG_NO_EXCEPTIONS } } // namespace namespace detail { // used by the macros for registering tests int regTest(const TestCase& tc) { getRegisteredTests().insert(tc); return 0; } // sets the current test suite int setTestSuite(const TestSuite& ts) { doctest_detail_test_suite_ns::getCurrentTestSuite() = ts; return 0; } #ifdef DOCTEST_IS_DEBUGGER_ACTIVE bool isDebuggerActive() { return DOCTEST_IS_DEBUGGER_ACTIVE(); } #else // DOCTEST_IS_DEBUGGER_ACTIVE #ifdef DOCTEST_PLATFORM_LINUX class ErrnoGuard { public: ErrnoGuard() : m_oldErrno(errno) {} ~ErrnoGuard() { errno = m_oldErrno; } private: int m_oldErrno; }; // See the comments in Catch2 for the reasoning behind this implementation: // https://github.com/catchorg/Catch2/blob/v2.13.1/include/internal/catch_debugger.cpp#L79-L102 bool isDebuggerActive() { ErrnoGuard guard; std::ifstream in("/proc/self/status"); for(std::string line; std::getline(in, line);) { static const int PREFIX_LEN = 11; if(line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) { return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; } } return false; } #elif defined(DOCTEST_PLATFORM_MAC) // The following function is taken directly from the following technical note: // https://developer.apple.com/library/archive/qa/qa1361/_index.html // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). bool isDebuggerActive() { int mib[4]; kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); if(sysctl(mib, DOCTEST_COUNTOF(mib), &info, &size, 0, 0) != 0) { std::cerr << "\nCall to sysctl failed - unable to determine if debugger is active **\n"; return false; } // We're being debugged if the P_TRACED flag is set. return ((info.kp_proc.p_flag & P_TRACED) != 0); } #elif DOCTEST_MSVC || defined(__MINGW32__) || defined(__MINGW64__) bool isDebuggerActive() { return ::IsDebuggerPresent() != 0; } #else bool isDebuggerActive() { return false; } #endif // Platform #endif // DOCTEST_IS_DEBUGGER_ACTIVE void registerExceptionTranslatorImpl(const IExceptionTranslator* et) { if(std::find(getExceptionTranslators().begin(), getExceptionTranslators().end(), et) == getExceptionTranslators().end()) getExceptionTranslators().push_back(et); } DOCTEST_THREAD_LOCAL std::vector<IContextScope*> g_infoContexts; // for logging with INFO() ContextScopeBase::ContextScopeBase() { g_infoContexts.push_back(this); } ContextScopeBase::ContextScopeBase(ContextScopeBase&& other) noexcept { if (other.need_to_destroy) { other.destroy(); } other.need_to_destroy = false; g_infoContexts.push_back(this); } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") // destroy cannot be inlined into the destructor because that would mean calling stringify after // ContextScope has been destroyed (base class destructors run after derived class destructors). // Instead, ContextScope calls this method directly from its destructor. void ContextScopeBase::destroy() { #if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) if(std::uncaught_exceptions() > 0) { #else if(std::uncaught_exception()) { #endif std::ostringstream s; this->stringify(&s); g_cs->stringifiedContexts.push_back(s.str().c_str()); } g_infoContexts.pop_back(); } DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP } // namespace detail namespace { using namespace detail; #if !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && !defined(DOCTEST_CONFIG_WINDOWS_SEH) struct FatalConditionHandler { static void reset() {} static void allocateAltStackMem() {} static void freeAltStackMem() {} }; #else // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH void reportFatal(const std::string&); #ifdef DOCTEST_PLATFORM_WINDOWS struct SignalDefs { DWORD id; const char* name; }; // There is no 1-1 mapping between signals and windows exceptions. // Windows can easily distinguish between SO and SigSegV, // but SigInt, SigTerm, etc are handled differently. SignalDefs signalDefs[] = { {static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal"}, {static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"}, {static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal"}, {static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"}, }; struct FatalConditionHandler { static LONG CALLBACK handleException(PEXCEPTION_POINTERS ExceptionInfo) { // Multiple threads may enter this filter/handler at once. We want the error message to be printed on the // console just once no matter how many threads have crashed. DOCTEST_DECLARE_STATIC_MUTEX(mutex) static bool execute = true; { DOCTEST_LOCK_MUTEX(mutex) if(execute) { bool reported = false; for(size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { if(ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) { reportFatal(signalDefs[i].name); reported = true; break; } } if(reported == false) reportFatal("Unhandled SEH exception caught"); if(isDebuggerActive() && !g_cs->no_breaks) DOCTEST_BREAK_INTO_DEBUGGER(); } execute = false; } std::exit(EXIT_FAILURE); } static void allocateAltStackMem() {} static void freeAltStackMem() {} FatalConditionHandler() { isSet = true; // 32k seems enough for doctest to handle stack overflow, // but the value was found experimentally, so there is no strong guarantee guaranteeSize = 32 * 1024; // Register an unhandled exception filter previousTop = SetUnhandledExceptionFilter(handleException); // Pass in guarantee size to be filled SetThreadStackGuarantee(&guaranteeSize); // On Windows uncaught exceptions from another thread, exceptions from // destructors, or calls to std::terminate are not a SEH exception // The terminal handler gets called when: // - std::terminate is called FROM THE TEST RUNNER THREAD // - an exception is thrown from a destructor FROM THE TEST RUNNER THREAD original_terminate_handler = std::get_terminate(); std::set_terminate([]() DOCTEST_NOEXCEPT { reportFatal("Terminate handler called"); if(isDebuggerActive() && !g_cs->no_breaks) DOCTEST_BREAK_INTO_DEBUGGER(); std::exit(EXIT_FAILURE); // explicitly exit - otherwise the SIGABRT handler may be called as well }); // SIGABRT is raised when: // - std::terminate is called FROM A DIFFERENT THREAD // - an exception is thrown from a destructor FROM A DIFFERENT THREAD // - an uncaught exception is thrown FROM A DIFFERENT THREAD prev_sigabrt_handler = std::signal(SIGABRT, [](int signal) DOCTEST_NOEXCEPT { if(signal == SIGABRT) { reportFatal("SIGABRT - Abort (abnormal termination) signal"); if(isDebuggerActive() && !g_cs->no_breaks) DOCTEST_BREAK_INTO_DEBUGGER(); std::exit(EXIT_FAILURE); } }); // The following settings are taken from google test, and more // specifically from UnitTest::Run() inside of gtest.cc // the user does not want to see pop-up dialogs about crashes prev_error_mode_1 = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); // This forces the abort message to go to stderr in all circumstances. prev_error_mode_2 = _set_error_mode(_OUT_TO_STDERR); // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program - we want to disable that. prev_abort_behavior = _set_abort_behavior(0x0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // In debug mode, the Windows CRT can crash with an assertion over invalid // input (e.g. passing an invalid file descriptor). The default handling // for these assertions is to pop up a dialog and wait for user input. // Instead ask the CRT to dump such assertions to stderr non-interactively. prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); prev_report_file = _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); } static void reset() { if(isSet) { // Unregister handler and restore the old guarantee SetUnhandledExceptionFilter(previousTop); SetThreadStackGuarantee(&guaranteeSize); std::set_terminate(original_terminate_handler); std::signal(SIGABRT, prev_sigabrt_handler); SetErrorMode(prev_error_mode_1); _set_error_mode(prev_error_mode_2); _set_abort_behavior(prev_abort_behavior, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); static_cast<void>(_CrtSetReportMode(_CRT_ASSERT, prev_report_mode)); static_cast<void>(_CrtSetReportFile(_CRT_ASSERT, prev_report_file)); isSet = false; } } ~FatalConditionHandler() { reset(); } private: static UINT prev_error_mode_1; static int prev_error_mode_2; static unsigned int prev_abort_behavior; static int prev_report_mode; static _HFILE prev_report_file; static void (DOCTEST_CDECL *prev_sigabrt_handler)(int); static std::terminate_handler original_terminate_handler; static bool isSet; static ULONG guaranteeSize; static LPTOP_LEVEL_EXCEPTION_FILTER previousTop; }; UINT FatalConditionHandler::prev_error_mode_1; int FatalConditionHandler::prev_error_mode_2; unsigned int FatalConditionHandler::prev_abort_behavior; int FatalConditionHandler::prev_report_mode; _HFILE FatalConditionHandler::prev_report_file; void (DOCTEST_CDECL *FatalConditionHandler::prev_sigabrt_handler)(int); std::terminate_handler FatalConditionHandler::original_terminate_handler; bool FatalConditionHandler::isSet = false; ULONG FatalConditionHandler::guaranteeSize = 0; LPTOP_LEVEL_EXCEPTION_FILTER FatalConditionHandler::previousTop = nullptr; #else // DOCTEST_PLATFORM_WINDOWS struct SignalDefs { int id; const char* name; }; SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"}, {SIGILL, "SIGILL - Illegal instruction signal"}, {SIGFPE, "SIGFPE - Floating point error signal"}, {SIGSEGV, "SIGSEGV - Segmentation violation signal"}, {SIGTERM, "SIGTERM - Termination request signal"}, {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}}; struct FatalConditionHandler { static bool isSet; static struct sigaction oldSigActions[DOCTEST_COUNTOF(signalDefs)]; static stack_t oldSigStack; static size_t altStackSize; static char* altStackMem; static void handleSignal(int sig) { const char* name = "<unknown signal>"; for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { SignalDefs& def = signalDefs[i]; if(sig == def.id) { name = def.name; break; } } reset(); reportFatal(name); raise(sig); } static void allocateAltStackMem() { altStackMem = new char[altStackSize]; } static void freeAltStackMem() { delete[] altStackMem; } FatalConditionHandler() { isSet = true; stack_t sigStack; sigStack.ss_sp = altStackMem; sigStack.ss_size = altStackSize; sigStack.ss_flags = 0; sigaltstack(&sigStack, &oldSigStack); struct sigaction sa = {}; sa.sa_handler = handleSignal; sa.sa_flags = SA_ONSTACK; for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); } } ~FatalConditionHandler() { reset(); } static void reset() { if(isSet) { // Set signals back to previous values -- hopefully nobody overwrote them in the meantime for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); } // Return the old stack sigaltstack(&oldSigStack, nullptr); isSet = false; } } }; bool FatalConditionHandler::isSet = false; struct sigaction FatalConditionHandler::oldSigActions[DOCTEST_COUNTOF(signalDefs)] = {}; stack_t FatalConditionHandler::oldSigStack = {}; size_t FatalConditionHandler::altStackSize = 4 * SIGSTKSZ; char* FatalConditionHandler::altStackMem = nullptr; #endif // DOCTEST_PLATFORM_WINDOWS #endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH } // namespace namespace { using namespace detail; #ifdef DOCTEST_PLATFORM_WINDOWS #define DOCTEST_OUTPUT_DEBUG_STRING(text) ::OutputDebugStringA(text) #else // TODO: integration with XCode and other IDEs #define DOCTEST_OUTPUT_DEBUG_STRING(text) #endif // Platform void addAssert(assertType::Enum at) { if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional g_cs->numAssertsCurrentTest_atomic++; } void addFailedAssert(assertType::Enum at) { if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional g_cs->numAssertsFailedCurrentTest_atomic++; } #if defined(DOCTEST_CONFIG_POSIX_SIGNALS) || defined(DOCTEST_CONFIG_WINDOWS_SEH) void reportFatal(const std::string& message) { g_cs->failure_flags |= TestCaseFailureReason::Crash; DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, {message.c_str(), true}); while (g_cs->subcaseStack.size()) { g_cs->subcaseStack.pop_back(); DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); } g_cs->finalizeTestCaseData(); DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); } #endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH } // namespace AssertData::AssertData(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const StringContains& exception_string) : m_test_case(g_cs->currentTest), m_at(at), m_file(file), m_line(line), m_expr(expr), m_failed(true), m_threw(false), m_threw_as(false), m_exception_type(exception_type), m_exception_string(exception_string) { #if DOCTEST_MSVC if (m_expr[0] == ' ') // this happens when variadic macros are disabled under MSVC ++m_expr; #endif // MSVC } namespace detail { ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const String& exception_string) : AssertData(at, file, line, expr, exception_type, exception_string) { } ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const Contains& exception_string) : AssertData(at, file, line, expr, exception_type, exception_string) { } void ResultBuilder::setResult(const Result& res) { m_decomp = res.m_decomp; m_failed = !res.m_passed; } void ResultBuilder::translateException() { m_threw = true; m_exception = translateActiveException(); } bool ResultBuilder::log() { if(m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional m_failed = !m_threw; } else if((m_at & assertType::is_throws_as) && (m_at & assertType::is_throws_with)) { //!OCLINT m_failed = !m_threw_as || !m_exception_string.check(m_exception); } else if(m_at & assertType::is_throws_as) { //!OCLINT bitwise operator in conditional m_failed = !m_threw_as; } else if(m_at & assertType::is_throws_with) { //!OCLINT bitwise operator in conditional m_failed = !m_exception_string.check(m_exception); } else if(m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional m_failed = m_threw; } if(m_exception.size()) m_exception = "\"" + m_exception + "\""; if(is_running_in_test) { addAssert(m_at); DOCTEST_ITERATE_THROUGH_REPORTERS(log_assert, *this); if(m_failed) addFailedAssert(m_at); } else if(m_failed) { failed_out_of_a_testing_context(*this); } return m_failed && isDebuggerActive() && !getContextOptions()->no_breaks && (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger } void ResultBuilder::react() const { if(m_failed && checkIfShouldThrow(m_at)) throwException(); } void failed_out_of_a_testing_context(const AssertData& ad) { if(g_cs->ah) g_cs->ah(ad); else std::abort(); } bool decomp_assert(assertType::Enum at, const char* file, int line, const char* expr, const Result& result) { bool failed = !result.m_passed; // ################################################################################### // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED // ################################################################################### DOCTEST_ASSERT_OUT_OF_TESTS(result.m_decomp); DOCTEST_ASSERT_IN_TESTS(result.m_decomp); return !failed; } MessageBuilder::MessageBuilder(const char* file, int line, assertType::Enum severity) { m_stream = tlssPush(); m_file = file; m_line = line; m_severity = severity; } MessageBuilder::~MessageBuilder() { if (!logged) tlssPop(); } DOCTEST_DEFINE_INTERFACE(IExceptionTranslator) bool MessageBuilder::log() { if (!logged) { m_string = tlssPop(); logged = true; } DOCTEST_ITERATE_THROUGH_REPORTERS(log_message, *this); const bool isWarn = m_severity & assertType::is_warn; // warn is just a message in this context so we don't treat it as an assert if(!isWarn) { addAssert(m_severity); addFailedAssert(m_severity); } return isDebuggerActive() && !getContextOptions()->no_breaks && !isWarn && (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger } void MessageBuilder::react() { if(m_severity & assertType::is_require) //!OCLINT bitwise operator in conditional throwException(); } } // namespace detail namespace { using namespace detail; // clang-format off // ================================================================================================= // The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp // This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. // ================================================================================================= class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); void encodeTo( std::ostream& os ) const; friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); private: std::string m_str; ForWhat m_forWhat; }; class XmlWriter { public: class ScopedElement { public: ScopedElement( XmlWriter* writer ); ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT; ScopedElement& operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT; ~ScopedElement(); ScopedElement& writeText( std::string const& text, bool indent = true ); template<typename T> ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { m_writer->writeAttribute( name, attribute ); return *this; } private: mutable XmlWriter* m_writer = nullptr; }; #ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM XmlWriter( std::ostream& os = std::cout ); #else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM XmlWriter( std::ostream& os ); #endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM ~XmlWriter(); XmlWriter( XmlWriter const& ) = delete; XmlWriter& operator=( XmlWriter const& ) = delete; XmlWriter& startElement( std::string const& name ); ScopedElement scopedElement( std::string const& name ); XmlWriter& endElement(); XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); XmlWriter& writeAttribute( std::string const& name, const char* attribute ); XmlWriter& writeAttribute( std::string const& name, bool attribute ); template<typename T> XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { std::stringstream rss; rss << attribute; return writeAttribute( name, rss.str() ); } XmlWriter& writeText( std::string const& text, bool indent = true ); //XmlWriter& writeComment( std::string const& text ); //void writeStylesheetRef( std::string const& url ); //XmlWriter& writeBlankLine(); void ensureTagClosed(); void writeDeclaration(); private: void newlineIfNecessary(); bool m_tagIsOpen = false; bool m_needsNewline = false; std::vector<std::string> m_tags; std::string m_indent; std::ostream& m_os; }; // ================================================================================================= // The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp // This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. // ================================================================================================= using uchar = unsigned char; namespace { size_t trailingBytes(unsigned char c) { if ((c & 0xE0) == 0xC0) { return 2; } if ((c & 0xF0) == 0xE0) { return 3; } if ((c & 0xF8) == 0xF0) { return 4; } DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); } uint32_t headerValue(unsigned char c) { if ((c & 0xE0) == 0xC0) { return c & 0x1F; } if ((c & 0xF0) == 0xE0) { return c & 0x0F; } if ((c & 0xF8) == 0xF0) { return c & 0x07; } DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); } void hexEscapeChar(std::ostream& os, unsigned char c) { std::ios_base::fmtflags f(os.flags()); os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(c); os.flags(f); } } // anonymous namespace XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) : m_str( str ), m_forWhat( forWhat ) {} void XmlEncode::encodeTo( std::ostream& os ) const { // Apostrophe escaping not necessary if we always use " to write attributes // (see: https://www.w3.org/TR/xml/#syntax) for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { uchar c = m_str[idx]; switch (c) { case '<': os << "&lt;"; break; case '&': os << "&amp;"; break; case '>': // See: https://www.w3.org/TR/xml/#syntax if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') os << "&gt;"; else os << c; break; case '\"': if (m_forWhat == ForAttributes) os << "&quot;"; else os << c; break; default: // Check for control characters and invalid utf-8 // Escape control characters in standard ascii // see https://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { hexEscapeChar(os, c); break; } // Plain ASCII: Write it to stream if (c < 0x7F) { os << c; break; } // UTF-8 territory // Check if the encoding is valid and if it is not, hex escape bytes. // Important: We do not check the exact decoded values for validity, only the encoding format // First check that this bytes is a valid lead byte: // This means that it is not encoded as 1111 1XXX // Or as 10XX XXXX if (c < 0xC0 || c >= 0xF8) { hexEscapeChar(os, c); break; } auto encBytes = trailingBytes(c); // Are there enough bytes left to avoid accessing out-of-bounds memory? if (idx + encBytes - 1 >= m_str.size()) { hexEscapeChar(os, c); break; } // The header is valid, check data // The next encBytes bytes must together be a valid utf-8 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) bool valid = true; uint32_t value = headerValue(c); for (std::size_t n = 1; n < encBytes; ++n) { uchar nc = m_str[idx + n]; valid &= ((nc & 0xC0) == 0x80); value = (value << 6) | (nc & 0x3F); } if ( // Wrong bit pattern of following bytes (!valid) || // Overlong encodings (value < 0x80) || ( value < 0x800 && encBytes > 2) || // removed "0x80 <= value &&" because redundant (0x800 < value && value < 0x10000 && encBytes > 3) || // Encoded value out of range (value >= 0x110000) ) { hexEscapeChar(os, c); break; } // If we got here, this is in fact a valid(ish) utf-8 sequence for (std::size_t n = 0; n < encBytes; ++n) { os << m_str[idx + n]; } idx += encBytes - 1; break; } } } std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { xmlEncode.encodeTo( os ); return os; } XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer ) : m_writer( writer ) {} XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT : m_writer( other.m_writer ){ other.m_writer = nullptr; } XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT { if ( m_writer ) { m_writer->endElement(); } m_writer = other.m_writer; other.m_writer = nullptr; return *this; } XmlWriter::ScopedElement::~ScopedElement() { if( m_writer ) m_writer->endElement(); } XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) { m_writer->writeText( text, indent ); return *this; } XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) { // writeDeclaration(); // called explicitly by the reporters that use the writer class - see issue #627 } XmlWriter::~XmlWriter() { while( !m_tags.empty() ) endElement(); } XmlWriter& XmlWriter::startElement( std::string const& name ) { ensureTagClosed(); newlineIfNecessary(); m_os << m_indent << '<' << name; m_tags.push_back( name ); m_indent += " "; m_tagIsOpen = true; return *this; } XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) { ScopedElement scoped( this ); startElement( name ); return scoped; } XmlWriter& XmlWriter::endElement() { newlineIfNecessary(); m_indent = m_indent.substr( 0, m_indent.size()-2 ); if( m_tagIsOpen ) { m_os << "/>"; m_tagIsOpen = false; } else { m_os << m_indent << "</" << m_tags.back() << ">"; } m_os << std::endl; m_tags.pop_back(); return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { if( !name.empty() && !attribute.empty() ) m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, const char* attribute ) { if( !name.empty() && attribute && attribute[0] != '\0' ) m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; return *this; } XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) { if( !text.empty() ){ bool tagWasOpen = m_tagIsOpen; ensureTagClosed(); if( tagWasOpen && indent ) m_os << m_indent; m_os << XmlEncode( text ); m_needsNewline = true; } return *this; } //XmlWriter& XmlWriter::writeComment( std::string const& text ) { // ensureTagClosed(); // m_os << m_indent << "<!--" << text << "-->"; // m_needsNewline = true; // return *this; //} //void XmlWriter::writeStylesheetRef( std::string const& url ) { // m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n"; //} //XmlWriter& XmlWriter::writeBlankLine() { // ensureTagClosed(); // m_os << '\n'; // return *this; //} void XmlWriter::ensureTagClosed() { if( m_tagIsOpen ) { m_os << ">" << std::endl; m_tagIsOpen = false; } } void XmlWriter::writeDeclaration() { m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; } void XmlWriter::newlineIfNecessary() { if( m_needsNewline ) { m_os << std::endl; m_needsNewline = false; } } // ================================================================================================= // End of copy-pasted code from Catch // ================================================================================================= // clang-format on struct XmlReporter : public IReporter { XmlWriter xml; DOCTEST_DECLARE_MUTEX(mutex) // caching pointers/references to objects of these types - safe to do const ContextOptions& opt; const TestCaseData* tc = nullptr; XmlReporter(const ContextOptions& co) : xml(*co.cout) , opt(co) {} void log_contexts() { int num_contexts = get_num_active_contexts(); if(num_contexts) { auto contexts = get_active_contexts(); std::stringstream ss; for(int i = 0; i < num_contexts; ++i) { contexts[i]->stringify(&ss); xml.scopedElement("Info").writeText(ss.str()); ss.str(""); } } } unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } void test_case_start_impl(const TestCaseData& in) { bool open_ts_tag = false; if(tc != nullptr) { // we have already opened a test suite if(std::strcmp(tc->m_test_suite, in.m_test_suite) != 0) { xml.endElement(); open_ts_tag = true; } } else { open_ts_tag = true; // first test case ==> first test suite } if(open_ts_tag) { xml.startElement("TestSuite"); xml.writeAttribute("name", in.m_test_suite); } tc = &in; xml.startElement("TestCase") .writeAttribute("name", in.m_name) .writeAttribute("filename", skipPathFromFilename(in.m_file.c_str())) .writeAttribute("line", line(in.m_line)) .writeAttribute("description", in.m_description); if(Approx(in.m_timeout) != 0) xml.writeAttribute("timeout", in.m_timeout); if(in.m_may_fail) xml.writeAttribute("may_fail", true); if(in.m_should_fail) xml.writeAttribute("should_fail", true); } // ========================================================================================= // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE // ========================================================================================= void report_query(const QueryData& in) override { test_run_start(); if(opt.list_reporters) { for(auto& curr : getListeners()) xml.scopedElement("Listener") .writeAttribute("priority", curr.first.first) .writeAttribute("name", curr.first.second); for(auto& curr : getReporters()) xml.scopedElement("Reporter") .writeAttribute("priority", curr.first.first) .writeAttribute("name", curr.first.second); } else if(opt.count || opt.list_test_cases) { for(unsigned i = 0; i < in.num_data; ++i) { xml.scopedElement("TestCase").writeAttribute("name", in.data[i]->m_name) .writeAttribute("testsuite", in.data[i]->m_test_suite) .writeAttribute("filename", skipPathFromFilename(in.data[i]->m_file.c_str())) .writeAttribute("line", line(in.data[i]->m_line)) .writeAttribute("skipped", in.data[i]->m_skip); } xml.scopedElement("OverallResultsTestCases") .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); } else if(opt.list_test_suites) { for(unsigned i = 0; i < in.num_data; ++i) xml.scopedElement("TestSuite").writeAttribute("name", in.data[i]->m_test_suite); xml.scopedElement("OverallResultsTestCases") .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); xml.scopedElement("OverallResultsTestSuites") .writeAttribute("unskipped", in.run_stats->numTestSuitesPassingFilters); } xml.endElement(); } void test_run_start() override { xml.writeDeclaration(); // remove .exe extension - mainly to have the same output on UNIX and Windows std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); #ifdef DOCTEST_PLATFORM_WINDOWS if(binary_name.rfind(".exe") != std::string::npos) binary_name = binary_name.substr(0, binary_name.length() - 4); #endif // DOCTEST_PLATFORM_WINDOWS xml.startElement("doctest").writeAttribute("binary", binary_name); if(opt.no_version == false) xml.writeAttribute("version", DOCTEST_VERSION_STR); // only the consequential ones (TODO: filters) xml.scopedElement("Options") .writeAttribute("order_by", opt.order_by.c_str()) .writeAttribute("rand_seed", opt.rand_seed) .writeAttribute("first", opt.first) .writeAttribute("last", opt.last) .writeAttribute("abort_after", opt.abort_after) .writeAttribute("subcase_filter_levels", opt.subcase_filter_levels) .writeAttribute("case_sensitive", opt.case_sensitive) .writeAttribute("no_throw", opt.no_throw) .writeAttribute("no_skip", opt.no_skip); } void test_run_end(const TestRunStats& p) override { if(tc) // the TestSuite tag - only if there has been at least 1 test case xml.endElement(); xml.scopedElement("OverallResultsAsserts") .writeAttribute("successes", p.numAsserts - p.numAssertsFailed) .writeAttribute("failures", p.numAssertsFailed); xml.startElement("OverallResultsTestCases") .writeAttribute("successes", p.numTestCasesPassingFilters - p.numTestCasesFailed) .writeAttribute("failures", p.numTestCasesFailed); if(opt.no_skipped_summary == false) xml.writeAttribute("skipped", p.numTestCases - p.numTestCasesPassingFilters); xml.endElement(); xml.endElement(); } void test_case_start(const TestCaseData& in) override { test_case_start_impl(in); xml.ensureTagClosed(); } void test_case_reenter(const TestCaseData&) override {} void test_case_end(const CurrentTestCaseStats& st) override { xml.startElement("OverallResultsAsserts") .writeAttribute("successes", st.numAssertsCurrentTest - st.numAssertsFailedCurrentTest) .writeAttribute("failures", st.numAssertsFailedCurrentTest) .writeAttribute("test_case_success", st.testCaseSuccess); if(opt.duration) xml.writeAttribute("duration", st.seconds); if(tc->m_expected_failures) xml.writeAttribute("expected_failures", tc->m_expected_failures); xml.endElement(); xml.endElement(); } void test_case_exception(const TestCaseException& e) override { DOCTEST_LOCK_MUTEX(mutex) xml.scopedElement("Exception") .writeAttribute("crash", e.is_crash) .writeText(e.error_string.c_str()); } void subcase_start(const SubcaseSignature& in) override { xml.startElement("SubCase") .writeAttribute("name", in.m_name) .writeAttribute("filename", skipPathFromFilename(in.m_file)) .writeAttribute("line", line(in.m_line)); xml.ensureTagClosed(); } void subcase_end() override { xml.endElement(); } void log_assert(const AssertData& rb) override { if(!rb.m_failed && !opt.success) return; DOCTEST_LOCK_MUTEX(mutex) xml.startElement("Expression") .writeAttribute("success", !rb.m_failed) .writeAttribute("type", assertString(rb.m_at)) .writeAttribute("filename", skipPathFromFilename(rb.m_file)) .writeAttribute("line", line(rb.m_line)); xml.scopedElement("Original").writeText(rb.m_expr); if(rb.m_threw) xml.scopedElement("Exception").writeText(rb.m_exception.c_str()); if(rb.m_at & assertType::is_throws_as) xml.scopedElement("ExpectedException").writeText(rb.m_exception_type); if(rb.m_at & assertType::is_throws_with) xml.scopedElement("ExpectedExceptionString").writeText(rb.m_exception_string.c_str()); if((rb.m_at & assertType::is_normal) && !rb.m_threw) xml.scopedElement("Expanded").writeText(rb.m_decomp.c_str()); log_contexts(); xml.endElement(); } void log_message(const MessageData& mb) override { DOCTEST_LOCK_MUTEX(mutex) xml.startElement("Message") .writeAttribute("type", failureString(mb.m_severity)) .writeAttribute("filename", skipPathFromFilename(mb.m_file)) .writeAttribute("line", line(mb.m_line)); xml.scopedElement("Text").writeText(mb.m_string.c_str()); log_contexts(); xml.endElement(); } void test_case_skipped(const TestCaseData& in) override { if(opt.no_skipped_summary == false) { test_case_start_impl(in); xml.writeAttribute("skipped", "true"); xml.endElement(); } } }; DOCTEST_REGISTER_REPORTER("xml", 0, XmlReporter); void fulltext_log_assert_to_stream(std::ostream& s, const AssertData& rb) { if((rb.m_at & (assertType::is_throws_as | assertType::is_throws_with)) == 0) //!OCLINT bitwise operator in conditional s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << " ) " << Color::None; if(rb.m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional s << (rb.m_threw ? "threw as expected!" : "did NOT throw at all!") << "\n"; } else if((rb.m_at & assertType::is_throws_as) && (rb.m_at & assertType::is_throws_with)) { //!OCLINT s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" << rb.m_exception_string.c_str() << "\", " << rb.m_exception_type << " ) " << Color::None; if(rb.m_threw) { if(!rb.m_failed) { s << "threw as expected!\n"; } else { s << "threw a DIFFERENT exception! (contents: " << rb.m_exception << ")\n"; } } else { s << "did NOT throw at all!\n"; } } else if(rb.m_at & assertType::is_throws_as) { //!OCLINT bitwise operator in conditional s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", " << rb.m_exception_type << " ) " << Color::None << (rb.m_threw ? (rb.m_threw_as ? "threw as expected!" : "threw a DIFFERENT exception: ") : "did NOT throw at all!") << Color::Cyan << rb.m_exception << "\n"; } else if(rb.m_at & assertType::is_throws_with) { //!OCLINT bitwise operator in conditional s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" << rb.m_exception_string.c_str() << "\" ) " << Color::None << (rb.m_threw ? (!rb.m_failed ? "threw as expected!" : "threw a DIFFERENT exception: ") : "did NOT throw at all!") << Color::Cyan << rb.m_exception << "\n"; } else if(rb.m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional s << (rb.m_threw ? "THREW exception: " : "didn't throw!") << Color::Cyan << rb.m_exception << "\n"; } else { s << (rb.m_threw ? "THREW exception: " : (!rb.m_failed ? "is correct!\n" : "is NOT correct!\n")); if(rb.m_threw) s << rb.m_exception << "\n"; else s << " values: " << assertString(rb.m_at) << "( " << rb.m_decomp << " )\n"; } } // TODO: // - log_message() // - respond to queries // - honor remaining options // - more attributes in tags struct JUnitReporter : public IReporter { XmlWriter xml; DOCTEST_DECLARE_MUTEX(mutex) Timer timer; std::vector<String> deepestSubcaseStackNames; struct JUnitTestCaseData { static std::string getCurrentTimestamp() { // Beware, this is not reentrant because of backward compatibility issues // Also, UTC only, again because of backward compatibility (%z is C++11) time_t rawtime; std::time(&rawtime); auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); std::tm timeInfo; #ifdef DOCTEST_PLATFORM_WINDOWS gmtime_s(&timeInfo, &rawtime); #else // DOCTEST_PLATFORM_WINDOWS gmtime_r(&rawtime, &timeInfo); #endif // DOCTEST_PLATFORM_WINDOWS char timeStamp[timeStampSize]; const char* const fmt = "%Y-%m-%dT%H:%M:%SZ"; std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); return std::string(timeStamp); } struct JUnitTestMessage { JUnitTestMessage(const std::string& _message, const std::string& _type, const std::string& _details) : message(_message), type(_type), details(_details) {} JUnitTestMessage(const std::string& _message, const std::string& _details) : message(_message), type(), details(_details) {} std::string message, type, details; }; struct JUnitTestCase { JUnitTestCase(const std::string& _classname, const std::string& _name) : classname(_classname), name(_name), time(0), failures() {} std::string classname, name; double time; std::vector<JUnitTestMessage> failures, errors; }; void add(const std::string& classname, const std::string& name) { testcases.emplace_back(classname, name); } void appendSubcaseNamesToLastTestcase(std::vector<String> nameStack) { for(auto& curr: nameStack) if(curr.size()) testcases.back().name += std::string("/") + curr.c_str(); } void addTime(double time) { if(time < 1e-4) time = 0; testcases.back().time = time; totalSeconds += time; } void addFailure(const std::string& message, const std::string& type, const std::string& details) { testcases.back().failures.emplace_back(message, type, details); ++totalFailures; } void addError(const std::string& message, const std::string& details) { testcases.back().errors.emplace_back(message, details); ++totalErrors; } std::vector<JUnitTestCase> testcases; double totalSeconds = 0; int totalErrors = 0, totalFailures = 0; }; JUnitTestCaseData testCaseData; // caching pointers/references to objects of these types - safe to do const ContextOptions& opt; const TestCaseData* tc = nullptr; JUnitReporter(const ContextOptions& co) : xml(*co.cout) , opt(co) {} unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } // ========================================================================================= // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE // ========================================================================================= void report_query(const QueryData&) override { xml.writeDeclaration(); } void test_run_start() override { xml.writeDeclaration(); } void test_run_end(const TestRunStats& p) override { // remove .exe extension - mainly to have the same output on UNIX and Windows std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); #ifdef DOCTEST_PLATFORM_WINDOWS if(binary_name.rfind(".exe") != std::string::npos) binary_name = binary_name.substr(0, binary_name.length() - 4); #endif // DOCTEST_PLATFORM_WINDOWS xml.startElement("testsuites"); xml.startElement("testsuite").writeAttribute("name", binary_name) .writeAttribute("errors", testCaseData.totalErrors) .writeAttribute("failures", testCaseData.totalFailures) .writeAttribute("tests", p.numAsserts); if(opt.no_time_in_output == false) { xml.writeAttribute("time", testCaseData.totalSeconds); xml.writeAttribute("timestamp", JUnitTestCaseData::getCurrentTimestamp()); } if(opt.no_version == false) xml.writeAttribute("doctest_version", DOCTEST_VERSION_STR); for(const auto& testCase : testCaseData.testcases) { xml.startElement("testcase") .writeAttribute("classname", testCase.classname) .writeAttribute("name", testCase.name); if(opt.no_time_in_output == false) xml.writeAttribute("time", testCase.time); // This is not ideal, but it should be enough to mimic gtest's junit output. xml.writeAttribute("status", "run"); for(const auto& failure : testCase.failures) { xml.scopedElement("failure") .writeAttribute("message", failure.message) .writeAttribute("type", failure.type) .writeText(failure.details, false); } for(const auto& error : testCase.errors) { xml.scopedElement("error") .writeAttribute("message", error.message) .writeText(error.details); } xml.endElement(); } xml.endElement(); xml.endElement(); } void test_case_start(const TestCaseData& in) override { testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name); timer.start(); } void test_case_reenter(const TestCaseData& in) override { testCaseData.addTime(timer.getElapsedSeconds()); testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames); deepestSubcaseStackNames.clear(); timer.start(); testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name); } void test_case_end(const CurrentTestCaseStats&) override { testCaseData.addTime(timer.getElapsedSeconds()); testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames); deepestSubcaseStackNames.clear(); } void test_case_exception(const TestCaseException& e) override { DOCTEST_LOCK_MUTEX(mutex) testCaseData.addError("exception", e.error_string.c_str()); } void subcase_start(const SubcaseSignature& in) override { deepestSubcaseStackNames.push_back(in.m_name); } void subcase_end() override {} void log_assert(const AssertData& rb) override { if(!rb.m_failed) // report only failures & ignore the `success` option return; DOCTEST_LOCK_MUTEX(mutex) std::ostringstream os; os << skipPathFromFilename(rb.m_file) << (opt.gnu_file_line ? ":" : "(") << line(rb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl; fulltext_log_assert_to_stream(os, rb); log_contexts(os); testCaseData.addFailure(rb.m_decomp.c_str(), assertString(rb.m_at), os.str()); } void log_message(const MessageData& mb) override { if(mb.m_severity & assertType::is_warn) // report only failures return; DOCTEST_LOCK_MUTEX(mutex) std::ostringstream os; os << skipPathFromFilename(mb.m_file) << (opt.gnu_file_line ? ":" : "(") << line(mb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl; os << mb.m_string.c_str() << "\n"; log_contexts(os); testCaseData.addFailure(mb.m_string.c_str(), mb.m_severity & assertType::is_check ? "FAIL_CHECK" : "FAIL", os.str()); } void test_case_skipped(const TestCaseData&) override {} void log_contexts(std::ostringstream& s) { int num_contexts = get_num_active_contexts(); if(num_contexts) { auto contexts = get_active_contexts(); s << " logged: "; for(int i = 0; i < num_contexts; ++i) { s << (i == 0 ? "" : " "); contexts[i]->stringify(&s); s << std::endl; } } } }; DOCTEST_REGISTER_REPORTER("junit", 0, JUnitReporter); struct Whitespace { int nrSpaces; explicit Whitespace(int nr) : nrSpaces(nr) {} }; std::ostream& operator<<(std::ostream& out, const Whitespace& ws) { if(ws.nrSpaces != 0) out << std::setw(ws.nrSpaces) << ' '; return out; } struct ConsoleReporter : public IReporter { std::ostream& s; bool hasLoggedCurrentTestStart; std::vector<SubcaseSignature> subcasesStack; size_t currentSubcaseLevel; DOCTEST_DECLARE_MUTEX(mutex) // caching pointers/references to objects of these types - safe to do const ContextOptions& opt; const TestCaseData* tc; ConsoleReporter(const ContextOptions& co) : s(*co.cout) , opt(co) {} ConsoleReporter(const ContextOptions& co, std::ostream& ostr) : s(ostr) , opt(co) {} // ========================================================================================= // WHAT FOLLOWS ARE HELPERS USED BY THE OVERRIDES OF THE VIRTUAL METHODS OF THE INTERFACE // ========================================================================================= void separator_to_stream() { s << Color::Yellow << "===============================================================================" "\n"; } const char* getSuccessOrFailString(bool success, assertType::Enum at, const char* success_str) { if(success) return success_str; return failureString(at); } Color::Enum getSuccessOrFailColor(bool success, assertType::Enum at) { return success ? Color::BrightGreen : (at & assertType::is_warn) ? Color::Yellow : Color::Red; } void successOrFailColoredStringToStream(bool success, assertType::Enum at, const char* success_str = "SUCCESS") { s << getSuccessOrFailColor(success, at) << getSuccessOrFailString(success, at, success_str) << ": "; } void log_contexts() { int num_contexts = get_num_active_contexts(); if(num_contexts) { auto contexts = get_active_contexts(); s << Color::None << " logged: "; for(int i = 0; i < num_contexts; ++i) { s << (i == 0 ? "" : " "); contexts[i]->stringify(&s); s << "\n"; } } s << "\n"; } // this was requested to be made virtual so users could override it virtual void file_line_to_stream(const char* file, int line, const char* tail = "") { s << Color::LightGrey << skipPathFromFilename(file) << (opt.gnu_file_line ? ":" : "(") << (opt.no_line_numbers ? 0 : line) // 0 or the real num depending on the option << (opt.gnu_file_line ? ":" : "):") << tail; } void logTestStart() { if(hasLoggedCurrentTestStart) return; separator_to_stream(); file_line_to_stream(tc->m_file.c_str(), tc->m_line, "\n"); if(tc->m_description) s << Color::Yellow << "DESCRIPTION: " << Color::None << tc->m_description << "\n"; if(tc->m_test_suite && tc->m_test_suite[0] != '\0') s << Color::Yellow << "TEST SUITE: " << Color::None << tc->m_test_suite << "\n"; if(strncmp(tc->m_name, " Scenario:", 11) != 0) s << Color::Yellow << "TEST CASE: "; s << Color::None << tc->m_name << "\n"; for(size_t i = 0; i < currentSubcaseLevel; ++i) { if(subcasesStack[i].m_name[0] != '\0') s << " " << subcasesStack[i].m_name << "\n"; } if(currentSubcaseLevel != subcasesStack.size()) { s << Color::Yellow << "\nDEEPEST SUBCASE STACK REACHED (DIFFERENT FROM THE CURRENT ONE):\n" << Color::None; for(size_t i = 0; i < subcasesStack.size(); ++i) { if(subcasesStack[i].m_name[0] != '\0') s << " " << subcasesStack[i].m_name << "\n"; } } s << "\n"; hasLoggedCurrentTestStart = true; } void printVersion() { if(opt.no_version == false) s << Color::Cyan << "[doctest] " << Color::None << "doctest version is \"" << DOCTEST_VERSION_STR << "\"\n"; } void printIntro() { if(opt.no_intro == false) { printVersion(); s << Color::Cyan << "[doctest] " << Color::None << "run with \"--" DOCTEST_OPTIONS_PREFIX_DISPLAY "help\" for options\n"; } } void printHelp() { int sizePrefixDisplay = static_cast<int>(strlen(DOCTEST_OPTIONS_PREFIX_DISPLAY)); printVersion(); // clang-format off s << Color::Cyan << "[doctest]\n" << Color::None; s << Color::Cyan << "[doctest] " << Color::None; s << "boolean values: \"1/on/yes/true\" or \"0/off/no/false\"\n"; s << Color::Cyan << "[doctest] " << Color::None; s << "filter values: \"str1,str2,str3\" (comma separated strings)\n"; s << Color::Cyan << "[doctest]\n" << Color::None; s << Color::Cyan << "[doctest] " << Color::None; s << "filters use wildcards for matching strings\n"; s << Color::Cyan << "[doctest] " << Color::None; s << "something passes a filter if any of the strings in a filter matches\n"; #ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS s << Color::Cyan << "[doctest]\n" << Color::None; s << Color::Cyan << "[doctest] " << Color::None; s << "ALL FLAGS, OPTIONS AND FILTERS ALSO AVAILABLE WITH A \"" DOCTEST_CONFIG_OPTIONS_PREFIX "\" PREFIX!!!\n"; #endif s << Color::Cyan << "[doctest]\n" << Color::None; s << Color::Cyan << "[doctest] " << Color::None; s << "Query flags - the program quits after them. Available:\n\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "?, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "help, -" DOCTEST_OPTIONS_PREFIX_DISPLAY "h " << Whitespace(sizePrefixDisplay*0) << "prints this message\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "v, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "version " << Whitespace(sizePrefixDisplay*1) << "prints the version\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "c, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "count " << Whitespace(sizePrefixDisplay*1) << "prints the number of matching tests\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ltc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-cases " << Whitespace(sizePrefixDisplay*1) << "lists all matching tests by name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-suites " << Whitespace(sizePrefixDisplay*1) << "lists all matching test suites\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-reporters " << Whitespace(sizePrefixDisplay*1) << "lists all registered reporters\n\n"; // ================================================================================== << 79 s << Color::Cyan << "[doctest] " << Color::None; s << "The available <int>/<string> options/filters are:\n\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters tests by their name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case-exclude=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters tests by their file\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sfe, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file-exclude=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their file\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters tests by their test suite\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tse, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite-exclude=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their test suite\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters subcases by their name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-exclude=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters OUT subcases by their name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "r, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "reporters=<filters> " << Whitespace(sizePrefixDisplay*1) << "reporters to use (console is default)\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "o, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "out=<string> " << Whitespace(sizePrefixDisplay*1) << "output filename\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ob, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "order-by=<string> " << Whitespace(sizePrefixDisplay*1) << "how the tests should be ordered\n"; s << Whitespace(sizePrefixDisplay*3) << " <string> - [file/suite/name/rand/none]\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "rs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "rand-seed=<int> " << Whitespace(sizePrefixDisplay*1) << "seed for random ordering\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "f, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "first=<int> " << Whitespace(sizePrefixDisplay*1) << "the first test passing the filters to\n"; s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "l, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "last=<int> " << Whitespace(sizePrefixDisplay*1) << "the last test passing the filters to\n"; s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "aa, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "abort-after=<int> " << Whitespace(sizePrefixDisplay*1) << "stop after <int> failed assertions\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "scfl,--" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-filter-levels=<int> " << Whitespace(sizePrefixDisplay*1) << "apply filters for the first <int> levels\n"; s << Color::Cyan << "\n[doctest] " << Color::None; s << "Bool options - can be used like flags and true is assumed. Available:\n\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "s, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "success=<bool> " << Whitespace(sizePrefixDisplay*1) << "include successful assertions in output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "cs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "case-sensitive=<bool> " << Whitespace(sizePrefixDisplay*1) << "filters being treated as case sensitive\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "e, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "exit=<bool> " << Whitespace(sizePrefixDisplay*1) << "exits after the tests finish\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "d, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "duration=<bool> " << Whitespace(sizePrefixDisplay*1) << "prints the time duration of each test\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "m, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "minimal=<bool> " << Whitespace(sizePrefixDisplay*1) << "minimal console output (only failures)\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "q, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "quiet=<bool> " << Whitespace(sizePrefixDisplay*1) << "no console output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nt, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-throw=<bool> " << Whitespace(sizePrefixDisplay*1) << "skips exceptions-related assert checks\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ne, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-exitcode=<bool> " << Whitespace(sizePrefixDisplay*1) << "returns (or exits) always with success\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-run=<bool> " << Whitespace(sizePrefixDisplay*1) << "skips all runtime doctest operations\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ni, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-intro=<bool> " << Whitespace(sizePrefixDisplay*1) << "omit the framework intro in the output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nv, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-version=<bool> " << Whitespace(sizePrefixDisplay*1) << "omit the framework version in the output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-colors=<bool> " << Whitespace(sizePrefixDisplay*1) << "disables colors in output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "fc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "force-colors=<bool> " << Whitespace(sizePrefixDisplay*1) << "use colors even when not in a tty\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nb, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-breaks=<bool> " << Whitespace(sizePrefixDisplay*1) << "disables breakpoints in debuggers\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ns, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-skip=<bool> " << Whitespace(sizePrefixDisplay*1) << "don't skip test cases marked as skip\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "gfl, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "gnu-file-line=<bool> " << Whitespace(sizePrefixDisplay*1) << ":n: vs (n): for line numbers in output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "npf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-path-filenames=<bool> " << Whitespace(sizePrefixDisplay*1) << "only filenames and no paths in output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nln, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-line-numbers=<bool> " << Whitespace(sizePrefixDisplay*1) << "0 instead of real line numbers in output\n"; // ================================================================================== << 79 // clang-format on s << Color::Cyan << "\n[doctest] " << Color::None; s << "for more information visit the project documentation\n\n"; } void printRegisteredReporters() { printVersion(); auto printReporters = [this] (const reporterMap& reporters, const char* type) { if(reporters.size()) { s << Color::Cyan << "[doctest] " << Color::None << "listing all registered " << type << "\n"; for(auto& curr : reporters) s << "priority: " << std::setw(5) << curr.first.first << " name: " << curr.first.second << "\n"; } }; printReporters(getListeners(), "listeners"); printReporters(getReporters(), "reporters"); } // ========================================================================================= // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE // ========================================================================================= void report_query(const QueryData& in) override { if(opt.version) { printVersion(); } else if(opt.help) { printHelp(); } else if(opt.list_reporters) { printRegisteredReporters(); } else if(opt.count || opt.list_test_cases) { if(opt.list_test_cases) { s << Color::Cyan << "[doctest] " << Color::None << "listing all test case names\n"; separator_to_stream(); } for(unsigned i = 0; i < in.num_data; ++i) s << Color::None << in.data[i]->m_name << "\n"; separator_to_stream(); s << Color::Cyan << "[doctest] " << Color::None << "unskipped test cases passing the current filters: " << g_cs->numTestCasesPassingFilters << "\n"; } else if(opt.list_test_suites) { s << Color::Cyan << "[doctest] " << Color::None << "listing all test suites\n"; separator_to_stream(); for(unsigned i = 0; i < in.num_data; ++i) s << Color::None << in.data[i]->m_test_suite << "\n"; separator_to_stream(); s << Color::Cyan << "[doctest] " << Color::None << "unskipped test cases passing the current filters: " << g_cs->numTestCasesPassingFilters << "\n"; s << Color::Cyan << "[doctest] " << Color::None << "test suites with unskipped test cases passing the current filters: " << g_cs->numTestSuitesPassingFilters << "\n"; } } void test_run_start() override { if(!opt.minimal) printIntro(); } void test_run_end(const TestRunStats& p) override { if(opt.minimal && p.numTestCasesFailed == 0) return; separator_to_stream(); s << std::dec; auto totwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesPassingFilters, static_cast<unsigned>(p.numAsserts))) + 1))); auto passwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesPassingFilters - p.numTestCasesFailed, static_cast<unsigned>(p.numAsserts - p.numAssertsFailed))) + 1))); auto failwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesFailed, static_cast<unsigned>(p.numAssertsFailed))) + 1))); const bool anythingFailed = p.numTestCasesFailed > 0 || p.numAssertsFailed > 0; s << Color::Cyan << "[doctest] " << Color::None << "test cases: " << std::setw(totwidth) << p.numTestCasesPassingFilters << " | " << ((p.numTestCasesPassingFilters == 0 || anythingFailed) ? Color::None : Color::Green) << std::setw(passwidth) << p.numTestCasesPassingFilters - p.numTestCasesFailed << " passed" << Color::None << " | " << (p.numTestCasesFailed > 0 ? Color::Red : Color::None) << std::setw(failwidth) << p.numTestCasesFailed << " failed" << Color::None << " |"; if(opt.no_skipped_summary == false) { const int numSkipped = p.numTestCases - p.numTestCasesPassingFilters; s << " " << (numSkipped == 0 ? Color::None : Color::Yellow) << numSkipped << " skipped" << Color::None; } s << "\n"; s << Color::Cyan << "[doctest] " << Color::None << "assertions: " << std::setw(totwidth) << p.numAsserts << " | " << ((p.numAsserts == 0 || anythingFailed) ? Color::None : Color::Green) << std::setw(passwidth) << (p.numAsserts - p.numAssertsFailed) << " passed" << Color::None << " | " << (p.numAssertsFailed > 0 ? Color::Red : Color::None) << std::setw(failwidth) << p.numAssertsFailed << " failed" << Color::None << " |\n"; s << Color::Cyan << "[doctest] " << Color::None << "Status: " << (p.numTestCasesFailed > 0 ? Color::Red : Color::Green) << ((p.numTestCasesFailed > 0) ? "FAILURE!" : "SUCCESS!") << Color::None << std::endl; } void test_case_start(const TestCaseData& in) override { hasLoggedCurrentTestStart = false; tc = &in; subcasesStack.clear(); currentSubcaseLevel = 0; } void test_case_reenter(const TestCaseData&) override { subcasesStack.clear(); } void test_case_end(const CurrentTestCaseStats& st) override { if(tc->m_no_output) return; // log the preamble of the test case only if there is something // else to print - something other than that an assert has failed if(opt.duration || (st.failure_flags && st.failure_flags != static_cast<int>(TestCaseFailureReason::AssertFailure))) logTestStart(); if(opt.duration) s << Color::None << std::setprecision(6) << std::fixed << st.seconds << " s: " << tc->m_name << "\n"; if(st.failure_flags & TestCaseFailureReason::Timeout) s << Color::Red << "Test case exceeded time limit of " << std::setprecision(6) << std::fixed << tc->m_timeout << "!\n"; if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedButDidnt) { s << Color::Red << "Should have failed but didn't! Marking it as failed!\n"; } else if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedAndDid) { s << Color::Yellow << "Failed as expected so marking it as not failed\n"; } else if(st.failure_flags & TestCaseFailureReason::CouldHaveFailedAndDid) { s << Color::Yellow << "Allowed to fail so marking it as not failed\n"; } else if(st.failure_flags & TestCaseFailureReason::DidntFailExactlyNumTimes) { s << Color::Red << "Didn't fail exactly " << tc->m_expected_failures << " times so marking it as failed!\n"; } else if(st.failure_flags & TestCaseFailureReason::FailedExactlyNumTimes) { s << Color::Yellow << "Failed exactly " << tc->m_expected_failures << " times as expected so marking it as not failed!\n"; } if(st.failure_flags & TestCaseFailureReason::TooManyFailedAsserts) { s << Color::Red << "Aborting - too many failed asserts!\n"; } s << Color::None; // lgtm [cpp/useless-expression] } void test_case_exception(const TestCaseException& e) override { DOCTEST_LOCK_MUTEX(mutex) if(tc->m_no_output) return; logTestStart(); file_line_to_stream(tc->m_file.c_str(), tc->m_line, " "); successOrFailColoredStringToStream(false, e.is_crash ? assertType::is_require : assertType::is_check); s << Color::Red << (e.is_crash ? "test case CRASHED: " : "test case THREW exception: ") << Color::Cyan << e.error_string << "\n"; int num_stringified_contexts = get_num_stringified_contexts(); if(num_stringified_contexts) { auto stringified_contexts = get_stringified_contexts(); s << Color::None << " logged: "; for(int i = num_stringified_contexts; i > 0; --i) { s << (i == num_stringified_contexts ? "" : " ") << stringified_contexts[i - 1] << "\n"; } } s << "\n" << Color::None; } void subcase_start(const SubcaseSignature& subc) override { subcasesStack.push_back(subc); ++currentSubcaseLevel; hasLoggedCurrentTestStart = false; } void subcase_end() override { --currentSubcaseLevel; hasLoggedCurrentTestStart = false; } void log_assert(const AssertData& rb) override { if((!rb.m_failed && !opt.success) || tc->m_no_output) return; DOCTEST_LOCK_MUTEX(mutex) logTestStart(); file_line_to_stream(rb.m_file, rb.m_line, " "); successOrFailColoredStringToStream(!rb.m_failed, rb.m_at); fulltext_log_assert_to_stream(s, rb); log_contexts(); } void log_message(const MessageData& mb) override { if(tc->m_no_output) return; DOCTEST_LOCK_MUTEX(mutex) logTestStart(); file_line_to_stream(mb.m_file, mb.m_line, " "); s << getSuccessOrFailColor(false, mb.m_severity) << getSuccessOrFailString(mb.m_severity & assertType::is_warn, mb.m_severity, "MESSAGE") << ": "; s << Color::None << mb.m_string << "\n"; log_contexts(); } void test_case_skipped(const TestCaseData&) override {} }; DOCTEST_REGISTER_REPORTER("console", 0, ConsoleReporter); #ifdef DOCTEST_PLATFORM_WINDOWS struct DebugOutputWindowReporter : public ConsoleReporter { DOCTEST_THREAD_LOCAL static std::ostringstream oss; DebugOutputWindowReporter(const ContextOptions& co) : ConsoleReporter(co, oss) {} #define DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(func, type, arg) \ void func(type arg) override { \ bool with_col = g_no_colors; \ g_no_colors = false; \ ConsoleReporter::func(arg); \ if(oss.tellp() != std::streampos{}) { \ DOCTEST_OUTPUT_DEBUG_STRING(oss.str().c_str()); \ oss.str(""); \ } \ g_no_colors = with_col; \ } DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_start, DOCTEST_EMPTY, DOCTEST_EMPTY) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_end, const TestRunStats&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_start, const TestCaseData&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_reenter, const TestCaseData&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_end, const CurrentTestCaseStats&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_exception, const TestCaseException&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_start, const SubcaseSignature&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_end, DOCTEST_EMPTY, DOCTEST_EMPTY) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_assert, const AssertData&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_message, const MessageData&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_skipped, const TestCaseData&, in) }; DOCTEST_THREAD_LOCAL std::ostringstream DebugOutputWindowReporter::oss; #endif // DOCTEST_PLATFORM_WINDOWS // the implementation of parseOption() bool parseOptionImpl(int argc, const char* const* argv, const char* pattern, String* value) { // going from the end to the beginning and stopping on the first occurrence from the end for(int i = argc; i > 0; --i) { auto index = i - 1; auto temp = std::strstr(argv[index], pattern); if(temp && (value || strlen(temp) == strlen(pattern))) { //!OCLINT prefer early exits and continue // eliminate matches in which the chars before the option are not '-' bool noBadCharsFound = true; auto curr = argv[index]; while(curr != temp) { if(*curr++ != '-') { noBadCharsFound = false; break; } } if(noBadCharsFound && argv[index][0] == '-') { if(value) { // parsing the value of an option temp += strlen(pattern); const unsigned len = strlen(temp); if(len) { *value = temp; return true; } } else { // just a flag - no value return true; } } } } return false; } // parses an option and returns the string after the '=' character bool parseOption(int argc, const char* const* argv, const char* pattern, String* value = nullptr, const String& defaultVal = String()) { if(value) *value = defaultVal; #ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS // offset (normally 3 for "dt-") to skip prefix if(parseOptionImpl(argc, argv, pattern + strlen(DOCTEST_CONFIG_OPTIONS_PREFIX), value)) return true; #endif // DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS return parseOptionImpl(argc, argv, pattern, value); } // locates a flag on the command line bool parseFlag(int argc, const char* const* argv, const char* pattern) { return parseOption(argc, argv, pattern); } // parses a comma separated list of words after a pattern in one of the arguments in argv bool parseCommaSepArgs(int argc, const char* const* argv, const char* pattern, std::vector<String>& res) { String filtersString; if(parseOption(argc, argv, pattern, &filtersString)) { // tokenize with "," as a separator, unless escaped with backslash std::ostringstream s; auto flush = [&s, &res]() { auto string = s.str(); if(string.size() > 0) { res.push_back(string.c_str()); } s.str(""); }; bool seenBackslash = false; const char* current = filtersString.c_str(); const char* end = current + strlen(current); while(current != end) { char character = *current++; if(seenBackslash) { seenBackslash = false; if(character == ',' || character == '\\') { s.put(character); continue; } s.put('\\'); } if(character == '\\') { seenBackslash = true; } else if(character == ',') { flush(); } else { s.put(character); } } if(seenBackslash) { s.put('\\'); } flush(); return true; } return false; } enum optionType { option_bool, option_int }; // parses an int/bool option from the command line bool parseIntOption(int argc, const char* const* argv, const char* pattern, optionType type, int& res) { String parsedValue; if(!parseOption(argc, argv, pattern, &parsedValue)) return false; if(type) { // integer // TODO: change this to use std::stoi or something else! currently it uses undefined behavior - assumes '0' on failed parse... int theInt = std::atoi(parsedValue.c_str()); if (theInt != 0) { res = theInt; //!OCLINT parameter reassignment return true; } } else { // boolean const char positive[][5] = { "1", "true", "on", "yes" }; // 5 - strlen("true") + 1 const char negative[][6] = { "0", "false", "off", "no" }; // 6 - strlen("false") + 1 // if the value matches any of the positive/negative possibilities for (unsigned i = 0; i < 4; i++) { if (parsedValue.compare(positive[i], true) == 0) { res = 1; //!OCLINT parameter reassignment return true; } if (parsedValue.compare(negative[i], true) == 0) { res = 0; //!OCLINT parameter reassignment return true; } } } return false; } } // namespace Context::Context(int argc, const char* const* argv) : p(new detail::ContextState) { parseArgs(argc, argv, true); if(argc) p->binary_name = argv[0]; } Context::~Context() { if(g_cs == p) g_cs = nullptr; delete p; } void Context::applyCommandLine(int argc, const char* const* argv) { parseArgs(argc, argv); if(argc) p->binary_name = argv[0]; } // parses args void Context::parseArgs(int argc, const char* const* argv, bool withDefaults) { using namespace detail; // clang-format off parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file=", p->filters[0]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sf=", p->filters[0]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file-exclude=",p->filters[1]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sfe=", p->filters[1]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite=", p->filters[2]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ts=", p->filters[2]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite-exclude=", p->filters[3]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tse=", p->filters[3]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case=", p->filters[4]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tc=", p->filters[4]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case-exclude=", p->filters[5]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tce=", p->filters[5]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase=", p->filters[6]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sc=", p->filters[6]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase-exclude=", p->filters[7]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sce=", p->filters[7]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "reporters=", p->filters[8]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "r=", p->filters[8]); // clang-format on int intRes = 0; String strRes; #define DOCTEST_PARSE_AS_BOOL_OR_FLAG(name, sname, var, default) \ if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_bool, intRes) || \ parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_bool, intRes)) \ p->var = static_cast<bool>(intRes); \ else if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name) || \ parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname)) \ p->var = true; \ else if(withDefaults) \ p->var = default #define DOCTEST_PARSE_INT_OPTION(name, sname, var, default) \ if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_int, intRes) || \ parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_int, intRes)) \ p->var = intRes; \ else if(withDefaults) \ p->var = default #define DOCTEST_PARSE_STR_OPTION(name, sname, var, default) \ if(parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", &strRes, default) || \ parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", &strRes, default) || \ withDefaults) \ p->var = strRes // clang-format off DOCTEST_PARSE_STR_OPTION("out", "o", out, ""); DOCTEST_PARSE_STR_OPTION("order-by", "ob", order_by, "file"); DOCTEST_PARSE_INT_OPTION("rand-seed", "rs", rand_seed, 0); DOCTEST_PARSE_INT_OPTION("first", "f", first, 0); DOCTEST_PARSE_INT_OPTION("last", "l", last, UINT_MAX); DOCTEST_PARSE_INT_OPTION("abort-after", "aa", abort_after, 0); DOCTEST_PARSE_INT_OPTION("subcase-filter-levels", "scfl", subcase_filter_levels, INT_MAX); DOCTEST_PARSE_AS_BOOL_OR_FLAG("success", "s", success, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("case-sensitive", "cs", case_sensitive, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("exit", "e", exit, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("duration", "d", duration, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("minimal", "m", minimal, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("quiet", "q", quiet, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-throw", "nt", no_throw, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-exitcode", "ne", no_exitcode, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-run", "nr", no_run, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-intro", "ni", no_intro, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-version", "nv", no_version, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-colors", "nc", no_colors, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("force-colors", "fc", force_colors, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-breaks", "nb", no_breaks, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skip", "ns", no_skip, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("gnu-file-line", "gfl", gnu_file_line, !bool(DOCTEST_MSVC)); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-path-filenames", "npf", no_path_in_filenames, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-line-numbers", "nln", no_line_numbers, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-debug-output", "ndo", no_debug_output, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skipped-summary", "nss", no_skipped_summary, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-time-in-output", "ntio", no_time_in_output, false); // clang-format on if(withDefaults) { p->help = false; p->version = false; p->count = false; p->list_test_cases = false; p->list_test_suites = false; p->list_reporters = false; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "help") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "h") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "?")) { p->help = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "version") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "v")) { p->version = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "count") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "c")) { p->count = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-cases") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ltc")) { p->list_test_cases = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-suites") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lts")) { p->list_test_suites = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-reporters") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lr")) { p->list_reporters = true; p->exit = true; } } // allows the user to add procedurally to the filters from the command line void Context::addFilter(const char* filter, const char* value) { setOption(filter, value); } // allows the user to clear all filters from the command line void Context::clearFilters() { for(auto& curr : p->filters) curr.clear(); } // allows the user to override procedurally the bool options from the command line void Context::setOption(const char* option, bool value) { setOption(option, value ? "true" : "false"); } // allows the user to override procedurally the int options from the command line void Context::setOption(const char* option, int value) { setOption(option, toString(value).c_str()); } // allows the user to override procedurally the string options from the command line void Context::setOption(const char* option, const char* value) { auto argv = String("-") + option + "=" + value; auto lvalue = argv.c_str(); parseArgs(1, &lvalue); } // users should query this in their main() and exit the program if true bool Context::shouldExit() { return p->exit; } void Context::setAsDefaultForAssertsOutOfTestCases() { g_cs = p; } void Context::setAssertHandler(detail::assert_handler ah) { p->ah = ah; } void Context::setCout(std::ostream* out) { p->cout = out; } static class DiscardOStream : public std::ostream { private: class : public std::streambuf { private: // allowing some buffering decreases the amount of calls to overflow char buf[1024]; protected: std::streamsize xsputn(const char_type*, std::streamsize count) override { return count; } int_type overflow(int_type ch) override { setp(std::begin(buf), std::end(buf)); return traits_type::not_eof(ch); } } discardBuf; public: DiscardOStream() : std::ostream(&discardBuf) {} } discardOut; // the main function that does all the filtering and test running int Context::run() { using namespace detail; // save the old context state in case such was setup - for using asserts out of a testing context auto old_cs = g_cs; // this is the current contest g_cs = p; is_running_in_test = true; g_no_colors = p->no_colors; p->resetRunData(); std::fstream fstr; if(p->cout == nullptr) { if(p->quiet) { p->cout = &discardOut; } else if(p->out.size()) { // to a file if specified fstr.open(p->out.c_str(), std::fstream::out); p->cout = &fstr; } else { #ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM // stdout by default p->cout = &std::cout; #else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM return EXIT_FAILURE; #endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM } } FatalConditionHandler::allocateAltStackMem(); auto cleanup_and_return = [&]() { FatalConditionHandler::freeAltStackMem(); if(fstr.is_open()) fstr.close(); // restore context g_cs = old_cs; is_running_in_test = false; // we have to free the reporters which were allocated when the run started for(auto& curr : p->reporters_currently_used) delete curr; p->reporters_currently_used.clear(); if(p->numTestCasesFailed && !p->no_exitcode) return EXIT_FAILURE; return EXIT_SUCCESS; }; // setup default reporter if none is given through the command line if(p->filters[8].empty()) p->filters[8].push_back("console"); // check to see if any of the registered reporters has been selected for(auto& curr : getReporters()) { if(matchesAny(curr.first.second.c_str(), p->filters[8], false, p->case_sensitive)) p->reporters_currently_used.push_back(curr.second(*g_cs)); } // TODO: check if there is nothing in reporters_currently_used // prepend all listeners for(auto& curr : getListeners()) p->reporters_currently_used.insert(p->reporters_currently_used.begin(), curr.second(*g_cs)); #ifdef DOCTEST_PLATFORM_WINDOWS if(isDebuggerActive() && p->no_debug_output == false) p->reporters_currently_used.push_back(new DebugOutputWindowReporter(*g_cs)); #endif // DOCTEST_PLATFORM_WINDOWS // handle version, help and no_run if(p->no_run || p->version || p->help || p->list_reporters) { DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, QueryData()); return cleanup_and_return(); } std::vector<const TestCase*> testArray; for(auto& curr : getRegisteredTests()) testArray.push_back(&curr); p->numTestCases = testArray.size(); // sort the collected records if(!testArray.empty()) { if(p->order_by.compare("file", true) == 0) { std::sort(testArray.begin(), testArray.end(), fileOrderComparator); } else if(p->order_by.compare("suite", true) == 0) { std::sort(testArray.begin(), testArray.end(), suiteOrderComparator); } else if(p->order_by.compare("name", true) == 0) { std::sort(testArray.begin(), testArray.end(), nameOrderComparator); } else if(p->order_by.compare("rand", true) == 0) { std::srand(p->rand_seed); // random_shuffle implementation const auto first = &testArray[0]; for(size_t i = testArray.size() - 1; i > 0; --i) { int idxToSwap = std::rand() % (i + 1); const auto temp = first[i]; first[i] = first[idxToSwap]; first[idxToSwap] = temp; } } else if(p->order_by.compare("none", true) == 0) { // means no sorting - beneficial for death tests which call into the executable // with a specific test case in mind - we don't want to slow down the startup times } } std::set<String> testSuitesPassingFilt; bool query_mode = p->count || p->list_test_cases || p->list_test_suites; std::vector<const TestCaseData*> queryResults; if(!query_mode) DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_start, DOCTEST_EMPTY); // invoke the registered functions if they match the filter criteria (or just count them) for(auto& curr : testArray) { const auto& tc = *curr; bool skip_me = false; if(tc.m_skip && !p->no_skip) skip_me = true; if(!matchesAny(tc.m_file.c_str(), p->filters[0], true, p->case_sensitive)) skip_me = true; if(matchesAny(tc.m_file.c_str(), p->filters[1], false, p->case_sensitive)) skip_me = true; if(!matchesAny(tc.m_test_suite, p->filters[2], true, p->case_sensitive)) skip_me = true; if(matchesAny(tc.m_test_suite, p->filters[3], false, p->case_sensitive)) skip_me = true; if(!matchesAny(tc.m_name, p->filters[4], true, p->case_sensitive)) skip_me = true; if(matchesAny(tc.m_name, p->filters[5], false, p->case_sensitive)) skip_me = true; if(!skip_me) p->numTestCasesPassingFilters++; // skip the test if it is not in the execution range if((p->last < p->numTestCasesPassingFilters && p->first <= p->last) || (p->first > p->numTestCasesPassingFilters)) skip_me = true; if(skip_me) { if(!query_mode) DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_skipped, tc); continue; } // do not execute the test if we are to only count the number of filter passing tests if(p->count) continue; // print the name of the test and don't execute it if(p->list_test_cases) { queryResults.push_back(&tc); continue; } // print the name of the test suite if not done already and don't execute it if(p->list_test_suites) { if((testSuitesPassingFilt.count(tc.m_test_suite) == 0) && tc.m_test_suite[0] != '\0') { queryResults.push_back(&tc); testSuitesPassingFilt.insert(tc.m_test_suite); p->numTestSuitesPassingFilters++; } continue; } // execute the test if it passes all the filtering { p->currentTest = &tc; p->failure_flags = TestCaseFailureReason::None; p->seconds = 0; // reset atomic counters p->numAssertsFailedCurrentTest_atomic = 0; p->numAssertsCurrentTest_atomic = 0; p->fullyTraversedSubcases.clear(); DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_start, tc); p->timer.start(); bool run_test = true; do { // reset some of the fields for subcases (except for the set of fully passed ones) p->reachedLeaf = false; // May not be empty if previous subcase exited via exception. p->subcaseStack.clear(); p->currentSubcaseDepth = 0; p->shouldLogCurrentException = true; // reset stuff for logging with INFO() p->stringifiedContexts.clear(); #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS try { #endif // DOCTEST_CONFIG_NO_EXCEPTIONS // MSVC 2015 diagnoses fatalConditionHandler as unused (because reset() is a static method) DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4101) // unreferenced local variable FatalConditionHandler fatalConditionHandler; // Handle signals // execute the test tc.m_test(); fatalConditionHandler.reset(); DOCTEST_MSVC_SUPPRESS_WARNING_POP #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS } catch(const TestFailureException&) { p->failure_flags |= TestCaseFailureReason::AssertFailure; } catch(...) { DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, {translateActiveException(), false}); p->failure_flags |= TestCaseFailureReason::Exception; } #endif // DOCTEST_CONFIG_NO_EXCEPTIONS // exit this loop if enough assertions have failed - even if there are more subcases if(p->abort_after > 0 && p->numAssertsFailed + p->numAssertsFailedCurrentTest_atomic >= p->abort_after) { run_test = false; p->failure_flags |= TestCaseFailureReason::TooManyFailedAsserts; } if(!p->nextSubcaseStack.empty() && run_test) DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_reenter, tc); if(p->nextSubcaseStack.empty()) run_test = false; } while(run_test); p->finalizeTestCaseData(); DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); p->currentTest = nullptr; // stop executing tests if enough assertions have failed if(p->abort_after > 0 && p->numAssertsFailed >= p->abort_after) break; } } if(!query_mode) { DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); } else { QueryData qdata; qdata.run_stats = g_cs; qdata.data = queryResults.data(); qdata.num_data = unsigned(queryResults.size()); DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, qdata); } return cleanup_and_return(); } DOCTEST_DEFINE_INTERFACE(IReporter) int IReporter::get_num_active_contexts() { return detail::g_infoContexts.size(); } const IContextScope* const* IReporter::get_active_contexts() { return get_num_active_contexts() ? &detail::g_infoContexts[0] : nullptr; } int IReporter::get_num_stringified_contexts() { return detail::g_cs->stringifiedContexts.size(); } const String* IReporter::get_stringified_contexts() { return get_num_stringified_contexts() ? &detail::g_cs->stringifiedContexts[0] : nullptr; } namespace detail { void registerReporterImpl(const char* name, int priority, reporterCreatorFunc c, bool isReporter) { if(isReporter) getReporters().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); else getListeners().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); } } // namespace detail } // namespace doctest #endif // DOCTEST_CONFIG_DISABLE #ifdef DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) // 'function' : must be 'attribute' - see issue #182 int main(int argc, char** argv) { return doctest::Context(argc, argv).run(); } DOCTEST_MSVC_SUPPRESS_WARNING_POP #endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP DOCTEST_SUPPRESS_COMMON_WARNINGS_POP #endif // DOCTEST_LIBRARY_IMPLEMENTATION #endif // DOCTEST_CONFIG_IMPLEMENT #ifdef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #undef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN #endif // DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN #ifdef DOCTEST_UNDEF_NOMINMAX #undef NOMINMAX #undef DOCTEST_UNDEF_NOMINMAX #endif // DOCTEST_UNDEF_NOMINMAX
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/cmake_target_include_directories/project/Foo.cpp
.cpp
344
12
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "Foo.hpp" class Foo;
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/cmake_target_include_directories/project/Bar.cpp
.cpp
344
12
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include "Bar.hpp" class Bar;
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/cmake_target_include_directories/project/Foo.hpp
.hpp
370
13
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #pragma once #include <nlohmann/json.hpp> class Foo {};
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/cmake_target_include_directories/project/main.cpp
.cpp
416
17
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include <nlohmann/json.hpp> int main(int argc, char** argv) { nlohmann::json j; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/cmake_target_include_directories/project/Bar.hpp
.hpp
389
13
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include <nlohmann/json.hpp> #include "Foo.hpp" class Bar : public Foo {};
Unknown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/tests/cmake_add_subdirectory/project/main.cpp
.cpp
416
17
// __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ (supporting code) // | | |__ | | | | | | version 3.11.2 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me> // SPDX-License-Identifier: MIT #include <nlohmann/json.hpp> int main(int argc, char** argv) { nlohmann::json j; return 0; }
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/allocator.h
.h
1,588
70
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include <vector> #include <cstring> #include "conf.h" namespace IsoSpec { template <typename T> inline void copyConf( const T* source, T* destination, int dim ){ memcpy(destination, source, dim*sizeof(T)); } template <typename T> class Allocator { private: T* currentTab; int currentId; const int dim, tabSize; std::vector<T*> prevTabs; public: explicit Allocator(const int dim, const int tabSize = 10000); ~Allocator(); Allocator(const Allocator& other) = delete; Allocator& operator=(const Allocator& other) = delete; void shiftTables(); inline T* newConf() { currentId++; if (currentId >= tabSize) shiftTables(); return &(currentTab[ currentId * dim ]); } inline T* makeCopy(const T* conf) { T* currentPlace = newConf(); copyConf<T>( conf, currentPlace, dim ); return currentPlace; } }; } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/operators.h
.h
3,986
151
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include "conf.h" #include "isoMath.h" #include "misc.h" #include "platform.h" #include <cstring> namespace IsoSpec { class KeyHasher { private: int dim; public: explicit KeyHasher(int dim); inline std::size_t operator()(const int* conf) const noexcept { std::size_t seed = conf[0]; for(int i = 1; i < dim; ++i ) { constexpr_if(sizeof(std::size_t) == 8) seed = seed << 6; else // Assuming 32 bit arch. If not, well, there will be // more hash collisions but it still should run OK seed = seed << 3; seed ^= conf[i]; } return seed; }; }; class ConfEqual { private: int size; public: explicit ConfEqual(int dim); inline bool operator()(const int* conf1, const int* conf2) const { // The memcmp() function returns zero if the two strings are identical, oth- // erwise returns the difference between the first two differing bytes // (treated as unsigned char values, so that `\200' is greater than `\0', // for example). Zero-length strings are always identical. This behavior // is not required by C and portable code should only depend on the sign of // the returned value. // sacred man of memcmp. return memcmp(conf1, conf2, size) == 0; } }; class ConfOrder { // configurations comparator public: inline bool operator()(void* conf1, void* conf2) const { return *reinterpret_cast<double*>(conf1) < *reinterpret_cast<double*>(conf2); }; }; class ConfOrderMarginal { // configurations comparator const double* logProbs; int dim; public: ConfOrderMarginal(const double* logProbs, int dim); inline bool operator()(const Conf conf1, const Conf conf2) { // Return true if conf1 is less probable than conf2. return unnormalized_logProb(conf1, logProbs, dim) < unnormalized_logProb(conf2, logProbs, dim); }; }; class ConfOrderMarginalDescending { // configurations comparator const double* logProbs; int dim; public: ConfOrderMarginalDescending(const double* logProbs, int dim); inline bool operator()(const Conf conf1, const Conf conf2) { // Return true if conf1 is less probable than conf2. return unnormalized_logProb(conf1, logProbs, dim) > unnormalized_logProb(conf2, logProbs, dim); }; }; template<typename T> class ReverseOrder { public: inline ReverseOrder() {} inline bool operator()(const T a, const T b) const { return a > b; } }; template<typename T> class TableOrder { const T* tbl; public: inline explicit TableOrder(const T* _tbl) : tbl(_tbl) {} inline bool operator()(unsigned int i, unsigned int j) { return tbl[i] < tbl[j]; } }; } // namespace IsoSpec #include "marginalTrek++.h" class PrecalculatedMarginal; // In case marginalTrek++.h us including us, and can't be included again... namespace IsoSpec { template<typename T> class OrderMarginalsBySizeDecresing { T const* const* const MT; public: explicit OrderMarginalsBySizeDecresing(T const* const * const MT_) : MT(MT_) {}; inline bool operator()(int m1, int m2) { return MT[m1]->get_no_confs() > MT[m2]->get_no_confs(); } }; } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/tabulator.h
.h
3,389
102
#pragma once #include <stdlib.h> #include "isoSpec++.h" #define ISOSPEC_INIT_TABLE_SIZE 1024 namespace IsoSpec { template <typename T> class Tabulator { private: double* _masses; double* _lprobs; double* _probs; int* _confs; size_t _confs_no; public: Tabulator(T* generator, bool get_masses, bool get_probs, bool get_lprobs, bool get_confs); ~Tabulator(); inline double* masses(bool release = false) { double* ret = _masses; if(release) _masses = nullptr; return ret; }; inline double* lprobs(bool release = false) { double* ret = _lprobs; if(release) _lprobs = nullptr; return ret; }; inline double* probs(bool release = false) { double* ret = _probs; if(release) _probs = nullptr; return ret; }; inline int* confs(bool release = false) { int* ret = _confs; if(release) _confs = nullptr; return ret; }; inline size_t confs_no() { return _confs_no; }; }; inline void reallocate(double **array, int new_size){ if( *array != nullptr ){ *array = (double *) realloc(*array, new_size); } } template <typename T> Tabulator<T>::Tabulator(T* generator, bool get_masses, bool get_probs, bool get_lprobs, bool get_confs ) { size_t current_size = ISOSPEC_INIT_TABLE_SIZE; int confs_tbl_idx = 0; _confs_no = 0; const int allDimSizeOfInt = sizeof(int)*generator->getAllDim(); _masses = get_masses ? (double *) malloc(ISOSPEC_INIT_TABLE_SIZE * sizeof(double)) : nullptr; _lprobs = get_lprobs ? (double *) malloc(ISOSPEC_INIT_TABLE_SIZE * sizeof(double)) : nullptr; _probs = get_probs ? (double *) malloc(ISOSPEC_INIT_TABLE_SIZE * sizeof(double)) : nullptr; _confs = get_confs ? (int *) malloc(ISOSPEC_INIT_TABLE_SIZE * allDimSizeOfInt): nullptr; while(generator->advanceToNextConfiguration()){ if( _confs_no == current_size ) { current_size *= 2; // FIXME: Handle overflow gracefully here. It definitely could happen for people still stuck on 32 bits... reallocate(&_masses, current_size * sizeof(double)); reallocate(&_lprobs, current_size * sizeof(double)); reallocate(&_probs, current_size * sizeof(double)); if( _confs != nullptr ){ _confs = (int *) realloc(_confs, current_size * allDimSizeOfInt); } } if(_masses != nullptr) _masses[_confs_no] = generator->mass(); if(_lprobs != nullptr) _lprobs[_confs_no] = generator->lprob(); if(_probs != nullptr) _probs[_confs_no] = generator->prob(); if(_confs != nullptr){ generator->get_conf_signature(_confs + confs_tbl_idx); confs_tbl_idx += generator->getAllDim(); } _confs_no++; } _masses = (double *) realloc(_masses, _confs_no * sizeof(double)); _lprobs = (double *) realloc(_lprobs, _confs_no * sizeof(double)); _probs = (double *) realloc(_probs, _confs_no * sizeof(double)); _confs = (int *) realloc(_confs, confs_tbl_idx * sizeof(int)); } template <typename T> Tabulator<T>::~Tabulator() { if( _masses != nullptr ) free(_masses); if( _lprobs != nullptr ) free(_lprobs); if( _probs != nullptr ) free(_probs); if( _confs != nullptr ) free(_confs); } } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/isoSpec++.h
.h
27,275
637
/*! Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. This file is part of IsoSpec. IsoSpec is free software: you can redistribute it and/or modify it under the terms of the Simplified ("2-clause") BSD licence. IsoSpec 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. You should have received a copy of the Simplified BSD Licence along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include <unordered_map> #include <queue> #include <limits> #include <string> #include <vector> #include "platform.h" #include "dirtyAllocator.h" #include "summator.h" #include "operators.h" #include "marginalTrek++.h" namespace IsoSpec { // This function is NOT guaranteed to be secure against malicious input. It should be used only for debugging. unsigned int parse_formula(const char* formula, std::vector<double>& isotope_masses, std::vector<double>& isotope_probabilities, int** isotopeNumbers, int** atomCounts, unsigned int* confSize, bool use_nominal_masses = false); //! The Iso class for the calculation of the isotopic distribution. /*! It contains full description of the molecule for which one would like to calculate the isotopic distribution. */ class ISOSPEC_EXPORT_SYMBOL Iso { private: //! Set up the marginal isotopic envelopes, corresponding to subisotopologues. /*! \param _isotopeMasses A table of masses of isotopes of the elements in the chemical formula, e.g. {12.0, 13.003355, 1.007825, 2.014102} for C100H202. \param _isotopeProbabilities A table of isotope frequencies of the elements in the chemical formula, e.g. {.989212, .010788, .999885, .000115} for C100H202. */ void setupMarginals(const double* _isotopeMasses, const double* _isotopeProbabilities); bool disowned; /*!< A variable showing if the Iso class was specialized by its child-class. If so, then the description of the molecules has been transfered there and Iso is a carcass class, dead as a dodo, an ex-class if you will. */ protected: int dimNumber; /*!< The number of elements in the chemical formula of the molecule. */ int* isotopeNumbers; /*!< A table with numbers of isotopes for each element. */ int* atomCounts; /*!< A table with numbers of isotopes for each element. */ unsigned int confSize; /*!< The number of bytes needed to represent the counts of isotopes present in the extended chemical formula. */ int allDim; /*!< The total number of isotopes of elements present in a chemical formula, e.g. for H20 it is 2+3=5. */ Marginal** marginals; /*!< The table of pointers to the distributions of individual subisotopologues. */ bool doMarginalsNeedSorting() const; public: Iso(); //! General constructror. /*! \param _dimNumber The number of elements in the formula, e.g. for C100H202 it would be 2, as there are only carbon and hydrogen atoms. \param _isotopeNumbers A table with numbers of isotopes for each element, e.g. for C100H202 it would be {2, 2}, because both C and H have two stable isotopes. \param _atomCounts Number of atoms of each element in the formula, e.g. for C100H202 corresponds to {100, 202}. \param _isotopeMasses A table of tables of masses of isotopes of the elements in the chemical formula, e.g. {{12.0, 13.003355}, {1.007825, 2.014102}} for C100H202. \param _isotopeProbabilities A table of tables of isotope frequencies of the elements in the chemical formula, e.g. {{.989212, .010788}, {.999885, .000115}} for C100H202. */ Iso( int _dimNumber, const int* _isotopeNumbers, const int* _atomCounts, const double* _isotopeMasses, const double* _isotopeProbabilities ); Iso( int _dimNumber, const int* _isotopeNumbers, const int* _atomCounts, const double* const * _isotopeMasses, const double* const * _isotopeProbabilities ); //! Constructor from the formula object. Iso(const char* formula, bool use_nominal_masses = false); // NOLINT(runtime/explicit) - constructor deliberately left to be used as a conversion //! Constructor from C++ std::string chemical formula. inline Iso(const std::string& formula, bool use_nominal_masses = false) : Iso(formula.c_str(), use_nominal_masses) {} // NOLINT(runtime/explicit) - constructor deliberately left to be used as a conversion //! Constructor (named) from aminoacid FASTA sequence as C string. /*! \param fasta An aminoacid FASTA sequence. May be upper/lower/mixed case, may contain selenocystein (U). Subisotopologues will be in order: CHNOS, possibly with Se added at an end if present. \use_nominal_masses Whether to use nucleon number instead of the real mass of each isotope during calculations. \add_water Whether the chain should have the terminating -H and -OH groups at the N and C terminus, respectively. */ static Iso FromFASTA(const char* fasta, bool use_nominal_masses = false, bool add_water = true); //! Constructor (named) from aminoacid FASTA sequence as C++ std::string. See above for details. static inline Iso FromFASTA(const std::string& fasta, bool use_nominal_masses = false, bool add_water = true) { return FromFASTA(fasta.c_str(), use_nominal_masses, add_water); } //! The move constructor. Iso(Iso&& other) noexcept ; /* We're not exactly following standard copy and assign semantics with Iso objects, so delete the default assign constructor just in case, so noone tries to use it. Copy ctor declared below. */ Iso& operator=(const Iso& other) = delete; //! The copy constructor. /*! \param other The other instance of the Iso class. \param fullcopy If false, copy only the number of atoms in the formula, the size of the configuration, the total number of isotopes, and the probability of the mode isotopologue. */ Iso(const Iso& other, bool fullcopy); //! Destructor. virtual ~Iso(); //! Get the mass of the lightest peak in the isotopic distribution. double getLightestPeakMass() const; //! Get the mass of the heaviest peak in the isotopic distribution. double getHeaviestPeakMass() const; /*! Get the mass of the monoisotopic peak in the isotopic distribution. Monoisotopc molecule is defined as consisting only of the most frequent isotopes of each element. These are often (but not always) the lightest ones, making this often (but again, not always) equal to getLightestPeakMass() */ double getMonoisotopicPeakMass() const; //! Get the log-probability of the mode-configuration (if there are many modes, they share this value). double getModeLProb() const; //! Get the logprobability of the least probable subisotopologue. double getUnlikeliestPeakLProb() const; //! Get the mass of the mode-configuration (if there are many modes, it is undefined which one will be selected). double getModeMass() const; //! Get the theoretical average mass of the molecule. double getTheoreticalAverageMass() const; //! Get the theoretical variance of the distribution. double variance() const; //! Get the standard deviation of the theoretical distribution. double stddev() const { return sqrt(variance()); } //! Get the number of elements in the chemical formula of the molecule. inline int getDimNumber() const { return dimNumber; } //! Get the total number of isotopes of elements present in a chemical formula. inline int getAllDim() const { return allDim; } //! Add an element to the molecule. Note: this method can only be used BEFORE Iso is used to construct an IsoGenerator instance. void addElement(int atomCount, int noIsotopes, const double* isotopeMasses, const double* isotopeProbabilities); //! Save estimates of logarithms of target sizes of marginals using Gaussian approximation into argument array. Array priorities must have length equal to dimNumber. void saveMarginalLogSizeEstimates(double* priorities, double target_total_prob) const; }; //! The generator of isotopologues. /*! This class provides the common interface for all isotopic generators. */ class ISOSPEC_EXPORT_SYMBOL IsoGenerator : public Iso { public: const double mode_lprob; protected: double* partialLProbs; /*!< The prefix sum of the log-probabilities of the current isotopologue. */ double* partialMasses; /*!< The prefix sum of the masses of the current isotopologue. */ double* partialProbs; /*!< The prefix product of the probabilities of the current isotopologue. */ public: //! Advance to the next, not yet visited, most probable isotopologue. /*! \return Return false if it is not possible to advance. */ virtual bool advanceToNextConfiguration() = 0; //! Get the log-probability of the current isotopologue. /*! \return The log-probability of the current isotopologue. */ virtual double lprob() const { return partialLProbs[0]; } //! Get the mass of the current isotopologue. /*! \return The mass of the current isotopologue. */ virtual double mass() const { return partialMasses[0]; } //! Get the probability of the current isotopologue. /*! \return The probability of the current isotopologue. */ virtual double prob() const { return partialProbs[0]; } //! Write the signature of configuration into target memory location. It must be large enough to accomodate it. virtual void get_conf_signature(int* space) const = 0; //! Move constructor. IsoGenerator(Iso&& iso, bool alloc_partials = true); // NOLINT(runtime/explicit) - constructor deliberately left to be used as a conversion //! Destructor. ~IsoGenerator() override; }; //! The generator of isotopologues sorted by their probability of occurrence. /*! The subsequent isotopologues are generated with diminishing probability, starting from the mode. This algorithm take O(N*log(N)) to compute the N isotopologues because of using the Priority Queue data structure. Obtaining the N isotopologues can be achieved in O(N) if they are not required to be spit out in the descending order. */ class ISOSPEC_EXPORT_SYMBOL IsoOrderedGenerator: public IsoGenerator { private: MarginalTrek** marginalResults; /*!< Table of pointers to marginal distributions of subisotopologues. */ std::priority_queue<void*, std::vector<void*>, ConfOrder> pq; /*!< The priority queue used to generate isotopologues ordered by descending probability. */ void* topConf; /*!< Most probable configuration. */ DirtyAllocator allocator; /*!< Structure used for alocating memory for isotopologues. */ const std::vector<double>** logProbs; /*!< Obtained log-probabilities. */ const std::vector<double>** masses; /*!< Obtained masses. */ const std::vector<int*>** marginalConfs; /*!< Obtained counts of isotopes. */ double currentLProb; /*!< The log-probability of the current isotopologue. */ double currentMass; /*!< The mass of the current isotopologue. */ double currentProb; /*!< The probability of the current isotopologue. */ int ccount; public: IsoOrderedGenerator(const IsoOrderedGenerator& other) = delete; IsoOrderedGenerator& operator=(const IsoOrderedGenerator& other) = delete; bool advanceToNextConfiguration() final; //! Save the counts of isotopes in the space. /*! \param space An array where counts of isotopes shall be written. Must be as big as the overall number of isotopes. */ inline void get_conf_signature(int* space) const final { int* c = getConf(topConf); if (ccount >= 0) c[ccount]--; for(int ii = 0; ii < dimNumber; ii++) { memcpy(space, marginalResults[ii]->confs()[c[ii]], isotopeNumbers[ii]*sizeof(int)); space += isotopeNumbers[ii]; } if (ccount >= 0) c[ccount]++; }; //! The move-contstructor. IsoOrderedGenerator(Iso&& iso, int _tabSize = 1000, int _hashSize = 1000); // NOLINT(runtime/explicit) - constructor deliberately left to be used as a conversion //! Destructor. ~IsoOrderedGenerator() override; }; //! The generator of isotopologues above a given threshold value. /*! Attention: the calculated configurations are only partially ordeded and the user should not assume they will be ordered. This algorithm computes N isotopologues in O(N). It is a considerable advantage w.r.t. the IsoOrderedGenerator. */ class ISOSPEC_EXPORT_SYMBOL IsoThresholdGenerator: public IsoGenerator { private: int* counter; /*!< An array storing the position of an isotopologue in terms of the subisotopologues ordered by decreasing probability. */ double* maxConfsLPSum; const double Lcutoff; /*!< The logarithm of the lower bound on the calculated probabilities. */ PrecalculatedMarginal** marginalResults; PrecalculatedMarginal** marginalResultsUnsorted; int* marginalOrder; const double* lProbs_ptr; const double* lProbs_ptr_start; double* partialLProbs_second; double partialLProbs_second_val, lcfmsv; bool empty; public: IsoThresholdGenerator(const IsoThresholdGenerator& other) = delete; IsoThresholdGenerator& operator=(const IsoThresholdGenerator& other) = delete; inline void get_conf_signature(int* space) const final { counter[0] = lProbs_ptr - lProbs_ptr_start; if(marginalOrder != nullptr) { for(int ii = 0; ii < dimNumber; ii++) { int jj = marginalOrder[ii]; memcpy(space, marginalResultsUnsorted[ii]->get_conf(counter[jj]), isotopeNumbers[ii]*sizeof(int)); space += isotopeNumbers[ii]; } } else { for(int ii = 0; ii < dimNumber; ii++) { memcpy(space, marginalResultsUnsorted[ii]->get_conf(counter[ii]), isotopeNumbers[ii]*sizeof(int)); space += isotopeNumbers[ii]; } } }; //! The move-constructor. /*! \param iso An instance of the Iso class. \param _threshold The threshold value. \param _absolute If true, the _threshold is interpreted as the absolute minimal peak height for the isotopologues. If false, the _threshold is the fraction of the heighest peak's probability. \param tabSize The size of the extension of the table with configurations. \param hashSize The size of the hash-table used to store subisotopologues and check if they have been already calculated. */ IsoThresholdGenerator(Iso&& iso, double _threshold, bool _absolute = true, int _tabSize = 1000, int _hashSize = 1000, bool reorder_marginals = true); ~IsoThresholdGenerator() override; // Perform highly aggressive inling as this function is often called as while(advanceToNextConfiguration()) {} // which leads to an extremely tight loop and some compilers miss this (potentially due to the length of the function). ISOSPEC_FORCE_INLINE bool advanceToNextConfiguration() final { lProbs_ptr++; if(ISOSPEC_LIKELY(*lProbs_ptr >= lcfmsv)) { return true; } // If we reached this point, a carry is needed int idx = 0; lProbs_ptr = lProbs_ptr_start; int * cntr_ptr = counter; while(idx < dimNumber-1) { // counter[idx] = 0; *cntr_ptr = 0; idx++; cntr_ptr++; // counter[idx]++; (*cntr_ptr)++; partialLProbs[idx] = partialLProbs[idx+1] + marginalResults[idx]->get_lProb(counter[idx]); if(partialLProbs[idx] + maxConfsLPSum[idx-1] >= Lcutoff) { partialMasses[idx] = partialMasses[idx+1] + marginalResults[idx]->get_mass(counter[idx]); partialProbs[idx] = partialProbs[idx+1] * marginalResults[idx]->get_prob(counter[idx]); recalc(idx-1); return true; } } terminate_search(); return false; } ISOSPEC_FORCE_INLINE double lprob() const final { return partialLProbs_second_val + (*(lProbs_ptr)); } ISOSPEC_FORCE_INLINE double mass() const final { return partialMasses[1] + marginalResults[0]->get_mass(lProbs_ptr - lProbs_ptr_start); } ISOSPEC_FORCE_INLINE double prob() const final { return partialProbs[1] * marginalResults[0]->get_prob(lProbs_ptr - lProbs_ptr_start); } //! Block the subsequent search of isotopologues. void terminate_search(); /*! Reset the generator to the beginning of the sequence. Allows it to be reused, eg. to go through the conf space once, calculate the amount of space needed to store configurations, then to allocate that memory, and go through it again, this time saving configurations (and *is* in fact faster than allocating a std::vector and depending on it to grow as needed. This is cheaper than throwing away the generator and making a new one too: marginal distributions don't need to be recalculated. */ void reset(); /*! Count the number of configurations in the distribution. This can be used to pre-allocate enough memory to store it (e.g. * std::vector's reserve() method - this is faster than depending on the vector's dynamic resizing, even though it means that * the configuration space is walked through twice. This method has to be called before the first call to advanceToNextConfiguration * and has undefined results (incl. segfaults) otherwise. */ size_t count_confs(); private: //! Recalculate the current partial log-probabilities, masses, and probabilities. ISOSPEC_FORCE_INLINE void recalc(int idx) { for(; idx > 0; idx--) { partialLProbs[idx] = partialLProbs[idx+1] + marginalResults[idx]->get_lProb(counter[idx]); partialMasses[idx] = partialMasses[idx+1] + marginalResults[idx]->get_mass(counter[idx]); partialProbs[idx] = partialProbs[idx+1] * marginalResults[idx]->get_prob(counter[idx]); } partialLProbs_second_val = *partialLProbs_second; partialLProbs[0] = *partialLProbs_second + marginalResults[0]->get_lProb(counter[0]); lcfmsv = Lcutoff - partialLProbs_second_val; } ISOSPEC_FORCE_INLINE void short_recalc(int idx) { for(; idx > 0; idx--) partialLProbs[idx] = partialLProbs[idx+1] + marginalResults[idx]->get_lProb(counter[idx]); partialLProbs_second_val = *partialLProbs_second; partialLProbs[0] = *partialLProbs_second + marginalResults[0]->get_lProb(counter[0]); lcfmsv = Lcutoff - partialLProbs_second_val; } }; class ISOSPEC_EXPORT_SYMBOL IsoLayeredGenerator : public IsoGenerator { private: int* counter; /*!< An array storing the position of an isotopologue in terms of the subisotopologues ordered by decreasing probability. */ double* maxConfsLPSum; double currentLThreshold, lastLThreshold; LayeredMarginal** marginalResults; LayeredMarginal** marginalResultsUnsorted; int* marginalOrder; const double* lProbs_ptr; const double* lProbs_ptr_start; const double** resetPositions; double* partialLProbs_second; double partialLProbs_second_val, lcfmsv, last_lcfmsv; bool marginalsNeedSorting; public: IsoLayeredGenerator(const IsoLayeredGenerator& other) = delete; IsoLayeredGenerator& operator=(const IsoLayeredGenerator& other) = delete; inline void get_conf_signature(int* space) const final { counter[0] = lProbs_ptr - lProbs_ptr_start; if(marginalOrder != nullptr) { for(int ii = 0; ii < dimNumber; ii++) { int jj = marginalOrder[ii]; memcpy(space, marginalResultsUnsorted[ii]->get_conf(counter[jj]), isotopeNumbers[ii]*sizeof(int)); space += isotopeNumbers[ii]; } } else { for(int ii = 0; ii < dimNumber; ii++) { memcpy(space, marginalResultsUnsorted[ii]->get_conf(counter[ii]), isotopeNumbers[ii]*sizeof(int)); space += isotopeNumbers[ii]; } } }; inline double get_currentLThreshold() const { return currentLThreshold; } IsoLayeredGenerator(Iso&& iso, int _tabSize = 1000, int _hashSize = 1000, bool reorder_marginals = true, double t_prob_hint = 0.99); // NOLINT(runtime/explicit) - constructor deliberately left to be used as a conversion ~IsoLayeredGenerator() override; ISOSPEC_FORCE_INLINE bool advanceToNextConfiguration() final { do { if(advanceToNextConfigurationWithinLayer()) return true; } while(IsoLayeredGenerator::nextLayer(-2.0)); return false; } ISOSPEC_FORCE_INLINE bool advanceToNextConfigurationWithinLayer() { do{ lProbs_ptr++; if(ISOSPEC_LIKELY(*lProbs_ptr >= lcfmsv)) return true; } while(carry()); // NOLINT(whitespace/empty_loop_body) - cpplint bug, that's not an empty loop body, that's a do{...}while(...) construct return false; } ISOSPEC_FORCE_INLINE double lprob() const final { return partialLProbs_second_val + (*(lProbs_ptr)); }; ISOSPEC_FORCE_INLINE double mass() const final { return partialMasses[1] + marginalResults[0]->get_mass(lProbs_ptr - lProbs_ptr_start); }; ISOSPEC_FORCE_INLINE double prob() const final { return partialProbs[1] * marginalResults[0]->get_prob(lProbs_ptr - lProbs_ptr_start); }; //! Block the subsequent search of isotopologues. void terminate_search(); //! Recalculate the current partial log-probabilities, masses, and probabilities. ISOSPEC_FORCE_INLINE void recalc(int idx) { for(; idx > 0; idx--) { partialLProbs[idx] = partialLProbs[idx+1] + marginalResults[idx]->get_lProb(counter[idx]); partialMasses[idx] = partialMasses[idx+1] + marginalResults[idx]->get_mass(counter[idx]); partialProbs[idx] = partialProbs[idx+1] * marginalResults[idx]->get_prob(counter[idx]); } partialLProbs_second_val = *partialLProbs_second; partialLProbs[0] = partialLProbs_second_val + marginalResults[0]->get_lProb(counter[0]); lcfmsv = currentLThreshold - partialLProbs_second_val; last_lcfmsv = lastLThreshold - partialLProbs_second_val; } bool nextLayer(double offset); private: bool carry(); }; class IsoStochasticGenerator : IsoGenerator { IsoLayeredGenerator ILG; size_t to_sample_left; const double precision; const double beta_bias; double confs_prob; double chasing_prob; size_t current_count; public: IsoStochasticGenerator(Iso&& iso, size_t no_molecules, double precision = 0.9999, double beta_bias = 5.0); ISOSPEC_FORCE_INLINE size_t count() const { return current_count; } ISOSPEC_FORCE_INLINE double mass() const final { return ILG.mass(); } ISOSPEC_FORCE_INLINE double prob() const final { return static_cast<double>(count()); } ISOSPEC_FORCE_INLINE double lprob() const final { return log(prob()); } ISOSPEC_FORCE_INLINE void get_conf_signature(int* space) const final { ILG.get_conf_signature(space); } ISOSPEC_FORCE_INLINE bool advanceToNextConfiguration() final { /* This function will be used mainly in very small, tight loops, therefore it makes sense to * aggressively inline it, despite its seemingly large body. */ while(true) { double curr_conf_prob_left, current_prob; if(to_sample_left <= 0) return false; if(confs_prob < chasing_prob) { // Beta was last current_count = 1; to_sample_left--; ILG.advanceToNextConfiguration(); current_prob = ILG.prob(); confs_prob += current_prob; while(confs_prob <= chasing_prob) { ILG.advanceToNextConfiguration(); current_prob = ILG.prob(); confs_prob += current_prob; } if(to_sample_left <= 0) return true; curr_conf_prob_left = confs_prob - chasing_prob; } else { // Binomial was last current_count = 0; ILG.advanceToNextConfiguration(); current_prob = ILG.prob(); confs_prob += current_prob; curr_conf_prob_left = current_prob; } double prob_left_to_1 = precision - chasing_prob; double expected_confs = curr_conf_prob_left * to_sample_left / prob_left_to_1; if(expected_confs <= beta_bias) { // Beta mode: we keep making beta jumps until we leave the current configuration chasing_prob += rdvariate_beta_1_b(to_sample_left) * prob_left_to_1; while(chasing_prob <= confs_prob) { current_count++; to_sample_left--; if(to_sample_left == 0) return true; prob_left_to_1 = precision - chasing_prob; chasing_prob += rdvariate_beta_1_b(to_sample_left) * prob_left_to_1; } if(current_count > 0) return true; } else { // Binomial mode: a single binomial step size_t rbin = rdvariate_binom(to_sample_left, curr_conf_prob_left/prob_left_to_1); current_count += rbin; to_sample_left -= rbin; chasing_prob = confs_prob; if(current_count > 0) return true; } }; } }; } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/cwrapper.h
.h
5,028
141
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #define ISOSPEC_ALGO_LAYERED 0 #define ISOSPEC_ALGO_ORDERED 1 #define ISOSPEC_ALGO_THRESHOLD_ABSOLUTE 2 #define ISOSPEC_ALGO_THRESHOLD_RELATIVE 3 #define ISOSPEC_ALGO_LAYERED_ESTIMATE 4 #ifdef __cplusplus extern "C" { #else #include <stdbool.h> #endif void * setupIso(int dimNumber, const int* isotopeNumbers, const int* atomCounts, const double* isotopeMasses, const double* isotopeProbabilities); void * isoFromFasta(const char* fasta, bool use_nominal_masses, bool add_water); double getLightestPeakMassIso(void* iso); double getHeaviestPeakMassIso(void* iso); double getMonoisotopicPeakMassIso(void* iso); double getModeLProbIso(void* iso); double getModeMassIso(void* iso); double getTheoreticalAverageMassIso(void* iso); double getIsoVariance(void* iso); double getIsoStddev(void* iso); double* getMarginalLogSizeEstimates(void* iso, double target_total_prob); void deleteIso(void* iso); #define ISOSPEC_C_FN_HEADER(generatorType, dataType, method)\ dataType method##generatorType(void* generator); #define ISOSPEC_C_FN_HEADER_GET_CONF_SIGNATURE(generatorType)\ void method##generatorType(void* generator); #define ISOSPEC_C_FN_HEADERS(generatorType)\ ISOSPEC_C_FN_HEADER(generatorType, double, mass) \ ISOSPEC_C_FN_HEADER(generatorType, double, lprob) \ ISOSPEC_C_FN_HEADER(generatorType, double, prob) \ ISOSPEC_C_FN_HEADER_GET_CONF_SIGNATURE(generatorType) \ ISOSPEC_C_FN_HEADER(generatorType, bool, advanceToNextConfiguration) \ ISOSPEC_C_FN_HEADER(generatorType, void, delete) // ______________________________________________________THRESHOLD GENERATOR void* setupIsoThresholdGenerator(void* iso, double threshold, bool _absolute, int _tabSize, int _hashSize, bool reorder_marginals); ISOSPEC_C_FN_HEADERS(IsoThresholdGenerator) // ______________________________________________________LAYERED GENERATOR void* setupIsoLayeredGenerator(void* iso, int _tabSize, int _hashSize, bool reorder_marginals, double t_prob_hint); ISOSPEC_C_FN_HEADERS(IsoLayeredGenerator) // ______________________________________________________ORDERED GENERATOR void* setupIsoOrderedGenerator(void* iso, int _tabSize, int _hashSize); ISOSPEC_C_FN_HEADERS(IsoOrderedGenerator) void* setupIsoStrochasticGenerator(void* iso, size_t no_molecules, double precision, double beta_bias); ISOSPEC_C_FN_HEADERS(IsoStochasticGenerator) void* setupThresholdFixedEnvelope(void* iso, double threshold, bool absolute, bool get_confs); void* setupTotalProbFixedEnvelope(void* iso, double taget_coverage, bool optimize, bool get_confs); void freeReleasedArray(void* array); void* setupFixedEnvelope(double* masses, double* probs, size_t size, bool mass_sorted, bool prob_sorted, double total_prob); void deleteFixedEnvelope(void* tabulator, bool releaseEverything); const double* massesFixedEnvelope(void* tabulator); const double* probsFixedEnvelope(void* tabulator); const int* confsFixedEnvelope(void* tabulator); int confs_noFixedEnvelope(void* tabulator); double wassersteinDistance(void* tabulator1, void* tabulator2); double orientedWassersteinDistance(void* tabulator1, void* tabulator2); void* addEnvelopes(void* tabulator1, void* tabulator2); void* convolveEnvelopes(void* tabulator1, void* tabulator2); double getTotalProbOfEnvelope(void* envelope); void scaleEnvelope(void* envelope, double factor); void normalizeEnvelope(void* envelope); void* binnedEnvelope(void* envelope, double width, double middle); void* linearCombination(void* const * const envelopes, const double* intensities, size_t count); void sortEnvelopeByMass(void* envelope); void sortEnvelopeByProb(void* envelope); void parse_fasta_c(const char* fasta, int atomCounts[6]); #ifdef __cplusplus } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/dirtyAllocator.h
.h
1,409
59
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include <vector> #include <cstring> namespace IsoSpec { class DirtyAllocator { private: void* currentTab; void* currentConf; void* endOfTablePtr; const int tabSize; int cellSize; std::vector<void*> prevTabs; public: explicit DirtyAllocator(const int dim, const int tabSize = 10000); ~DirtyAllocator(); DirtyAllocator(const DirtyAllocator& other) = delete; DirtyAllocator& operator=(const DirtyAllocator& other) = delete; void shiftTables(); inline void* newConf() { if (currentConf >= endOfTablePtr) { shiftTables(); } void* ret = currentConf; currentConf = reinterpret_cast<char*>(currentConf) + cellSize; return ret; } }; } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/dirtyAllocator.cpp
.cpp
1,555
55
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include <stdlib.h> #include "dirtyAllocator.h" namespace IsoSpec { DirtyAllocator::DirtyAllocator( const int dim, const int tabSize_ ): tabSize(tabSize_) { cellSize = sizeof(double) + sizeof(int) * dim; // Fix memory alignment problems for SPARC if(cellSize % sizeof(double) != 0) cellSize += sizeof(double) - cellSize % sizeof(double); currentTab = malloc( cellSize * tabSize ); currentConf = currentTab; endOfTablePtr = reinterpret_cast<char*>(currentTab) + cellSize*tabSize; } DirtyAllocator::~DirtyAllocator() { for(unsigned int i = 0; i < prevTabs.size(); ++i) free(prevTabs[i]); free(currentTab); } void DirtyAllocator::shiftTables() { prevTabs.push_back(currentTab); currentTab = malloc( cellSize * tabSize ); currentConf = currentTab; endOfTablePtr = reinterpret_cast<char*>(currentTab) + cellSize*tabSize; } } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/allocator.cpp
.cpp
1,217
51
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include "allocator.h" namespace IsoSpec { template <typename T> Allocator<T>::Allocator(const int dim_, const int tabSize_): currentId(-1), dim(dim_), tabSize(tabSize_) { currentTab = new T[dim * tabSize]; } template <typename T> Allocator<T>::~Allocator() { for(unsigned int i = 0; i < prevTabs.size(); ++i) { delete [] prevTabs[i]; } delete [] currentTab; } template <typename T> void Allocator<T>::shiftTables() { prevTabs.push_back(currentTab); currentTab = new T[dim * tabSize]; currentId = 0; } template class Allocator<int>; } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/platform.h
.h
4,255
127
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #if !defined(ISOSPEC_BUILDING_R) #define ISOSPEC_BUILDING_R false #endif #if !defined(ISOSPEC_BUILDING_CPP) #define ISOSPEC_BUILDING_CPP true #endif #if !defined(ISOSPEC_BUILDING_PYTHON) #define ISOSPEC_BUILDING_PYTHON false #endif #if !defined(ISOSPEC_BUILDING_OPENMS) #define ISOSPEC_BUILDING_OPENMS true #endif #if defined(__unix__) || defined(__unix) || \ (defined(__APPLE__) && defined(__MACH__)) #define ISOSPEC_TEST_WE_ARE_ON_UNIX_YAY true #define ISOSPEC_TEST_WE_ARE_ON_WINDOWS false /* CYGWIN doesn't really count as Windows for our purposes, we'll be using UNIX API anyway */ #define ISOSPEC_TEST_GOT_SYSTEM_MMAN true #define ISOSPEC_TEST_GOT_MMAN true #elif defined(__MINGW32__) || defined(_WIN32) #define ISOSPEC_TEST_WE_ARE_ON_UNIX_YAY false #define ISOSPEC_TEST_WE_ARE_ON_WINDOWS true #define ISOSPEC_TEST_GOT_SYSTEM_MMAN false #define ISOSPEC_TEST_GOT_MMAN true #else #define ISOSPEC_TEST_WE_ARE_ON_UNIX_YAY false /* Well, probably... */ #define ISOSPEC_TEST_WE_ARE_ON_WINDOWS false #define ISOSPEC_TEST_GOT_SYSTEM_MMAN false #define ISOSPEC_TEST_GOT_MMAN false #endif #if !defined(ISOSPEC_USE_PTHREADS) #define ISOSPEC_USE_PTHREADS false // TODO(who knows?): possibly put a macro here to detect whether we #endif // can/should use pthreads - or rip them out altogether. // Investigate whether the performance advantage of pthreads on // some platforms (*cough* CYGWIN *cough*) is still large // enough to justify keeping both implementations around #if !defined(ISOSPEC_WE_ARE_ON_UNIX_YAY) #define ISOSPEC_WE_ARE_ON_UNIX_YAY ISOSPEC_TEST_WE_ARE_ON_UNIX_YAY #endif #if !defined(ISOSPEC_WE_ARE_ON_WINDOWS) #define ISOSPEC_WE_ARE_ON_WINDOWS ISOSPEC_TEST_WE_ARE_ON_WINDOWS #endif #if !defined(ISOSPEC_GOT_SYSTEM_MMAN) #define ISOSPEC_GOT_SYSTEM_MMAN ISOSPEC_TEST_GOT_SYSTEM_MMAN #endif #if !defined(ISOSPEC_GOT_MMAN) #define ISOSPEC_GOT_MMAN ISOSPEC_TEST_GOT_MMAN #endif // Note: __GNUC__ is defined by clang and gcc #ifdef __GNUC__ #define ISOSPEC_IMPOSSIBLE(condition) if(condition) __builtin_unreachable(); #define ISOSPEC_LIKELY(condition) __builtin_expect(static_cast<bool>(condition), 1) #define ISOSPEC_UNLIKELY(condition) __builtin_expect(static_cast<bool>(condition), 0) // For aggressive inlining #define ISOSPEC_FORCE_INLINE __attribute__ ((always_inline)) inline #elif defined _MSC_VER #define ISOSPEC_IMPOSSIBLE(condition) __assume(!(condition)); #define ISOSPEC_LIKELY(condition) condition #define ISOSPEC_UNLIKELY(condition) condition #define ISOSPEC_FORCE_INLINE __forceinline inline #else #define ISOSPEC_IMPOSSIBLE(condition) #define ISOSPEC_LIKELY(condition) condition #define ISOSPEC_UNLIKELY(condition) condition #define ISOSPEC_FORCE_INLINE inline #endif #if ISOSPEC_DEBUG #undef ISOSPEC_IMPOSSIBLE #include <cassert> #define ISOSPEC_IMPOSSIBLE(condition) assert(!(condition)); #endif /* ISOSPEC_DEBUG */ #if ISOSPEC_GOT_MMAN #if ISOSPEC_GOT_SYSTEM_MMAN #include <sys/mman.h> #else #include "mman.h" #endif #else #include <cstdlib> /* malloc, free, rand */ #endif #if defined(OPENMS_DLLAPI) /* IsoSpec is being built as a part of OpenMS: use their visibility macros */ #define ISOSPEC_EXPORT_SYMBOL OPENMS_DLLAPI #else /* it's a can of worms we don't yet want to open ourselves though... */ #define ISOSPEC_EXPORT_SYMBOL #endif #if !defined(__cpp_if_constexpr) #define constexpr_if if #define ISOSPEC_MAYBE_UNUSED #else #define constexpr_if if constexpr #define ISOSPEC_MAYBE_UNUSED [[maybe_unused]] #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/misc.h
.h
3,353
141
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include <iostream> #include <vector> #include <cstring> #include "isoMath.h" namespace IsoSpec { inline double combinedSum( const int* conf, const std::vector<double>** valuesContainer, int dimNumber ){ double res = 0.0; for(int i = 0; i < dimNumber; i++) res += (*(valuesContainer[i]))[conf[i]]; return res; } inline int* getConf(void* conf) { return reinterpret_cast<int*>( reinterpret_cast<char*>(conf) + sizeof(double) ); } inline double getLProb(void* conf) { double ret = *reinterpret_cast<double*>(conf); return ret; } inline double unnormalized_logProb(const int* conf, const double* logProbs, int dim) { double res = 0.0; for(int i = 0; i < dim; i++) res += minuslogFactorial(conf[i]) + conf[i] * logProbs[i]; return res; } inline double calc_mass(const int* conf, const double* masses, int dim) { double res = 0.0; for(int i = 0; i < dim; i++) { res += conf[i] * masses[i]; } return res; } template<typename T> void printArray(const T* array, int size, const char* prefix = "") { if (strlen(prefix) > 0) std::cout << prefix << " "; for (int i = 0; i < size; i++) std::cout << array[i] << " "; std::cout << std::endl; } template<typename T> void printVector(const std::vector<T>& vec) { printArray<T>(vec.data(), vec.size()); } template<typename T> void printOffsets(const T** array, int size, const T* offset, const char* prefix = "") { if (strlen(prefix) > 0) std::cout << prefix << " "; for (int i = 0; i < size; i++) std::cout << array[i] - offset << " "; std::cout << std::endl; } template<typename T> void printNestedArray(const T** array, const int* shape, int size) { for (int i = 0; i < size; i++) printArray(array[i], shape[i]); std::cout << std::endl; } //! Quickly select the n'th positional statistic, including the weights. void* quickselect(const void** array, int n, int start, int end); template <typename T> inline static T* array_copy(const T* A, int size) { T* ret = new T[size]; memcpy(ret, A, size*sizeof(T)); return ret; } template <typename T> static T* array_copy_nptr(const T* A, int size) { if(A == nullptr) return nullptr; return array_copy(A, size); } template<typename T> void dealloc_table(T* tbl, int dim) { for(int i = 0; i < dim; i++) { delete tbl[i]; } delete[] tbl; } template<typename T> void realloc_append(T** array, T what, size_t old_array_size) { T* newT = new T[old_array_size+1]; memcpy(newT, *array, old_array_size*sizeof(T)); newT[old_array_size] = what; delete[] *array; *array = newT; } } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/mman.h
.h
1,684
68
/* * NOLINT(legal/copyright) - the original authors did not slap a (C) notice in here, * for whatever reason, and I'm in no position to do that for them. * * sys/mman.h * mman-win32 * * This file has been included as a part of IsoSpec project, under a MIT licence. It * comes from the repository: * * https://github.com/witwall/mman-win32 * * which itself is a mirror of: * * https://code.google.com/archive/p/mman-win32/ */ #pragma once #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif /* All the headers include this file. */ #ifndef _MSC_VER #include <_mingw.h> #endif /* Determine offset type */ #include <stdint.h> #if defined(_WIN64) typedef int64_t OffsetType; #else typedef uint32_t OffsetType; #endif #include <sys/types.h> #define PROT_NONE 0 #define PROT_READ 1 #define PROT_WRITE 2 #define PROT_EXEC 4 #define MAP_FILE 0 #define MAP_SHARED 1 #define MAP_PRIVATE 2 #define MAP_TYPE 0xf #define MAP_FIXED 0x10 #define MAP_ANONYMOUS 0x20 #define MAP_ANON MAP_ANONYMOUS #define MAP_FAILED ((void *)-1) /* Flags for msync. */ #define MS_ASYNC 1 #define MS_SYNC 2 #define MS_INVALIDATE 4 void* mmap(void *addr, size_t len, int prot, int flags, int fildes, OffsetType off); int munmap(void *addr, size_t len); int _mprotect(void *addr, size_t len, int prot); int msync(void *addr, size_t len, int flags); int mlock(const void *addr, size_t len); int munlock(const void *addr, size_t len);
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/conf.h
.h
659
26
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once namespace IsoSpec { typedef int* Conf; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/misc.cpp
.cpp
1,866
69
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include "misc.h" #include <utility> #include "platform.h" #include "isoMath.h" namespace IsoSpec { void* quickselect(void ** array, int n, int start, int end) { if(start == end) return array[start]; while(true) { // Partition part int len = end - start; #if ISOSPEC_BUILDING_R int pivot = len/2 + start; #else size_t pivot = random_gen() % len + start; // Using Mersenne twister directly - we don't // need a very uniform distribution just for pivot // selection #endif void* pval = array[pivot]; double pprob = getLProb(pval); std::swap(array[pivot], array[end-1]); int loweridx = start; for(int i = start; i < end-1; i++) { if(getLProb(array[i]) < pprob) { std::swap(array[i], array[loweridx]); loweridx++; } } std::swap(array[end-1], array[loweridx]); // Selection part if(n == loweridx) return array[n]; if(n < loweridx) end = loweridx; else start = loweridx+1; }; } } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/fasta.cpp
.cpp
16,693
316
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include <cstring> #include "element_tables.h" #include "fasta.h" namespace IsoSpec{ // We will work with C H N O S Se tuples */ const int aa_isotope_numbers[6] = {2, 2, 2, 3, 4, 6}; const double aa_elem_masses[19] = { elem_table_mass[9], elem_table_mass[10], // Carbon elem_table_mass[0], elem_table_mass[1], // Hydrogen elem_table_mass[11], elem_table_mass[12], // Nitrogen elem_table_mass[13], elem_table_mass[14], elem_table_mass[15], // Oxygen elem_table_mass[29], elem_table_mass[30], elem_table_mass[31], elem_table_mass[32], // Sulfur elem_table_mass[85], elem_table_mass[86], elem_table_mass[87], elem_table_mass[88], elem_table_mass[89], elem_table_mass[90] // Selenium }; const double aa_elem_nominal_masses[19] = { elem_table_massNo[9], elem_table_massNo[10], // Carbon elem_table_massNo[0], elem_table_massNo[1], // Hydrogen elem_table_massNo[11], elem_table_massNo[12], // Nitrogen elem_table_massNo[13], elem_table_massNo[14], elem_table_massNo[15], // Oxygen elem_table_massNo[29], elem_table_massNo[30], elem_table_massNo[31], elem_table_massNo[32], // Sulfur elem_table_massNo[85], elem_table_massNo[86], elem_table_massNo[87], elem_table_massNo[88], elem_table_massNo[89], elem_table_massNo[90] // Selenium }; const double aa_elem_probabilities[19] = { elem_table_probability[9], elem_table_probability[10], // Carbon elem_table_probability[0], elem_table_probability[1], // Hydrogen elem_table_probability[11], elem_table_probability[12], // Nitrogen elem_table_probability[13], elem_table_probability[14], elem_table_probability[15], // Oxygen elem_table_probability[29], elem_table_probability[30], elem_table_probability[31], elem_table_probability[32], // Sulfur elem_table_probability[85], elem_table_probability[86], elem_table_probability[87], elem_table_probability[88], elem_table_probability[89], elem_table_probability[90] // Selenium }; const int aa_symbol_to_elem_counts[256*6] = { /* Code: 0 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 1 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 2 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 3 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 4 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 5 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 6 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 7 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 8 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 9 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 10 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 11 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 12 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 13 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 14 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 15 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 16 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 17 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 18 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 19 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 20 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 21 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 22 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 23 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 24 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 25 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 26 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 27 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 28 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 29 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 30 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 31 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 32 ASCII char: */ 0, 0, 0, 0, 0, 0, /* Code: 33 ASCII char: ! */ 0, 0, 0, 0, 0, 0, /* Code: 34 ASCII char: " */ 0, 0, 0, 0, 0, 0, /* Code: 35 ASCII char: # */ 0, 0, 0, 0, 0, 0, /* Code: 36 ASCII char: $ */ 0, 0, 0, 0, 0, 0, /* Code: 37 ASCII char: % */ 0, 0, 0, 0, 0, 0, /* Code: 38 ASCII char: & */ 0, 0, 0, 0, 0, 0, /* Code: 39 ASCII char: ' */ 0, 0, 0, 0, 0, 0, /* Code: 40 ASCII char: ( */ 0, 0, 0, 0, 0, 0, /* Code: 41 ASCII char: ) */ 0, 0, 0, 0, 0, 0, /* Code: 42 ASCII char: * */ 0, 0, 0, 0, 0, 0, /* Code: 43 ASCII char: + */ 0, 0, 0, 0, 0, 0, /* Code: 44 ASCII char: , */ 0, 0, 0, 0, 0, 0, /* Code: 45 ASCII char: - */ 0, 0, 0, 0, 0, 0, /* Code: 46 ASCII char: . */ 0, 0, 0, 0, 0, 0, /* Code: 47 ASCII char: / */ 0, 0, 0, 0, 0, 0, /* Code: 48 ASCII char: 0 */ 0, 0, 0, 0, 0, 0, /* Code: 49 ASCII char: 1 */ 0, 0, 0, 0, 0, 0, /* Code: 50 ASCII char: 2 */ 0, 0, 0, 0, 0, 0, /* Code: 51 ASCII char: 3 */ 0, 0, 0, 0, 0, 0, /* Code: 52 ASCII char: 4 */ 0, 0, 0, 0, 0, 0, /* Code: 53 ASCII char: 5 */ 0, 0, 0, 0, 0, 0, /* Code: 54 ASCII char: 6 */ 0, 0, 0, 0, 0, 0, /* Code: 55 ASCII char: 7 */ 0, 0, 0, 0, 0, 0, /* Code: 56 ASCII char: 8 */ 0, 0, 0, 0, 0, 0, /* Code: 57 ASCII char: 9 */ 0, 0, 0, 0, 0, 0, /* Code: 58 ASCII char: : */ 0, 0, 0, 0, 0, 0, /* Code: 59 ASCII char: ; */ 0, 0, 0, 0, 0, 0, /* Code: 60 ASCII char: < */ 0, 0, 0, 0, 0, 0, /* Code: 61 ASCII char: = */ 0, 0, 0, 0, 0, 0, /* Code: 62 ASCII char: > */ 0, 0, 0, 0, 0, 0, /* Code: 63 ASCII char: ? */ 0, 0, 0, 0, 0, 0, /* Code: 64 ASCII char: @ */ 0, 0, 0, 0, 0, 0, /* Code: 65 ASCII char: A */ 3, 5, 1, 1, 0, 0, /* Code: 66 ASCII char: B */ 0, 0, 0, 0, 0, 0, /* Code: 67 ASCII char: C */ 3, 5, 1, 1, 1, 0, /* Code: 68 ASCII char: D */ 4, 5, 1, 3, 0, 0, /* Code: 69 ASCII char: E */ 5, 7, 1, 3, 0, 0, /* Code: 70 ASCII char: F */ 9, 9, 1, 1, 0, 0, /* Code: 71 ASCII char: G */ 2, 3, 1, 1, 0, 0, /* Code: 72 ASCII char: H */ 6, 7, 3, 1, 0, 0, /* Code: 73 ASCII char: I */ 6, 11, 1, 1, 0, 0, /* Code: 74 ASCII char: J */ 0, 0, 0, 0, 0, 0, /* Code: 75 ASCII char: K */ 6, 12, 2, 1, 0, 0, /* Code: 76 ASCII char: L */ 6, 11, 1, 1, 0, 0, /* Code: 77 ASCII char: M */ 5, 9, 1, 1, 1, 0, /* Code: 78 ASCII char: N */ 4, 6, 2, 2, 0, 0, /* Code: 79 ASCII char: O */ 12, 21, 3, 3, 0, 0, /* Code: 80 ASCII char: P */ 5, 7, 1, 1, 0, 0, /* Code: 81 ASCII char: Q */ 5, 8, 2, 2, 0, 0, /* Code: 82 ASCII char: R */ 6, 12, 4, 1, 0, 0, /* Code: 83 ASCII char: S */ 3, 5, 1, 2, 0, 0, /* Code: 84 ASCII char: T */ 4, 7, 1, 2, 0, 0, /* Code: 85 ASCII char: U */ 3, 5, 1, 1, 0, 1, /* Code: 86 ASCII char: V */ 5, 9, 1, 1, 0, 0, /* Code: 87 ASCII char: W */ 11, 10, 2, 1, 0, 0, /* Code: 88 ASCII char: X */ 0, 0, 0, 0, 0, 0, /* Code: 89 ASCII char: Y */ 9, 9, 1, 2, 0, 0, /* Code: 90 ASCII char: Z */ 0, 0, 0, 0, 0, 0, /* Code: 91 ASCII char: [ */ 0, 0, 0, 0, 0, 0, /* Code: 92 ASCII char: \ */ 0, 0, 0, 0, 0, 0, /* Code: 93 ASCII char: ] */ 0, 0, 0, 0, 0, 0, /* Code: 94 ASCII char: ^ */ 0, 0, 0, 0, 0, 0, /* Code: 95 ASCII char: _ */ 0, 0, 0, 0, 0, 0, /* Code: 96 ASCII char: ` */ 0, 0, 0, 0, 0, 0, /* Code: 97 ASCII char: a */ 3, 5, 1, 1, 0, 0, /* Code: 98 ASCII char: b */ 0, 0, 0, 0, 0, 0, /* Code: 99 ASCII char: c */ 3, 5, 1, 1, 1, 0, /* Code: 100 ASCII char: d */ 4, 5, 1, 3, 0, 0, /* Code: 101 ASCII char: e */ 5, 7, 1, 3, 0, 0, /* Code: 102 ASCII char: f */ 9, 9, 1, 1, 0, 0, /* Code: 103 ASCII char: g */ 2, 3, 1, 1, 0, 0, /* Code: 104 ASCII char: h */ 6, 7, 3, 1, 0, 0, /* Code: 105 ASCII char: i */ 6, 11, 1, 1, 0, 0, /* Code: 106 ASCII char: j */ 0, 0, 0, 0, 0, 0, /* Code: 107 ASCII char: k */ 6, 12, 2, 1, 0, 0, /* Code: 108 ASCII char: l */ 6, 11, 1, 1, 0, 0, /* Code: 109 ASCII char: m */ 5, 9, 1, 1, 1, 0, /* Code: 110 ASCII char: n */ 4, 6, 2, 2, 0, 0, /* Code: 111 ASCII char: o */ 12, 21, 3, 3, 0, 0, /* Code: 112 ASCII char: p */ 5, 7, 1, 1, 0, 0, /* Code: 113 ASCII char: q */ 5, 8, 2, 2, 0, 0, /* Code: 114 ASCII char: r */ 6, 12, 4, 1, 0, 0, /* Code: 115 ASCII char: s */ 3, 5, 1, 2, 0, 0, /* Code: 116 ASCII char: t */ 4, 7, 1, 2, 0, 0, /* Code: 117 ASCII char: u */ 3, 5, 1, 1, 0, 1, /* Code: 118 ASCII char: v */ 5, 9, 1, 1, 0, 0, /* Code: 119 ASCII char: w */ 11, 10, 2, 1, 0, 0, /* Code: 120 ASCII char: x */ 0, 0, 0, 0, 0, 0, /* Code: 121 ASCII char: y */ 9, 9, 1, 2, 0, 0, /* Code: 122 ASCII char: z */ 0, 0, 0, 0, 0, 0, /* Code: 123 ASCII char: { */ 0, 0, 0, 0, 0, 0, /* Code: 124 ASCII char: | */ 0, 0, 0, 0, 0, 0, /* Code: 125 ASCII char: } */ 0, 0, 0, 0, 0, 0, /* Code: 126 ASCII char: ~ */ 0, 0, 0, 0, 0, 0, /* Code: 127 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 128 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 129 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 130 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 131 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 132 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 133 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 134 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 135 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 136 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 137 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 138 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 139 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 140 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 141 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 142 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 143 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 144 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 145 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 146 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 147 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 148 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 149 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 150 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 151 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 152 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 153 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 154 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 155 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 156 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 157 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 158 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 159 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 160 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 161 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 162 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 163 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 164 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 165 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 166 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 167 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 168 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 169 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 170 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 171 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 172 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 173 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 174 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 175 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 176 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 177 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 178 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 179 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 180 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 181 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 182 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 183 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 184 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 185 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 186 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 187 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 188 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 189 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 190 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 191 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 192 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 193 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 194 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 195 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 196 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 197 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 198 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 199 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 200 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 201 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 202 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 203 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 204 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 205 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 206 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 207 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 208 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 209 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 210 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 211 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 212 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 213 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 214 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 215 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 216 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 217 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 218 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 219 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 220 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 221 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 222 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 223 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 224 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 225 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 226 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 227 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 228 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 229 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 230 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 231 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 232 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 233 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 234 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 235 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 236 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 237 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 238 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 239 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 240 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 241 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 242 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 243 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 244 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 245 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 246 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 247 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 248 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 249 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 250 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 251 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 252 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 253 unprintable */ 0, 0, 0, 0, 0, 0, /* Code: 254 unprintable */ 0, 0, 0, 0, 0, 0 }; } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/summator.h
.h
2,319
119
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include <cmath> #include <vector> #include <utility> namespace IsoSpec { class SSummator { // Shewchuk algorithm std::vector<double> partials; int maxpart; public: inline SSummator() { maxpart = 0; } inline SSummator(const SSummator& other) : partials(other.partials), maxpart(other.maxpart) {} inline void add(double x) { unsigned int i = 0; for(int pidx = 0; pidx < maxpart; pidx++) { double y = partials[pidx]; if(std::abs(x) < std::abs(y)) std::swap(x, y); double hi = x+y; double lo = y-(hi-x); if(lo != 0.0) { partials[i] = lo; i += 1; } x = hi; } while(partials.size() <= i) partials.push_back(0.0); partials[i] = x; maxpart = i+1; } inline double get() { double ret = 0.0; for(int i = 0; i < maxpart; i++) ret += partials[i]; return ret; } }; class Summator{ // Kahan algorithm double sum; double c; public: inline Summator() { sum = 0.0; c = 0.0;} inline void add(double what) { double y = what - c; double t = sum + y; c = (t - sum) - y; sum = t; } inline double get() const { return sum; } }; class TSummator { // Trivial algorithm, for testing only double sum; public: inline TSummator() { sum = 0.0; } inline void add(double what) { sum += what; } inline double get() const { return sum; } }; } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/isoSpec++.cpp
.cpp
27,063
943
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include "isoSpec++.h" #include <cmath> #include <algorithm> #include <vector> #include <cstdlib> #include <cstring> #include <unordered_map> #include <queue> #include <utility> #include <iostream> #include <iomanip> #include <stdexcept> #include <string> #include <limits> #include <memory> #include <cassert> #include <cctype> #include "platform.h" #include "conf.h" #include "dirtyAllocator.h" #include "operators.h" #include "summator.h" #include "marginalTrek++.h" #include "misc.h" #include "element_tables.h" #include "fasta.h" namespace IsoSpec { Iso::Iso() : disowned(false), dimNumber(0), isotopeNumbers(new int[0]), atomCounts(new int[0]), confSize(0), allDim(0), marginals(new Marginal*[0]) {} Iso::Iso( int _dimNumber, const int* _isotopeNumbers, const int* _atomCounts, const double* const * _isotopeMasses, const double* const * _isotopeProbabilities ) : disowned(false), dimNumber(_dimNumber), isotopeNumbers(array_copy<int>(_isotopeNumbers, _dimNumber)), atomCounts(array_copy<int>(_atomCounts, _dimNumber)), confSize(_dimNumber * sizeof(int)), allDim(0), marginals(nullptr) { for(int ii = 0; ii < dimNumber; ++ii) allDim += isotopeNumbers[ii]; std::unique_ptr<double[]> masses(new double[allDim]); std::unique_ptr<double[]> probs(new double[allDim]); size_t idx = 0; for(int ii = 0; ii < dimNumber; ++ii) for(int jj = 0; jj < isotopeNumbers[ii]; ++jj) { masses[idx] = _isotopeMasses[ii][jj]; probs[idx] = _isotopeProbabilities[ii][jj]; ++idx; } allDim = 0; // setupMarginals will recalculate it, assuming it's set to 0 try{ setupMarginals(masses.get(), probs.get()); } catch(...) { delete[] isotopeNumbers; delete[] atomCounts; // Since we're throwing in a constructor, the destructor won't run, and we don't need to NULL these. // However, this is not the fast code path and we can afford two unneeded instructions to keep // some static analysis tools happy. isotopeNumbers = nullptr; atomCounts = nullptr; throw; } } Iso::Iso( int _dimNumber, const int* _isotopeNumbers, const int* _atomCounts, const double* _isotopeMasses, const double* _isotopeProbabilities ) : disowned(false), dimNumber(_dimNumber), isotopeNumbers(array_copy<int>(_isotopeNumbers, _dimNumber)), atomCounts(array_copy<int>(_atomCounts, _dimNumber)), confSize(_dimNumber * sizeof(int)), allDim(0), marginals(nullptr) { try{ setupMarginals(_isotopeMasses, _isotopeProbabilities); } catch(...) { delete[] isotopeNumbers; delete[] atomCounts; // Since we're throwing in a constructor, the destructor won't run, and we don't need to NULL these. // However, this is not the fast code path and we can afford two unneeded instructions to keep // some static analysis tools happy. isotopeNumbers = nullptr; atomCounts = nullptr; throw; } } Iso::Iso(Iso&& other) noexcept : disowned(other.disowned), dimNumber(other.dimNumber), isotopeNumbers(other.isotopeNumbers), atomCounts(other.atomCounts), confSize(other.confSize), allDim(other.allDim), marginals(other.marginals) { other.disowned = true; } Iso::Iso(const Iso& other, bool fullcopy) : disowned(!fullcopy), dimNumber(other.dimNumber), isotopeNumbers(fullcopy ? array_copy<int>(other.isotopeNumbers, dimNumber) : other.isotopeNumbers), atomCounts(fullcopy ? array_copy<int>(other.atomCounts, dimNumber) : other.atomCounts), confSize(other.confSize), allDim(other.allDim), marginals(fullcopy ? new Marginal*[dimNumber] : other.marginals) { if(fullcopy) { for(int ii = 0; ii < dimNumber; ii++) marginals[ii] = new Marginal(*other.marginals[ii]); } } Iso Iso::FromFASTA(const char* fasta, bool use_nominal_masses, bool add_water) { int atomCounts[6]; parse_fasta(fasta, atomCounts); if(add_water) { atomCounts[1] += 2; atomCounts[3] += 1; } const int dimNr = atomCounts[5] > 0 ? 6 : 5; return Iso(dimNr, aa_isotope_numbers, atomCounts, use_nominal_masses ? aa_elem_nominal_masses : aa_elem_masses, aa_elem_probabilities); } inline void Iso::setupMarginals(const double* _isotopeMasses, const double* _isotopeProbabilities) { if (marginals == nullptr) { int ii = 0; marginals = new Marginal*[dimNumber]; try { while(ii < dimNumber) { marginals[ii] = new Marginal( &_isotopeMasses[allDim], &_isotopeProbabilities[allDim], isotopeNumbers[ii], atomCounts[ii] ); allDim += isotopeNumbers[ii]; ii++; } } catch(...) { ii--; while(ii >= 0) { delete marginals[ii]; ii--; } delete[] marginals; marginals = nullptr; throw; } } } Iso::~Iso() { if(!disowned) { if (marginals != nullptr) dealloc_table(marginals, dimNumber); delete[] isotopeNumbers; delete[] atomCounts; } } bool Iso::doMarginalsNeedSorting() const { int nontrivial_marginals = 0; for(int ii = 0; ii < dimNumber; ii++) { if(marginals[ii]->get_isotopeNo() > 1) nontrivial_marginals++; if(nontrivial_marginals > 1) return true; } return false; } double Iso::getLightestPeakMass() const { double mass = 0.0; for (int ii = 0; ii < dimNumber; ii++) mass += marginals[ii]->getLightestConfMass(); return mass; } double Iso::getHeaviestPeakMass() const { double mass = 0.0; for (int ii = 0; ii < dimNumber; ii++) mass += marginals[ii]->getHeaviestConfMass(); return mass; } double Iso::getMonoisotopicPeakMass() const { double mass = 0.0; for (int ii = 0; ii < dimNumber; ii++) mass += marginals[ii]->getMonoisotopicConfMass(); return mass; } double Iso::getUnlikeliestPeakLProb() const { double lprob = 0.0; for (int ii = 0; ii < dimNumber; ii++) lprob += marginals[ii]->getSmallestLProb(); return lprob; } double Iso::getModeMass() const { double mass = 0.0; for (int ii = 0; ii < dimNumber; ii++) mass += marginals[ii]->getModeMass(); return mass; } double Iso::getModeLProb() const { double ret = 0.0; for (int ii = 0; ii < dimNumber; ii++) ret += marginals[ii]->getModeLProb(); return ret; } double Iso::getTheoreticalAverageMass() const { double mass = 0.0; for (int ii = 0; ii < dimNumber; ii++) mass += marginals[ii]->getTheoreticalAverageMass(); return mass; } double Iso::variance() const { double ret = 0.0; for(int ii = 0; ii < dimNumber; ii++) ret += marginals[ii]->variance(); return ret; } Iso::Iso(const char* formula, bool use_nominal_masses) : disowned(false), allDim(0), marginals(nullptr) { std::vector<double> isotope_masses; std::vector<double> isotope_probabilities; dimNumber = parse_formula(formula, isotope_masses, isotope_probabilities, &isotopeNumbers, &atomCounts, &confSize, use_nominal_masses); setupMarginals(isotope_masses.data(), isotope_probabilities.data()); } void Iso::addElement(int atomCount, int noIsotopes, const double* isotopeMasses, const double* isotopeProbabilities) { Marginal* m = new Marginal(isotopeMasses, isotopeProbabilities, noIsotopes, atomCount); realloc_append<int>(&isotopeNumbers, noIsotopes, dimNumber); realloc_append<int>(&atomCounts, atomCount, dimNumber); realloc_append<Marginal*>(&marginals, m, dimNumber); dimNumber++; confSize += sizeof(int); allDim += noIsotopes; } void Iso::saveMarginalLogSizeEstimates(double* priorities, double target_total_prob) const { /* * We shall now use Gaussian approximations of the marginal multinomial distributions to estimate * how many configurations we shall need to visit from each marginal. This should be approximately * proportional to the volume of the optimal P-ellipsoid of the marginal, which, in turn is defined * by the quantile function of the chi-square distribution plus some modifications. * * We're dropping the constant factor and the (monotonic) exp() transform - these will be used as keys * for sorting, so only the ordering is important. */ double K = allDim - dimNumber; double log_R2 = log(InverseChiSquareCDF2(K, target_total_prob)); for(int ii = 0; ii < dimNumber; ii++) priorities[ii] = marginals[ii]->getLogSizeEstimate(log_R2); } unsigned int parse_formula(const char* formula, std::vector<double>& isotope_masses, std::vector<double>& isotope_probabilities, int** isotopeNumbers, int** atomCounts, unsigned int* confSize, bool use_nominal_masses) { // This function is NOT guaranteed to be secure against malicious input. It should be used only for debugging. size_t slen = strlen(formula); // Yes, it would be more elegant to use std::string here, but it's the only promiment place where it would be used in IsoSpec, and avoiding it here // means we can run the whole thing through Clang's memory sanitizer without the need for instrumented libc++/libstdc++. That's worth messing with char pointers a // little bit. std::vector<std::pair<const char*, size_t> > elements; std::vector<int> numbers; if(slen == 0) throw std::invalid_argument("Invalid formula: can't be empty"); if(!isdigit(formula[slen-1])) throw std::invalid_argument("Invalid formula: every element must be followed by a number - write H2O1 and not H2O for water"); for(size_t ii = 0; ii < slen; ii++) if(!isdigit(formula[ii]) && !isalpha(formula[ii])) throw std::invalid_argument("Invalid formula: contains invalid (non-digit, non-alpha) character"); size_t position = 0; while(position < slen) { size_t elem_end = position; while(isalpha(formula[elem_end])) elem_end++; size_t digit_end = elem_end; while(isdigit(formula[digit_end])) digit_end++; elements.emplace_back(&formula[position], elem_end-position); numbers.push_back(std::stoi(&formula[elem_end])); position = digit_end; } std::vector<int> element_indexes; for (unsigned int i = 0; i < elements.size(); i++) { int idx = -1; for(int j = 0; j < ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES; j++) { if ((strlen(elem_table_symbol[j]) == elements[i].second) && (strncmp(elements[i].first, elem_table_symbol[j], elements[i].second) == 0)) { idx = j; break; } } if(idx < 0) throw std::invalid_argument("Invalid formula"); element_indexes.push_back(idx); } std::vector<int> _isotope_numbers; const double* masses = use_nominal_masses ? elem_table_massNo : elem_table_mass; for(std::vector<int>::iterator it = element_indexes.begin(); it != element_indexes.end(); ++it) { int num = 0; int at_idx = *it; int elem_ID = elem_table_ID[at_idx]; while(at_idx < ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES && elem_table_ID[at_idx] == elem_ID) { isotope_masses.push_back(masses[at_idx]); isotope_probabilities.push_back(elem_table_probability[at_idx]); at_idx++; num++; } _isotope_numbers.push_back(num); } const unsigned int dimNumber = elements.size(); *isotopeNumbers = array_copy<int>(_isotope_numbers.data(), dimNumber); *atomCounts = array_copy<int>(numbers.data(), dimNumber); *confSize = dimNumber * sizeof(int); return dimNumber; } /* * ---------------------------------------------------------------------------------------------------------- */ IsoGenerator::IsoGenerator(Iso&& iso, bool alloc_partials) : Iso(std::move(iso)), mode_lprob(getModeLProb()), partialLProbs(alloc_partials ? new double[dimNumber+1] : nullptr), partialMasses(alloc_partials ? new double[dimNumber+1] : nullptr), partialProbs(alloc_partials ? new double[dimNumber+1] : nullptr) { for(int ii = 0; ii < dimNumber; ++ii) marginals[ii]->ensureModeConf(); if(alloc_partials) { partialLProbs[dimNumber] = 0.0; partialMasses[dimNumber] = 0.0; partialProbs[dimNumber] = 1.0; } } IsoGenerator::~IsoGenerator() { if(partialLProbs != nullptr) delete[] partialLProbs; if(partialMasses != nullptr) delete[] partialMasses; if(partialProbs != nullptr) delete[] partialProbs; } /* * ---------------------------------------------------------------------------------------------------------- */ static const double minsqrt = -1.3407796239501852e+154; // == constexpr(-sqrt(std::numeric_limits<double>::max())); IsoThresholdGenerator::IsoThresholdGenerator(Iso&& iso, double _threshold, bool _absolute, int tabSize, int hashSize, bool reorder_marginals) : IsoGenerator(std::move(iso)), Lcutoff(_threshold <= 0.0 ? minsqrt : (_absolute ? log(_threshold) : log(_threshold) + mode_lprob)) { counter = new int[dimNumber]; maxConfsLPSum = new double[dimNumber-1]; marginalResultsUnsorted = new PrecalculatedMarginal*[dimNumber]; empty = false; const bool marginalsNeedSorting = doMarginalsNeedSorting(); for(int ii = 0; ii < dimNumber; ii++) { counter[ii] = 0; marginalResultsUnsorted[ii] = new PrecalculatedMarginal(std::move(*(marginals[ii])), Lcutoff - mode_lprob + marginals[ii]->fastGetModeLProb(), marginalsNeedSorting, tabSize, hashSize); if(!marginalResultsUnsorted[ii]->inRange(0)) empty = true; } if(reorder_marginals && dimNumber > 1) { OrderMarginalsBySizeDecresing<PrecalculatedMarginal> comparator(marginalResultsUnsorted); int* tmpMarginalOrder = new int[dimNumber]; for(int ii = 0; ii < dimNumber; ii++) tmpMarginalOrder[ii] = ii; std::sort(tmpMarginalOrder, tmpMarginalOrder + dimNumber, comparator); marginalResults = new PrecalculatedMarginal*[dimNumber]; for(int ii = 0; ii < dimNumber; ii++) marginalResults[ii] = marginalResultsUnsorted[tmpMarginalOrder[ii]]; marginalOrder = new int[dimNumber]; for(int ii = 0; ii < dimNumber; ii++) marginalOrder[tmpMarginalOrder[ii]] = ii; delete[] tmpMarginalOrder; } else { marginalResults = marginalResultsUnsorted; marginalOrder = nullptr; } lProbs_ptr_start = marginalResults[0]->get_lProbs_ptr(); if(dimNumber > 1) maxConfsLPSum[0] = marginalResults[0]->fastGetModeLProb(); for(int ii = 1; ii < dimNumber-1; ii++) maxConfsLPSum[ii] = maxConfsLPSum[ii-1] + marginalResults[ii]->fastGetModeLProb(); lProbs_ptr = lProbs_ptr_start; partialLProbs_second = partialLProbs; partialLProbs_second++; if(!empty) { recalc(dimNumber-1); counter[0]--; lProbs_ptr--; } else { terminate_search(); lcfmsv = std::numeric_limits<double>::infinity(); } } void IsoThresholdGenerator::terminate_search() { for(int ii = 0; ii < dimNumber; ii++) { counter[ii] = marginalResults[ii]->get_no_confs()-1; partialLProbs[ii] = -std::numeric_limits<double>::infinity(); } partialLProbs[dimNumber] = -std::numeric_limits<double>::infinity(); lProbs_ptr = lProbs_ptr_start + marginalResults[0]->get_no_confs()-1; } size_t IsoThresholdGenerator::count_confs() { if(empty) return 0; if(dimNumber == 1) return marginalResults[0]->get_no_confs(); const double* lProbs_ptr_l = marginalResults[0]->get_lProbs_ptr() + marginalResults[0]->get_no_confs(); std::unique_ptr<const double* []> lProbs_restarts(new const double*[dimNumber]); for(int ii = 0; ii < dimNumber; ii++) lProbs_restarts[ii] = lProbs_ptr_l; size_t count = 0; while(*lProbs_ptr_l < lcfmsv) lProbs_ptr_l--; while(true) { count += lProbs_ptr_l - lProbs_ptr_start + 1; int idx = 0; int * cntr_ptr = counter; while(idx < dimNumber - 1) { *cntr_ptr = 0; idx++; cntr_ptr++; (*cntr_ptr)++; partialLProbs[idx] = partialLProbs[idx+1] + marginalResults[idx]->get_lProb(counter[idx]); if(partialLProbs[idx] + maxConfsLPSum[idx-1] >= Lcutoff) { short_recalc(idx-1); lProbs_ptr_l = lProbs_restarts[idx]; while(*lProbs_ptr_l < lcfmsv) lProbs_ptr_l--; for(idx--; idx > 0; idx--) lProbs_restarts[idx] = lProbs_ptr_l; break; } } if(idx == dimNumber - 1) { reset(); return count; } } } void IsoThresholdGenerator::reset() { if(empty) { terminate_search(); return; } partialLProbs[dimNumber] = 0.0; memset(counter, 0, sizeof(int)*dimNumber); recalc(dimNumber-1); counter[0]--; lProbs_ptr = lProbs_ptr_start - 1; } IsoThresholdGenerator::~IsoThresholdGenerator() { delete[] counter; delete[] maxConfsLPSum; if (marginalResultsUnsorted != marginalResults) delete[] marginalResultsUnsorted; dealloc_table(marginalResults, dimNumber); if(marginalOrder != nullptr) delete[] marginalOrder; } /* * ------------------------------------------------------------------------------------------------------------------------ */ IsoLayeredGenerator::IsoLayeredGenerator(Iso&& iso, int tabSize, int hashSize, bool reorder_marginals, double t_prob_hint) : IsoGenerator(std::move(iso)) { counter = new int[dimNumber]; maxConfsLPSum = new double[dimNumber-1]; currentLThreshold = nextafter(mode_lprob, -std::numeric_limits<double>::infinity()); lastLThreshold = (std::numeric_limits<double>::min)(); marginalResultsUnsorted = new LayeredMarginal*[dimNumber]; resetPositions = new const double*[dimNumber]; marginalsNeedSorting = doMarginalsNeedSorting(); memset(counter, 0, sizeof(int)*dimNumber); for(int ii = 0; ii < dimNumber; ii++) marginalResultsUnsorted[ii] = new LayeredMarginal(std::move(*(marginals[ii])), tabSize, hashSize); if(reorder_marginals && dimNumber > 1) { double* marginal_priorities = new double[dimNumber]; saveMarginalLogSizeEstimates(marginal_priorities, t_prob_hint); int* tmpMarginalOrder = new int[dimNumber]; for(int ii = 0; ii < dimNumber; ii++) tmpMarginalOrder[ii] = ii; TableOrder<double> TO(marginal_priorities); std::sort(tmpMarginalOrder, tmpMarginalOrder + dimNumber, TO); marginalResults = new LayeredMarginal*[dimNumber]; for(int ii = 0; ii < dimNumber; ii++) marginalResults[ii] = marginalResultsUnsorted[tmpMarginalOrder[ii]]; marginalOrder = new int[dimNumber]; for(int ii = 0; ii < dimNumber; ii++) marginalOrder[tmpMarginalOrder[ii]] = ii; delete[] tmpMarginalOrder; delete[] marginal_priorities; } else { marginalResults = marginalResultsUnsorted; marginalOrder = nullptr; } lProbs_ptr_start = marginalResults[0]->get_lProbs_ptr(); if(dimNumber > 1) maxConfsLPSum[0] = marginalResults[0]->fastGetModeLProb(); for(int ii = 1; ii < dimNumber-1; ii++) maxConfsLPSum[ii] = maxConfsLPSum[ii-1] + marginalResults[ii]->fastGetModeLProb(); lProbs_ptr = lProbs_ptr_start; partialLProbs_second = partialLProbs; partialLProbs_second++; counter[0]--; lProbs_ptr--; lastLThreshold = 10.0; IsoLayeredGenerator::nextLayer(-0.00001); } bool IsoLayeredGenerator::nextLayer(double offset) { size_t first_mrg_size = marginalResults[0]->get_no_confs(); if(lastLThreshold < getUnlikeliestPeakLProb()) return false; lastLThreshold = currentLThreshold; currentLThreshold += offset; for(int ii = 0; ii < dimNumber; ii++) { marginalResults[ii]->extend(currentLThreshold - mode_lprob + marginalResults[ii]->fastGetModeLProb(), marginalsNeedSorting); counter[ii] = 0; } lProbs_ptr_start = marginalResults[0]->get_lProbs_ptr(); // vector relocation might have happened lProbs_ptr = lProbs_ptr_start + first_mrg_size - 1; for(int ii = 0; ii < dimNumber; ii++) resetPositions[ii] = lProbs_ptr; recalc(dimNumber-1); return true; } bool IsoLayeredGenerator::carry() { // If we reached this point, a carry is needed int idx = 0; int * cntr_ptr = counter; while(idx < dimNumber-1) { *cntr_ptr = 0; idx++; cntr_ptr++; (*cntr_ptr)++; partialLProbs[idx] = partialLProbs[idx+1] + marginalResults[idx]->get_lProb(counter[idx]); if(partialLProbs[idx] + maxConfsLPSum[idx-1] >= currentLThreshold) { partialMasses[idx] = partialMasses[idx+1] + marginalResults[idx]->get_mass(counter[idx]); partialProbs[idx] = partialProbs[idx+1] * marginalResults[idx]->get_prob(counter[idx]); recalc(idx-1); lProbs_ptr = resetPositions[idx]; while(*lProbs_ptr <= last_lcfmsv) lProbs_ptr--; for(int ii = 0; ii < idx; ii++) resetPositions[ii] = lProbs_ptr; return true; } } return false; } void IsoLayeredGenerator::terminate_search() { for(int ii = 0; ii < dimNumber; ii++) { counter[ii] = marginalResults[ii]->get_no_confs()-1; partialLProbs[ii] = -std::numeric_limits<double>::infinity(); } partialLProbs[dimNumber] = -std::numeric_limits<double>::infinity(); lProbs_ptr = lProbs_ptr_start + marginalResults[0]->get_no_confs()-1; } IsoLayeredGenerator::~IsoLayeredGenerator() { delete[] counter; delete[] maxConfsLPSum; delete[] resetPositions; if (marginalResultsUnsorted != marginalResults) delete[] marginalResultsUnsorted; dealloc_table(marginalResults, dimNumber); if(marginalOrder != nullptr) delete[] marginalOrder; } /* * ------------------------------------------------------------------------------------------------------------------------ */ IsoOrderedGenerator::IsoOrderedGenerator(Iso&& iso, int _tabSize, int _hashSize) : IsoGenerator(std::move(iso), false), allocator(dimNumber, _tabSize) { partialLProbs = &currentLProb; partialMasses = &currentMass; partialProbs = &currentProb; marginalResults = new MarginalTrek*[dimNumber]; for(int i = 0; i < dimNumber; i++) marginalResults[i] = new MarginalTrek(std::move(*(marginals[i])), _tabSize, _hashSize); logProbs = new const std::vector<double>*[dimNumber]; masses = new const std::vector<double>*[dimNumber]; marginalConfs = new const std::vector<int*>*[dimNumber]; for(int i = 0; i < dimNumber; i++) { masses[i] = &marginalResults[i]->conf_masses(); logProbs[i] = &marginalResults[i]->conf_lprobs(); marginalConfs[i] = &marginalResults[i]->confs(); } topConf = allocator.newConf(); memset( reinterpret_cast<char*>(topConf) + sizeof(double), 0, sizeof(int)*dimNumber ); *(reinterpret_cast<double*>(topConf)) = combinedSum( getConf(topConf), logProbs, dimNumber ); pq.push(topConf); } IsoOrderedGenerator::~IsoOrderedGenerator() { dealloc_table<MarginalTrek*>(marginalResults, dimNumber); delete[] logProbs; delete[] masses; delete[] marginalConfs; partialLProbs = nullptr; partialMasses = nullptr; partialProbs = nullptr; } bool IsoOrderedGenerator::advanceToNextConfiguration() { if(pq.size() < 1) return false; topConf = pq.top(); pq.pop(); int* topConfIsoCounts = getConf(topConf); currentLProb = *(reinterpret_cast<double*>(topConf)); currentMass = combinedSum( topConfIsoCounts, masses, dimNumber ); currentProb = exp(currentLProb); ccount = -1; for(int j = 0; j < dimNumber; ++j) { if(marginalResults[j]->probeConfigurationIdx(topConfIsoCounts[j] + 1)) { if(ccount == -1) { topConfIsoCounts[j]++; *(reinterpret_cast<double*>(topConf)) = combinedSum(topConfIsoCounts, logProbs, dimNumber); pq.push(topConf); topConfIsoCounts[j]--; ccount = j; } else { void* acceptedCandidate = allocator.newConf(); int* acceptedCandidateIsoCounts = getConf(acceptedCandidate); memcpy(acceptedCandidateIsoCounts, topConfIsoCounts, confSize); acceptedCandidateIsoCounts[j]++; *(reinterpret_cast<double*>(acceptedCandidate)) = combinedSum(acceptedCandidateIsoCounts, logProbs, dimNumber); pq.push(acceptedCandidate); } } if(topConfIsoCounts[j] > 0) break; } if(ccount >=0) topConfIsoCounts[ccount]++; return true; } /* * --------------------------------------------------------------------------------------------------- */ IsoStochasticGenerator::IsoStochasticGenerator(Iso&& iso, size_t no_molecules, double _precision, double _beta_bias) : IsoGenerator(std::move(iso)), ILG(std::move(*this)), to_sample_left(no_molecules), precision(_precision), beta_bias(_beta_bias), confs_prob(0.0), chasing_prob(0.0) {} /* * --------------------------------------------------------------------------------------------------- */ } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/marginalTrek++.cpp
.cpp
18,300
649
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include <cmath> #include <algorithm> #include <vector> #include <cstdlib> #include <unordered_map> #include <unordered_set> #include <queue> #include <utility> #include <cstring> #include <string> #include <limits> #include "platform.h" #include "marginalTrek++.h" #include "conf.h" #include "allocator.h" #include "operators.h" #include "summator.h" #include "element_tables.h" #include "misc.h" namespace IsoSpec { //! Find one of the most probable subisotopologues. /*! The algorithm uses the hill-climbing algorithm. It starts from a subisotopologue close to the mean of the underlying multinomial distribution. There might be more than one modes, in case of which this function will return only one of them, close to the mean. \param atomCnt */ void writeInitialConfiguration(const int atomCnt, const int isotopeNo, const double* lprobs, int* res) { /*! Here we perform hill climbing to the mode of the marginal distribution (the subisotopologue distribution). We start from the point close to the mean of the underlying multinomial distribution. */ // This approximates the mode (heuristics: the mean is close to the mode). for(int i = 0; i < isotopeNo; ++i) res[i] = static_cast<int>( atomCnt * exp(lprobs[i]) ) + 1; // The number of assigned atoms above. int s = 0; for(int i = 0; i < isotopeNo; ++i) s += res[i]; int diff = atomCnt - s; // Too little: enlarging fist index. if( diff > 0 ){ res[0] += diff; } // Too much: trying to redistribute the difference: hopefully the first element is the largest. if( diff < 0 ){ diff = abs(diff); int i = 0; while( diff > 0){ int coordDiff = res[i] - diff; if( coordDiff >= 0 ){ res[i] -= diff; diff = 0; } else { res[i] = 0; i++; diff = abs(coordDiff); } } } // What we computed so far will be very close to the mode: hillclimb the rest of the way bool modified = true; double LP = unnormalized_logProb(res, lprobs, isotopeNo); double NLP; while(modified) { modified = false; for(int ii = 0; ii < isotopeNo; ii++) for(int jj = 0; jj < isotopeNo; jj++) if(ii != jj && res[ii] > 0) { res[ii]--; res[jj]++; NLP = unnormalized_logProb(res, lprobs, isotopeNo); if(NLP > LP || (NLP == LP && ii > jj)) { modified = true; LP = NLP; } else { res[ii]++; res[jj]--; } } } } double* getMLogProbs(const double* probs, int isoNo) { /*! Here we order the processor to round the numbers up rather than down. Rounding down could result in the algorithm falling in an infinite loop because of the numerical instability of summing. */ for(int ii = 0; ii < isoNo; ii++) if(probs[ii] <= 0.0 || probs[ii] > 1.0) throw std::invalid_argument("All isotope probabilities p must fulfill: 0.0 < p <= 1.0"); double* ret = new double[isoNo]; // here we change the table of probabilities and log it. for(int i = 0; i < isoNo; i++) { ret[i] = log(probs[i]); for(int j = 0; j < ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES; j++) if(elem_table_probability[j] == probs[i]) { ret[i] = elem_table_log_probability[j]; break; } } return ret; } double get_loggamma_nominator(int x) { // calculate log gamma of the nominator calculated in the binomial exression. double ret = lgamma(x+1); return ret; } int verify_atom_cnt(int atomCnt) { #if !ISOSPEC_BUILDING_OPENMS if(ISOSPEC_G_FACT_TABLE_SIZE-1 <= atomCnt) throw std::length_error("Subisotopologue too large, size limit (that is, the maximum number of atoms of a single element in a molecule) is: " + std::to_string(ISOSPEC_G_FACT_TABLE_SIZE-1)); #endif return atomCnt; } Marginal::Marginal( const double* _masses, const double* _probs, int _isotopeNo, int _atomCnt ) : disowned(false), isotopeNo(_isotopeNo), atomCnt(verify_atom_cnt(_atomCnt)), atom_lProbs(getMLogProbs(_probs, isotopeNo)), atom_masses(array_copy<double>(_masses, _isotopeNo)), loggamma_nominator(get_loggamma_nominator(_atomCnt)), mode_conf(nullptr) // Deliberately not initializing mode_lprob {} Marginal::Marginal(const Marginal& other) : disowned(false), isotopeNo(other.isotopeNo), atomCnt(other.atomCnt), atom_lProbs(array_copy<double>(other.atom_lProbs, isotopeNo)), atom_masses(array_copy<double>(other.atom_masses, isotopeNo)), loggamma_nominator(other.loggamma_nominator) { if(other.mode_conf == nullptr) { mode_conf = nullptr; // Deliberately not initializing mode_lprob. In this state other.mode_lprob is uninitialized too. } else { mode_conf = array_copy<int>(other.mode_conf, isotopeNo); mode_lprob = other.mode_lprob; } } // the move-constructor: used in the specialization of the marginal. Marginal::Marginal(Marginal&& other) noexcept : disowned(other.disowned), isotopeNo(other.isotopeNo), atomCnt(other.atomCnt), atom_lProbs(other.atom_lProbs), atom_masses(other.atom_masses), loggamma_nominator(other.loggamma_nominator) { other.disowned = true; if(other.mode_conf == nullptr) { mode_conf = nullptr; // Deliberately not initializing mode_lprob. In this state other.mode_lprob is uninitialized too. } else { mode_conf = other.mode_conf; mode_lprob = other.mode_lprob; } } Marginal::~Marginal() { if(!disowned) { delete[] atom_masses; delete[] atom_lProbs; delete[] mode_conf; } } Conf Marginal::computeModeConf() const { Conf res = new int[isotopeNo]; writeInitialConfiguration(atomCnt, isotopeNo, atom_lProbs, res); return res; } void Marginal::setupMode() { ISOSPEC_IMPOSSIBLE(mode_conf != nullptr); mode_conf = computeModeConf(); mode_lprob = logProb(mode_conf); } double Marginal::getLightestConfMass() const { double ret_mass = std::numeric_limits<double>::infinity(); for(unsigned int ii = 0; ii < isotopeNo; ii++) if( ret_mass > atom_masses[ii] ) ret_mass = atom_masses[ii]; return ret_mass*atomCnt; } double Marginal::getHeaviestConfMass() const { double ret_mass = 0.0; for(unsigned int ii = 0; ii < isotopeNo; ii++) if( ret_mass < atom_masses[ii] ) ret_mass = atom_masses[ii]; return ret_mass*atomCnt; } double Marginal::getMonoisotopicConfMass() const { double found_prob = -std::numeric_limits<double>::infinity(); double found_mass = 0.0; // to avoid uninitialized var warning for(unsigned int ii = 0; ii < isotopeNo; ii++) if( found_prob < atom_lProbs[ii] ) { found_prob = atom_lProbs[ii]; found_mass = atom_masses[ii]; } return found_mass*atomCnt; } double Marginal::getAtomAverageMass() const { double ret = 0.0; for(unsigned int ii = 0; ii < isotopeNo; ii++) ret += exp(atom_lProbs[ii]) * atom_masses[ii]; return ret; } double Marginal::variance() const { double ret = 0.0; double mean = getAtomAverageMass(); for(size_t ii = 0; ii < isotopeNo; ii++) { double msq = atom_masses[ii] - mean; ret += exp(atom_lProbs[ii]) * msq * msq; } return ret * atomCnt; } double Marginal::getLogSizeEstimate(double logEllipsoidRadius) const { if(isotopeNo <= 1) return -std::numeric_limits<double>::infinity(); const double i = static_cast<double>(isotopeNo); const double k = i - 1.0; const double n = static_cast<double>(atomCnt); double sum_lprobs = 0.0; for(int jj = 0; jj < i; jj++) sum_lprobs += atom_lProbs[jj]; double log_V_simplex = k * log(n) - lgamma(i); double log_N_simplex = lgamma(n+i) - lgamma(n+1.0) - lgamma(i); double log_V_ellipsoid = (k * (log(n) + logpi + logEllipsoidRadius) + sum_lprobs) * 0.5 - lgamma((i+1)*0.5); return log_N_simplex + log_V_ellipsoid - log_V_simplex; } // this is roughly an equivalent of IsoSpec-Threshold-Generator MarginalTrek::MarginalTrek( Marginal&& m, int tabSize, int hashSize ) : Marginal(std::move(m)), current_count(0), keyHasher(isotopeNo), equalizer(isotopeNo), orderMarginal(atom_lProbs, isotopeNo), visited(hashSize, keyHasher, equalizer), pq(orderMarginal), totalProb(), candidate(new int[isotopeNo]), allocator(isotopeNo, tabSize) { int* initialConf = allocator.makeCopy(mode_conf); pq.push(initialConf); visited[initialConf] = 0; totalProb = Summator(); current_count = 0; add_next_conf(); } bool MarginalTrek::add_next_conf() { /*! Add next configuration. If visited all, return false. */ if(pq.size() < 1) return false; Conf topConf = pq.top(); pq.pop(); ++current_count; visited[topConf] = current_count; _confs.push_back(topConf); _conf_masses.push_back(calc_mass(topConf, atom_masses, isotopeNo)); double logprob = logProb(topConf); _conf_lprobs.push_back(logprob); totalProb.add( exp( logprob ) ); for( unsigned int i = 0; i < isotopeNo; ++i ) { for( unsigned int j = 0; j < isotopeNo; ++j ) { // Growing index different than decreasing one AND // Remain on simplex condition. if( i != j && topConf[j] > 0 ){ copyConf(topConf, candidate, isotopeNo); ++candidate[i]; --candidate[j]; // candidate should not have been already visited. if( visited.count( candidate ) == 0 ) { Conf acceptedCandidate = allocator.makeCopy(candidate); pq.push(acceptedCandidate); visited[acceptedCandidate] = 0; } } } } return true; } int MarginalTrek::processUntilCutoff(double cutoff) { Summator s; int last_idx = -1; for(unsigned int i = 0; i < _conf_lprobs.size(); i++) { s.add(_conf_lprobs[i]); if(s.get() >= cutoff) { last_idx = i; break; } } if(last_idx > -1) return last_idx; while(totalProb.get() < cutoff && add_next_conf()) {} return _conf_lprobs.size(); } MarginalTrek::~MarginalTrek() { delete[] candidate; } PrecalculatedMarginal::PrecalculatedMarginal(Marginal&& m, double lCutOff, bool sort, int tabSize, int hashSize ) : Marginal(std::move(m)), allocator(isotopeNo, tabSize) { const ConfEqual equalizer(isotopeNo); const KeyHasher keyHasher(isotopeNo); const ConfOrderMarginalDescending orderMarginal(atom_lProbs, isotopeNo); lCutOff -= loggamma_nominator; std::unordered_set<Conf, KeyHasher, ConfEqual> visited(hashSize, keyHasher, equalizer); Conf currentConf = allocator.makeCopy(mode_conf); if(unnormalized_logProb(currentConf) >= lCutOff) { // create a copy and store a ptr to the *same* copy in both structures // (save some space and time) auto tmp = allocator.makeCopy(currentConf); configurations.push_back(tmp); visited.insert(tmp); } unsigned int idx = 0; while(idx < configurations.size()) { memcpy(currentConf, configurations[idx], sizeof(int)*isotopeNo); idx++; for(unsigned int ii = 0; ii < isotopeNo; ii++ ) { currentConf[ii]++; for(unsigned int jj = 0; jj < isotopeNo; jj++ ) { if( ii != jj && currentConf[jj] > 0) { currentConf[jj]--; if (visited.count(currentConf) == 0 && unnormalized_logProb(currentConf) >= lCutOff) { // create a copy and store a ptr to the *same* copy in // both structures (save some space and time) auto tmp = allocator.makeCopy(currentConf); visited.insert(tmp); configurations.push_back(tmp); // std::cout << " V: "; for (auto it : visited) std::cout << it << " "; std::cout << std::endl; } currentConf[jj]++; } } currentConf[ii]--; } } // orderMarginal defines the order of configurations (compares their logprobs) // akin to key in Python sort. if(sort) std::sort(configurations.begin(), configurations.end(), orderMarginal); confs = &configurations[0]; no_confs = configurations.size(); lProbs = new double[no_confs+1]; probs = new double[no_confs]; masses = new double[no_confs]; for(unsigned int ii = 0; ii < no_confs; ii++) { lProbs[ii] = logProb(confs[ii]); probs[ii] = exp(lProbs[ii]); masses[ii] = calc_mass(confs[ii], atom_masses, isotopeNo); } lProbs[no_confs] = -std::numeric_limits<double>::infinity(); } PrecalculatedMarginal::~PrecalculatedMarginal() { if(lProbs != nullptr) delete[] lProbs; if(masses != nullptr) delete[] masses; if(probs != nullptr) delete[] probs; } LayeredMarginal::LayeredMarginal(Marginal&& m, int tabSize, int _hashSize) : Marginal(std::move(m)), current_threshold(1.0), allocator(isotopeNo, tabSize), equalizer(isotopeNo), keyHasher(isotopeNo), orderMarginal(atom_lProbs, isotopeNo), hashSize(_hashSize) { fringe.push_back(mode_conf); lProbs.push_back(std::numeric_limits<double>::infinity()); lProbs.push_back(-std::numeric_limits<double>::infinity()); guarded_lProbs = lProbs.data()+1; } bool LayeredMarginal::extend(double new_threshold, bool do_sort) { if(fringe.empty()) return false; std::vector<Conf> new_fringe; std::unordered_set<Conf, KeyHasher, ConfEqual> visited(hashSize, keyHasher, equalizer); for(unsigned int ii = 0; ii < fringe.size(); ii++) visited.insert(fringe[ii]); Conf currentConf; while(!fringe.empty()) { currentConf = fringe.back(); fringe.pop_back(); double opc = logProb(currentConf); if(opc < new_threshold) new_fringe.push_back(currentConf); else { configurations.push_back(currentConf); for(unsigned int ii = 0; ii < isotopeNo; ii++ ) { currentConf[ii]++; for(unsigned int jj = 0; jj < isotopeNo; jj++ ) { if( ii != jj && currentConf[jj] > 0 ) { currentConf[jj]--; double lpc = logProb(currentConf); if (lpc < current_threshold && (opc > lpc || (opc == lpc && ii > jj)) && visited.count(currentConf) == 0) { Conf nc = allocator.makeCopy(currentConf); currentConf[ii]--; currentConf[jj]++; visited.insert(nc); currentConf[ii]++; if(lpc >= new_threshold) fringe.push_back(nc); else new_fringe.push_back(nc); } else { currentConf[jj]++; } } } currentConf[ii]--; } } } current_threshold = new_threshold; fringe.swap(new_fringe); if(do_sort) std::sort(configurations.begin()+probs.size(), configurations.end(), orderMarginal); if(lProbs.capacity() * 2 < configurations.size() + 2) { // Reserve space for new values lProbs.reserve(configurations.size()+2); probs.reserve(configurations.size()); masses.reserve(configurations.size()); } // Otherwise we're growing slowly enough that standard reallocations on push_back work better - we waste some extra memory // but don't reallocate on every call lProbs.pop_back(); // The guardian... for(unsigned int ii = probs.size(); ii < configurations.size(); ii++) { lProbs.push_back(logProb(configurations[ii])); probs.push_back(exp(lProbs.back())); masses.push_back(calc_mass(configurations[ii], atom_masses, isotopeNo)); } lProbs.push_back(-std::numeric_limits<double>::infinity()); // Restore guardian guarded_lProbs = lProbs.data()+1; // Vector might have reallocated its backing storage return true; } double LayeredMarginal::get_min_mass() const { double ret = std::numeric_limits<double>::infinity(); for(std::vector<double>::const_iterator it = masses.begin(); it != masses.end(); ++it) if(*it < ret) ret = *it; return ret; } double LayeredMarginal::get_max_mass() const { double ret = -std::numeric_limits<double>::infinity(); for(std::vector<double>::const_iterator it = masses.begin(); it != masses.end(); ++it) if(*it > ret) ret = *it; return ret; } } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/element_tables.cpp
.cpp
55,020
2,993
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include "element_tables.h" namespace IsoSpec { #ifdef __cplusplus extern "C" { #endif const size_t isospec_number_of_isotopic_entries = ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES; const int elem_table_ID [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 9, 10, 10, 10, 11, 12, 12, 12, 13, 14, 14, 14, 15, 16, 16, 16, 16, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, 20, 21, 22, 22, 22, 22, 22, 23, 23, 24, 24, 24, 24, 25, 26, 26, 26, 26, 27, 28, 28, 28, 28, 28, 29, 29, 30, 30, 30, 30, 30, 31, 31, 32, 32, 32, 32, 32, 33, 34, 34, 34, 34, 34, 34, 35, 35, 36, 36, 36, 36, 36, 36, 37, 37, 38, 38, 38, 38, 39, 40, 40, 40, 40, 40, 41, 42, 42, 42, 42, 42, 42, 42, 44, 44, 44, 44, 44, 44, 44, 45, 46, 46, 46, 46, 46, 46, 47, 47, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 55, 56, 56, 56, 56, 56, 56, 56, 57, 57, 58, 58, 58, 58, 59, 60, 60, 60, 60, 60, 60, 60, 62, 62, 62, 62, 62, 62, 62, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65, 66, 66, 66, 66, 66, 66, 66, 67, 68, 68, 68, 68, 68, 68, 69, 70, 70, 70, 70, 70, 70, 70, 71, 71, 72, 72, 72, 72, 72, 72, 73, 73, 74, 74, 74, 74, 74, 75, 75, 76, 76, 76, 76, 76, 76, 76, 77, 77, 78, 78, 78, 78, 78, 78, 79, 80, 80, 80, 80, 80, 80, 80, 81, 81, 82, 82, 82, 82, 83, 92, 92, 92, 90, 91, 1000, // Electron 1001, // Missing electron 1002, // Protonation 1002, // Protonation (Deuterium) }; const int elem_table_atomicNo [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 9, 10, 10, 10, 11, 12, 12, 12, 13, 14, 14, 14, 15, 16, 16, 16, 16, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, 20, 21, 22, 22, 22, 22, 22, 23, 23, 24, 24, 24, 24, 25, 26, 26, 26, 26, 27, 28, 28, 28, 28, 28, 29, 29, 30, 30, 30, 30, 30, 31, 31, 32, 32, 32, 32, 32, 33, 34, 34, 34, 34, 34, 34, 35, 35, 36, 36, 36, 36, 36, 36, 37, 37, 38, 38, 38, 38, 39, 40, 40, 40, 40, 40, 41, 42, 42, 42, 42, 42, 42, 42, 44, 44, 44, 44, 44, 44, 44, 45, 46, 46, 46, 46, 46, 46, 47, 47, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 53, 54, 54, 54, 54, 54, 54, 54, 54, 54, 55, 56, 56, 56, 56, 56, 56, 56, 57, 57, 58, 58, 58, 58, 59, 60, 60, 60, 60, 60, 60, 60, 62, 62, 62, 62, 62, 62, 62, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65, 66, 66, 66, 66, 66, 66, 66, 67, 68, 68, 68, 68, 68, 68, 69, 70, 70, 70, 70, 70, 70, 70, 71, 71, 72, 72, 72, 72, 72, 72, 73, 73, 74, 74, 74, 74, 74, 75, 75, 76, 76, 76, 76, 76, 76, 76, 77, 77, 78, 78, 78, 78, 78, 78, 79, 80, 80, 80, 80, 80, 80, 80, 81, 81, 82, 82, 82, 82, 83, 92, 92, 92, 90, 91, 0, 0, 1, 1, }; const double elem_table_mass [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { 1.00782503227, 2.01410177819, 3.016029322, 4.00260325414, 6.0151228871, 7.016003443, 9.01218316, 10.0129373, 11.0093053, 12, 13.0033548352, 14.0030740042, 15.0001088994, 15.9949146202, 16.9991317576, 17.9991596137, 18.9984031637, 19.992440182, 20.99384673, 21.99138512, 22.989769282, 23.985041701, 24.98583703, 25.98259302, 26.98153858, 27.9769265353, 28.9764946653, 29.973770012, 30.9737619986, 31.9720711741, 32.9714589101, 33.96786703, 35.9670812, 34.96885273, 36.96590264, 35.96754512, 37.9627322, 39.962383122, 38.963706493, 39.96399824, 40.961825263, 39.96259092, 41.9586181, 42.9587662, 43.9554822, 45.953692, 47.95252289, 44.9559086, 45.9526283, 46.9517593, 47.9479423, 48.9478663, 49.9447873, 49.9471567, 50.9439577, 49.9460427, 51.9405064, 52.9406484, 53.9388794, 54.9380443, 53.9396093, 55.9349363, 56.9353933, 57.9332743, 58.9331944, 57.9353423, 59.9307863, 60.9310563, 61.9283454, 63.9279674, 62.9295984, 64.9277906, 63.9291426, 65.9260347, 66.9271287, 67.9248457, 69.925322, 68.9255749, 70.9247037, 69.9242497, 71.92207586, 72.92345904, 73.921177761, 75.92140272, 74.9215957, 73.92247591, 75.91921372, 76.91991426, 77.9173092, 79.9165229, 81.9167001, 78.9183381, 80.9162901, 77.9203656, 79.9163786, 81.9134837, 82.9141272, 83.911497733, 85.910610633, 84.911789743, 86.909180536, 83.9134199, 85.9092619, 86.9088789, 87.9056139, 88.905842, 89.904702, 90.905642, 91.905032, 93.906312, 95.908272, 92.906372, 91.9068086, 93.9050853, 94.9058393, 95.9046763, 96.9060183, 97.9054053, 99.9074728, 95.9075903, 97.905296, 98.9059348, 99.9042148, 100.9055779, 101.9043449, 103.905432, 102.905502, 101.905602, 103.9040311, 104.9050809, 105.9034809, 107.9038929, 109.9051726, 106.905092, 108.9047551, 105.9064609, 107.9041839, 109.9030074, 110.9041834, 111.9027634, 112.9044083, 113.9033653, 115.9047632, 112.9040627, 114.903878789, 111.9048244, 113.9027837, 114.90334471, 115.9017431, 116.9029543, 117.9016073, 118.9033116, 119.9022027, 121.903442, 123.9052778, 120.903812, 122.904212, 119.904062, 121.903041, 122.904271, 123.902821, 124.904431, 125.903311, 127.9044617, 129.906222759, 126.904473, 123.905892, 125.904303, 127.9035318, 128.904780864, 129.90350941, 130.9050842, 131.904155094, 133.9053957, 135.907214488, 132.905451967, 129.906322, 131.9050618, 133.9045082, 134.9056882, 135.9045762, 136.9058272, 137.9052472, 137.907123, 138.906362, 135.9071293, 137.905998, 139.905442, 141.909252, 140.907662, 141.907732, 142.909822, 143.910092, 144.912582, 145.913122, 147.916902, 149.920902, 143.912012, 146.914902, 147.914832, 148.917192, 149.917282, 151.919742, 153.922222, 150.919862, 152.921242, 151.919802, 153.920872, 154.922632, 155.922132, 156.923972, 157.924112, 159.927062, 158.925352, 155.924282, 157.924422, 159.925202, 160.926942, 161.926812, 162.928742, 163.929182, 164.930332, 161.928792, 163.929212, 165.930302, 166.932052, 167.932382, 169.935472, 168.934222, 167.933892, 169.934772, 170.936332, 171.936392, 172.938222, 173.938872, 175.942582, 174.940782, 175.942692, 173.940052, 175.941412, 176.943232, 177.943712, 178.945822, 179.946562, 179.947462, 180.948002, 179.946712, 181.9482047, 182.9502237, 183.9509317, 185.954362, 184.9529559, 186.955751, 183.9524891, 185.953841, 186.955751, 187.955841, 188.958142, 189.958442, 191.961482, 190.960592, 192.962922, 189.959934, 191.961042, 193.9626817, 194.9647927, 195.9649527, 197.967892, 196.9665696, 195.965832, 197.9667693, 198.9682813, 199.9683273, 200.9703036, 201.9706436, 203.9734943, 202.9723451, 204.9744281, 203.9730449, 205.9744669, 206.9758979, 207.9766539, 208.980401, 234.040952, 235.043932, 238.050792, 232.038062, 231.035882, 0.000548579909065, // Electron -0.000548579909065, // Missing electron 1.007276466879, // Protonation 2.013553212745, // Protonation (deuterium) }; const double elem_table_massNo [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { 1.0, 2.0, 3.0, 4.0, 6.0, 7.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 36.0, 35.0, 37.0, 36.0, 38.0, 40.0, 39.0, 40.0, 41.0, 40.0, 42.0, 43.0, 44.0, 46.0, 48.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 50.0, 51.0, 50.0, 52.0, 53.0, 54.0, 55.0, 54.0, 56.0, 57.0, 58.0, 59.0, 58.0, 60.0, 61.0, 62.0, 64.0, 63.0, 65.0, 64.0, 66.0, 67.0, 68.0, 70.0, 69.0, 71.0, 70.0, 72.0, 73.0, 74.0, 76.0, 75.0, 74.0, 76.0, 77.0, 78.0, 80.0, 82.0, 79.0, 81.0, 78.0, 80.0, 82.0, 83.0, 84.0, 86.0, 85.0, 87.0, 84.0, 86.0, 87.0, 88.0, 89.0, 90.0, 91.0, 92.0, 94.0, 96.0, 93.0, 92.0, 94.0, 95.0, 96.0, 97.0, 98.0, 100.0, 96.0, 98.0, 99.0, 100.0, 101.0, 102.0, 104.0, 103.0, 102.0, 104.0, 105.0, 106.0, 108.0, 110.0, 107.0, 109.0, 106.0, 108.0, 110.0, 111.0, 112.0, 113.0, 114.0, 116.0, 113.0, 115.0, 112.0, 114.0, 115.0, 116.0, 117.0, 118.0, 119.0, 120.0, 122.0, 124.0, 121.0, 123.0, 120.0, 122.0, 123.0, 124.0, 125.0, 126.0, 128.0, 130.0, 127.0, 124.0, 126.0, 128.0, 129.0, 130.0, 131.0, 132.0, 134.0, 136.0, 133.0, 130.0, 132.0, 134.0, 135.0, 136.0, 137.0, 138.0, 138.0, 139.0, 136.0, 138.0, 140.0, 142.0, 141.0, 142.0, 143.0, 144.0, 145.0, 146.0, 148.0, 150.0, 144.0, 147.0, 148.0, 149.0, 150.0, 152.0, 154.0, 151.0, 153.0, 152.0, 154.0, 155.0, 156.0, 157.0, 158.0, 160.0, 159.0, 156.0, 158.0, 160.0, 161.0, 162.0, 163.0, 164.0, 165.0, 162.0, 164.0, 166.0, 167.0, 168.0, 170.0, 169.0, 168.0, 170.0, 171.0, 172.0, 173.0, 174.0, 176.0, 175.0, 176.0, 174.0, 176.0, 177.0, 178.0, 179.0, 180.0, 180.0, 181.0, 180.0, 182.0, 183.0, 184.0, 186.0, 185.0, 187.0, 184.0, 186.0, 187.0, 188.0, 189.0, 190.0, 192.0, 191.0, 193.0, 190.0, 192.0, 194.0, 195.0, 196.0, 198.0, 197.0, 196.0, 198.0, 199.0, 200.0, 201.0, 202.0, 204.0, 203.0, 205.0, 204.0, 206.0, 207.0, 208.0, 209.0, 234.0, 235.0, 238.0, 232.0, 231.0, 0.0, 0.0, 1.0, 2.0, }; const int elem_table_extraNeutrons [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 4, 0, 2, 0, 2, 4, 0, 1, 2, 0, 2, 3, 4, 6, 8, 0, 0, 1, 2, 3, 4, 0, 1, 0, 2, 3, 4, 0, 0, 2, 3, 4, 0, 0, 2, 3, 4, 6, 0, 2, 0, 2, 3, 4, 6, 0, 2, 0, 2, 3, 4, 6, 0, 0, 2, 3, 4, 6, 8, 0, 2, 0, 2, 4, 5, 6, 8, 0, 2, 0, 2, 3, 4, 0, 0, 1, 2, 4, 6, 0, 0, 2, 3, 4, 5, 6, 8, 0, 2, 3, 4, 5, 6, 8, 0, 0, 2, 3, 4, 6, 8, 0, 2, 0, 2, 4, 5, 6, 7, 8, 10, 0, 2, 0, 2, 3, 4, 5, 6, 7, 8, 10, 12, 0, 2, 0, 2, 3, 4, 5, 6, 8, 10, 0, 0, 2, 4, 5, 6, 7, 8, 10, 12, 0, 0, 2, 4, 5, 6, 7, 8, 0, 1, 0, 2, 4, 6, 0, 0, 1, 2, 3, 4, 6, 8, 0, 3, 4, 5, 6, 8, 10, 0, 2, 0, 2, 3, 4, 5, 6, 8, 0, 0, 2, 4, 5, 6, 7, 8, 0, 0, 2, 4, 5, 6, 8, 0, 0, 2, 3, 4, 5, 6, 8, 0, 1, 0, 2, 3, 4, 5, 6, 0, 1, 0, 2, 3, 4, 6, 0, 2, 0, 2, 3, 4, 5, 6, 8, 0, 2, 0, 2, 4, 5, 6, 8, 0, 0, 2, 3, 4, 5, 6, 8, 0, 2, 0, 2, 3, 4, 0, 1, 2, 5, 0, 0, 0, 0, 0, 1, }; const char* elem_table_element [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { "hydrogen", "hydrogen", "helium", "helium", "lithium", "lithium", "beryllium", "boron", "boron", "carbon", "carbon", "nitrogen", "nitrogen", "oxygen", "oxygen", "oxygen", "fluorine", "neon", "neon", "neon", "sodium", "magnesium", "magnesium", "magnesium", "aluminium", "silicon", "silicon", "silicon", "phosphorus", "sulfur", "sulfur", "sulfur", "sulfur", "chlorine", "chlorine", "argon", "argon", "argon", "potassium", "potassium", "potassium", "calcium", "calcium", "calcium", "calcium", "calcium", "calcium", "scandium", "titanium", "titanium", "titanium", "titanium", "titanium", "vanadium", "vanadium", "chromium", "chromium", "chromium", "chromium", "manganese", "iron", "iron", "iron", "iron", "cobalt", "nickel", "nickel", "nickel", "nickel", "nickel", "copper", "copper", "zinc", "zinc", "zinc", "zinc", "zinc", "gallium", "gallium", "germanium", "germanium", "germanium", "germanium", "germanium", "arsenic", "selenium", "selenium", "selenium", "selenium", "selenium", "selenium", "bromine", "bromine", "krypton", "krypton", "krypton", "krypton", "krypton", "krypton", "rubidium", "rubidium", "strontium", "strontium", "strontium", "strontium", "yttrium", "zirconium", "zirconium", "zirconium", "zirconium", "zirconium", "niobium", "molybdenum", "molybdenum", "molybdenum", "molybdenum", "molybdenum", "molybdenum", "molybdenum", "ruthenium", "ruthenium", "ruthenium", "ruthenium", "ruthenium", "ruthenium", "ruthenium", "rhodium", "palladium", "palladium", "palladium", "palladium", "palladium", "palladium", "silver", "silver", "cadmium", "cadmium", "cadmium", "cadmium", "cadmium", "cadmium", "cadmium", "cadmium", "indium", "indium", "tin", "tin", "tin", "tin", "tin", "tin", "tin", "tin", "tin", "tin", "antimony", "antimony", "tellurium", "tellurium", "tellurium", "tellurium", "tellurium", "tellurium", "tellurium", "tellurium", "iodine", "xenon", "xenon", "xenon", "xenon", "xenon", "xenon", "xenon", "xenon", "xenon", "caesium", "barium", "barium", "barium", "barium", "barium", "barium", "barium", "lanthanum", "lanthanum", "cerium", "cerium", "cerium", "cerium", "praseodymium", "neodymium", "neodymium", "neodymium", "neodymium", "neodymium", "neodymium", "neodymium", "samarium", "samarium", "samarium", "samarium", "samarium", "samarium", "samarium", "europium", "europium", "gadolinium", "gadolinium", "gadolinium", "gadolinium", "gadolinium", "gadolinium", "gadolinium", "terbium", "dysprosium", "dysprosium", "dysprosium", "dysprosium", "dysprosium", "dysprosium", "dysprosium", "holmium", "erbium", "erbium", "erbium", "erbium", "erbium", "erbium", "thulium", "ytterbium", "ytterbium", "ytterbium", "ytterbium", "ytterbium", "ytterbium", "ytterbium", "lutetium", "lutetium", "hafnium", "hafnium", "hafnium", "hafnium", "hafnium", "hafnium", "tantalum", "tantalum", "tungsten", "tungsten", "tungsten", "tungsten", "tungsten", "rhenium", "rhenium", "osmium", "osmium", "osmium", "osmium", "osmium", "osmium", "osmium", "iridium", "iridium", "platinum", "platinum", "platinum", "platinum", "platinum", "platinum", "gold", "mercury", "mercury", "mercury", "mercury", "mercury", "mercury", "mercury", "thallium", "thallium", "lead", "lead", "lead", "lead", "bismuth", "uranium", "uranium", "uranium", "thorium", "protactinium", "electron", "missing electron", "protonation", "protonation", // with deuteron }; const char* elem_table_symbol [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { "H", "H", "He", "He", "Li", "Li", "Be", "B", "B", "C", "C", "N", "N", "O", "O", "O", "F", "Ne", "Ne", "Ne", "Na", "Mg", "Mg", "Mg", "Al", "Si", "Si", "Si", "P", "S", "S", "S", "S", "Cl", "Cl", "Ar", "Ar", "Ar", "K", "K", "K", "Ca", "Ca", "Ca", "Ca", "Ca", "Ca", "Sc", "Ti", "Ti", "Ti", "Ti", "Ti", "V", "V", "Cr", "Cr", "Cr", "Cr", "Mn", "Fe", "Fe", "Fe", "Fe", "Co", "Ni", "Ni", "Ni", "Ni", "Ni", "Cu", "Cu", "Zn", "Zn", "Zn", "Zn", "Zn", "Ga", "Ga", "Ge", "Ge", "Ge", "Ge", "Ge", "As", "Se", "Se", "Se", "Se", "Se", "Se", "Br", "Br", "Kr", "Kr", "Kr", "Kr", "Kr", "Kr", "Rb", "Rb", "Sr", "Sr", "Sr", "Sr", "Y", "Zr", "Zr", "Zr", "Zr", "Zr", "Nb", "Mo", "Mo", "Mo", "Mo", "Mo", "Mo", "Mo", "Ru", "Ru", "Ru", "Ru", "Ru", "Ru", "Ru", "Rh", "Pd", "Pd", "Pd", "Pd", "Pd", "Pd", "Ag", "Ag", "Cd", "Cd", "Cd", "Cd", "Cd", "Cd", "Cd", "Cd", "In", "In", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sn", "Sb", "Sb", "Te", "Te", "Te", "Te", "Te", "Te", "Te", "Te", "I", "Xe", "Xe", "Xe", "Xe", "Xe", "Xe", "Xe", "Xe", "Xe", "Cs", "Ba", "Ba", "Ba", "Ba", "Ba", "Ba", "Ba", "La", "La", "Ce", "Ce", "Ce", "Ce", "Pr", "Nd", "Nd", "Nd", "Nd", "Nd", "Nd", "Nd", "Sm", "Sm", "Sm", "Sm", "Sm", "Sm", "Sm", "Eu", "Eu", "Gd", "Gd", "Gd", "Gd", "Gd", "Gd", "Gd", "Tb", "Dy", "Dy", "Dy", "Dy", "Dy", "Dy", "Dy", "Ho", "Er", "Er", "Er", "Er", "Er", "Er", "Tm", "Yb", "Yb", "Yb", "Yb", "Yb", "Yb", "Yb", "Lu", "Lu", "Hf", "Hf", "Hf", "Hf", "Hf", "Hf", "Ta", "Ta", "W", "W", "W", "W", "W", "Re", "Re", "Os", "Os", "Os", "Os", "Os", "Os", "Os", "Ir", "Ir", "Pt", "Pt", "Pt", "Pt", "Pt", "Pt", "Au", "Hg", "Hg", "Hg", "Hg", "Hg", "Hg", "Hg", "Tl", "Tl", "Pb", "Pb", "Pb", "Pb", "Bi", "U", "U", "U", "Th", "Pa", "E", "Me", "Pn", "Pn", }; const bool elem_table_Radioactive [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, true, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, true, false, false, true, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, true, false, true, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, true, false, false, false, true, false, true, true, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, true, false, true, false, false, false, false, false, true, true, true, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, false, false, false, false, }; const double elem_table_probability [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { 0.999884290164307909520857720053754746913909912109375000000000, 0.000115709835692033314582735648023970043141162022948265075684, 0.000001342999991941999914655050951672876635711872950196266174, 0.999998657000008006612290500925155356526374816894531250000000, 0.075933925285977116326208147256693337112665176391601562500000, 0.924066074714022800407065005856566131114959716796875000000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.199480830670926506664741850727295968681573867797851562500000, 0.800519169329073410068531302385963499546051025390625000000000, 0.989211941850466902614869013632414862513542175292968750000000, 0.010788058149533083507343178553128382191061973571777343750000, 0.996358014567941707717579902237048372626304626464843750000000, 0.003641985432058271465738386041266494430601596832275390625000, 0.997567609729561044495937949250219389796257019042968750000000, 0.000380998476006095935803702490218825005285907536745071411133, 0.002051391794432822109073288885383590240962803363800048828125, 1.000000000000000000000000000000000000000000000000000000000000, 0.904766666333356561757739200402284041047096252441406250000000, 0.002709810313278070148523823945652111433446407318115234375000, 0.092523523353365264010328417043638182803988456726074218750000, 1.000000000000000000000000000000000000000000000000000000000000, 0.789876809855211581279377242026384919881820678710937500000000, 0.100001999840012789633192369365133345127105712890625000000000, 0.110121190304775615209642580794024979695677757263183593750000, 1.000000000000000000000000000000000000000000000000000000000000, 0.922220833349999713490774411184247583150863647460937500000000, 0.046858437698747611166449900110819726251065731048583984375000, 0.030920728951252581667707985957349592354148626327514648437500, 1.000000000000000000000000000000000000000000000000000000000000, 0.949850011999040066967836537514813244342803955078125000000000, 0.007519398448124149821059081233443066594190895557403564453125, 0.042520598352131823427502155254842364229261875152587890625000, 0.000109991200703943683199964587160479823069181293249130249023, 0.757594848103037898923162174469325691461563110351562500000000, 0.242405151896962045565686594272847287356853485107421875000000, 0.003336205796380696270847510120916012965608388185501098632812, 0.000629799206452999775149304007015871320618316531181335449219, 0.996033994997166272078459314798237755894660949707031250000000, 0.932580526071084436878777523816097527742385864257812500000000, 0.000117099885242112454345267402722186034225160256028175354004, 0.067302374043673424131029037198459263890981674194335937500000, 0.969400838426726974006442105746828019618988037109375000000000, 0.006472228417153705684605746739634923869743943214416503906250, 0.001350985058105257227353823701321289263432845473289489746094, 0.020860869278785776348428271376178599894046783447265625000000, 0.000042999524425259849917842214228613784143817611038684844971, 0.001872079294802999303859447621789513505063951015472412109375, 1.000000000000000000000000000000000000000000000000000000000000, 0.082520097588289403889305617667559999972581863403320312500000, 0.074411070671519405350657905273692449554800987243652343750000, 0.737141543014838140912559083517407998442649841308593750000000, 0.054113506379234489751528514034362160600721836090087890625000, 0.051813782346118462951434224805780104361474514007568359375000, 0.002503979968160254584302881752932989911641925573348999023438, 0.997496020031839680797247638111002743244171142578125000000000, 0.043450743830478963380947732275672024115920066833496093750000, 0.837881075122238416774678171350387856364250183105468750000000, 0.095010483865806516501351097758742980659008026123046875000000, 0.023657697181476075587447382986283628270030021667480468750000, 1.000000000000000000000000000000000000000000000000000000000000, 0.058452792721208068904559240763774141669273376464843750000000, 0.917532497856775930422656983864726498723030090332031250000000, 0.021190743592002535267138085828264593146741390228271484375000, 0.002823965830013456732028309659199294401332736015319824218750, 1.000000000000000000000000000000000000000000000000000000000000, 0.680769095231327558970235713786678388714790344238281250000000, 0.262230419610671172669924544607056304812431335449218750000000, 0.011399083035777891892426083586542517878115177154541015625000, 0.036346250253448952882706635136855766177177429199218750000000, 0.009255151868774300419340228529563319170847535133361816406250, 0.691494255172344751692037334578344598412513732910156250000000, 0.308505744827655137285660202906001359224319458007812500000000, 0.491645713885820234700929631799226626753807067871093750000000, 0.277325508740183801492662496457342058420181274414062500000000, 0.040405292597461665848879164286699960939586162567138671875000, 0.184515103497573135227227680843498092144727706909179687500000, 0.006108381278961075126765489784474993939511477947235107421875, 0.601079797840404217446064194518839940428733825683593750000000, 0.398920202159595671531633342965506017208099365234375000000000, 0.205705812301332946478993335404084064066410064697265625000000, 0.274503726116209989527305879164487123489379882812500000000000, 0.077504017086240106770844704442424699664115905761718750000000, 0.364982406812098314485837136089685373008251190185546875000000, 0.077304037684118531714716482383664697408676147460937500000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.008938426836876709608015190156038443092256784439086914062500, 0.093712506598838590798905556766840163618326187133789062500000, 0.076302570747548426055573145276866853237152099609375000000000, 0.237686167234566703143627819372341036796569824218750000000000, 0.496053694549759227605534306348999962210655212402343750000000, 0.087306634032410290746639702774700708687305450439453125000000, 0.506898896176611657438115798868238925933837890625000000000000, 0.493101103823388231539581738616107031702995300292968750000000, 0.003552948126957346328819165037771199422422796487808227539062, 0.022860666234272977725971998097520554438233375549316406250000, 0.115931407401451927463575941601447993889451026916503906250000, 0.115000220996773441783922464765055337920784950256347656250000, 0.569863179997571966950431487930472940206527709960937500000000, 0.172791577242972227423933873069472610950469970703125000000000, 0.721691132354705722207199869444593787193298339843750000000000, 0.278308867645294166770497668039752170443534851074218750000000, 0.005609775608975640752429381308274969342164695262908935546875, 0.098606055757769678349333730693615507334470748901367187500000, 0.070007199712011511372189431767765199765563011169433593750000, 0.825776968921243081922511919401586055755615234375000000000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.514422711621750239352479638910153880715370178222656250000000, 0.112234410554393593262290096390643157064914703369140625000000, 0.171550886397901253266340404479706194251775741577148437500000, 0.173788376250214926521664438041625544428825378417968750000000, 0.028003615175739928616627238966430013533681631088256835937500, 1.000000000000000000000000000000000000000000000000000000000000, 0.145308494342837241086741073559096548706293106079101562500000, 0.091496458524138415957516201615362660959362983703613281250000, 0.158387558641321063435114524509117472916841506958007812500000, 0.166690329831184980147185115129104815423488616943359375000000, 0.095999792030779435014764544575882609933614730834960937500000, 0.243900902666405350327494261364336125552654266357421875000000, 0.098216463963333416886669624545902479439973831176757812500000, 0.055402974808013198682044020415560225956141948699951171875000, 0.018726273471579152340993346115283202379941940307617187500000, 0.127588609866636532030881312493875157088041305541992187500000, 0.126054915071900669465421174209041055291891098022460937500000, 0.170586053375378299268305681835045106709003448486328125000000, 0.315451225206183960558803391904802992939949035644531250000000, 0.186189948200308125203505937861336860805749893188476562500000, 1.000000000000000000000000000000000000000000000000000000000000, 0.010207550187954890497099569302008603699505329132080078125000, 0.111463248820283120088525663504697149619460105895996093750000, 0.223336399264176588275176982278935611248016357421875000000000, 0.273264416540030363744762098576757125556468963623046875000000, 0.264546508837878890929573572066146880388259887695312500000000, 0.117181876349676070137029171291942475363612174987792968750000, 0.518389668985958174118877650471404194831848144531250000000000, 0.481610331014041714858819887012941762804985046386718750000000, 0.012567197514954164816458614950533956289291381835937500000000, 0.008928009053980960965657409644791187020018696784973144531250, 0.124890149496662231087817929164884844794869422912597656250000, 0.127983459688489453753845737082883715629577636718750000000000, 0.241267197414976458658131264201074372977018356323242187500000, 0.122184752800125570604272695618419675156474113464355468750000, 0.287277937020044504823346187549759633839130401611328125000000, 0.074901297010766587636254598692175932228565216064453125000000, 0.042954845418549769675564675708301365375518798828125000000000, 0.957045154581450119302132861776044592261314392089843750000000, 0.009707379007667929146641050408561568474397063255310058593750, 0.006608215781738930282018795736576066701672971248626708984375, 0.003409079548521898664348306340343697229400277137756347656250, 0.145370749897527656857576516813423950225114822387695312500000, 0.076859248003039171148742525474517606198787689208984375000000, 0.242144620952342848330118840749491937458515167236328125000000, 0.085916802463334898676272644024720648303627967834472656250000, 0.325722055045137792728127124064485542476177215576171875000000, 0.046317494276545329023875297025369945913553237915039062500000, 0.057944355024143474885978122301821713335812091827392578125000, 0.572091349038115315472907695948379114270210266113281250000000, 0.427908650961884573504789841535966843366622924804687500000000, 0.000909764371027903685079651907585684966761618852615356445312, 0.025505394102927340937991829150632838718593120574951171875000, 0.008927687728878220055350745099076448241248726844787597656250, 0.047401722953754971134898710261040832847356796264648437500000, 0.070696689557404629455916733604681212455034255981445312500000, 0.188376210561464557668998054396070074290037155151367187500000, 0.317407791382032011817670991149498149752616882324218750000000, 0.340774739342510235573513455165084451436996459960937500000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.000952296533640617525774685336870106766582466661930084228516, 0.000890196759683794711613680217254795934422872960567474365234, 0.019102830465697103606848017420816177036613225936889648437500, 0.264005869018636762923790683998959138989448547363281250000000, 0.040709981815666186621971434078659513033926486968994140625000, 0.212323527142361190289676642350968904793262481689453125000000, 0.269085350529324029977829013660084456205368041992187500000000, 0.104356830141138279266499466757522895932197570800781250000000, 0.088573117593851946605099101361702196300029754638671875000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.001060985146207953045902061539607075246749445796012878417969, 0.001010985846198153050023993415607037604786455631256103515625, 0.024171461599537605313692267827718751505017280578613281250000, 0.065920277116120362670415033790050074458122253417968750000000, 0.078541300421794094099858796198532218113541603088378906250000, 0.112320827508414877726750091824214905500411987304687500000000, 0.716974162361726841119491382414707913994789123535156250000000, 0.000888171872103250392010975744483403104823082685470581054688, 0.999111828127896672846475212281802669167518615722656250000000, 0.001851973331584025024912354417949700291501358151435852050781, 0.002511963827720880421123794690174690913408994674682617187500, 0.884492463308528265031327464384958148002624511718750000000000, 0.111143599532166723053983048430382041260600090026855468750000, 1.000000000000000000000000000000000000000000000000000000000000, 0.271519166958828106483991859931848011910915374755859375000000, 0.121740433020292235233306143982190405949950218200683593750000, 0.237977663997580829446931716120161581784486770629882812500000, 0.082929723850915446070608538775559281930327415466308593750000, 0.171890140355501652713599014532519504427909851074218750000000, 0.057561075412857647115583148433870519511401653289794921875000, 0.056381796404024006608146635244338540360331535339355468750000, 0.030772522277086666181444840617587033193558454513549804687500, 0.149881578776357327065227309503825381398200988769531250000000, 0.112382691006085513873991033051424892619252204895019531250000, 0.138246406123312015612469849656918086111545562744140625000000, 0.073792068527347848272412988990254234522581100463867187500000, 0.267451009404714612482933944193064235150814056396484375000000, 0.227473723885095902019770619517657905817031860351562500000000, 0.478103065570820051632949798658955842256546020507812500000000, 0.521896934429179837344747738825390115380287170410156250000000, 0.002009636255837693018938550082452820788603276014328002929688, 0.021826049485043207132317633067941642366349697113037109375000, 0.147985214676143617129611129712429828941822052001953125000000, 0.204672954195290635048820604424690827727317810058593750000000, 0.156491675006823760529783839956508018076419830322265625000000, 0.248435033258980114689862261911912355571985244750976562500000, 0.218579437121880937322515592313720844686031341552734375000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.000562985756460361477619691594753703611786477267742156982422, 0.000952975889709990254573812595850768047966994345188140869141, 0.023291210732368467645203580218549177516251802444458007812500, 0.188889421097646226233024435714469291269779205322265625000000, 0.254747154896981076177553404704667627811431884765625000000000, 0.248957901365095435330943018925609067082405090332031250000000, 0.282598350261738351374418698469526134431362152099609375000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.001395973476503946332158423437874716910300776362419128417969, 0.016012695758780580435054474719436257146298885345458984375000, 0.335027234482544788995994622382568195462226867675781250000000, 0.228686654953555862368475004586798604577779769897460937500000, 0.269776674243189351631855288360384292900562286376953125000000, 0.149100767085425356395234075534972362220287322998046875000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.001232929969577727796758992440118163358420133590698242187500, 0.029822206098693591902470956256365752778947353363037109375000, 0.140905996539396560773838018576498143374919891357421875000000, 0.216800685721051017429417129278590437024831771850585937500000, 0.161027253651992552363481081556528806686401367187500000000000, 0.320249909805123023076589561242144554853439331054687500000000, 0.129961018214165419104588750087714288383722305297851562500000, 0.974008767577204226384424146090168505907058715820312500000000, 0.025991232422795697287742910930319339968264102935791015625000, 0.001609652315099938373749166586890169128309935331344604492188, 0.052668623577307296934613134453684324398636817932128906250000, 0.185969830516608397585898160286888014525175094604492187500000, 0.272821070648739838482299546740250661969184875488281250000000, 0.136190582834107815068946933934057597070932388305664062500000, 0.350740240108136591690168870627530850470066070556640625000000, 0.000120131992311552486551486096377772128107608295977115631104, 0.999879868007688354936135510797612369060516357421875000000000, 0.001209872963338849303702171589236513682408258318901062011719, 0.264988176241494621798722164385253563523292541503906250000000, 0.143124971877952811283307710255030542612075805664062500000000, 0.306387829277925793913794905165559612214565277099609375000000, 0.284289149639287863635672692907974123954772949218750000000000, 0.374005039798408045470523575204424560070037841796875000000000, 0.625994960201591843507173962279921397566795349121093750000000, 0.000209947723016968765524098428087995671376120299100875854492, 0.015926034417430057904541129687459033448249101638793945312500, 0.019615115836156795520173190539026109036058187484741210937500, 0.132457018202467580181291850749403238296508789062500000000000, 0.161519781574387955025429164379602298140525817871093750000000, 0.262554623898649197588639481182326562702655792236328125000000, 0.407717478347891348899878494194126687943935394287109375000000, 0.373050779688124722888176165724871680140495300292968750000000, 0.626949220311875166089521371759474277496337890625000000000000, 0.000121987349911814132899338936066868654961581341922283172607, 0.007821588901230941415221309398475568741559982299804687500000, 0.328605923565726210089366077227168716490268707275390625000000, 0.337788971283677852408544595164130441844463348388671875000000, 0.252107856415289710572125159160350449383258819580078125000000, 0.073553672484163390432598816914833150804042816162109375000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.001509815802472098391837085351596670079743489623069763183594, 0.099707835644051417967048678292485419660806655883789062500000, 0.168701418426951910145561441822792403399944305419921875000000, 0.230990819120067331082779560347262304276227951049804687500000, 0.131793921141620695713925215386552736163139343261718750000000, 0.298589572072207154462830658303573727607727050781250000000000, 0.068706617792629293139938795320631470531225204467773437500000, 0.295204095918081610427918803907232359051704406738281250000000, 0.704795904081918278549778733577113598585128784179687500000000, 0.014094362255097959285565778486670751590281724929809570312500, 0.241003598560575765796798464180028531700372695922851562500000, 0.221011595361855245345239495691203046590089797973632812500000, 0.523890443822470963652904174523428082466125488281250000000000, 1.000000000000000000000000000000000000000000000000000000000000, 0.000054599923560107009460132254652364736102754250168800354004, 0.007204689913434121108226637630878030904568731784820556640625, 0.992740710163005690702675565262325108051300048828125000000000, 1.000000000000000000000000000000000000000000000000000000000000, 1.000000000000000000000000000000000000000000000000000000000000, 1.0, 1.0, 0.999884290164307909520857720053754746913909912109375000000000, 0.000115709835692033314582735648023970043141162022948265075684, }; const double elem_table_log_probability [ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES] = { -0.000115716530591520062594239337538937206772970966994762420654, -9.064424917075021070900220365729182958602905273437500000000000, -13.520604646423175054792409355286508798599243164062500000000000, -0.000001343000893767296712052561162564767727189973811618983746, -2.577891720978651601825504258158616721630096435546875000000000, -0.078971700466369670889932308455172460526227951049804687500000, 0.000000000000000000000000000000000000000000000000000000000000, -1.612037134131381055368592569720931351184844970703125000000000, -0.222494800137427506392384657374350354075431823730468750000000, -0.010846671177187771836769591971005866071209311485290527343750, -4.529315483514038120915756735485047101974487304687500000000000, -0.003648633607616148452623683340334537206217646598815917968750, -5.615226297668721500144783931318670511245727539062500000000000, -0.002435353337518350851781390176142849668394774198532104492188, -7.872715182829573166145564755424857139587402343750000000000000, -6.189236792082963845018639403861016035079956054687500000000000, 0.000000000000000000000000000000000000000000000000000000000000, -0.100078195781331494296217954342864686623215675354003906250000, -5.910876641640641970809610938886180520057678222656250000000000, -2.380292360271312634978357891668565571308135986328125000000000, 0.000000000000000000000000000000000000000000000000000000000000, -0.235878282572628383828572395941591821610927581787109375000000, -2.302565094793883382351395994191989302635192871093750000000000, -2.206173789605455404227996041299775242805480957031250000000000, 0.000000000000000000000000000000000000000000000000000000000000, -0.080970568540825488268453113960276823490858078002929687500000, -3.060624186220378017964094397029839456081390380859375000000000, -3.476328480144544208485513081541284918785095214843750000000000, 0.000000000000000000000000000000000000000000000000000000000000, -0.051451188958515865767839869704403099603950977325439453125000, -4.890269137820559386398144852137193083763122558593750000000000, -3.157766653355948971437783256988041102886199951171875000000000, -9.115110188972028737453001667745411396026611328125000000000000, -0.277606537419771426389303314863354898989200592041015625000000, -1.417144771312495832304989562544506043195724487304687500000000, -5.702921106825801444983881083317101001739501953125000000000000, -7.370109509296556282720302988309413194656372070312500000000000, -0.003973890456746663815690290277871099533513188362121582031250, -0.069799776156532433724066777358530089259147644042968750000000, -9.052483267360123875278077321127057075500488281250000000000000, -2.698559767416127019856730839819647371768951416015625000000000, -0.031077090678799931117159971449837030377238988876342773437500, -5.040234806716209270405215647770091891288757324218750000000000, -6.606921279942914004834619845496490597724914550781250000000000, -3.869880158236262079896050636307336390018463134765625000000000, -10.054321502209552008366699737962335348129272460937500000000000, -6.280705543488890540970714937429875135421752929687500000000000, 0.000000000000000000000000000000000000000000000000000000000000, -2.494713408178120150893164463923312723636627197265625000000000, -2.598150548864236686341655513388104736804962158203125000000000, -0.304975352295239643396485007542651146650314331054687500000000, -2.916671468480125817279713373864069581031799316406250000000000, -2.960099096648749483762230738648213446140289306640625000000000, -5.989873825712285437816717603709548711776733398437500000000000, -0.002507120169096173530054461053850900498218834400177001953125, -3.136127308188753737283605005359277129173278808593750000000000, -0.176879103699552453488053060937090776860713958740234375000000, -2.353768036988251211028000398073345422744750976562500000000000, -3.744066754776672834026385316974483430385589599609375000000000, 0.000000000000000000000000000000000000000000000000000000000000, -2.839535812544084603104010966490022838115692138671875000000000, -0.086067279673300162157190129619266372174024581909179687500000, -3.854190815670504033363386042765341699123382568359375000000000, -5.869613059277937416879922238877043128013610839843750000000000, 0.000000000000000000000000000000000000000000000000000000000000, -0.384532097536943340276849312431295402348041534423828125000000, -1.338531697560186861650777245813515037298202514648437500000000, -4.474222362274872466514352709054946899414062500000000000000000, -3.314664237037550087450199498562142252922058105468750000000000, -4.682574923715371539856278104707598686218261718750000000000000, -0.368900435688631012087768112905905582010746002197265625000000, -1.176014814002444008878001113771460950374603271484375000000000, -0.709996915609857004447746930964058265089988708496093750000000, -1.282563340904273152531800405995454639196395874023437500000000, -3.208794497707758708315850526560097932815551757812500000000000, -1.690023957076583371872402494773268699645996093750000000000000, -5.098093470692335316130083811003714799880981445312500000000000, -0.509027578151938331352255318051902577280998229980468750000000, -0.918993876681337473755206701753195375204086303710937500000000, -1.581308226517597503857359697576612234115600585937500000000000, -1.292790443930836863373201595095451921224594116210937500000000, -2.557425510595298323579527277615852653980255126953125000000000, -1.007906127076126923114429700945038348436355590820312500000000, -2.560009090805706488680471011321060359477996826171875000000000, 0.000000000000000000000000000000000000000000000000000000000000, -4.717395674310531639150667615467682480812072753906250000000000, -2.367523623737181281967423274181783199310302734375000000000000, -2.573048648630889889687978211441077291965484619140625000000000, -1.436804100526558380934716296906117349863052368164062500000000, -0.701071102975730831019518518587574362754821777343750000000000, -2.438328827816317101451204507611691951751708984375000000000000, -0.679443711102156733261381305055692791938781738281250000000000, -0.707041047215952844773312335746595636010169982910156250000000, -5.639977561836668762396129750413820147514343261718750000000000, -3.778337476933724126126890041632577776908874511718750000000000, -2.154756578276459499932116159470751881599426269531250000000000, -2.162821228909660220551813836209475994110107421875000000000000, -0.562358982058553724669991424889303743839263916015625000000000, -1.755669166607024767046141278115101158618927001953125000000000, -0.326158026142060741836559145667706616222858428955078125000000, -1.279023747338471794776637580071110278367996215820312500000000, -5.183244558647554178776317712618038058280944824218750000000000, -2.316622601837921013867571673472411930561065673828125000000000, -2.659157189193052328590738397906534373760223388671875000000000, -0.191430555333882340685036638205929193645715713500976562500000, 0.000000000000000000000000000000000000000000000000000000000000, -0.664709955358130821778672725486103445291519165039062500000000, -2.187165643480033949686003325041383504867553710937500000000000, -1.762875342696557545707491954090073704719543457031250000000000, -1.749916948420700224531287858553696423768997192382812500000000, -3.575421663722070153568211026140488684177398681640625000000000, 0.000000000000000000000000000000000000000000000000000000000000, -1.928896249393138528915869756019674241542816162109375000000000, -2.391455012103930855005273770075291395187377929687500000000000, -1.842710346617601580021528206998482346534729003906250000000000, -1.791617500319007794118419951701071113348007202148437500000000, -2.343409253862695162951013116980902850627899169921875000000000, -1.410993272797839370724659602274186909198760986328125000000000, -2.320581420206905942649200369487516582012176513671875000000000, -2.893121989774980473697496563545428216457366943359375000000000, -3.977827742728266446903262476553209125995635986328125000000000, -2.058944176423800787034679160569794476032257080078125000000000, -2.071037633074694905843671222100965678691864013671875000000000, -1.768515397703714908672623096208553761243820190429687500000000, -1.153751204177984268639534093381371349096298217773437500000000, -1.680987899482990099997437027923297137022018432617187500000000, 0.000000000000000000000000000000000000000000000000000000000000, -4.584627618010170380102863418869674205780029296875000000000000, -2.194060349407264354226754221599549055099487304687500000000000, -1.499076127310911887846600620832759886980056762695312500000000, -1.297315393792867643796284937707241624593734741210937500000000, -1.329738206325086657955125701846554875373840332031250000000000, -2.144028052451655508292560625704936683177947998046875000000000, -0.657028062796280343249577526876237243413925170898437500000000, -0.730619933776488150733996462804498150944709777832031250000000, -4.376665231519177190477876138174906373023986816406250000000000, -4.718561859232925925766721775289624929428100585937500000000000, -2.080320732081178736194715384044684469699859619140625000000000, -2.055854244595972435405428768717683851718902587890625000000000, -1.421850256682005708697147383645642548799514770507812500000000, -2.102221012532442756537420791573822498321533203125000000000000, -1.247305110167633124262920318869873881340026855468750000000000, -2.591584072043251474326552852289751172065734863281250000000000, -3.147605821582104113076638896018266677856445312500000000000000, -0.043904705171597842305875047941299271769821643829345703125000, -4.634868960235463575259018398355692625045776367187500000000000, -5.019441588675102039474040793720632791519165039062500000000000, -5.681312951243271847090454684803262352943420410156250000000000, -1.928467904013302591792466955666895955801010131835937500000000, -2.565779477876660052970692049711942672729492187500000000000000, -1.418220124080461719273671405971981585025787353515625000000000, -2.454375864191848055639866288402117788791656494140625000000000, -1.121710853164690879779641363711562007665634155273437500000000, -3.072235543110140021383358543971553444862365722656250000000000, -2.848272125086215300626690805074758827686309814453125000000000, -0.558456599237618478426270485215354710817337036132812500000000, -0.848845538512307262735134827380534261465072631835937500000000, -7.002324924918669424300787795800715684890747070312500000000000, -3.668865315739671117967191094066947698593139648437500000000000, -4.718597850559019590832576795946806669235229492187500000000000, -3.049096701706386802754877862753346562385559082031250000000000, -2.649356530974964485380951373372226953506469726562500000000000, -1.669314195717893856141245123581029474735260009765625000000000, -1.147567923673684653351756423944607377052307128906250000000000, -1.076533608421685217493291020218748599290847778320312500000000, 0.000000000000000000000000000000000000000000000000000000000000, -6.956634086757649271248737932182848453521728515625000000000000, -7.024068041375896243039278488140553236007690429687500000000000, -3.957918762987576943856993239023722708225250244140625000000000, -1.331783944951729026229259034153074026107788085937500000000000, -3.201281963147128539759478371706791222095489501953125000000000, -1.549644096147559713116947932576294988393783569335937500000000, -1.312726661492457758129148714942857623100280761718750000000000, -2.259939193445343441624117986066266894340515136718750000000000, -2.423926880572130126978436237550340592861175537109375000000000, 0.000000000000000000000000000000000000000000000000000000000000, -6.848557419252292000066972832428291440010070800781250000000000, -6.896829338845804180380127945682033896446228027343750000000000, -3.722582614455130833874818563344888389110565185546875000000000, -2.719309189565115580933252203976735472679138183593750000000000, -2.544130672523534641982223547529429197311401367187500000000000, -2.186395971313551900294669394497759640216827392578125000000000, -0.332715474789523235621402363904053345322608947753906250000000, -7.026345284034602123313106858404353260993957519531250000000000, -0.000888566530440708531556059934786162557429634034633636474609, -6.291503542654471203832144965417683124542236328125000000000000, -5.986690430272505913933400734094902873039245605468750000000000, -0.122741286268200244791160002932883799076080322265625000000000, -2.196932224286036738902794240857474505901336669921875000000000, 0.000000000000000000000000000000000000000000000000000000000000, -1.303722545566528001614869936020113527774810791015625000000000, -2.105864098995690714133388610207475721836090087890625000000000, -1.435578458464392248572494281688705086708068847656250000000000, -2.489761730430327446583760320208966732025146484375000000000000, -1.760899725099839052688821539049968123435974121093750000000000, -2.854908713800850428299327177228406071662902832031250000000000, -2.875608931369854293080834395368583500385284423828125000000000, -3.481133121051686263314195457496680319309234619140625000000000, -1.897909771509530774125096286297775804996490478515625000000000, -2.185845347988713882614320027641952037811279296875000000000000, -1.978717634408995396100294783536810427904129028320312500000000, -2.606504025680458358493751802598126232624053955078125000000000, -1.318818871830977013104302386636845767498016357421875000000000, -1.480720546667873893653677441761828958988189697265625000000000, -0.737928951383980402667361886415164917707443237304687500000000, -0.650285154216317162756411107693566009402275085449218750000000, -6.209801540532629005042508651968091726303100585937500000000000, -3.824651092041761124562526674708351492881774902343750000000000, -1.910642911045310476936265331460162997245788574218750000000000, -1.586341919151083468264573639316949993371963500976562500000000, -1.854752465261401805918239915627054870128631591796875000000000, -1.392573903203236485026650370855350047349929809570312500000000, -1.520605773895307155640921337180770933628082275390625000000000, 0.000000000000000000000000000000000000000000000000000000000000, -7.482256229504544720043668348807841539382934570312500000000000, -6.955920953990032629121742502320557832717895507812500000000000, -3.759679211363279094371137034613639116287231445312500000000000, -1.666593508702244319508167791354935616254806518554687500000000, -1.367483775157640080166743246081750839948654174804687500000000, -1.390471467634422086945278351777233183383941650390625000000000, -1.263728646463758931162146836868487298488616943359375000000000, 0.000000000000000000000000000000000000000000000000000000000000, -6.574163274461459316455602674977853894233703613281250000000000, -4.134373386461300370342542009893804788589477539062500000000000, -1.093543453498669215662175702163949608802795410156250000000000, -1.475402531411262208038692733680363744497299194335937500000000, -1.310160794679168905219057705835439264774322509765625000000000, -1.903132912453214142800561603507958352565765380859375000000000, 0.000000000000000000000000000000000000000000000000000000000000, -6.698361853186871606169461301760748028755187988281250000000000, -3.512501991875810691823289744206704199314117431640625000000000, -1.959662302151332857746979243529494851827621459960937500000000, -1.528776846501670894085123109107371419668197631835937500000000, -1.826181650981897996999236966075841337442398071289062500000000, -1.138653619844293141127877788676414638757705688476562500000000, -2.040520733384556528733355662552639842033386230468750000000000, -0.026334973760810023724054929061821894720196723937988281250000, -3.649996012338110329409346377360634505748748779296875000000000, -6.431737076661124596910212858347222208976745605468750000000000, -2.943735378782415867959798561059869825839996337890625000000000, -1.682170819948636486529380817955825477838516235351562500000000, -1.298939117547105670524842935265041887760162353515625000000000, -1.993700029844323484695678416755981743335723876953125000000000, -1.047709386165366352017258577689062803983688354492187500000000, -9.026919483738925720217594061978161334991455078125000000000000, -0.000120139208737295727770326425609681564310449175536632537842, -6.717239913861373423742406885139644145965576171875000000000000, -1.328070071947949681856471215724013745784759521484375000000000, -1.944037101159571623298916165367700159549713134765625000000000, -1.182903563582415440436079734354279935359954833984375000000000, -1.257763426233626136152565777592826634645462036132812500000000, -0.983486006261584555510069094452774152159690856933593750000000, -0.468412958710625382252601411892101168632507324218750000000000, -8.468651996251450597696930344682186841964721679687500000000000, -4.139800124064825226355424092616885900497436523437500000000000, -3.931454793849565199082007893593981862068176269531250000000000, -2.021497077106750417385683249449357390403747558593750000000000, -1.823127657291570224984411652258131653070449829101562500000000, -1.337296127555923419549799291417002677917480468750000000000000, -0.897180799465370992784585268964292481541633605957031250000000, -0.986040730030275258677363581227837130427360534667968750000000, -0.466889729967265909582607719130464829504489898681640625000000, -9.011593207854545539703394751995801925659179687500000000000000, -4.850867560763419739089385984698310494422912597656250000000000, -1.112896046865470500719652591214980930089950561523437500000000, -1.085333923798379451852724741911515593528747558593750000000000, -1.377898281389317913792069703049492090940475463867187500000000, -2.609739901377524873282709449995309114456176757812500000000000, 0.000000000000000000000000000000000000000000000000000000000000, -6.495767620713909451524159521795809268951416015625000000000000, -2.305511012885385291326656442834064364433288574218750000000000, -1.779624881481258524829058842442464083433151245117187500000000, -1.465377313319132568381064629647880792617797851562500000000000, -2.026515779816368212351562760886736214160919189453125000000000, -1.208685317218918919834891312348190695047378540039062500000000, -2.677909755533927516069070406956598162651062011718750000000000, -1.220088311290825400234894004825036972761154174804687500000000, -0.349847015838577246604756965098204091191291809082031250000000, -4.261980401619341662922124669421464204788208007812500000000000, -1.422943413816338820154783206817228347063064575195312500000000, -1.509540111140063478600836788245942443609237670898437500000000, -0.646472693195343506289418655796907842159271240234375000000000, 0.000000000000000000000000000000000000000000000000000000000000, -9.815478075212435982166425674222409725189208984375000000000000, -4.933023088148108747930109529988840222358703613281250000000000, -0.007285766694735069763655399555091207730583846569061279296875, 0.000000000000000000000000000000000000000000000000000000000000, 0.000000000000000000000000000000000000000000000000000000000000, 0.0, 0.0, -0.000115716530591520062594239337538937206772970966994762420654, -9.064424917075021070900220365729182958602905273437500000000000, }; #ifdef __cplusplus } #endif } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/isoMath.h
.h
2,736
88
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include <cmath> #include <random> #if !defined(ISOSPEC_G_FACT_TABLE_SIZE) // 10M should be enough for anyone, right? // Actually, yes. If anyone tries to input a molecule that has more than 10M atoms, // he deserves to get an exception thrown in his face. OpenMS guys don't want to alloc // a table of 10M to memoize the necessary values though, use something smaller for them. #if ISOSPEC_BUILDING_OPENMS #define ISOSPEC_G_FACT_TABLE_SIZE 1024 #else #define ISOSPEC_G_FACT_TABLE_SIZE 1024*1024*10 #endif #endif namespace IsoSpec { extern double* g_lfact_table; static inline double minuslogFactorial(int n) { if (n < 2) return 0.0; #if ISOSPEC_BUILDING_OPENMS if (n >= ISOSPEC_G_FACT_TABLE_SIZE) return -lgamma(n+1); #endif if (g_lfact_table[n] == 0.0) g_lfact_table[n] = -lgamma(n+1); return g_lfact_table[n]; } const double pi = 3.14159265358979323846264338328; const double logpi = 1.144729885849400174143427351353058711647294812915311571513623071472137769884826079783623270275489708; double NormalCDFInverse(double p); double NormalCDFInverse(double p, double mean, double stdev); double NormalCDF(double x, double mean, double stdev); double NormalPDF(double x, double mean = 0.0, double stdev = 1.0); // Returns lower incomplete gamma function of a/2, x, where a is int and > 0. double LowerIncompleteGamma2(int a, double x); // Returns y such that LowerIncompleteGamma2(a, y) == x. Approximately. double InverseLowerIncompleteGamma2(int a, double x); // Computes the inverse Cumulative Distribution Funcion of the Chi-Square distribution with k degrees of freedom inline double InverseChiSquareCDF2(int k, double x) { return InverseLowerIncompleteGamma2(k, x*tgamma(static_cast<double>(k)/2.0)) * 2.0; } extern std::mt19937 random_gen; extern std::uniform_real_distribution<double> stdunif; inline double rdvariate_beta_1_b(double b, std::mt19937& rgen = random_gen) { return 1.0 - pow(stdunif(rgen), 1.0/b); } size_t rdvariate_binom(size_t tries, double succ_prob, std::mt19937& rgen = random_gen); } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/btrd.h
.h
5,984
207
/* This file was taken from Boost, as permitted by Boost licence, * with slight modifications. The reason is: we don't want to introduce * dependency on the whole Boost just for this one thing. * * Source: boost random/binomial_distribution.hpp header file, at version 1.71 * * Copyright Steven Watanabe 2010 * 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) * * See http://www.boost.org for most recent version including documentation. * */ #pragma once #include "isoMath.h" #include <cstdlib> #include <cstdint> #include <cmath> #include <limits> namespace IsoSpec { typedef double RealType; typedef int64_t IntType; static const RealType btrd_binomial_table[10] = { 0.08106146679532726, 0.04134069595540929, 0.02767792568499834, 0.02079067210376509, 0.01664469118982119, 0.01387612882307075, 0.01189670994589177, 0.01041126526197209, 0.009255462182712733, 0.008330563433362871 }; /** * The binomial distribution is an integer valued distribution with * two parameters, @c t and @c p. The values of the distribution * are within the range [0,t]. * * The distribution function is * \f$\displaystyle P(k) = {t \choose k}p^k(1-p)^{t-k}\f$. * * The algorithm used is the BTRD algorithm described in * * @blockquote * "The generation of binomial random variates", Wolfgang Hormann, * Journal of Statistical Computation and Simulation, Volume 46, * Issue 1 & 2 April 1993 , pages 101 - 110 * @endblockquote */ // computes the correction factor for the Stirling approximation // for log(k!) static RealType fc(IntType k) { if(k < 10) { return btrd_binomial_table[k]; } else { RealType ikp1 = RealType(1) / (k + 1); return (RealType(1)/12 - (RealType(1)/360 - (RealType(1)/1260)*(ikp1*ikp1))*(ikp1*ikp1))*ikp1; } } IntType btrd(IntType _t, RealType p, IntType m, std::mt19937& urng = random_gen) { using std::floor; using std::abs; using std::log; RealType btrd_r = p/(1-p); RealType btrd_nr = (_t+1)*btrd_r; RealType btrd_npq = _t*p*(1-p); RealType sqrt_npq = sqrt(btrd_npq); RealType btrd_b = 1.15 + 2.53 * sqrt_npq; RealType btrd_a = -0.0873 + 0.0248*btrd_b + 0.01*p; RealType btrd_c = _t*p + 0.5; RealType btrd_alpha = (2.83 + 5.1/btrd_b) * sqrt_npq; RealType btrd_v_r = 0.92 - 4.2/btrd_b; RealType btrd_u_rv_r = 0.86*btrd_v_r; while(true) { RealType u; RealType v = stdunif(urng); if(v <= btrd_u_rv_r) { u = v/btrd_v_r - 0.43; return static_cast<IntType>(floor( (2*btrd_a/(0.5 - abs(u)) + btrd_b)*u + btrd_c)); } if(v >= btrd_v_r) { u = stdunif(urng) - 0.5; } else { u = v/btrd_v_r - 0.93; u = ((u < 0)? -0.5 : 0.5) - u; v = stdunif(urng) * btrd_v_r; } RealType us = 0.5 - abs(u); IntType k = static_cast<IntType>(floor((2*btrd_a/us + btrd_b)*u + btrd_c)); if(k < 0 || k > _t) continue; v = v*btrd_alpha/(btrd_a/(us*us) + btrd_b); RealType km = abs(k - m); if(km <= 15) { RealType f = 1; if(m < k) { IntType i = m; do { ++i; f = f*(btrd_nr/i - btrd_r); } while(i != k); } else if(m > k) { IntType i = k; do { ++i; v = v*(btrd_nr/i - btrd_r); } while(i != m); } if(v <= f) return k; else continue; } else { // final acceptance/rejection v = log(v); RealType rho = (km/btrd_npq)*(((km/3. + 0.625)*km + 1./6)/btrd_npq + 0.5); RealType t = -km*km/(2*btrd_npq); if(v < t - rho) return k; if(v > t + rho) continue; IntType nm = _t - m + 1; RealType h = (m + 0.5)*log((m + 1)/(btrd_r*nm)) + fc(m) + fc(_t - m); IntType nk = _t - k + 1; if(v <= h + (_t+1)*log(static_cast<RealType>(nm)/nk) + (k + 0.5)*log(nk*btrd_r/(k+1)) - fc(k) - fc(_t - k)) { return k; } else { continue; } } } } IntType invert(IntType t, RealType p, std::mt19937& urng = random_gen) { RealType q = 1 - p; RealType s = p / q; RealType a = (t + 1) * s; RealType r = pow((1 - p), static_cast<RealType>(t)); RealType u = stdunif(urng); IntType x = 0; while(u > r) { u = u - r; ++x; RealType r1 = ((a/x) - s) * r; // If r gets too small then the round-off error // becomes a problem. At this point, p(i) is // decreasing exponentially, so if we just call // it 0, it's close enough. Note that the // minimum value of q_n is about 1e-7, so we // may need to be a little careful to make sure that // we don't terminate the first time through the loop // for float. (Hence the test that r is decreasing) if(r1 < std::numeric_limits<RealType>::epsilon() && r1 < r) { break; } r = r1; } return x; } IntType boost_binomial_distribution_variate(IntType t_arg, RealType p_arg, std::mt19937& urng = random_gen) { bool other_side = p_arg > 0.5; RealType fake_p = other_side ? 1.0 - p_arg : p_arg; IntType m = static_cast<IntType>((t_arg+1)*fake_p); IntType result; if(m < 11) result = invert(t_arg, fake_p, urng); else result = btrd(t_arg, fake_p, m, urng); if(other_side) return t_arg - result; else return result; } } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/isoMath.cpp
.cpp
3,612
164
/* * This file has been released into public domain by John D. Cook * and is used here with some slight modifications (which are hereby * also released into public domain), * * This file is part of IsoSpec. */ // NOLINT(legal/copyright) #include <cmath> #include <cstdlib> #include "isoMath.h" #include "platform.h" #include "btrd.h" namespace IsoSpec { void release_g_lfact_table() { #if ISOSPEC_GOT_MMAN munmap(g_lfact_table, ISOSPEC_G_FACT_TABLE_SIZE*sizeof(double)); #else free(g_lfact_table); #endif } double* alloc_lfact_table() { double* ret; # if ISOSPEC_GOT_MMAN ret = reinterpret_cast<double*>(mmap(nullptr, sizeof(double)*ISOSPEC_G_FACT_TABLE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0)); #else ret = reinterpret_cast<double*>(calloc(ISOSPEC_G_FACT_TABLE_SIZE, sizeof(double))); #endif std::atexit(release_g_lfact_table); return ret; } double* g_lfact_table = alloc_lfact_table(); double RationalApproximation(double t) { // Abramowitz and Stegun formula 26.2.23. // The absolute value of the error should be less than 4.5 e-4. double c[] = {2.515517, 0.802853, 0.010328}; double d[] = {1.432788, 0.189269, 0.001308}; return t - ((c[2]*t + c[1])*t + c[0]) / (((d[2]*t + d[1])*t + d[0])*t + 1.0); } double NormalCDFInverse(double p) { if (p < 0.5) return -RationalApproximation( sqrt(-2.0*log(p)) ); else return RationalApproximation( sqrt(-2.0*log(1-p)) ); } double NormalCDFInverse(double p, double mean, double stdev) { return mean + stdev * NormalCDFInverse(p); } double NormalCDF(double x, double mean, double stdev) { x = (x-mean)/stdev * 0.7071067811865476; // constants double a1 = 0.254829592; double a2 = -0.284496736; double a3 = 1.421413741; double a4 = -1.453152027; double a5 = 1.061405429; double p = 0.3275911; // Save the sign of x int sign = 1; if (x < 0) sign = -1; x = fabs(x); // A&S formula 7.1.26 double t = 1.0/(1.0 + p*x); double y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x); return 0.5*(1.0 + sign*y); } double NormalPDF(double x, double mean, double stdev) { double two_variance = stdev * stdev * 2.0; double delta = x-mean; return exp( -delta*delta / two_variance ) / sqrt( two_variance * pi ); } const double sqrt_pi = 1.772453850905516027298167483341145182798; double LowerIncompleteGamma2(int a, double x) { double base; double exp_minus_x = exp(-x); double current_s; if(a % 2 == 0) { base = 1 - exp_minus_x; current_s = 1.0; a--; } else { base = sqrt_pi * erf(sqrt(x)); current_s = 0.5; } a = a/2; for(; a; a--) { base = base * current_s - pow(x, current_s) * exp_minus_x; current_s += 1.0; } return base; } double InverseLowerIncompleteGamma2(int a, double x) { double l = 0.0; double p = tgamma(a); double s; do { s = (l+p) / 2.0; double v = LowerIncompleteGamma2(a, s); if (x < v) p = s; else l = s; } while((p-l)*1000.0 > p); return s; } std::random_device random_dev; std::mt19937 random_gen(random_dev()); std::uniform_real_distribution<double> stdunif(0.0, 1.0); size_t rdvariate_binom(size_t tries, double succ_prob, std::mt19937& rgen) { if (succ_prob >= 1.0) return tries; return IsoSpec::boost_binomial_distribution_variate(tries, succ_prob, rgen); } } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/fixedEnvelopes.cpp
.cpp
17,964
598
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include "fixedEnvelopes.h" #include <limits> #include "isoMath.h" namespace IsoSpec { FixedEnvelope::FixedEnvelope(const FixedEnvelope& other) : _masses(array_copy<double>(other._masses, other._confs_no)), _probs(array_copy<double>(other._probs, other._confs_no)), _confs(array_copy<int>(other._confs, other._confs_no*other.allDim)), _confs_no(other._confs_no), allDim(other.allDim), sorted_by_mass(other.sorted_by_mass), sorted_by_prob(other.sorted_by_prob), total_prob(other.total_prob) {} FixedEnvelope::FixedEnvelope(FixedEnvelope&& other) : _masses(other._masses), _probs(other._probs), _confs(other._confs), _confs_no(other._confs_no), allDim(other.allDim), sorted_by_mass(other.sorted_by_mass), sorted_by_prob(other.sorted_by_prob), total_prob(other.total_prob) { other._masses = nullptr; other._probs = nullptr; other._confs = nullptr; other._confs_no = 0; other.total_prob = 0.0; } FixedEnvelope::FixedEnvelope(double* in_masses, double* in_probs, size_t in_confs_no, bool masses_sorted, bool probs_sorted, double _total_prob) : _masses(in_masses), _probs(in_probs), _confs(nullptr), _confs_no(in_confs_no), allDim(0), sorted_by_mass(masses_sorted), sorted_by_prob(probs_sorted), total_prob(_total_prob) {} FixedEnvelope FixedEnvelope::operator+(const FixedEnvelope& other) const { double* nprobs = reinterpret_cast<double*>(malloc(sizeof(double) * (_confs_no+other._confs_no))); if(nprobs == nullptr) throw std::bad_alloc(); double* nmasses = reinterpret_cast<double*>(malloc(sizeof(double) * (_confs_no+other._confs_no))); if(nmasses == nullptr) { free(nprobs); throw std::bad_alloc(); } memcpy(nprobs, _probs, sizeof(double) * _confs_no); memcpy(nmasses, _masses, sizeof(double) * _confs_no); memcpy(nprobs+_confs_no, other._probs, sizeof(double) * other._confs_no); memcpy(nmasses+_confs_no, other._masses, sizeof(double) * other._confs_no); return FixedEnvelope(nmasses, nprobs, _confs_no + other._confs_no); } FixedEnvelope FixedEnvelope::operator*(const FixedEnvelope& other) const { double* nprobs = reinterpret_cast<double*>(malloc(sizeof(double) * _confs_no * other._confs_no)); if(nprobs == nullptr) throw std::bad_alloc(); // deepcode ignore CMemoryLeak: It's not a memleak: the memory is passed to FixedEnvelope which // deepcode ignore CMemoryLeak: takes ownership of it, and will properly free() it in destructor. double* nmasses = reinterpret_cast<double*>(malloc(sizeof(double) * _confs_no * other._confs_no)); if(nmasses == nullptr) { free(nprobs); throw std::bad_alloc(); } size_t tgt_idx = 0; for(size_t ii = 0; ii < _confs_no; ii++) for(size_t jj = 0; jj < other._confs_no; jj++) { nprobs[tgt_idx] = _probs[ii] * other._probs[jj]; nmasses[tgt_idx] = _masses[ii] + other._masses[jj]; tgt_idx++; } return FixedEnvelope(nmasses, nprobs, tgt_idx); } void FixedEnvelope::sort_by_mass() { if(sorted_by_mass) return; sort_by(_masses); sorted_by_mass = true; sorted_by_prob = false; } void FixedEnvelope::sort_by_prob() { if(sorted_by_prob) return; sort_by(_probs); sorted_by_prob = true; sorted_by_mass = false; } template<typename T> void reorder_array(T* arr, size_t* order, size_t size, bool can_destroy = false) { if(!can_destroy) { size_t* order_c = new size_t[size]; memcpy(order_c, order, sizeof(size_t)*size); order = order_c; } for(size_t ii = 0; ii < size; ii++) while(order[ii] != ii) { std::swap(arr[ii], arr[order[ii]]); std::swap(order[order[ii]], order[ii]); } if(!can_destroy) delete[] order; } void FixedEnvelope::sort_by(double* order) { size_t* indices = new size_t[_confs_no]; for(size_t ii = 0; ii < _confs_no; ii++) indices[ii] = ii; std::sort<size_t*>(indices, indices + _confs_no, TableOrder<double>(order)); size_t* inverse = new size_t[_confs_no]; for(size_t ii = 0; ii < _confs_no; ii++) inverse[indices[ii]] = ii; delete[] indices; reorder_array(_masses, inverse, _confs_no); reorder_array(_probs, inverse, _confs_no); if(_confs != nullptr) { int* swapspace = new int[allDim]; for(size_t ii = 0; ii < _confs_no; ii++) while(order[ii] != ii) { memcpy(swapspace, &_confs[ii*allDim], allDimSizeofInt); memcpy(&_confs[ii*allDim], &_confs[inverse[ii]*allDim], allDimSizeofInt); memcpy(&_confs[inverse[ii]*allDim], swapspace, allDimSizeofInt); } delete[] swapspace; } delete[] inverse; } double FixedEnvelope::get_total_prob() { if(std::isnan(total_prob)) { total_prob = 0.0; for(size_t ii = 0; ii < _confs_no; ii++) total_prob += _probs[ii]; } return total_prob; } void FixedEnvelope::scale(double factor) { for(size_t ii = 0; ii < _confs_no; ii++) _probs[ii] *= factor; total_prob *= factor; } void FixedEnvelope::normalize() { double tp = get_total_prob(); if(tp != 1.0) { scale(1.0/tp); total_prob = 1.0; } } FixedEnvelope FixedEnvelope::LinearCombination(const std::vector<const FixedEnvelope*>& spectra, const std::vector<double>& intensities) { return LinearCombination(spectra.data(), intensities.data(), spectra.size()); } FixedEnvelope FixedEnvelope::LinearCombination(const FixedEnvelope* const * spectra, const double* intensities, size_t size) { size_t ret_size = 0; for(size_t ii = 0; ii < size; ii++) ret_size += spectra[ii]->_confs_no; double* newprobs = reinterpret_cast<double*>(malloc(sizeof(double)*ret_size)); if(newprobs == nullptr) throw std::bad_alloc(); double* newmasses = reinterpret_cast<double*>(malloc(sizeof(double)*ret_size)); if(newmasses == nullptr) { free(newprobs); throw std::bad_alloc(); } size_t cntr = 0; for(size_t ii = 0; ii < size; ii++) { double mul = intensities[ii]; for(size_t jj = 0; jj < spectra[ii]->_confs_no; jj++) newprobs[jj+cntr] = spectra[ii]->_probs[jj] * mul; memcpy(newmasses + cntr, spectra[ii]->_masses, sizeof(double) * spectra[ii]->_confs_no); cntr += spectra[ii]->_confs_no; } return FixedEnvelope(newmasses, newprobs, cntr); } double FixedEnvelope::WassersteinDistance(FixedEnvelope& other) { double ret = 0.0; if((get_total_prob()*0.999 > other.get_total_prob()) || (other.get_total_prob() > get_total_prob()*1.001)) throw std::logic_error("Spectra must be normalized before computing Wasserstein Distance"); if(_confs_no == 0 || other._confs_no == 0) return 0.0; sort_by_mass(); other.sort_by_mass(); size_t idx_this = 0; size_t idx_other = 0; double acc_prob = 0.0; double last_point = 0.0; while(idx_this < _confs_no && idx_other < other._confs_no) { if(_masses[idx_this] < other._masses[idx_other]) { ret += (_masses[idx_this] - last_point) * std::abs(acc_prob); acc_prob += _probs[idx_this]; last_point = _masses[idx_this]; idx_this++; } else { ret += (other._masses[idx_other] - last_point) * std::abs(acc_prob); acc_prob -= other._probs[idx_other]; last_point = other._masses[idx_other]; idx_other++; } } acc_prob = std::abs(acc_prob); while(idx_this < _confs_no) { ret += (_masses[idx_this] - last_point) * acc_prob; acc_prob -= _probs[idx_this]; last_point = _masses[idx_this]; idx_this++; } while(idx_other < other._confs_no) { ret += (other._masses[idx_other] - last_point) * acc_prob; acc_prob -= other._probs[idx_other]; last_point = other._masses[idx_other]; idx_other++; } return ret; } double FixedEnvelope::OrientedWassersteinDistance(FixedEnvelope& other) { double ret = 0.0; if((get_total_prob()*0.999 > other.get_total_prob()) || (other.get_total_prob() > get_total_prob()*1.001)) throw std::logic_error("Spectra must be normalized before computing Wasserstein Distance"); if(_confs_no == 0 || other._confs_no == 0) return 0.0; sort_by_mass(); other.sort_by_mass(); size_t idx_this = 0; size_t idx_other = 0; double acc_prob = 0.0; double last_point = 0.0; while(idx_this < _confs_no && idx_other < other._confs_no) { if(_masses[idx_this] < other._masses[idx_other]) { ret += (_masses[idx_this] - last_point) * acc_prob; acc_prob += _probs[idx_this]; last_point = _masses[idx_this]; idx_this++; } else { ret += (other._masses[idx_other] - last_point) * acc_prob; acc_prob -= other._probs[idx_other]; last_point = other._masses[idx_other]; idx_other++; } } while(idx_this < _confs_no) { ret += (_masses[idx_this] - last_point) * acc_prob; acc_prob -= _probs[idx_this]; last_point = _masses[idx_this]; idx_this++; } while(idx_other < other._confs_no) { ret += (other._masses[idx_other] - last_point) * acc_prob; acc_prob -= other._probs[idx_other]; last_point = other._masses[idx_other]; idx_other++; } return ret; } FixedEnvelope FixedEnvelope::bin(double bin_width, double middle) { sort_by_mass(); FixedEnvelope ret; if(_confs_no == 0) return ret; ret.reallocate_memory<false>(ISOSPEC_INIT_TABLE_SIZE); ret.current_size = ISOSPEC_INIT_TABLE_SIZE; size_t ii = 0; double half_width = 0.5*bin_width; double hwmm = half_width-middle; while(ii < _confs_no) { double current_bin_middle = floor((_masses[ii]+hwmm)/bin_width)*bin_width + middle; double current_bin_end = current_bin_middle + half_width; double bin_prob = 0.0; while(ii < _confs_no && _masses[ii] <= current_bin_end) { bin_prob += _probs[ii]; ii++; } ret.store_conf(current_bin_middle, bin_prob); } return ret; } template<bool tgetConfs> void FixedEnvelope::reallocate_memory(size_t new_size) { // FIXME: Handle overflow gracefully here. It definitely could happen for people still stuck on 32 bits... _masses = reinterpret_cast<double*>(realloc(_masses, new_size * sizeof(double))); if(_masses == nullptr) throw std::bad_alloc(); tmasses = _masses + _confs_no; _probs = reinterpret_cast<double*>(realloc(_probs, new_size * sizeof(double))); if(_probs == nullptr) throw std::bad_alloc(); tprobs = _probs + _confs_no; constexpr_if(tgetConfs) { _confs = reinterpret_cast<int*>(realloc(_confs, new_size * allDimSizeofInt)); if(_confs == nullptr) throw std::bad_alloc(); tconfs = _confs + (allDim * _confs_no); } } void FixedEnvelope::slow_reallocate_memory(size_t new_size) { // FIXME: Handle overflow gracefully here. It definitely could happen for people still stuck on 32 bits... _masses = reinterpret_cast<double*>(realloc(_masses, new_size * sizeof(double))); if(_masses == nullptr) throw std::bad_alloc(); tmasses = _masses + _confs_no; _probs = reinterpret_cast<double*>(realloc(_probs, new_size * sizeof(double))); if(_probs == nullptr) throw std::bad_alloc(); tprobs = _probs + _confs_no; if(_confs != nullptr) { _confs = reinterpret_cast<int*>(realloc(_confs, new_size * allDimSizeofInt)); if(_confs == nullptr) throw std::bad_alloc(); tconfs = _confs + (allDim * _confs_no); } } template<bool tgetConfs> void FixedEnvelope::threshold_init(Iso&& iso, double threshold, bool absolute) { IsoThresholdGenerator generator(std::move(iso), threshold, absolute); size_t tab_size = generator.count_confs(); this->allDim = generator.getAllDim(); this->allDimSizeofInt = this->allDim * sizeof(int); this->reallocate_memory<tgetConfs>(tab_size); double* ttmasses = this->_masses; double* ttprobs = this->_probs; ISOSPEC_MAYBE_UNUSED int* ttconfs; constexpr_if(tgetConfs) ttconfs = _confs; while(generator.advanceToNextConfiguration()) { *ttmasses = generator.mass(); ttmasses++; *ttprobs = generator.prob(); ttprobs++; constexpr_if(tgetConfs) { generator.get_conf_signature(ttconfs); ttconfs += allDim; } } this->_confs_no = tab_size; } template void FixedEnvelope::threshold_init<true>(Iso&& iso, double threshold, bool absolute); template void FixedEnvelope::threshold_init<false>(Iso&& iso, double threshold, bool absolute); template<bool tgetConfs> void FixedEnvelope::total_prob_init(Iso&& iso, double target_total_prob, bool optimize) { if(target_total_prob <= 0.0) return; if(target_total_prob >= 1.0) { threshold_init<tgetConfs>(std::move(iso), 0.0, true); return; } current_size = ISOSPEC_INIT_TABLE_SIZE; IsoLayeredGenerator generator(std::move(iso), 1000, 1000, true, std::min<double>(target_total_prob, 0.9999)); this->allDim = generator.getAllDim(); this->allDimSizeofInt = this->allDim*sizeof(int); this->reallocate_memory<tgetConfs>(ISOSPEC_INIT_TABLE_SIZE); size_t last_switch = 0; double prob_at_last_switch = 0.0; double prob_so_far = 0.0; double layer_delta; const double sum_above = log1p(-target_total_prob) - 2.3025850929940455; // log(0.1); do { // Store confs until we accumulate more prob than needed - and, if optimizing, // store also the rest of the last layer while(generator.advanceToNextConfigurationWithinLayer()) { this->template addConfILG<tgetConfs>(generator); prob_so_far += *(tprobs-1); // The just-stored probability if(prob_so_far >= target_total_prob) { if (optimize) { while(generator.advanceToNextConfigurationWithinLayer()) this->template addConfILG<tgetConfs>(generator); break; } else return; } } if(prob_so_far >= target_total_prob) break; last_switch = this->_confs_no; prob_at_last_switch = prob_so_far; layer_delta = sum_above - log1p(-prob_so_far); layer_delta = (std::max)((std::min)(layer_delta, -0.1), -5.0); } while(generator.nextLayer(layer_delta)); if(!optimize || prob_so_far <= target_total_prob) return; // Right. We have extra configurations and we have been asked to produce an optimal p-set, so // now we shall trim unneeded configurations, using an algorithm dubbed "quicktrim" // - similar to the quickselect algorithm, except that we use the cumulative sum of elements // left of pivot to decide whether to go left or right, instead of the positional index. // We'll be sorting by the prob array, permuting the other ones in parallel. int* conf_swapspace = nullptr; constexpr_if(tgetConfs) conf_swapspace = reinterpret_cast<int*>(malloc(this->allDimSizeofInt)); size_t start = last_switch; size_t end = this->_confs_no; double sum_to_start = prob_at_last_switch; while(start < end) { // Partition part size_t len = end - start; #if ISOSPEC_BUILDING_R size_t pivot = len/2 + start; #else size_t pivot = random_gen() % len + start; // Using Mersenne twister directly - we don't // need a very uniform distribution just for pivot // selection #endif double pprob = this->_probs[pivot]; swap<tgetConfs>(pivot, end-1, conf_swapspace); double new_csum = sum_to_start; size_t loweridx = start; for(size_t ii = start; ii < end-1; ii++) if(this->_probs[ii] > pprob) { swap<tgetConfs>(ii, loweridx, conf_swapspace); new_csum += this->_probs[loweridx]; loweridx++; } swap<tgetConfs>(end-1, loweridx, conf_swapspace); // Selection part if(new_csum < target_total_prob) { start = loweridx + 1; sum_to_start = new_csum + this->_probs[loweridx]; } else end = loweridx; } constexpr_if(tgetConfs) free(conf_swapspace); if(end <= current_size/2) // Overhead in memory of 2x or more, shrink to fit this->template reallocate_memory<tgetConfs>(end); this->_confs_no = end; } template void FixedEnvelope::total_prob_init<true>(Iso&& iso, double target_total_prob, bool optimize); template void FixedEnvelope::total_prob_init<false>(Iso&& iso, double target_total_prob, bool optimize); } // namespace IsoSpec
C++
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/element_tables.h
.h
1,617
49
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include <stddef.h> namespace IsoSpec { #ifdef __cplusplus extern "C" { #endif #define ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES 292 extern const size_t isospec_number_of_isotopic_entries; extern const int elem_table_ID[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const int elem_table_atomicNo[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const double elem_table_probability[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const double elem_table_mass[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const double elem_table_massNo[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const int elem_table_extraNeutrons[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const char* elem_table_element[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const char* elem_table_symbol[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const bool elem_table_Radioactive[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; extern const double elem_table_log_probability[ISOSPEC_NUMBER_OF_ISOTOPIC_ENTRIES]; #ifdef __cplusplus } #endif } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/fixedEnvelopes.h
.h
6,588
205
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #pragma once #include <cstdlib> #include <algorithm> #include <vector> #include <utility> #include "isoSpec++.h" #define ISOSPEC_INIT_TABLE_SIZE 1024 namespace IsoSpec { class ISOSPEC_EXPORT_SYMBOL FixedEnvelope { protected: double* _masses; double* _probs; int* _confs; size_t _confs_no; int allDim; bool sorted_by_mass; bool sorted_by_prob; double total_prob; size_t current_size; double* tmasses; double* tprobs; int* tconfs; int allDimSizeofInt; public: ISOSPEC_FORCE_INLINE FixedEnvelope() : _masses(nullptr), _probs(nullptr), _confs(nullptr), _confs_no(0), allDim(0), sorted_by_mass(false), sorted_by_prob(false), total_prob(0.0), current_size(0), allDimSizeofInt(0) // Deliberately not initializing tmasses, tprobs, tconfs {}; FixedEnvelope(const FixedEnvelope& other); FixedEnvelope(FixedEnvelope&& other); FixedEnvelope(double* masses, double* probs, size_t confs_no, bool masses_sorted = false, bool probs_sorted = false, double _total_prob = NAN); virtual ~FixedEnvelope() { free(_masses); free(_probs); free(_confs); }; FixedEnvelope operator+(const FixedEnvelope& other) const; FixedEnvelope operator*(const FixedEnvelope& other) const; inline size_t confs_no() const { return _confs_no; } inline int getAllDim() const { return allDim; } inline const double* masses() const { return _masses; } inline const double* probs() const { return _probs; } inline const int* confs() const { return _confs; } inline double* release_masses() { double* ret = _masses; _masses = nullptr; return ret; } inline double* release_probs() { double* ret = _probs; _probs = nullptr; return ret; } inline int* release_confs() { int* ret = _confs; _confs = nullptr; return ret; } inline double mass(size_t i) const { return _masses[i]; } inline double prob(size_t i) const { return _probs[i]; } inline const int* conf(size_t i) const { return _confs + i*allDim; } void sort_by_mass(); void sort_by_prob(); double get_total_prob(); void scale(double factor); void normalize(); double WassersteinDistance(FixedEnvelope& other); double OrientedWassersteinDistance(FixedEnvelope& other); static FixedEnvelope LinearCombination(const std::vector<const FixedEnvelope*>& spectra, const std::vector<double>& intensities); static FixedEnvelope LinearCombination(const FixedEnvelope* const * spectra, const double* intensities, size_t size); FixedEnvelope bin(double bin_width = 1.0, double middle = 0.0); private: void sort_by(double* order); protected: template<typename T, bool tgetConfs> ISOSPEC_FORCE_INLINE void store_conf(const T& generator) { *tmasses = generator.mass(); tmasses++; *tprobs = generator.prob(); tprobs++; constexpr_if(tgetConfs) { generator.get_conf_signature(tconfs); tconfs += allDim; } } ISOSPEC_FORCE_INLINE void store_conf(double _mass, double _prob) { if(_confs_no == current_size) { current_size *= 2; reallocate_memory<false>(current_size); } *tprobs = _prob; *tmasses = _mass; tprobs++; tmasses++; _confs_no++; } template<bool tgetConfs> ISOSPEC_FORCE_INLINE void swap(size_t idx1, size_t idx2, ISOSPEC_MAYBE_UNUSED int* conf_swapspace) { std::swap<double>(this->_probs[idx1], this->_probs[idx2]); std::swap<double>(this->_masses[idx1], this->_masses[idx2]); constexpr_if(tgetConfs) { int* c1 = this->_confs + (idx1*this->allDim); int* c2 = this->_confs + (idx2*this->allDim); memcpy(conf_swapspace, c1, this->allDimSizeofInt); memcpy(c1, c2, this->allDimSizeofInt); memcpy(c2, conf_swapspace, this->allDimSizeofInt); } } template<bool tgetConfs> void reallocate_memory(size_t new_size); void slow_reallocate_memory(size_t new_size); public: template<bool tgetConfs> void threshold_init(Iso&& iso, double threshold, bool absolute); template<bool tgetConfs> void addConfILG(const IsoLayeredGenerator& generator) { if(this->_confs_no == this->current_size) { this->current_size *= 2; this->template reallocate_memory<tgetConfs>(this->current_size); } this->template store_conf<IsoLayeredGenerator, tgetConfs>(generator); this->_confs_no++; } template<bool tgetConfs> void total_prob_init(Iso&& iso, double target_prob, bool trim); static FixedEnvelope FromThreshold(Iso&& iso, double threshold, bool absolute, bool tgetConfs = false) { FixedEnvelope ret; if(tgetConfs) ret.threshold_init<true>(std::move(iso), threshold, absolute); else ret.threshold_init<false>(std::move(iso), threshold, absolute); return ret; } inline static FixedEnvelope FromThreshold(const Iso& iso, double _threshold, bool _absolute, bool tgetConfs = false) { return FromThreshold(Iso(iso, false), _threshold, _absolute, tgetConfs); } static FixedEnvelope FromTotalProb(Iso&& iso, double target_total_prob, bool optimize, bool tgetConfs = false) { FixedEnvelope ret; if(tgetConfs) ret.total_prob_init<true>(std::move(iso), target_total_prob, optimize); else ret.total_prob_init<false>(std::move(iso), target_total_prob, optimize); return ret; } inline static FixedEnvelope FromTotalProb(const Iso& iso, double _target_total_prob, bool _optimize, bool tgetConfs = false) { return FromTotalProb(Iso(iso, false), _target_total_prob, _optimize, tgetConfs); } }; } // namespace IsoSpec
Unknown
3D
OpenMS/OpenMS
src/openms/extern/IsoSpec/IsoSpec/unity-build.cpp
.cpp
1,514
41
/* * Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek. * * This file is part of IsoSpec. * * IsoSpec is free software: you can redistribute it and/or modify * it under the terms of the Simplified ("2-clause") BSD licence. * * IsoSpec 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. * * You should have received a copy of the Simplified BSD Licence * along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>. */ #include "platform.h" #if !ISOSPEC_BUILDING_R #if !ISOSPEC_GOT_SYSTEM_MMAN && ISOSPEC_GOT_MMAN #include "mman.cpp" // NOLINT(build/include) #endif // A poor-man's replacement for LTO. We're small enough that we can do that. And // ignore cpplint's complaints about it. #include "allocator.cpp" // NOLINT(build/include) #include "dirtyAllocator.cpp" // NOLINT(build/include) #include "isoSpec++.cpp" // NOLINT(build/include) #include "isoMath.cpp" // NOLINT(build/include) #include "marginalTrek++.cpp" // NOLINT(build/include) #include "operators.cpp" // NOLINT(build/include) #include "element_tables.cpp" // NOLINT(build/include) #include "fasta.cpp" // NOLINT(build/include) #include "cwrapper.cpp" // NOLINT(build/include) #include "fixedEnvelopes.cpp" // NOLINT(build/include) #include "misc.cpp" // NOLINT(build/include) #endif
C++