hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f6605e5e38bacbdc4d3c19b8c840d58deb22f7a0 | 2,939 | cpp | C++ | cpp/example_code/ses/list_receipt_filters.cpp | onehitcombo/aws-doc-sdk-examples | 03e2e0c5dee75c5decbbb99e849c51417521fd82 | [
"Apache-2.0"
] | 3 | 2021-01-19T20:23:17.000Z | 2021-01-19T21:38:59.000Z | cpp/example_code/ses/list_receipt_filters.cpp | onehitcombo/aws-doc-sdk-examples | 03e2e0c5dee75c5decbbb99e849c51417521fd82 | [
"Apache-2.0"
] | null | null | null | cpp/example_code/ses/list_receipt_filters.cpp | onehitcombo/aws-doc-sdk-examples | 03e2e0c5dee75c5decbbb99e849c51417521fd82 | [
"Apache-2.0"
] | 2 | 2019-12-27T13:58:00.000Z | 2020-05-21T18:35:40.000Z | //snippet-sourcedescription:[list_receipt_filters.cpp demonstrates how to list the Amazon SES IP filters for an AWS account.]
//snippet-service:[ses]
//snippet-keyword:[Amazon Simple Email Service]
//snippet-keyword:[C++]
//snippet-keyword:[Code Sample]
//snippet-sourcetype:[full-example]
//snippet-sourceauthor:[AWS]
/*
Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
This file is licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License. A copy of
the License is located at
http://aws.amazon.com/apache2.0/
This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
#include <aws/core/Aws.h>
#include <aws/email/SESClient.h>
#include <aws/email/model/ListReceiptFiltersRequest.h>
#include <aws/email/model/ListReceiptFiltersResult.h>
#include <aws/email/model/ReceiptFilterPolicy.h>
#include <iostream>
int main(int argc, char **argv)
{
Aws::SDKOptions options;
Aws::InitAPI(options);
{
Aws::SES::SESClient ses;
Aws::SES::Model::ListReceiptFiltersRequest lrf_req;
auto lrf_out = ses.ListReceiptFilters(lrf_req);
if (!lrf_out.IsSuccess())
{
std::cout << "Error retrieving IP address filters: "
<< lrf_out.GetError().GetMessage() << std::endl;
}
else
{
// Output filter details
std::cout << "Amazon Simple Email Service\n";
std::cout << "Email Receiving: IP Address Filters:\n\n";
auto filters = lrf_out.GetResult().GetFilters();
if (filters.empty())
{
std::cout << "No filters defined" << std::endl;
}
else
{
for (auto filter : filters)
{
std::cout << "Name: " << filter.GetName() << "\n";
std::cout << " Policy: ";
auto ip_filter = filter.GetIpFilter();
switch (ip_filter.GetPolicy())
{
case Aws::SES::Model::ReceiptFilterPolicy::Block:
std::cout << "Block\n";
break;
case Aws::SES::Model::ReceiptFilterPolicy::Allow:
std::cout << "Allow\n";
break;
default:
std::cout << "NOT SET\n";
break;
}
std::cout << " CIDR: " << ip_filter.GetCidr() << std::endl;
}
}
}
}
Aws::ShutdownAPI(options);
return 0;
}
| 35.841463 | 126 | 0.536917 | onehitcombo |
f6609f6d03e7978270d4bf9a093b009cf884c0cd | 3,145 | cpp | C++ | Src/OpenGlRenderMechanism.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | Src/OpenGlRenderMechanism.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | Src/OpenGlRenderMechanism.cpp | Remag/GraphicsInversed | 6dff72130891010774c37d1e44080261db3cdb8e | [
"MIT"
] | null | null | null | #include <common.h>
#pragma hdrstop
#include <OpenGlRenderMechanism.h>
#include <GlContextManager.h>
#include <GlWindowUtils.h>
#include <DrawEnums.h>
#include <State.h>
#include <Framebuffer.h>
namespace Gin {
//////////////////////////////////////////////////////////////////////////
COpenGlRenderMechanism::COpenGlRenderMechanism( CGlContextManager& _glContextManager ) :
glContextManager( _glContextManager )
{
backgroundBrush = ::CreateSolidBrush( RGB( 0, 0, 0 ) );
}
COpenGlRenderMechanism::~COpenGlRenderMechanism()
{
::DeleteObject( backgroundBrush );
}
void COpenGlRenderMechanism::AttachNewWindow( const CGlWindow& newWindow )
{
assert( newWindow.IsCreated() );
targetWindow = &newWindow;
OnWindowResize( newWindow.WindowSize() );
}
void COpenGlRenderMechanism::ActivateWindowTarget()
{
glContextManager.SetContextTarget( targetWindow->GetDeviceContext() );
}
void COpenGlRenderMechanism::SetBackgroundColor( CColor newValue )
{
backgroundColor = newValue;
::DeleteObject( backgroundBrush );
backgroundBrush = ::CreateSolidBrush( RGB( newValue.R, newValue.G, newValue.B ) );
}
void COpenGlRenderMechanism::OnWindowResize( CVector2<int> )
{
}
LRESULT COpenGlRenderMechanism::OnEraseBackground( HWND, WPARAM wParam, LPARAM )
{
RECT bgRect{ INT_MIN, INT_MIN, INT_MAX, INT_MAX };
HDC bgDC = reinterpret_cast<HDC>( wParam );
::FillRect( bgDC, &bgRect, backgroundBrush );
return 1;
}
void COpenGlRenderMechanism::OnDraw( const IState& currentState ) const
{
const auto windowSize = targetWindow->WindowSize();
CViewportSwitcher::SetBaseViewport( CVector2<int>{}, windowSize );
// Set the clear values.
gl::ClearColor( backgroundColor.GetRed(), backgroundColor.GetGreen(), backgroundColor.GetBlue(), backgroundColor.GetAlpha() );
gl::ClearDepth( glContextManager.GetDepthZFar() );
gl::Enable( gl::DEPTH_TEST );
gl::Disable( gl::BLEND );
// Clear the buffer.
gl::Clear( gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT | gl::STENCIL_BUFFER_BIT );
currentState.Draw( COpenGlRenderParameters( *targetWindow ) );
}
void COpenGlRenderMechanism::OnPostDraw() const
{
::SwapBuffers( targetWindow->GetDeviceContext() );
}
LRESULT COpenGlRenderMechanism::OnPaintMessage( HWND window, WPARAM wParam, LPARAM lParam, const IState& ) const
{
return ::DefWindowProc( window, WM_PAINT, wParam, lParam );
}
CArray<BYTE> COpenGlRenderMechanism::ReadScreenBuffer( TTexelFormat format, CVector2<int>& bufferSize ) const
{
assert( CFramebufferSwitcher::GetReadTarget() == 0 );
const auto viewportSize = CViewportSwitcher::GetViewportSize();
const int rowSize = CeilTo( 3 * viewportSize.X(), 4 );
const int dataSize = rowSize * viewportSize.Y();
CArray<BYTE> data;
data.IncreaseSizeNoInitialize( dataSize );
gl::PixelStorei( AT_Pack, 4 );
gl::ReadPixels( 0, 0, viewportSize.X(), viewportSize.Y(), format, TDT_UnsignedByte, data.Ptr() );
gl::PixelStorei( AT_Pack, 1 );
bufferSize = viewportSize;
return data;
}
//////////////////////////////////////////////////////////////////////////
} // namespace Gin.
| 30.240385 | 128 | 0.694118 | Remag |
f6631eb3bb96639cf6dceb69da8b1f396690a38b | 472 | inl | C++ | include/CoreLib/LogSystem/EntityLogger.inl | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | 45 | 2018-09-29T14:16:04.000Z | 2022-03-10T18:53:58.000Z | include/CoreLib/LogSystem/EntityLogger.inl | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | 46 | 2019-12-22T17:29:41.000Z | 2022-03-20T14:15:06.000Z | include/CoreLib/LogSystem/EntityLogger.inl | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | 19 | 2018-09-29T11:53:25.000Z | 2022-01-14T17:00:07.000Z | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#include <CoreLib/LogSystem/EntityLogger.hpp>
namespace bw
{
inline EntityLogger::EntityLogger(Ndk::EntityHandle entity, const Logger& logParent) :
LoggerProxy(logParent),
m_entity(std::move(entity))
{
}
inline void EntityLogger::UpdateEntity(Ndk::EntityHandle newEntity)
{
m_entity = newEntity;
}
}
| 23.6 | 87 | 0.756356 | AntoineJT |
f6647e6a84681938cef7fe76635a019510ae7d6a | 11,230 | cpp | C++ | llvm/lib/Target/Mips/MipsRegisterInfo.cpp | haohua-li/t-sgx-mirror | 49188063f3cb5300cda8a03255cfe800e8266ace | [
"MIT"
] | 26 | 2017-04-18T15:51:16.000Z | 2022-03-29T07:03:37.000Z | llvm/lib/Target/Mips/MipsRegisterInfo.cpp | haohua-li/t-sgx-mirror | 49188063f3cb5300cda8a03255cfe800e8266ace | [
"MIT"
] | 2 | 2017-10-27T21:29:04.000Z | 2019-06-12T01:23:38.000Z | 3.7.0/llvm-3.7.0.src/lib/Target/Mips/MipsRegisterInfo.cpp | androm3da/clang_sles | 2ba6d0711546ad681883c42dfb8661b842806695 | [
"MIT"
] | 9 | 2017-10-02T19:54:36.000Z | 2021-11-22T00:48:18.000Z | //===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#include "MipsRegisterInfo.h"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsInstrInfo.h"
#include "MipsMachineFunction.h"
#include "MipsSubtarget.h"
#include "MipsTargetMachine.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;
#define DEBUG_TYPE "mips-reg-info"
#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"
MipsRegisterInfo::MipsRegisterInfo() : MipsGenRegisterInfo(Mips::RA) {}
unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
const TargetRegisterClass *
MipsRegisterInfo::getPointerRegClass(const MachineFunction &MF,
unsigned Kind) const {
MipsABIInfo ABI = MF.getSubtarget<MipsSubtarget>().getABI();
return ABI.ArePtrs64bit() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass;
}
unsigned
MipsRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
MachineFunction &MF) const {
switch (RC->getID()) {
default:
return 0;
case Mips::GPR32RegClassID:
case Mips::GPR64RegClassID:
case Mips::DSPRRegClassID: {
const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
return 28 - TFI->hasFP(MF);
}
case Mips::FGR32RegClassID:
return 32;
case Mips::AFGR64RegClassID:
return 16;
case Mips::FGR64RegClassID:
return 32;
}
}
//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//
/// Mips Callee Saved Registers
const MCPhysReg *
MipsRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
const MipsSubtarget &Subtarget = MF->getSubtarget<MipsSubtarget>();
if (Subtarget.isSingleFloat())
return CSR_SingleFloatOnly_SaveList;
if (Subtarget.isABI_N64())
return CSR_N64_SaveList;
if (Subtarget.isABI_N32())
return CSR_N32_SaveList;
if (Subtarget.isFP64bit())
return CSR_O32_FP64_SaveList;
if (Subtarget.isFPXX())
return CSR_O32_FPXX_SaveList;
return CSR_O32_SaveList;
}
const uint32_t *
MipsRegisterInfo::getCallPreservedMask(const MachineFunction &MF,
CallingConv::ID) const {
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
if (Subtarget.isSingleFloat())
return CSR_SingleFloatOnly_RegMask;
if (Subtarget.isABI_N64())
return CSR_N64_RegMask;
if (Subtarget.isABI_N32())
return CSR_N32_RegMask;
if (Subtarget.isFP64bit())
return CSR_O32_FP64_RegMask;
if (Subtarget.isFPXX())
return CSR_O32_FPXX_RegMask;
return CSR_O32_RegMask;
}
const uint32_t *MipsRegisterInfo::getMips16RetHelperMask() {
return CSR_Mips16RetHelper_RegMask;
}
BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
static const MCPhysReg ReservedGPR32[] = {
Mips::ZERO, Mips::K0, Mips::K1, Mips::SP
};
static const MCPhysReg ReservedGPR64[] = {
Mips::ZERO_64, Mips::K0_64, Mips::K1_64, Mips::SP_64
};
BitVector Reserved(getNumRegs());
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
typedef TargetRegisterClass::const_iterator RegIter;
for (unsigned I = 0; I < array_lengthof(ReservedGPR32); ++I)
Reserved.set(ReservedGPR32[I]);
// Reserve registers for the NaCl sandbox.
if (Subtarget.isTargetNaCl()) {
Reserved.set(Mips::T6); // Reserved for control flow mask.
Reserved.set(Mips::T7); // Reserved for memory access mask.
Reserved.set(Mips::T8); // Reserved for thread pointer.
}
for (unsigned I = 0; I < array_lengthof(ReservedGPR64); ++I)
Reserved.set(ReservedGPR64[I]);
// For mno-abicalls, GP is a program invariant!
if (!Subtarget.isABICalls()) {
Reserved.set(Mips::GP);
Reserved.set(Mips::GP_64);
}
if (Subtarget.isFP64bit()) {
// Reserve all registers in AFGR64.
for (RegIter Reg = Mips::AFGR64RegClass.begin(),
EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
} else {
// Reserve all registers in FGR64.
for (RegIter Reg = Mips::FGR64RegClass.begin(),
EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg)
Reserved.set(*Reg);
}
// Reserve FP if this function should have a dedicated frame pointer register.
if (Subtarget.getFrameLowering()->hasFP(MF)) {
if (Subtarget.inMips16Mode())
Reserved.set(Mips::S0);
else {
Reserved.set(Mips::FP);
Reserved.set(Mips::FP_64);
// Reserve the base register if we need to both realign the stack and
// allocate variable-sized objects at runtime. This should test the
// same conditions as MipsFrameLowering::hasBP().
if (needsStackRealignment(MF) &&
MF.getFrameInfo()->hasVarSizedObjects()) {
Reserved.set(Mips::S7);
Reserved.set(Mips::S7_64);
}
}
}
// Reserve hardware registers.
Reserved.set(Mips::HWR29);
// Reserve DSP control register.
Reserved.set(Mips::DSPPos);
Reserved.set(Mips::DSPSCount);
Reserved.set(Mips::DSPCarry);
Reserved.set(Mips::DSPEFI);
Reserved.set(Mips::DSPOutFlag);
// Reserve MSA control registers.
Reserved.set(Mips::MSAIR);
Reserved.set(Mips::MSACSR);
Reserved.set(Mips::MSAAccess);
Reserved.set(Mips::MSASave);
Reserved.set(Mips::MSAModify);
Reserved.set(Mips::MSARequest);
Reserved.set(Mips::MSAMap);
Reserved.set(Mips::MSAUnmap);
// Reserve RA if in mips16 mode.
if (Subtarget.inMips16Mode()) {
const MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
Reserved.set(Mips::RA);
Reserved.set(Mips::RA_64);
Reserved.set(Mips::T0);
Reserved.set(Mips::T1);
if (MF.getFunction()->hasFnAttribute("saveS2") || MipsFI->hasSaveS2())
Reserved.set(Mips::S2);
}
// Reserve GP if small section is used.
if (Subtarget.useSmallSection()) {
Reserved.set(Mips::GP);
Reserved.set(Mips::GP_64);
}
if (Subtarget.isABI_O32() && !Subtarget.useOddSPReg()) {
for (const auto &Reg : Mips::OddSPRegClass)
Reserved.set(Reg);
}
return Reserved;
}
bool
MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
return true;
}
bool
MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
return true;
}
// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
unsigned FIOperandNum, RegScavenger *RS) const {
MachineInstr &MI = *II;
MachineFunction &MF = *MI.getParent()->getParent();
DEBUG(errs() << "\nFunction : " << MF.getName() << "\n";
errs() << "<--------->\n" << MI);
int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
uint64_t stackSize = MF.getFrameInfo()->getStackSize();
int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);
DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
<< "spOffset : " << spOffset << "\n"
<< "stackSize : " << stackSize << "\n");
eliminateFI(MI, FIOperandNum, FrameIndex, stackSize, spOffset);
}
unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
bool IsN64 =
static_cast<const MipsTargetMachine &>(MF.getTarget()).getABI().IsN64();
if (Subtarget.inMips16Mode())
return TFI->hasFP(MF) ? Mips::S0 : Mips::SP;
else
return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
(IsN64 ? Mips::SP_64 : Mips::SP);
}
bool MipsRegisterInfo::canRealignStack(const MachineFunction &MF) const {
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
unsigned FP = Subtarget.isGP32bit() ? Mips::FP : Mips::FP_64;
unsigned BP = Subtarget.isGP32bit() ? Mips::S7 : Mips::S7_64;
// Support dynamic stack realignment only for targets with standard encoding.
if (!Subtarget.hasStandardEncoding())
return false;
// We can't perform dynamic stack realignment if we can't reserve the
// frame pointer register.
if (!MF.getRegInfo().canReserveReg(FP))
return false;
// We can realign the stack if we know the maximum call frame size and we
// don't have variable sized objects.
if (Subtarget.getFrameLowering()->hasReservedCallFrame(MF))
return true;
// We have to reserve the base pointer register in the presence of variable
// sized objects.
return MF.getRegInfo().canReserveReg(BP);
}
bool MipsRegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
const MipsSubtarget &Subtarget = MF.getSubtarget<MipsSubtarget>();
const MachineFrameInfo *MFI = MF.getFrameInfo();
bool CanRealign = canRealignStack(MF);
// Avoid realigning functions that explicitly do not want to be realigned.
// Normally, we should report an error when a function should be dynamically
// realigned but also has the attribute no-realign-stack. Unfortunately,
// with this attribute, MachineFrameInfo clamps each new object's alignment
// to that of the stack's alignment as specified by the ABI. As a result,
// the information of whether we have objects with larger alignment
// requirement than the stack's alignment is already lost at this point.
if (MF.getFunction()->hasFnAttribute("no-realign-stack"))
return false;
const Function *F = MF.getFunction();
if (F->hasFnAttribute(Attribute::StackAlignment)) {
#ifdef DEBUG
if (!CanRealign)
DEBUG(dbgs() << "It's not possible to realign the stack of the function: "
<< F->getName() << "\n");
#endif
return CanRealign;
}
unsigned StackAlignment = Subtarget.getFrameLowering()->getStackAlignment();
if (MFI->getMaxAlignment() > StackAlignment) {
#ifdef DEBUG
if (!CanRealign)
DEBUG(dbgs() << "It's not possible to realign the stack of the function: "
<< F->getName() << "\n");
#endif
return CanRealign;
}
return false;
}
| 32.270115 | 80 | 0.675779 | haohua-li |
f665aafd47ad0225a86edafc3ab16d93540c4b4a | 2,598 | cpp | C++ | Engine/Source/Editor/BehaviorTreeEditor/Private/BehaviorTreeEditorCommands.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Editor/BehaviorTreeEditor/Private/BehaviorTreeEditorCommands.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Editor/BehaviorTreeEditor/Private/BehaviorTreeEditorCommands.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "BehaviorTreeEditorPrivatePCH.h"
#include "BehaviorTreeEditorCommands.h"
#define LOCTEXT_NAMESPACE "BehaviorTreeEditorCommands"
FBTCommonCommands::FBTCommonCommands()
: TCommands<FBTCommonCommands>("BTEditor.Common", LOCTEXT("Common", "Common"), NAME_None, FEditorStyle::GetStyleSetName())
{
}
void FBTCommonCommands::RegisterCommands()
{
UI_COMMAND(SearchBT, "Search", "Search this Behavior Tree.", EUserInterfaceActionType::Button, FInputChord(EModifierKey::Control, EKeys::F));
UI_COMMAND(NewBlackboard, "New Blackboard", "Create a new Blackboard Data Asset", EUserInterfaceActionType::Button, FInputChord());
}
FBTDebuggerCommands::FBTDebuggerCommands()
: TCommands<FBTDebuggerCommands>("BTEditor.Debugger", LOCTEXT("Debugger", "Debugger"), NAME_None, FEditorStyle::GetStyleSetName())
{
}
void FBTDebuggerCommands::RegisterCommands()
{
UI_COMMAND(BackInto, "Back: Into", "Show state from previous step, can go into subtrees", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(BackOver, "Back: Over", "Show state from previous step, don't go into subtrees", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(ForwardInto, "Forward: Into", "Show state from next step, can go into subtrees", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(ForwardOver, "Forward: Over", "Show state from next step, don't go into subtrees", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(StepOut, "Step Out", "Show state from next step, leave current subtree", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(PausePlaySession, "Pause", "Pause simulation", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(ResumePlaySession, "Resume", "Resume simulation", EUserInterfaceActionType::Button, FInputChord() );
UI_COMMAND(StopPlaySession, "Stop", "Stop simulation", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(CurrentValues, "Current", "View current values", EUserInterfaceActionType::RadioButton, FInputChord());
UI_COMMAND(SavedValues, "Saved", "View saved values", EUserInterfaceActionType::RadioButton, FInputChord());
}
FBTBlackboardCommands::FBTBlackboardCommands()
: TCommands<FBTBlackboardCommands>("BTEditor.Blackboard", LOCTEXT("Blackboard", "Blackboard"), NAME_None, FEditorStyle::GetStyleSetName())
{
}
void FBTBlackboardCommands::RegisterCommands()
{
UI_COMMAND(DeleteEntry, "Delete", "Delete this blackboard entry", EUserInterfaceActionType::Button, FInputChord(EKeys::Platform_Delete));
}
#undef LOCTEXT_NAMESPACE
| 50.941176 | 144 | 0.787529 | PopCap |
f666731692c1409b15ae70912db29faa51c966a4 | 5,634 | cpp | C++ | MonoNative/mscorlib/System/Security/Permissions/mscorlib_System_Security_Permissions_StrongNameIdentityPermissionAttribute.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative/mscorlib/System/Security/Permissions/mscorlib_System_Security_Permissions_StrongNameIdentityPermissionAttribute.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative/mscorlib/System/Security/Permissions/mscorlib_System_Security_Permissions_StrongNameIdentityPermissionAttribute.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | #include <mscorlib/System/Security/Permissions/mscorlib_System_Security_Permissions_StrongNameIdentityPermissionAttribute.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace Security
{
namespace Permissions
{
//Public Methods
mscorlib::System::Security::IPermission StrongNameIdentityPermissionAttribute::CreatePermission()
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "CreatePermission", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Security::IPermission(__result__);
}
//Get Set Properties Methods
// Get/Set:Name
mscorlib::System::String StrongNameIdentityPermissionAttribute::get_Name() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "get_Name", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::String(__result__);
}
void StrongNameIdentityPermissionAttribute::set_Name(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "set_Name", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get/Set:PublicKey
mscorlib::System::String StrongNameIdentityPermissionAttribute::get_PublicKey() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "get_PublicKey", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::String(__result__);
}
void StrongNameIdentityPermissionAttribute::set_PublicKey(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "set_PublicKey", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get/Set:Version
mscorlib::System::String StrongNameIdentityPermissionAttribute::get_Version() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "get_Version", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::String(__result__);
}
void StrongNameIdentityPermissionAttribute::set_Version(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
Global::InvokeMethod("mscorlib", "System.Security.Permissions", "StrongNameIdentityPermissionAttribute", 0, NULL, "set_Version", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get/Set:Unrestricted
mscorlib::System::Boolean StrongNameIdentityPermissionAttribute::get_Unrestricted() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "SecurityAttribute", 0, NULL, "get_Unrestricted", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
void StrongNameIdentityPermissionAttribute::set_Unrestricted(mscorlib::System::Boolean value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = reinterpret_cast<void*>(value);
Global::InvokeMethod("mscorlib", "System.Security.Permissions", "SecurityAttribute", 0, NULL, "set_Unrestricted", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get/Set:Action
mscorlib::System::Security::Permissions::SecurityAction::__ENUM__ StrongNameIdentityPermissionAttribute::get_Action() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.Permissions", "SecurityAttribute", 0, NULL, "get_Action", __native_object__, 0, NULL, NULL, NULL);
return static_cast<mscorlib::System::Security::Permissions::SecurityAction::__ENUM__>(*(mscorlib::System::Int32*)mono_object_unbox(__result__));
}
void StrongNameIdentityPermissionAttribute::set_Action(mscorlib::System::Security::Permissions::SecurityAction::__ENUM__ value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
mscorlib::System::Int32 __param_value__ = value;
__parameters__[0] = &__param_value__;
Global::InvokeMethod("mscorlib", "System.Security.Permissions", "SecurityAttribute", 0, NULL, "set_Action", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get:TypeId
mscorlib::System::Object StrongNameIdentityPermissionAttribute::get_TypeId() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Attribute", 0, NULL, "get_TypeId", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Object(__result__);
}
}
}
}
}
| 45.804878 | 205 | 0.739084 | brunolauze |
f6667fc5ddf352b78ed6ee9132a338f7719e614e | 514 | cpp | C++ | ObjectOrientedProgramming/AccountClassInheritance/Checking_Account.cpp | Sebery/CPP-Practice-Projects | cf200e7753be79d13042f9f9de666d25c8215d69 | [
"MIT"
] | null | null | null | ObjectOrientedProgramming/AccountClassInheritance/Checking_Account.cpp | Sebery/CPP-Practice-Projects | cf200e7753be79d13042f9f9de666d25c8215d69 | [
"MIT"
] | null | null | null | ObjectOrientedProgramming/AccountClassInheritance/Checking_Account.cpp | Sebery/CPP-Practice-Projects | cf200e7753be79d13042f9f9de666d25c8215d69 | [
"MIT"
] | null | null | null | //
// Created by Sebastian on 26/11/2020.
//
#include "Checking_Account.h"
Checking_Account::Checking_Account(std::string name, double balance, double fee)
: Account{name, balance}, fee{fee} {
}
bool Checking_Account::withdraw(double amount) {
amount += fee;
return Account::withdraw(amount);
}
std::ostream &operator<<(std::ostream &os, const Checking_Account &account) {
os << "[Checking_Account: " << account.name << " : " << account.balance << ", " << account.fee << "]";
return os;
} | 24.47619 | 106 | 0.657588 | Sebery |
f667ecc9d030534ef1c83377b5eafff7f562714e | 36,610 | hpp | C++ | openjdk11/src/hotspot/share/runtime/perfData.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | openjdk11/src/hotspot/share/runtime/perfData.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | openjdk11/src/hotspot/share/runtime/perfData.hpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_RUNTIME_PERFDATA_HPP
#define SHARE_VM_RUNTIME_PERFDATA_HPP
#include "memory/allocation.hpp"
#include "runtime/perfMemory.hpp"
#include "runtime/timer.hpp"
template <typename T> class GrowableArray;
/* jvmstat global and subsystem counter name space - enumeration value
* serve as an index into the PerfDataManager::_name_space[] array
* containing the corresponding name space string. Only the top level
* subsystem name spaces are represented here.
*/
enum CounterNS {
// top level name spaces
JAVA_NS,
COM_NS,
SUN_NS,
// subsystem name spaces
JAVA_GC, // Garbage Collection name spaces
COM_GC,
SUN_GC,
JAVA_CI, // Compiler name spaces
COM_CI,
SUN_CI,
JAVA_CLS, // Class Loader name spaces
COM_CLS,
SUN_CLS,
JAVA_RT, // Runtime name spaces
COM_RT,
SUN_RT,
JAVA_OS, // Operating System name spaces
COM_OS,
SUN_OS,
JAVA_THREADS, // Threads System name spaces
COM_THREADS,
SUN_THREADS,
JAVA_PROPERTY, // Java Property name spaces
COM_PROPERTY,
SUN_PROPERTY,
NULL_NS,
COUNTERNS_LAST = NULL_NS
};
/*
* Classes to support access to production performance data
*
* The PerfData class structure is provided for creation, access, and update
* of performance data (a.k.a. instrumentation) in a specific memory region
* which is possibly accessible as shared memory. Although not explicitly
* prevented from doing so, developers should not use the values returned
* by accessor methods to make algorithmic decisions as they are potentially
* extracted from a shared memory region. Although any shared memory region
* created is with appropriate access restrictions, allowing read-write access
* only to the principal that created the JVM, it is believed that a the
* shared memory region facilitates an easier attack path than attacks
* launched through mechanisms such as /proc. For this reason, it is
* recommended that data returned by PerfData accessor methods be used
* cautiously.
*
* There are three variability classifications of performance data
* Constants - value is written to the PerfData memory once, on creation
* Variables - value is modifiable, with no particular restrictions
* Counters - value is monotonically changing (increasing or decreasing)
*
* The performance data items can also have various types. The class
* hierarchy and the structure of the memory region are designed to
* accommodate new types as they are needed. Types are specified in
* terms of Java basic types, which accommodates client applications
* written in the Java programming language. The class hierarchy is:
*
* - PerfData (Abstract)
* - PerfLong (Abstract)
* - PerfLongConstant (alias: PerfConstant)
* - PerfLongVariant (Abstract)
* - PerfLongVariable (alias: PerfVariable)
* - PerfLongCounter (alias: PerfCounter)
*
* - PerfByteArray (Abstract)
* - PerfString (Abstract)
* - PerfStringVariable
* - PerfStringConstant
*
*
* As seen in the class hierarchy, the initially supported types are:
*
* Long - performance data holds a Java long type
* ByteArray - performance data holds an array of Java bytes
* used for holding C++ char arrays.
*
* The String type is derived from the ByteArray type.
*
* A PerfData subtype is not required to provide an implementation for
* each variability classification. For example, the String type provides
* Variable and Constant variability classifications in the PerfStringVariable
* and PerfStringConstant classes, but does not provide a counter type.
*
* Performance data are also described by a unit of measure. Units allow
* client applications to make reasonable decisions on how to treat
* performance data generically, preventing the need to hard-code the
* specifics of a particular data item in client applications. The current
* set of units are:
*
* None - the data has no units of measure
* Bytes - data is measured in bytes
* Ticks - data is measured in clock ticks
* Events - data is measured in events. For example,
* the number of garbage collection events or the
* number of methods compiled.
* String - data is not numerical. For example,
* the java command line options
* Hertz - data is a frequency
*
* The performance counters also provide a support attribute, indicating
* the stability of the counter as a programmatic interface. The support
* level is also implied by the name space in which the counter is created.
* The counter name space support conventions follow the Java package, class,
* and property support conventions:
*
* java.* - stable, supported interface
* com.sun.* - unstable, supported interface
* sun.* - unstable, unsupported interface
*
* In the above context, unstable is a measure of the interface support
* level, not the implementation stability level.
*
* Currently, instances of PerfData subtypes are considered to have
* a life time equal to that of the VM and are managed by the
* PerfDataManager class. All constructors for the PerfData class and
* its subtypes have protected constructors. Creation of PerfData
* instances is performed by invoking various create methods on the
* PerfDataManager class. Users should not attempt to delete these
* instances as the PerfDataManager class expects to perform deletion
* operations on exit of the VM.
*
* Examples:
*
* Creating performance counter that holds a monotonically increasing
* long data value with units specified in U_Bytes in the "java.gc.*"
* name space.
*
* PerfLongCounter* foo_counter;
*
* foo_counter = PerfDataManager::create_long_counter(JAVA_GC, "foo",
* PerfData::U_Bytes,
* optionalInitialValue,
* CHECK);
* foo_counter->inc();
*
* Creating a performance counter that holds a variably change long
* data value with units specified in U_Bytes in the "com.sun.ci
* name space.
*
* PerfLongVariable* bar_variable;
* bar_variable = PerfDataManager::create_long_variable(COM_CI, "bar",
.* PerfData::U_Bytes,
* optionalInitialValue,
* CHECK);
*
* bar_variable->inc();
* bar_variable->set_value(0);
*
* Creating a performance counter that holds a constant string value in
* the "sun.cls.*" name space.
*
* PerfDataManager::create_string_constant(SUN_CLS, "foo", string, CHECK);
*
* Although the create_string_constant() factory method returns a pointer
* to the PerfStringConstant object, it can safely be ignored. Developers
* are not encouraged to access the string constant's value via this
* pointer at this time due to security concerns.
*
* Creating a performance counter in an arbitrary name space that holds a
* value that is sampled by the StatSampler periodic task.
*
* PerfDataManager::create_counter("foo.sampled", PerfData::U_Events,
* &my_jlong, CHECK);
*
* In this example, the PerfData pointer can be ignored as the caller
* is relying on the StatSampler PeriodicTask to sample the given
* address at a regular interval. The interval is defined by the
* PerfDataSamplingInterval global variable, and is applied on
* a system wide basis, not on an per-counter basis.
*
* Creating a performance counter in an arbitrary name space that utilizes
* a helper object to return a value to the StatSampler via the take_sample()
* method.
*
* class MyTimeSampler : public PerfLongSampleHelper {
* public:
* jlong take_sample() { return os::elapsed_counter(); }
* };
*
* PerfDataManager::create_counter(SUN_RT, "helped",
* PerfData::U_Ticks,
* new MyTimeSampler(), CHECK);
*
* In this example, a subtype of PerfLongSampleHelper is instantiated
* and its take_sample() method is overridden to perform whatever
* operation is necessary to generate the data sample. This method
* will be called by the StatSampler at a regular interval, defined
* by the PerfDataSamplingInterval global variable.
*
* As before, PerfSampleHelper is an alias for PerfLongSampleHelper.
*
* For additional uses of PerfData subtypes, see the utility classes
* PerfTraceTime and PerfTraceTimedEvent below.
*
* Always-on non-sampled counters can be created independent of
* the UsePerfData flag. Counters will be created on the c-heap
* if UsePerfData is false.
*
* Until further notice, all PerfData objects should be created and
* manipulated within a guarded block. The guard variable is
* UsePerfData, a product flag set to true by default. This flag may
* be removed from the product in the future.
*
*/
class PerfData : public CHeapObj<mtInternal> {
friend class StatSampler; // for access to protected void sample()
friend class PerfDataManager; // for access to protected destructor
friend class VMStructs;
public:
// the Variability enum must be kept in synchronization with the
// the com.sun.hotspot.perfdata.Variability class
enum Variability {
V_Constant = 1,
V_Monotonic = 2,
V_Variable = 3,
V_last = V_Variable
};
// the Units enum must be kept in synchronization with the
// the com.sun.hotspot.perfdata.Units class
enum Units {
U_None = 1,
U_Bytes = 2,
U_Ticks = 3,
U_Events = 4,
U_String = 5,
U_Hertz = 6,
U_Last = U_Hertz
};
// Miscellaneous flags
enum Flags {
F_None = 0x0,
F_Supported = 0x1 // interface is supported - java.* and com.sun.*
};
private:
char* _name;
Variability _v;
Units _u;
bool _on_c_heap;
Flags _flags;
PerfDataEntry* _pdep;
protected:
void *_valuep;
PerfData(CounterNS ns, const char* name, Units u, Variability v);
virtual ~PerfData();
// create the entry for the PerfData item in the PerfData memory region.
// this region is maintained separately from the PerfData objects to
// facilitate its use by external processes.
void create_entry(BasicType dtype, size_t dsize, size_t dlen = 0);
// sample the data item given at creation time and write its value
// into the its corresponding PerfMemory location.
virtual void sample() = 0;
public:
// returns a boolean indicating the validity of this object.
// the object is valid if and only if memory in PerfMemory
// region was successfully allocated.
inline bool is_valid() { return _valuep != NULL; }
// returns a boolean indicating whether the underlying object
// was allocated in the PerfMemory region or on the C heap.
inline bool is_on_c_heap() { return _on_c_heap; }
// returns a pointer to a char* containing the name of the item.
// The pointer returned is the pointer to a copy of the name
// passed to the constructor, not the pointer to the name in the
// PerfData memory region. This redundancy is maintained for
// security reasons as the PerfMemory region may be in shared
// memory.
const char* name() { return _name; }
// returns the variability classification associated with this item
Variability variability() { return _v; }
// returns the units associated with this item.
Units units() { return _u; }
// returns the flags associated with this item.
Flags flags() { return _flags; }
// returns the address of the data portion of the item in the
// PerfData memory region.
inline void* get_address() { return _valuep; }
// returns the value of the data portion of the item in the
// PerfData memory region formatted as a string.
virtual int format(char* cp, int length) = 0;
};
/*
* PerfLongSampleHelper, and its alias PerfSamplerHelper, is a base class
* for helper classes that rely upon the StatSampler periodic task to
* invoke the take_sample() method and write the value returned to its
* appropriate location in the PerfData memory region.
*/
class PerfLongSampleHelper : public CHeapObj<mtInternal> {
public:
virtual jlong take_sample() = 0;
};
typedef PerfLongSampleHelper PerfSampleHelper;
/*
* PerfLong is the base class for the various Long PerfData subtypes.
* it contains implementation details that are common among its derived
* types.
*/
class PerfLong : public PerfData {
protected:
PerfLong(CounterNS ns, const char* namep, Units u, Variability v);
public:
int format(char* buffer, int length);
// returns the value of the data portion of the item in the
// PerfData memory region.
inline jlong get_value() { return *(jlong*)_valuep; }
};
/*
* The PerfLongConstant class, and its alias PerfConstant, implement
* a PerfData subtype that holds a jlong data value that is set upon
* creation of an instance of this class. This class provides no
* methods for changing the data value stored in PerfData memory region.
*/
class PerfLongConstant : public PerfLong {
friend class PerfDataManager; // for access to protected constructor
private:
// hide sample() - no need to sample constants
void sample() { }
protected:
PerfLongConstant(CounterNS ns, const char* namep, Units u,
jlong initial_value=0)
: PerfLong(ns, namep, u, V_Constant) {
if (is_valid()) *(jlong*)_valuep = initial_value;
}
};
typedef PerfLongConstant PerfConstant;
/*
* The PerfLongVariant class, and its alias PerfVariant, implement
* a PerfData subtype that holds a jlong data value that can be modified
* in an unrestricted manner. This class provides the implementation details
* for common functionality among its derived types.
*/
class PerfLongVariant : public PerfLong {
protected:
jlong* _sampled;
PerfLongSampleHelper* _sample_helper;
PerfLongVariant(CounterNS ns, const char* namep, Units u, Variability v,
jlong initial_value=0)
: PerfLong(ns, namep, u, v) {
if (is_valid()) *(jlong*)_valuep = initial_value;
}
PerfLongVariant(CounterNS ns, const char* namep, Units u, Variability v,
jlong* sampled);
PerfLongVariant(CounterNS ns, const char* namep, Units u, Variability v,
PerfLongSampleHelper* sample_helper);
void sample();
public:
inline void inc() { (*(jlong*)_valuep)++; }
inline void inc(jlong val) { (*(jlong*)_valuep) += val; }
inline void dec(jlong val) { inc(-val); }
inline void add(jlong val) { (*(jlong*)_valuep) += val; }
void clear_sample_helper() { _sample_helper = NULL; }
};
/*
* The PerfLongCounter class, and its alias PerfCounter, implement
* a PerfData subtype that holds a jlong data value that can (should)
* be modified in a monotonic manner. The inc(jlong) and add(jlong)
* methods can be passed negative values to implement a monotonically
* decreasing value. However, we rely upon the programmer to honor
* the notion that this counter always moves in the same direction -
* either increasing or decreasing.
*/
class PerfLongCounter : public PerfLongVariant {
friend class PerfDataManager; // for access to protected constructor
protected:
PerfLongCounter(CounterNS ns, const char* namep, Units u,
jlong initial_value=0)
: PerfLongVariant(ns, namep, u, V_Monotonic,
initial_value) { }
PerfLongCounter(CounterNS ns, const char* namep, Units u, jlong* sampled)
: PerfLongVariant(ns, namep, u, V_Monotonic, sampled) { }
PerfLongCounter(CounterNS ns, const char* namep, Units u,
PerfLongSampleHelper* sample_helper)
: PerfLongVariant(ns, namep, u, V_Monotonic,
sample_helper) { }
};
typedef PerfLongCounter PerfCounter;
/*
* The PerfLongVariable class, and its alias PerfVariable, implement
* a PerfData subtype that holds a jlong data value that can
* be modified in an unrestricted manner.
*/
class PerfLongVariable : public PerfLongVariant {
friend class PerfDataManager; // for access to protected constructor
protected:
PerfLongVariable(CounterNS ns, const char* namep, Units u,
jlong initial_value=0)
: PerfLongVariant(ns, namep, u, V_Variable,
initial_value) { }
PerfLongVariable(CounterNS ns, const char* namep, Units u, jlong* sampled)
: PerfLongVariant(ns, namep, u, V_Variable, sampled) { }
PerfLongVariable(CounterNS ns, const char* namep, Units u,
PerfLongSampleHelper* sample_helper)
: PerfLongVariant(ns, namep, u, V_Variable,
sample_helper) { }
public:
inline void set_value(jlong val) { (*(jlong*)_valuep) = val; }
};
typedef PerfLongVariable PerfVariable;
/*
* The PerfByteArray provides a PerfData subtype that allows the creation
* of a contiguous region of the PerfData memory region for storing a vector
* of bytes. This class is currently intended to be a base class for
* the PerfString class, and cannot be instantiated directly.
*/
class PerfByteArray : public PerfData {
protected:
jint _length;
PerfByteArray(CounterNS ns, const char* namep, Units u, Variability v,
jint length);
};
class PerfString : public PerfByteArray {
protected:
void set_string(const char* s2);
PerfString(CounterNS ns, const char* namep, Variability v, jint length,
const char* initial_value)
: PerfByteArray(ns, namep, U_String, v, length) {
if (is_valid()) set_string(initial_value);
}
public:
int format(char* buffer, int length);
};
/*
* The PerfStringConstant class provides a PerfData sub class that
* allows a null terminated string of single byte characters to be
* stored in the PerfData memory region.
*/
class PerfStringConstant : public PerfString {
friend class PerfDataManager; // for access to protected constructor
private:
// hide sample() - no need to sample constants
void sample() { }
protected:
// Restrict string constant lengths to be <= PerfMaxStringConstLength.
// This prevents long string constants, as can occur with very
// long classpaths or java command lines, from consuming too much
// PerfData memory.
PerfStringConstant(CounterNS ns, const char* namep,
const char* initial_value);
};
/*
* The PerfStringVariable class provides a PerfData sub class that
* allows a null terminated string of single byte character data
* to be stored in PerfData memory region. The string value can be reset
* after initialization. If the string value is >= max_length, then
* it will be truncated to max_length characters. The copied string
* is always null terminated.
*/
class PerfStringVariable : public PerfString {
friend class PerfDataManager; // for access to protected constructor
protected:
// sampling of string variables are not yet supported
void sample() { }
PerfStringVariable(CounterNS ns, const char* namep, jint max_length,
const char* initial_value)
: PerfString(ns, namep, V_Variable, max_length+1,
initial_value) { }
public:
inline void set_value(const char* val) { set_string(val); }
};
/*
* The PerfDataList class is a container class for managing lists
* of PerfData items. The intention of this class is to allow for
* alternative implementations for management of list of PerfData
* items without impacting the code that uses the lists.
*
* The initial implementation is based upon GrowableArray. Searches
* on GrowableArray types is linear in nature and this may become
* a performance issue for creation of PerfData items, particularly
* from Java code where a test for existence is implemented as a
* search over all existing PerfData items.
*
* The abstraction is not complete. A more general container class
* would provide an Iterator abstraction that could be used to
* traverse the lists. This implementation still relies upon integer
* iterators and the at(int index) method. However, the GrowableArray
* is not directly visible outside this class and can be replaced by
* some other implementation, as long as that implementation provides
* a mechanism to iterate over the container by index.
*/
class PerfDataList : public CHeapObj<mtInternal> {
private:
// GrowableArray implementation
typedef GrowableArray<PerfData*> PerfDataArray;
PerfDataArray* _set;
// method to search for a instrumentation object by name
static bool by_name(void* name, PerfData* pd);
protected:
// we expose the implementation here to facilitate the clone
// method.
PerfDataArray* get_impl() { return _set; }
public:
// create a PerfDataList with the given initial length
PerfDataList(int length);
// create a PerfDataList as a shallow copy of the given PerfDataList
PerfDataList(PerfDataList* p);
~PerfDataList();
// return the PerfData item indicated by name,
// or NULL if it doesn't exist.
PerfData* find_by_name(const char* name);
// return true if a PerfData item with the name specified in the
// argument exists, otherwise return false.
bool contains(const char* name) { return find_by_name(name) != NULL; }
// return the number of PerfData items in this list
inline int length();
// add a PerfData item to this list
inline void append(PerfData *p);
// remove the given PerfData item from this list. When called
// while iterating over the list, this method will result in a
// change in the length of the container. The at(int index)
// method is also impacted by this method as elements with an
// index greater than the index of the element removed by this
// method will be shifted down by one.
inline void remove(PerfData *p);
// create a new PerfDataList from this list. The new list is
// a shallow copy of the original list and care should be taken
// with respect to delete operations on the elements of the list
// as the are likely in use by another copy of the list.
PerfDataList* clone();
// for backward compatibility with GrowableArray - need to implement
// some form of iterator to provide a cleaner abstraction for
// iteration over the container.
inline PerfData* at(int index);
};
/*
* The PerfDataManager class is responsible for creating PerfData
* subtypes via a set a factory methods and for managing lists
* of the various PerfData types.
*/
class PerfDataManager : AllStatic {
friend class StatSampler; // for access to protected PerfDataList methods
private:
static PerfDataList* _all;
static PerfDataList* _sampled;
static PerfDataList* _constants;
static const char* _name_spaces[];
static volatile bool _has_PerfData;
// add a PerfData item to the list(s) of know PerfData objects
static void add_item(PerfData* p, bool sampled);
protected:
// return the list of all known PerfData items
static PerfDataList* all();
static inline int count();
// return the list of all known PerfData items that are to be
// sampled by the StatSampler.
static PerfDataList* sampled();
static inline int sampled_count();
// return the list of all known PerfData items that have a
// variability classification of type Constant
static PerfDataList* constants();
static inline int constants_count();
public:
// method to check for the existence of a PerfData item with
// the given name.
static inline bool exists(const char* name);
// method to search for a instrumentation object by name
static PerfData* find_by_name(const char* name);
// method to map a CounterNS enumeration to a namespace string
static const char* ns_to_string(CounterNS ns) {
return _name_spaces[ns];
}
// methods to test the interface stability of a given counter namespace
//
static bool is_stable_supported(CounterNS ns) {
return (ns != NULL_NS) && ((ns % 3) == JAVA_NS);
}
static bool is_unstable_supported(CounterNS ns) {
return (ns != NULL_NS) && ((ns % 3) == COM_NS);
}
static bool is_unstable_unsupported(CounterNS ns) {
return (ns == NULL_NS) || ((ns % 3) == SUN_NS);
}
// methods to test the interface stability of a given counter name
//
static bool is_stable_supported(const char* name) {
const char* javadot = "java.";
return strncmp(name, javadot, strlen(javadot)) == 0;
}
static bool is_unstable_supported(const char* name) {
const char* comdot = "com.sun.";
return strncmp(name, comdot, strlen(comdot)) == 0;
}
static bool is_unstable_unsupported(const char* name) {
return !(is_stable_supported(name) && is_unstable_supported(name));
}
// method to construct counter name strings in a given name space.
// The string object is allocated from the Resource Area and calls
// to this method must be made within a ResourceMark.
//
static char* counter_name(const char* name_space, const char* name);
// method to construct name space strings in a given name space.
// The string object is allocated from the Resource Area and calls
// to this method must be made within a ResourceMark.
//
static char* name_space(const char* name_space, const char* sub_space) {
return counter_name(name_space, sub_space);
}
// same as above, but appends the instance number to the name space
//
static char* name_space(const char* name_space, const char* sub_space,
int instance);
static char* name_space(const char* name_space, int instance);
// these methods provide the general interface for creating
// performance data resources. The types of performance data
// resources can be extended by adding additional create<type>
// methods.
// Constant Types
static PerfStringConstant* create_string_constant(CounterNS ns,
const char* name,
const char *s, TRAPS);
static PerfLongConstant* create_long_constant(CounterNS ns,
const char* name,
PerfData::Units u,
jlong val, TRAPS);
// Variable Types
static PerfStringVariable* create_string_variable(CounterNS ns,
const char* name,
int max_length,
const char *s, TRAPS);
static PerfStringVariable* create_string_variable(CounterNS ns,
const char* name,
const char *s, TRAPS) {
return create_string_variable(ns, name, 0, s, THREAD);
};
static PerfLongVariable* create_long_variable(CounterNS ns,
const char* name,
PerfData::Units u,
jlong ival, TRAPS);
static PerfLongVariable* create_long_variable(CounterNS ns,
const char* name,
PerfData::Units u, TRAPS) {
return create_long_variable(ns, name, u, (jlong)0, THREAD);
};
static PerfLongVariable* create_long_variable(CounterNS, const char* name,
PerfData::Units u,
jlong* sp, TRAPS);
static PerfLongVariable* create_long_variable(CounterNS ns,
const char* name,
PerfData::Units u,
PerfLongSampleHelper* sh,
TRAPS);
// Counter Types
static PerfLongCounter* create_long_counter(CounterNS ns, const char* name,
PerfData::Units u,
jlong ival, TRAPS);
static PerfLongCounter* create_long_counter(CounterNS ns, const char* name,
PerfData::Units u, TRAPS) {
return create_long_counter(ns, name, u, (jlong)0, THREAD);
};
static PerfLongCounter* create_long_counter(CounterNS ns, const char* name,
PerfData::Units u, jlong* sp,
TRAPS);
static PerfLongCounter* create_long_counter(CounterNS ns, const char* name,
PerfData::Units u,
PerfLongSampleHelper* sh,
TRAPS);
// these creation methods are provided for ease of use. These allow
// Long performance data types to be created with a shorthand syntax.
static PerfConstant* create_constant(CounterNS ns, const char* name,
PerfData::Units u, jlong val, TRAPS) {
return create_long_constant(ns, name, u, val, THREAD);
}
static PerfVariable* create_variable(CounterNS ns, const char* name,
PerfData::Units u, jlong ival, TRAPS) {
return create_long_variable(ns, name, u, ival, THREAD);
}
static PerfVariable* create_variable(CounterNS ns, const char* name,
PerfData::Units u, TRAPS) {
return create_long_variable(ns, name, u, (jlong)0, THREAD);
}
static PerfVariable* create_variable(CounterNS ns, const char* name,
PerfData::Units u, jlong* sp, TRAPS) {
return create_long_variable(ns, name, u, sp, THREAD);
}
static PerfVariable* create_variable(CounterNS ns, const char* name,
PerfData::Units u,
PerfSampleHelper* sh, TRAPS) {
return create_long_variable(ns, name, u, sh, THREAD);
}
static PerfCounter* create_counter(CounterNS ns, const char* name,
PerfData::Units u, jlong ival, TRAPS) {
return create_long_counter(ns, name, u, ival, THREAD);
}
static PerfCounter* create_counter(CounterNS ns, const char* name,
PerfData::Units u, TRAPS) {
return create_long_counter(ns, name, u, (jlong)0, THREAD);
}
static PerfCounter* create_counter(CounterNS ns, const char* name,
PerfData::Units u, jlong* sp, TRAPS) {
return create_long_counter(ns, name, u, sp, THREAD);
}
static PerfCounter* create_counter(CounterNS ns, const char* name,
PerfData::Units u,
PerfSampleHelper* sh, TRAPS) {
return create_long_counter(ns, name, u, sh, THREAD);
}
static void destroy();
static bool has_PerfData() { return _has_PerfData; }
};
// Useful macros to create the performance counters
#define NEWPERFTICKCOUNTER(counter, counter_ns, counter_name) \
{counter = PerfDataManager::create_counter(counter_ns, counter_name, \
PerfData::U_Ticks,CHECK);}
#define NEWPERFEVENTCOUNTER(counter, counter_ns, counter_name) \
{counter = PerfDataManager::create_counter(counter_ns, counter_name, \
PerfData::U_Events,CHECK);}
#define NEWPERFBYTECOUNTER(counter, counter_ns, counter_name) \
{counter = PerfDataManager::create_counter(counter_ns, counter_name, \
PerfData::U_Bytes,CHECK);}
// Utility Classes
/*
* this class will administer a PerfCounter used as a time accumulator
* for a basic block much like the TraceTime class.
*
* Example:
*
* static PerfCounter* my_time_counter = PerfDataManager::create_counter("my.time.counter", PerfData::U_Ticks, 0LL, CHECK);
*
* {
* PerfTraceTime ptt(my_time_counter);
* // perform the operation you want to measure
* }
*
* Note: use of this class does not need to occur within a guarded
* block. The UsePerfData guard is used with the implementation
* of this class.
*/
class PerfTraceTime : public StackObj {
protected:
elapsedTimer _t;
PerfLongCounter* _timerp;
// pointer to thread-local or global recursion counter variable
int* _recursion_counter;
public:
inline PerfTraceTime(PerfLongCounter* timerp) : _timerp(timerp), _recursion_counter(NULL) {
if (!UsePerfData) return;
_t.start();
}
inline PerfTraceTime(PerfLongCounter* timerp, int* recursion_counter) : _timerp(timerp), _recursion_counter(recursion_counter) {
if (!UsePerfData || (_recursion_counter != NULL &&
(*_recursion_counter)++ > 0)) return;
_t.start();
}
inline void suspend() { if (!UsePerfData) return; _t.stop(); }
inline void resume() { if (!UsePerfData) return; _t.start(); }
~PerfTraceTime();
};
/* The PerfTraceTimedEvent class is responsible for counting the
* occurrence of some event and measuring the the elapsed time of
* the event in two separate PerfCounter instances.
*
* Example:
*
* static PerfCounter* my_time_counter = PerfDataManager::create_counter("my.time.counter", PerfData::U_Ticks, CHECK);
* static PerfCounter* my_event_counter = PerfDataManager::create_counter("my.event.counter", PerfData::U_Events, CHECK);
*
* {
* PerfTraceTimedEvent ptte(my_time_counter, my_event_counter);
* // perform the operation you want to count and measure
* }
*
* Note: use of this class does not need to occur within a guarded
* block. The UsePerfData guard is used with the implementation
* of this class.
*
*/
class PerfTraceTimedEvent : public PerfTraceTime {
protected:
PerfLongCounter* _eventp;
public:
inline PerfTraceTimedEvent(PerfLongCounter* timerp, PerfLongCounter* eventp): PerfTraceTime(timerp), _eventp(eventp) {
if (!UsePerfData) return;
_eventp->inc();
}
inline PerfTraceTimedEvent(PerfLongCounter* timerp, PerfLongCounter* eventp, int* recursion_counter): PerfTraceTime(timerp, recursion_counter), _eventp(eventp) {
if (!UsePerfData) return;
_eventp->inc();
}
};
#endif // SHARE_VM_RUNTIME_PERFDATA_HPP
| 37.587269 | 165 | 0.65575 | iootclab |
f667edd2ca9cdb9cf27bf08d14221b03df07d2b6 | 1,873 | hpp | C++ | data-struct/other/SlidingWindowAggregation.hpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | 3 | 2021-11-04T08:45:12.000Z | 2021-11-29T08:44:26.000Z | data-struct/other/SlidingWindowAggregation.hpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | null | null | null | data-struct/other/SlidingWindowAggregation.hpp | shiomusubi496/library | 907f72eb6ee4ac6ef617bb359693588167f779e7 | [
"MIT"
] | null | null | null | #pragma once
#include "../../other/template.hpp"
#include "../../other/monoid.hpp"
template<class M> class SlidingWindowAggregation {
protected:
using T = typename M::value_type;
std::stack<T> lst, rst;
std::stack<T> lsm, rsm;
T internal_all_prod() const {
assert(!empty());
if (lst.empty()) return rsm.top();
if (rst.empty()) return lsm.top();
return M::op(lsm.top(), rsm.top());
}
public:
SlidingWindowAggregation() = default;
int size() const {
return lst.size() + rst.size();
}
bool empty() const {
return lst.empty() && rst.empty();
}
void push(const T& x) {
rst.push(x);
if (rsm.empty()) rsm.push(rst.top());
else rsm.push(M::op(rsm.top(), rst.top()));
}
template<class... Args> void emplace(Args&&... args) {
rst.emplace(std::forward<Args>(args)...);
if (rsm.empty()) rsm.push(rst.top());
else rsm.push(M::op(rsm.top(), rst.top()));
}
void pop() {
assert(!empty());
if (lst.empty()) {
lst.push(rst.top()); lsm.push(rst.top());
rst.pop(); rsm.pop();
while (!rst.empty()) {
lst.push(rst.top()); lsm.push(M::op(rst.top(), lsm.top()));
rst.pop(); rsm.pop();
}
}
lst.pop(); lsm.pop();
}
template<bool AlwaysTrue = true, typename std::enable_if< Monoid::has_id<M>::value && AlwaysTrue>::type* = nullptr>
T all_prod() const {
if (empty()) return M::id();
return internal_all_prod();
}
template<bool AlwaysTrue = true, typename std::enable_if<!Monoid::has_id<M>::value && AlwaysTrue>::type* = nullptr>
T all_prod() const {
return internal_all_prod();
}
};
/**
* @brief SlidingWindowAggregation(SWAG)
* @docs docs/SlidingWindowAggregation.md
*/
| 30.209677 | 119 | 0.541911 | shiomusubi496 |
f6680017c9c7fa779421505620ffec33cb20debc | 8,107 | cc | C++ | base/power_monitor/power_monitor_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | base/power_monitor/power_monitor_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | base/power_monitor/power_monitor_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/power_monitor/power_monitor.h"
#include "base/macros.h"
#include "base/test/power_monitor_test_base.h"
#include "base/test/task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
class PowerMonitorTest : public testing::Test {
protected:
PowerMonitorTest() = default;
void TearDown() override { PowerMonitor::ShutdownForTesting(); }
void PowerMonitorInitialize() {
power_monitor_source_ = new PowerMonitorTestSource();
PowerMonitor::Initialize(
std::unique_ptr<PowerMonitorSource>(power_monitor_source_));
}
PowerMonitorTestSource* source() { return power_monitor_source_; }
private:
test::TaskEnvironment task_environment_;
PowerMonitorTestSource* power_monitor_source_;
DISALLOW_COPY_AND_ASSIGN(PowerMonitorTest);
};
// PowerMonitorSource is tightly coupled with the PowerMonitor, so this test
// covers both classes.
TEST_F(PowerMonitorTest, PowerNotifications) {
const int kObservers = 5;
PowerMonitorInitialize();
PowerMonitorTestObserver observers[kObservers];
for (auto& index : observers) {
PowerMonitor::AddPowerSuspendObserver(&index);
PowerMonitor::AddPowerStateObserver(&index);
PowerMonitor::AddPowerThermalObserver(&index);
}
// Sending resume when not suspended should have no effect.
source()->GenerateResumeEvent();
EXPECT_EQ(observers[0].resumes(), 0);
// Pretend we suspended.
source()->GenerateSuspendEvent();
// Ensure all observers were notified of the event
for (const auto& index : observers)
EXPECT_EQ(index.suspends(), 1);
// Send a second suspend notification. This should be suppressed.
source()->GenerateSuspendEvent();
EXPECT_EQ(observers[0].suspends(), 1);
// Pretend we were awakened.
source()->GenerateResumeEvent();
EXPECT_EQ(observers[0].resumes(), 1);
// Send a duplicate resume notification. This should be suppressed.
source()->GenerateResumeEvent();
EXPECT_EQ(observers[0].resumes(), 1);
// Pretend the device has gone on battery power
source()->GeneratePowerStateEvent(true);
EXPECT_EQ(observers[0].power_state_changes(), 1);
EXPECT_EQ(observers[0].last_power_state(), true);
// Repeated indications the device is on battery power should be suppressed.
source()->GeneratePowerStateEvent(true);
EXPECT_EQ(observers[0].power_state_changes(), 1);
// Pretend the device has gone off battery power
source()->GeneratePowerStateEvent(false);
EXPECT_EQ(observers[0].power_state_changes(), 2);
EXPECT_EQ(observers[0].last_power_state(), false);
// Repeated indications the device is off battery power should be suppressed.
source()->GeneratePowerStateEvent(false);
EXPECT_EQ(observers[0].power_state_changes(), 2);
EXPECT_EQ(observers[0].thermal_state_changes(), 0);
// Send a power thermal change notification.
source()->GenerateThermalThrottlingEvent(
PowerThermalObserver::DeviceThermalState::kNominal);
EXPECT_EQ(observers[0].thermal_state_changes(), 1);
EXPECT_EQ(observers[0].last_thermal_state(),
PowerThermalObserver::DeviceThermalState::kNominal);
// Send a duplicate power thermal notification. This should be suppressed.
source()->GenerateThermalThrottlingEvent(
PowerThermalObserver::DeviceThermalState::kNominal);
EXPECT_EQ(observers[0].thermal_state_changes(), 1);
// Send a different power thermal change notification.
source()->GenerateThermalThrottlingEvent(
PowerThermalObserver::DeviceThermalState::kFair);
EXPECT_EQ(observers[0].thermal_state_changes(), 2);
EXPECT_EQ(observers[0].last_thermal_state(),
PowerThermalObserver::DeviceThermalState::kFair);
for (auto& index : observers) {
PowerMonitor::RemovePowerSuspendObserver(&index);
PowerMonitor::RemovePowerStateObserver(&index);
PowerMonitor::RemovePowerThermalObserver(&index);
}
}
TEST_F(PowerMonitorTest, ThermalThrottling) {
PowerMonitorTestObserver observer;
PowerMonitor::AddPowerThermalObserver(&observer);
PowerMonitorInitialize();
constexpr PowerThermalObserver::DeviceThermalState kThermalStates[] = {
PowerThermalObserver::DeviceThermalState::kUnknown,
PowerThermalObserver::DeviceThermalState::kNominal,
PowerThermalObserver::DeviceThermalState::kFair,
PowerThermalObserver::DeviceThermalState::kSerious,
PowerThermalObserver::DeviceThermalState::kCritical};
for (const auto state : kThermalStates) {
source()->GenerateThermalThrottlingEvent(state);
EXPECT_EQ(state, source()->GetCurrentThermalState());
EXPECT_EQ(observer.last_thermal_state(), state);
}
PowerMonitor::RemovePowerThermalObserver(&observer);
}
TEST_F(PowerMonitorTest, AddPowerSuspendObserverBeforeAndAfterInitialization) {
PowerMonitorTestObserver observer1;
PowerMonitorTestObserver observer2;
// An observer is added before the PowerMonitor initialization.
PowerMonitor::AddPowerSuspendObserver(&observer1);
PowerMonitorInitialize();
// An observer is added after the PowerMonitor initialization.
PowerMonitor::AddPowerSuspendObserver(&observer2);
// Simulate suspend/resume notifications.
source()->GenerateSuspendEvent();
EXPECT_EQ(observer1.suspends(), 1);
EXPECT_EQ(observer2.suspends(), 1);
EXPECT_EQ(observer1.resumes(), 0);
EXPECT_EQ(observer2.resumes(), 0);
source()->GenerateResumeEvent();
EXPECT_EQ(observer1.resumes(), 1);
EXPECT_EQ(observer2.resumes(), 1);
PowerMonitor::RemovePowerSuspendObserver(&observer1);
PowerMonitor::RemovePowerSuspendObserver(&observer2);
}
TEST_F(PowerMonitorTest, AddPowerStateObserverBeforeAndAfterInitialization) {
PowerMonitorTestObserver observer1;
PowerMonitorTestObserver observer2;
// An observer is added before the PowerMonitor initialization.
PowerMonitor::AddPowerStateObserver(&observer1);
PowerMonitorInitialize();
// An observer is added after the PowerMonitor initialization.
PowerMonitor::AddPowerStateObserver(&observer2);
// Simulate power state transitions (e.g. battery on/off).
EXPECT_EQ(observer1.power_state_changes(), 0);
EXPECT_EQ(observer2.power_state_changes(), 0);
source()->GeneratePowerStateEvent(true);
EXPECT_EQ(observer1.power_state_changes(), 1);
EXPECT_EQ(observer2.power_state_changes(), 1);
source()->GeneratePowerStateEvent(false);
EXPECT_EQ(observer1.power_state_changes(), 2);
EXPECT_EQ(observer2.power_state_changes(), 2);
PowerMonitor::RemovePowerStateObserver(&observer1);
PowerMonitor::RemovePowerStateObserver(&observer2);
}
TEST_F(PowerMonitorTest, SuspendStateReturnedFromAddObserver) {
PowerMonitorTestObserver observer1;
PowerMonitorTestObserver observer2;
PowerMonitorInitialize();
EXPECT_FALSE(
PowerMonitor::AddPowerSuspendObserverAndReturnSuspendedState(&observer1));
source()->GenerateSuspendEvent();
EXPECT_TRUE(
PowerMonitor::AddPowerSuspendObserverAndReturnSuspendedState(&observer2));
EXPECT_EQ(observer1.suspends(), 1);
EXPECT_EQ(observer2.suspends(), 0);
EXPECT_EQ(observer1.resumes(), 0);
EXPECT_EQ(observer2.resumes(), 0);
PowerMonitor::RemovePowerSuspendObserver(&observer1);
PowerMonitor::RemovePowerSuspendObserver(&observer2);
}
TEST_F(PowerMonitorTest, PowerStateReturnedFromAddObserver) {
PowerMonitorTestObserver observer1;
PowerMonitorTestObserver observer2;
PowerMonitorInitialize();
// An observer is added before the on-battery notification.
EXPECT_FALSE(
PowerMonitor::AddPowerStateObserverAndReturnOnBatteryState(&observer1));
source()->GeneratePowerStateEvent(true);
// An observer is added after the on-battery notification.
EXPECT_TRUE(
PowerMonitor::AddPowerStateObserverAndReturnOnBatteryState(&observer2));
EXPECT_EQ(observer1.power_state_changes(), 1);
EXPECT_EQ(observer2.power_state_changes(), 0);
PowerMonitor::RemovePowerStateObserver(&observer1);
PowerMonitor::RemovePowerStateObserver(&observer2);
}
} // namespace base
| 33.920502 | 80 | 0.771185 | iridium-browser |
f66843733c8f31723fce47e76a0304a614a1f610 | 11,924 | hpp | C++ | master/core/third/boost/geometry/algorithms/detail/assign_values.hpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | master/core/third/boost/geometry/algorithms/detail/assign_values.hpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 197 | 2017-07-06T16:53:59.000Z | 2019-05-31T17:57:51.000Z | master/core/third/boost/geometry/algorithms/detail/assign_values.hpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP
#define BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP
#include <cstddef>
#include <boost/concept/requires.hpp>
#include <boost/concept_check.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/if.hpp>
#include <boost/numeric/conversion/bounds.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/type_traits.hpp>
#include <boost/geometry/arithmetic/arithmetic.hpp>
#include <boost/geometry/algorithms/append.hpp>
#include <boost/geometry/algorithms/clear.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>
#include <boost/geometry/util/for_each_coordinate.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace assign
{
template
<
typename Box, std::size_t Index,
std::size_t Dimension, std::size_t DimensionCount
>
struct initialize
{
typedef typename coordinate_type<Box>::type coordinate_type;
static inline void apply(Box& box, coordinate_type const& value)
{
geometry::set<Index, Dimension>(box, value);
initialize<Box, Index, Dimension + 1, DimensionCount>::apply(box, value);
}
};
template <typename Box, std::size_t Index, std::size_t DimensionCount>
struct initialize<Box, Index, DimensionCount, DimensionCount>
{
typedef typename coordinate_type<Box>::type coordinate_type;
static inline void apply(Box&, coordinate_type const& )
{}
};
template <typename Point>
struct assign_zero_point
{
static inline void apply(Point& point)
{
geometry::assign_value(point, 0);
}
};
template <typename BoxOrSegment>
struct assign_inverse_box_or_segment
{
typedef typename point_type<BoxOrSegment>::type point_type;
static inline void apply(BoxOrSegment& geometry)
{
typedef typename coordinate_type<point_type>::type bound_type;
initialize
<
BoxOrSegment, 0, 0, dimension<BoxOrSegment>::type::value
>::apply(
geometry, boost::numeric::bounds<bound_type>::highest());
initialize
<
BoxOrSegment, 1, 0, dimension<BoxOrSegment>::type::value
>::apply(
geometry, boost::numeric::bounds<bound_type>::lowest());
}
};
template <typename BoxOrSegment>
struct assign_zero_box_or_segment
{
static inline void apply(BoxOrSegment& geometry)
{
typedef typename coordinate_type<BoxOrSegment>::type coordinate_type;
initialize
<
BoxOrSegment, 0, 0, dimension<BoxOrSegment>::type::value
>::apply(geometry, coordinate_type());
initialize
<
BoxOrSegment, 1, 0, dimension<BoxOrSegment>::type::value
>::apply(geometry, coordinate_type());
}
};
template
<
std::size_t Corner1, std::size_t Corner2,
typename Box, typename Point
>
inline void assign_box_2d_corner(Box const& box, Point& point)
{
// Be sure both are 2-Dimensional
assert_dimension<Box, 2>();
assert_dimension<Point, 2>();
// Copy coordinates
typedef typename coordinate_type<Point>::type coordinate_type;
geometry::set<0>(point, boost::numeric_cast<coordinate_type>(get<Corner1, 0>(box)));
geometry::set<1>(point, boost::numeric_cast<coordinate_type>(get<Corner2, 1>(box)));
}
template
<
typename Geometry, typename Point,
std::size_t Index,
std::size_t Dimension, std::size_t DimensionCount
>
struct assign_point_to_index
{
static inline void apply(Point const& point, Geometry& geometry)
{
geometry::set<Index, Dimension>(geometry, boost::numeric_cast
<
typename coordinate_type<Geometry>::type
>(geometry::get<Dimension>(point)));
assign_point_to_index
<
Geometry, Point, Index, Dimension + 1, DimensionCount
>::apply(point, geometry);
}
};
template
<
typename Geometry, typename Point,
std::size_t Index,
std::size_t DimensionCount
>
struct assign_point_to_index
<
Geometry, Point,
Index,
DimensionCount, DimensionCount
>
{
static inline void apply(Point const& , Geometry& )
{
}
};
template
<
typename Geometry, typename Point,
std::size_t Index,
std::size_t Dimension, std::size_t DimensionCount
>
struct assign_point_from_index
{
static inline void apply(Geometry const& geometry, Point& point)
{
geometry::set<Dimension>( point, boost::numeric_cast
<
typename coordinate_type<Point>::type
>(geometry::get<Index, Dimension>(geometry)));
assign_point_from_index
<
Geometry, Point, Index, Dimension + 1, DimensionCount
>::apply(geometry, point);
}
};
template
<
typename Geometry, typename Point,
std::size_t Index,
std::size_t DimensionCount
>
struct assign_point_from_index
<
Geometry, Point,
Index,
DimensionCount, DimensionCount
>
{
static inline void apply(Geometry const&, Point&)
{
}
};
template <typename Geometry>
struct assign_2d_box_or_segment
{
typedef typename coordinate_type<Geometry>::type coordinate_type;
// Here we assign 4 coordinates to a box of segment
// -> Most logical is: x1,y1,x2,y2
// In case the user reverses x1/x2 or y1/y2, for a box, we could reverse them (THAT IS NOT IMPLEMENTED)
template <typename Type>
static inline void apply(Geometry& geometry,
Type const& x1, Type const& y1, Type const& x2, Type const& y2)
{
geometry::set<0, 0>(geometry, boost::numeric_cast<coordinate_type>(x1));
geometry::set<0, 1>(geometry, boost::numeric_cast<coordinate_type>(y1));
geometry::set<1, 0>(geometry, boost::numeric_cast<coordinate_type>(x2));
geometry::set<1, 1>(geometry, boost::numeric_cast<coordinate_type>(y2));
}
};
}} // namespace detail::assign
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
template <typename GeometryTag, typename Geometry, std::size_t DimensionCount>
struct assign
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_OR_NOT_YET_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPE
, (types<Geometry>)
);
};
template <typename Point>
struct assign<point_tag, Point, 2>
{
typedef typename coordinate_type<Point>::type coordinate_type;
template <typename T>
static inline void apply(Point& point, T const& c1, T const& c2)
{
set<0>(point, boost::numeric_cast<coordinate_type>(c1));
set<1>(point, boost::numeric_cast<coordinate_type>(c2));
}
};
template <typename Point>
struct assign<point_tag, Point, 3>
{
typedef typename coordinate_type<Point>::type coordinate_type;
template <typename T>
static inline void apply(Point& point, T const& c1, T const& c2, T const& c3)
{
set<0>(point, boost::numeric_cast<coordinate_type>(c1));
set<1>(point, boost::numeric_cast<coordinate_type>(c2));
set<2>(point, boost::numeric_cast<coordinate_type>(c3));
}
};
template <typename Box>
struct assign<box_tag, Box, 2>
: detail::assign::assign_2d_box_or_segment<Box>
{};
template <typename Segment>
struct assign<segment_tag, Segment, 2>
: detail::assign::assign_2d_box_or_segment<Segment>
{};
template <typename GeometryTag, typename Geometry>
struct assign_zero {};
template <typename Point>
struct assign_zero<point_tag, Point>
: detail::assign::assign_zero_point<Point>
{};
template <typename Box>
struct assign_zero<box_tag, Box>
: detail::assign::assign_zero_box_or_segment<Box>
{};
template <typename Segment>
struct assign_zero<segment_tag, Segment>
: detail::assign::assign_zero_box_or_segment<Segment>
{};
template <typename GeometryTag, typename Geometry>
struct assign_inverse {};
template <typename Box>
struct assign_inverse<box_tag, Box>
: detail::assign::assign_inverse_box_or_segment<Box>
{};
template <typename Segment>
struct assign_inverse<segment_tag, Segment>
: detail::assign::assign_inverse_box_or_segment<Segment>
{};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
/*!
\brief Assign two coordinates to a geometry (usually a 2D point)
\ingroup assign
\tparam Geometry \tparam_geometry
\tparam Type \tparam_numeric to specify the coordinates
\param geometry \param_geometry
\param c1 \param_x
\param c2 \param_y
\qbk{distinguish, 2 coordinate values}
\qbk{
[heading Example]
[assign_2d_point] [assign_2d_point_output]
[heading See also]
\* [link geometry.reference.algorithms.make.make_2_2_coordinate_values make]
}
*/
template <typename Geometry, typename Type>
inline void assign_values(Geometry& geometry, Type const& c1, Type const& c2)
{
concept::check<Geometry>();
dispatch::assign
<
typename tag<Geometry>::type,
Geometry,
geometry::dimension<Geometry>::type::value
>::apply(geometry, c1, c2);
}
/*!
\brief Assign three values to a geometry (usually a 3D point)
\ingroup assign
\tparam Geometry \tparam_geometry
\tparam Type \tparam_numeric to specify the coordinates
\param geometry \param_geometry
\param c1 \param_x
\param c2 \param_y
\param c3 \param_z
\qbk{distinguish, 3 coordinate values}
\qbk{
[heading Example]
[assign_3d_point] [assign_3d_point_output]
[heading See also]
\* [link geometry.reference.algorithms.make.make_3_3_coordinate_values make]
}
*/
template <typename Geometry, typename Type>
inline void assign_values(Geometry& geometry,
Type const& c1, Type const& c2, Type const& c3)
{
concept::check<Geometry>();
dispatch::assign
<
typename tag<Geometry>::type,
Geometry,
geometry::dimension<Geometry>::type::value
>::apply(geometry, c1, c2, c3);
}
/*!
\brief Assign four values to a geometry (usually a box or segment)
\ingroup assign
\tparam Geometry \tparam_geometry
\tparam Type \tparam_numeric to specify the coordinates
\param geometry \param_geometry
\param c1 First coordinate (usually x1)
\param c2 Second coordinate (usually y1)
\param c3 Third coordinate (usually x2)
\param c4 Fourth coordinate (usually y2)
\qbk{distinguish, 4 coordinate values}
*/
template <typename Geometry, typename Type>
inline void assign_values(Geometry& geometry,
Type const& c1, Type const& c2, Type const& c3, Type const& c4)
{
concept::check<Geometry>();
dispatch::assign
<
typename tag<Geometry>::type,
Geometry,
geometry::dimension<Geometry>::type::value
>::apply(geometry, c1, c2, c3, c4);
}
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_ASSIGN_VALUES_HPP
| 26.855856 | 108 | 0.666303 | importlib |
f66b0132adc58690de57d30ce814cef2bf34ccec | 33,014 | cpp | C++ | opennurbs_matrix.cpp | averbin/opennurbslib | 8904e11a90d108304f679d233ad1ea2d621dd3b2 | [
"Zlib"
] | 14 | 2015-07-06T13:04:49.000Z | 2022-02-06T10:09:05.000Z | opennurbs_matrix.cpp | averbin/opennurbslib | 8904e11a90d108304f679d233ad1ea2d621dd3b2 | [
"Zlib"
] | 1 | 2020-12-07T03:26:39.000Z | 2020-12-07T03:26:39.000Z | opennurbs_matrix.cpp | averbin/opennurbslib | 8904e11a90d108304f679d233ad1ea2d621dd3b2 | [
"Zlib"
] | 11 | 2015-07-06T13:04:43.000Z | 2022-03-29T10:57:04.000Z | /* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#include "opennurbs.h"
// 8 July 2003 Dale Lear
// changed ON_Matrix to use multiple allocations
// for coefficient memory in large matrices.
// ON_Matrix.m_cmem points to a struct DBLBLK
struct DBLBLK
{
int count;
double* a;
struct DBLBLK *next;
};
double const * const * ON_Matrix::ThisM() const
{
// When the "expert" constructor Create(row_count,col_count,user_memory,...)
// is used, m_rowmem[] is empty and m = user_memory;
// When any other constructor is used, m_rowmem[] is the 0-based
// row memory.
return (m_row_count == m_rowmem.Count()) ? m_rowmem.Array() : m;
}
double * * ON_Matrix::ThisM()
{
// When the "expert" constructor Create(row_count,col_count,user_memory,...)
// is used, m_rowmem[] is empty and m = user_memory;
// When any other constructor is used, m_rowmem[] is the 0-based
// row memory.
return (m_row_count == m_rowmem.Count()) ? m_rowmem.Array() : m;
}
double* ON_Matrix::operator[](int i)
{
return m[i];
}
const double* ON_Matrix::operator[](int i) const
{
return m[i];
}
ON_Matrix::ON_Matrix()
: m(0)
, m_row_count(0)
, m_col_count(0)
, m_Mmem(0)
, m_row_offset(0)
, m_col_offset(0)
, m_cmem(0)
{
}
ON_Matrix::ON_Matrix( int row_size, int col_size )
: m(0)
, m_row_count(0)
, m_col_count(0)
, m_Mmem(0)
, m_row_offset(0)
, m_col_offset(0)
, m_cmem(0)
{
Create(row_size,col_size);
}
ON_Matrix::ON_Matrix( int row0, int row1, int col0, int col1 )
: m(0)
, m_row_count(0)
, m_col_count(0)
, m_Mmem(0)
, m_row_offset(0)
, m_col_offset(0)
, m_cmem(0)
{
Create(row0,row1,col0,col1);
}
ON_Matrix::ON_Matrix( const ON_Xform& x )
: m(0)
, m_row_count(0)
, m_col_count(0)
, m_Mmem(0)
, m_row_offset(0)
, m_col_offset(0)
, m_cmem(0)
{
*this = x;
}
ON_Matrix::ON_Matrix( const ON_Matrix& src )
: m(0)
, m_row_count(0)
, m_col_count(0)
, m_Mmem(0)
, m_row_offset(0)
, m_col_offset(0)
, m_cmem(0)
{
*this = src;
}
ON_Matrix::ON_Matrix(
int row_count,
int col_count,
double** M,
bool bDestructorFreeM
)
: m(0)
, m_row_count(0)
, m_col_count(0)
, m_Mmem(0)
, m_row_offset(0)
, m_col_offset(0)
, m_cmem(0)
{
Create(row_count,col_count,M,bDestructorFreeM);
}
ON_Matrix::~ON_Matrix()
{
if ( 0 != m_Mmem )
{
onfree(m_Mmem);
m_Mmem = 0;
}
m_row_offset = 0;
m_col_offset = 0;
struct DBLBLK* p = (struct DBLBLK*)m_cmem;
m_cmem = 0;
while(0 != p)
{
struct DBLBLK* next = p->next;
onfree(p);
p = next;
}
}
int ON_Matrix::RowCount() const
{
return m_row_count;
}
int ON_Matrix::ColCount() const
{
return m_col_count;
}
int ON_Matrix::MinCount() const
{
return (m_row_count <= m_col_count) ? m_row_count : m_col_count;
}
int ON_Matrix::MaxCount() const
{
return (m_row_count >= m_col_count) ? m_row_count : m_col_count;
}
bool ON_Matrix::Create( int row_count, int col_count)
{
bool b = false;
Destroy();
if ( row_count > 0 && col_count > 0 )
{
m_rowmem.Reserve(row_count);
if ( 0 != m_rowmem.Array() )
{
m_rowmem.SetCount(row_count);
// In general, allocate coefficient memory in chunks
// of <= max_dblblk_size bytes. The value of max_dblblk_size
// is tuned to maximize speed on calculations involving
// large matrices. If all of the coefficients will fit
// into a chunk of memory <= 1.1*max_dblblk_size, then
// a single chunk is allocated.
// In limited testing, these two values appeared to work ok.
// The latter was a hair faster in solving large row reduction
// problems (for reasons I do not understand).
//const int max_dblblk_size = 1024*1024*8;
const int max_dblblk_size = 512*1024;
int rows_per_block = max_dblblk_size/(col_count*sizeof(double));
if ( rows_per_block > row_count )
rows_per_block = row_count;
else if ( rows_per_block < 1 )
rows_per_block = 1;
else if ( rows_per_block < row_count && 11*rows_per_block >= 10*row_count )
rows_per_block = row_count;
int j, i = row_count;
m = m_rowmem.Array();
double** row = m;
for ( i = row_count; i > 0; i -= rows_per_block )
{
if ( i < rows_per_block )
rows_per_block = i;
int dblblk_count = rows_per_block*col_count;
struct DBLBLK* p = (struct DBLBLK*)onmalloc(sizeof(*p) + dblblk_count*sizeof(p->a[0]));
p->a = (double*)(p+1);
p->count = dblblk_count;
p->next = (struct DBLBLK*)m_cmem;
m_cmem = p;
*row = p->a;
j = rows_per_block-1;
while(j--)
{
row[1] = row[0] + col_count;
row++;
}
row++;
}
m_row_count = row_count;
m_col_count = col_count;
b = true;
}
}
return b;
}
bool ON_Matrix::Create( // E.g., Create(1,5,1,7) creates a 5x7 sized matrix that with
// "top" row = m[1][1],...,m[1][7] and "bottom" row
// = m[5][1],...,m[5][7]. The result of Create(0,m,0,n) is
// identical to the result of Create(m+1,n+1).
int ri0, // first valid row index
int ri1, // last valid row index
int ci0, // first valid column index
int ci1 // last valid column index
)
{
bool b = false;
if ( ri1 > ri0 && ci1 > ci0 )
{
// juggle m[] pointers so that m[ri0+i][ci0+j] = m_row[i][j];
b = Create( ri1-ri0, ci1-ci0 );
if (b)
{
m_row_offset = ri0; // this is the only line of code where m_row_offset should be set to a non-zero value
m_col_offset = ci0; // this is the only line of code where m_col_offset should be set to a non-zero value
if ( ci0 != 0 )
{
int i;
for ( i = 0; i < m_row_count; i++ ) {
m[i] -= ci0;
}
}
if ( ri0 != 0 )
m -= ri0;
}
}
return b;
}
bool ON_Matrix::Create(
int row_count,
int col_count,
double** M,
bool bDestructorFreeM
)
{
Destroy();
if ( row_count < 1 || col_count < 1 || 0 == M )
return false;
m = M;
m_row_count = row_count;
m_col_count = col_count;
if ( bDestructorFreeM )
m_Mmem = M;
return true;
}
void ON_Matrix::Destroy()
{
m = 0;
m_row_count = 0;
m_col_count = 0;
m_rowmem.SetCount(0);
if ( 0 != m_Mmem )
{
// pointer passed to Create( row_count, col_count, M, bDestructorFreeM )
// when bDestructorFreeM = true.
onfree(m_Mmem);
m_Mmem = 0;
}
m_row_offset = 0;
m_col_offset = 0;
struct DBLBLK* cmem = (struct DBLBLK*)m_cmem;
m_cmem = 0;
while( 0 != cmem )
{
struct DBLBLK* next_cmem = cmem->next;
onfree(cmem);
cmem = next_cmem;
}
}
void ON_Matrix::EmergencyDestroy()
{
// call if memory pool used matrix by becomes invalid
m = 0;
m_row_count = 0;
m_col_count = 0;
m_rowmem.EmergencyDestroy();
m_Mmem = 0;
m_row_offset = 0;
m_col_offset = 0;
m_cmem = 0;
}
ON_Matrix& ON_Matrix::operator=(const ON_Matrix& src)
{
if ( this != &src )
{
if ( src.m_row_count != m_row_count || src.m_col_count != m_col_count || 0 == m )
{
Destroy();
Create( src.RowCount(), src.ColCount() );
}
if (src.m_row_count == m_row_count && src.m_col_count == m_col_count && 0 != m )
{
int i;
// src rows may be permuted - copy row by row
double** m_dest = ThisM();
double const*const* m_src = src.ThisM();
const int sizeof_row = m_col_count*sizeof(m_dest[0][0]);
for ( i = 0; i < m_row_count; i++ )
{
memcpy( m_dest[i], m_src[i], sizeof_row );
}
m_row_offset = src.m_row_offset;
m_col_offset = src.m_col_offset;
}
}
return *this;
}
ON_Matrix& ON_Matrix::operator=(const ON_Xform& src)
{
m_row_offset = 0;
m_col_offset = 0;
if ( 4 != m_row_count || 4 != m_col_count || 0 == m )
{
Destroy();
Create( 4, 4 );
}
if ( 4 == m_row_count && 4 == m_col_count && 0 != m )
{
double** this_m = ThisM();
if ( this_m )
{
memcpy( this_m[0], &src.m_xform[0][0], 4*sizeof(this_m[0][0]) );
memcpy( this_m[1], &src.m_xform[1][0], 4*sizeof(this_m[0][0]) );
memcpy( this_m[2], &src.m_xform[2][0], 4*sizeof(this_m[0][0]) );
memcpy( this_m[3], &src.m_xform[3][0], 4*sizeof(this_m[0][0]) );
}
}
return *this;
}
bool ON_Matrix::Transpose()
{
bool rc = false;
int i, j;
double t;
const int row_count = RowCount();
const int col_count = ColCount();
if ( row_count > 0 && col_count > 0 )
{
double** this_m = ThisM();
if ( row_count == col_count )
{
rc = true;
for ( i = 0; i < row_count; i++ ) for ( j = i+1; j < row_count; j++ )
{
t = this_m[i][j]; this_m[i][j] = this_m[j][i]; this_m[j][i] = t;
}
}
else if ( this_m == m_rowmem.Array() )
{
ON_Matrix A(*this);
rc = Create(col_count,row_count)
&& m_row_count == A.ColCount()
&& m_col_count == A.RowCount();
if (rc)
{
double const*const* Am = A.ThisM();
this_m = ThisM(); // Create allocates new memory
for ( i = 0; i < row_count; i++ ) for ( j = 0; j < col_count; j++ )
{
this_m[j][i] = Am[i][j];
}
m_row_offset = A.m_col_offset;
m_col_offset = A.m_row_offset;
}
else
{
// attempt to put values back
*this = A;
}
}
}
return rc;
}
bool ON_Matrix::SwapRows( int row0, int row1 )
{
bool b = false;
double** this_m = ThisM();
row0 -= m_row_offset;
row1 -= m_row_offset;
if ( this_m && 0 <= row0 && row0 < m_row_count && 0 <= row1 && row1 < m_row_count )
{
if ( row0 != row1 )
{
double* tmp = this_m[row0]; this_m[row0] = this_m[row1]; this_m[row1] = tmp;
}
b = true;
}
return b;
}
bool ON_Matrix::SwapCols( int col0, int col1 )
{
bool b = false;
int i;
double t;
double** this_m = ThisM();
col0 -= m_col_offset;
col1 -= m_col_offset;
if ( this_m && 0 <= col0 && col0 < m_col_count && 0 <= col1 && col1 < m_col_count )
{
if ( col0 != col1 )
{
for ( i = 0; i < m_row_count; i++ )
{
t = this_m[i][col0]; this_m[i][col0] = this_m[i][col1]; this_m[i][col1] = t;
}
}
b = true;
}
return b;
}
void ON_Matrix::RowScale( int dest_row, double s )
{
double** this_m = ThisM();
dest_row -= m_row_offset;
ON_ArrayScale( m_col_count, s, this_m[dest_row], this_m[dest_row] );
}
void ON_Matrix::RowOp( int dest_row, double s, int src_row )
{
double** this_m = ThisM();
dest_row -= m_row_offset;
src_row -= m_row_offset;
ON_Array_aA_plus_B( m_col_count, s, this_m[src_row], this_m[dest_row], this_m[dest_row] );
}
void ON_Matrix::ColScale( int dest_col, double s )
{
int i;
double** this_m = ThisM();
dest_col -= m_col_offset;
for ( i = 0; i < m_row_count; i++ )
{
this_m[i][dest_col] *= s;
}
}
void ON_Matrix::ColOp( int dest_col, double s, int src_col )
{
int i;
double** this_m = ThisM();
dest_col -= m_col_offset;
src_col -= m_col_offset;
for ( i = 0; i < m_row_count; i++ )
{
this_m[i][dest_col] += s*this_m[i][src_col];
}
}
int
ON_Matrix::RowReduce(
double zero_tolerance,
double& determinant,
double& pivot
)
{
double x, piv, det;
int i, k, ix, rank;
double** this_m = ThisM();
piv = det = 1.0;
rank = 0;
const int n = m_row_count <= m_col_count ? m_row_count : m_col_count;
for ( k = 0; k < n; k++ ) {
ix = k;
x = fabs(this_m[ix][k]);
for ( i = k+1; i < m_row_count; i++ ) {
if ( fabs(this_m[i][k]) > x ) {
ix = i;
x = fabs(this_m[ix][k]);
}
}
if ( x < piv || k == 0 ) {
piv = x;
}
if ( x <= zero_tolerance ) {
det = 0.0;
break;
}
rank++;
if ( ix != k )
{
// swap rows
SwapRows( ix, k );
det = -det;
}
// scale row k of matrix and B
det *= this_m[k][k];
x = 1.0/this_m[k][k];
this_m[k][k] = 1.0;
ON_ArrayScale( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[k][k+1] );
// zero column k for rows below this_m[k][k]
for ( i = k+1; i < m_row_count; i++ ) {
x = -this_m[i][k];
this_m[i][k] = 0.0;
if ( fabs(x) > zero_tolerance ) {
ON_Array_aA_plus_B( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] );
}
}
}
pivot = piv;
determinant = det;
return rank;
}
int
ON_Matrix::RowReduce(
double zero_tolerance,
double* B,
double* pivot
)
{
double t;
double x, piv;
int i, k, ix, rank;
double** this_m = ThisM();
piv = 0.0;
rank = 0;
const int n = m_row_count <= m_col_count ? m_row_count : m_col_count;
for ( k = 0; k < n; k++ ) {
ix = k;
x = fabs(this_m[ix][k]);
for ( i = k+1; i < m_row_count; i++ ) {
if ( fabs(this_m[i][k]) > x ) {
ix = i;
x = fabs(this_m[ix][k]);
}
}
if ( x < piv || k == 0 ) {
piv = x;
}
if ( x <= zero_tolerance )
break;
rank++;
if ( ix != k )
{
// swap rows of matrix and B
SwapRows( ix, k );
t = B[ix]; B[ix] = B[k]; B[k] = t;
}
// scale row k of matrix and B
x = 1.0/this_m[k][k];
this_m[k][k] = 1.0;
ON_ArrayScale( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[k][k+1] );
B[k] *= x;
// zero column k for rows below this_m[k][k]
for ( i = k+1; i < m_row_count; i++ ) {
x = -this_m[i][k];
this_m[i][k] = 0.0;
if ( fabs(x) > zero_tolerance ) {
ON_Array_aA_plus_B( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] );
B[i] += x*B[k];
}
}
}
if ( pivot )
*pivot = piv;
return rank;
}
int
ON_Matrix::RowReduce(
double zero_tolerance,
ON_3dPoint* B,
double* pivot
)
{
ON_3dPoint t;
double x, piv;
int i, k, ix, rank;
double** this_m = ThisM();
piv = 0.0;
rank = 0;
const int n = m_row_count <= m_col_count ? m_row_count : m_col_count;
for ( k = 0; k < n; k++ ) {
//onfree( onmalloc( 1)); // 8-06-03 lw for cancel thread responsiveness
onmalloc( 0); // 9-4-03 lw changed to 0
ix = k;
x = fabs(this_m[ix][k]);
for ( i = k+1; i < m_row_count; i++ ) {
if ( fabs(this_m[i][k]) > x ) {
ix = i;
x = fabs(this_m[ix][k]);
}
}
if ( x < piv || k == 0 ) {
piv = x;
}
if ( x <= zero_tolerance )
break;
rank++;
if ( ix != k )
{
// swap rows of matrix and B
SwapRows( ix, k );
t = B[ix]; B[ix] = B[k]; B[k] = t;
}
// scale row k of matrix and B
x = 1.0/this_m[k][k];
this_m[k][k] = 1.0;
ON_ArrayScale( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[k][k+1] );
B[k] *= x;
// zero column k for rows below this_m[k][k]
for ( i = k+1; i < m_row_count; i++ ) {
x = -this_m[i][k];
this_m[i][k] = 0.0;
if ( fabs(x) > zero_tolerance ) {
ON_Array_aA_plus_B( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] );
B[i] += x*B[k];
}
}
}
if ( pivot )
*pivot = piv;
return rank;
}
int
ON_Matrix::RowReduce(
double zero_tolerance,
int pt_dim, int pt_stride, double* pt,
double* pivot
)
{
const int sizeof_pt = pt_dim*sizeof(pt[0]);
double* tmp_pt = (double*)onmalloc(pt_dim*sizeof(tmp_pt[0]));
double *ptA, *ptB;
double x, piv;
int i, k, ix, rank, pti;
double** this_m = ThisM();
piv = 0.0;
rank = 0;
const int n = m_row_count <= m_col_count ? m_row_count : m_col_count;
for ( k = 0; k < n; k++ ) {
// onfree( onmalloc( 1)); // 8-06-03 lw for cancel thread responsiveness
onmalloc( 0); // 9-4-03 lw changed to 0
ix = k;
x = fabs(this_m[ix][k]);
for ( i = k+1; i < m_row_count; i++ ) {
if ( fabs(this_m[i][k]) > x ) {
ix = i;
x = fabs(this_m[ix][k]);
}
}
if ( x < piv || k == 0 ) {
piv = x;
}
if ( x <= zero_tolerance )
break;
rank++;
// swap rows of matrix and B
if ( ix != k ) {
SwapRows( ix, k );
ptA = pt + (ix*pt_stride);
ptB = pt + (k*pt_stride);
memcpy( tmp_pt, ptA, sizeof_pt );
memcpy( ptA, ptB, sizeof_pt );
memcpy( ptB, tmp_pt, sizeof_pt );
}
// scale row k of matrix and B
x = 1.0/this_m[k][k];
if ( x != 1.0 ) {
this_m[k][k] = 1.0;
ON_ArrayScale( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[k][k+1] );
ptA = pt + (k*pt_stride);
for ( pti = 0; pti < pt_dim; pti++ )
ptA[pti] *= x;
}
// zero column k for rows below this_m[k][k]
ptB = pt + (k*pt_stride);
for ( i = k+1; i < m_row_count; i++ ) {
x = -this_m[i][k];
this_m[i][k] = 0.0;
if ( fabs(x) > zero_tolerance ) {
ON_Array_aA_plus_B( m_col_count - 1 - k, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] );
ptA = pt + (i*pt_stride);
for ( pti = 0; pti < pt_dim; pti++ ) {
ptA[pti] += x*ptB[pti];
}
}
}
}
if ( pivot )
*pivot = piv;
onfree(tmp_pt);
return rank;
}
bool
ON_Matrix::BackSolve(
double zero_tolerance,
int Bsize,
const double* B,
double* X
) const
{
int i;
if ( m_col_count > m_row_count )
return false; // under determined
if ( Bsize < m_col_count || Bsize > m_row_count )
return false; // under determined
for ( i = m_col_count; i < Bsize; i++ ) {
if ( fabs(B[i]) > zero_tolerance )
return false; // over determined
}
// backsolve
double const*const* this_m = ThisM();
const int n = m_col_count-1;
if ( X != B )
X[n] = B[n];
for ( i = n-1; i >= 0; i-- ) {
X[i] = B[i] - ON_ArrayDotProduct( n-i, &this_m[i][i+1], &X[i+1] );
}
return true;
}
bool
ON_Matrix::BackSolve(
double zero_tolerance,
int Bsize,
const ON_3dPoint* B,
ON_3dPoint* X
) const
{
int i, j;
if ( m_col_count > m_row_count )
return false; // under determined
if ( Bsize < m_col_count || Bsize > m_row_count )
return false; // under determined
for ( i = m_col_count; i < Bsize; i++ ) {
if ( B[i].MaximumCoordinate() > zero_tolerance )
return false; // over determined
}
// backsolve
double const*const* this_m = ThisM();
if ( X != B )
{
X[m_col_count-1] = B[m_col_count-1];
for ( i = m_col_count-2; i >= 0; i-- ) {
X[i] = B[i];
for ( j = i+1; j < m_col_count; j++ ) {
X[i] -= this_m[i][j]*X[j];
}
}
}
else {
for ( i = m_col_count-2; i >= 0; i-- ) {
for ( j = i+1; j < m_col_count; j++ ) {
X[i] -= this_m[i][j]*X[j];
}
}
}
return true;
}
bool
ON_Matrix::BackSolve(
double zero_tolerance,
int pt_dim,
int Bsize,
int Bpt_stride,
const double* Bpt,
int Xpt_stride,
double* Xpt
) const
{
const int sizeof_pt = pt_dim*sizeof(double);
double mij;
int i, j, k;
const double* Bi;
double* Xi;
double* Xj;
if ( m_col_count > m_row_count )
return false; // under determined
if ( Bsize < m_col_count || Bsize > m_row_count )
return false; // under determined
for ( i = m_col_count; i < Bsize; i++ )
{
Bi = Bpt + i*Bpt_stride;
for( j = 0; j < pt_dim; j++ )
{
if ( fabs(Bi[j]) > zero_tolerance )
return false; // over determined
}
}
// backsolve
double const*const* this_m = ThisM();
if ( Xpt != Bpt )
{
Xi = Xpt + (m_col_count-1)*Xpt_stride;
Bi = Bpt + (m_col_count-1)*Bpt_stride;
memcpy(Xi,Bi,sizeof_pt);
for ( i = m_col_count-2; i >= 0; i-- ) {
Xi = Xpt + i*Xpt_stride;
Bi = Bpt + i*Bpt_stride;
memcpy(Xi,Bi,sizeof_pt);
for ( j = i+1; j < m_col_count; j++ ) {
Xj = Xpt + j*Xpt_stride;
mij = this_m[i][j];
for ( k = 0; k < pt_dim; k++ )
Xi[k] -= mij*Xj[k];
}
}
}
else {
for ( i = m_col_count-2; i >= 0; i-- ) {
Xi = Xpt + i*Xpt_stride;
for ( j = i+1; j < m_col_count; j++ ) {
Xj = Xpt + j*Xpt_stride;
mij = this_m[i][j];
for ( k = 0; k < pt_dim; k++ )
Xi[k] -= mij*Xj[k];
}
}
}
return true;
}
void ON_Matrix::Zero()
{
struct DBLBLK* cmem = (struct DBLBLK*)m_cmem;
while ( 0 != cmem )
{
if ( 0 != cmem->a && cmem->count > 0 )
{
memset( cmem->a, 0, cmem->count*sizeof(cmem->a[0]) );
}
cmem = cmem->next;
}
//m_a.Zero();
}
void ON_Matrix::SetDiagonal( double d)
{
const int n = MinCount();
int i;
Zero();
double** this_m = ThisM();
for ( i = 0; i < n; i++ )
{
this_m[i][i] = d;
}
}
void ON_Matrix::SetDiagonal( const double* d )
{
Zero();
if (d)
{
double** this_m = ThisM();
const int n = MinCount();
int i;
for ( i = 0; i < n; i++ )
{
this_m[i][i] = *d++;
}
}
}
void ON_Matrix::SetDiagonal( int count, const double* d )
{
Create(count,count);
Zero();
SetDiagonal(d);
}
void ON_Matrix::SetDiagonal( const ON_SimpleArray<double>& a )
{
SetDiagonal( a.Count(), a.Array() );
}
bool ON_Matrix::IsValid() const
{
if ( m_row_count < 1 || m_col_count < 1 )
return false;
if ( 0 == m )
return false;
return true;
}
int ON_Matrix::IsSquare() const
{
return ( m_row_count > 0 && m_col_count == m_row_count ) ? m_row_count : 0;
}
bool ON_Matrix::IsRowOrthoganal() const
{
double d0, d1, d;
int i0, i1, j;
double const*const* this_m = ThisM();
bool rc = ( m_row_count <= m_col_count && m_row_count > 0 );
for ( i0 = 0; i0 < m_row_count && rc; i0++ ) for ( i1 = i0+1; i1 < m_row_count && rc; i1++ ) {
d0 = d1 = d = 0.0;
for ( j = 0; j < m_col_count; j++ ) {
d0 += fabs(this_m[i0][j]);
d1 += fabs(this_m[i0][j]);
d += this_m[i0][j]*this_m[i1][j];
}
if ( d0 <= ON_EPSILON || d1 <= ON_EPSILON || fabs(d) >= d0*d1* ON_SQRT_EPSILON )
rc = false;
}
return rc;
}
bool ON_Matrix::IsRowOrthoNormal() const
{
double d;
int i, j;
bool rc = IsRowOrthoganal();
if ( rc ) {
double const*const* this_m = ThisM();
for ( i = 0; i < m_row_count; i++ ) {
d = 0.0;
for ( j = 0; j < m_col_count; j++ ) {
d += this_m[i][j]*this_m[i][j];
}
if ( fabs(1.0-d) >= ON_SQRT_EPSILON )
rc = false;
}
}
return rc;
}
bool ON_Matrix::IsColOrthoganal() const
{
double d0, d1, d;
int i, j0, j1;
bool rc = ( m_col_count <= m_row_count && m_col_count > 0 );
double const*const* this_m = ThisM();
for ( j0 = 0; j0 < m_col_count && rc; j0++ ) for ( j1 = j0+1; j1 < m_col_count && rc; j1++ ) {
d0 = d1 = d = 0.0;
for ( i = 0; i < m_row_count; i++ ) {
d0 += fabs(this_m[i][j0]);
d1 += fabs(this_m[i][j0]);
d += this_m[i][j0]*this_m[i][j1];
}
if ( d0 <= ON_EPSILON || d1 <= ON_EPSILON || fabs(d) > ON_SQRT_EPSILON )
rc = false;
}
return rc;
}
bool ON_Matrix::IsColOrthoNormal() const
{
double d;
int i, j;
bool rc = IsColOrthoganal();
double const*const* this_m = ThisM();
if ( rc ) {
for ( j = 0; j < m_col_count; j++ ) {
d = 0.0;
for ( i = 0; i < m_row_count; i++ ) {
d += this_m[i][j]*this_m[i][j];
}
if ( fabs(1.0-d) >= ON_SQRT_EPSILON )
rc = false;
}
}
return rc;
}
bool ON_Matrix::Invert( double zero_tolerance )
{
ON_Workspace ws;
int i, j, k, ix, jx, rank;
double x;
const int n = MinCount();
if ( n < 1 )
return false;
ON_Matrix I(m_col_count, m_row_count);
int* col = ws.GetIntMemory(n);
I.SetDiagonal(1.0);
rank = 0;
double** this_m = ThisM();
for ( k = 0; k < n; k++ ) {
// find largest value in sub matrix
ix = jx = k;
x = fabs(this_m[ix][jx]);
for ( i = k; i < n; i++ ) {
for ( j = k; j < n; j++ ) {
if ( fabs(this_m[i][j]) > x ) {
ix = i;
jx = j;
x = fabs(this_m[ix][jx]);
}
}
}
SwapRows( k, ix );
I.SwapRows( k, ix );
SwapCols( k, jx );
col[k] = jx;
if ( x <= zero_tolerance ) {
break;
}
x = 1.0/this_m[k][k];
this_m[k][k] = 1.0;
ON_ArrayScale( m_col_count-k-1, x, &this_m[k][k+1], &this_m[k][k+1] );
I.RowScale( k, x );
// zero this_m[!=k][k]'s
for ( i = 0; i < n; i++ ) {
if ( i != k ) {
x = -this_m[i][k];
this_m[i][k] = 0.0;
if ( fabs(x) > zero_tolerance ) {
ON_Array_aA_plus_B( m_col_count-k-1, x, &this_m[k][k+1], &this_m[i][k+1], &this_m[i][k+1] );
I.RowOp( i, x, k );
}
}
}
}
// take care of column swaps
for ( i = k-1; i >= 0; i-- ) {
if ( i != col[i] )
I.SwapRows(i,col[i]);
}
*this = I;
return (k == n) ? true : false;
}
bool ON_Matrix::Multiply( const ON_Matrix& a, const ON_Matrix& b )
{
int i, j, k, mult_count;
double x;
if (a.ColCount() != b.RowCount() )
return false;
if ( a.RowCount() < 1 || a.ColCount() < 1 || b.ColCount() < 1 )
return false;
if ( this == &a ) {
ON_Matrix tmp(a);
return Multiply(tmp,b);
}
if ( this == &b ) {
ON_Matrix tmp(b);
return Multiply(a,tmp);
}
Create( a.RowCount(), b.ColCount() );
mult_count = a.ColCount();
double const*const* am = a.ThisM();
double const*const* bm = b.ThisM();
double** this_m = ThisM();
for ( i = 0; i < m_row_count; i++ ) for ( j = 0; j < m_col_count; j++ ) {
x = 0.0;
for (k = 0; k < mult_count; k++ ) {
x += am[i][k] * bm[k][j];
}
this_m[i][j] = x;
}
return true;
}
bool ON_Matrix::Add( const ON_Matrix& a, const ON_Matrix& b )
{
int i, j;
if (a.ColCount() != b.ColCount() )
return false;
if (a.RowCount() != b.RowCount() )
return false;
if ( a.RowCount() < 1 || a.ColCount() < 1 )
return false;
if ( this != &a && this != &b ) {
Create( a.RowCount(), b.ColCount() );
}
double const*const* am = a.ThisM();
double const*const* bm = b.ThisM();
double** this_m = ThisM();
for ( i = 0; i < m_row_count; i++ ) for ( j = 0; j < m_col_count; j++ ) {
this_m[i][j] = am[i][j] + bm[i][j];
}
return true;
}
bool ON_Matrix::Scale( double s )
{
bool rc = false;
if ( m_row_count > 0 && m_col_count > 0 )
{
struct DBLBLK* cmem = (struct DBLBLK*)m_cmem;
int i;
double* p;
while ( 0 != cmem )
{
if ( 0 != cmem->a && cmem->count > 0 )
{
p = cmem->a;
i = cmem->count;
while(i--)
*p++ *= s;
}
cmem = cmem->next;
}
rc = true;
}
/*
int i = m_a.Capacity();
if ( m_row_count > 0 && m_col_count > 0 && m_row_count*m_col_count <= i ) {
double* p = m_a.Array();
while ( i-- )
*p++ *= s;
rc = true;
}
*/
return rc;
}
int ON_RowReduce( int row_count,
int col_count,
double zero_pivot,
double** A,
double** B,
double pivots[2]
)
{
// returned A is identity, B = inverse of input A
const int M = row_count;
const int N = col_count;
const size_t sizeof_row = N*sizeof(A[0][0]);
int i, j, ii;
double a, p, p0, p1;
const double* ptr0;
double* ptr1;
if ( pivots )
{
pivots[0] = 0.0;
pivots[1] = 0.0;
}
if ( zero_pivot <= 0.0 || !ON_IsValid(zero_pivot) )
zero_pivot = 0.0;
for ( i = 0; i < M; i++ )
{
memset(B[i],0,sizeof_row);
if ( i < N )
B[i][i] = 1.0;
}
p0 = p1 = A[0][0];
for ( i = 0; i < M; i++ )
{
p = fabs(a = A[i][i]);
if ( p < p0 ) p0 = p; else if (p > p1) p1 = p;
if ( 1.0 != a )
{
if ( p <= zero_pivot || !ON_IsValid(a) )
{
break;
}
a = 1.0/a;
//A[i][i] = 1.0; // no need to do this
// The "ptr" voodoo is faster but does the same thing as
//
//for ( j = i+1; j < N; j++ )
// A[i][j] *= a;
//
j = i+1;
ptr1 = A[i] + j;
j = N - j;
while(j--) *ptr1++ *= a;
// The "ptr" voodoo is faster but does the same thing as
//
//for ( j = 0; j <= i; j++ )
// B[i][j] *= a;
//
ptr1 = B[i];
j = i+1;
while(j--) *ptr1++ *= a;
}
for ( ii = i+1; ii < M; ii++ )
{
a = A[ii][i];
if ( 0.0 == a )
continue;
a = -a;
//A[ii][i] = 0.0; // no need to do this
// The "ptr" voodoo is faster but does the same thing as
//
//for( j = i+1; j < N; j++ )
// A[ii][j] += a*A[i][j];
//
j = i+1;
ptr0 = A[i] + j;
ptr1 = A[ii] + j;
j = N - j;
while(j--) *ptr1++ += a* *ptr0++;
for( j = 0; j <= i; j++ )
B[ii][j] += a*B[i][j];
}
}
if ( pivots )
{
pivots[0] = p0;
pivots[1] = p1;
}
if ( i < M )
{
return i;
}
// A is now upper triangular with all 1s on diagonal
// (That is, if the lines that say "no need to do this" are used.)
// B is lower triangular with a nonzero diagonal
for ( i = M-1; i >= 0; i-- )
{
for ( ii = i-1; ii >= 0; ii-- )
{
a = A[ii][i];
if ( 0.0 == a )
continue;
a = -a;
//A[ii][i] = 0.0; // no need to do this
// The "ptr" voodoo is faster but does the same thing as
//
//for( j = 0; j < N; j++ )
// B[ii][j] += a*B[i][j];
//
ptr0 = B[i];
ptr1 = B[ii];
j = N;
while(j--) *ptr1++ += a* *ptr0++;
}
}
// At this point, A is trash.
// If the input A was really nice (positive definite....)
// the B = inverse of the input A. If A was not nice,
// B is also trash.
return M;
}
int ON_InvertSVDW(
int count,
const double* W,
double*& invW
)
{
double w, maxw;
int i;
if ( 0 == W || count <= 0 )
return -1;
if ( 0 == invW )
{
invW = (double*)onmalloc(count*sizeof(invW[0]));
}
maxw = fabs(W[0]);
for (i = 1; i < count; i++) {
w = fabs(W[i]);
if (w > maxw) maxw = w;
}
if (maxw == 0.0)
{
if ( W != invW )
memset(invW,0,count*sizeof(invW[0]));
return 0;
}
i = 0;
maxw *= ON_SQRT_EPSILON;
while (count--)
{
if (fabs(W[count]) > maxw)
{
i++;
invW[count] = 1.0/W[count];
}
else
invW[count] = 0.0;
}
return i; // number of nonzero terms in invW[]
}
bool ON_SolveSVD(
int row_count,
int col_count,
double const * const * U,
const double* invW,
double const * const * V,
const double* B,
double*& X
)
{
int i, j;
double *Y;
const double* p0;
double workY[128], x;
if ( row_count < 1 || col_count < 1 || 0 == U || 0 == invW || 0 == V || 0 == B)
return false;
if ( 0 == X )
X = (double*)onmalloc(col_count*sizeof(X[0]));
Y = (col_count > 128)
? ( (double*)onmalloc(col_count*sizeof(*Y)) )
: workY;
for (i = 0; i < col_count; i++)
{
double y = 0.0;
for (j = 0; j < row_count; j++)
y += U[j][i] * *B++;
B -= row_count;
Y[i] = invW[i] * y;
}
for (i = 0; i < col_count; i++)
{
p0 = V[i];
j = col_count;
x = 0.0;
while (j--)
x += *p0++ * *Y++;
Y -= col_count;
X[i] = x;
}
if (Y != workY)
onfree(Y);
return true;
}
| 22.958275 | 112 | 0.500121 | averbin |
f66b5ac0f48a4979e86d542880502816994cba65 | 4,364 | cpp | C++ | Source/bindings/core/v8/V8NodeFilterCondition.cpp | primiano/blink-gitcs | 0b5424070e3006102e0036deea1e2e263b871eaa | [
"BSD-3-Clause"
] | 1 | 2017-08-25T05:15:52.000Z | 2017-08-25T05:15:52.000Z | Source/bindings/core/v8/V8NodeFilterCondition.cpp | primiano/blink-gitcs | 0b5424070e3006102e0036deea1e2e263b871eaa | [
"BSD-3-Clause"
] | null | null | null | Source/bindings/core/v8/V8NodeFilterCondition.cpp | primiano/blink-gitcs | 0b5424070e3006102e0036deea1e2e263b871eaa | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2008, 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "bindings/core/v8/V8NodeFilterCondition.h"
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8Node.h"
#include "core/dom/Node.h"
#include "core/dom/NodeFilter.h"
#include "wtf/OwnPtr.h"
namespace blink {
V8NodeFilterCondition::V8NodeFilterCondition(v8::Handle<v8::Value> filter, v8::Handle<v8::Object> owner, ScriptState* scriptState)
: m_scriptState(scriptState)
{
// ..acceptNode(..) will only dispatch m_filter if m_filter->IsObject().
// We'll make sure m_filter is either usable by acceptNode or empty.
// (See the fast/dom/node-filter-gc test for a case where 'empty' happens.)
if (!filter.IsEmpty() && filter->IsObject()) {
V8HiddenValue::setHiddenValue(scriptState->isolate(), owner, V8HiddenValue::condition(scriptState->isolate()), filter);
m_filter.set(scriptState->isolate(), filter);
m_filter.setWeak(this, &setWeakCallback);
}
}
V8NodeFilterCondition::~V8NodeFilterCondition()
{
}
short V8NodeFilterCondition::acceptNode(Node* node, ExceptionState& exceptionState) const
{
v8::Isolate* isolate = m_scriptState->isolate();
ASSERT(!m_scriptState->context().IsEmpty());
v8::HandleScope handleScope(isolate);
v8::Handle<v8::Value> filter = m_filter.newLocal(isolate);
ASSERT(filter.IsEmpty() || filter->IsObject());
if (filter.IsEmpty())
return NodeFilter::FILTER_ACCEPT;
v8::TryCatch exceptionCatcher;
v8::Handle<v8::Function> callback;
if (filter->IsFunction()) {
callback = v8::Handle<v8::Function>::Cast(filter);
} else {
v8::Local<v8::Value> value = filter->ToObject(isolate)->Get(v8AtomicString(isolate, "acceptNode"));
if (value.IsEmpty() || !value->IsFunction()) {
exceptionState.throwTypeError("NodeFilter object does not have an acceptNode function");
return NodeFilter::FILTER_REJECT;
}
callback = v8::Handle<v8::Function>::Cast(value);
}
OwnPtr<v8::Handle<v8::Value>[]> info = adoptArrayPtr(new v8::Handle<v8::Value>[1]);
v8::Handle<v8::Object> context = m_scriptState->context()->Global();
info[0] = toV8(node, context, isolate);
v8::Handle<v8::Value> result = ScriptController::callFunction(m_scriptState->executionContext(), callback, context, 1, info.get(), isolate);
if (exceptionCatcher.HasCaught()) {
exceptionState.rethrowV8Exception(exceptionCatcher.Exception());
return NodeFilter::FILTER_REJECT;
}
ASSERT(!result.IsEmpty());
return result->Int32Value();
}
void V8NodeFilterCondition::setWeakCallback(const v8::WeakCallbackData<v8::Value, V8NodeFilterCondition>& data)
{
data.GetParameter()->m_filter.clear();
}
} // namespace blink
| 40.785047 | 144 | 0.719982 | primiano |
f66c182b3e30c4aa1f2fb4b15a73b57ba40eba23 | 630 | inl | C++ | src/ScriptSystem/Init/details/UECS_AutoRefl/SingletonsView_AutoRefl.inl | Jerry-Shen0527/Utopia | 5f40edc814e5f6a33957cdc889524c41c5ef870f | [
"MIT"
] | 321 | 2020-10-04T01:43:36.000Z | 2022-03-31T02:43:38.000Z | src/ScriptSystem/Init/details/UECS_AutoRefl/SingletonsView_AutoRefl.inl | Jerry-Shen0527/Utopia | 5f40edc814e5f6a33957cdc889524c41c5ef870f | [
"MIT"
] | 9 | 2020-11-17T04:06:22.000Z | 2022-02-19T09:05:29.000Z | src/ScriptSystem/Init/details/UECS_AutoRefl/SingletonsView_AutoRefl.inl | Jerry-Shen0527/Utopia | 5f40edc814e5f6a33957cdc889524c41c5ef870f | [
"MIT"
] | 41 | 2020-10-09T10:09:34.000Z | 2022-03-27T02:51:57.000Z | // This file is generated by Ubpa::USRefl::AutoRefl
#pragma once
#include <USRefl/USRefl.h>
template<>
struct Ubpa::USRefl::TypeInfo<Ubpa::UECS::SingletonsView> :
TypeInfoBase<Ubpa::UECS::SingletonsView>
{
#ifdef UBPA_USREFL_NOT_USE_NAMEOF
static constexpr char name[27] = "Ubpa::UECS::SingletonsView";
#endif
static constexpr AttrList attrs = {};
static constexpr FieldList fields = {
Field {TSTR(UMeta::constructor), WrapConstructor<Type(Span<const UECS::CmptAccessPtr>)>()},
Field {TSTR("GetSingleton"), &Type::GetSingleton},
Field {TSTR("Singletons"), &Type::Singletons},
};
};
| 28.636364 | 99 | 0.695238 | Jerry-Shen0527 |
f66ccb4ebbe19d7275dd48c79f3e5646b8f2c47e | 4,241 | cpp | C++ | ace/tao/examples/Simple/grid/Grid_i.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/examples/Simple/grid/Grid_i.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/examples/Simple/grid/Grid_i.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // -*- C++ -*-
// Grid_i.cpp,v 1.20 2001/04/02 18:12:24 kitty Exp
#include "Grid_i.h"
#include "tao/corba.h"
// Default constructor.
Grid_i::Grid_i (void)
: width_ (0),
height_ (0),
array_ (0)
{
//no-op
}
// Constructor.
Grid_i::Grid_i (CORBA::Short x,
CORBA::Short y,
CORBA::Environment &ACE_TRY_ENV)
: width_ (x),
height_ (y)
{
ACE_NEW_THROW_EX (array_,
CORBA::Long *[y],
CORBA::NO_MEMORY ());
ACE_CHECK;
// Allocate memory for the matrix.
for (int ctr = 0; ctr < y; ctr++)
{
ACE_NEW_THROW_EX (array_[ctr],
CORBA::Long[x],
CORBA::NO_MEMORY ());
ACE_CHECK;
}
}
// Default destructor.
Grid_i::~Grid_i (void)
{
// no-op.
}
// Set a value in the grid.
void
Grid_i::set (CORBA::Short x,
CORBA::Short y,
CORBA::Long value,
CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException,
Grid::RANGE_ERROR))
{
if (x < 0
|| y < 0
|| x >= width_
|| y >= height_)
ACE_THROW (Grid::RANGE_ERROR ());
else
array_[x][y] = value;
}
// Get a value from the grid.
CORBA::Long
Grid_i::get (CORBA::Short x,
CORBA::Short y,
CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException,
Grid::RANGE_ERROR))
{
if (x < 0
|| y < 0
|| x >= width_
|| y >= height_)
ACE_THROW_RETURN (Grid::RANGE_ERROR (), -1);
else
return array_[x][y];
}
// Access methods.
CORBA::Short
Grid_i::width (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException))
{
return this->width_;
}
CORBA::Short
Grid_i::height (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException))
{
return this->height_;
}
void
Grid_i::width (CORBA::Short x,
CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException))
{
this->width_ = x;
}
void
Grid_i::height (CORBA::Short y,
CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException))
{
this->height_ = y;
}
// Destroy the grid
void
Grid_i::destroy (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException))
{
// Delete the array.
for (int i = 0; i < height_; i++)
delete [] array_[i];
delete [] array_;
ACE_DEBUG ((LM_DEBUG,
"(%P|%t) %s\n",
"Grid has been destroyed"));
}
// Set the ORB pointer.
void
Grid_Factory_i::orb (CORBA::ORB_ptr o)
{
this->orb_ = CORBA::ORB::_duplicate (o);
}
// Shutdown.
void
Grid_Factory_i::shutdown (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException))
{
ACE_DEBUG ((LM_DEBUG,
"(%P|%t) %s\n",
"Grid Factory is shutting down"));
// Instruct the ORB to shutdown.
this->orb_->shutdown ();
}
// Constructor
Grid_Factory_i::Grid_Factory_i (void)
{
// no-op
}
// Copy Constructor
Grid_Factory_i::Grid_Factory_i (Grid_Factory_i &grid)
:POA_Grid_Factory (grid)
{
// no-op
}
// Destructor
Grid_Factory_i::~Grid_Factory_i (void)
{
// no-op
}
// Make a <Grid>.
Grid_ptr
Grid_Factory_i::make_grid (CORBA::Short width,
CORBA::Short height,
CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException))
{
Grid_i *grid_ptr = 0;
ACE_DEBUG ((LM_DEBUG,
"(%P|%t) Making a new Grid\n"));
// Set a default value for width.
if (width <= 0)
width = Grid_Factory::DEFAULT_WIDTH;
// Set a default value for height.
if (height <= 0)
height = Grid_Factory::DEFAULT_HEIGHT;
// This attempts to create a new Grid_i and throws an exception and
// returns a null value if it fails
CORBA::Environment &env = ACE_TRY_ENV;
ACE_NEW_THROW_EX (grid_ptr,
Grid_i (width, height, env),
CORBA::NO_MEMORY ());
ACE_CHECK_RETURN (Grid::_nil ());
// Register the Grid pointer.
Grid_ptr gptr = grid_ptr->_this (ACE_TRY_ENV);
ACE_CHECK_RETURN (0);
return gptr;
}
| 19.910798 | 70 | 0.559066 | tharindusathis |
f66e04b24cd3d32c9759829ef5582ebbed696105 | 6,639 | cpp | C++ | libs/mathio/src/ostream.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | 1 | 2021-08-28T03:47:54.000Z | 2021-08-28T03:47:54.000Z | libs/mathio/src/ostream.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | null | null | null | libs/mathio/src/ostream.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <mathio/ostream.h>
#include <math/mat2.h>
#include <math/mat3.h>
#include <math/mat4.h>
#include <math/vec2.h>
#include <math/vec3.h>
#include <math/vec4.h>
#include <math/quat.h>
#include <math/half.h>
#include <iomanip>
#include <ostream>
#include <string>
namespace filament {
namespace math {
namespace details {
template<typename T>
std::ostream& printVector(std::ostream& stream, const T* data, size_t count) {
stream << "< ";
for (size_t i = 0; i < count - 1; i++) {
stream << data[i] << ", ";
}
stream << data[count - 1] << " >";
return stream;
}
template<typename T>
std::ostream& printMatrix(std::ostream& stream, const T* m, size_t rows, size_t cols) {
for (size_t row = 0; row < rows; ++row) {
if (row != 0) {
stream << std::endl;
}
if (row == 0) {
stream << "/ ";
} else if (row == rows - 1) {
stream << "\\ ";
} else {
stream << "| ";
}
for (size_t col = 0; col < cols; ++col) {
stream << std::setw(10) << std::to_string(m[row + col * rows]);
}
if (row == 0) {
stream << " \\";
} else if (row == rows - 1) {
stream << " /";
} else {
stream << " |";
}
}
return stream;
}
template<template<typename T> class BASE, typename T>
std::ostream& printQuat(std::ostream& stream, const BASE<T>& q) {
return stream << "< " << q.w << " + " << q.x << "i + " << q.y << "j + " << q.z << "k >";
}
} // namespace details
using namespace details;
template<typename T>
std::ostream& operator<<(std::ostream& out, const details::TVec2<T>& v) noexcept {
return printVector(out, v.v, 2);
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const details::TVec3<T>& v) noexcept {
return printVector(out, v.v, 3);
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const details::TVec4<T>& v) noexcept {
return printVector(out, v.v, 4);
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const details::TMat22<T>& v) noexcept {
return printMatrix(out, v.asArray(), 2, 2);
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const details::TMat33<T>& v) noexcept {
return printMatrix(out, v.asArray(), 3, 3);
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const details::TMat44<T>& v) noexcept {
return printMatrix(out, v.asArray(), 4, 4);
}
template std::ostream& operator<<(std::ostream& out, const details::TVec2<double>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<float>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<half>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<uint32_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<int32_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<uint16_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<int16_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<uint8_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<int8_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec2<bool>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<double>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<float>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<half>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<uint32_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<int32_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<uint16_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<int16_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<uint8_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<int8_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec3<bool>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<double>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<float>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<half>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<uint32_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<int32_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<uint16_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<int16_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<uint8_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<int8_t>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TVec4<bool>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TMat22<double>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TMat22<float>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TMat33<double>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TMat33<float>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TMat44<double>& v) noexcept;
template std::ostream& operator<<(std::ostream& out, const details::TMat44<float>& v) noexcept;
} // namespace math
} // namespace filament
| 41.754717 | 97 | 0.672993 | Alan-love |
f66f37cef2a4e4c2d23ef176fd390855137116b8 | 2,705 | hpp | C++ | include/clotho/cuda/data_spaces/sequence_space/device_sequence_space_kernels.hpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2015-06-16T21:27:57.000Z | 2022-01-25T23:26:54.000Z | include/clotho/cuda/data_spaces/sequence_space/device_sequence_space_kernels.hpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2015-06-16T21:12:42.000Z | 2015-06-23T12:41:00.000Z | include/clotho/cuda/data_spaces/sequence_space/device_sequence_space_kernels.hpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright 2015 Patrick Putnam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef DEVICE_SEQUENCE_SPACE_KERNELS_HPP_
#define DEVICE_SEQUENCE_SPACE_KERNELS_HPP_
#include "clotho/cuda/data_spaces/sequence_space/device_sequence_space_def.hpp"
#include "clotho/cuda/data_spaces/sequence_space/device_sequence_space_kernel_api.hpp"
template < class IntType >
__device__ void _resize_space_impl( device_sequence_space< IntType > * sspace, unsigned int cols, unsigned int rows ) {
// assert( blockIdx.y * gridDim.x + blockIdx.x == 0);
// assert( threadIdx.y * blockDim.x + threadIdx.x == 0 );
typedef typename device_sequence_space< IntType >::int_type int_type;
unsigned int N = cols * rows;
if( sspace->capacity < N ) {
int_type * seqs = sspace->sequences;
if( seqs ) {
delete seqs;
}
seqs = new int_type[ N ];
assert( seqs != NULL );
sspace->sequences = seqs;
sspace->capacity = N;
}
sspace->size = N;
sspace->seq_count = rows;
sspace->seq_width = cols;
}
template < class IntType >
__global__ void _resize_space( device_sequence_space< IntType > * sspace, unsigned int cols, unsigned int rows = 1 ) {
assert( blockIdx.y * gridDim.x + blockIdx.x == 0 );
if( threadIdx.y * blockDim.x + threadIdx.x == 0 ) {
_resize_space_impl( sspace, cols, rows );
}
};
template < class IntType, class ColumnSpaceType >
__global__ void _resize_space( device_sequence_space< IntType > * sspace, ColumnSpaceType * aspace, unsigned int seq_count ) {
assert( blockIdx.y * gridDim.x + blockIdx.x == 0 );
if( threadIdx.y * blockDim.x + threadIdx.x == 0 ) {
typedef device_sequence_space< IntType > space_type;
typedef typename space_type::int_type int_type;
unsigned int W = aspace->capacity;
W /= space_type::OBJECTS_PER_INT;
_resize_space_impl( sspace, W, seq_count );
}
}
template < class IntType >
__global__ void _delete_space( device_sequence_space< IntType > * sspace ) {
if( sspace->sequences != NULL ) {
delete sspace->sequences;
}
}
#endif // DEVICE_SEQUENCE_SPACE_KERNELS_HPP_
| 34.240506 | 126 | 0.686137 | putnampp |
f6735fb842458815a52fd84c4a647b00f7d0e0e4 | 24,618 | hpp | C++ | ESMF/src/Infrastructure/Mesh/include/sacado/Sacado_LFad_LogicalSparse.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 1 | 2018-07-05T16:48:58.000Z | 2018-07-05T16:48:58.000Z | ESMF/src/Infrastructure/Mesh/include/sacado/Sacado_LFad_LogicalSparse.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 1 | 2022-03-04T16:12:02.000Z | 2022-03-04T16:12:02.000Z | ESMF/src/Infrastructure/Mesh/include/sacado/Sacado_LFad_LogicalSparse.hpp | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | null | null | null | // @HEADER
// ***********************************************************************
//
// Sacado Package
// Copyright (2006) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
// USA
// Questions? Contact David M. Gay (dmgay@sandia.gov) or Eric T. Phipps
// (etphipp@sandia.gov).
//
// ***********************************************************************
// @HEADER
#ifndef SACADO_LFAD_LOGICALSPARSE_HPP
#define SACADO_LFAD_LOGICALSPARSE_HPP
#include "Sacado_LFad_LogicalSparseTraits.hpp"
#include "Sacado_LFad_ExpressionTraits.hpp"
#include "Sacado_Fad_DynamicStorage.hpp"
namespace Sacado {
//! Namespace for logical forward-mode AD classes
namespace LFad {
//! Wrapper for a generic expression template
/*!
* This template class serves as a wrapper for all Fad expression
* template classes.
*/
template <typename ExprT> class Expr {};
//! Meta-function for determining nesting with an expression
/*!
* This determines the level of nesting within nested Fad types.
* The default implementation works for any type that isn't a Fad type
* or an expression of Fad types.
*/
template <typename T>
struct ExprLevel {
static const unsigned value = 0;
};
template <typename T>
struct ExprLevel< Expr<T> > {
static const unsigned value =
ExprLevel< typename Expr<T>::value_type >::value + 1;
};
//! Determine whether a given type is an expression
template <typename T>
struct IsFadExpr {
static const bool value = false;
};
template <typename T>
struct IsFadExpr< Expr<T> > {
static const bool value = true;
};
// Forward declaration
template <typename ValT, typename LogT> class LogicalSparse;
/*!
* \brief Implementation class for computing the logical sparsity of a
* derivative using forward-mode AD.
*/
template <typename ValT, typename LogT>
class LogicalSparseImp :
public Fad::DynamicStorage<ValT,LogT> {
typedef Fad::DynamicStorage<ValT,LogT> Storage;
public:
//! Typename of values (e.g., double)
typedef ValT value_type;
//! Typename of scalar's (which may be different from ValT)
typedef typename ScalarType<value_type>::type scalar_type;
//! Logical type (i.e., type for derivative array components (e.g., bool)
typedef LogT logical_type;
/*!
* @name Initialization methods
*/
//@{
//! Default constructor
LogicalSparseImp() : Storage(value_type(0)) {}
//! Constructor with supplied value \c x
/*!
* Initializes value to \c x and derivative array is empty
*/
template <typename S>
LogicalSparseImp(const S& x, SACADO_ENABLE_VALUE_CTOR_DECL) :
Storage(x) {}
//! Constructor with size \c sz and value \c x
/*!
* Initializes value to \c x and derivative array 0 of length \c sz
*/
LogicalSparseImp(const int sz, const value_type & x) :
Storage(sz, x, InitDerivArray) {}
//! Constructor with size \c sz, index \c i, and value \c x
/*!
* Initializes value to \c x and derivative array of length \c sz
* as row \c i of the identity matrix, i.e., sets derivative component
* \c i to 1 and all other's to zero.
*/
LogicalSparseImp(const int sz, const int i, const value_type & x) :
Storage(sz, x, InitDerivArray) {
this->fastAccessDx(i)=logical_type(1);
}
//! Copy constructor
LogicalSparseImp(const LogicalSparseImp& x) :
Storage(x) {}
//! Copy constructor from any Expression object
template <typename S>
LogicalSparseImp(const Expr<S>& x, SACADO_ENABLE_EXPR_CTOR_DECL) :
Storage(value_type(0)) {
int sz = x.size();
if (sz != this->size())
this->resize(sz);
if (sz) {
if (x.hasFastAccess())
for(int i=0; i<sz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
else
for(int i=0; i<sz; ++i)
this->fastAccessDx(i) = x.dx(i);
}
this->val() = x.val();
}
//! Destructor
~LogicalSparseImp() {}
//! Set %LogicalSparseImp object as the \c ith independent variable
/*!
* Sets the derivative array of length \c n to the \c ith row of the
* identity matrix and has the same affect as the
* Implementation(const int sz, const int i, const T & x)
* constructor.
*/
void diff(const int ith, const int n) {
if (this->size() != n)
this->resize(n);
this->zero();
this->fastAccessDx(ith) = logical_type(1);
}
//! Returns whether two Fad objects have the same values
template <typename S>
SACADO_ENABLE_EXPR_FUNC(bool) isEqualTo(const Expr<S>& x) const {
typedef IsEqual<value_type> IE;
if (x.size() != this->size()) return false;
bool eq = IE::eval(x.val(), this->val());
for (int i=0; i<this->size(); i++)
eq = eq && IE::eval(x.dx(i), this->dx(i));
return eq;
}
//@}
/*!
* @name Derivative accessor methods
*/
//@{
//! Returns true if derivative array is not empty
bool hasFastAccess() const { return this->size()!=0;}
//! Returns true if derivative array is empty
bool isPassive() const { return this->size()!=0;}
//! Set whether variable is constant
void setIsConstant(bool is_const) {
if (is_const && this->size()!=0)
this->resize(0);
}
//@}
/*!
* @name Assignment operators
*/
//@{
//! Assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator=(const S& v) {
this->val() = v;
if (this->size()) {
this->zero();
this->resize(0);
}
return *this;
}
//! Assignment with Expr right-hand-side
LogicalSparseImp& operator=(const LogicalSparseImp& x) {
// Copy value & dx_
Storage::operator=(x);
return *this;
}
//! Assignment operator with any expression right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator=(const Expr<S>& x) {
int sz = x.size();
if (sz != this->size())
this->resize(sz);
if (sz) {
if (x.hasFastAccess())
for(int i=0; i<sz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
else
for(int i=0; i<sz; ++i)
this->fastAccessDx(i) = x.dx(i);
}
this->val() = x.val();
return *this;
}
//@}
/*!
* @name Unary operators
*/
//@{
//! Addition-assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator += (const S& v) {
this->val() += v;
return *this;
}
//! Subtraction-assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator -= (const S& v) {
this->val() -= v;
return *this;
}
//! Multiplication-assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator *= (const S& v) {
this->val() *= v;
return *this;
}
//! Division-assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparseImp&) operator /= (const S& v) {
this->val() /= v;
return *this;
}
//! Addition-assignment operator with LogicalSparseImp right-hand-side
LogicalSparseImp& operator += (const LogicalSparseImp& x) {
int xsz = x.size(), sz = this->size();
#ifdef SACADO_DEBUG
if ((xsz != sz) && (xsz != 0) && (sz != 0))
throw "LFad Error: Attempt to assign with incompatible sizes";
#endif
if (xsz) {
if (sz) {
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i);
}
else {
this->resize(xsz);
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
}
}
this->val() += x.val();
return *this;
}
//! Subtraction-assignment operator with LogicalSparseImp right-hand-side
LogicalSparseImp& operator -= (const LogicalSparseImp& x) {
int xsz = x.size(), sz = this->size();
#ifdef SACADO_DEBUG
if ((xsz != sz) && (xsz != 0) && (sz != 0))
throw "LFad Error: Attempt to assign with incompatible sizes";
#endif
if (xsz) {
if (sz) {
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i);
}
else {
this->resize(xsz);
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
}
}
this->val() -= x.val();
return *this;
}
//! Multiplication-assignment operator with LogicalSparseImp right-hand-side
LogicalSparseImp& operator *= (const LogicalSparseImp& x) {
int xsz = x.size(), sz = this->size();
#ifdef SACADO_DEBUG
if ((xsz != sz) && (xsz != 0) && (sz != 0))
throw "LFad Error: Attempt to assign with incompatible sizes";
#endif
if (xsz) {
if (sz) {
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i);
}
else {
this->resize(xsz);
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
}
}
this->val() *= x.val();
return *this;
}
//! Division-assignment operator with LogicalSparseImp right-hand-side
LogicalSparseImp& operator /= (const LogicalSparseImp& x) {
int xsz = x.size(), sz = this->size();
#ifdef SACADO_DEBUG
if ((xsz != sz) && (xsz != 0) && (sz != 0))
throw "LFad Error: Attempt to assign with incompatible sizes";
#endif
if (xsz) {
if (sz) {
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i);
}
else {
this->resize(xsz);
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
}
}
this->val() /= x.val();
return *this;
}
//! Addition-assignment operator with Expr right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator += (const Expr<S>& x){
int xsz = x.size(), sz = this->size();
#ifdef SACADO_DEBUG
if ((xsz != sz) && (xsz != 0) && (sz != 0))
throw "LFad Error: Attempt to assign with incompatible sizes";
#endif
if (xsz) {
if (sz) {
if (x.hasFastAccess())
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i);
else
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.dx(i);
}
else {
this->resize(xsz);
if (x.hasFastAccess())
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
else
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.dx(i);
}
}
this->val() += x.val();
return *this;
}
//! Subtraction-assignment operator with Expr right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator -= (const Expr<S>& x){
int xsz = x.size(), sz = this->size();
#ifdef SACADO_DEBUG
if ((xsz != sz) && (xsz != 0) && (sz != 0))
throw "LFad Error: Attempt to assign with incompatible sizes";
#endif
if (xsz) {
if (sz) {
if (x.hasFastAccess())
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i);
else
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.dx(i);
}
else {
this->resize(xsz);
if (x.hasFastAccess())
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
else
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.dx(i);
}
}
this->val() -= x.val();
return *this;
}
//! Multiplication-assignment operator with Expr right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator *= (const Expr<S>& x){
int xsz = x.size(), sz = this->size();
#ifdef SACADO_DEBUG
if ((xsz != sz) && (xsz != 0) && (sz != 0))
throw "LFad Error: Attempt to assign with incompatible sizes";
#endif
if (xsz) {
if (sz) {
if (x.hasFastAccess())
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i);
else
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.dx(i);
}
else {
this->resize(xsz);
if (x.hasFastAccess())
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
else
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.dx(i);
}
}
this->val() *= x.val();
return *this;
}
//! Division-assignment operator with Expr right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparseImp&) operator /= (const Expr<S>& x){
int xsz = x.size(), sz = this->size();
#ifdef SACADO_DEBUG
if ((xsz != sz) && (xsz != 0) && (sz != 0))
throw "LFad Error: Attempt to assign with incompatible sizes";
#endif
if (xsz) {
if (sz) {
if (x.hasFastAccess())
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.fastAccessDx(i);
else
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = this->fastAccessDx(i) || x.dx(i);
}
else {
this->resize(xsz);
if (x.hasFastAccess())
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.fastAccessDx(i);
else
for (int i=0; i<xsz; ++i)
this->fastAccessDx(i) = x.dx(i);
}
}
this->val() /= x.val();
return *this;
}
//@}
}; // class LogicalSparseImp
//! Expression template specialization for LogicalSparse
template <typename ValT, typename LogT>
class Expr< LogicalSparseImp<ValT,LogT> > :
public LogicalSparseImp<ValT,LogT> {
public:
//! Typename of values
typedef typename LogicalSparseImp<ValT,LogT>::value_type value_type;
//! Typename of scalar's (which may be different from value_type)
typedef typename LogicalSparseImp<ValT,LogT>::scalar_type scalar_type;
//! Typename of base-expressions
typedef LogicalSparse<ValT,LogT> base_expr_type;
//! Default constructor
Expr() :
LogicalSparseImp<ValT,LogT>() {}
//! Constructor with supplied value \c x
/*!
* Initializes value to \c x and derivative array is empty
*/
template <typename S>
Expr(const S & x, SACADO_ENABLE_VALUE_CTOR_DECL) :
LogicalSparseImp<ValT,LogT>(x) {}
//! Constructor with size \c sz and value \c x
/*!
* Initializes value to \c x and derivative array 0 of length \c sz
*/
Expr(const int sz, const ValT & x) :
LogicalSparseImp<ValT,LogT>(sz,x) {}
//! Constructor with size \c sz, index \c i, and value \c x
/*!
* Initializes value to \c x and derivative array of length \c sz
* as row \c i of the identity matrix, i.e., sets derivative component
* \c i to 1 and all other's to zero.
*/
Expr(const int sz, const int i, const ValT & x) :
LogicalSparseImp<ValT,LogT>(sz,i,x) {}
//! Copy constructor
Expr(const Expr& x) :
LogicalSparseImp<ValT,LogT>(x) {}
//! Copy constructor from any Expression object
template <typename S>
Expr(const Expr<S>& x, SACADO_ENABLE_EXPR_CTOR_DECL) :
LogicalSparseImp<ValT,LogT>(x) {}
//! Destructor
~Expr() {}
}; // class Expr<LogicalSparseImp>
/*!
* \brief User inteface class for computing the logical sparsity pattern
* of a derivative via forward-mode AD.
*/
template <typename ValT, typename LogT >
class LogicalSparse : public Expr< LogicalSparseImp<ValT,LogT > > {
public:
//! Base classes
typedef LogicalSparseImp< ValT,LogT > ImplType;
typedef Expr<ImplType> ExprType;
//! Typename of values
typedef typename ExprType::value_type value_type;
//! Typename of scalar's (which may be different from value_type)
typedef typename ExprType::scalar_type scalar_type;
//! Turn LogicalSparse into a meta-function class usable with mpl::apply
template <typename T, typename U = LogT>
struct apply {
typedef LogicalSparse<T,U> type;
};
/*!
* @name Initialization methods
*/
//@{
//! Default constructor.
/*!
* Initializes value to 0 and derivative array is empty
*/
LogicalSparse() :
ExprType() {}
//! Constructor with supplied value \c x of type ValueT
/*!
* Initializes value to \c x and derivative array is empty
*/
template <typename S>
LogicalSparse(const S& x, SACADO_ENABLE_VALUE_CTOR_DECL) :
ExprType(x) {}
//! Constructor with size \c sz and value \c x
/*!
* Initializes value to \c x and derivative array 0 of length \c sz
*/
LogicalSparse(const int sz, const ValT& x) :
ExprType(sz,x) {}
//! Constructor with size \c sz, index \c i, and value \c x
/*!
* Initializes value to \c x and derivative array of length \c sz
* as row \c i of the identity matrix, i.e., sets derivative component
* \c i to 1 and all other's to zero.
*/
LogicalSparse(const int sz, const int i, const ValT & x) :
ExprType(sz,i,x) {}
//! Copy constructor
LogicalSparse(const LogicalSparse& x) :
ExprType(x) {}
//! Copy constructor from any Expression object
template <typename S>
LogicalSparse(const Expr<S>& x, SACADO_ENABLE_EXPR_CTOR_DECL) :
ExprType(x) {}
//@}
//! Destructor
~LogicalSparse() {}
//! Assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator=(const S& v) {
ImplType::operator=(v);
return *this;
}
//! Assignment operator with LogicalSparse right-hand-side
LogicalSparse& operator=(const LogicalSparse& x) {
ImplType::operator=(static_cast<const ImplType&>(x));
return *this;
}
//! Assignment operator with any expression right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator=(const Expr<S>& x)
{
ImplType::operator=(x);
return *this;
}
//! Addition-assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator += (const S& x) {
ImplType::operator+=(x);
return *this;
}
//! Subtraction-assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator -= (const S& x) {
ImplType::operator-=(x);
return *this;
}
//! Multiplication-assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator *= (const S& x) {
ImplType::operator*=(x);
return *this;
}
//! Division-assignment operator with constant right-hand-side
template <typename S>
SACADO_ENABLE_VALUE_FUNC(LogicalSparse&) operator /= (const S& x) {
ImplType::operator/=(x);
return *this;
}
//! Addition-assignment operator with LogicalSparse right-hand-side
LogicalSparse& operator += (const LogicalSparse& x) {
ImplType::operator+=(static_cast<const ImplType&>(x));
return *this;
}
//! Subtraction-assignment operator with LogicalSparse right-hand-side
LogicalSparse& operator -= (const LogicalSparse& x) {
ImplType::operator-=(static_cast<const ImplType&>(x));
return *this;
}
//! Multiplication-assignment operator with LogicalSparse right-hand-side
LogicalSparse& operator *= (const LogicalSparse& x) {
ImplType::operator*=(static_cast<const ImplType&>(x));
return *this;
}
//! Division-assignment operator with LogicalSparse right-hand-side
LogicalSparse& operator /= (const LogicalSparse& x) {
ImplType::operator/=(static_cast<const ImplType&>(x));
return *this;
}
//! Addition-assignment operator with Expr right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator += (const Expr<S>& x) {
ImplType::operator+=(x);
return *this;
}
//! Subtraction-assignment operator with Expr right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator -= (const Expr<S>& x) {
ImplType::operator-=(x);
return *this;
}
//! Multiplication-assignment operator with Expr right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator *= (const Expr<S>& x) {
ImplType::operator*=(x);
return *this;
}
//! Division-assignment operator with Expr right-hand-side
template <typename S>
SACADO_ENABLE_EXPR_FUNC(LogicalSparse&) operator /= (const Expr<S>& x) {
ImplType::operator/=(x);
return *this;
}
}; // class LogicalSparse<ValT,LogT>
template <typename T, typename L>
struct ExprLevel< LogicalSparse<T,L> > {
static const unsigned value =
ExprLevel< typename LogicalSparse<T,L>::value_type >::value + 1;
};
} // namespace LFad
template <typename T>
struct IsExpr< LFad::Expr<T> > {
static const bool value = true;
};
template <typename T>
struct BaseExprType< LFad::Expr<T> > {
typedef typename LFad::Expr<T>::base_expr_type type;
};
template <typename T, typename L>
struct IsExpr< LFad::LogicalSparse<T,L> > {
static const bool value = true;
};
template <typename T, typename L>
struct BaseExprType< LFad::LogicalSparse<T,L> > {
typedef typename LFad::LogicalSparse<T,L>::base_expr_type type;
};
} // namespace Sacado
#include "Sacado_LFad_LogicalSparseOps.hpp"
#endif // SACADO_LFAD_LOGICALSPARSE_HPP
| 30.392593 | 83 | 0.566862 | joeylamcy |
f67383a22bc818daf38c06ea9b6933cfbf5e061e | 297 | cpp | C++ | tf_publisher/src/tf_publisher_main.cpp | HosseinSheikhi/ros2_ws | 410e5e554d077ff2f735f999fc00bb66a88ce8c0 | [
"MIT"
] | null | null | null | tf_publisher/src/tf_publisher_main.cpp | HosseinSheikhi/ros2_ws | 410e5e554d077ff2f735f999fc00bb66a88ce8c0 | [
"MIT"
] | null | null | null | tf_publisher/src/tf_publisher_main.cpp | HosseinSheikhi/ros2_ws | 410e5e554d077ff2f735f999fc00bb66a88ce8c0 | [
"MIT"
] | null | null | null | //
// Created by hossein on 9/22/20.
//
#include "tf_publisher/tf_publisher.h"
int main(int argc, char **argv){
rclcpp::init(argc, argv);
std::shared_ptr<TFPublisher> tf_publisher_node = std::make_shared<TFPublisher>();
rclcpp::spin(tf_publisher_node);
rclcpp::shutdown();
return 0;
} | 21.214286 | 83 | 0.703704 | HosseinSheikhi |
f674c0dcf600570b752370947e23f6a1f8003b21 | 5,896 | cpp | C++ | src/clinterface/batteryarg.cpp | pvavercak/randomness-testing-toolkit | 8a29349edee0dc44bc8e765708555dda57b9e339 | [
"MIT"
] | null | null | null | src/clinterface/batteryarg.cpp | pvavercak/randomness-testing-toolkit | 8a29349edee0dc44bc8e765708555dda57b9e339 | [
"MIT"
] | null | null | null | src/clinterface/batteryarg.cpp | pvavercak/randomness-testing-toolkit | 8a29349edee0dc44bc8e765708555dda57b9e339 | [
"MIT"
] | null | null | null | #include "clinterface/batteryarg.h"
namespace rtt {
namespace clinterface {
BatteryArg::BatteryArg() {}
BatteryArg::BatteryArg(const std::string & battery) {
init(battery);
}
std::string BatteryArg::getName(Constants::BatteryID batteryId) {
switch(batteryId) {
case Constants::BatteryID::NIST_STS:
return "NIST Statistical Testing Suite";
case Constants::BatteryID::DIEHARDER:
return "Dieharder";
case Constants::BatteryID::TU01_SMALLCRUSH:
return "TestU01 Small Crush";
case Constants::BatteryID::TU01_CRUSH:
return "TestU01 Crush";
case Constants::BatteryID::TU01_BIGCRUSH:
return "TestU01 Big Crush";
case Constants::BatteryID::TU01_RABBIT:
return "TestU01 Rabbit";
case Constants::BatteryID::TU01_ALPHABIT:
return "TestU01 Alphabit";
case Constants::BatteryID::TU01_BLOCK_ALPHABIT:
return "TestU01 Block Alphabit";
default:
raiseBugException("invalid battery id");
}
}
std::string BatteryArg::getShortName(Constants::BatteryID batteryId) {
switch(batteryId) {
case Constants::BatteryID::NIST_STS:
return "nist_sts";
case Constants::BatteryID::DIEHARDER:
return "dieharder";
case Constants::BatteryID::TU01_SMALLCRUSH:
return "tu01_smallcrush";
case Constants::BatteryID::TU01_CRUSH:
return "tu01_crush";
case Constants::BatteryID::TU01_BIGCRUSH:
return "tu01_bigcrush";
case Constants::BatteryID::TU01_RABBIT:
return "tu01_rabbit";
case Constants::BatteryID::TU01_ALPHABIT:
return "tu01_alphabit";
case Constants::BatteryID::TU01_BLOCK_ALPHABIT:
return "tu01_blockalphabit";
default:
raiseBugException("invalid battery id");
}
}
uint BatteryArg::getExpectedExitCode(Constants::BatteryID batteryId) {
switch(batteryId) {
case Constants::BatteryID::NIST_STS:
return 256;
case Constants::BatteryID::DIEHARDER:
case Constants::BatteryID::TU01_SMALLCRUSH:
case Constants::BatteryID::TU01_CRUSH:
case Constants::BatteryID::TU01_BIGCRUSH:
case Constants::BatteryID::TU01_RABBIT:
case Constants::BatteryID::TU01_ALPHABIT:
case Constants::BatteryID::TU01_BLOCK_ALPHABIT:
return 0;
default:
raiseBugException("invalid battery id");
}
}
Constants::BatteryID BatteryArg::getBatteryId() const {
initCheck();
return batteryId;
}
std::string BatteryArg::getName() const {
initCheck();
return name;
}
std::string BatteryArg::getShortName() const {
initCheck();
return shortName;
}
uint BatteryArg::getExpectedExitCode() const {
initCheck();
return expectedExitCode;
}
bool BatteryArg::isInTU01Family() const {
initCheck();
switch(batteryId) {
case Constants::BatteryID::NIST_STS:
case Constants::BatteryID::DIEHARDER:
return false;
case Constants::BatteryID::TU01_SMALLCRUSH:
case Constants::BatteryID::TU01_CRUSH:
case Constants::BatteryID::TU01_BIGCRUSH:
case Constants::BatteryID::TU01_RABBIT:
case Constants::BatteryID::TU01_ALPHABIT:
case Constants::BatteryID::TU01_BLOCK_ALPHABIT:
return true;
default:
raiseBugException("invalid battery id");
}
}
bool BatteryArg::isInTU01CrushFamily() const {
initCheck();
switch(batteryId) {
case Constants::BatteryID::NIST_STS:
case Constants::BatteryID::DIEHARDER:
case Constants::BatteryID::TU01_RABBIT:
case Constants::BatteryID::TU01_ALPHABIT:
case Constants::BatteryID::TU01_BLOCK_ALPHABIT:
return false;
case Constants::BatteryID::TU01_SMALLCRUSH:
case Constants::BatteryID::TU01_CRUSH:
case Constants::BatteryID::TU01_BIGCRUSH:
return true;
default:
raiseBugException("invalid battery id");
}
}
bool BatteryArg::isInTU01BitFamily() const {
initCheck();
switch(batteryId) {
case Constants::BatteryID::NIST_STS:
case Constants::BatteryID::DIEHARDER:
case Constants::BatteryID::TU01_SMALLCRUSH:
case Constants::BatteryID::TU01_CRUSH:
case Constants::BatteryID::TU01_BIGCRUSH:
return false;
case Constants::BatteryID::TU01_RABBIT:
case Constants::BatteryID::TU01_ALPHABIT:
case Constants::BatteryID::TU01_BLOCK_ALPHABIT:
return true;
default:
raiseBugException("invalid battery id");
}
}
bool BatteryArg::isInTU01AlphabitFamily() const {
initCheck();
switch(batteryId) {
case Constants::BatteryID::NIST_STS:
case Constants::BatteryID::DIEHARDER:
case Constants::BatteryID::TU01_SMALLCRUSH:
case Constants::BatteryID::TU01_CRUSH:
case Constants::BatteryID::TU01_BIGCRUSH:
case Constants::BatteryID::TU01_RABBIT:
return false;
case Constants::BatteryID::TU01_ALPHABIT:
case Constants::BatteryID::TU01_BLOCK_ALPHABIT:
return true;
default:
raiseBugException("invalid battery id");
}
}
Constants::BatteryID BatteryArg::getBatteryIdFromShortName(const std::string & shortName){
Constants::BatteryID batteryId;
for(int i = 1; i < static_cast<int>(Constants::BatteryID::LAST_ITEM); ++i) {
batteryId = static_cast<Constants::BatteryID>(i);
if(shortName == getShortName(batteryId))
return batteryId;
}
throw std::runtime_error("unknown battery argument: " + shortName);
}
void BatteryArg::init(const std::string & shortName) {
if(initialized)
raiseBugException("BatteryArg is already initialized");
batteryId = getBatteryIdFromShortName(shortName);
this->shortName = shortName;
name = getName(batteryId);
expectedExitCode = getExpectedExitCode(batteryId);
initialized = true;
}
void BatteryArg::initCheck() const {
if(!initialized)
raiseBugException("BatteryArg is not initialized");
}
} // namespace clinterface
} // namespace rtt
| 29.044335 | 90 | 0.697592 | pvavercak |
f6751c072b76874425093e568f7d9da8981801fd | 9,149 | hh | C++ | extern/typed-geometry/src/typed-geometry/functions/objects/rasterize.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/typed-geometry/src/typed-geometry/functions/objects/rasterize.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/typed-geometry/src/typed-geometry/functions/objects/rasterize.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
#include <typed-geometry/functions/basic/limits.hh>
#include <typed-geometry/functions/vector/math.hh>
#include <typed-geometry/types/objects/triangle.hh>
#include "aabb.hh"
#include "coordinates.hh"
/**
* Rasterization of objects
*
* Enumerates all integer points (tg::ipos2, tg::ipos3, ...) that are contained in the objects
* (e.g. contains(obj, pos) == true for all enumerated positions)
*/
namespace tg
{
// F: (tg::ipos2 p, float a) -> void
template <class ScalarT, class F>
constexpr void rasterize(segment<2, ScalarT> const& l, F&& f)
{
// TODO add limits?
// bresenham, see http://www.roguebasin.com/index.php?title=Bresenham%27s_Line_Algorithm
auto x0 = iround(l.pos0.x);
auto x1 = iround(l.pos1.x);
auto y0 = iround(l.pos0.y);
auto y1 = iround(l.pos1.y);
auto delta_x = x1 - x0;
// if x1 == x2, then it does not matter what we set here
signed char const ix((delta_x > 0) - (delta_x < 0));
delta_x = std::abs(delta_x) << 1;
auto delta_y = y1 - y0;
// if y1 == y2, then it does not matter what we set here
signed char const iy((delta_y > 0) - (delta_y < 0));
delta_y = std::abs(delta_y) << 1;
// start
f(tg::ipos2(x0, y0), ScalarT(0));
if (delta_x >= delta_y)
{
// done
if (x0 == x1)
return;
// error may go below zero
int error(delta_y - (delta_x >> 1));
while (x0 != x1)
{
// reduce error, while taking into account the corner case of error == 0
if ((error > 0) || (!error && (ix > 0)))
{
error -= delta_x;
y0 += iy;
}
// else do nothing
error += delta_y;
x0 += ix;
f(tg::ipos2(x0, y0), min(length(tg::pos2(x0, y0) - l.pos0) / length(l.pos1 - l.pos0), ScalarT(1)));
}
}
else
{
// done
if (y0 == y1)
return;
// error may go below zero
int error(delta_x - (delta_y >> 1));
while (y1 != y0)
{
// reduce error, while taking into account the corner case of error == 0
if ((error > 0) || (!error && (iy > 0)))
{
error -= delta_y;
x0 += ix;
}
// else do nothing
error += delta_x;
y0 += iy;
f(tg::ipos2(x0, y0), min(length(tg::pos2(x0, y0) - l.pos0) / length(l.pos1 - l.pos0), ScalarT(1)));
}
}
}
// F: (tg::ipos2 p, float a, float b) -> void
// offset is subpixel offset, e.g. 0.5f means sampling at pixel center
template <class ScalarT, class F>
constexpr void rasterize_bresenham(triangle<2, ScalarT> const& t, F&& f)
{
// bresenham 3 sides of a triangle, then fill contour
// inspired by https://stackoverflow.com/a/11145708
auto const box = aabb_of(t);
// margin so that we can safely round/clamp to integer coords
auto const minPix = ifloor(box.min);
auto const maxPix = iceil(box.max);
// TODO no abs, correct?
// auto const width = maxPix.x - minPix.x;
auto const height = maxPix.y - minPix.y;
// stores leftmost and rightmost pixel from bresenham
auto contour = new int*[uint(height)];
for (auto r = 0; r < height; r++)
{
contour[r] = new int[2];
// will bresenham to find left and right bounds of row
// will scanline only if row[0] <= row[1]
contour[r][0] = tg::detail::limits<int>().max();
contour[r][1] = tg::detail::limits<int>().min();
}
// rasterize two sides of the triangle
auto lines = {tg::segment(t.pos0, t.pos1), tg::segment(t.pos1, t.pos2), tg::segment(t.pos2, t.pos0)};
// note that if the triangle is "flat" (that means one side is not slanted with respect to the pixel grid) two edges would be sufficient!
// rasterize to get triangle contour for each row
for (auto l : lines)
tg::rasterize(l, [&](tg::ipos2 p, ScalarT a) {
auto iy = p.y - minPix.y;
if (iy < 0 || iy >= height)
// std::cout << "bad y: " << iy << " | height is " << height << std::endl;
return;
// update contour
if (p.x < contour[iy][0])
contour[iy][0] = p.x;
if (p.x > contour[iy][1])
contour[iy][1] = p.x;
// TODO interpolate line parameters for bary?
(void)a;
});
for (auto y = 0; y < height; ++y)
{
// bresenham was here
for (auto x = contour[y][0]; x <= contour[y][1]; x++)
{
auto const pos = tg::ipos2(x, y + minPix.y);
// TODO if experimental: derive bary from line parameters and x / (maxPix.x - minPix.x) instead?
// TODO note that calculating barycentrics for pixels may give values outside 0..1 as pixels may be
// "touched" by a triangle but e.g. their topleft corner may not actually be contained
// TODO offset?
auto const off = ScalarT(0.0); // subpixel offset
auto bary = tg::coordinates(t, tg::pos2(pos.x + off, pos.y + off));
// TODO might be slightly outside of triangle, clamp
bary[0] = tg::clamp(bary[0], 0, 1);
bary[1] = tg::clamp(bary[1], 0, 1);
f(pos, bary[0], bary[1]);
}
}
}
// no barycentric coords returned:
// F: (tg::ipos2 p) -> void
// offset is subpixel offset, e.g. 0.5f means sampling at pixel center
template <class ScalarT, class F>
constexpr void fast_rasterize(triangle<2, ScalarT> const& t, F&& f, tg::vec<2, ScalarT> const& offset = tg::vec<2, ScalarT>(0))
{
// adaptive half-space rasterization
// see https://www.uni-obuda.hu/journal/Mileff_Nehez_Dudra_63.pdf
auto const fbox = aabb_of(t);
auto box = tg::aabb<2, int>(tg::ipos2(ifloor(fbox.min)), tg::ipos2(iceil(fbox.max)));
// edge functions and their constants
ScalarT edgeConstants[3 * 3];
tg::pos<2, ScalarT> verts[3] = {t.pos0, t.pos1, t.pos2};
// edges AB, BC and CA
for (auto e = 0; e < 3; e++)
{
auto next = (e + 1) % 3;
edgeConstants[e * 3 + 0] = verts[e].y - verts[next].y;
edgeConstants[e * 3 + 1] = verts[next].x - verts[e].x;
edgeConstants[e * 3 + 2] = verts[e].x * verts[next].y - verts[e].y * verts[next].x;
}
auto edgeFunction = [edgeConstants, offset](tg::ipos2 pos, int f) {
auto first = min(f * 3, 6);
return edgeConstants[first + 0] * (pos.x + offset.x) + edgeConstants[first + 1] * (pos.y + offset.y) + edgeConstants[first + 2];
};
auto renderBlock = [f, edgeFunction, edgeConstants](int x, int y, int sizeX, int sizeY) {
if (sizeX * sizeY <= 0)
return;
// compute once, increment later
auto pos = tg::ipos2(x, y);
auto cy1 = edgeFunction(pos, 0);
auto cy2 = edgeFunction(pos, 1);
auto cy3 = edgeFunction(pos, 2);
auto cx1 = cy1;
auto cx2 = cy2;
auto cx3 = cy3;
for (auto py = y; py < y + sizeY; py++)
{
// y has changed, clip cx to cy
cx1 = cy1;
cx2 = cy2;
cx3 = cy3;
for (auto px = x; px < x + sizeX; px++)
{
// allows for both ccw and cc vertex order
auto in = (cx1 < 0 && cx2 < 0 && cx3 < 0) || (cx1 >= 0 && cx2 >= 0 && cx3 >= 0);
if (in)
{
f(tg::ipos2(px, py));
}
// increment
cx1 += edgeConstants[3 * 0 + 0]; // I values
cx2 += edgeConstants[3 * 1 + 0];
cx3 += edgeConstants[3 * 2 + 0];
}
// update cy values
cy1 += edgeConstants[3 * 0 + 1]; // J values
cy2 += edgeConstants[3 * 1 + 1];
cy3 += edgeConstants[3 * 2 + 1];
}
};
auto width = box.max.x - box.min.x;
auto height = box.max.y - box.min.y;
renderBlock(box.min.x, box.min.y, width, height);
}
// F: (tg::ipos2 p, float a, float b) -> void
// offset is subpixel offset, e.g. 0.5f means sampling at pixel center
template <class ScalarT, class F>
constexpr void rasterize(triangle<2, ScalarT> const& t, F&& f, tg::vec<2, ScalarT> const& offset = tg::vec<2, ScalarT>(0))
{
auto const box = aabb_of(t);
// margin so that we can safely round/clamp to integer coords
auto const minPix = ifloor(box.min);
auto const maxPix = iceil(box.max);
// TODO: Bresenham on two of the triangle edges, then scanline
for (auto y = minPix.y; y <= maxPix.y; ++y)
for (auto x = minPix.x; x <= maxPix.x; ++x)
{
auto const pos = tg::pos<2, ScalarT>(ScalarT(x), ScalarT(y)) + offset;
auto const bary = coordinates(t, pos);
auto const a = bary[0];
auto const b = bary[1];
auto const c = bary[2];
if (a >= 0 && b >= 0 && c >= 0)
{
// inside triangle
f(ipos2(x, y), a, b);
}
}
}
} // namespace tg
| 32.101754 | 141 | 0.529675 | rovedit |
f677471113ab9a5273f15f27f139c97467d6fbfb | 15,862 | cpp | C++ | quantitative_finance/L2/tests/GarmanKohlhagenEngine/src/host/gk_test.cpp | Geekdude/Vitis_Libraries | bca52cee88c07e9ccbec90c00e6df98f4b450ec1 | [
"Apache-2.0"
] | 1 | 2020-10-27T07:37:10.000Z | 2020-10-27T07:37:10.000Z | quantitative_finance/L2/tests/GarmanKohlhagenEngine/src/host/gk_test.cpp | Geekdude/Vitis_Libraries | bca52cee88c07e9ccbec90c00e6df98f4b450ec1 | [
"Apache-2.0"
] | null | null | null | quantitative_finance/L2/tests/GarmanKohlhagenEngine/src/host/gk_test.cpp | Geekdude/Vitis_Libraries | bca52cee88c07e9ccbec90c00e6df98f4b450ec1 | [
"Apache-2.0"
] | 1 | 2021-04-28T05:58:38.000Z | 2021-04-28T05:58:38.000Z | /*
* Copyright 2019 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file gk_test.cpp
* @brief Testbench to generate randomized input data and launch on kernel.
* Results are compared to a full precision model.
*/
#include <stdio.h>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <chrono>
#include "gk_host.hpp"
#include "xcl2.hpp"
/// @def Controls the data type used in the kernel
#define KERNEL_DT float
// Temporary copy of this macro definition until new xcl2.hpp is used
#define OCL_CHECK(error, call) \
call; \
if (error != CL_SUCCESS) { \
printf("%s:%d Error calling " #call ", error code is: %d\n", __FILE__, __LINE__, error); \
exit(EXIT_FAILURE); \
}
static void usage(std::string exe) {
std::cout << "Usage: " << exe << " ./xclbin/<kernel_name> <test data file>" << std::endl;
std::cout << "Test data file line format:" << std::endl;
std::cout << "s=<value>, k=<value>, r_domestic=<value>1, r_foreign=<value>1, v=<value>1, t=<value>" << std::endl;
std::cout << "# comments out the line" << std::endl;
}
static int validate_parameters(int argc, char* argv[]) {
/* check 2 arguments specified */
if (argc != 3) {
usage(argv[0]);
return 0;
}
/* check xclbin file exists */
std::ifstream ifs1(argv[1]);
if (!ifs1.is_open()) {
std::cout << "ERROR: cannot open " << argv[1] << std::endl;
return 0;
}
/* check test data file exists */
std::ifstream ifs2(argv[2]);
if (!ifs2.is_open()) {
std::cout << "ERROR: cannot open " << argv[2] << std::endl;
return 0;
}
return 1;
}
/// @brief Main entry point to test
///
/// This is a command-line application to test the kernel. It supports software
/// and hardware emulation as well as
/// running on an Alveo target.
///
/// Usage: ./gk_test ./xclbin/<kernel_name> <test data file>
///
/// @param[in] argc Standard C++ argument count
/// @param[in] argv Standard C++ input arguments
int main(int argc, char* argv[]) {
std::cout << std::endl << std::endl;
std::cout << "**************************" << std::endl;
std::cout << "Garman-Kohlhagen Demo v1.0" << std::endl;
std::cout << "**************************" << std::endl;
std::cout << std::endl;
if (!validate_parameters(argc, argv)) {
exit(1);
}
// parse the input test data file
std::vector<struct parsed_params*>* vect = parse_file(argv[2]);
if (vect == nullptr) {
return 1;
}
unsigned int num = vect->size();
// kernel expects multiple of 16 input data
unsigned int remainder = num % 16;
unsigned int extra = 0;
if (remainder != 0) {
extra = 16 - remainder;
}
unsigned int modified_num = num + extra;
// Test parameters
static const unsigned int call = 1;
std::string xclbin_file(argv[1]);
// Vectors for parameter storage. These use an aligned allocator in order
// to avoid an additional copy of the host memory into the device
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > s(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > v(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > r_domestic(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > r_foreign(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > t(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > k(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > price(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > delta(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > gamma(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > vega(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > theta(modified_num);
std::vector<KERNEL_DT, aligned_allocator<KERNEL_DT> > rho(modified_num);
// Host results (always double precision)
double* host_price = new double[modified_num];
double* host_delta = new double[modified_num];
double* host_gamma = new double[modified_num];
double* host_vega = new double[modified_num];
double* host_theta = new double[modified_num];
double* host_rho = new double[modified_num];
// write the test data to the input vectors and calculate the model results
std::cout << "Generating reference results..." << std::endl;
for (unsigned int i = 0; i < num; i++) {
s[i] = vect->at(i)->s;
v[i] = vect->at(i)->v;
t[i] = vect->at(i)->t;
k[i] = vect->at(i)->k;
r_domestic[i] = vect->at(i)->r_domestic;
r_foreign[i] = vect->at(i)->r_foreign;
}
for (unsigned int i = num; i < modified_num; i++) {
s[i] = 0;
v[i] = 0;
t[i] = 0;
k[i] = 0;
r_domestic[i] = 0;
r_foreign[i] = 0;
}
std::cout << "Running CPU model..." << std::endl;
auto t_start = std::chrono::high_resolution_clock::now();
for (unsigned int i = 0; i < num; i++) {
gk_model(s[i], v[i], r_domestic[i], t[i], k[i], r_foreign[i], call, host_price[i], host_delta[i], host_gamma[i],
host_vega[i], host_theta[i], host_rho[i]);
}
auto cpu_duration =
std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - t_start)
.count();
// OPENCL HOST CODE AREA START
// get_xil_devices() is a utility API which will find the xilinx
// platforms and will return list of devices connected to Xilinx platform
std::cout << "Connecting to device and loading kernel..." << std::endl;
std::vector<cl::Device> devices = xcl::get_xil_devices();
cl::Device device = devices[0];
cl_int err;
OCL_CHECK(err, cl::Context context(device, NULL, NULL, NULL, &err));
OCL_CHECK(err, cl::CommandQueue cq(context, device, CL_QUEUE_PROFILING_ENABLE, &err));
// Load the binary file (using function from xcl2.cpp)
cl::Program::Binaries bins = xcl::import_binary_file(xclbin_file);
devices.resize(1);
OCL_CHECK(err, cl::Program program(context, devices, bins, NULL, &err));
OCL_CHECK(err, cl::Kernel krnl_cfGKEngine(program, "gk_kernel", &err));
// Allocate Buffer in Global Memory
// Buffers are allocated using CL_MEM_USE_HOST_PTR for efficient memory and
// Device-to-host communication
std::cout << "Allocating buffers..." << std::endl;
OCL_CHECK(err, cl::Buffer buffer_s(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
modified_num * sizeof(KERNEL_DT), s.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_v(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
modified_num * sizeof(KERNEL_DT), v.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_r_domestic(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
modified_num * sizeof(KERNEL_DT), r_domestic.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_t(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
modified_num * sizeof(KERNEL_DT), t.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_k(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
modified_num * sizeof(KERNEL_DT), k.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_r_foreign(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
modified_num * sizeof(KERNEL_DT), r_foreign.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_price(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
modified_num * sizeof(KERNEL_DT), price.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_delta(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
modified_num * sizeof(KERNEL_DT), delta.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_gamma(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
modified_num * sizeof(KERNEL_DT), gamma.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_vega(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
modified_num * sizeof(KERNEL_DT), vega.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_theta(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
modified_num * sizeof(KERNEL_DT), theta.data(), &err));
OCL_CHECK(err, cl::Buffer buffer_rho(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
modified_num * sizeof(KERNEL_DT), rho.data(), &err));
// Set the arguments
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(0, buffer_s));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(1, buffer_v));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(2, buffer_r_domestic));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(3, buffer_t));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(4, buffer_k));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(5, buffer_r_foreign));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(6, call));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(7, modified_num));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(8, buffer_price));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(9, buffer_delta));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(10, buffer_gamma));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(11, buffer_vega));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(12, buffer_theta));
OCL_CHECK(err, err = krnl_cfGKEngine.setArg(13, buffer_rho));
// Copy input data to device global memory
t_start = std::chrono::high_resolution_clock::now();
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_s}, 0));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_v}, 0));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_r_domestic}, 0));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_t}, 0));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_k}, 0));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_r_foreign}, 0));
// Launch the Kernel
std::cout << "Launching kernel..." << std::endl;
uint64_t nstimestart, nstimeend;
cl::Event event;
OCL_CHECK(err, err = cq.enqueueTask(krnl_cfGKEngine, NULL, &event));
OCL_CHECK(err, err = cq.finish());
OCL_CHECK(err, err = event.getProfilingInfo<uint64_t>(CL_PROFILING_COMMAND_START, &nstimestart));
OCL_CHECK(err, err = event.getProfilingInfo<uint64_t>(CL_PROFILING_COMMAND_END, &nstimeend));
auto duration_nanosec = nstimeend - nstimestart;
// Copy Result from Device Global Memory to Host Local Memory
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_price}, CL_MIGRATE_MEM_OBJECT_HOST));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_delta}, CL_MIGRATE_MEM_OBJECT_HOST));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_gamma}, CL_MIGRATE_MEM_OBJECT_HOST));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_vega}, CL_MIGRATE_MEM_OBJECT_HOST));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_theta}, CL_MIGRATE_MEM_OBJECT_HOST));
OCL_CHECK(err, err = cq.enqueueMigrateMemObjects({buffer_rho}, CL_MIGRATE_MEM_OBJECT_HOST));
cq.finish();
auto fpga_duration =
std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - t_start)
.count();
// OPENCL HOST CODE AREA END
// Check results
double max_price_diff = 0.0f;
double max_delta_diff = 0.0f;
double max_gamma_diff = 0.0f;
double max_vega_diff = 0.0f;
double max_theta_diff = 0.0f;
double max_rho_diff = 0.0f;
for (unsigned int i = 0; i < num; i++) {
double temp = 0.0f;
std::cout << price[i] << " " << host_price[i] << " diff = " << price[i] - host_price[i] << std::endl;
if (std::abs(temp = (price[i] - host_price[i])) > std::abs(max_price_diff)) max_price_diff = temp;
if (std::abs(temp = (delta[i] - host_delta[i])) > std::abs(max_delta_diff)) max_delta_diff = temp;
if (std::abs(temp = (gamma[i] - host_gamma[i])) > std::abs(max_gamma_diff)) max_gamma_diff = temp;
if (std::abs(temp = (vega[i] - host_vega[i])) > std::abs(max_vega_diff)) max_vega_diff = temp;
if (std::abs(temp = (theta[i] - host_theta[i])) > std::abs(max_theta_diff)) max_theta_diff = temp;
if (std::abs(temp = (rho[i] - host_rho[i])) > std::abs(max_rho_diff)) max_rho_diff = temp;
}
std::cout << "Kernel done!" << std::endl;
std::cout << "Comparing results..." << std::endl;
std::cout << "Processed " << num;
if (call) {
std::cout << " call options:" << std::endl;
} else {
std::cout << " put options:" << std::endl;
}
std::cout << "Throughput = " << (1.0 * num) / (duration_nanosec * 1.0e-9) / 1.0e6 << " Mega options/sec"
<< std::endl;
std::cout << std::endl;
std::cout << " Largest host-kernel price difference = " << max_price_diff << std::endl;
std::cout << " Largest host-kernel delta difference = " << max_delta_diff << std::endl;
std::cout << " Largest host-kernel gamma difference = " << max_gamma_diff << std::endl;
std::cout << " Largest host-kernel vega difference = " << max_vega_diff << std::endl;
std::cout << " Largest host-kernel theta difference = " << max_theta_diff << std::endl;
std::cout << " Largest host-kernel rho difference = " << max_rho_diff << std::endl;
std::cout << "CPU execution time = " << cpu_duration << "us" << std::endl;
std::cout << "FPGA time returned by profile API = " << (duration_nanosec * (1.0e-6)) << " ms"
<< std::endl;
std::cout << "FPGA execution time (including mem transfer)= " << fpga_duration << "us" << std::endl;
int ret = 0;
if (std::abs(max_price_diff) > 6.0e-5) {
std::cout << "FAIL: max_price_diff = " << max_price_diff << std::endl;
ret = 1;
}
if (std::abs(max_delta_diff) > 4.0e-7) {
std::cout << "FAIL: max_delta_diff = " << max_delta_diff << std::endl;
ret = 1;
}
if (std::abs(max_gamma_diff) > 3.0e-7) {
std::cout << "FAIL: max_gamma_diff = " << max_gamma_diff << std::endl;
ret = 1;
}
if (std::abs(max_vega_diff) > 6.0e-7) {
std::cout << "FAIL: max_vega_diff = " << max_vega_diff << std::endl;
ret = 1;
}
if (std::abs(max_theta_diff) > 5.0e-8) {
std::cout << "FAIL: max_theta_diff = " << max_theta_diff << std::endl;
ret = 1;
}
if (std::abs(max_rho_diff) > 6.0e-7) {
std::cout << "FAIL: max_rho_diff = " << max_rho_diff << std::endl;
ret = 1;
}
if (!ret) {
std::cout << "PASS" << std::endl;
}
return ret;
}
| 47.208333 | 120 | 0.619279 | Geekdude |
f67868f2832fe24f3939dff1120585ad34e55879 | 1,925 | hpp | C++ | libs/lxcpp/commands/pivot-and-prep-root.hpp | Samsung/vasum | 53e3cd916141a336eb0cb59ba40cbdc83dc4d42c | [
"Apache-2.0"
] | 29 | 2015-05-27T14:09:44.000Z | 2020-12-27T11:21:54.000Z | libs/lxcpp/commands/pivot-and-prep-root.hpp | Samsung/vasum | 53e3cd916141a336eb0cb59ba40cbdc83dc4d42c | [
"Apache-2.0"
] | null | null | null | libs/lxcpp/commands/pivot-and-prep-root.hpp | Samsung/vasum | 53e3cd916141a336eb0cb59ba40cbdc83dc4d42c | [
"Apache-2.0"
] | 9 | 2015-10-08T10:59:07.000Z | 2020-01-21T17:57:21.000Z | /*
* Copyright (C) 2015 Samsung Electronics Co., Ltd All Rights Reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* @author Lukasz Pawelczyk (l.pawelczyk@samsung.com)
* @brief Headers of root FS preparation command
*/
#ifndef LXCPP_COMMANDS_PIVOT_AND_PREP_ROOT_HPP
#define LXCPP_COMMANDS_PIVOT_AND_PREP_ROOT_HPP
#include "lxcpp/commands/command.hpp"
#include "lxcpp/container-config.hpp"
namespace lxcpp {
class PivotAndPrepRoot final: Command {
public:
/**
* Does a pivot_root syscall and prepares the resulting root fs for its usage
*
* After the pivot_root previously prepared /dev and /dev/pts filesystems are mounted,
* as well as a list of static mounts that are required for a fully working OS.
* Things like /proc, /sys and security filesystem (if permitted).
*
* @param config A container config
*/
PivotAndPrepRoot(ContainerConfig &config);
~PivotAndPrepRoot();
void execute();
private:
ContainerConfig &mConfig;
const bool mIsUserNamespace;
const bool mIsNetNamespace;
void pivotRoot();
void cleanUpRoot();
void mountStatic();
void prepDev();
void symlinkStatic();
};
} // namespace lxcpp
#endif // LXCPP_COMMANDS_PIVOT_AND_PREP_ROOT_HPP
| 28.731343 | 90 | 0.722078 | Samsung |
f679521d60113e4d94f7538beb9a775997eb4066 | 4,002 | cpp | C++ | stl/src/xstoxflt.cpp | oktonion/STL | e2fce45b9ca899f3887b7fa48e24de95859a7b8e | [
"Apache-2.0"
] | 2 | 2021-01-19T02:43:19.000Z | 2021-11-20T05:21:42.000Z | stl/src/xstoxflt.cpp | tapaswenipathak/STL | 0d75fc5ab6684d4f6239879a6ec162aad0da860d | [
"Apache-2.0"
] | null | null | null | stl/src/xstoxflt.cpp | tapaswenipathak/STL | 0d75fc5ab6684d4f6239879a6ec162aad0da860d | [
"Apache-2.0"
] | 4 | 2020-04-24T05:04:54.000Z | 2020-05-17T22:48:58.000Z | // Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// _Stoxflt function
#include "xmath.h"
#include <ctype.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
_EXTERN_C_UNLESS_PURE
constexpr int _Base = 16; // hexadecimal
constexpr int _Ndig = 7; // hexadecimal digits per long element
constexpr int _Maxsig = 5 * _Ndig; // maximum significant digits to keep
int _Stoxflt(const char* s0, const char* s, char** endptr, long lo[],
int maxsig) { // convert string to array of long plus exponent
char buf[_Maxsig + 1]; // worst case, with room for rounding digit
int nsig = 0; // number of significant digits seen
int seen = 0; // any valid field characters seen
int word = 0; // current long word to fill
const char* pd;
static const char digits[] = "0123456789abcdefABCDEF";
static const char vals[] = {// values of hex digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 10, 11, 12, 13, 14, 15};
maxsig *= _Ndig; // convert word count to digit count
if (_Maxsig < maxsig) {
maxsig = _Maxsig; // protect against bad call
}
lo[0] = 0; // power of ten exponent
lo[1] = 0; // first _Ndig-digit word of fraction
while (*s == '0') { // strip leading zeros
++s;
seen = 1;
}
while ((pd = (char*) memchr(&digits[0], *s, 22)) != 0) {
if (nsig <= maxsig) {
buf[nsig++] = vals[pd - digits]; // accumulate a digit
} else {
++lo[0]; // too many digits, just scale exponent
}
++s;
seen = 1;
}
if (*s == localeconv()->decimal_point[0]) {
++s;
}
if (nsig == 0) {
for (; *s == '0'; ++s, seen = 1) {
--lo[0]; // strip zeros after point
}
}
for (; (pd = (char*) memchr(&digits[0], *s, 22)) != 0; ++s, seen = 1) {
if (nsig <= maxsig) { // accumulate a fraction digit
buf[nsig++] = vals[pd - digits];
--lo[0];
}
}
if (maxsig < nsig) { // discard excess digit after rounding up
if (_Base / 2 <= buf[maxsig]) {
++buf[maxsig - 1]; // okay if digit becomes _Base
}
nsig = maxsig;
++lo[0];
}
for (; 0 < nsig && buf[nsig - 1] == '\0'; --nsig) {
++lo[0]; // discard trailing zeros
}
if (nsig == 0) {
buf[nsig++] = '\0'; // ensure at least one digit
}
lo[0] <<= 2; // change hex exponent to binary exponent
if (seen) { // convert digit sequence to words
int bufidx = 0; // next digit in buffer
int wordidx = _Ndig - nsig % _Ndig; // next digit in word (% _Ndig)
word = wordidx % _Ndig == 0 ? 0 : 1;
for (; bufidx < nsig; ++wordidx, ++bufidx) {
if (wordidx % _Ndig == 0) {
lo[++word] = buf[bufidx];
} else {
lo[word] = lo[word] * _Base + buf[bufidx];
}
}
if (*s == 'p' || *s == 'P') { // parse exponent
const char* ssav = s;
const char esign = *++s == '+' || *s == '-' ? *s++ : '+';
int eseen = 0;
long lexp = 0;
for (; isdigit((unsigned char) *s); ++s, eseen = 1) {
if (lexp < 100000000) { // else overflow
lexp = lexp * 10 + (unsigned char) *s - '0';
}
}
if (esign == '-') {
lexp = -lexp;
}
lo[0] += lexp;
if (!eseen) {
s = ssav; // roll back if incomplete exponent
}
}
}
if (!seen) {
word = 0; // return zero if bad parse
}
if (endptr) {
*endptr = (char*) (seen ? s : s0); // roll back if bad parse
}
return word;
}
_END_EXTERN_C_UNLESS_PURE
| 29.211679 | 87 | 0.471514 | oktonion |
f67acb0effd9cdec60c1fd0d041181f032eba566 | 603 | cpp | C++ | Nyx/VelocityComponent.cpp | Rykkata/nyx | 72d6f222a123e6f120cf83b4843e029036a0d8a9 | [
"Apache-2.0"
] | null | null | null | Nyx/VelocityComponent.cpp | Rykkata/nyx | 72d6f222a123e6f120cf83b4843e029036a0d8a9 | [
"Apache-2.0"
] | null | null | null | Nyx/VelocityComponent.cpp | Rykkata/nyx | 72d6f222a123e6f120cf83b4843e029036a0d8a9 | [
"Apache-2.0"
] | null | null | null | #include "VelocityComponent.h"
VelocityComponent::VelocityComponent()
{
m_xVelocity = 0;
m_yVelocity = 0;
}
VelocityComponent::~VelocityComponent()
{
}
VelocityComponent::VelocityComponent(int xVelocity, int yVelocity)
{
}
int VelocityComponent::GetXVelocity()
{
return 0;
}
int VelocityComponent::GetYVelocity()
{
return 0;
}
int VelocityComponent::SetXVelocity(int newXVelocity)
{
return 0;
}
int VelocityComponent::SetYVelocity(int newYVelocity)
{
return 0;
}
const char* VelocityComponent::GetComponentType() const
{
return TYPE;
} | 12.829787 | 67 | 0.693201 | Rykkata |
f67af4da2a2e637137d602437569600f4c040819 | 1,758 | cpp | C++ | Dev/Cpp/Viewer/3D/EffectSetting.cpp | Shockblast/Effekseer | bac86c0fc965f04a0f57c5863d37a9c2d5c3be97 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-12-21T07:03:42.000Z | 2021-12-21T07:03:42.000Z | Dev/Cpp/Viewer/3D/EffectSetting.cpp | Shockblast/Effekseer | bac86c0fc965f04a0f57c5863d37a9c2d5c3be97 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/Viewer/3D/EffectSetting.cpp | Shockblast/Effekseer | bac86c0fc965f04a0f57c5863d37a9c2d5c3be97 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | #include "EffectSetting.h"
#include "../Graphics/GraphicsDevice.h"
#include "../Sound/SoundDevice.h"
#include "FileInterface.h"
#ifdef _WIN32
#include "../Graphics/Platform/DX11/efk.GraphicsDX11.h"
#endif
#include "../Graphics/Platform/GL/efk.GraphicsGL.h"
#include <EffekseerSoundOSMixer.h>
namespace Effekseer::Tool
{
std::shared_ptr<EffectSetting> EffectSetting::Create(std::shared_ptr<Effekseer::Tool::GraphicsDevice> graphicsDevice, std::shared_ptr<Effekseer::Tool::SoundDevice> soundDevice)
{
auto ret = std::make_shared<EffectSetting>();
auto setting = Effekseer::Setting::Create();
ret->setting_ = setting;
auto gd = graphicsDevice->GetGraphics()->GetGraphicsDevice();
auto fileInterface = Effekseer::MakeRefPtr<Effekseer::Tool::EffekseerFile>();
auto textureLoader = EffekseerRenderer::CreateTextureLoader(
gd,
fileInterface,
graphicsDevice->GetIsSRGBMode() ? ::Effekseer::ColorSpaceType::Linear : ::Effekseer::ColorSpaceType::Gamma);
setting->SetTextureLoader(textureLoader);
auto modelLoader = EffekseerRenderer::CreateModelLoader(gd, fileInterface);
setting->SetModelLoader(modelLoader);
setting->SetCurveLoader(Effekseer::CurveLoaderRef(new ::Effekseer::CurveLoader(fileInterface)));
if (soundDevice != nullptr)
{
setting->SetSoundLoader(soundDevice->GetSound()->CreateSoundLoader(fileInterface));
}
if (graphicsDevice->GetDeviceType() == DeviceType::DirectX11)
{
#ifdef _WIN32
setting->SetMaterialLoader(EffekseerRendererDX11::CreateMaterialLoader(gd, fileInterface));
#endif
}
else if (graphicsDevice->GetDeviceType() == DeviceType::OpenGL)
{
setting->SetMaterialLoader(EffekseerRendererGL::CreateMaterialLoader(gd, fileInterface));
}
return ret;
return nullptr;
}
} // namespace Effekseer::Tool | 29.79661 | 176 | 0.771331 | Shockblast |
f67c8ae0b3ed6985b7284832d69f3be9b2ef8a82 | 27,569 | cpp | C++ | src/tools/CHapticPoint.cpp | Yung-Quant/elec490 | 09314b1c3f4f061effa396c104f094f28a0aabff | [
"BSD-3-Clause"
] | null | null | null | src/tools/CHapticPoint.cpp | Yung-Quant/elec490 | 09314b1c3f4f061effa396c104f094f28a0aabff | [
"BSD-3-Clause"
] | null | null | null | src/tools/CHapticPoint.cpp | Yung-Quant/elec490 | 09314b1c3f4f061effa396c104f094f28a0aabff | [
"BSD-3-Clause"
] | null | null | null | //==============================================================================
/*
Software License Agreement (BSD License)
Copyright (c) 2003-2016, CHAI3D.
(www.chai3d.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of CHAI3D nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
\author <http://www.chai3d.org>
\author Francois Conti
\version $MAJOR.$MINOR.$RELEASE $Rev: 2158 $
*/
//==============================================================================
//------------------------------------------------------------------------------
#include "tools/CHapticPoint.h"
//------------------------------------------------------------------------------
#include "tools/CGenericTool.h"
#include "world/CMultiMesh.h"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
namespace chai3d {
//------------------------------------------------------------------------------
//==============================================================================
/*!
Constructor of cHapticPoint.
*/
//==============================================================================
cHapticPoint::cHapticPoint(cGenericTool* a_parentTool)
{
// set parent tool
m_parentTool = a_parentTool;
// initialize variables
m_radiusDisplay = 0.0;
m_radiusContact = 0.0;
m_lastComputedGlobalForce.zero();
m_meshProxyContacts[0] = NULL;
m_meshProxyContacts[1] = NULL;
m_meshProxyContacts[2] = NULL;
m_audioSourceImpact[0] = NULL;
m_audioSourceImpact[1] = NULL;
m_audioSourceImpact[2] = NULL;
m_audioSourceFriction[0] = NULL;
m_audioSourceFriction[1] = NULL;
m_audioSourceFriction[2] = NULL;
m_audioProxyContacts[0] = NULL;
m_audioProxyContacts[1] = NULL;
m_audioProxyContacts[2] = NULL;
m_useAudioSources = false;
// create finger-proxy algorithm used for modelling contacts with
// cMesh objects.
m_algorithmFingerProxy = new cAlgorithmFingerProxy();
// create potential field algorithm used for modelling interaction
// forces with haptic effects.
m_algorithmPotentialField = new cAlgorithmPotentialField();
// create sphere object used for rendering the Proxy position.
m_sphereProxy = new cShapeSphere(0.0);
// create sphere object used for rendering the Goal position.
m_sphereGoal = new cShapeSphere(0.0);
// Set default radius of proxy and goal spheres
setRadius(0.01, 0.01);
// define a color for the proxy sphere
m_sphereProxy->m_material->setGrayDim();
// define a color for the goal sphere
m_sphereGoal->m_material->setGrayLight();
// Initialize force rendering algorithms
initialize(cVector3d(0.0, 0.0, 0.0));
}
//==============================================================================
/*!
Destructor of cHapticPoint.
*/
//==============================================================================
cHapticPoint::~cHapticPoint()
{
// delete force rendering algorithms
delete m_algorithmFingerProxy;
delete m_algorithmPotentialField;
// delete graphical spheres (proxy and goal)
delete m_sphereProxy;
delete m_sphereGoal;
// delete audio sources for impact
for (int i = 0; i<3; i++)
{
if (m_audioSourceImpact[i] != NULL)
{
delete m_audioSourceImpact[i];
}
}
// delete audio sources for friction
for (int i = 0; i<3; i++)
{
if (m_audioSourceFriction[i] != NULL)
{
delete m_audioSourceFriction[i];
}
}
}
//==============================================================================
/*!
This method returns the current desired goal position of the contact
point in world global coordinates.
\return Goal position of haptic point.
*/
//==============================================================================
cVector3d cHapticPoint::getGlobalPosGoal()
{
return(m_algorithmFingerProxy->getDeviceGlobalPosition());
}
//==============================================================================
/*!
This method returns the current proxy position of the haptic point in world
global coordinates.
\return Proxy position of haptic point.
*/
//==============================================================================
cVector3d cHapticPoint::getGlobalPosProxy()
{
return(m_algorithmFingerProxy->getProxyGlobalPosition());
}
//==============================================================================
/*!
This method returns the current desired goal position of the haptic point
in local tool coordinates.
\return Goal position of haptic point.
*/
//==============================================================================
cVector3d cHapticPoint::getLocalPosGoal()
{
cMatrix3d rot;
cVector3d newpos;
cVector3d toolGlobalPos = m_parentTool->getGlobalPos();
cMatrix3d toolGlobalRot = m_parentTool->getGlobalRot();
cVector3d pos = m_algorithmFingerProxy->getDeviceGlobalPosition();
toolGlobalRot.transr(rot);
pos.sub(toolGlobalPos);
rot.mulr(pos, newpos);
return(newpos);
}
//==============================================================================
/*!
This method returns the current proxy position of the haptic point in local
tool coordinates.
\return Proxy position of haptic point.
*/
//==============================================================================
cVector3d cHapticPoint::getLocalPosProxy()
{
cMatrix3d rot;
cVector3d newpos;
cVector3d toolGlobalPos = m_parentTool->getGlobalPos();
cMatrix3d toolGlobalRot = m_parentTool->getGlobalRot();
cVector3d pos = m_algorithmFingerProxy->getProxyGlobalPosition();
toolGlobalRot.transr(rot);
pos.sub(toolGlobalPos);
rot.mulr(pos, newpos);
return(newpos);
}
//==============================================================================
/*!
This method resets the position of the proxy to be at the current desired
goal position.
*/
//==============================================================================
void cHapticPoint::initialize()
{
// reset finger proxy algorithm by placing the proxy and the same position
// as the goal.
m_algorithmFingerProxy->reset();
// update position of proxy and goal spheres in tool coordinates
updateSpherePositions();
}
//==============================================================================
/*!
This method initializes the position of the haptic point to a new desired
position. The __proxy__ and the __device__ are set to the same value
despite any constraints.
\param a_globalPos New desired position of the haptic point.
*/
//==============================================================================
void cHapticPoint::initialize(cVector3d a_globalPos)
{
// initialize proxy algorithm.
m_algorithmFingerProxy->initialize(m_parentTool->getParentWorld(), a_globalPos);
m_algorithmPotentialField->initialize(m_parentTool->getParentWorld(), a_globalPos);
// update position of proxy and goal spheres in tool coordinates
updateSpherePositions();
}
//==============================================================================
/*!
This method sets the radius size of the haptic point. The radius affects
the physical radius of the proxy and the radius of the spheres that are used
to render the goal and proxy positions.
\param a_radius New radius for display rendering and contact computation.
*/
//==============================================================================
void cHapticPoint::setRadius(double a_radius)
{
m_radiusContact = a_radius;
m_radiusDisplay = a_radius;
// set the radius of the contact model of the proxy
m_algorithmFingerProxy->setProxyRadius(m_radiusContact);
// set radius of proxy and goal. goal radius is slightly smaller to avoid graphical
// artifacts when both sphere are located at the same position.
m_sphereProxy->setRadius(m_radiusDisplay);
m_sphereGoal->setRadius(0.95 * m_radiusDisplay);
}
//==============================================================================
/*!
This method sets the radius size of the display spheres (goal and proxy) and
physical contact sphere (proxy) used to compute the contact forces.
Setting the a_radiusContact parameter to zero will generally accelerate the
force rendering algorithm. For more realistic effects, settings both
values to be identical is recommended
\param a_radiusDisplay New radius for display of spheres (proxy and goal).
\param a_radiusContact New radius for contact computation (proxy).
*/
//==============================================================================
void cHapticPoint::setRadius(double a_radiusDisplay, double a_radiusContact)
{
m_radiusContact = a_radiusContact;
m_radiusDisplay = a_radiusDisplay;
// set the radius of the contact model of the proxy
m_algorithmFingerProxy->setProxyRadius(m_radiusContact);
// set radius of proxy and goal. goal radius is slightly smaller to avoid graphical
// artifacts when both sphere are located at the same position.
m_sphereProxy->setRadius(m_radiusDisplay);
m_sphereGoal->setRadius(0.95 * m_radiusDisplay);
}
//==============================================================================
/*!
This method sets the radius size of the physical proxy.
\param a_radiusContact New radius for contact computation (proxy).
*/
//==============================================================================
void cHapticPoint::setRadiusContact(double a_radiusContact)
{
m_radiusContact = a_radiusContact;
// set the radius of the contact model of the proxy
m_algorithmFingerProxy->setProxyRadius(m_radiusContact);
}
//==============================================================================
/*!
This method sets the radius size of the sphere used to display the proxy
and goal position.
\param a_radiusDisplay New radius for display of spheres (proxy and goal).
*/
//==============================================================================
void cHapticPoint::setRadiusDisplay(double a_radiusDisplay)
{
m_radiusDisplay = a_radiusDisplay;
// set radius of proxy and goal. goal radius is slightly smaller to avoid graphical
// artifacts when both sphere are located at the same position.
m_sphereProxy->setRadius(m_radiusDisplay);
m_sphereGoal->setRadius(0.99 * m_radiusDisplay);
}
//==============================================================================
/*!
This method sets the display options of the goal and proxy spheres.
If both spheres are enabled, a small line is drawn between both spheres.
\param a_showProxy If __true__, then the proxy sphere is displayed.
\param a_showGoal If __true__, then the goal sphere is displayed.
\param a_colorLine Color of line connecting proxy to goal spheres.
*/
//==============================================================================
void cHapticPoint::setShow(bool a_showProxy,
bool a_showGoal,
cColorf a_colorLine)
{
// update display properties of both spheres
m_sphereProxy->setShowEnabled(a_showProxy);
m_sphereGoal->setShowEnabled(a_showGoal);
m_colorLine = a_colorLine;
}
//==============================================================================
/*!
This method creates an audio source for this haptic point.
\param a_audioDevice Audio device.
*/
//==============================================================================
bool cHapticPoint::createAudioSource(cAudioDevice* a_audioDevice)
{
// sanity check
if (a_audioDevice == NULL) { return (C_ERROR); }
// create three audio sources for impact
for (int i=0; i<3; i++)
{
m_audioSourceImpact[i] = new cAudioSource();
}
// create three audio sources for friction
for (int i=0; i<3; i++)
{
m_audioSourceFriction[i] = new cAudioSource();
}
// audio sources have been created and are now enabled
m_useAudioSources = true;
// success
return (C_SUCCESS);
}
//==============================================================================
/*!
This method computes all interaction forces between the tool haptic points
and the virtual environment.
\param a_globalPos New desired goal position.
\param a_globalRot New desired goal rotation.
\param a_globalLinVel Linear velocity of tool.
\param a_globalAngVel Angular velocity of tool.
\return Computed interaction force in world coordinates.
*/
//==============================================================================
cVector3d cHapticPoint::computeInteractionForces(cVector3d& a_globalPos,
cMatrix3d& a_globalRot,
cVector3d& a_globalLinVel,
cVector3d& a_globalAngVel)
{
///////////////////////////////////////////////////////////////////////////
// ALGORITHM FINGER PROXY
///////////////////////////////////////////////////////////////////////////
// we first consider all object the proxy may have been in contact with and
// mark their interaction as no longer active.
for (int i=0; i<3; i++)
{
if (m_meshProxyContacts[i] != NULL)
{
m_meshProxyContacts[i]->m_interactionInside = false;
cMultiMesh* multiMesh = dynamic_cast<cMultiMesh*>(m_meshProxyContacts[i]->getOwner());
if (multiMesh != NULL)
{
multiMesh->m_interactionInside = false;
}
m_meshProxyContacts[i] = NULL;
}
}
// we now update the new position of a goal point and update the proxy position.
// As a result, the force contribution from the proxy is now calculated.
cVector3d force0 = m_algorithmFingerProxy->computeForces(a_globalPos, a_globalLinVel);
// we now flag each mesh for which the proxy may be interacting with. This information is
// necessary for haptic effects that may be associated with these mesh objects.
for (int i=0; i<3; i++)
{
if (m_algorithmFingerProxy->m_collisionEvents[i]->m_object != NULL)
{
m_meshProxyContacts[i] = m_algorithmFingerProxy->m_collisionEvents[i]->m_object;
cGenericObject* object = m_meshProxyContacts[i];
object->m_interactionInside = true;
object->m_interactionPoint = m_algorithmFingerProxy->m_collisionEvents[i]->m_localPos;
object->m_interactionNormal = m_algorithmFingerProxy->m_collisionEvents[i]->m_localNormal;
cMultiMesh* multiMesh = dynamic_cast<cMultiMesh*>(m_meshProxyContacts[i]->getOwner());
if (multiMesh != NULL)
{
multiMesh->m_interactionInside = true;
multiMesh->m_interactionPoint = cAdd(object->getLocalPos(), cMul(object->getLocalRot(),object->m_interactionPoint));
multiMesh->m_interactionNormal = cMul(object->getLocalRot(), object->m_interactionNormal);
}
}
}
///////////////////////////////////////////////////////////////////////////
// ALGORITHM POTENTIAL FIELD
///////////////////////////////////////////////////////////////////////////
// compute interaction forces (haptic effects) in world coordinates between tool and all
// objects for which haptic effects have been programmed
cVector3d force1 = m_algorithmPotentialField->computeForces(a_globalPos, a_globalLinVel);
///////////////////////////////////////////////////////////////////////////
// FINALIZATION
///////////////////////////////////////////////////////////////////////////
// update position of proxy and goal spheres in tool coordinates
updateSpherePositions();
// finally return the contribution from both force models.
force0.addr(force1, m_lastComputedGlobalForce);
///////////////////////////////////////////////////////////////////////////
// AUDIO
///////////////////////////////////////////////////////////////////////////
// force magnitude
double force = m_lastComputedGlobalForce.length();
// velocity of tool
double velocity = m_parentTool->getDeviceGlobalLinVel().length();
// friction sound
if (m_useAudioSources)
{
for (int i=0; i<3; i++)
{
///////////////////////////////////////////////////////////////////
// FRICTION SOUND
///////////////////////////////////////////////////////////////////
m_audioSourceFriction[i]->setSourcePos(a_globalPos);
// if tool is not in contact, or material does not exist, turn off sound.
if (m_meshProxyContacts[i] == NULL)
{
m_audioSourceFriction[i]->setGain(0.0);
}
// if tool is in contact and material exist
else
{
// check if tool is touching a new material, in which case we swap audio buffers
if (m_meshProxyContacts[i]->m_material->getAudioFrictionBuffer() != NULL)
{
if (m_audioSourceFriction[i]->getAudioBuffer() != m_meshProxyContacts[i]->m_material->getAudioFrictionBuffer())
{
m_audioSourceFriction[i]->stop();
m_audioSourceFriction[i]->setGain(0.0);
m_audioSourceFriction[i]->setPitch(1.0);
m_audioSourceFriction[i]->setAudioBuffer(m_meshProxyContacts[i]->m_material->getAudioFrictionBuffer());
m_audioSourceFriction[i]->setLoop(true);
m_audioSourceFriction[i]->play();
}
}
// we compute an angle that compares the velocity of the tool with the reaction force. This friction maximizes
// returns a value between o.0 and 1.0 which maximize tangential forces, versus normal forces. The higher
// the tangential force, the higher the sound level. This is slightly hacky but could be improved by
// taking the exact tangential component of the force.
double angleFactor = 0.0;
if ((force > C_SMALL) && (velocity > C_SMALL))
{
angleFactor = cSqr(cSqr(sin(cAngle(m_lastComputedGlobalForce, m_parentTool->getDeviceGlobalLinVel())))) ;
}
// adjust audio gains according to material properties, and force and velocity of tool.
m_audioSourceFriction[i]->setGain((float)(m_meshProxyContacts[i]->m_material->getAudioFrictionGain() * angleFactor * force * cSqr(velocity)));
m_audioSourceFriction[i]->setPitch((float)(m_meshProxyContacts[i]->m_material->getAudioFrictionPitchOffset() + m_meshProxyContacts[i]->m_material->getAudioFrictionPitchGain() * velocity));
}
///////////////////////////////////////////////////////////////////
// IMAPCT SOUND
///////////////////////////////////////////////////////////////////
m_audioSourceImpact[i]->setSourcePos(a_globalPos);
if ((m_audioProxyContacts[i] == NULL) && (m_meshProxyContacts[i] != NULL))
{
if ((m_audioSourceImpact[i]->getAudioBuffer() != m_meshProxyContacts[i]->m_material->getAudioImpactBuffer()) &&
(m_meshProxyContacts[i]->m_material->getAudioImpactBuffer() != NULL))
{
m_audioSourceImpact[i]->stop();
m_audioSourceImpact[i]->setAudioBuffer(m_meshProxyContacts[i]->m_material->getAudioImpactBuffer());
m_audioSourceImpact[i]->setLoop(false);
}
m_audioSourceImpact[i]->setGain((float)(m_meshProxyContacts[i]->m_material->getAudioImpactGain() * cSqr(velocity)));
m_audioSourceImpact[i]->play();
}
// update contact list
m_audioProxyContacts[i] = m_meshProxyContacts[i];
}
}
// return result
return (m_lastComputedGlobalForce);
}
//==============================================================================
/*!
This method checks if the tool is touching a particular object passed
as argument.
\param a_object Object to checked for possible contact.
\return __true__ if the object is in contact with tool, __false__ otherwise.
*/
//==============================================================================
bool cHapticPoint::isInContact(cGenericObject* a_object)
{
/////////////////////////////////////////////////////////////////////
// verify finger-proxy algorithm
/////////////////////////////////////////////////////////////////////
// contact 0
if (m_algorithmFingerProxy->m_collisionEvents[0]->m_object == a_object)
{
return (true);
}
// contact 1
if ((m_algorithmFingerProxy->m_collisionEvents[0]->m_object != NULL) &&
(m_algorithmFingerProxy->m_collisionEvents[1]->m_object == a_object))
{
return (true);
}
// contact 2
if ((m_algorithmFingerProxy->m_collisionEvents[0]->m_object != NULL) &&
(m_algorithmFingerProxy->m_collisionEvents[1]->m_object != NULL) &&
(m_algorithmFingerProxy->m_collisionEvents[2]->m_object == a_object))
{
return (true);
}
/////////////////////////////////////////////////////////////////////
// verify potential-field algorithm
/////////////////////////////////////////////////////////////////////
unsigned int num = (int)(m_algorithmPotentialField->m_interactionRecorder.m_interactions.size());
unsigned int i = 0;
while (i < num)
{
// check next interaction
if (m_algorithmPotentialField->m_interactionRecorder.m_interactions[i].m_object == a_object)
{
return (true);
}
// increment counter
i++;
}
// no object in contact
return (false);
}
//==============================================================================
/*!
This method renders the tool graphically using OpenGL.
\param a_options Rendering options.
*/
//==============================================================================
void cHapticPoint::render(cRenderOptions& a_options)
{
#ifdef C_USE_OPENGL
/////////////////////////////////////////////////////////////////////////
// Render parts that are always opaque
/////////////////////////////////////////////////////////////////////////
if (SECTION_RENDER_OPAQUE_PARTS_ONLY(a_options))
{
// render line only if both spheres are enabled for display
if (m_sphereProxy->getShowEnabled() && m_sphereGoal->getShowEnabled())
{
// disable lighting
glDisable(GL_LIGHTING);
// points describe line extremities
cVector3d posA = m_sphereProxy->getLocalPos();
cVector3d posB = m_sphereGoal->getLocalPos();
// draw line
glBegin(GL_LINES);
m_colorLine.render();
glVertex3dv(&posA(0) );
glVertex3dv(&posB(0) );
glEnd();
// restore lighting to default value
glEnable(GL_LIGHTING);
}
}
/////////////////////////////////////////////////////////////////////////
// Render other objects
/////////////////////////////////////////////////////////////////////////
// render proxy sphere
m_sphereProxy->renderSceneGraph(a_options);
// render goal sphere
m_sphereGoal->renderSceneGraph(a_options);
// render proxy algorithm (debug purposes)
//m_algorithmFingerProxy->render(a_options);
#endif
}
//==============================================================================
/*!
This method updates the position of the spheres in tool coordinates.
The position of the actual proxy and goal spheres need to be expressed in the
tool's local coordinate system. This comes from the fact that the contact
points are rendered at the same time as the tool, respectively when the
OpenGL model view matrix corresponds to the one of the parent tool.
*/
//==============================================================================
void cHapticPoint::updateSpherePositions()
{
// sanity check
if (m_parentTool == NULL) { return; }
// position and orientation of tool in world global coordinates
cMatrix3d toolGlobalRot = m_parentTool->getGlobalRot();
// temp variables
cVector3d pos;
cMatrix3d rot;
toolGlobalRot.transr(rot);
// update position of proxy sphere
pos = getLocalPosProxy();
m_sphereProxy->setLocalPos(pos);
// update position of goal sphere
pos = getLocalPosGoal();
m_sphereGoal->setLocalPos(pos);
}
//------------------------------------------------------------------------------
} // namespace chai3d
//------------------------------------------------------------------------------
| 38.131397 | 205 | 0.526606 | Yung-Quant |
f67d2757f7cae38ab947eb82b62aa2c0f4788f88 | 43,655 | cpp | C++ | src/C/Security-57031.40.6/sslViewer/SSLViewer.cpp | GaloisInc/hacrypto | 5c99d7ac73360e9b05452ac9380c1c7dc6784849 | [
"BSD-3-Clause"
] | 34 | 2015-02-04T18:03:14.000Z | 2020-11-10T06:45:28.000Z | src/C/Security-57031.40.6/sslViewer/SSLViewer.cpp | GaloisInc/hacrypto | 5c99d7ac73360e9b05452ac9380c1c7dc6784849 | [
"BSD-3-Clause"
] | 5 | 2015-06-30T21:17:00.000Z | 2016-06-14T22:31:51.000Z | src/C/Security-57031.40.6/sslViewer/SSLViewer.cpp | GaloisInc/hacrypto | 5c99d7ac73360e9b05452ac9380c1c7dc6784849 | [
"BSD-3-Clause"
] | 15 | 2015-10-29T14:21:58.000Z | 2022-01-19T07:33:14.000Z | /*
* Copyright (c) 2006-2013 Apple Inc. All Rights Reserved.
*
* SSL viewer tool, SecureTransport / Aspen version.
*/
#include <Security/SecureTransport.h>
#include <Security/SecureTransportPriv.h> // for SSLGetPeerSecTrust
#include <Security/SecTrustPriv.h>
#include "sslAppUtils.h"
#include "ioSock.h"
#include "utilities/fileIo.h"
#include "utilities/SecCFWrappers.h"
#include <Security/SecBase.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <CoreFoundation/CoreFoundation.h>
#include "SecurityTool/print_cert.h"
#include <utilities/SecIOFormat.h>
#if NO_SERVER
#include <securityd/spi.h>
#endif
#define DEFAULT_GETMSG "GET"
#define DEFAULT_PATH "/"
#define DEFAULT_GET_SUFFIX "HTTP/1.0\r\n\r\n"
#define DEFAULT_HOST "www.amazon.com"
#define DEFAULT_PORT 443
#include <Security/SecCertificate.h>
static void usageNorm(char **argv)
{
printf("Usage: %s [hostname|-] [path] [option ...]\n", argv[0]);
printf(" %s hostname [path] [option ...]\n", argv[0]);
printf("Specifying '-' for hostname, or no args, uses default of %s.\n",
DEFAULT_HOST);
printf("Optional path argument must start with leading '/'.\n");
printf("Options:\n");
printf(" e Allow Expired Certs\n");
printf(" E Allow Expired Roots\n");
printf(" r Allow any root cert\n");
printf(" c Display peer certs\n");
printf(" c c Display peer SecTrust\n");
printf(" d Display received data\n");
printf(" 2 SSLv2 only (default is TLSv1)\n");
printf(" 3 SSLv3 only (default is TLSv1)\n");
printf(" t TLSv1\n");
printf(" %% TLSv1.1 only\n");
printf(" ^ TLSv1.2 only\n");
printf(" L all - TLSv1.2, TLSv1.1, TLSv1.0, SSLv3, SSLv2 (default = TLSv1.2)\n");
printf(" g={prot...} Specify legal protocols; prot = any combo of"
" [23t]\n");
printf(" k=keychain Contains cert and keys. Optional.\n");
printf(" l=loopCount Perform loopCount ops (default = 1)\n");
printf(" P=port Default = %d\n", DEFAULT_PORT);
printf(" p Pause after each loop\n");
printf(" q Quiet/diagnostic mode (site names and errors"
" only)\n");
printf(" a fileName Add fileName to list of trusted roots\n");
printf(" A fileName fileName is ONLY trusted root\n");
printf(" x Disable Cert Verification\n");
printf(" z=password Unlock client keychain with password.\n");
printf(" 8 Complete cert chains (default is out cert is a root)\n");
printf(" s Silent\n");
printf(" V Verbose\n");
printf(" h Help\n");
printf(" hv More, verbose help\n");
}
static void usageVerbose(char **argv) __attribute__((noreturn));
static void usageVerbose(char **argv)
{
usageNorm(argv);
printf("Obscure Usage:\n");
printf(" u kSSLProtocolUnknown only (TLSv1)\n");
printf(" M Manual cert verification via "
"SecTrustEvaluate\n");
printf(" f fileBase Write Peer Certs to fileBase*\n");
printf(" o TLSv1, SSLv3 use kSSLProtocol__X__Only\n");
printf(" C=cipherSuite (e=40-bit d=DES D=40-bit DES 3=3DES 4=RC4 "
"$=40-bit RC4\n"
" 2=RC2 a=AES128 A=AES256 h=DH H=Anon DH r=DHE/RSA s=DH/DSS\n");
printf(" y=keychain Encryption-only cert and keys. Optional.\n");
printf(" K Keep connected until server disconnects\n");
printf(" n Require closure notify message in TLSv1, "
"SSLv3 mode (implies K)\n");
printf(" R Disable resumable session support\n");
printf(" b Non-blocking I/O\n");
printf(" v Verify negotiated protocol equals attempted\n");
printf(" m=[23t] Max protocol supported as specified; implies "
"v\n");
printf(" T=[nrsj] Verify client cert state = "
"none/requested/sent/rejected\n");
printf(" H allow hostname spoofing\n");
printf(" F=vfyHost Verify certs with specified host name\n");
printf(" G=getMsg Specify entire GET, POST, etc.\n");
printf(" N Log handshake timing\n");
printf(" 7 Pause only after first loop\n");
exit(1);
}
static void usage(char **argv) __attribute__((noreturn));
static void usage(char **argv)
{
usageNorm(argv);
exit(1);
}
/*
* Arguments to top-level sslPing()
*/
typedef struct {
SSLProtocol tryVersion; // only used if acceptedProts NULL
// uses SSLSetProtocolVersion
char *acceptedProts; // optional, any combo of {2,3,t}
// uses SSLSetProtocolVersionEnabled
const char *hostName; // e.g., "www.amazon.com"
const char *vfyHostName; // use this for cert vfy if non-NULL,
// else use hostName
unsigned short port;
const char *getMsg; // e.g.,
// "GET / HTTP/1.0\r\n\r\n"
bool allowExpired;
bool allowAnyRoot;
bool allowExpiredRoot;
bool disableCertVerify;
bool manualCertVerify;
bool dumpRxData; // display server data
char cipherRestrict; // '2', 'd'. etc...; '\0' for
// no restriction
bool keepConnected;
bool requireNotify; // require closure notify
// in V3 mode
bool resumableEnable;
bool allowHostnameSpoof;
bool nonBlocking;
char *anchorFile;
bool replaceAnchors;
CFArrayRef clientCerts; // optional
CFArrayRef encryptClientCerts; // optional
bool quiet; // minimal stdout
bool silent; // no stdout
bool verbose;
SSLProtocol negVersion; // RETURNED
SSLCipherSuite negCipher; // RETURNED
CFArrayRef peerCerts; // mallocd & RETURNED
SecTrustRef peerTrust; // RETURNED
SSLClientCertificateState certState; // RETURNED
char *password; // optional to open clientCerts
char **argv;
Boolean sessionWasResumed;
unsigned char sessionID[MAX_SESSION_ID_LENGTH];
size_t sessionIDLength;
CFAbsoluteTime handshakeTimeOp; // time for this op
CFAbsoluteTime handshakeTimeFirst; // time for FIRST op, not averaged
CFAbsoluteTime handshakeTimeTotal; // time for all ops except first
unsigned numHandshakes;
} sslPingArgs;
#include <signal.h>
static void sigpipe(int sig)
{
fflush(stdin);
printf("***SIGPIPE***\n");
}
/*
* Snag a copy of current connection's peer certs so we can
* examine them later after the connection is closed.
* SecureTransport actually does the create and retain for us.
*/
static OSStatus copyPeerCerts(
SSLContext *ctx,
CFArrayRef *peerCerts) // mallocd & RETURNED
{
OSStatus ortn = SSLCopyPeerCertificates(ctx, peerCerts);
if(ortn) {
printf("***Error obtaining peer certs: %s\n",
sslGetSSLErrString(ortn));
}
return ortn;
}
/* free the cert array obtained via SSLGetPeerCertificates() */
static void freePeerCerts(
CFArrayRef peerCerts)
{
if(peerCerts) {
CFRelease(peerCerts);
}
}
/*
* Manually evaluate session's SecTrustRef.
*/
#define SSL_SEC_TRUST 1
static OSStatus sslEvaluateTrust(
SSLContext *ctx,
bool verbose,
bool silent,
CFArrayRef *peerCerts) // fetched and retained
{
OSStatus ortn = errSecSuccess;
#if USE_CDSA_CRYPTO
SecTrustRef secTrust = NULL;
#if SSL_SEC_TRUST
ortn = SSLGetPeerSecTrust(ctx, &secTrust);
#else
ortn = errSecUnimplemented;
#endif
if(ortn) {
printf("\n***Error obtaining peer SecTrustRef: %s\n",
sslGetSSLErrString(ortn));
return ortn;
}
if(secTrust == NULL) {
/* this is the normal case for resumed sessions, in which
* no cert evaluation is performed */
if(!silent) {
printf("...No SecTrust available - this is a resumed session, right?\n");
}
return errSecSuccess;
}
SecTrustResultType secTrustResult;
ortn = SecTrustEvaluate(secTrust, &secTrustResult);
if(ortn) {
printf("\n***Error on SecTrustEvaluate: %d\n", (int)ortn);
return ortn;
}
if(verbose) {
char *res = NULL;
switch(secTrustResult) {
case kSecTrustResultInvalid:
res = "kSecTrustResultInvalid"; break;
case kSecTrustResultProceed:
res = "kSecTrustResultProceed"; break;
case kSecTrustResultConfirm:
res = "kSecTrustResultConfirm"; break;
case kSecTrustResultDeny:
res = "kSecTrustResultDeny"; break;
case kSecTrustResultUnspecified:
res = "kSecTrustResultUnspecified"; break;
case kSecTrustResultRecoverableTrustFailure:
res = "kSecTrustResultRecoverableTrustFailure"; break;
case kSecTrustResultFatalTrustFailure:
res = "kSecTrustResultFatalTrustFailure"; break;
case kSecTrustResultOtherError:
res = "kSecTrustResultOtherError"; break;
default:
res = "UNKNOWN"; break;
}
printf("\nSecTrustEvaluate(): secTrustResult %s\n", res);
}
switch(secTrustResult) {
case kSecTrustResultUnspecified:
/* cert chain valid, no special UserTrust assignments */
case kSecTrustResultProceed:
/* cert chain valid AND user explicitly trusts this */
break;
default:
printf("\n***SecTrustEvaluate reported secTrustResult %d\n",
(int)secTrustResult);
ortn = errSSLXCertChainInvalid;
break;
}
#endif
*peerCerts = NULL;
#ifdef USE_CDSA_CRYPTO
/* one more thing - get peer certs in the form of an evidence chain */
CSSM_TP_APPLE_EVIDENCE_INFO *dummyEv;
OSStatus thisRtn = SecTrustGetResult(secTrust, &secTrustResult,
peerCerts, &dummyEv);
if(thisRtn) {
printSslErrStr("SecTrustGetResult", thisRtn);
}
else {
/* workaround for the fact that SSLGetPeerCertificates()
* leaves a retain count on each element in the returned array,
* requiring us to do a release on each cert.
*/
CFIndex numCerts = CFArrayGetCount(*peerCerts);
for(CFIndex dex=0; dex<numCerts; dex++) {
CFRetain(CFArrayGetValueAtIndex(*peerCerts, dex));
}
}
#endif
return ortn;
}
/* print reply received from server, safely */
static void dumpAscii(
uint8_t *rcvBuf,
size_t len)
{
char *cp = (char *)rcvBuf;
uint32_t i;
char c;
for(i=0; i<len; i++) {
c = *cp++;
if(c == '\0') {
break;
}
switch(c) {
case '\n':
printf("\\n");
break;
case '\r':
printf("\\r");
break;
default:
if(isprint(c) && (c != '\n')) {
printf("%c", c);
}
else {
printf("<%02X>", ((unsigned)c) & 0xff);
}
break;
}
}
printf("\n");
}
/*
* Perform one SSL diagnostic session. Returns nonzero on error. Normally no
* output to stdout except initial "connecting to" message, unless there
* is a really screwed up error (i.e., something not directly related
* to the SSL connection).
*/
#define RCV_BUF_SIZE 256
static OSStatus sslPing(
sslPingArgs *pargs)
{
PeerSpec peerId;
otSocket sock = 0;
OSStatus ortn;
SSLContextRef ctx = NULL;
size_t length;
size_t actLen;
uint8_t rcvBuf[RCV_BUF_SIZE];
CFAbsoluteTime startHandshake;
CFAbsoluteTime endHandshake;
pargs->negVersion = kSSLProtocolUnknown;
pargs->negCipher = SSL_NULL_WITH_NULL_NULL;
pargs->peerCerts = NULL;
/* first make sure requested server is there */
ortn = MakeServerConnection(pargs->hostName, pargs->port, pargs->nonBlocking,
&sock, &peerId);
if(ortn) {
printf("MakeServerConnection returned %d; aborting\n", (int)ortn);
return ortn;
}
if(pargs->verbose) {
printf("...connected to server; starting SecureTransport\n");
}
/*
* Set up a SecureTransport session.
* First the standard calls.
*/
ortn = SSLNewContext(false, &ctx);
if(ortn) {
printSslErrStr("SSLNewContext", ortn);
goto cleanup;
}
ortn = SSLSetIOFuncs(ctx, SocketRead, SocketWrite);
if(ortn) {
printSslErrStr("SSLSetIOFuncs", ortn);
goto cleanup;
}
ortn = SSLSetConnection(ctx, (SSLConnectionRef)(intptr_t)sock);
if(ortn) {
printSslErrStr("SSLSetConnection", ortn);
goto cleanup;
}
SSLConnectionRef getConn;
ortn = SSLGetConnection(ctx, &getConn);
if(ortn) {
printSslErrStr("SSLGetConnection", ortn);
goto cleanup;
}
if(getConn != (SSLConnectionRef)(intptr_t)sock) {
printf("***SSLGetConnection error\n");
ortn = errSecParam;
goto cleanup;
}
if(!pargs->allowHostnameSpoof) {
/* if this isn't set, it isn't checked by AppleX509TP */
const char *vfyHost = pargs->hostName;
if(pargs->vfyHostName) {
/* generally means we're expecting an error */
vfyHost = pargs->vfyHostName;
}
ortn = SSLSetPeerDomainName(ctx, vfyHost, strlen(vfyHost));
if(ortn) {
printSslErrStr("SSLSetPeerDomainName", ortn);
goto cleanup;
}
}
/*
* SecureTransport options.
*/
if(pargs->acceptedProts) {
ortn = SSLSetProtocolVersionEnabled(ctx, kSSLProtocolAll, false);
if(ortn) {
printSslErrStr("SSLSetProtocolVersionEnabled(all off)", ortn);
goto cleanup;
}
for(const char *cp = pargs->acceptedProts; *cp; cp++) {
SSLProtocol prot;
switch(*cp) {
case '2':
prot = kSSLProtocol2;
break;
case '3':
prot = kSSLProtocol3;
break;
case 't':
prot = kTLSProtocol12;
break;
default:
usage(pargs->argv);
}
ortn = SSLSetProtocolVersionEnabled(ctx, prot, true);
if(ortn) {
printSslErrStr("SSLSetProtocolVersionEnabled", ortn);
goto cleanup;
}
}
}
else {
ortn = SSLSetProtocolVersion(ctx, pargs->tryVersion);
if(ortn) {
printSslErrStr("SSLSetProtocolVersion", ortn);
goto cleanup;
}
SSLProtocol getVers;
ortn = SSLGetProtocolVersion(ctx, &getVers);
if(ortn) {
printSslErrStr("SSLGetProtocolVersion", ortn);
goto cleanup;
}
if(getVers != pargs->tryVersion) {
printf("***SSLGetProtocolVersion screwup: try %s get %s\n",
sslGetProtocolVersionString(pargs->tryVersion),
sslGetProtocolVersionString(getVers));
ortn = errSecParam;
goto cleanup;
}
}
if(pargs->resumableEnable) {
const void *rtnId = NULL;
size_t rtnIdLen = 0;
ortn = SSLSetPeerID(ctx, &peerId, sizeof(PeerSpec));
if(ortn) {
printSslErrStr("SSLSetPeerID", ortn);
goto cleanup;
}
/* quick test of the get fcn */
ortn = SSLGetPeerID(ctx, &rtnId, &rtnIdLen);
if(ortn) {
printSslErrStr("SSLGetPeerID", ortn);
goto cleanup;
}
if((rtnId == NULL) || (rtnIdLen != sizeof(PeerSpec))) {
printf("***SSLGetPeerID screwup\n");
}
else if(memcmp(&peerId, rtnId, rtnIdLen) != 0) {
printf("***SSLGetPeerID data mismatch\n");
}
}
if(pargs->allowExpired) {
ortn = SSLSetAllowsExpiredCerts(ctx, true);
if(ortn) {
printSslErrStr("SSLSetAllowExpiredCerts", ortn);
goto cleanup;
}
}
if(pargs->allowExpiredRoot) {
ortn = SSLSetAllowsExpiredRoots(ctx, true);
if(ortn) {
printSslErrStr("SSLSetAllowsExpiredRoots", ortn);
goto cleanup;
}
}
if(pargs->disableCertVerify) {
ortn = SSLSetEnableCertVerify(ctx, false);
if(ortn) {
printSslErrStr("SSLSetEnableCertVerify", ortn);
goto cleanup;
}
}
if(pargs->allowAnyRoot) {
ortn = SSLSetAllowsAnyRoot(ctx, true);
if(ortn) {
printSslErrStr("SSLSetAllowAnyRoot", ortn);
goto cleanup;
}
}
if(pargs->cipherRestrict != '\0') {
ortn = sslSetCipherRestrictions(ctx, pargs->cipherRestrict);
if(ortn) {
goto cleanup;
}
}
if(pargs->anchorFile) {
ortn = sslAddTrustedRoot(ctx, pargs->anchorFile, pargs->replaceAnchors);
if(ortn) {
printf("***Error obtaining anchor file %s\n", pargs->anchorFile);
goto cleanup;
}
}
if(pargs->clientCerts) {
CFArrayRef dummy;
if(pargs->anchorFile == NULL) {
/* assume this is a root we want to implicitly trust */
ortn = addIdentityAsTrustedRoot(ctx, pargs->clientCerts);
if(ortn) {
goto cleanup;
}
}
ortn = SSLSetCertificate(ctx, pargs->clientCerts);
if(ortn) {
printSslErrStr("SSLSetCertificate", ortn);
goto cleanup;
}
/* quickie test for this new function */
ortn = SSLGetCertificate(ctx, &dummy);
if(ortn) {
printSslErrStr("SSLGetCertificate", ortn);
goto cleanup;
}
if(dummy != pargs->clientCerts) {
printf("***SSLGetCertificate error\n");
ortn = errSecIO;
goto cleanup;
}
}
if(pargs->encryptClientCerts) {
if(pargs->anchorFile == NULL) {
ortn = addIdentityAsTrustedRoot(ctx, pargs->encryptClientCerts);
if(ortn) {
goto cleanup;
}
}
ortn = SSLSetEncryptionCertificate(ctx, pargs->encryptClientCerts);
if(ortn) {
printSslErrStr("SSLSetEncryptionCertificate", ortn);
goto cleanup;
}
}
/*** end options ***/
if(pargs->verbose) {
printf("...starting SSL handshake\n");
}
startHandshake = CFAbsoluteTimeGetCurrent();
do
{ ortn = SSLHandshake(ctx);
if((ortn == errSSLWouldBlock) && !pargs->silent) {
/* keep UI responsive */
sslOutputDot();
}
} while (ortn == errSSLWouldBlock);
endHandshake = CFAbsoluteTimeGetCurrent();
pargs->handshakeTimeOp = endHandshake - startHandshake;
if(pargs->numHandshakes == 0) {
/* special case, this one is always way longer */
pargs->handshakeTimeFirst = pargs->handshakeTimeOp;
}
else {
/* normal running total */
pargs->handshakeTimeTotal += pargs->handshakeTimeOp;
}
pargs->numHandshakes++;
/* this works even if handshake failed due to cert chain invalid */
if(!pargs->manualCertVerify) {
copyPeerCerts(ctx, &pargs->peerCerts);
}
else {
/* else fetched via SecTrust later */
pargs->peerCerts = NULL;
}
ortn = SSLCopyPeerTrust(ctx, &pargs->peerTrust);
if(ortn) {
printf("***SSLCopyPeerTrust error %" PRIdOSStatus "\n", ortn);
pargs->peerTrust = NULL;
}
/* ditto */
SSLGetClientCertificateState(ctx, &pargs->certState);
SSLGetNegotiatedCipher(ctx, &pargs->negCipher);
SSLGetNegotiatedProtocolVersion(ctx, &pargs->negVersion);
pargs->sessionIDLength = MAX_SESSION_ID_LENGTH;
SSLGetResumableSessionInfo(ctx, &pargs->sessionWasResumed, pargs->sessionID,
&pargs->sessionIDLength);
if(pargs->manualCertVerify) {
OSStatus certRtn = sslEvaluateTrust(ctx, pargs->verbose, pargs->silent,
&pargs->peerCerts);
if(certRtn && !ortn ) {
ortn = certRtn;
}
}
if(ortn) {
if(!pargs->silent) {
printf("\n");
}
goto cleanup;
}
if(pargs->verbose) {
printf("...SSL handshake complete\n");
}
length = strlen(pargs->getMsg);
(void) SSLWrite(ctx, pargs->getMsg, length, &actLen);
/*
* Try to snag RCV_BUF_SIZE bytes. Exit if (!keepConnected and we get any data
* at all), or (keepConnected and err != (none, wouldBlock)).
*/
while (1) {
actLen = 0;
if(pargs->dumpRxData) {
size_t avail = 0;
ortn = SSLGetBufferedReadSize(ctx, &avail);
if(ortn) {
printf("***SSLGetBufferedReadSize error\n");
break;
}
if(avail != 0) {
printf("\n%d bytes available: ", (int)avail);
}
}
ortn = SSLRead(ctx, rcvBuf, RCV_BUF_SIZE, &actLen);
if((actLen == 0) && !pargs->silent) {
sslOutputDot();
}
if((actLen == 0) && (ortn == errSecSuccess)) {
printf("***Radar 2984932 confirmed***\n");
}
if (ortn == errSSLWouldBlock) {
/* for this loop, these are identical */
ortn = errSecSuccess;
}
if((actLen > 0) && pargs->dumpRxData) {
dumpAscii(rcvBuf, actLen);
}
if(ortn != errSecSuccess) {
/* connection closed by server or by error */
break;
}
if(!pargs->keepConnected && (actLen > 0)) {
/* good enough, we connected */
break;
}
}
if(!pargs->silent) {
printf("\n");
}
/* snag these again in case of renegotiate */
SSLGetClientCertificateState(ctx, &pargs->certState);
SSLGetNegotiatedCipher(ctx, &pargs->negCipher);
SSLGetNegotiatedProtocolVersion(ctx, &pargs->negVersion);
/* convert normal "shutdown" into zero err rtn */
if(ortn == errSSLClosedGraceful) {
ortn = errSecSuccess;
}
if((ortn == errSSLClosedNoNotify) && !pargs->requireNotify) {
/* relaxed disconnect rules */
ortn = errSecSuccess;
}
cleanup:
/*
* always do close, even on error - to flush outgoing write queue
*/
OSStatus cerr = SSLClose(ctx);
if(ortn == errSecSuccess) {
ortn = cerr;
}
if(sock) {
endpointShutdown(sock);
}
if(ctx) {
SSLDisposeContext(ctx);
}
return ortn;
}
static void add_key(const void *key, const void *value, void *context) {
CFArrayAppendValue((CFMutableArrayRef)context, key);
}
static void showInfo(CFDictionaryRef info) {
CFIndex dict_count, key_ix, key_count;
CFMutableArrayRef keys = NULL;
CFIndex maxWidth = 20; /* Maybe precompute this or grab from context? */
dict_count = CFDictionaryGetCount(info);
keys = CFArrayCreateMutable(kCFAllocatorDefault, dict_count,
&kCFTypeArrayCallBacks);
CFDictionaryApplyFunction(info, add_key, keys);
key_count = CFArrayGetCount(keys);
CFArraySortValues(keys, CFRangeMake(0, key_count),
(CFComparatorFunction)CFStringCompare, 0);
for (key_ix = 0; key_ix < key_count; ++key_ix) {
CFStringRef key = (CFStringRef)CFArrayGetValueAtIndex(keys, key_ix);
CFTypeRef value = CFDictionaryGetValue(info, key);
CFMutableStringRef line = CFStringCreateMutable(NULL, 0);
CFStringAppend(line, key);
CFIndex jx;
for (jx = CFStringGetLength(key);
jx < maxWidth; ++jx) {
CFStringAppend(line, CFSTR(" "));
}
CFStringAppend(line, CFSTR(" : "));
if (CFStringGetTypeID() == CFGetTypeID(value)) {
CFStringAppend(line, (CFStringRef)value);
} else if (CFDateGetTypeID() == CFGetTypeID(value)) {
CFLocaleRef lc = CFLocaleCopyCurrent();
CFDateFormatterRef df = CFDateFormatterCreate(NULL, lc,
kCFDateFormatterFullStyle, kCFDateFormatterFullStyle);
CFDateRef date = (CFDateRef)value;
CFStringRef ds = CFDateFormatterCreateStringWithDate(NULL, df,
date);
CFStringAppend(line, ds);
CFRelease(ds);
CFRelease(df);
CFRelease(lc);
} else if (CFURLGetTypeID() == CFGetTypeID(value)) {
CFURLRef url = (CFURLRef)value;
CFStringAppend(line, CFSTR("<"));
CFStringAppend(line, CFURLGetString(url));
CFStringAppend(line, CFSTR(">"));
} else if (CFDataGetTypeID() == CFGetTypeID(value)) {
CFDataRef v_d = (CFDataRef)value;
CFStringRef v_s = CFStringCreateFromExternalRepresentation(
kCFAllocatorDefault, v_d, kCFStringEncodingUTF8);
if (v_s) {
CFStringAppend(line, CFSTR("/"));
CFStringAppend(line, v_s);
CFStringAppend(line, CFSTR("/ "));
CFRelease(v_s);
}
const uint8_t *bytes = CFDataGetBytePtr(v_d);
CFIndex len = CFDataGetLength(v_d);
for (jx = 0; jx < len; ++jx) {
CFStringAppendFormat(line, NULL, CFSTR("%.02X"), bytes[jx]);
}
} else {
CFStringAppendFormat(line, NULL, CFSTR("%@"), value);
}
CFStringWriteToFileWithNewline(line, stdout);
CFRelease(line);
}
CFRelease(keys);
}
static void showPeerTrust(SecTrustRef peerTrust, bool verbose) {
CFIndex numCerts;
CFIndex i;
if(peerTrust == NULL) {
return;
}
printf("\n=============== Peer Trust Properties ===============\n");
CFArrayRef plist = SecTrustCopyProperties(peerTrust);
if (plist) {
print_plist(plist);
CFRelease(plist);
}
printf("\n================== Peer Trust Info ==================\n");
CFDictionaryRef info = SecTrustCopyInfo(peerTrust);
if (info && CFDictionaryGetCount(info)) {
showInfo(info);
}
if (info)
CFRelease(info);
numCerts = SecTrustGetCertificateCount(peerTrust);
for(i=0; i<numCerts; i++) {
plist = SecTrustCopySummaryPropertiesAtIndex(peerTrust, i);
printf("\n============= Peer Trust Cert %lu Summary =============\n\n", i);
print_plist(plist);
if (plist)
CFRelease(plist);
printf("\n============= Peer Trust Cert %lu Details =============\n\n", i);
plist = SecTrustCopyDetailedPropertiesAtIndex(peerTrust, i);
print_plist(plist);
if (plist)
CFRelease(plist);
printf("\n============= End of Peer Trust Cert %lu ==============\n", i);
}
}
static void showPeerCerts(
CFArrayRef peerCerts,
bool verbose)
{
CFIndex numCerts;
SecCertificateRef certRef;
CFIndex i;
if(peerCerts == NULL) {
return;
}
numCerts = CFArrayGetCount(peerCerts);
for(i=0; i<numCerts; i++) {
certRef = (SecCertificateRef)CFArrayGetValueAtIndex(peerCerts, i);
printf("\n==================== Peer Cert %lu ====================\n\n", i);
print_cert(certRef, verbose);
printf("\n================ End of Peer Cert %lu =================\n", i);
}
}
static void writePeerCerts(
CFArrayRef peerCerts,
const char *fileBase)
{
CFIndex numCerts;
SecCertificateRef certRef;
CFIndex i;
char fileName[100];
if(peerCerts == NULL) {
return;
}
numCerts = CFArrayGetCount(peerCerts);
for(i=0; i<numCerts; i++) {
sprintf(fileName, "%s%02d.cer", fileBase, (int)i);
certRef = (SecCertificateRef)CFArrayGetValueAtIndex(peerCerts, i);
CFDataRef derCert = SecCertificateCopyData(certRef);
if (derCert) {
writeFile(fileName, CFDataGetBytePtr(derCert),
CFDataGetLength(derCert));
CFRelease(derCert);
}
}
printf("...wrote %lu certs to fileBase %s\n", numCerts, fileBase);
}
/*
* Show result of an sslPing().
* Assumes the following from sslPingArgs:
*
* verbose
* tryVersion
* acceptedProts
* negVersion
* negCipher
* peerCerts
* certState
* sessionWasResumed
* sessionID
* sessionIDLength
* handshakeTime
*/
static void showSSLResult(
const sslPingArgs &pargs,
OSStatus err,
int displayPeerCerts,
char *fileBase) // non-NULL: write certs to file
{
CFIndex numPeerCerts;
printf("\n");
if(pargs.acceptedProts) {
printf(" Allowed SSL versions : %s\n", pargs.acceptedProts);
}
else {
printf(" Attempted SSL version : %s\n",
sslGetProtocolVersionString(pargs.tryVersion));
}
printf(" Result : %s\n", sslGetSSLErrString(err));
printf(" Negotiated SSL version : %s\n",
sslGetProtocolVersionString(pargs.negVersion));
printf(" Negotiated CipherSuite : %s\n",
sslGetCipherSuiteString(pargs.negCipher));
if(pargs.certState != kSSLClientCertNone) {
printf(" Client Cert State : %s\n",
sslGetClientCertStateString(pargs.certState));
}
if(pargs.verbose) {
printf(" Resumed Session : ");
if(pargs.sessionWasResumed) {
for(unsigned dex=0; dex<pargs.sessionIDLength; dex++) {
printf("%02X ", pargs.sessionID[dex]);
if(((dex % 8) == 7) && (dex != (pargs.sessionIDLength - 1))) {
printf("\n ");
}
}
printf("\n");
}
else {
printf("NOT RESUMED\n");
}
printf(" Handshake time : %f seconds\n", pargs.handshakeTimeOp);
}
if(pargs.peerCerts == NULL) {
numPeerCerts = 0;
}
else {
numPeerCerts = CFArrayGetCount(pargs.peerCerts);
}
printf(" Number of server certs : %lu\n", numPeerCerts);
if(numPeerCerts != 0) {
if (displayPeerCerts == 1) {
showPeerCerts(pargs.peerCerts, false);
} else if (displayPeerCerts == 2) {
showPeerTrust(pargs.peerTrust, false);
}
if(fileBase != NULL) {
writePeerCerts(pargs.peerCerts, fileBase);
}
}
printf("\n");
}
static int verifyProtocol(
bool verifyProt,
SSLProtocol maxProtocol,
SSLProtocol reqProtocol,
SSLProtocol negProtocol)
{
if(!verifyProt) {
return 0;
}
if(reqProtocol > maxProtocol) {
/* known not to support this attempt, relax */
reqProtocol = maxProtocol;
}
if(reqProtocol != negProtocol) {
printf("***Expected protocol %s; negotiated %s\n",
sslGetProtocolVersionString(reqProtocol),
sslGetProtocolVersionString(negProtocol));
return 1;
}
else {
return 0;
}
}
static int verifyClientCertState(
bool verifyCertState,
SSLClientCertificateState expectState,
SSLClientCertificateState gotState)
{
if(!verifyCertState) {
return 0;
}
if(expectState == gotState) {
return 0;
}
printf("***Expected clientCertState %s; got %s\n",
sslGetClientCertStateString(expectState),
sslGetClientCertStateString(gotState));
return 1;
}
static SSLProtocol charToProt(
char c, // 2, 3, t
char **argv)
{
switch(c) {
case '2':
return kSSLProtocol2;
case '3':
return kSSLProtocol3;
case 't':
return kTLSProtocol12;
default:
usage(argv);
}
/* NOT REACHED */
return kSSLProtocolUnknown;
}
int main(int argc, char **argv)
{
OSStatus err;
int arg;
char *argp;
char getMsg[300];
char fullFileBase[100];
int ourRtn = 0; // exit status - sum of all errors
unsigned loop;
SecKeychainRef serverKc = nil;
SecKeychainRef encryptKc = nil;
sslPingArgs pargs;
/* user-spec'd parameters */
const char *getPath = DEFAULT_PATH;
char *fileBase = NULL;
int displayCerts = 0;
bool doSslV2 = false;
bool doSslV3 = false;
bool doTlsV1 = true;
bool doTlsV11 = false;
bool doTlsV12 = false;
bool protXOnly = false; // kSSLProtocol3Only, kTLSProtocol1Only
bool doProtUnknown = false;
unsigned loopCount = 1;
bool doPause = false;
bool pauseFirstLoop = false;
bool verifyProt = false;
SSLProtocol maxProtocol = kTLSProtocol12; // for verifying negotiated
// protocol
char *acceptedProts = NULL;
char *keyChainName = NULL;
char *encryptKeyChainName = NULL;
char *getMsgSpec = NULL;
bool vfyCertState = false;
SSLClientCertificateState expectCertState = kSSLClientCertNone;
bool displayHandshakeTimes = false;
bool completeCertChain = false;
/* special case - one arg of "h" or "-h" or "hv" */
if(argc == 2) {
if((strcmp(argv[1], "h") == 0) || (strcmp(argv[1], "-h") == 0)) {
usage(argv);
}
if(strcmp(argv[1], "hv") == 0) {
usageVerbose(argv);
}
}
/* set up defaults */
memset(&pargs, 0, sizeof(sslPingArgs));
pargs.hostName = DEFAULT_HOST;
pargs.port = DEFAULT_PORT;
pargs.resumableEnable = true;
pargs.argv = argv;
for(arg=1; arg<argc; arg++) {
argp = argv[arg];
if(arg == 1) {
/* first arg, is always hostname; '-' means default */
if(argp[0] != '-') {
pargs.hostName = argp;
}
continue;
}
if(argp[0] == '/') {
/* path always starts with leading slash */
getPath = argp;
continue;
}
/* options */
switch(argp[0]) {
case 'e':
pargs.allowExpired = true;
break;
case 'E':
pargs.allowExpiredRoot = true;
break;
case 'x':
pargs.disableCertVerify = true;
break;
case 'M':
pargs.disableCertVerify = true; // implied
pargs.manualCertVerify = true;
break;
case 'a':
if(++arg == argc) {
/* requires another arg */
usage(argv);
}
pargs.anchorFile = argv[arg];
break;
case 'A':
if(++arg == argc) {
/* requires another arg */
usage(argv);
}
pargs.anchorFile = argv[arg];
pargs.replaceAnchors = true;
break;
case 'r':
pargs.allowAnyRoot = true;
break;
case 'd':
pargs.dumpRxData = true;
break;
case 'c':
displayCerts++;
break;
case 'f':
if(++arg == argc) {
/* requires another arg */
usage(argv);
}
fileBase = argv[arg];
break;
case 'C':
pargs.cipherRestrict = argp[2];
break;
case '2':
doSslV3 = doTlsV1 = doTlsV11 = false;
doSslV2 = true;
break;
case '3':
doSslV2 = doTlsV1 = doTlsV11 = doTlsV12 = false;
doSslV3 = true;
break;
case 't':
doSslV2 = doSslV3 = doTlsV11 = doTlsV12 = false;
doTlsV1 = true;
break;
case '%':
doSslV2 = doSslV3 = doTlsV1 = false;
doTlsV11 = true;
break;
case '^':
doSslV2 = doSslV3 = doTlsV1 = doTlsV12 = false;
doTlsV12 = true;
break;
case 'L':
doSslV2 = doSslV3 = doTlsV1 = doTlsV11 = doTlsV12 = true;
break;
case 'o':
protXOnly = true;
break;
case 'u':
doSslV2 = doSslV3 = doTlsV1 = doTlsV11 = doTlsV12 = false;
doProtUnknown = true;
break;
case 'K':
pargs.keepConnected = true;
break;
case 'n':
pargs.requireNotify = true;
pargs.keepConnected = true;
break;
case 'R':
pargs.resumableEnable = false;
break;
case 'b':
pargs.nonBlocking = true;
break;
case 'v':
verifyProt = true;
break;
case 'm':
if(argp[1] != '=') {
usage(argv);
}
verifyProt = true; // implied
maxProtocol = charToProt(argp[2], argv);
break;
case 'g':
if(argp[1] != '=') {
usage(argv);
}
acceptedProts = &argp[2];
doSslV3 = doSslV2 = doTlsV1 = doTlsV11 = doTlsV12 = false;
break;
case 'l':
loopCount = atoi(&argp[2]);
if(loopCount == 0) {
printf("***bad loopCount\n");
usage(argv);
}
break;
case 'P':
pargs.port = atoi(&argp[2]);
break;
case 'H':
pargs.allowHostnameSpoof = true;
break;
case 'F':
pargs.vfyHostName = &argp[2];
break;
case 'k':
keyChainName = &argp[2];
break;
case 'y':
encryptKeyChainName = &argp[2];
break;
case 'G':
getMsgSpec = &argp[2];
break;
case 'T':
if(argp[1] != '=') {
usage(argv);
}
vfyCertState = true;
switch(argp[2]) {
case 'n':
expectCertState = kSSLClientCertNone;
break;
case 'r':
expectCertState = kSSLClientCertRequested;
break;
case 's':
expectCertState = kSSLClientCertSent;
break;
case 'j':
expectCertState = kSSLClientCertRejected;
break;
default:
usage(argv);
}
break;
case 'z':
pargs.password = &argp[2];
break;
case 'p':
doPause = true;
break;
case '7':
pauseFirstLoop = true;
break;
case 'q':
pargs.quiet = true;
break;
case 'V':
pargs.verbose = true;
break;
case 's':
pargs.silent = pargs.quiet = true;
break;
case 'N':
displayHandshakeTimes = true;
break;
case '8':
completeCertChain = true;
break;
case 'h':
if(pargs.verbose || (argp[1] == 'v')) {
usageVerbose(argv);
}
else {
usage(argv);
}
default:
usage(argv);
}
}
if(getMsgSpec) {
pargs.getMsg = getMsgSpec;
}
else {
sprintf(getMsg, "%s %s %s",
DEFAULT_GETMSG, getPath, DEFAULT_GET_SUFFIX);
pargs.getMsg = getMsg;
}
#if NO_SERVER
# if DEBUG
securityd_init(NULL);
# endif
#endif
/* get client cert and optional encryption cert as CFArrayRef */
if(keyChainName) {
pargs.clientCerts = getSslCerts(keyChainName, false, completeCertChain,
pargs.anchorFile, &serverKc);
if(pargs.clientCerts == nil) {
exit(1);
}
#ifdef USE_CDSA_CRYPTO
if(pargs.password) {
OSStatus ortn = SecKeychainUnlock(serverKc,
strlen(pargs.password), pargs.password, true);
if(ortn) {
printf("SecKeychainUnlock returned %d\n", (int)ortn);
/* oh well */
}
}
#endif
}
if(encryptKeyChainName) {
pargs.encryptClientCerts = getSslCerts(encryptKeyChainName, true,
completeCertChain, pargs.anchorFile, &encryptKc);
if(pargs.encryptClientCerts == nil) {
exit(1);
}
}
signal(SIGPIPE, sigpipe);
for(loop=0; loop<loopCount; loop++) {
/*
* One pass for each protocol version, skipping any explicit version if
* an attempt at a higher version and succeeded in doing so successfully fell
* back.
*/
if(doTlsV12) {
pargs.tryVersion = kTLSProtocol12;
pargs.acceptedProts = NULL;
if(!pargs.silent) {
printf("Connecting to host %s with TLS V1.2...", pargs.hostName);
}
fflush(stdout);
err = sslPing(&pargs);
if(err) {
ourRtn++;
}
if(!pargs.quiet) {
if(fileBase) {
sprintf(fullFileBase, "%s_v3.1", fileBase);
}
showSSLResult(pargs,
err,
displayCerts,
fileBase ? fullFileBase : NULL);
}
freePeerCerts(pargs.peerCerts);
if(!err) {
/* deal with fallbacks, skipping redundant tests */
switch(pargs.negVersion) {
case kTLSProtocol11:
doTlsV11 =false;
break;
case kTLSProtocol1:
doTlsV11 =false;
doTlsV1 =false;
break;
case kSSLProtocol3:
doTlsV11 =false;
doTlsV1 =false;
doSslV3 = false;
break;
case kSSLProtocol2:
doTlsV11 =false;
doTlsV1 =false;
doSslV3 = false;
doSslV2 = false;
break;
default:
break;
}
ourRtn += verifyProtocol(verifyProt, maxProtocol, kTLSProtocol12,
pargs.negVersion);
}
/* note we do this regardless since the client state might be
* the cause of a failure */
ourRtn += verifyClientCertState(vfyCertState, expectCertState,
pargs.certState);
}
if(doTlsV11) {
pargs.tryVersion = kTLSProtocol11;
pargs.acceptedProts = NULL;
if(!pargs.silent) {
printf("Connecting to host %s with TLS V1.1...", pargs.hostName);
}
fflush(stdout);
err = sslPing(&pargs);
if(err) {
ourRtn++;
}
if(!pargs.quiet) {
if(fileBase) {
sprintf(fullFileBase, "%s_v3.1", fileBase);
}
showSSLResult(pargs,
err,
displayCerts,
fileBase ? fullFileBase : NULL);
}
freePeerCerts(pargs.peerCerts);
if(!err) {
/* deal with fallbacks, skipping redundant tests */
switch(pargs.negVersion) {
case kTLSProtocol1:
doTlsV1 =false;
break;
case kSSLProtocol3:
doTlsV1 =false;
doSslV3 = false;
break;
case kSSLProtocol2:
doTlsV1 =false;
doSslV3 = false;
doSslV2 = false;
break;
default:
break;
}
ourRtn += verifyProtocol(verifyProt, maxProtocol, kTLSProtocol11,
pargs.negVersion);
}
/* note we do this regardless since the client state might be
* the cause of a failure */
ourRtn += verifyClientCertState(vfyCertState, expectCertState,
pargs.certState);
}
if(doTlsV1) {
pargs.tryVersion =
protXOnly ? kTLSProtocol1Only : kTLSProtocol1;
pargs.acceptedProts = NULL;
if(!pargs.silent) {
printf("Connecting to host %s with TLS V1...", pargs.hostName);
}
fflush(stdout);
err = sslPing(&pargs);
if(err) {
ourRtn++;
}
if(!pargs.quiet) {
if(fileBase) {
sprintf(fullFileBase, "%s_v3.1", fileBase);
}
showSSLResult(pargs,
err,
displayCerts,
fileBase ? fullFileBase : NULL);
}
freePeerCerts(pargs.peerCerts);
if(!err) {
/* deal with fallbacks, skipping redundant tests */
switch(pargs.negVersion) {
case kSSLProtocol3:
doSslV3 = false;
break;
case kSSLProtocol2:
doSslV3 = false;
doSslV2 = false;
break;
default:
break;
}
ourRtn += verifyProtocol(verifyProt, maxProtocol, kTLSProtocol1,
pargs.negVersion);
}
/* note we do this regardless since the client state might be
* the cause of a failure */
ourRtn += verifyClientCertState(vfyCertState, expectCertState,
pargs.certState);
}
if(doSslV3) {
pargs.tryVersion = protXOnly ? kSSLProtocol3Only : kSSLProtocol3;
pargs.acceptedProts = NULL;
if(!pargs.silent) {
printf("Connecting to host %s with SSL V3...", pargs.hostName);
}
fflush(stdout);
err = sslPing(&pargs);
if(err) {
ourRtn++;
}
if(!pargs.quiet) {
if(fileBase) {
sprintf(fullFileBase, "%s_v3.0", fileBase);
}
showSSLResult(pargs,
err,
displayCerts,
fileBase ? fullFileBase : NULL);
}
freePeerCerts(pargs.peerCerts);
if(!err) {
/* deal with fallbacks, skipping redundant tests */
switch(pargs.negVersion) {
case kSSLProtocol2:
doSslV2 = false;
break;
default:
break;
}
ourRtn += verifyProtocol(verifyProt, maxProtocol, kSSLProtocol3,
pargs.negVersion);
}
/* note we do this regardless since the client state might be
* the cause of a failure */
ourRtn += verifyClientCertState(vfyCertState, expectCertState,
pargs.certState);
}
if(doSslV2) {
if(fileBase) {
sprintf(fullFileBase, "%s_v2", fileBase);
}
if(!pargs.silent) {
printf("Connecting to host %s with SSL V2...", pargs.hostName);
}
fflush(stdout);
pargs.tryVersion = kSSLProtocol2;
pargs.acceptedProts = NULL;
err = sslPing(&pargs);
if(err) {
ourRtn++;
}
if(!pargs.quiet) {
if(fileBase) {
sprintf(fullFileBase, "%s_v2", fileBase);
}
showSSLResult(pargs,
err,
displayCerts,
fileBase ? fullFileBase : NULL);
}
freePeerCerts(pargs.peerCerts);
if(!err) {
ourRtn += verifyProtocol(verifyProt, maxProtocol, kSSLProtocol2,
pargs.negVersion);
}
/* note we do this regardless since the client state might be
* the cause of a failure */
ourRtn += verifyClientCertState(vfyCertState, expectCertState,
pargs.certState);
}
if(doProtUnknown) {
if(!pargs.silent) {
printf("Connecting to host %s with kSSLProtocolUnknown...",
pargs.hostName);
}
fflush(stdout);
pargs.tryVersion = kSSLProtocolUnknown;
pargs.acceptedProts = NULL;
err = sslPing(&pargs);
if(err) {
ourRtn++;
}
if(!pargs.quiet) {
if(fileBase) {
sprintf(fullFileBase, "%s_def", fileBase);
}
showSSLResult(pargs,
err,
displayCerts,
fileBase ? fullFileBase : NULL);
}
freePeerCerts(pargs.peerCerts);
}
if(acceptedProts != NULL) {
pargs.acceptedProts = acceptedProts;
pargs.tryVersion = kSSLProtocolUnknown; // not used
if(!pargs.silent) {
printf("Connecting to host %s with acceptedProts %s...",
pargs.hostName, pargs.acceptedProts);
}
fflush(stdout);
err = sslPing(&pargs);
if(err) {
ourRtn++;
}
if(!pargs.quiet) {
if(fileBase) {
sprintf(fullFileBase, "%s_def", fileBase);
}
showSSLResult(pargs,
err,
displayCerts,
fileBase ? fullFileBase : NULL);
}
freePeerCerts(pargs.peerCerts);
}
if(doPause ||
(pauseFirstLoop &&
/* pause after first, before last to grab trace */
((loop == 0) || (loop == loopCount - 1))
)
) {
char resp;
fpurge(stdin);
printf("a to abort, c to continue: ");
resp = getchar();
if(resp == 'a') {
break;
}
}
} /* main loop */
if(displayHandshakeTimes) {
CFAbsoluteTime totalTime;
unsigned numHandshakes;
if(pargs.numHandshakes == 1) {
/* just display the first one */
totalTime = pargs.handshakeTimeFirst;
numHandshakes = 1;
}
else {
/* skip the first one */
totalTime = pargs.handshakeTimeTotal;
numHandshakes = pargs.numHandshakes - 1;
}
if(numHandshakes != 0) {
printf(" %u handshakes in %f seconds; %f seconds per handshake\n",
numHandshakes, totalTime,
(totalTime / numHandshakes));
}
}
//printCertShutdown();
if(ourRtn) {
printf("===%s exiting with %d %s for host %s\n", argv[0], ourRtn,
(ourRtn > 1) ? "errors" : "error", pargs.hostName);
}
return ourRtn;
}
| 26.815111 | 94 | 0.620204 | GaloisInc |
f67ea69d5ae165dfde1adcbcd5d28d00ace9b8c0 | 7,852 | hpp | C++ | engine/pmem_allocator/free_list.hpp | ZiyanShi/kvdk | ad8129a56bda0df645eb9bb0c7af7632a5521a0f | [
"BSD-3-Clause"
] | 100 | 2021-07-22T03:26:07.000Z | 2022-03-31T02:13:41.000Z | engine/pmem_allocator/free_list.hpp | ZiyanShi/kvdk | ad8129a56bda0df645eb9bb0c7af7632a5521a0f | [
"BSD-3-Clause"
] | 60 | 2021-08-09T03:38:33.000Z | 2022-03-30T08:54:25.000Z | engine/pmem_allocator/free_list.hpp | ZiyanShi/kvdk | ad8129a56bda0df645eb9bb0c7af7632a5521a0f | [
"BSD-3-Clause"
] | 37 | 2021-08-05T08:13:14.000Z | 2022-03-30T11:35:56.000Z | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2021 Intel Corporation
*/
#pragma once
#include <memory>
#include <set>
#include "../allocator.hpp"
#include "../utils/utils.hpp"
#include "kvdk/namespace.hpp"
namespace KVDK_NAMESPACE {
constexpr uint32_t kFreelistMaxClassifiedBlockSize = 255;
constexpr uint32_t kSpaceMapLockGranularity = 64;
class PMEMAllocator;
// A byte map to record free blocks of PMem space, used for merging adjacent
// free space entries in the free list
class SpaceMap {
public:
SpaceMap(uint64_t num_blocks)
: map_(num_blocks, {false, 0}),
lock_granularity_(kSpaceMapLockGranularity),
map_spins_(num_blocks / lock_granularity_ + 1) {}
uint64_t TestAndUnset(uint64_t offset, uint64_t length);
uint64_t TryMerge(uint64_t offset, uint64_t max_merge_length,
uint64_t min_merge_length);
void Set(uint64_t offset, uint64_t length);
uint64_t Size() { return map_.size(); }
private:
// The highest 1 bit ot the token indicates if this is the start of a space
// entry, the lower 7 bits indicate how many free blocks followed
struct Token {
public:
Token(bool is_start, uint8_t size)
: token_(size | (is_start ? (1 << 7) : 0)) {}
uint8_t Size() { return token_ & INT8_MAX; }
void Clear() { token_ = 0; }
bool Empty() { return Size() == 0; }
bool IsStart() { return token_ & (1 << 7); }
void UnStart() { token_ &= INT8_MAX; }
private:
uint8_t token_;
};
// how many blocks share a lock
const uint32_t lock_granularity_;
std::vector<Token> map_;
// every lock_granularity_ bytes share a spin lock
std::vector<SpinMutex> map_spins_;
};
// free entry pool consists of three level vectors, the first level
// indicates different block size, each block size consists of several free
// space entry lists (the second level), and each list consists of several
// free space entries (the third level).
//
// For a specific block size, a write thread will move a entry list from the
// pool to its thread cache while no usable free space in the cache, and the
// background thread will move cached entry list to the pool for merge and
// balance resource
//
// Organization of the three level vectors:
//
// block size (1st level) entry list (2nd level) entries (3th level)
// 1 ----------------- list1 ------------ entry1
// | |--- entry2
// |----- list2 ------------ entry1
// |--- entry2
// |--- entry3
// ...
// 2 ----------------- list1 ------------ entry1
// | |--- entry2
// | |--- entry3
// |----- list2
// ...
// ...
// max_block_size -------- list1
// |----- list2
class SpaceEntryPool {
public:
SpaceEntryPool(uint32_t max_classified_b_size)
: pool_(max_classified_b_size), spins_(max_classified_b_size) {}
// move a list of b_size free space entries to pool, "src" will be empty
// after move
void MoveEntryList(std::vector<PMemOffsetType> &src, uint32_t b_size) {
std::lock_guard<SpinMutex> lg(spins_[b_size]);
assert(b_size < pool_.size());
pool_[b_size].emplace_back();
pool_[b_size].back().swap(src);
}
// try to fetch a b_size free space entries list from pool to dst
bool TryFetchEntryList(std::vector<PMemOffsetType> &dst, uint32_t b_size) {
if (pool_[b_size].size() != 0) {
std::lock_guard<SpinMutex> lg(spins_[b_size]);
if (pool_[b_size].size() != 0) {
dst.swap(pool_[b_size].back());
pool_[b_size].pop_back();
return true;
}
}
return false;
}
private:
std::vector<std::vector<std::vector<PMemOffsetType>>> pool_;
// Entry lists of a same block size share a spin lock
std::vector<SpinMutex> spins_;
};
class Freelist {
public:
Freelist(uint32_t max_classified_b_size, uint64_t num_segment_blocks,
uint32_t block_size, uint32_t num_threads, uint64_t num_blocks,
PMEMAllocator *allocator)
: num_segment_blocks_(num_segment_blocks), block_size_(block_size),
max_classified_b_size_(max_classified_b_size),
active_pool_(max_classified_b_size),
merged_pool_(max_classified_b_size), space_map_(num_blocks),
flist_thread_cache_(num_threads, max_classified_b_size),
pmem_allocator_(allocator) {}
Freelist(uint64_t num_segment_blocks, uint32_t block_size,
uint32_t num_threads, uint64_t num_blocks, PMEMAllocator *allocator)
: Freelist(kFreelistMaxClassifiedBlockSize, num_segment_blocks,
block_size, num_threads, num_blocks, allocator) {}
// Add a space entry
void Push(const SpaceEntry &entry);
// Request a at least "size" free space entry
bool Get(uint32_t size, SpaceEntry *space_entry);
// Try to merge thread-cached free space entries to get a at least "size"
// entry
bool MergeGet(uint32_t size, SpaceEntry *space_entry);
// Merge adjacent free spaces stored in the entry pool into larger one
//
// Fetch every free space entry lists from active_pool_, for each entry in the
// list, try to merge followed free space with it. Then insert merged entries
// into merged_pool_. After merging, move all entry lists from merged_pool_ to
// active_pool_ for next run. Calculate the minimal timestamp of free entries
// in the pool meantime
// TODO: set a condition to decide if we need to do merging
void MergeAndCheckTSInPool();
// Move cached free space list to space entry pool to balance usable space
// of write threads
//
// Iterate every active entry lists of thread caches, move the list to
// active_pool_, and update minimal timestamp of free entries meantime
void MoveCachedListsToPool();
// Origanize free space entries, including merging adjacent space and move
// thread cached space entries to pool
void OrganizeFreeSpace();
private:
// Each write threads cache some freed space entries in active_entry_offsets
// to avoid contention. To balance free space entries among threads, if too
// many entries cached by a thread, newly freed entries will be stored to
// backup_entries and move to entry pool which shared by all threads.
struct alignas(64) FlistThreadCache {
FlistThreadCache(uint32_t max_classified_b_size)
: active_entry_offsets(max_classified_b_size),
spins(max_classified_b_size) {}
FlistThreadCache() = delete;
FlistThreadCache(FlistThreadCache &&) = delete;
FlistThreadCache(const FlistThreadCache &) = delete;
// Entry size stored in block unit
Array<std::vector<PMemOffsetType>> active_entry_offsets;
// Protect active_entry_offsets
Array<SpinMutex> spins;
};
class SpaceCmp {
public:
bool operator()(const SpaceEntry &s1, const SpaceEntry &s2) const {
return s1.size > s2.size;
}
};
uint64_t MergeSpace(uint64_t offset, uint64_t max_size,
uint64_t min_merge_size) {
if (min_merge_size > max_size) {
return 0;
}
uint64_t size = space_map_.TryMerge(offset, max_size, min_merge_size);
return size;
}
const uint64_t num_segment_blocks_;
const uint32_t block_size_;
const uint32_t max_classified_b_size_;
SpaceMap space_map_;
Array<FlistThreadCache> flist_thread_cache_;
SpaceEntryPool active_pool_;
SpaceEntryPool merged_pool_;
// Store all large free space entries that larger than max_classified_b_size_
std::set<SpaceEntry, SpaceCmp> large_entries_;
SpinMutex large_entries_spin_;
PMEMAllocator *pmem_allocator_;
};
} // namespace KVDK_NAMESPACE
| 35.529412 | 80 | 0.668492 | ZiyanShi |
f67fd54f28ab948d3d0082549649acdf0f75199f | 5,554 | cpp | C++ | src/modules/TUIO/OscPrintReceivedElements.cpp | my-digital-decay/Polycode | 5dd1836bc4710aea175a77433c17696f8330f596 | [
"MIT"
] | null | null | null | src/modules/TUIO/OscPrintReceivedElements.cpp | my-digital-decay/Polycode | 5dd1836bc4710aea175a77433c17696f8330f596 | [
"MIT"
] | null | null | null | src/modules/TUIO/OscPrintReceivedElements.cpp | my-digital-decay/Polycode | 5dd1836bc4710aea175a77433c17696f8330f596 | [
"MIT"
] | null | null | null | /*
oscpack -- Open Sound Control packet manipulation library
http://www.audiomulch.com/~rossb/oscpack
Copyright (c) 2004-2005 Ross Bencina <rossb@audiomulch.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
Any person wishing to distribute modifications to the Software is
requested to send the modifications to the original developer so that
they can be incorporated into the canonical version.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "OscPrintReceivedElements.h"
#include <iostream>
#include <iomanip>
#include <ctime>
namespace osc{
std::ostream& operator<<( std::ostream & os,
const ReceivedMessageArgument& arg )
{
switch( arg.TypeTag() ){
case TRUE_TYPE_TAG:
os << "bool:true";
break;
case FALSE_TYPE_TAG:
os << "bool:false";
break;
case NIL_TYPE_TAG:
os << "(Nil)";
break;
case INFINITUM_TYPE_TAG:
os << "(Infinitum)";
break;
case INT32_TYPE_TAG:
os << "int32:" << arg.AsInt32Unchecked();
break;
case FLOAT_TYPE_TAG:
os << "float32:" << arg.AsFloatUnchecked();
break;
case CHAR_TYPE_TAG:
{
char s[2] = {0};
s[0] = arg.AsCharUnchecked();
os << "char:'" << s << "'";
}
break;
case RGBA_COLOR_TYPE_TAG:
{
uint32 color = arg.AsRgbaColorUnchecked();
os << "RGBA:0x"
<< std::hex << std::setfill('0')
<< std::setw(2) << (int)((color>>24) & 0xFF)
<< std::setw(2) << (int)((color>>16) & 0xFF)
<< std::setw(2) << (int)((color>>8) & 0xFF)
<< std::setw(2) << (int)(color & 0xFF)
<< std::setfill(' ');
os.unsetf(std::ios::basefield);
}
break;
case MIDI_MESSAGE_TYPE_TAG:
{
uint32 m = arg.AsMidiMessageUnchecked();
os << "midi (port, status, data1, data2):<<"
<< std::hex << std::setfill('0')
<< "0x" << std::setw(2) << (int)((m>>24) & 0xFF)
<< " 0x" << std::setw(2) << (int)((m>>16) & 0xFF)
<< " 0x" << std::setw(2) << (int)((m>>8) & 0xFF)
<< " 0x" << std::setw(2) << (int)(m & 0xFF)
<< std::setfill(' ') << ">>";
os.unsetf(std::ios::basefield);
}
break;
case INT64_TYPE_TAG:
os << "int64:" << arg.AsInt64Unchecked();
break;
case TIME_TAG_TYPE_TAG:
{
os << "OSC-timetag:" << arg.AsTimeTagUnchecked();
std::time_t t =
(unsigned long)( arg.AsTimeTagUnchecked() >> 32 );
// strip trailing newline from string returned by ctime
const char *timeString = std::ctime( &t );
size_t len = strlen( timeString );
char *s = new char[ len + 1 ];
strcpy( s, timeString );
if( len )
s[ len - 1 ] = '\0';
os << " " << s;
}
break;
case DOUBLE_TYPE_TAG:
os << "double:" << arg.AsDoubleUnchecked();
break;
case STRING_TYPE_TAG:
os << "OSC-string:`" << arg.AsStringUnchecked() << "'";
break;
case SYMBOL_TYPE_TAG:
os << "OSC-string (symbol):`" << arg.AsSymbolUnchecked() << "'";
break;
case BLOB_TYPE_TAG:
{
unsigned long size;
const void *data;
arg.AsBlobUnchecked( data, size );
os << "OSC-blob:<<" << std::hex << std::setfill('0');
unsigned char *p = (unsigned char*)data;
for( unsigned long i = 0; i < size; ++i ){
os << "0x" << std::setw(2) << int(p[i]);
if( i != size-1 )
os << ' ';
}
os.unsetf(std::ios::basefield);
os << ">>" << std::setfill(' ');
}
break;
default:
os << "unknown";
}
return os;
}
std::ostream& operator<<( std::ostream & os, const ReceivedMessage& m )
{
os << "[" << m.AddressPattern();
bool first = true;
for( ReceivedMessage::const_iterator i = m.ArgumentsBegin();
i != m.ArgumentsEnd(); ++i ){
if( first ){
os << " ";
first = false;
}else{
os << ", ";
}
os << *i;
}
os << "]";
return os;
}
std::ostream& operator<<( std::ostream & os, const ReceivedBundle& b )
{
static int indent = 0;
for( int j=0; j < indent; ++j )
os << " ";
os << "{ ( ";
if( b.TimeTag() == 1 )
os << "immediate";
else
os << b.TimeTag();
os << " )\n";
++indent;
for( ReceivedBundle::const_iterator i = b.ElementsBegin();
i != b.ElementsEnd(); ++i ){
if( i->IsBundle() ){
ReceivedBundle b(*i);
os << b << "\n";
}else{
ReceivedMessage m(*i);
for( int j=0; j < indent; ++j )
os << " ";
os << m << "\n";
}
}
--indent;
for( int j=0; j < indent; ++j )
os << " ";
os << "}";
return os;
}
std::ostream& operator<<( std::ostream & os, const ReceivedPacket& p )
{
if( p.IsBundle() ){
ReceivedBundle b(p);
os << b << "\n";
}else{
ReceivedMessage m(p);
os << m << "\n";
}
return os;
}
} // namespace osc
| 23.045643 | 71 | 0.593086 | my-digital-decay |
f680e0ee906399c4abb2ed491b2d5f986f2d2220 | 3,048 | cpp | C++ | mandelbrot.cpp | Nicolas-Reyland/Mandelbrot-zoom | 3ec8200a9b2b46dadbc93c452fed050b691c113d | [
"MIT"
] | null | null | null | mandelbrot.cpp | Nicolas-Reyland/Mandelbrot-zoom | 3ec8200a9b2b46dadbc93c452fed050b691c113d | [
"MIT"
] | null | null | null | mandelbrot.cpp | Nicolas-Reyland/Mandelbrot-zoom | 3ec8200a9b2b46dadbc93c452fed050b691c113d | [
"MIT"
] | null | null | null | #include "mandelbrot.hpp"
#include <FL/fl_draw.H>
Mandelbrot::Mandelbrot(int max_iter, int screen_width, int screen_height, double start_x, double end_x, double start_y, double end_y, double zoom_center_x, double zoom_center_y, double zoom_coeff) :
max_iter(max_iter),
screen_width(screen_width), screen_height(screen_height),
start_x(start_x), start_y(start_y), end_x(end_x), end_y(end_y),
zoom_center_x(zoom_center_x), zoom_center_y(zoom_center_y), zoom_coeff(zoom_coeff)
{
}
Mandelbrot::~Mandelbrot() {}
void Mandelbrot::draw() {
// fl_point(int x, int y) -> draws a pixel at x,y
// fl_color(FL_Color|int c) -> sets the color
// fl_rgb_color(uchar g) -> returns grayscale
for (int i = 0; i < screen_height; i++) {
for (int j = 0; j < screen_width; j++) {
unsigned char color = set[i][j];
Fl_Color grayscale = fl_rgb_color(color);
fl_color(grayscale);
fl_point(j, i); // (j,i) and not (i,j) because i=y and j=x on screen
}
}
}
void Mandelbrot::calculate() {
// init variables
set = std::vector<std::vector<unsigned char>>();
double coeff = 255.0 / (double) max_iter;
double step_x = (end_x - start_x) / screen_width;
double step_y = (end_y - start_y) / screen_height;
//
unsigned char value;
// loop
for (double y = start_y; y < end_y; y += step_y) {
std::vector<unsigned char> row;
for (double x = start_x; x < end_x; x += step_x) {
int num_iter = calculate_point(std::complex<double>(x, y), max_iter);
value = (unsigned char) (255.0 - (((double) num_iter) * coeff));
row.push_back(value);
}
set.push_back(row);
}
}
void Mandelbrot::calculate_and_draw() {
// init variables
double coeff = 255.0 / (double) max_iter;
double step_x = (end_x - start_x) / screen_width;
double step_y = (end_y - start_y) / screen_height;
//
unsigned char value;
// loop
int i = 0;
for (double y = start_y; y < end_y; y += step_y) {
std::vector<unsigned char> row;
int j = 0;
for (double x = start_x; x < end_x; x += step_x) {
int num_iter = calculate_point(std::complex<double>(x, y), max_iter);
value = (unsigned char) (255.0 - (((double) num_iter) * coeff));
// draw pixel
Fl_Color grayscale = fl_rgb_color(value);
fl_color(grayscale);
fl_point(j, i);
j++;
}
i++;
}
}
void Mandelbrot::zoom() {
// calculate distances
double distance_left = zoom_center_x - start_x,
distance_right = end_x - zoom_center_x,
distance_top = zoom_center_y - start_y,
distance_bottom = end_y - zoom_center_y;
// calculate zoom distances
double zoom_left = distance_left * zoom_coeff,
zoom_right = distance_right * zoom_coeff,
zoom_top = distance_top * zoom_coeff,
zoom_bottom = distance_bottom * zoom_coeff;
// apply changes
start_x += zoom_left;
start_y += zoom_top;
end_x -= zoom_right;
end_y -= zoom_bottom;
}
int Mandelbrot::calculate_point(std::complex<double> z, int max_iter, int threshold) {
int num_iter = 0;
std::complex<double> c = z;
while (num_iter < max_iter && abs(z) < threshold) {
z = z * z + c;
num_iter++;
}
return num_iter;
}
| 29.592233 | 198 | 0.67979 | Nicolas-Reyland |
f680e37858f1de9e1fdc11fbde08ac8b389b435e | 62,594 | cpp | C++ | hi_scripting/scripting/engine/JavascriptEngineParser.cpp | romsom/HISE | 73e0e299493ce9236e6fafa7938d3477fcc36a4a | [
"Intel"
] | null | null | null | hi_scripting/scripting/engine/JavascriptEngineParser.cpp | romsom/HISE | 73e0e299493ce9236e6fafa7938d3477fcc36a4a | [
"Intel"
] | null | null | null | hi_scripting/scripting/engine/JavascriptEngineParser.cpp | romsom/HISE | 73e0e299493ce9236e6fafa7938d3477fcc36a4a | [
"Intel"
] | null | null | null | namespace hise { using namespace juce;
//==============================================================================
struct HiseJavascriptEngine::RootObject::TokenIterator
{
TokenIterator(const String& code, const String &externalFile) : location(code, externalFile), p(code.getCharPointer()) { skip(); }
DebugableObject::Location createDebugLocation()
{
DebugableObject::Location loc;
loc.fileName = location.externalFile;
loc.charNumber = (int)(location.location - location.program.getCharPointer());
return loc;
}
void skip()
{
skipWhitespaceAndComments();
location.location = p;
currentType = matchNextToken();
}
void skipBlock()
{
match(TokenTypes::openBrace);
int braceCount = 1;
while (currentType != TokenTypes::eof && braceCount > 0)
{
if (currentType == TokenTypes::openBrace) braceCount++;
else if (currentType == TokenTypes::closeBrace) braceCount--;
skip();
}
}
void match(TokenType expected)
{
if (currentType != expected)
location.throwError("Found " + getTokenName(currentType) + " when expecting " + getTokenName(expected));
skip();
}
bool matchIf(TokenType expected) { if (currentType == expected) { skip(); return true; } return false; }
bool matchesAny(TokenType t1, TokenType t2) const { return currentType == t1 || currentType == t2; }
bool matchesAny(TokenType t1, TokenType t2, TokenType t3) const { return matchesAny(t1, t2) || currentType == t3; }
CodeLocation location;
TokenType currentType;
var currentValue;
void clearLastComment()
{
lastComment = String();
}
String lastComment;
void skipWhitespaceAndComments()
{
for (;;)
{
p = p.findEndOfWhitespace();
if (*p == '/')
{
const juce_wchar c2 = p[1];
if (c2 == '/') { p = CharacterFunctions::find(p, (juce_wchar) '\n'); continue; }
if (c2 == '*')
{
location.location = p;
lastComment = String(p).upToFirstOccurrenceOf("*/", false, false).fromFirstOccurrenceOf("/**", false, false).trim();
p = CharacterFunctions::find(p + 2, CharPointer_ASCII("*/"));
if (p.isEmpty()) location.throwError("Unterminated '/*' comment");
p += 2; continue;
}
}
break;
}
}
private:
String::CharPointerType p;
static bool isIdentifierStart(const juce_wchar c) noexcept{ return CharacterFunctions::isLetter(c) || c == '_'; }
static bool isIdentifierBody(const juce_wchar c) noexcept{ return CharacterFunctions::isLetterOrDigit(c) || c == '_'; }
TokenType matchNextToken()
{
if (isIdentifierStart(*p))
{
String::CharPointerType end(p);
while (isIdentifierBody(*++end)) {}
const size_t len = (size_t)(end - p);
#define JUCE_JS_COMPARE_KEYWORD(name, str) if (len == sizeof (str) - 1 && matchToken (TokenTypes::name, len)) return TokenTypes::name;
JUCE_JS_KEYWORDS(JUCE_JS_COMPARE_KEYWORD)
currentValue = String(p, end); p = end;
return TokenTypes::identifier;
}
if (p.isDigit())
{
if (parseHexLiteral() || parseFloatLiteral() || parseOctalLiteral() || parseDecimalLiteral())
return TokenTypes::literal;
location.throwError("Syntax error in numeric constant");
}
if (parseStringLiteral(*p) || (*p == '.' && parseFloatLiteral()))
return TokenTypes::literal;
#define JUCE_JS_COMPARE_OPERATOR(name, str) if (matchToken (TokenTypes::name, sizeof (str) - 1)) return TokenTypes::name;
JUCE_JS_OPERATORS(JUCE_JS_COMPARE_OPERATOR)
if (!p.isEmpty())
location.throwError("Unexpected character '" + String::charToString(*p) + "' in source");
return TokenTypes::eof;
}
bool matchToken(TokenType name, const size_t len) noexcept
{
if (p.compareUpTo(CharPointer_ASCII(name), (int)len) != 0) return false;
p += (int)len; return true;
}
bool parseStringLiteral(juce_wchar quoteType)
{
if (quoteType != '"' && quoteType != '\'')
return false;
Result r(JSON::parseQuotedString(p, currentValue));
if (r.failed()) location.throwError(r.getErrorMessage());
return true;
}
bool parseHexLiteral()
{
if (*p != '0' || (p[1] != 'x' && p[1] != 'X')) return false;
String::CharPointerType t(++p);
int64 v = CharacterFunctions::getHexDigitValue(*++t);
if (v < 0) return false;
for (;;)
{
const int digit = CharacterFunctions::getHexDigitValue(*++t);
if (digit < 0) break;
v = v * 16 + digit;
}
currentValue = v; p = t;
return true;
}
bool parseFloatLiteral()
{
int numDigits = 0;
String::CharPointerType t(p);
while (t.isDigit()) { ++t; ++numDigits; }
const bool hasPoint = (*t == '.');
if (hasPoint)
while ((++t).isDigit()) ++numDigits;
if (numDigits == 0)
return false;
juce_wchar c = *t;
const bool hasExponent = (c == 'e' || c == 'E');
if (hasExponent)
{
c = *++t;
if (c == '+' || c == '-') ++t;
if (!t.isDigit()) return false;
while ((++t).isDigit()) {}
}
if (!(hasExponent || hasPoint)) return false;
currentValue = CharacterFunctions::getDoubleValue(p); p = t;
return true;
}
bool parseOctalLiteral()
{
String::CharPointerType t(p);
int64 v = *t - '0';
if (v != 0) return false; // first digit of octal must be 0
for (;;)
{
const int digit = (int)(*++t - '0');
if (isPositiveAndBelow(digit, 8)) v = v * 8 + digit;
else if (isPositiveAndBelow(digit, 10)) location.throwError("Decimal digit in octal constant");
else break;
}
currentValue = v; p = t;
return true;
}
bool parseDecimalLiteral()
{
int64 v = 0;
for (;; ++p)
{
const int digit = (int)(*p - '0');
if (isPositiveAndBelow(digit, 10)) v = v * 10 + digit;
else break;
}
currentValue = v;
return true;
}
};
//==============================================================================
struct HiseJavascriptEngine::RootObject::ExpressionTreeBuilder : private TokenIterator
{
ExpressionTreeBuilder(const String code, const String externalFile) :
TokenIterator(code, externalFile)
{
#if ENABLE_SCRIPTING_BREAKPOINTS
if (externalFile.isNotEmpty())
{
fileId = Identifier("File_" + File(externalFile).getFileNameWithoutExtension());
}
#endif
}
void setupApiData(HiseSpecialData &data, const String& codeToPreprocess)
{
hiseSpecialData = &data;
currentNamespace = hiseSpecialData;
#if 0 //ENABLE_SCRIPTING_BREAKPOINTS
Identifier localId = hiseSpecialData->getBreakpointLocalIdentifier();
if (localId.isValid())
{
if (hiseSpecialData->getCallback(localId) != nullptr)
{
currentlyParsedCallback = localId;
}
else if (auto obj = hiseSpecialData->getInlineFunction(localId))
{
currentInlineFunction = obj;
currentlyParsingInlineFunction = true;
}
}
#endif
if(codeToPreprocess.isNotEmpty())
preprocessCode(codeToPreprocess);
}
void preprocessCode(const String& codeToPreprocess, const String& externalFileName="");
BlockStatement* parseStatementList()
{
ScopedPointer<BlockStatement> b(new BlockStatement(location));
while (currentType != TokenTypes::closeBrace && currentType != TokenTypes::eof)
{
#if ENABLE_SCRIPTING_BREAKPOINTS
const int64 charactersBeforeToken = (location.location - location.program.getCharPointer());
ScopedPointer<Statement> s = parseStatement();
const int64 charactersAfterToken = (location.location - location.program.getCharPointer());
Range<int64> r(charactersBeforeToken, charactersAfterToken);
for (int i = 0; i < breakpoints.size(); i++)
{
const bool isOtherFile = !fileId.isNull() && breakpoints[i].snippetId != fileId;
const bool isFileButOnInit = fileId.isNull() && breakpoints[i].snippetId.toString().startsWith("File");
if (isOtherFile || isFileButOnInit)
continue;
if (breakpoints[i].found)
continue;
if (r.contains(breakpoints[i].charIndex))
{
if (currentInlineFunction != nullptr)
{
if (getCurrentNamespace() != hiseSpecialData)
{
const String combination = currentNamespace->id.toString() + "." + dynamic_cast<InlineFunction::Object*>(currentInlineFunction)->name.toString();
s->breakpointReference.localScopeId = Identifier(combination);
}
else
{
s->breakpointReference.localScopeId = dynamic_cast<InlineFunction::Object*>(currentInlineFunction)->name;
}
}
else if (currentlyParsedCallback.isValid())
{
s->breakpointReference.localScopeId = currentlyParsedCallback;
}
s->breakpointReference.index = breakpoints[i].index;
breakpoints.getReference(i).found = true;
break;
}
}
#else
ScopedPointer<Statement> s = parseStatement();
#endif
if (LockStatement* ls = dynamic_cast<LockStatement*>(s.get()))
{
b->lockStatements.add(ls);
s.release();
}
else
{
b->statements.add(s.release());
}
}
return b.release();
}
String removeUnneededNamespaces(int& counter);
String uglify();
void parseFunctionParamsAndBody(FunctionObject& fo)
{
match(TokenTypes::openParen);
while (currentType != TokenTypes::closeParen)
{
fo.parameters.add(currentValue.toString());
match(TokenTypes::identifier);
if (currentType != TokenTypes::closeParen)
match(TokenTypes::comma);
}
match(TokenTypes::closeParen);
fo.body = parseBlock();
}
#if INCLUDE_NATIVE_JIT
Expression* parseNativeJITExpression(NativeJITScope* scope)
{
const Identifier scopeId = parseIdentifier();
jassert(scopeId == scope->getName());
match(TokenTypes::dot);
static const Identifier pb("processBlock");
const Identifier id = parseIdentifier();
if (scope->isFunction(id))
{
ScopedPointer<RootObject::NativeJIT::FunctionCall> f = new RootObject::NativeJIT::FunctionCall(location);
f->scope = scope;
f->numArgs = scope->getNumArgsForFunction(id);
f->functionName = id;
match(TokenTypes::openParen);
while (currentType != TokenTypes::closeParen && currentType != TokenTypes::eof)
{
ExpPtr p = parseExpression();
matchIf(TokenTypes::comma);
f->arguments.add(p.release());
}
match(TokenTypes::closeParen);
if (f->numArgs != f->arguments.size())
{
location.throwError("Argument amount mismatch. Expected: " + String(f->numArgs) + ". Actual: " + String(f->arguments.size()));
}
return f.release();
}
else if (scope->isGlobal(id))
{
ScopedPointer<RootObject::NativeJIT::GlobalReference> r = new RootObject::NativeJIT::GlobalReference(location, scope);
r->index = scope->getIndexForGlobal(id);
return parseSuffixes(r.release());
}
else if (id == pb)
{
ScopedPointer<RootObject::NativeJIT::ProcessBufferCall> c = new RootObject::NativeJIT::ProcessBufferCall(location, scope);
match(TokenTypes::openParen);
ExpPtr target = parseExpression();
match(TokenTypes::closeParen);
c->target = target.release();
return c.release();
}
else
{
location.throwError(id.toString() + " not found in " + scope->getName());
}
}
#endif
Expression* parseExpression()
{
Identifier id = Identifier::isValidIdentifier(currentValue.toString()) ? Identifier(currentValue.toString()) : Identifier::null;
bool skipConsoleCalls = false;
#if !ENABLE_SCRIPTING_SAFE_CHECKS
static const Identifier c("Console");
if (id == c)
{
skipConsoleCalls = true;
}
#endif
ExpPtr lhs;
#if INCLUDE_NATIVE_JIT
if (auto s = hiseSpecialData->getNativeJITScope(id))
{
lhs = parseNativeJITExpression(s);
}
else if (auto c = hiseSpecialData->getNativeCompiler(id))
{
parseIdentifier();
match(TokenTypes::dot);
parseIdentifier();
match(TokenTypes::openParen);
match(TokenTypes::closeParen);
ScopedPointer<NativeJITScope> s = c->compileAndReturnScope();
if (s == nullptr)
{
location.throwError("NativeJIT compile error: " + c->getErrorMessage());
}
hiseSpecialData->jitScopes.add(s.get());
return new RootObject::NativeJIT::ScopeReference(location, s.release());
}
else
{
lhs = parseLogicOperator();
}
#else
lhs = parseLogicOperator();
#endif
if (matchIf(TokenTypes::in))
{
ExpPtr rhs(parseExpression());
currentIterator = id;
return rhs.release();
}
if (matchIf(TokenTypes::question)) return parseTerneryOperator(lhs);
if (matchIf(TokenTypes::assign)) { ExpPtr rhs(parseExpression()); return new Assignment(location, lhs, rhs); }
if (matchIf(TokenTypes::plusEquals)) return parseInPlaceOpExpression<AdditionOp>(lhs);
if (matchIf(TokenTypes::minusEquals)) return parseInPlaceOpExpression<SubtractionOp>(lhs);
if (matchIf(TokenTypes::timesEquals)) return parseInPlaceOpExpression<MultiplyOp>(lhs);
if (matchIf(TokenTypes::divideEquals)) return parseInPlaceOpExpression<DivideOp>(lhs);
if (matchIf(TokenTypes::moduloEquals)) return parseInPlaceOpExpression<ModuloOp>(lhs);
if (matchIf(TokenTypes::leftShiftEquals)) return parseInPlaceOpExpression<LeftShiftOp>(lhs);
if (matchIf(TokenTypes::andEquals)) return parseInPlaceOpExpression<BitwiseAndOp>(lhs);
if (matchIf(TokenTypes::orEquals)) return parseInPlaceOpExpression<BitwiseOrOp>(lhs);
if (matchIf(TokenTypes::xorEquals)) return parseInPlaceOpExpression<BitwiseXorOp>(lhs);
if (matchIf(TokenTypes::rightShiftEquals)) return parseInPlaceOpExpression<RightShiftOp>(lhs);
if (skipConsoleCalls)
{
return new Expression(location);
}
return lhs.release();
}
Array<Breakpoint> breakpoints;
private:
HiseSpecialData *hiseSpecialData;
bool currentlyParsingInlineFunction = false;
Identifier currentlyParsedCallback = Identifier::null;
Identifier fileId;
DynamicObject* currentInlineFunction = nullptr;
JavascriptNamespace* currentNamespace = nullptr;
JavascriptNamespace* getCurrentNamespace()
{
jassert(currentNamespace != nullptr);
return currentNamespace;
}
void throwError(const String& err) const { location.throwError(err); }
template <typename OpType>
Expression* parseInPlaceOpExpression(ExpPtr& lhs)
{
ExpPtr rhs(parseExpression());
Expression* bareLHS = lhs; // careful - bare pointer is deliberately alised
return new SelfAssignment(location, bareLHS, new OpType(location, lhs, rhs));
}
BlockStatement* parseBlock()
{
match(TokenTypes::openBrace);
ScopedPointer<BlockStatement> b(parseStatementList());
match(TokenTypes::closeBrace);
return b.release();
}
Statement* parseStatement()
{
if (matchIf(TokenTypes::include_)) return parseExternalFile();
if (matchIf(TokenTypes::inline_)) return parseInlineFunction(getCurrentNamespace());
if (currentType == TokenTypes::openBrace) return parseBlock();
if (matchIf(TokenTypes::const_)) return parseConstVar(getCurrentNamespace());
if (matchIf(TokenTypes::var)) return parseVar();
if (matchIf(TokenTypes::register_var)) return parseRegisterVar(getCurrentNamespace());
if (matchIf(TokenTypes::global_)) return parseGlobalAssignment();
if (matchIf(TokenTypes::local_)) return parseLocalAssignment();
if (matchIf(TokenTypes::namespace_)) return parseNamespace();
if (matchIf(TokenTypes::if_)) return parseIf();
if (matchIf(TokenTypes::while_)) return parseDoOrWhileLoop(false);
if (matchIf(TokenTypes::do_)) return parseDoOrWhileLoop(true);
if (matchIf(TokenTypes::for_)) return parseForLoop();
if (matchIf(TokenTypes::return_)) return parseReturn();
if (matchIf(TokenTypes::switch_)) return parseSwitchBlock();
if (matchIf(TokenTypes::break_)) return new BreakStatement(location);
if (matchIf(TokenTypes::continue_)) return new ContinueStatement(location);
if (matchIf(TokenTypes::function)) return parseFunction();
if (matchIf(TokenTypes::loadJit_)) return parseJITModule();
if (matchIf(TokenTypes::semicolon)) return new Statement(location);
if (matchIf(TokenTypes::plusplus)) return parsePreIncDec<AdditionOp>();
if (matchIf(TokenTypes::minusminus)) return parsePreIncDec<SubtractionOp>();
if (matchIf(TokenTypes::rLock_)) return parseLockStatement(true);
if (matchIf(TokenTypes::wLock_)) return parseLockStatement(false);
if (matchesAny(TokenTypes::openParen, TokenTypes::openBracket))
return matchEndOfStatement(parseFactor());
if (matchesAny(TokenTypes::identifier, TokenTypes::literal, TokenTypes::minus))
{
ExpPtr ex = parseExpression();
return matchEndOfStatement(ex.release());
}
throwError("Found " + getTokenName(currentType) + " when expecting a statement");
return nullptr;
}
String getFileContent(const String &fileNameInScript, String &refFileName)
{
String cleanedFileName = fileNameInScript.removeCharacters("\"\'");
if (cleanedFileName.contains("{DEVICE}"))
{
cleanedFileName = cleanedFileName.replace("{DEVICE}", HiseDeviceSimulator::getDeviceName());
}
#if USE_BACKEND
if (File::isAbsolutePath(cleanedFileName))
refFileName = cleanedFileName;
else if (cleanedFileName.contains("{GLOBAL_SCRIPT_FOLDER}"))
{
File globalScriptFolder = PresetHandler::getGlobalScriptFolder(dynamic_cast<Processor*>(hiseSpecialData->processor));
const String f1 = cleanedFileName.fromFirstOccurrenceOf("{GLOBAL_SCRIPT_FOLDER}", false, false);
refFileName = globalScriptFolder.getChildFile(f1).getFullPathName();
}
else
{
const String fileName = "{PROJECT_FOLDER}" + cleanedFileName;
refFileName = GET_PROJECT_HANDLER(dynamic_cast<Processor*>(hiseSpecialData->processor)).getFilePath(fileName, ProjectHandler::SubDirectories::Scripts);
}
File f(refFileName);
const String shortFileName = f.getFileName();
if (!f.existsAsFile())
throwError("File " + refFileName + " not found");
for (int i = 0; i < hiseSpecialData->includedFiles.size(); i++)
{
if (hiseSpecialData->includedFiles[i]->f == f)
{
debugToConsole(dynamic_cast<Processor*>(hiseSpecialData->processor), "File " + shortFileName + " was included multiple times");
return String();
}
}
return f.loadFileAsString();
#else
refFileName = cleanedFileName;
if (File::isAbsolutePath(refFileName))
{
File f(refFileName);
for (int i = 0; i < hiseSpecialData->includedFiles.size(); i++)
{
if (hiseSpecialData->includedFiles[i]->f == f)
{
DBG("File " + refFileName + " was included multiple times");
return String();
}
}
return f.loadFileAsString();
}
else
{
for (int i = 0; i < hiseSpecialData->includedFiles.size(); i++)
{
if (hiseSpecialData->includedFiles[i]->scriptName == refFileName)
{
DBG("Script " + refFileName + " was included multiple times");
return String();
}
}
return dynamic_cast<Processor*>(hiseSpecialData->processor)->getMainController()->getExternalScriptFromCollection(fileNameInScript);
}
#endif
};
Statement* parseExternalFile()
{
if (getCurrentNamespace() != hiseSpecialData)
{
location.throwError("Including files inside namespaces is not supported");
}
match(TokenTypes::openParen);
String refFileName;
String fileContent = getFileContent(currentValue.toString(), refFileName);
if (fileContent.isEmpty())
{
match(TokenTypes::literal);
match(TokenTypes::closeParen);
match(TokenTypes::semicolon);
return new Statement(location);
}
else
{
#if USE_BACKEND
File f(refFileName);
hiseSpecialData->includedFiles.add(new ExternalFileData(ExternalFileData::Type::RelativeFile, f, String()));
#else
if (File::isAbsolutePath(refFileName))
hiseSpecialData->includedFiles.add(new ExternalFileData(ExternalFileData::Type::AbsoluteFile, File(refFileName), String()));
else
hiseSpecialData->includedFiles.add(new ExternalFileData(ExternalFileData::Type::AbsoluteFile, File(), refFileName));
#endif
try
{
ExpressionTreeBuilder ftb(fileContent, refFileName);
#if ENABLE_SCRIPTING_BREAKPOINTS
ftb.breakpoints.addArray(breakpoints);
#endif
ftb.hiseSpecialData = hiseSpecialData;
ftb.currentNamespace = hiseSpecialData;
//ftb.setupApiData(*hiseSpecialData, fileContent);
ScopedPointer<BlockStatement> s = ftb.parseStatementList();
match(TokenTypes::literal);
match(TokenTypes::closeParen);
match(TokenTypes::semicolon);
return s.release();
}
catch (String &errorMessage)
{
hiseSpecialData->includedFiles.getLast()->setErrorMessage(errorMessage);
throw errorMessage;
}
}
}
Expression* matchEndOfStatement(Expression* ex) { ExpPtr e(ex); if (currentType != TokenTypes::eof) match(TokenTypes::semicolon); return e.release(); }
Expression* matchCloseParen(Expression* ex) { ExpPtr e(ex); match(TokenTypes::closeParen); return e.release(); }
Statement* parseIf()
{
ScopedPointer<IfStatement> s(new IfStatement(location));
match(TokenTypes::openParen);
s->condition = parseExpression();
match(TokenTypes::closeParen);
s->trueBranch = parseStatement();
s->falseBranch = matchIf(TokenTypes::else_) ? parseStatement() : new Statement(location);
return s.release();
}
Statement *parseRegisterAssignment(const Identifier &id)
{
match(TokenTypes::identifier);
match(TokenTypes::assign);
//const int index = registerIdentifiers.indexOf(id);
const int index = hiseSpecialData->varRegister.getRegisterIndex(id);
RegisterAssignment *r = new RegisterAssignment(location, index, parseExpression());
match(TokenTypes::semicolon);
return r;
}
Statement* parseReturn()
{
if (matchIf(TokenTypes::semicolon))
return new ReturnStatement(location, new Expression(location));
ReturnStatement* r = new ReturnStatement(location, parseExpression());
matchIf(TokenTypes::semicolon);
return r;
}
Statement* parseVar()
{
#if 0
if (getCurrentNamespace() != hiseSpecialData)
{
location.throwError("No var definitions inside namespaces (use reg or const var instead)");
}
#endif
ScopedPointer<VarStatement> s(new VarStatement(location));
s->name = parseIdentifier();
hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::RootScope, s->name, location);
s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location);
if (matchIf(TokenTypes::comma))
{
ScopedPointer<BlockStatement> block(new BlockStatement(location));
block->statements.add(s.release());
block->statements.add(parseVar());
return block.release();
}
match(TokenTypes::semicolon);
return s.release();
}
Statement* parseConstVar(JavascriptNamespace* ns)
{
matchIf(TokenTypes::var);
ScopedPointer<ConstVarStatement> s(new ConstVarStatement(location));
s->name = parseIdentifier();
hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::ConstVariables, s->name, location);
s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location);
#if INCLUDE_NATIVE_JIT
if (auto sr = dynamic_cast<RootObject::NativeJIT::ScopeReference*>(s->initialiser.get()))
{
sr->scope->setName(s->name);
}
#endif
if (matchIf(TokenTypes::comma))
{
ScopedPointer<BlockStatement> block(new BlockStatement(location));
block->statements.add(s.release());
block->statements.add(parseVar());
return block.release();
}
jassert(ns->constObjects.contains(s->name));
static const var uninitialised("uninitialised");
ns->constObjects.set(s->name, uninitialised); // Will be initialied at runtime
s->ns = ns;
return s.release();
}
Statement *parseRegisterVar(JavascriptNamespace* ns, TokenIterator* preparser=nullptr)
{
if (preparser)
{
Identifier name = preparser->currentValue.toString();
ns->varRegister.addRegister(name, var::undefined());
ns->registerLocations.add(preparser->createDebugLocation());
if (ns->registerLocations.size() != ns->varRegister.getNumUsedRegisters())
{
String s;
if (!ns->id.isNull())
s << ns->id.toString() << ".";
s << name << ": error at definition";
preparser->location.throwError(s);
}
return nullptr;
}
else
{
ScopedPointer<RegisterVarStatement> s(new RegisterVarStatement(location));
s->name = parseIdentifier();
hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::Register, s->name, location);
s->varRegister = &ns->varRegister;
s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location);
if (matchIf(TokenTypes::comma))
{
ScopedPointer<BlockStatement> block(new BlockStatement(location));
block->statements.add(s.release());
block->statements.add(parseVar());
return block.release();
}
match(TokenTypes::semicolon);
return s.release();
}
}
Statement* parseLockStatement(bool isReadLock)
{
ScopedPointer<LockStatement> ls = new LockStatement(location, isReadLock);
match(TokenTypes::openParen);
ls->lockedObj = parseFactor();
match(TokenTypes::closeParen);
match(TokenTypes::semicolon);
return ls.release();
}
Statement* parseGlobalAssignment()
{
ScopedPointer<GlobalVarStatement> s(new GlobalVarStatement(location));
s->name = parseIdentifier();
if (!hiseSpecialData->globals->hasProperty(s->name))
{
hiseSpecialData->globals->setProperty(s->name, var::undefined());
}
s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location);
if (matchIf(TokenTypes::comma))
{
ScopedPointer<BlockStatement> block(new BlockStatement(location));
block->statements.add(s.release());
block->statements.add(parseVar());
return block.release();
}
match(TokenTypes::semicolon);
return s.release();
}
Statement* parseLocalAssignment()
{
if (InlineFunction::Object::Ptr ifo = dynamic_cast<InlineFunction::Object*>(getCurrentInlineFunction()))
{
ScopedPointer<LocalVarStatement> s(new LocalVarStatement(location, ifo));
s->name = parseIdentifier();
hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::LocalScope, s->name, location);
ifo->localProperties.set(s->name, var::undefined());
s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location);
if (matchIf(TokenTypes::comma))
{
ScopedPointer<BlockStatement> block(new BlockStatement(location));
block->statements.add(s.release());
block->statements.add(parseVar());
return block.release();
}
match(TokenTypes::semicolon);
return s.release();
}
else if (!currentlyParsedCallback.isNull())
{
Callback* callback = hiseSpecialData->getCallback(currentlyParsedCallback);
ScopedPointer<CallbackLocalStatement> s(new CallbackLocalStatement(location, callback));
s->name = parseIdentifier();
hiseSpecialData->checkIfExistsInOtherStorage(HiseSpecialData::VariableStorageType::LocalScope, s->name, location);
callback->localProperties.set(s->name, var());
s->initialiser = matchIf(TokenTypes::assign) ? parseExpression() : new Expression(location);
if (matchIf(TokenTypes::comma))
{
ScopedPointer<BlockStatement> block(new BlockStatement(location));
block->statements.add(s.release());
block->statements.add(parseVar());
return block.release();
}
match(TokenTypes::semicolon);
return s.release();
}
throwError("Cannot define local variables outside of inline functions or callbacks.");
RETURN_IF_NO_THROW(nullptr)
}
Statement* parseCallback()
{
Identifier name = parseIdentifier();
Callback *c = hiseSpecialData->getCallback(name);
jassert(c != nullptr);
match(TokenTypes::openParen);
for (int i = 0; i < c->getNumArgs(); i++)
{
c->parameters[i] = parseIdentifier();
c->parameterValues[i] = var::undefined();
if (i != c->getNumArgs() - 1) match(TokenTypes::comma);
}
match(TokenTypes::closeParen);
ScopedValueSetter<Identifier> cParser(currentlyParsedCallback, name, Identifier::null);
ScopedPointer<BlockStatement> s = parseBlock();
c->setStatements(s.release());
return new Statement(location);
}
Statement* parseNamespace()
{
Identifier namespaceId = parseIdentifier();
currentNamespace = hiseSpecialData->getNamespace(namespaceId);
if (currentNamespace == nullptr)
{
location.throwError("Error at parsing namespace");
}
ScopedPointer<BlockStatement> block = parseBlock();
currentNamespace = hiseSpecialData;
return block.release();
}
Statement* parseFunction()
{
Identifier name;
if (hiseSpecialData->getCallback(currentValue.toString()))
{
return parseCallback();
}
var fn = parseFunctionDefinition(name);
if (name.isNull())
throwError("Functions defined at statement-level must have a name");
ExpPtr nm(new UnqualifiedName(location, name, true)), value(new LiteralValue(location, fn));
return new Assignment(location, nm, value);
}
InlineFunction::Object *getInlineFunction(Identifier &id, JavascriptNamespace* ns=nullptr)
{
if (ns == nullptr)
{
for (int i = 0; i < hiseSpecialData->inlineFunctions.size(); i++)
{
DynamicObject *o = hiseSpecialData->inlineFunctions.getUnchecked(i);
InlineFunction::Object *obj = dynamic_cast<InlineFunction::Object*>(o);
jassert(obj != nullptr);
if (obj->name == id) return obj;
}
}
else
{
for (int i = 0; i < ns->inlineFunctions.size(); i++)
{
DynamicObject *o = ns->inlineFunctions.getUnchecked(i);
InlineFunction::Object *obj = dynamic_cast<InlineFunction::Object*>(o);
jassert(obj != nullptr);
if (obj->name == id) return obj;
}
}
return nullptr;
}
JavascriptNamespace* getNamespaceForStorageType(JavascriptNamespace::StorageType storageType, JavascriptNamespace* nameSpaceToLook, const Identifier &id)
{
switch (storageType)
{
case HiseJavascriptEngine::RootObject::JavascriptNamespace::StorageType::Register:
if (nameSpaceToLook != nullptr && nameSpaceToLook->varRegister.getRegisterIndex(id) != -1) return nameSpaceToLook;
if (hiseSpecialData->varRegister.getRegisterIndex(id) != -1) return hiseSpecialData;
break;
case HiseJavascriptEngine::RootObject::JavascriptNamespace::StorageType::ConstVariable:
if (nameSpaceToLook != nullptr && nameSpaceToLook->constObjects.contains(id)) return nameSpaceToLook;
if (hiseSpecialData->constObjects.contains(id)) return hiseSpecialData;
break;
case HiseJavascriptEngine::RootObject::JavascriptNamespace::StorageType::InlineFunction:
{
if (nameSpaceToLook != nullptr)
{
for (int i = 0; i < nameSpaceToLook->inlineFunctions.size(); i++)
{
if (dynamic_cast<InlineFunction::Object*>(nameSpaceToLook->inlineFunctions[i].get())->name == id)
return nameSpaceToLook;
}
}
for (int i = 0; i < hiseSpecialData->inlineFunctions.size(); i++)
{
if (dynamic_cast<InlineFunction::Object*>(hiseSpecialData->inlineFunctions[i].get())->name == id)
return hiseSpecialData;
}
break;
}
case HiseJavascriptEngine::RootObject::JavascriptNamespace::StorageType::numStorageTypes:
break;
default:
break;
}
return nullptr;
}
int getRegisterIndex(const Identifier& id, JavascriptNamespace* ns = nullptr)
{
if (ns == nullptr)
{
return hiseSpecialData->varRegister.getRegisterIndex(id);
}
else
{
return ns->varRegister.getRegisterIndex(id);
}
}
var* getRegisterData(int index, JavascriptNamespace* ns = nullptr)
{
if (ns == nullptr)
{
return hiseSpecialData->varRegister.getVarPointer(index);
}
else
{
return ns->varRegister.getVarPointer(index);
}
}
int getConstIndex(const Identifier& id, JavascriptNamespace* ns = nullptr)
{
if (ns == nullptr)
{
return hiseSpecialData->constObjects.indexOf(id);
}
else
{
return ns->constObjects.indexOf(id);
}
}
var* getConstData(int index, JavascriptNamespace* ns = nullptr)
{
if (ns == nullptr)
{
return hiseSpecialData->constObjects.getVarPointerAt(index);
}
else
{
return ns->constObjects.getVarPointerAt(index);
}
}
DynamicObject* getCurrentInlineFunction()
{
return currentInlineFunction;
}
Expression* parseInlineFunctionCall(InlineFunction::Object *obj)
{
ScopedPointer<InlineFunction::FunctionCall> f = new InlineFunction::FunctionCall(location, obj);
parseIdentifier();
if (currentType == TokenTypes::openParen)
{
match(TokenTypes::openParen);
while (currentType != TokenTypes::closeParen)
{
f->addParameter(parseExpression());
if (currentType != TokenTypes::closeParen)
match(TokenTypes::comma);
}
if (f->numArgs != f->parameterExpressions.size())
{
throwError("Inline function call " + obj->name + ": parameter amount mismatch: " + String(f->parameterExpressions.size()) + " (Expected: " + String(f->numArgs) + ")");
}
return matchCloseParen(f.release());
}
else
{
return new LiteralValue(location, var(obj));
}
}
Statement *parseInlineFunction(JavascriptNamespace* ns, TokenIterator *preparser=nullptr)
{
if (preparser != nullptr)
{
DebugableObject::Location loc = preparser->createDebugLocation();
preparser->match(TokenTypes::function);
Identifier name = preparser->currentValue.toString();
preparser->match(TokenTypes::identifier);
preparser->match(TokenTypes::openParen);
Array<Identifier> inlineArguments;
while (preparser->currentType != TokenTypes::closeParen)
{
inlineArguments.add(preparser->currentValue.toString());
preparser->match(TokenTypes::identifier);
if (preparser->currentType != TokenTypes::closeParen)
preparser->match(TokenTypes::comma);
}
preparser->match(TokenTypes::closeParen);
ScopedPointer<InlineFunction::Object> o = new InlineFunction::Object(name, inlineArguments);
o->location = loc;
ns->inlineFunctions.add(o.release());
preparser->matchIf(TokenTypes::semicolon);
return nullptr;
}
else
{
if (getCurrentInlineFunction() != nullptr) throwError("No nested inline functions allowed.");
match(TokenTypes::function);
Identifier name = parseIdentifier();
match(TokenTypes::openParen);
while (currentType != TokenTypes::closeParen) skip();
match(TokenTypes::closeParen);
InlineFunction::Object::Ptr o;
for (int i = 0; i < ns->inlineFunctions.size(); i++)
{
if ((o = dynamic_cast<InlineFunction::Object*>(ns->inlineFunctions[i].get())))
{
if (o->name == name)
{
break;
}
}
}
currentInlineFunction = o;
if (o != nullptr)
{
o->commentDoc = lastComment;
clearLastComment();
ScopedPointer<BlockStatement> body = parseBlock();
o->body = body.release();
currentInlineFunction = nullptr;
matchIf(TokenTypes::semicolon);
return new Statement(location);
}
else
{
currentInlineFunction = nullptr;
location.throwError("Error at inline function parsing");
return nullptr;
}
}
}
Statement* parseJITModule()
{
match(TokenTypes::openParen);
String refFileName;
String fileContent = getFileContent(currentValue.toString(), refFileName);
match(TokenTypes::literal);
match(TokenTypes::closeParen);
match(TokenTypes::semicolon);
#if INCLUDE_NATIVE_JIT
ScopedPointer<NativeJITCompiler> compiler = new NativeJITCompiler(fileContent);
hiseSpecialData->jitModules.add(compiler.release());
#endif
return new Statement(location);
}
Statement* parseCaseStatement()
{
const bool isNotDefaultCase = currentType == TokenTypes::case_;
ScopedPointer<CaseStatement> s(new CaseStatement(location, isNotDefaultCase));
skip();
if (isNotDefaultCase) s->conditions.add(parseExpression());
match(TokenTypes::colon);
if (currentType == TokenTypes::openBrace)
{
s->body = parseBlock();
}
else if (currentType == TokenTypes::case_ || currentType == TokenTypes::default_ || currentType == TokenTypes::closeBrace)
{
// Empty statement (the condition will be added to the next case.
s->body = nullptr;
}
else
{
s->body = new BlockStatement(location);
while (currentType != TokenTypes::case_ && currentType != TokenTypes::closeBrace && currentType != TokenTypes::default_)
{
s->body->statements.add(parseStatement());
}
}
return s.release();
}
Statement* parseSwitchBlock()
{
ScopedPointer<SwitchStatement> s(new SwitchStatement(location));
match(TokenTypes::openParen);
s->condition = parseExpression();
match(TokenTypes::closeParen);
match(TokenTypes::openBrace);
OwnedArray<Expression> emptyCaseConditions;
while (currentType == TokenTypes::case_ || currentType == TokenTypes::default_)
{
ScopedPointer<CaseStatement> caseStatement = dynamic_cast<CaseStatement*>(parseCaseStatement());
if (caseStatement != nullptr)
{
if (caseStatement->body == nullptr)
{
for (auto& c : caseStatement->conditions)
{
emptyCaseConditions.add(c.release());
}
caseStatement->conditions.clear();
continue;
}
else
{
while (!emptyCaseConditions.isEmpty())
{
auto c = emptyCaseConditions.removeAndReturn(0);
caseStatement->conditions.add(c);
}
}
if (caseStatement->isNotDefault)
{
s->cases.add(caseStatement.release());
}
else
{
s->defaultCase = caseStatement.release();
}
}
}
match(TokenTypes::closeBrace);
return s.release();
}
Statement* parseForLoop()
{
match(TokenTypes::openParen);
const Identifier previousIteratorName = currentIterator;
const bool isVarInitialiser = matchIf(TokenTypes::var);
Expression *iter = parseExpression();
// Allow unqualified names in for loop initialisation for convenience
if (auto assignment = dynamic_cast<Assignment*>(iter))
{
if (auto un = dynamic_cast<UnqualifiedName*>(assignment->target.get()))
un->allowUnqualifiedDefinition = true;
}
if (!isVarInitialiser && currentType == TokenTypes::closeParen)
{
ScopedPointer<LoopStatement> s(new LoopStatement(location, false, true));
s->currentIterator = iter;
s->iterator = nullptr;
s->initialiser = nullptr;
s->condition = new LiteralValue(location, true);
match(TokenTypes::closeParen);
s->body = parseStatement();
currentIterator = previousIteratorName;
return s.release();
}
else
{
ScopedPointer<LoopStatement> s(new LoopStatement(location, false));
s->initialiser = matchEndOfStatement(iter);
if (matchIf(TokenTypes::semicolon))
s->condition = new LiteralValue(location, true);
else
{
s->condition = parseExpression();
match(TokenTypes::semicolon);
}
if (matchIf(TokenTypes::closeParen))
s->iterator = new Statement(location);
else
{
s->iterator = parseExpression();
match(TokenTypes::closeParen);
}
s->body = parseStatement();
return s.release();
}
}
Statement* parseDoOrWhileLoop(bool isDoLoop)
{
ScopedPointer<LoopStatement> s(new LoopStatement(location, isDoLoop));
s->initialiser = new Statement(location);
s->iterator = new Statement(location);
if (isDoLoop)
{
s->body = parseBlock();
match(TokenTypes::while_);
}
match(TokenTypes::openParen);
s->condition = parseExpression();
match(TokenTypes::closeParen);
if (!isDoLoop)
s->body = parseStatement();
return s.release();
}
Identifier parseIdentifier()
{
Identifier i;
if (currentType == TokenTypes::identifier)
i = currentValue.toString();
match(TokenTypes::identifier);
return i;
}
var parseFunctionDefinition(Identifier& functionName)
{
const String::CharPointerType functionStart(location.location);
if (currentType == TokenTypes::identifier)
functionName = parseIdentifier();
ScopedPointer<FunctionObject> fo(new FunctionObject());
parseFunctionParamsAndBody(*fo);
fo->functionCode = String(functionStart, location.location);
fo->createFunctionDefinition(functionName);
fo->commentDoc = lastComment;
clearLastComment();
return var(fo.release());
}
Expression* parseFunctionCall(FunctionCall* call, ExpPtr& function)
{
ScopedPointer<FunctionCall> s(call);
s->object = function;
match(TokenTypes::openParen);
while (currentType != TokenTypes::closeParen)
{
s->arguments.add(parseExpression());
if (currentType != TokenTypes::closeParen)
match(TokenTypes::comma);
}
return matchCloseParen(s.release());
}
Expression* parseApiExpression()
{
const Identifier apiId = parseIdentifier();
const int apiIndex = hiseSpecialData->apiIds.indexOf(apiId);
ApiClass *apiClass = hiseSpecialData->apiClasses.getUnchecked(apiIndex);
match(TokenTypes::dot);
const Identifier memberName = parseIdentifier();
int constantIndex = apiClass->getConstantIndex(memberName);
if (constantIndex != -1)
{
return parseApiConstant(apiClass, memberName);
}
else
{
return parseApiCall(apiClass, memberName);
}
}
Expression* parseApiConstant(ApiClass *apiClass, const Identifier &constantName)
{
const int index = apiClass->getConstantIndex(constantName);
const var value = apiClass->getConstantValue(index);
ScopedPointer<ApiConstant> s = new ApiConstant(location);
s->value = value;
return s.release();
}
Expression* parseApiCall(ApiClass *apiClass, const Identifier &functionName)
{
int functionIndex, numArgs;
apiClass->getIndexAndNumArgsForFunction(functionName, functionIndex, numArgs);
const String prettyName = apiClass->getObjectName() + "." + functionName.toString();
if (functionIndex < 0) throwError("Function / constant not found: " + prettyName); // Handle also missing constants here
ScopedPointer<ApiCall> s = new ApiCall(location, apiClass, numArgs, functionIndex);
match(TokenTypes::openParen);
int numActualArguments = 0;
while (currentType != TokenTypes::closeParen)
{
if (numActualArguments < numArgs)
{
s->argumentList[numActualArguments++] = parseExpression();
if (currentType != TokenTypes::closeParen)
match(TokenTypes::comma);
}
else throwError("Too many arguments in API call " + prettyName + "(). Expected: " + String(numArgs));
}
if (numArgs != numActualArguments) throwError("Call to " + prettyName + "(): argument number mismatch : " + String(numActualArguments) + " (Expected : " + String(numArgs) + ")");
return matchCloseParen(s.release());
}
Expression* parseConstExpression(JavascriptNamespace* ns=nullptr)
{
const Identifier constId = parseIdentifier();
const int index = getConstIndex(constId, ns);
#if 0
if (currentType == TokenTypes::dot)
{
match(TokenTypes::dot);
const Identifier memberName = parseIdentifier();
return parseConstObjectApiCall(constId, memberName, ns);
}
#endif
ns = (ns != nullptr) ? ns : hiseSpecialData;
return new ConstReference(location, ns, index);
}
Expression* parseConstObjectApiCall(const Identifier& objectName, const Identifier& functionName, JavascriptNamespace* ns=nullptr)
{
const String prettyName = objectName.toString() + "." + functionName.toString();
const int index = getConstIndex(objectName, ns);
var *v = getConstData(index, ns);
ScopedPointer<ConstObjectApiCall> s = new ConstObjectApiCall(location, v, functionName);
match(TokenTypes::openParen);
int numActualArguments = 0;
while (currentType != TokenTypes::closeParen)
{
s->argumentList[numActualArguments++] = parseExpression();
if (currentType != TokenTypes::closeParen)
match(TokenTypes::comma);
}
return matchCloseParen(s.release());
}
Expression* parseSuffixes(Expression* e)
{
ExpPtr input(e);
if (matchIf(TokenTypes::dot))
return parseSuffixes(new DotOperator(location, input, parseIdentifier()));
if (currentType == TokenTypes::openParen)
return parseSuffixes(parseFunctionCall(new FunctionCall(location), input));
if (matchIf(TokenTypes::openBracket))
{
ScopedPointer<ArraySubscript> s(new ArraySubscript(location));
s->object = input;
s->index = parseExpression();
match(TokenTypes::closeBracket);
return parseSuffixes(s.release());
}
if (matchIf(TokenTypes::plusplus)) return parsePostIncDec<AdditionOp>(input);
if (matchIf(TokenTypes::minusminus)) return parsePostIncDec<SubtractionOp>(input);
return input.release();
}
Expression* parseFactor(JavascriptNamespace* ns=nullptr)
{
if (currentType == TokenTypes::identifier)
{
Identifier id = Identifier(currentValue.toString());
// Allow direct referencing of namespaced variables within the namespace
if (getCurrentNamespace() != hiseSpecialData && ns == nullptr)
{
ns = getCurrentNamespace();
// Allow usage of namespace prefix within namespace
if (ns->id == id)
{
match(TokenTypes::identifier);
match(TokenTypes::dot);
id = currentValue.toString();
}
}
if (id == currentIterator)
{
return parseSuffixes(new LoopStatement::IteratorName(location, parseIdentifier()));
}
else if (currentInlineFunction != nullptr)
{
InlineFunction::Object* ob = dynamic_cast<InlineFunction::Object*>(currentInlineFunction);
const int inlineParameterIndex = ob->parameterNames.indexOf(id);
const int localParameterIndex = ob->localProperties.indexOf(id);
if (inlineParameterIndex >= 0)
{
parseIdentifier();
return parseSuffixes(new InlineFunction::ParameterReference(location, ob, inlineParameterIndex));
}
if (localParameterIndex >= 0)
{
parseIdentifier();
return parseSuffixes(new LocalReference(location, ob, id));
}
}
// Only resolve one level of namespaces
JavascriptNamespace* namespaceForId = hiseSpecialData->getNamespace(id);
if (namespaceForId != nullptr)
{
match(TokenTypes::identifier);
match(TokenTypes::dot);
return parseFactor(namespaceForId);
}
else
{
if (JavascriptNamespace* inlineNamespace = getNamespaceForStorageType(JavascriptNamespace::StorageType::InlineFunction, ns, id))
{
InlineFunction::Object *obj = getInlineFunction(id, inlineNamespace);
return parseSuffixes(parseInlineFunctionCall(obj));
}
else if (JavascriptNamespace* constNamespace = getNamespaceForStorageType(JavascriptNamespace::StorageType::ConstVariable, ns, id))
{
return parseSuffixes(parseConstExpression(constNamespace));
}
else if (JavascriptNamespace* regNamespace = getNamespaceForStorageType(JavascriptNamespace::StorageType::Register, ns, id))
{
VarRegister* rootRegister = ®Namespace->varRegister;
const int registerIndex = rootRegister->getRegisterIndex(id);
return parseSuffixes(new RegisterName(location, parseIdentifier(), rootRegister, registerIndex, getRegisterData(registerIndex, regNamespace)));
}
const int apiClassIndex = hiseSpecialData->apiIds.indexOf(id);
const int globalIndex = hiseSpecialData->globals != nullptr ? hiseSpecialData->globals->getProperties().indexOf(id) : -1;
if (apiClassIndex != -1)
{
return parseSuffixes(parseApiExpression());
}
#if INCLUDE_NATIVE_JIT
else if (auto compiler = hiseSpecialData->getNativeCompiler(id))
{
match(TokenTypes::dot);
match(TokenTypes::identifier);
match(TokenTypes::openParen);
match(TokenTypes::closeParen);
return new RootObject::NativeJIT::ScopeReference(location, compiler->compileAndReturnScope());
}
#endif
else if (globalIndex != -1)
{
return parseSuffixes(new GlobalReference(location, hiseSpecialData->globals, parseIdentifier()));
}
else
{
if (!currentlyParsedCallback.isNull())
{
Callback *c = hiseSpecialData->getCallback(currentlyParsedCallback);
if (c != nullptr)
{
var* callbackParameter = c->getVarPointer(id);
if (callbackParameter != nullptr)
{
parseIdentifier();
return parseSuffixes(new CallbackParameterReference(location, callbackParameter));
}
var* localParameter = c->localProperties.getVarPointer(id);
if (localParameter != nullptr)
{
auto name = parseIdentifier();
return parseSuffixes(new CallbackLocalReference(location, c, name));
}
}
else
{
jassertfalse;
}
}
return parseSuffixes(new UnqualifiedName(location, parseIdentifier(), false));
}
}
}
if (matchIf(TokenTypes::openParen)) return parseSuffixes(matchCloseParen(parseExpression()));
if (matchIf(TokenTypes::true_)) return parseSuffixes(new LiteralValue(location, (int)1));
if (matchIf(TokenTypes::false_)) return parseSuffixes(new LiteralValue(location, (int)0));
if (matchIf(TokenTypes::null_)) return parseSuffixes(new LiteralValue(location, var()));
if (matchIf(TokenTypes::undefined)) return parseSuffixes(new Expression(location));
if (currentType == TokenTypes::literal)
{
var v(currentValue); skip();
return parseSuffixes(new LiteralValue(location, v));
}
if (matchIf(TokenTypes::openBrace))
{
ScopedPointer<ObjectDeclaration> e(new ObjectDeclaration(location));
while (currentType != TokenTypes::closeBrace)
{
e->names.add(currentValue.toString());
match((currentType == TokenTypes::literal && currentValue.isString())
? TokenTypes::literal : TokenTypes::identifier);
match(TokenTypes::colon);
e->initialisers.add(parseExpression());
if (currentType != TokenTypes::closeBrace)
match(TokenTypes::comma);
}
match(TokenTypes::closeBrace);
return parseSuffixes(e.release());
}
if (matchIf(TokenTypes::openBracket))
{
ScopedPointer<ArrayDeclaration> e(new ArrayDeclaration(location));
while (currentType != TokenTypes::closeBracket)
{
e->values.add(parseExpression());
if (currentType != TokenTypes::closeBracket)
match(TokenTypes::comma);
}
match(TokenTypes::closeBracket);
return parseSuffixes(e.release());
}
if (matchIf(TokenTypes::function))
{
Identifier name;
var fn = parseFunctionDefinition(name);
if (name.isValid())
throwError("Inline functions definitions cannot have a name");
return new LiteralValue(location, fn);
}
if (matchIf(TokenTypes::new_))
{
return parseNewOperator();
}
if (matchIf(TokenTypes::isDefined_))
{
return parseIsDefined();
}
throwError("Found " + getTokenName(currentType) + " when expecting an expression");
RETURN_IF_NO_THROW(nullptr);
}
template <typename OpType>
Expression* parsePreIncDec()
{
Expression* e = parseFactor(); // careful - bare pointer is deliberately alised
ExpPtr lhs(e), one(new LiteralValue(location, (int)1));
return new SelfAssignment(location, e, new OpType(location, lhs, one));
}
template <typename OpType>
Expression* parsePostIncDec(ExpPtr& lhs)
{
Expression* e = lhs.release(); // careful - bare pointer is deliberately alised
ExpPtr lhs2(e), one(new LiteralValue(location, (int)1));
return new PostAssignment(location, e, new OpType(location, lhs2, one));
}
Expression* parseTypeof()
{
ScopedPointer<FunctionCall> f(new FunctionCall(location));
f->object = new UnqualifiedName(location, "typeof", true);
f->arguments.add(parseUnary());
return f.release();
}
Expression* parseUnary()
{
if (matchIf(TokenTypes::minus)) { ExpPtr a(new LiteralValue(location, (int)0)), b(parseUnary()); return new SubtractionOp(location, a, b); }
if (matchIf(TokenTypes::logicalNot)) { ExpPtr a(new LiteralValue(location, (int)0)), b(parseUnary()); return new EqualsOp(location, a, b); }
if (matchIf(TokenTypes::plusplus)) return parsePreIncDec<AdditionOp>();
if (matchIf(TokenTypes::minusminus)) return parsePreIncDec<SubtractionOp>();
if (matchIf(TokenTypes::typeof_)) return parseTypeof();
return parseFactor();
}
Expression* parseNewOperator()
{
location.throwError("new is not supported anymore");
return nullptr;
}
Expression* parseIsDefined()
{
match(TokenTypes::openParen);
ExpPtr a(parseExpression());
match(TokenTypes::closeParen);
return new IsDefinedTest(location, a.release());
}
Expression* parseMultiplyDivide()
{
ExpPtr a(parseUnary());
for (;;)
{
if (matchIf(TokenTypes::times)) { ExpPtr b(parseUnary()); a = new MultiplyOp(location, a, b); }
else if (matchIf(TokenTypes::divide)) { ExpPtr b(parseUnary()); a = new DivideOp(location, a, b); }
else if (matchIf(TokenTypes::modulo)) { ExpPtr b(parseUnary()); a = new ModuloOp(location, a, b); }
else break;
}
return a.release();
}
Expression* parseAdditionSubtraction()
{
ExpPtr a(parseMultiplyDivide());
for (;;)
{
if (matchIf(TokenTypes::plus)) { ExpPtr b(parseMultiplyDivide()); a = new AdditionOp(location, a, b); }
else if (matchIf(TokenTypes::minus)) { ExpPtr b(parseMultiplyDivide()); a = new SubtractionOp(location, a, b); }
else break;
}
return a.release();
}
Expression* parseShiftOperator()
{
ExpPtr a(parseAdditionSubtraction());
for (;;)
{
if (matchIf(TokenTypes::leftShift)) { ExpPtr b(parseExpression()); a = new LeftShiftOp(location, a, b); }
else if (matchIf(TokenTypes::rightShift)) { ExpPtr b(parseExpression()); a = new RightShiftOp(location, a, b); }
else if (matchIf(TokenTypes::rightShiftUnsigned)) { ExpPtr b(parseExpression()); a = new RightShiftUnsignedOp(location, a, b); }
else break;
}
return a.release();
}
Expression* parseComparator()
{
ExpPtr a(parseShiftOperator());
for (;;)
{
if (matchIf(TokenTypes::equals)) { ExpPtr b(parseShiftOperator()); a = new EqualsOp(location, a, b); }
else if (matchIf(TokenTypes::notEquals)) { ExpPtr b(parseShiftOperator()); a = new NotEqualsOp(location, a, b); }
else if (matchIf(TokenTypes::typeEquals)) { ExpPtr b(parseShiftOperator()); a = new TypeEqualsOp(location, a, b); }
else if (matchIf(TokenTypes::typeNotEquals)) { ExpPtr b(parseShiftOperator()); a = new TypeNotEqualsOp(location, a, b); }
else if (matchIf(TokenTypes::lessThan)) { ExpPtr b(parseShiftOperator()); a = new LessThanOp(location, a, b); }
else if (matchIf(TokenTypes::lessThanOrEqual)) { ExpPtr b(parseShiftOperator()); a = new LessThanOrEqualOp(location, a, b); }
else if (matchIf(TokenTypes::greaterThan)) { ExpPtr b(parseShiftOperator()); a = new GreaterThanOp(location, a, b); }
else if (matchIf(TokenTypes::greaterThanOrEqual)) { ExpPtr b(parseShiftOperator()); a = new GreaterThanOrEqualOp(location, a, b); }
else break;
}
return a.release();
}
Expression* parseLogicOperator()
{
ExpPtr a(parseComparator());
for (;;)
{
if (matchIf(TokenTypes::logicalAnd)) { ExpPtr b(parseComparator()); a = new LogicalAndOp(location, a, b); }
else if (matchIf(TokenTypes::logicalOr)) { ExpPtr b(parseComparator()); a = new LogicalOrOp(location, a, b); }
else if (matchIf(TokenTypes::bitwiseAnd)) { ExpPtr b(parseComparator()); a = new BitwiseAndOp(location, a, b); }
else if (matchIf(TokenTypes::bitwiseOr)) { ExpPtr b(parseComparator()); a = new BitwiseOrOp(location, a, b); }
else if (matchIf(TokenTypes::bitwiseXor)) { ExpPtr b(parseComparator()); a = new BitwiseXorOp(location, a, b); }
else break;
}
return a.release();
}
Expression* parseTerneryOperator(ExpPtr& condition)
{
ScopedPointer<ConditionalOp> e(new ConditionalOp(location));
e->condition = condition;
e->trueBranch = parseExpression();
match(TokenTypes::colon);
e->falseBranch = parseExpression();
return e.release();
}
Array<Identifier> registerIdentifiers;
Identifier currentIterator;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ExpressionTreeBuilder)
};
void HiseJavascriptEngine::RootObject::ExpressionTreeBuilder::preprocessCode(const String& codeToPreprocess, const String& externalFileName)
{
if (codeToPreprocess.isEmpty()) return;
static const var undeclared("undeclared");
JavascriptNamespace* rootNamespace = hiseSpecialData;
JavascriptNamespace* cns = rootNamespace;
TokenIterator it(codeToPreprocess, externalFileName);
int braceLevel = 0;
while (it.currentType != TokenTypes::eof)
{
if (it.currentType == TokenTypes::namespace_)
{
if (cns != rootNamespace)
{
it.location.throwError("Nesting of namespaces is not allowed");
}
it.match(TokenTypes::namespace_);
Identifier namespaceId = Identifier(it.currentValue);
if (hiseSpecialData->getNamespace(namespaceId) == nullptr)
{
ScopedPointer<JavascriptNamespace> newNamespace = new JavascriptNamespace(namespaceId);
newNamespace->namespaceLocation = it.createDebugLocation();
cns = newNamespace;
hiseSpecialData->namespaces.add(newNamespace.release());
continue;
}
else
{
it.location.throwError("Duplicate namespace " + namespaceId.toString());
}
}
// Skip extern "C" functions
if (it.currentType == TokenTypes::extern_)
{
while (!(it.currentType == TokenTypes::closeBrace && braceLevel == 1) &&
!(it.currentType == TokenTypes::eof))
{
if (it.currentType == TokenTypes::openBrace) braceLevel++;
else if (it.currentType == TokenTypes::closeBrace) braceLevel--;
it.skip();
}
}
// Search in included files
if (it.currentType == TokenTypes::include_)
{
it.match(TokenTypes::include_);
it.match(TokenTypes::openParen);
String fileName = it.currentValue.toString();
String externalCode = getFileContent(it.currentValue.toString(), fileName);
preprocessCode(externalCode, fileName);
continue;
}
// Handle the brace level
if (it.matchIf(TokenTypes::openBrace))
{
braceLevel++;
continue;
}
else if (it.matchIf(TokenTypes::closeBrace))
{
braceLevel--;
if (braceLevel == 0 && (rootNamespace != cns))
{
cns = rootNamespace;
}
continue;
}
if (it.matchIf(TokenTypes::inline_))
{
parseInlineFunction(cns, &it);
continue;
}
if (it.matchIf(TokenTypes::register_var))
{
parseRegisterVar(cns, &it);
continue;
}
// Handle the keyword
if (it.currentType == TokenTypes::const_)
{
it.match(TokenTypes::const_);
it.matchIf(TokenTypes::var);
const Identifier newId(it.currentValue);
if ((rootNamespace == cns) && braceLevel != 0) it.location.throwError("const var declaration must be on global level");
if (newId.isNull()) it.location.throwError("Expected identifier for const var declaration");
if (cns->constObjects.contains(newId)) it.location.throwError("Duplicate const var declaration.");
cns->constObjects.set(newId, undeclared);
cns->constLocations.add(it.createDebugLocation());
continue;
}
else
{
it.skip();
}
}
if (rootNamespace != cns)
{
it.location.throwError("Parsing error (open namespace)");
}
if (cns->constObjects.size() != cns->constLocations.size())
{
jassertfalse;
}
}
String HiseJavascriptEngine::RootObject::ExpressionTreeBuilder::removeUnneededNamespaces(int& counter)
{
StringArray namespaces;
while (currentType != TokenTypes::eof)
{
if (currentType != TokenTypes::namespace_) skip();
else
{
auto start = location.location;
match(TokenTypes::namespace_);
match(TokenTypes::identifier);
skipBlock();
matchIf(TokenTypes::semicolon);
auto end = location.location;
namespaces.add(String(start, end));
}
}
String returnCode = location.program;
for (int i = namespaces.size() - 1; i >= 0; i--)
{
const String namespaceId = RegexFunctions::getFirstMatch("namespace\\s+(\\w+)", namespaces[i])[1];
const String remainingCode = returnCode.fromFirstOccurrenceOf(namespaces[i], false, false);
TokenIterator it(remainingCode, "");
bool found = false;
while (it.currentType != TokenTypes::eof)
{
if (it.currentType == TokenTypes::identifier && it.currentValue == namespaceId)
{
found = true;
break;
}
it.skip();
}
if (!found)
{
returnCode = returnCode.replace(namespaces[i], "");
counter++;
}
}
return returnCode;
}
String HiseJavascriptEngine::RootObject::ExpressionTreeBuilder::uglify()
{
String uglyCode;
int tokenCounter = 0;
while (currentType != TokenTypes::eof)
{
if (currentType == TokenTypes::in) uglyCode << ' '; // the only keyword that needs a leading space...
if (currentType == TokenTypes::identifier)
{
uglyCode << currentValue.toString();
}
else if (currentType == TokenTypes::literal)
{
if (currentValue.isString())
{
uglyCode << "\"" << currentValue.toString().replace("\n", "\\n") << "\"";
}
else
{
uglyCode << currentValue.toString();
}
}
else
{
uglyCode << currentType;
}
if (currentType == TokenTypes::namespace_ ||
currentType == TokenTypes::function ||
currentType == TokenTypes::const_ ||
currentType == TokenTypes::extern_ ||
currentType == TokenTypes::case_ ||
currentType == TokenTypes::const_ ||
currentType == TokenTypes::local_ ||
currentType == TokenTypes::var ||
currentType == TokenTypes::in ||
currentType == TokenTypes::inline_ ||
currentType == TokenTypes::return_ ||
currentType == TokenTypes::typeof_ ||
currentType == TokenTypes::register_var ||
currentType == TokenTypes::new_ ||
currentType == TokenTypes::else_ ||
currentType == TokenTypes::global_)
{
uglyCode << ' ';
}
tokenCounter++;
if (tokenCounter % 256 == 0) uglyCode << NewLine::getDefault(); // one single line is too slow for the code editor...
skip();
}
return uglyCode;
}
var HiseJavascriptEngine::RootObject::evaluate(const String& code)
{
ExpressionTreeBuilder tb(code, String());
tb.setupApiData(hiseSpecialData, code);
return ExpPtr(tb.parseExpression())->getResult(Scope(nullptr, this, this));
}
void HiseJavascriptEngine::RootObject::execute(const String& code, bool allowConstDeclarations)
{
ExpressionTreeBuilder tb(code, String());
#if ENABLE_SCRIPTING_BREAKPOINTS
tb.breakpoints.swapWith(breakpoints);
#endif
tb.setupApiData(hiseSpecialData, allowConstDeclarations ? code : String());
auto sl = ScopedPointer<BlockStatement>(tb.parseStatementList());
if(shouldUseCycleCheck)
prepareCycleReferenceCheck();
sl->perform(Scope(nullptr, this, this), nullptr);
}
HiseJavascriptEngine::RootObject::FunctionObject::FunctionObject(const FunctionObject& other) : DynamicObject(), functionCode(other.functionCode)
{
ExpressionTreeBuilder tb(functionCode, String());
tb.parseFunctionParamsAndBody(*this);
}
} // namespace hise | 26.887457 | 180 | 0.691376 | romsom |
f682e90f25224d5ee7a4f1ab61aa3e861d85b5d4 | 1,938 | cpp | C++ | GenericCallback/main.cpp | CrystaLamb/TryMePlease | 1e33b9fc0ce9af688db409a682f5227aea0a63cb | [
"Apache-2.0"
] | null | null | null | GenericCallback/main.cpp | CrystaLamb/TryMePlease | 1e33b9fc0ce9af688db409a682f5227aea0a63cb | [
"Apache-2.0"
] | null | null | null | GenericCallback/main.cpp | CrystaLamb/TryMePlease | 1e33b9fc0ce9af688db409a682f5227aea0a63cb | [
"Apache-2.0"
] | null | null | null | #include <utility>
#include <iostream>
#include <tuple>
#include <functional>
template <typename N>
void print(N v)
{
std::cout << v << std::endl;
}
template <typename N, typename... Ns>
void print(N v, Ns... vs)
{
std::cout << v << ", ";
print(vs...);
}
template <size_t... I>
void print(std::index_sequence<I...>)
{
print(I...);
}
template <typename Func, typename Tuple, size_t... I>
auto callback(Func&& func, Tuple t, std::index_sequence<I...>)
{
return func(std::get<I>(t)...);
}
template <typename Func, typename Tuple>
auto callback(Func&& func, Tuple t)
{
return callback(std::forward<Func>(func), t, std::make_index_sequence<std::tuple_size_v<Tuple>>{});
}
template <typename Func, typename... Args>
auto callback(Func&& func, Args... args)
{
return callback(std::forward<Func>(func), std::make_tuple(args...));
}
class TestClass
{
public:
typedef std::function<int(int, int)> add_func_t;
void Test()
{
auto generic_lambda = [this](auto&&... args) -> decltype(auto)
{
return this->TestClass::Hello(std::forward<decltype(args)>(args)...);
};
CatchAddFunc(generic_lambda);
}
void CatchAddFunc(add_func_t&& func)
{
std::cout << "Catch func!\n";
}
private:
int Hello(int a, int b)
{
std::cout << a << " + " << b << " = " << a + b << "\n";
return a + b;
}
};
int main()
{
print(std::make_index_sequence<10>{});
print(std::make_index_sequence<6>{});
auto lambda = [](int a, double b) -> int
{
std::cout << a << ": " << b;
return 5;
};
auto lambda1 = [](int a, int b, int c) -> void
{
std::cout << a << " " << b << " " << c << "\nsum: " << a + b + c << std::endl;
};
std::cout << " return: " << callback(lambda, 2, 6.55) << "\n";
std::cout << " return: " << callback(lambda, 8, 8454.55) << "\n";
std::cout << " return: " << callback(lambda, 999, 5424.55) << "\n";
callback(lambda1, 8, 9, 5);
callback(lambda1, 84, 91, 52);
TestClass testClass;
testClass.Test();
} | 20.83871 | 100 | 0.594943 | CrystaLamb |
f68382963d477ecc147391172465bdcd0f29f57f | 3,401 | cpp | C++ | third_party/WebKit/Source/platform/v8_inspector/V8ConsoleAgentImpl.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | third_party/WebKit/Source/platform/v8_inspector/V8ConsoleAgentImpl.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/v8_inspector/V8ConsoleAgentImpl.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "platform/v8_inspector/V8ConsoleAgentImpl.h"
#include "platform/v8_inspector/V8ConsoleMessage.h"
#include "platform/v8_inspector/V8DebuggerImpl.h"
#include "platform/v8_inspector/V8InspectorSessionImpl.h"
#include "platform/v8_inspector/V8StackTraceImpl.h"
namespace blink {
namespace ConsoleAgentState {
static const char consoleEnabled[] = "consoleEnabled";
}
V8ConsoleAgentImpl::V8ConsoleAgentImpl(V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel, protocol::DictionaryValue* state)
: m_session(session)
, m_state(state)
, m_frontend(frontendChannel)
, m_enabled(false)
{
}
V8ConsoleAgentImpl::~V8ConsoleAgentImpl()
{
}
void V8ConsoleAgentImpl::enable(ErrorString* errorString)
{
if (m_enabled)
return;
m_state->setBoolean(ConsoleAgentState::consoleEnabled, true);
m_enabled = true;
m_session->debugger()->enableStackCapturingIfNeeded();
reportAllMessages();
m_session->client()->consoleEnabled();
}
void V8ConsoleAgentImpl::disable(ErrorString* errorString)
{
if (!m_enabled)
return;
m_session->debugger()->disableStackCapturingIfNeeded();
m_state->setBoolean(ConsoleAgentState::consoleEnabled, false);
m_enabled = false;
}
void V8ConsoleAgentImpl::clearMessages(ErrorString* errorString)
{
m_session->debugger()->ensureConsoleMessageStorage(m_session->contextGroupId())->clear();
}
void V8ConsoleAgentImpl::restore()
{
if (!m_state->booleanProperty(ConsoleAgentState::consoleEnabled, false))
return;
m_frontend.messagesCleared();
ErrorString ignored;
enable(&ignored);
}
void V8ConsoleAgentImpl::messageAdded(V8ConsoleMessage* message)
{
if (m_enabled)
reportMessage(message, true);
}
void V8ConsoleAgentImpl::reset()
{
if (m_enabled)
m_frontend.messagesCleared();
}
bool V8ConsoleAgentImpl::enabled()
{
return m_enabled;
}
void V8ConsoleAgentImpl::reportAllMessages()
{
V8ConsoleMessageStorage* storage = m_session->debugger()->ensureConsoleMessageStorage(m_session->contextGroupId());
if (storage->expiredCount()) {
std::unique_ptr<protocol::Console::ConsoleMessage> expired = protocol::Console::ConsoleMessage::create()
.setSource(protocol::Console::ConsoleMessage::SourceEnum::Other)
.setLevel(protocol::Console::ConsoleMessage::LevelEnum::Warning)
.setText(String16::number(storage->expiredCount()) + String16("console messages are not shown."))
.setTimestamp(0)
.build();
expired->setType(protocol::Console::ConsoleMessage::TypeEnum::Log);
expired->setLine(0);
expired->setColumn(0);
expired->setUrl("");
m_frontend.messageAdded(std::move(expired));
m_frontend.flush();
}
for (const auto& message : storage->messages()) {
if (!reportMessage(message.get(), false))
return;
}
}
bool V8ConsoleAgentImpl::reportMessage(V8ConsoleMessage* message, bool generatePreview)
{
m_frontend.messageAdded(message->buildInspectorObject(m_session, generatePreview));
m_frontend.flush();
return m_session->debugger()->hasConsoleMessageStorage(m_session->contextGroupId());
}
} // namespace blink
| 30.366071 | 149 | 0.723023 | Wzzzx |
f6853d3937aa8308c67f3a3a8936c6f32d9e4b9d | 486 | cpp | C++ | 1099.cpp | fenatan/URI-Online-Judge | 983cadd364e658cdebcbc2c0165e8f54e023a823 | [
"MIT"
] | null | null | null | 1099.cpp | fenatan/URI-Online-Judge | 983cadd364e658cdebcbc2c0165e8f54e023a823 | [
"MIT"
] | null | null | null | 1099.cpp | fenatan/URI-Online-Judge | 983cadd364e658cdebcbc2c0165e8f54e023a823 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main(){
int v[10001], n,x,y, maior, menor;
scanf("%d", &n);
for(int i =0; i < n; i++){
scanf("%d %d", &x, &y);
if(x > y){
maior = x; menor = y;
}else{
maior = y; menor = x;
}
v[i]=0;
for(int j = menor + 1; j < maior; j++){
if(j % 2 != 0)
v[i]+=j;
}
}
for(int i =0; i < n; i++){
printf("%d\n", v[i]);
}
return 0;
}
| 18 | 47 | 0.329218 | fenatan |
f686b9e9914f26a76f24616010336866acebd753 | 2,342 | cpp | C++ | nuiengine/core/views/KButtonView.cpp | 15d23/NUIEngine | a1369d5cea90cca81d74a39b8a853b3fba850595 | [
"Apache-2.0"
] | 204 | 2017-05-08T05:41:29.000Z | 2022-03-29T16:57:44.000Z | nuiengine/core/views/KButtonView.cpp | 15d23/NUIEngine | a1369d5cea90cca81d74a39b8a853b3fba850595 | [
"Apache-2.0"
] | 7 | 2017-05-10T15:32:09.000Z | 2020-12-23T06:00:30.000Z | nuiengine/core/views/KButtonView.cpp | 15d23/NUIEngine | a1369d5cea90cca81d74a39b8a853b3fba850595 | [
"Apache-2.0"
] | 65 | 2017-05-25T05:46:56.000Z | 2021-02-06T11:07:38.000Z | // **************************************
// File: KButtonView.cpp
// Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved.
// Website: http://www.nuiengine.com
// Description: This code is part of NUI Engine (NUI Graphics Lib)
// Comments:
// Rev: 2
// Created: 2017/4/11
// Last edit: 2017/4/28
// Author: Chen Zhi
// E-mail: cz_666@qq.com
// License: APACHE V2.0 (see license file)
// ***************************************
#include "KButtonView.h"
#include "DataSync.h"
#include "KShapeDrawable.h"
/////////////////// KImgButtonView //////////////////////////
KImgButtonView::KImgButtonView()
{
m_e_viewtype = KVIEW_BUTTON;
m_b_check_alpha = FALSE;
}
KImgButtonView::~KImgButtonView()
{
}
void KImgButtonView::setState( ViewState state, kn_bool bRefresh )
{
//调用基类函数设置文本状态,传入False不激活刷新
if (m_state != state)
{
//m_state = state;
writeLock lock(m_lst_drawable_mutex);
switch(state)
{
case BS_FOCUS:
m_lst_drawable[0] = m_focus_bk_drawable;
break;
case BS_NORMAL:
m_lst_drawable[0] = m_bk_drawable;
break;
case BS_PRESSED:
case BS_ACTIVE:
m_lst_drawable[0] = m_selected_bk_drawable;
break;
case BS_DISABLED:
m_lst_drawable[0] = m_disable_bk_drawable;
break;
default:
break;
}
lock.unlock();
KTextView::setState(state, FALSE);
if (bRefresh)
{
InvalidateView();
}
}
}
void KImgButtonView::setBKGImage(const kn_string& normalResPath,
const kn_string& focusResPath,
const kn_string& selectedResPath,
const kn_string& disabledResPath)
{
KDrawable_PTR normal = KImageDrawable_PTR(new KImageDrawable(normalResPath));
KDrawable_PTR focus = KImageDrawable_PTR(new KImageDrawable(focusResPath));
KDrawable_PTR selected = KImageDrawable_PTR(new KImageDrawable(selectedResPath));
KDrawable_PTR disable = KImageDrawable_PTR(new KImageDrawable(disabledResPath));
setBKG(normal,focus,selected,disable);
}
void KImgButtonView::setBKG( KDrawable_PTR normal, KDrawable_PTR focus, KDrawable_PTR selected, KDrawable_PTR disabled)
{
writeLock lock(m_lst_drawable_mutex);
m_bk_drawable = normal;
m_focus_bk_drawable = focus;
m_selected_bk_drawable = selected;
m_disable_bk_drawable = disabled;
m_lst_drawable[0] = m_bk_drawable;
//不要忘了释放锁
lock.unlock();
showBK(TRUE);
}
| 24.395833 | 120 | 0.690436 | 15d23 |
f687699bf50cf7e2cc158cec90e596168fc497a0 | 14,569 | cc | C++ | net/url_request/url_request_context_builder.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-02-03T05:32:07.000Z | 2019-02-03T05:32:07.000Z | net/url_request/url_request_context_builder.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | net/url_request/url_request_context_builder.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:19:17.000Z | 2020-11-04T07:19:17.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/url_request/url_request_context_builder.h"
#include <string>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread.h"
#include "net/base/cache_type.h"
#include "net/base/net_errors.h"
#include "net/base/network_delegate.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/host_resolver.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_layer.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties_impl.h"
#include "net/http/transport_security_persister.h"
#include "net/http/transport_security_state.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_throttler_manager.h"
#if !defined(DISABLE_FILE_SUPPORT)
#include "net/url_request/file_protocol_handler.h"
#endif
#if !defined(DISABLE_FTP_SUPPORT)
#include "net/url_request/ftp_protocol_handler.h"
#endif
namespace net {
namespace {
class BasicNetworkDelegate : public NetworkDelegate {
public:
BasicNetworkDelegate() {}
virtual ~BasicNetworkDelegate() {}
private:
virtual int OnBeforeURLRequest(URLRequest* request,
const CompletionCallback& callback,
GURL* new_url) OVERRIDE {
return OK;
}
virtual int OnBeforeSendHeaders(URLRequest* request,
const CompletionCallback& callback,
HttpRequestHeaders* headers) OVERRIDE {
return OK;
}
virtual void OnSendHeaders(URLRequest* request,
const HttpRequestHeaders& headers) OVERRIDE {}
virtual int OnHeadersReceived(
URLRequest* request,
const CompletionCallback& callback,
const HttpResponseHeaders* original_response_headers,
scoped_refptr<HttpResponseHeaders>* override_response_headers,
GURL* allowed_unsafe_redirect_url) OVERRIDE {
return OK;
}
virtual void OnBeforeRedirect(URLRequest* request,
const GURL& new_location) OVERRIDE {}
virtual void OnResponseStarted(URLRequest* request) OVERRIDE {}
virtual void OnRawBytesRead(const URLRequest& request,
int bytes_read) OVERRIDE {}
virtual void OnCompleted(URLRequest* request, bool started) OVERRIDE {}
virtual void OnURLRequestDestroyed(URLRequest* request) OVERRIDE {}
virtual void OnPACScriptError(int line_number,
const base::string16& error) OVERRIDE {}
virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
URLRequest* request,
const AuthChallengeInfo& auth_info,
const AuthCallback& callback,
AuthCredentials* credentials) OVERRIDE {
return NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
}
virtual bool OnCanGetCookies(const URLRequest& request,
const CookieList& cookie_list) OVERRIDE {
return true;
}
virtual bool OnCanSetCookie(const URLRequest& request,
const std::string& cookie_line,
CookieOptions* options) OVERRIDE {
return true;
}
virtual bool OnCanAccessFile(const net::URLRequest& request,
const base::FilePath& path) const OVERRIDE {
return true;
}
virtual bool OnCanThrottleRequest(const URLRequest& request) const OVERRIDE {
// Returning true will only enable throttling if there's also a
// URLRequestThrottlerManager, which there isn't, by default.
return true;
}
virtual int OnBeforeSocketStreamConnect(
SocketStream* stream,
const CompletionCallback& callback) OVERRIDE {
return OK;
}
DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate);
};
class BasicURLRequestContext : public URLRequestContext {
public:
BasicURLRequestContext()
: storage_(this) {}
URLRequestContextStorage* storage() {
return &storage_;
}
base::Thread* GetCacheThread() {
if (!cache_thread_) {
cache_thread_.reset(new base::Thread("Network Cache Thread"));
cache_thread_->StartWithOptions(
base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
}
return cache_thread_.get();
}
base::Thread* GetFileThread() {
if (!file_thread_) {
file_thread_.reset(new base::Thread("Network File Thread"));
file_thread_->StartWithOptions(
base::Thread::Options(base::MessageLoop::TYPE_DEFAULT, 0));
}
return file_thread_.get();
}
void set_transport_security_persister(
scoped_ptr<TransportSecurityPersister> transport_security_persister) {
transport_security_persister = transport_security_persister.Pass();
}
protected:
virtual ~BasicURLRequestContext() {
AssertNoURLRequests();
}
private:
// Threads should be torn down last.
scoped_ptr<base::Thread> cache_thread_;
scoped_ptr<base::Thread> file_thread_;
URLRequestContextStorage storage_;
scoped_ptr<TransportSecurityPersister> transport_security_persister_;
DISALLOW_COPY_AND_ASSIGN(BasicURLRequestContext);
};
} // namespace
URLRequestContextBuilder::HttpCacheParams::HttpCacheParams()
: type(IN_MEMORY),
max_size(0) {}
URLRequestContextBuilder::HttpCacheParams::~HttpCacheParams() {}
URLRequestContextBuilder::HttpNetworkSessionParams::HttpNetworkSessionParams()
: ignore_certificate_errors(false),
host_mapping_rules(NULL),
testing_fixed_http_port(0),
testing_fixed_https_port(0),
next_protos(NextProtosDefaults()),
use_alternate_protocols(true),
enable_quic(false) {
}
URLRequestContextBuilder::HttpNetworkSessionParams::~HttpNetworkSessionParams()
{}
URLRequestContextBuilder::SchemeFactory::SchemeFactory(
const std::string& auth_scheme,
net::HttpAuthHandlerFactory* auth_handler_factory)
: scheme(auth_scheme), factory(auth_handler_factory) {
}
URLRequestContextBuilder::SchemeFactory::~SchemeFactory() {
}
URLRequestContextBuilder::URLRequestContextBuilder()
: data_enabled_(false),
#if !defined(DISABLE_FILE_SUPPORT)
file_enabled_(false),
#endif
#if !defined(DISABLE_FTP_SUPPORT)
ftp_enabled_(false),
#endif
http_cache_enabled_(true),
throttling_enabled_(false),
channel_id_enabled_(true) {
}
URLRequestContextBuilder::~URLRequestContextBuilder() {}
void URLRequestContextBuilder::EnableHttpCache(const HttpCacheParams& params) {
http_cache_enabled_ = true;
http_cache_params_ = params;
}
void URLRequestContextBuilder::DisableHttpCache() {
http_cache_enabled_ = false;
http_cache_params_ = HttpCacheParams();
}
void URLRequestContextBuilder::SetSpdyAndQuicEnabled(bool spdy_enabled,
bool quic_enabled) {
http_network_session_params_.next_protos =
NextProtosWithSpdyAndQuic(spdy_enabled, quic_enabled);
http_network_session_params_.enable_quic = quic_enabled;
}
URLRequestContext* URLRequestContextBuilder::Build() {
BasicURLRequestContext* context = new BasicURLRequestContext;
URLRequestContextStorage* storage = context->storage();
storage->set_http_user_agent_settings(new StaticHttpUserAgentSettings(
accept_language_, user_agent_));
if (!network_delegate_)
network_delegate_.reset(new BasicNetworkDelegate);
NetworkDelegate* network_delegate = network_delegate_.release();
storage->set_network_delegate(network_delegate);
if (net_log_) {
storage->set_net_log(net_log_.release());
} else {
storage->set_net_log(new net::NetLog);
}
if (!host_resolver_) {
host_resolver_ = net::HostResolver::CreateDefaultResolver(
context->net_log());
}
storage->set_host_resolver(host_resolver_.Pass());
if (!proxy_service_) {
// TODO(willchan): Switch to using this code when
// ProxyService::CreateSystemProxyConfigService()'s signature doesn't suck.
#if defined(OS_LINUX) || defined(OS_ANDROID)
ProxyConfigService* proxy_config_service = proxy_config_service_.release();
#else
ProxyConfigService* proxy_config_service = NULL;
if (proxy_config_service_) {
proxy_config_service = proxy_config_service_.release();
} else {
proxy_config_service =
ProxyService::CreateSystemProxyConfigService(
base::ThreadTaskRunnerHandle::Get().get(),
context->GetFileThread()->task_runner());
}
#endif // defined(OS_LINUX) || defined(OS_ANDROID)
proxy_service_.reset(
ProxyService::CreateUsingSystemProxyResolver(
proxy_config_service,
0, // This results in using the default value.
context->net_log()));
}
storage->set_proxy_service(proxy_service_.release());
storage->set_ssl_config_service(new net::SSLConfigServiceDefaults);
HttpAuthHandlerRegistryFactory* http_auth_handler_registry_factory =
net::HttpAuthHandlerRegistryFactory::CreateDefault(
context->host_resolver());
for (size_t i = 0; i < extra_http_auth_handlers_.size(); ++i) {
http_auth_handler_registry_factory->RegisterSchemeFactory(
extra_http_auth_handlers_[i].scheme,
extra_http_auth_handlers_[i].factory);
}
storage->set_http_auth_handler_factory(http_auth_handler_registry_factory);
storage->set_cookie_store(new CookieMonster(NULL, NULL));
if (channel_id_enabled_) {
// TODO(mmenke): This always creates a file thread, even when it ends up
// not being used. Consider lazily creating the thread.
storage->set_channel_id_service(
new ChannelIDService(
new DefaultChannelIDStore(NULL),
context->GetFileThread()->message_loop_proxy()));
}
storage->set_transport_security_state(new net::TransportSecurityState());
if (!transport_security_persister_path_.empty()) {
context->set_transport_security_persister(
make_scoped_ptr<TransportSecurityPersister>(
new TransportSecurityPersister(
context->transport_security_state(),
transport_security_persister_path_,
context->GetFileThread()->message_loop_proxy(),
false)));
}
storage->set_http_server_properties(
scoped_ptr<net::HttpServerProperties>(
new net::HttpServerPropertiesImpl()));
storage->set_cert_verifier(CertVerifier::CreateDefault());
if (throttling_enabled_)
storage->set_throttler_manager(new URLRequestThrottlerManager());
net::HttpNetworkSession::Params network_session_params;
network_session_params.host_resolver = context->host_resolver();
network_session_params.cert_verifier = context->cert_verifier();
network_session_params.transport_security_state =
context->transport_security_state();
network_session_params.proxy_service = context->proxy_service();
network_session_params.ssl_config_service =
context->ssl_config_service();
network_session_params.http_auth_handler_factory =
context->http_auth_handler_factory();
network_session_params.network_delegate = network_delegate;
network_session_params.http_server_properties =
context->http_server_properties();
network_session_params.net_log = context->net_log();
network_session_params.ignore_certificate_errors =
http_network_session_params_.ignore_certificate_errors;
network_session_params.host_mapping_rules =
http_network_session_params_.host_mapping_rules;
network_session_params.testing_fixed_http_port =
http_network_session_params_.testing_fixed_http_port;
network_session_params.testing_fixed_https_port =
http_network_session_params_.testing_fixed_https_port;
network_session_params.use_alternate_protocols =
http_network_session_params_.use_alternate_protocols;
network_session_params.trusted_spdy_proxy =
http_network_session_params_.trusted_spdy_proxy;
network_session_params.next_protos = http_network_session_params_.next_protos;
network_session_params.enable_quic = http_network_session_params_.enable_quic;
HttpTransactionFactory* http_transaction_factory = NULL;
if (http_cache_enabled_) {
network_session_params.channel_id_service =
context->channel_id_service();
HttpCache::BackendFactory* http_cache_backend = NULL;
if (http_cache_params_.type == HttpCacheParams::DISK) {
http_cache_backend = new HttpCache::DefaultBackend(
DISK_CACHE,
net::CACHE_BACKEND_DEFAULT,
http_cache_params_.path,
http_cache_params_.max_size,
context->GetCacheThread()->task_runner());
} else {
http_cache_backend =
HttpCache::DefaultBackend::InMemory(http_cache_params_.max_size);
}
http_transaction_factory = new HttpCache(
network_session_params, http_cache_backend);
} else {
scoped_refptr<net::HttpNetworkSession> network_session(
new net::HttpNetworkSession(network_session_params));
http_transaction_factory = new HttpNetworkLayer(network_session.get());
}
storage->set_http_transaction_factory(http_transaction_factory);
URLRequestJobFactoryImpl* job_factory = new URLRequestJobFactoryImpl;
if (data_enabled_)
job_factory->SetProtocolHandler("data", new DataProtocolHandler);
#if !defined(DISABLE_FILE_SUPPORT)
if (file_enabled_) {
job_factory->SetProtocolHandler(
"file",
new FileProtocolHandler(context->GetFileThread()->message_loop_proxy()));
}
#endif // !defined(DISABLE_FILE_SUPPORT)
#if !defined(DISABLE_FTP_SUPPORT)
if (ftp_enabled_) {
ftp_transaction_factory_.reset(
new FtpNetworkLayer(context->host_resolver()));
job_factory->SetProtocolHandler("ftp",
new FtpProtocolHandler(ftp_transaction_factory_.get()));
}
#endif // !defined(DISABLE_FTP_SUPPORT)
storage->set_job_factory(job_factory);
// TODO(willchan): Support sdch.
return context;
}
} // namespace net
| 34.854067 | 80 | 0.738143 | Fusion-Rom |
f688466b6cacf6f9f3c7a6d86561510d28e6ef31 | 3,054 | hpp | C++ | phylanx/execution_tree/primitives/sum_operation.hpp | rtohid/phylanx | c2e4e8e531c204a70b1907995b1fd467870e6d9d | [
"BSL-1.0"
] | null | null | null | phylanx/execution_tree/primitives/sum_operation.hpp | rtohid/phylanx | c2e4e8e531c204a70b1907995b1fd467870e6d9d | [
"BSL-1.0"
] | null | null | null | phylanx/execution_tree/primitives/sum_operation.hpp | rtohid/phylanx | c2e4e8e531c204a70b1907995b1fd467870e6d9d | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2018 Parsa Amini
// Copyright (c) 2018 Hartmut Kaiser
//
// 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)
#if !defined(PHYLANX_PRIMITIVES_SUM)
#define PHYLANX_PRIMITIVES_SUM
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/base_primitive.hpp>
#include <phylanx/execution_tree/primitives/primitive_component_base.hpp>
#include <hpx/lcos/future.hpp>
#include <hpx/util/optional.hpp>
#include <cstdint>
#include <string>
#include <vector>
namespace phylanx { namespace execution_tree { namespace primitives
{
/// \brief Sums the values of the elements of a vector or a matrix or
/// returns the value of the scalar that was given to it.
/// \param a The scalar, vector, or matrix to perform sum over
/// \param axis Optional. If provided, sum is calculated along the
/// provided axis and a vector of results is returned.
/// \p keep_dims is ignored if \p axis present. Must be
/// nil if \p keep_dims is set
/// \param keep_dims Optional. Whether the sum value has to have the same
/// number of dimensions as \p a. Ignored if \p axis is
/// anything except nil.
class sum_operation
: public primitive_component_base
, public std::enable_shared_from_this<sum_operation>
{
protected:
hpx::future<primitive_argument_type> eval(
std::vector<primitive_argument_type> const& operands,
std::vector<primitive_argument_type> const& args) const;
using val_type = double;
using arg_type = ir::node_data<val_type>;
using args_type = std::vector<arg_type>;
public:
static match_pattern_type const match_data;
sum_operation() = default;
sum_operation(std::vector<primitive_argument_type>&& operands,
std::string const& name, std::string const& codename);
hpx::future<primitive_argument_type> eval(
std::vector<primitive_argument_type> const& args) const override;
private:
primitive_argument_type sum0d(arg_type&& arg,
hpx::util::optional<std::int64_t> axis, bool keep_dims) const;
primitive_argument_type sum1d(arg_type&& arg,
hpx::util::optional<std::int64_t> axis, bool keep_dims) const;
primitive_argument_type sum2d(arg_type&& arg,
hpx::util::optional<std::int64_t> axis, bool keep_dims) const;
primitive_argument_type sum2d_flat(
arg_type&& arg, bool keep_dims) const;
primitive_argument_type sum2d_axis0(arg_type&& arg) const;
primitive_argument_type sum2d_axis1(arg_type&& arg) const;
};
PHYLANX_EXPORT primitive create_sum_operation(hpx::id_type const& locality,
std::vector<primitive_argument_type>&& operands,
std::string const& name = "", std::string const& codename = "");
}}}
#endif
| 40.184211 | 79 | 0.672233 | rtohid |
f688bc2ad7271e058f94ab26c3876ccc1361b18e | 29,258 | cpp | C++ | Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_CfgSrvBrws.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_CfgSrvBrws.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/RemBrws/CQCTreeBrws/CQCTreeBrws_CfgSrvBrws.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCTreeBrws_CfgSrvBrws.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 12/11/2015
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the remote browser derivative that handles browsing the
// config server.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CQCTreeBrws_.hpp"
#include "CQCTreeBrws_CfgSrvBrws_.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TCQCCfgSrvBrws,TCQCTreeBrwsIntf)
// ---------------------------------------------------------------------------
// CLASS: TCQCCfgSrvBrws
// PREFIX: rbrws
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TCQCCfgSrvBrws: Constructors and Destructor
// ---------------------------------------------------------------------------
TCQCCfgSrvBrws::TCQCCfgSrvBrws() :
TCQCTreeBrwsIntf
(
kCQCRemBrws::strPath_Configure
, kCQCRemBrws::strItem_Configure
, facCQCTreeBrws().strMsg(kTBrwsMsgs::midTitle_ConfBrower)
)
{
}
TCQCCfgSrvBrws::~TCQCCfgSrvBrws()
{
}
// ---------------------------------------------------------------------------
// TCQCCfgSrvBrws: Public, inherited methods
// ---------------------------------------------------------------------------
// Our browser object never accepts dropped files, so this won't get called
tCIDLib::TVoid
TCQCCfgSrvBrws::AcceptFiles(const TString&
, const tCIDLib::TStrList&
, const tCIDLib::TStrList&)
{
CIDAssert2(L"The config server browser should not be accepting files");
}
// We never accept dropped files in this section
tCIDLib::TBoolean
TCQCCfgSrvBrws::bAcceptsNew(const TString&, const tCIDLib::TStrHashSet&) const
{
return kCIDLib::False;
}
//
// The browser window calls us here if the user invokes a menu operation on the
// tree window.
//
tCIDLib::TBoolean
TCQCCfgSrvBrws::bDoMenuAction( const TString& strPath
, TTreeBrowseInfo& wnotToSend)
{
// Get the area of this item, tell it to use just the text width
TArea areaItem;
wndBrowser().bQueryItemArea(strPath, areaItem, kCIDLib::True, kCIDLib::True);
// Get the center point of it and convert to screen coordinates
TPoint pntAt;
wndBrowser().ToScreenCoordinates(areaItem.pntCenter(), pntAt);
// Create the menu and load it up from the resource
TPopupMenu menuAction(L"/Configure Action");
// Depending on the type of thing selected, we do a different menu
tCIDLib::TBoolean bAtTop;
const tCQCRemBrws::EDTypes eDType = ePathToDType(strPath, bAtTop);
const tCIDLib::TBoolean bNoType(eDType == tCQCRemBrws::EDTypes::Count);
const tCIDLib::TBoolean bScope = wndBrowser().bIsScope(strPath);
tCIDLib::TCard4 c4MenuCmd = 0;
menuAction.Create(facCQCTreeBrws(), kCQCTreeBrws::ridMenu_GenFile);
// If an item, or not e-mail or user, then disable new
if (!bScope
|| ((eDType != tCQCRemBrws::EDTypes::EMailAccount)
&& (eDType != tCQCRemBrws::EDTypes::User)))
{
menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_New, kCIDLib::False);
}
// If a scope, or not an e-mail or user, then disable delete
if (bScope
|| ((eDType != tCQCRemBrws::EDTypes::EMailAccount)
&& (eDType != tCQCRemBrws::EDTypes::User)))
{
menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Delete, kCIDLib::False);
}
// If a scope, disable the Edit and Copy. If not, disable the Refresh and Paste
if (bScope)
{
menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Copy, kCIDLib::False);
menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Edit, kCIDLib::False);
}
else
{
menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Paste, kCIDLib::False);
menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Refresh, kCIDLib::False);
}
// We only allow email accounts to be renamed
if (bScope || (eDType != tCQCRemBrws::EDTypes::EMailAccount))
menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_Rename, kCIDLib::False);
c4MenuCmd = menuAction.c4Process(wndBrowser(), pntAt, tCIDLib::EVJustify::Bottom);
//
// If they made a choice, then we have to translate it to the standard action
// enum that the browser window will understand.
//
return bProcessMenuSelection(c4MenuCmd, strPath, wnotToSend);
}
// We don't use a persistent connection, so we just say yes
tCIDLib::TBoolean TCQCCfgSrvBrws::bIsConnected() const
{
return kCIDLib::True;
}
//
// Our own bDoMenuAction calls this if a selection is made. It is also called by the
// browser window if an accelerator driven command is seen. That's why it's split out
// so that we can avoid duplicating this code.
//
tCIDLib::TBoolean
TCQCCfgSrvBrws::bProcessMenuSelection( const tCIDLib::TCard4 c4CmdId
, const TString& strPath
, TTreeBrowseInfo& wnotToSend)
{
// See what the data type is, if any
tCIDLib::TBoolean bAtTop = kCIDLib::False;
const tCQCRemBrws::EDTypes eType = ePathToDType(strPath, bAtTop);
tCIDLib::TBoolean bRet = kCIDLib::True;
switch(c4CmdId)
{
case kCQCTreeBrws::ridMenu_GenFile_Edit :
{
// Just inform the containing application that the user wants to edit
CIDAssert(eType != tCQCRemBrws::EDTypes::Count, L"Unknown data type for Edit");
wnotToSend = TTreeBrowseInfo
(
tCQCTreeBrws::EEvents::Edit, strPath, eType, wndBrowser()
);
break;
}
case kCQCTreeBrws::ridMenu_GenFile_New :
{
CIDAssert(eType != tCQCRemBrws::EDTypes::Count, L"Unknown data type for New");
bRet = bMakeNewFile(strPath, eType, wnotToSend);
break;
}
case kCQCTreeBrws::ridMenu_GenFile_Delete :
{
CIDAssert(eType != tCQCRemBrws::EDTypes::Count, L"Unknown data type for Delete");
// Delete the indicated file
if (bDeleteFile(strPath))
{
// Let any listeners know we did this
wnotToSend = TTreeBrowseInfo
(
tCQCTreeBrws::EEvents::Deleted, strPath, eType, wndBrowser()
);
}
break;
}
case kCQCTreeBrws::ridMenu_GenFile_Refresh :
{
// We just handle this one internally
UpdateScope(strPath);
break;
}
case kCQCTreeBrws::ridMenu_GenFile_Rename :
{
// Call our parent's rename method which does what we want
bRet = bDoRename(strPath, wnotToSend);
break;
}
default :
bRet = kCIDLib::False;
break;
};
return bRet;
}
//
// For our stuff, as long as it's not our top level path or some other scope, it's fine
// to report it all when double clicked. The client code will decide if it really
// wants to deal with it and how. So just checking to see if it's a scope is a good
// enough check. We indicate these are all edit operations.
//
tCIDLib::TBoolean
TCQCCfgSrvBrws::bReportInvocation(const TString& strPath, tCIDLib::TBoolean& bAsEdit) const
{
bAsEdit = kCIDLib::True;
return !wndBrowser().bIsScope(strPath);
}
//
// We add our top level scope and all of the next level ones since it's a fixed set
// that we always have.
//
tCIDLib::TVoid TCQCCfgSrvBrws::Initialize(const TCQCUserCtx& cuctxUser)
{
TParent::Initialize(cuctxUser);
TTreeView& wndTar = wndBrowser();
//
// Add our top level scope. It's not marked as virtual in this case, since we
// preload all of the possible top level items and sub-scopes. Some of our
// sub-scopes will be virtual.
//
wndTar.AddScope
(
kCQCRemBrws::strPath_Root, kCQCRemBrws::strItem_Configure, kCIDLib::False
);
//
// Load our main scopes. Some are virtual and will be faulted in only if
// they are accessed. Others we know the content and will go ahead and load them.
//
wndTar.AddScope(kCQCRemBrws::strPath_Configure, L"Accounts", kCIDLib::True);
wndTar.AddScope(kCQCRemBrws::strPath_Accounts, L"EMail", kCIDLib::True);
wndTar.AddScope(kCQCRemBrws::strPath_Configure, L"Ports", kCIDLib::True);
wndTar.AddScope(kCQCRemBrws::strPath_Configure, L"Users", kCIDLib::True);
//
// These are items at the top level, not scopes. These are for known, fixed data
// and cannot be removed.
//
wndTar.AddItem(kCQCRemBrws::strPath_Ports, L"GC-100");
wndTar.AddItem(kCQCRemBrws::strPath_Ports, L"JustAddPwr");
wndTar.AddItem(kCQCRemBrws::strPath_Configure, L"LogicSrv");
wndTar.AddItem(kCQCRemBrws::strPath_Configure, L"Location");
wndTar.AddItem(kCQCRemBrws::strPath_Configure, L"SystemCfg");
}
tCIDLib::TVoid
TCQCCfgSrvBrws::LoadScope(const TString& strPath)
{
TTreeView& wndTar = wndBrowser();
try
{
//
// Depending on the path, let's load up the relevant info and put it into
// the tree.
//
if (strPath.bStartsWithI(kCQCRemBrws::strPath_Users))
LoadUsers(wndTar);
else if (strPath.bStartsWithI(kCQCRemBrws::strPath_EMailAccts))
LoadEMails(wndTar);
//
// Probably this happened, if we added any above. But, if the scope was
// empty, then we need to do this just in case, to clear set the child
// count info, which also turns off the virtual scope flag, so we won't
// try to fault this one back in.
//
wndTar.UpdateChildCnt(strPath);
//
// At the end of an expansion, force the expanded once state on. It won't
// get done if this is a lazily faulted in tree and the expanded scope
// ended up being empty. That will cause lots of problems later.
//
wndTar.ForceExpandedOnce(strPath);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
facCQCGKit().ShowError
(
wndBrowser(), strTitle(), L"Could not expand item", errToCatch
);
}
}
//
// Some of our stuff doesn't use this, like user accounts, because they have to have a
// correct name up front. For other stuff we create a default name based on the parent
// scope.
//
tCIDLib::TVoid
TCQCCfgSrvBrws::MakeDefName(const TString& strParScope
, TString& strToFill
, const tCIDLib::TBoolean bIsFile) const
{
tCIDLib::TBoolean bAtTop = kCIDLib::False;
const tCQCRemBrws::EDTypes eType = ePathToDType(strParScope, bAtTop);
CIDAssert(bAtTop, L"The parent scope was not the top level scope for its type");
// Build up the base name for the new guy
TString strCurPath(strParScope);
strCurPath.Append(kCIDLib::chForwardSlash);
strCurPath.Append(tCQCRemBrws::strXlatEDTypes(eType));
// Now we add numbers to it until we get a unique name not already in this scope.
const tCIDLib::TCard4 c4BaseLen = strCurPath.c4Length();
tCIDLib::TCard4 c4Num = 1;
while (kCIDLib::True)
{
strCurPath.CapAt(c4BaseLen);
strCurPath.AppendFormatted(c4Num);
if (!wndBrowser().bPathExists(strCurPath))
{
strToFill = tCQCRemBrws::strXlatEDTypes(eType);
strToFill.AppendFormatted(c4Num);
break;
}
// Not unique, to try another
c4Num++;
}
}
//
// If the browser window gets an accelerator key translation call, he will call us
// here to load up an accelerator table for him which he will process. If it causes
// him to get a menu call, he will pass it on to us.
//
tCIDLib::TVoid
TCQCCfgSrvBrws::QueryAccelTable(const TString& strPath
, TAccelTable& accelToFill) const
{
//
// Just load it up from our menu. So we just create an instance of our menu but
// never show it.
//
TPopupMenu menuAction(L"/Configure Action");
// Depending on the type of thing selected, we do a different menu
tCIDLib::TBoolean bAtTop;
const tCQCRemBrws::EDTypes eDType = ePathToDType(strPath, bAtTop);
if ((eDType == tCQCRemBrws::EDTypes::EMailAccount)
|| (eDType == tCQCRemBrws::EDTypes::User))
{
menuAction.Create(facCQCTreeBrws(), kCQCTreeBrws::ridMenu_GenFile);
if (!bAtTop)
menuAction.SetItemEnable(kCQCTreeBrws::ridMenu_GenFile_New, kCIDLib::False);
}
else
{
// Don't have a menu for this so nothing
return;
}
// And now set up the accel table from the menu
accelToFill.Create(menuAction);
}
// We don't use a persistent connection, so nothing really to do here
tCIDLib::TVoid TCQCCfgSrvBrws::Terminate()
{
}
// ---------------------------------------------------------------------------
// TCQCCfgSrvBrws: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TCQCCfgSrvBrws::bCanRename(const TString& strPath) const
{
//
// The only things we currently allow to be renamed are e-mail accounts. Everything
// else is all special stuff.
//
return
(
!wndBrowser().bIsScope(strPath)
&& strPath.bStartsWithI(kCQCRemBrws::strPath_EMailAccts)
);
}
tCIDLib::TBoolean
TCQCCfgSrvBrws::bRenameItem(const TString& strParScope
, const TString& strOldName
, const TString& strNewName
, const tCIDLib::TBoolean bIsScope)
{
try
{
// Depending on the parent scope, we do the appropriate thing
if (strParScope.bStartsWithI(kCQCRemBrws::strPath_EMailAccts))
{
TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait);
tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy();
orbcInst->RenameEMailAccount(strOldName, strNewName, sectUser());
// And now tell the tree to update the display text of the item
wndBrowser().UpdateItem(strParScope, strOldName, strNewName);
}
else
{
TErrBox msgbErr(strTitle(), L"This data type cannot be renamed");
msgbErr.ShowIt(wndBrowser());
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
facCQCGKit().ShowError
(
wndBrowser(), strTitle(), L"Could not expand item", errToCatch
);
return kCIDLib::False;
}
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// TCQCCfgSrvBrws: Private, non-virtual methods
// ---------------------------------------------------------------------------
//
// This is called if we get a delete command (via menu or hot key). We look at
// the type and do the appropriate
//
tCIDLib::TBoolean TCQCCfgSrvBrws::bDeleteFile(const TString& strPath)
{
// Make sure that they really want to do it
TYesNoBox msgbConfirm
(
strTitle(), facCQCTreeBrws().strMsg(kTBrwsMsgs::midQ_DeleteItem, strPath)
);
if (!msgbConfirm.bShowIt(wndBrowser()))
return kCIDLib::False;
tCQCRemBrws::EDTypes eType = tCQCRemBrws::EDTypes::Count;
try
{
if (strPath.bStartsWithI(kCQCRemBrws::strPath_Users))
{
// Set this first in case of error
eType = tCQCRemBrws::EDTypes::User;
//
// Let's try to delete the indicated user. The last part of the path is
// the login name. We can get an error, even if the login name is valid,
// if they try to delete the last admin account.
//
TString strLoginName;
facCQCRemBrws().QueryNamePart(strPath, strLoginName);
tCQCKit::TSecuritySrvProxy orbcSrc = facCQCKit().orbcSecuritySrvProxy();
orbcSrc->DeleteAccount(strLoginName, sectUser());
}
else if (strPath.bStartsWithI(kCQCRemBrws::strPath_EMailAccts))
{
// Set this first in case of error
eType = tCQCRemBrws::EDTypes::EMailAccount;
TString strAcctName;
facCQCRemBrws().QueryNamePart(strPath, strAcctName);
TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait);
tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy();
if (!orbcInst->bDeleteEMailAccount(strAcctName, sectUser()))
{
facCQCTreeBrws().LogMsg
(
CID_FILE
, CID_LINE
, kTBrwsErrs::errcBrws_EMailDelete
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
, strAcctName
);
}
}
else
{
//
// Shouldn't happen, since we don't allow it in menus and we don't create
// a delete accellerator unless it's a deletable item. But, just in case.
//
facCQCGKit().ShowError
(
wndBrowser()
, strTitle()
, L"This item cannot be deleted, and you shouldn't have been able to "
L" try to do so. Sorry about that. Please report this issue."
);
return kCIDLib::False;
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
TString strMsg = TString::strConcat
(
L"An error occurred while deleting the ", tCQCRemBrws::strLoadEDTypes(eType)
);
facCQCGKit().ShowError(wndBrowser(), strTitle(), strMsg, errToCatch);
return kCIDLib::False;
}
// It didn't fail, so remove this item from the browser window
wndBrowser().RemoveItem(strPath);
return kCIDLib::True;
}
//
// This is called when we get a New menu selection. We see if it's one of the types
// of ours that we can create (it should be since the menu shouldn't have allowed
// otherwise.) We try to create the new file and get it into the browser.
//
tCIDLib::TBoolean
TCQCCfgSrvBrws::bMakeNewFile(const TString& strParHPath
, const tCQCRemBrws::EDTypes eDType
, TTreeBrowseInfo& wnotToSend)
{
// We need the browser a number of times so get a convenient ref
TCQCTreeBrowser& wndTar = wndBrowser();
//
// The first thing we need to do is to get a name from the user. We call
// a helper on the browser window do this since it's sort of messy. If they
// don't commit, we return and nothing has been done.
//
TString strNewName;
if (!wndTar.bGetNewName(strParHPath, kCIDLib::False, eDType, strNewName, *this))
return kCIDLib::False;
// Build up the new full hierarchical path
TString strNewHPath(strParHPath);
facCQCRemBrws().AddPathComp(strNewHPath, strNewName);
//
// At this point the item is in the tree. We need to make sure it gets removed
// if we don't explicitly decide to keep it.
//
TTreeItemJan janTree(&wndTar, strNewHPath);
// Get the type relative version of the parent path
TString strParRelPath;
facCQCRemBrws().CreateRelPath(strParHPath, eDType, strParRelPath);
tCIDLib::TBoolean bRet = kCIDLib::False;
try
{
if (eDType == tCQCRemBrws::EDTypes::EMailAccount)
{
bRet = bMakeNewEmailAcct(strParHPath, strParRelPath, strNewName);
}
else if (eDType == tCQCRemBrws::EDTypes::User)
{
bRet = bMakeNewUserAcct(strParHPath, strParRelPath, strNewName);
}
else
{
// Not something we can edit
TErrBox msgbView
(
strTitle()
, facCQCTreeBrws().strMsg
(
kTBrwsMsgs::midStatus_CantNew
, tCQCRemBrws::strLoadEDTypes(eDType)
, strNewHPath
)
);
msgbView.ShowIt(wndBrowser());
return kCIDLib::False;
}
// It appears to have worked, so prevent the janitor from removing it
janTree.Orphan();
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
TErrBox msgbNew
(
strTitle()
, facCQCRemBrws().strMsg(kTBrwsMsgs::midStatus_CantCreateFile, strNewHPath)
);
msgbNew.ShowIt(wndTar);
return kCIDLib::False;
}
// Select this new guy
wndTar.SelectPath(strNewHPath);
// It workeed so fill in a notification to be sent to the containing app
wnotToSend = TTreeBrowseInfo
(
tCQCTreeBrws::EEvents::NewFile, strNewHPath, eDType, wndBrowser()
);
return bRet;
}
//
// This is called to create a e-mail account. We just generate an empty one with
// a default name, save it which also adds it to the tree view, and select it. We don't
// need the hierarchy path info here for this.
//
tCIDLib::TBoolean
TCQCCfgSrvBrws::bMakeNewEmailAcct(const TString&, const TString&, const TString& strNewName)
{
// Set up a default account
TCQCEMailAccount emacctNew;
emacctNew.Set
(
tCQCKit::EEMailTypes::Unused
, strNewName
, L"me@myisp.com"
, L"HappyWeaselParty"
, L"myisp.com"
, L"Bubba"
, 25
);
TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait);
tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy();
tCIDLib::TCard4 c4SerNum = 0;
// Indicate it must be a new account, if not it will throw
return orbcInst->bUpdateEmailAccount(emacctNew, c4SerNum, sectUser(), kCIDLib::True);
}
//
// Called when the user asks to create a new user account. This one is a little special.
// In this case, we don't get a default name. The name has to be set up front and
// cannot be changed once it's created and stored away. So in this special case we
// get a login name from the user up front and use that.
//
tCIDLib::TBoolean
TCQCCfgSrvBrws::bMakeNewUserAcct(const TString& strParHPath
, const TString& strParRelPath
, const TString& strNewName)
{
// Set up a user account with basic info
TCQCUserAccount uaccNew
(
tCQCKit::EUserRoles::NormalUser
, L"New user account"
, strNewName
, L"Welcome"
, L"John"
, L"Smith"
);
// Create the hierarchical path for display purposes
TString strNewHPath(strParHPath);
strNewHPath.Append(kCIDLib::chForwardSlash);
strNewHPath.Append(strNewName);
tCQCKit::TSecuritySrvProxy orbcSrc = facCQCKit().orbcSecuritySrvProxy();
//
// In order to provide a more targeted error message for a common possible
// error, we check to see if this login name already exists. We have to provide
// the current user's security token to get this info.
//
if (orbcSrc->bLoginExists(strNewName, cuctxUser().sectUser()))
{
TErrBox msgbNew
(
strTitle()
, facCQCTreeBrws().strMsg(kTBrwsErrs::errcBrws_UAccExists, strNewName)
);
msgbNew.ShowIt(wndBrowser());
return kCIDLib::False;
}
orbcSrc->CreateAccount(uaccNew, sectUser());
return kCIDLib::True;
}
//
// Check the path to see if starts with the top level path for any of the types we
// deal with. If not, we return the _Count value.
//
// We also indicate if it was the top level for that type, or is on some sub-scope of
// it.
//
tCQCRemBrws::EDTypes
TCQCCfgSrvBrws::ePathToDType(const TString& strPath, tCIDLib::TBoolean& bAtTop) const
{
bAtTop = kCIDLib::False;
tCQCRemBrws::EDTypes eRet = tCQCRemBrws::EDTypes::Count;
const TString* pstrRoot = nullptr;
if (strPath.bStartsWithI(kCQCRemBrws::strPath_EMailAccts))
{
eRet = tCQCRemBrws::EDTypes::EMailAccount;
pstrRoot = &kCQCRemBrws::strPath_EMailAccts;
}
else if (strPath.bStartsWithI(kCQCRemBrws::strPath_GC100Ports))
{
eRet = tCQCRemBrws::EDTypes::GC100Ports;
pstrRoot = &kCQCRemBrws::strPath_GC100Ports;
}
else if (strPath.bStartsWithI(kCQCRemBrws::strPath_JAPwrPorts))
{
eRet = tCQCRemBrws::EDTypes::JAPwrPorts;
pstrRoot = &kCQCRemBrws::strPath_JAPwrPorts;
}
else if (strPath.bStartsWithI(kCQCRemBrws::strPath_Location))
{
eRet = tCQCRemBrws::EDTypes::Location;
pstrRoot = &kCQCRemBrws::strPath_Location;
}
else if (strPath.bStartsWithI(kCQCRemBrws::strPath_LogicSrv))
{
eRet = tCQCRemBrws::EDTypes::LogicSrv;
pstrRoot = &kCQCRemBrws::strPath_LogicSrv;
}
else if (strPath.bStartsWithI(kCQCRemBrws::strPath_SystemCfg))
{
eRet = tCQCRemBrws::EDTypes::SystemCfg;
pstrRoot = &kCQCRemBrws::strPath_SystemCfg;
}
else if (strPath.bStartsWithI(kCQCRemBrws::strPath_Users))
{
eRet = tCQCRemBrws::EDTypes::User;
pstrRoot = &kCQCRemBrws::strPath_Users;
}
if (eRet != tCQCRemBrws::EDTypes::Count)
bAtTop = (strPath == *pstrRoot);
return eRet;
}
//
// Called when it's time to fault in our email accounts scope or the user asks to reload
// the scope. In our case we just need to interate the config server scope that contains
// the email accounts and load an entry for each one.
//
// We let exceptions propagate.
//
tCIDLib::TVoid TCQCCfgSrvBrws::LoadEMails(TTreeView& wndTar)
{
TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait);
tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy();
tCIDLib::TStrList colList;
orbcInst->bQueryEMailAccountNames(colList, sectUser());
colList.bForEach([&wndTar](const TString& strName)
{
wndTar.AddItem(kCQCRemBrws::strPath_EMailAccts, strName);
return kCIDLib::True;
});
}
//
// Called when it's time to fault in our users scope or the user asks to reload the
// scope.
//
// We let exceptions propagate.
//
tCIDLib::TVoid TCQCCfgSrvBrws::LoadUsers(TTreeView& wndTar)
{
tCQCKit::TSecuritySrvProxy orbcSrc = facCQCKit().orbcSecuritySrvProxy();
// If we don't get any, then we are done
TVector<TCQCUserAccount> colList;
if (!orbcSrc->c4QueryAccounts(colList, sectUser()))
return;
//
// Loop though the list and load them into the tree. The text is the login
// name, which is also the key to upload changes, delete users and so forth.
//
TString strCurPath;
const tCIDLib::TCard4 c4Count = colList.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
const TCQCUserAccount& uaccCur = colList[c4Index];
wndTar.AddItem(kCQCRemBrws::strPath_Users, uaccCur.strLoginName());
}
}
//
// We query the contents of the indicated path, which must be a scope. We don't
// try to be clever. We temporarily disable drawing, remove the contents of
// the scope, then call our scope loader above to reload it. This also serves to
// toss all of the nested scopes, so we go back to virtual scope mode on all of
// them, to be subsequently reloaded as well. Not the most efficient, but the
// safest.
//
tCIDLib::TVoid TCQCCfgSrvBrws::UpdateScope(const TString& strPath)
{
TTreeView& wndTar = wndBrowser();
try
{
// Has to be a scope
CIDAssert(wndTar.bIsScope(strPath), L"Cannot update a non-scope item");
// Stop updates while we do this
TWndPaintJanitor janPaint(&wndTar);
wndBrowser().RemoveChildrenOf(strPath);
// Now call the same private helper used to do the initial load
if (strPath.bStartsWithI(kCQCRemBrws::strPath_Users))
LoadUsers(wndTar);
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
facCQCGKit().ShowError
(
wndBrowser(), strTitle(), L"Could not update scope", errToCatch
);
}
}
| 32.54505 | 93 | 0.610534 | MarkStega |
f688c47b9ff94e5d654d92525a5491e831d5c738 | 7,244 | cpp | C++ | src/OpenAnalysis/Activity/ManagerActiveStandard.cpp | sriharikrishna/OpenAnalysis | 0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc | [
"BSD-3-Clause"
] | null | null | null | src/OpenAnalysis/Activity/ManagerActiveStandard.cpp | sriharikrishna/OpenAnalysis | 0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc | [
"BSD-3-Clause"
] | null | null | null | src/OpenAnalysis/Activity/ManagerActiveStandard.cpp | sriharikrishna/OpenAnalysis | 0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc | [
"BSD-3-Clause"
] | null | null | null | /*! \file
\brief The AnnotationManager that generates ActiveStandard.
\authors Michelle Strout
\version $Id: ManagerActiveStandard.cpp,v 1.8 2005/06/10 02:32:02 mstrout Exp $
Copyright (c) 2002-2005, Rice University <br>
Copyright (c) 2004-2005, University of Chicago <br>
Copyright (c) 2006, Contributors <br>
All rights reserved. <br>
See ../../../Copyright.txt for details. <br>
*/
#include "ManagerActiveStandard.hpp"
#include <Utils/Util.hpp>
namespace OA {
namespace Activity {
static bool debug = false;
/*!
*/
ManagerActiveStandard::ManagerActiveStandard(OA_ptr<ActivityIRInterface> _ir)
: mIR(_ir)
{
OA_DEBUG_CTRL_MACRO("DEBUG_ManagerActiveStandard:ALL", debug);
}
/*!
OA_ptr<ActiveStandard> ManagerActiveStandard::performAnalysis(ProcHandle proc,
OA_ptr<CFG::Interface> cfg,
OA_ptr<Alias::Interface> alias,
OA_ptr<SideEffect::InterSideEffectInterface> interSE)
{
return performAnalysis(proc, cfg, alias, interSE,
interSE->getUSEIterator(proc),
interSE->getMODIterator(proc));
}
*/
/*!
*/
OA_ptr<ActiveStandard> ManagerActiveStandard::performAnalysis(ProcHandle proc,
OA_ptr<CFG::CFGInterface> cfg,
OA_ptr<Alias::Interface> alias,
OA_ptr<VaryStandard> vary,
OA_ptr<UsefulStandard> useful)
{
mAlias = alias;
mActive = new ActiveStandard(proc);
if (debug) {
std::cout << "ManagerActiveStandard::performAnalysis: ";
std::cout << "\tAnalyzing procedure " << mIR->toString(proc);
std::cout << std::endl;
}
// first create DepStandard, VaryStandard, and UsefulStandard
// Dep Analysis
// OA_ptr<ManagerDepStandard> depman;
// depman = new ManagerDepStandard(mIR);
//mDep = depman->performAnalysis(proc, alias, cfg);
// if (debug) { mDep->dump(std::cout, mIR); }
// Vary
// OA_ptr<ManagerVaryStandard> varyman;
// varyman = new ManagerVaryStandard(mIR);
// OA_ptr<VaryStandard> vary
// = varyman->performAnalysis(proc, cfg, mDep, indepLocIter);
// if (debug) { vary->dump(std::cout, mIR); }
// Useful
// OA_ptr<ManagerUsefulStandard> usefulman;
// usefulman = new ManagerUsefulStandard(mIR);
// OA_ptr<UsefulStandard> useful
// = usefulman->performAnalysis(proc, cfg, mDep, depLocIter);
// if (debug) { useful->dump(std::cout, mIR); }
// initialize OutVaryIterator to iterator over independent variables
OA_ptr<LocIterator> outVaryIterPtr = vary->getIndepSetIterator();
OA_ptr<LocIterator> depLocIter = useful->getDepSetIterator();
StmtHandle prevStmt = StmtHandle(0);
// for each statement in the procedure
OA_ptr<OA::IRStmtIterator> stmtIterPtr = mIR->getStmtIterator(proc);
for ( ; stmtIterPtr->isValid(); (*stmtIterPtr)++) {
OA::StmtHandle stmt = stmtIterPtr->current();
// send iterator for OutVary from previous stmt and InVary for current
// stmt into a helper function that determines active locations, whether
// the previous stmt was active, and which memory references in the
// previous and current stmt are active
calculateActive(prevStmt, outVaryIterPtr,
stmt, useful->getInUsefulIterator(stmt));
// get OutVary for this stmt
outVaryIterPtr = vary->getOutVaryIterator(stmt);
prevStmt = stmt;
}
// do calculation for point after last stmt
calculateActive(prevStmt, outVaryIterPtr, StmtHandle(0), depLocIter);
return mActive;
}
/*!
A helper function that determines active locations, whether
the previous stmt was active, and which memory references in the
previous and current stmt are active
*/
void ManagerActiveStandard::calculateActive(
StmtHandle prevStmt, OA_ptr<LocIterator> prevOutVaryIter,
StmtHandle stmt, OA_ptr<LocIterator> inUsefulIter)
{
if (debug) {
std::cout << "\tcalculateActive ---------------------" << std::endl;
}
// get set of active locations
prevOutVaryIter->reset();
for ( ; prevOutVaryIter->isValid(); (*prevOutVaryIter)++ ) {
OA_ptr<Location> loc = prevOutVaryIter->current();
if (debug) {
std::cout << "\t\tinVary loc = ";
loc->dump(std::cout,mIR);
}
inUsefulIter->reset();
for ( ; inUsefulIter->isValid(); (*inUsefulIter)++ ) {
if (debug) {
std::cout << "\t\tinUseful loc = ";
inUsefulIter->current()->dump(std::cout,mIR);
}
if (loc->mayOverlap(*(inUsefulIter->current())) ) {
mActive->insertLoc(loc);
mActive->insertLoc(inUsefulIter->current());
if (debug) {
std::cout << "\t\tinserting active loc = ";
loc->dump(std::cout,mIR);
std::cout << "\t\tinserting active loc = ";
inUsefulIter->current()->dump(std::cout,mIR);
}
}
}
}
// get all the defines from prevStmt and if any of those memory
// references have maylocs that may overlap with the active
// locations then the prevStmt and the memory references are active
if (prevStmt != StmtHandle(0)) {
OA_ptr<MemRefHandleIterator> defIterPtr = mIR->getDefMemRefs(prevStmt);
for ( ; defIterPtr->isValid(); (*defIterPtr)++ ) {
MemRefHandle def = defIterPtr->current();
if (debug) {
std::cout << "\t\tdef (" << def.hval() << ") = ";
mIR->dump(def,std::cout);
}
OA_ptr<LocIterator> activeIterPtr
= mActive->getActiveLocsIterator();
OA_ptr<LocIterator> locIterPtr = mAlias->getMayLocs(def);
for (; locIterPtr->isValid(); ++(*locIterPtr)) {
OA_ptr<Location> loc = locIterPtr->current();
activeIterPtr->reset();
for (; activeIterPtr->isValid(); (*activeIterPtr)++ ) {
if (loc->mayOverlap(*(activeIterPtr->current())) ) {
mActive->insertStmt(prevStmt);
mActive->insertMemRef(def);
}
}
}
}
}
// get all the uses from stmt and if any of those memory
// references have maylocs that may overlap with the active
// locations then those memory references are active
if (stmt != StmtHandle(0)) {
OA_ptr<MemRefHandleIterator> useIterPtr = mIR->getUseMemRefs(stmt);
for ( ; useIterPtr->isValid(); (*useIterPtr)++ ) {
MemRefHandle use = useIterPtr->current();
if (debug) {
std::cout << "\t\tuse (" << use.hval() << ") = ";
mIR->dump(use,std::cout);
}
OA_ptr<LocIterator> locIterPtr = mAlias->getMayLocs(use);
OA_ptr<LocIterator> activeIterPtr
= mActive->getActiveLocsIterator();
for (; locIterPtr->isValid(); ++(*locIterPtr)) {
OA_ptr<Location> loc = locIterPtr->current();
activeIterPtr->reset();
for (; activeIterPtr->isValid(); (*activeIterPtr)++ ) {
if (loc->mayOverlap(*(activeIterPtr->current())) ) {
mActive->insertMemRef(use);
}
}
}
}
}
}
} // end of namespace Activity
} // end of namespace OA
| 33.382488 | 81 | 0.612369 | sriharikrishna |
f689b7f083146c9f563f3d3c4c2415d3a6f46c2e | 9,299 | cpp | C++ | graph_replanning/src/test/test_new_start.cpp | JRL-CARI-CNR-UNIBS/online_replanner | 67f5af2563986182804bab9471325a3505865e55 | [
"BSD-3-Clause"
] | 1 | 2021-11-10T04:03:23.000Z | 2021-11-10T04:03:23.000Z | graph_replanning/src/test/test_new_start.cpp | JRL-CARI-CNR-UNIBS/online_replanner | 67f5af2563986182804bab9471325a3505865e55 | [
"BSD-3-Clause"
] | null | null | null | graph_replanning/src/test/test_new_start.cpp | JRL-CARI-CNR-UNIBS/online_replanner | 67f5af2563986182804bab9471325a3505865e55 | [
"BSD-3-Clause"
] | null | null | null | #include <ros/ros.h>
#include <graph_core/parallel_moveit_collision_checker.h>
#include <graph_replanning/trajectory.h>
#include <moveit/robot_state/robot_state.h>
#include <graph_replanning/replanner.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "node_test_replanner");
ros::AsyncSpinner spinner(4);
spinner.start();
ros::NodeHandle nh;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string group_name = "cartesian_arm";
std::string last_link = "end_effector";
moveit::planning_interface::MoveGroupInterface move_group(group_name);
robot_model_loader::RobotModelLoader robot_model_loader("robot_description");
robot_model::RobotModelPtr kinematic_model = robot_model_loader.getModel();
planning_scene::PlanningScenePtr planning_scene = std::make_shared<planning_scene::PlanningScene>(kinematic_model);
const robot_state::JointModelGroup* joint_model_group = move_group.getCurrentState()->getJointModelGroup(group_name);
std::vector<std::string> joint_names = joint_model_group->getActiveJointModelNames();
unsigned int dof = joint_names.size();
Eigen::VectorXd lb(dof);
Eigen::VectorXd ub(dof);
for (unsigned int idx = 0; idx < dof; idx++)
{
const robot_model::VariableBounds& bounds = kinematic_model->getVariableBounds(joint_names.at(idx)); //bounds dei joints definito in urdf e file joints limit
if (bounds.position_bounded_)
{
lb(idx) = bounds.min_position_;
ub(idx) = bounds.max_position_;
}
}
// //////////////////////////////////////////UPDATING PLANNING SCENE////////////////////////////////////////////////////////
ros::ServiceClient ps_client=nh.serviceClient<moveit_msgs::GetPlanningScene>("/get_planning_scene");
if (!ps_client.waitForExistence(ros::Duration(10)))
{
ROS_ERROR("unable to connect to /get_planning_scene");
return 1;
}
moveit_msgs::GetPlanningScene ps_srv;
if (!ps_client.call(ps_srv))
{
ROS_ERROR("call to srv not ok");
return 1;
}
if (!planning_scene->setPlanningSceneMsg(ps_srv.response.scene))
{
ROS_ERROR("unable to update planning scene");
return 0;
}
// //////////////////////////////////////////PATH PLAN & VISUALIZATION////////////////////////////////////////////////////////
pathplan::MetricsPtr metrics = std::make_shared<pathplan::Metrics>();
pathplan::CollisionCheckerPtr checker = std::make_shared<pathplan::ParallelMoveitCollisionChecker>(planning_scene, group_name);
pathplan::DisplayPtr disp = std::make_shared<pathplan::Display>(planning_scene,group_name,last_link);
disp->clearMarkers();
ros::Duration(1).sleep();
pathplan::Trajectory trajectory = pathplan::Trajectory(nh,planning_scene,group_name);
std::vector<pathplan::PathPtr> path_vector;
Eigen::VectorXd start_conf(3);
start_conf << 0.0,0.0,0.0;
Eigen::VectorXd goal_conf(3);
goal_conf << 0.8,0.8,0.8;
int id=100;
int id_wp = 1000;
for (unsigned int i =0; i<2; i++)
{
pathplan::SamplerPtr sampler = std::make_shared<pathplan::InformedSampler>(start_conf, goal_conf, lb, ub);
pathplan::BiRRTPtr solver = std::make_shared<pathplan::BiRRT>(metrics, checker, sampler);
pathplan::PathPtr solution = trajectory.computePath(start_conf, goal_conf,solver,1);
path_vector.push_back(solution);
std::vector<double> marker_color;
if(i==0) marker_color = {0.5,0.5,0.0,1.0};
if(i==1) marker_color = {0.0f,0.0f,1.0,1.0};
disp->displayPathAndWaypoints(solution,id,id_wp,"pathplan",marker_color);
id +=1;
id_wp +=50;
ros::Duration(0.5).sleep();
}
pathplan::PathPtr current_path = path_vector.front();
std::vector<pathplan::PathPtr> other_paths = {path_vector.at(1)};
Eigen::VectorXd parent = current_path->getConnections().at(2)->getParent()->getConfiguration();
Eigen::VectorXd child = current_path->getConnections().at(2)->getChild()->getConfiguration();
Eigen::VectorXd current_configuration = parent + (child-parent)*0.5;
current_path->getConnections().at(3)->setCost(std::numeric_limits<double>::infinity());
current_path->cost();
// ///////////////////////////////////////// VISUALIZATION OF CURRENT NODE ///////////////////////////////////////////////////////////
std::vector<double> marker_color_sphere_actual = {1.0,0.0,1.0,1.0};
disp->displayNode(std::make_shared<pathplan::Node>(current_configuration),id,"pathplan",marker_color_sphere_actual);
id++;
// //////////////////////////////////////// REPLANNING & TEST ////////////////////////////////////////////////////////////////
pathplan::SamplerPtr samp = std::make_shared<pathplan::InformedSampler>(start_conf, goal_conf, lb, ub);
pathplan::BiRRTPtr solver = std::make_shared<pathplan::BiRRT>(metrics, checker, samp);
solver->config(nh);
pathplan::Replanner replanner = pathplan::Replanner(current_configuration, current_path, other_paths, solver, metrics, checker, lb, ub);
double time_repl = 1.0;
bool success = replanner.informedOnlineReplanning(time_repl);
std::vector<double> marker_color = {1.0,1.0,0.0,1.0};
std::vector<double> marker_color_sphere_new_curr_conf = {0.0,0.0,0.0,1.0};
int id_new_curr_conf = 1678;
if(success)
{
ROS_WARN("SUCCESS");
std::vector<double> marker_scale(3,0.01);
disp->changeConnectionSize(marker_scale);
disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color);
}
else
{
return 0;
}
int idx_replanned_path_start;
pathplan::PathPtr replanned_path = replanner.getReplannedPath()->clone();
pathplan::ConnectionPtr replanned_path_conn = current_path->findConnection(replanned_path->getWaypoints().at(0),idx_replanned_path_start);
pathplan::NodePtr parent_node,child_node;
Eigen::VectorXd new_current_configuration;
//
disp->nextButton("Starting replanned path from conf1 -> press NEXT");
parent_node = replanned_path_conn->getParent();
child_node = replanned_path_conn->getChild();;
new_current_configuration = parent_node->getConfiguration()+0.3*(child_node->getConfiguration()-parent_node->getConfiguration());
replanner.startReplannedPathFromNewCurrentConf(new_current_configuration);
disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color);
disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf);
replanner.setReplannedPath(replanned_path->clone());
//
disp->nextButton("Starting replanned path from conf2 -> press NEXT");
parent_node = current_path->getConnections().at(0)->getParent();
child_node = current_path->getConnections().at(0)->getChild();
new_current_configuration = current_path->getWaypoints().at(0)+0.3*(current_path->getWaypoints().at(1)-current_path->getWaypoints().at(0));
replanner.startReplannedPathFromNewCurrentConf(new_current_configuration);
disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color);
disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf);
replanner.setReplannedPath(replanned_path->clone());
//
disp->nextButton("Starting replanned path from conf3 -> press NEXT");
parent_node = replanned_path->getConnections().at(0)->getParent();
child_node = replanned_path->getConnections().at(0)->getChild();
new_current_configuration = parent_node->getConfiguration()+0.3*(child_node->getConfiguration()-parent_node->getConfiguration());
replanner.startReplannedPathFromNewCurrentConf(new_current_configuration);
disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color);
disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf);
replanner.setReplannedPath(replanned_path->clone());
//
disp->nextButton("Starting replanned path from conf4 -> press NEXT");
parent_node = replanned_path->getConnections().at(1)->getParent();
child_node = replanned_path->getConnections().at(1)->getChild();
new_current_configuration = parent_node->getConfiguration()+0.3*(child_node->getConfiguration()-parent_node->getConfiguration());
replanner.startReplannedPathFromNewCurrentConf(new_current_configuration);
disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color);
disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf);
replanner.setReplannedPath(replanned_path->clone());
//
disp->nextButton("Starting replanned path from conf5 -> press NEXT");
parent_node = current_path->getConnections().at(idx_replanned_path_start+1)->getParent();
child_node = current_path->getConnections().at(idx_replanned_path_start+1)->getChild();
new_current_configuration = parent_node->getConfiguration()+0.3*(child_node->getConfiguration()-parent_node->getConfiguration());
replanner.startReplannedPathFromNewCurrentConf(new_current_configuration);
disp->displayPath(replanner.getReplannedPath(),id,"pathplan",marker_color);
disp->displayNode(std::make_shared<pathplan::Node>(new_current_configuration),id_new_curr_conf,"pathplan",marker_color_sphere_new_curr_conf);
return 0;
}
| 43.050926 | 162 | 0.715991 | JRL-CARI-CNR-UNIBS |
f68a2603503b415854d3574a5b07307773aaaa66 | 47,872 | cpp | C++ | src/landscapes/svo_tree.sanity.cpp | realazthat/landscapes | 0d56d67beb5641b913100d86601fce8a5a63fb1c | [
"MIT",
"WTFPL",
"Unlicense",
"0BSD"
] | 32 | 2015-12-29T04:33:08.000Z | 2021-04-08T01:46:44.000Z | src/landscapes/svo_tree.sanity.cpp | realazthat/landscapes | 0d56d67beb5641b913100d86601fce8a5a63fb1c | [
"MIT",
"WTFPL",
"Unlicense",
"0BSD"
] | null | null | null | src/landscapes/svo_tree.sanity.cpp | realazthat/landscapes | 0d56d67beb5641b913100d86601fce8a5a63fb1c | [
"MIT",
"WTFPL",
"Unlicense",
"0BSD"
] | 2 | 2019-04-05T02:28:02.000Z | 2019-06-11T07:59:53.000Z |
#include "landscapes/svo_tree.sanity.hpp"
#include "landscapes/svo_tree.hpp"
#include "landscapes/svo_formatters.hpp"
#include "format.h"
#include <iostream>
#include <tuple>
namespace svo{
::std::ostream& operator<<(::std::ostream& out, const svo::svo_block_sanity_error_t& error)
{
if (!error.has_error) {
out << "no error";
return out;
}
out << error.error;
return out;
}
::std::ostream& operator<<(::std::ostream& out, const svo::svo_slice_sanity_error_t& error)
{
if (!error.has_error) {
out << "no error";
return out;
}
out << error.error;
return out;
}
svo_slice_sanity_error_t svo_slice_sanity_minimal(const svo_slice_t* slice, svo_sanity_type_t sanity_type);
svo_slice_sanity_error_t svo_slice_sanity_pos_data_to_parent(const svo_slice_t* slice);
svo_slice_sanity_error_t svo_slice_sanity_channel_data_to_parent(const svo_slice_t* slice);
svo_block_sanity_error_t svo_block_sanity_data(const svo_block_t* block)
{
assert(block);
assert(block->tree);
goffset_t root_shadow_cd_goffset = block->root_shadow_cd_goffset;
goffset_t parent_root_cd_goffset = block->parent_root_cd_goffset;
if (root_shadow_cd_goffset == 0)
return svo_block_sanity_error_t("root_shadow_cd_goffset is 0", block);
if (parent_root_cd_goffset == 0)
return svo_block_sanity_error_t("parent_root_cd_goffset is 0", block);
if (block->root_shadow_cd_goffset == invalid_goffset)
return svo_block_sanity_error_t(fmt::format("root_shadow_cd_goffset is invalid")
, block);
if (!block->is_valid_cd_goffset(block->root_shadow_cd_goffset))
return svo_block_sanity_error_t(fmt::format("root_shadow_cd_goffset is not within the block")
, block);
if (!block->parent_block)
{
if (block->parent_root_cd_goffset != invalid_goffset)
return svo_block_sanity_error_t(fmt::format("block->parent_block is blank, but parent_root_cd_goffset is pointing somewhere"
", parent_root_cd_goffset: {}"
, block->parent_root_cd_goffset)
, block);
}
if (block->parent_block)
{
if (!block->has_root_children_goffset())
return svo_block_sanity_error_t(fmt::format("block has parent but has no root_children_goffset ..")
, block);
if (block->parent_root_cd_goffset == invalid_goffset)
return svo_block_sanity_error_t(fmt::format("block->parent_block is set, but parent_root_cd_goffset is invalid")
, block);
if (!block->parent_block->is_valid_cd_goffset(block->parent_root_cd_goffset))
return svo_block_sanity_error_t(fmt::format("parent_root_cd_goffset is not within the parent block")
, block);
///gets the root shadow CD, which lies in the current block
const auto* shadow_root_cd = svo_cget_cd(block->tree->address_space, block->root_shadow_cd_goffset);
///gets the root CD, which lies in the parent block
const auto* parent_root_cd = svo_cget_cd(block->tree->address_space, block->parent_root_cd_goffset);
///the root CD should always have a far pointer to this block.
if (!svo_get_far(parent_root_cd))
return svo_block_sanity_error_t(fmt::format("the root CD that points into this block is not using a far ptr")
, block);
///the goffset to the beginning of the root children set.
goffset_t shadow_root_cd_children_goffset = svo_get_child_ptr_goffset(block->tree->address_space, block->root_shadow_cd_goffset, shadow_root_cd);
///the goffset to the beginning of the root children set.
goffset_t parent_root_cd_children_goffset = svo_get_child_ptr_goffset(block->tree->address_space, block->parent_root_cd_goffset, parent_root_cd);
assert(block->is_valid_cd_goffset(block->root_shadow_cd_goffset));
assert(block->parent_block->is_valid_cd_goffset(block->parent_root_cd_goffset));
assert(shadow_root_cd_children_goffset == block->root_children_goffset());
if (!block->is_valid_cd_goffset(parent_root_cd_children_goffset))
return svo_block_sanity_error_t(fmt::format("the root CD that points into this block is pointing somewhere not inside this block"
", parent_root_cd_children_goffset: {}"
, parent_root_cd_children_goffset)
, block);
if (!block->is_valid_cd_goffset(shadow_root_cd_children_goffset))
return svo_block_sanity_error_t(fmt::format("the shadow CD of this block is pointing somewhere not inside this block"
", shadow_root_cd_children_goffset: {}"
, shadow_root_cd_children_goffset)
, block);
if (shadow_root_cd_children_goffset != parent_root_cd_children_goffset)
return svo_block_sanity_error_t(fmt::format("the root CD that points into this block is not pointing to the same location as the shadow root CD"
", shadow_root_cd_children_goffset: {}, parent_root_cd_children_goffset: {}"
, shadow_root_cd_children_goffset, parent_root_cd_children_goffset)
, block);
}
if (block->root_valid_bit)
{
} else {
//if (root_shadow_cd_goffset != invalid_goffset)
// return svo_block_sanity_error_t("root is not root_valid_bit, yet has a root shadow CD", block);
}
if (block->root_leaf_bit)
{
if (!(block->root_valid_bit))
return svo_block_sanity_error_t("root_valid_bit is not set, yet root_leaf_bit is set ...", block);
} else {
if (root_shadow_cd_goffset == invalid_goffset)
return svo_block_sanity_error_t("root is not a leaf, and has no root shadow CD", block);
}
std::vector< svo_block_sanity_error_t > issues;
std::size_t voxel_count = 0;
std::size_t leaf_count = 0;
std::size_t cd_count = 0;
std::set< goffset_t > found_cd_goffsets;
auto visitor = [&voxel_count, &leaf_count, &cd_count, &block, &issues, &found_cd_goffsets](goffset_t pcd_goffset, goffset_t cd_goffset, ccurve_t voxel_ccurve
, std::tuple<std::size_t, vcurve_t> metadata)
{
++voxel_count;
std::size_t level = std::get<0>(metadata);
vcurve_t parent_vcurve = std::get<1>(metadata);
vcurve_t voxel_vcurve = parent_vcurve*8 + voxel_ccurve;
vside_t level_side = 1 << level;
vcurvesize_t level_size = vcurvesize(level_side);
bool is_cd = (cd_goffset != invalid_goffset);
bool is_invalid_cd = is_cd && (!block->is_valid_cd_goffset(cd_goffset));
const child_descriptor_t* cd = 0;
if (is_cd && !is_invalid_cd)
cd = svo_cget_cd(block->tree->address_space, cd_goffset);
std::size_t cd_nonleaf_count = cd ? svo_get_cd_nonleaf_count(cd) : 0;
std::size_t cd_valid_count = cd ? svo_get_cd_valid_count(cd) : 0;
bool is_leaf = !is_cd || (!is_invalid_cd && (cd_valid_count == 0));
bool is_bottom_leaf = !block->trunk && (level == block->height - 1);
/*
std::cout << "is_bottom_leaf: " << (is_bottom_leaf ? "true" : "false")
<< ", is_leaf: " << (is_leaf ? "true" : "false")
<< ", is_cd: " << (is_cd ? "true" : "false")
<< ", cd_nonleaf_count: " << cd_nonleaf_count
<< std::endl;
if (cd)
std::cout << ", cd: " << *cd << std::endl;
*/
if (is_leaf)
++leaf_count;
if (is_cd)
++cd_count;
if(cd_goffset != invalid_goffset)
{
if (cd_goffset == svo_get_ph_goffset(cd_goffset))
issues.push_back(svo_block_sanity_error_t(fmt::format("CD is located on a page header!"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}"
, pcd_goffset, cd_goffset, voxel_ccurve, level, block->height)
, block));
if (found_cd_goffsets.count(cd_goffset) > 0)
issues.push_back(svo_block_sanity_error_t(fmt::format("Duplicate CD goffset"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}"
, pcd_goffset, cd_goffset, voxel_ccurve, level, block->height)
, block));
if (pcd_goffset != invalid_goffset && found_cd_goffsets.count(pcd_goffset) == 0)
issues.push_back(svo_block_sanity_error_t(fmt::format("Parent CD is not in found_cd_goffsets"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}"
, pcd_goffset, cd_goffset, voxel_ccurve, level, block->height)
, block));
found_cd_goffsets.insert(cd_goffset);
}
if (!block->trunk && !(level < block->height))
{
issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel level out of block bounds"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}"
, pcd_goffset, cd_goffset, voxel_ccurve, level, block->height)
, block));
}
if (!(voxel_vcurve < level_size))
{
issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel vcurve out of level bounds"
", pcd_goffset: {}, cd_goffset: {}, block->height: {}"
", level: {}, level_side: {}, level_size:{}, voxel_ccurve: {}"
, pcd_goffset, cd_goffset, block->height
, level, level_side, level_size, voxel_vcurve)
, block));
}
if (is_invalid_cd)
{
issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel is a CD but is not inside block"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}"
, pcd_goffset, cd_goffset, voxel_ccurve, level, block->height)
, block));
}
if (is_bottom_leaf && !is_leaf)
{
issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel is at bottom leaf level, but not a leaf"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}"
, pcd_goffset, cd_goffset, voxel_ccurve, level, block->height)
, block));
}
/*
if (is_bottom_leaf && is_cd)
{
issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel is at bottom leaf level, but has a CD"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}, level: {}, block->height: {}"
, pcd_goffset, cd_goffset, voxel_ccurve, level, block->height)
, block));
}*/
if (pcd_goffset == 0)
issues.push_back(svo_block_sanity_error_t(fmt::format("pcd_goffset somehow is equal to zero, zero is not an defined;"
" it isn't even an invalid offset, use @c invalid_goffset instead")
, block));
if (cd_goffset == 0)
issues.push_back(svo_block_sanity_error_t(fmt::format("cd_goffset somehow is equal to zero, zero is not an defined;"
" it isn't even an invalid offset, use @c invalid_goffset instead")
, block));
if (!is_leaf && cd_goffset == pcd_goffset)
issues.push_back(svo_block_sanity_error_t(fmt::format("Child ptr is zero, yet this is a non-leaf voxel .."
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}"
, pcd_goffset, cd_goffset, voxel_ccurve), block));
if (cd_goffset != invalid_goffset && cd_goffset != 0 && !block->is_valid_cd_goffset(cd_goffset))
issues.push_back(svo_block_sanity_error_t(fmt::format("cd_goffset is an invalid CD, not inside block bounds .."
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}"
, pcd_goffset, cd_goffset, voxel_ccurve), block));
if (pcd_goffset != invalid_goffset && pcd_goffset != 0 && !block->is_valid_cd_goffset(pcd_goffset))
issues.push_back(svo_block_sanity_error_t(fmt::format("pcd_goffset is an invalid CD, not inside block bounds .."
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}"
, pcd_goffset, cd_goffset, voxel_ccurve), block));
if (pcd_goffset != invalid_goffset && pcd_goffset != 0 && block->is_valid_cd_goffset(pcd_goffset))
{
const auto* pcd = svo_cget_cd(block->tree->address_space, pcd_goffset);
bool parent_valid_bit = svo_get_valid_bit(pcd, voxel_ccurve);
bool parent_leaf_bit = svo_get_leaf_bit(pcd, voxel_ccurve);
if (!parent_valid_bit)
issues.push_back(svo_block_sanity_error_t(fmt::format("Voxel exists, but parent says this is an invalid voxel"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}"
, pcd_goffset, cd_goffset, voxel_ccurve), block));
if (parent_leaf_bit && cd_goffset != invalid_goffset && cd_goffset != 0)
issues.push_back(svo_block_sanity_error_t(fmt::format("Parent says voxel is a leaf, but yet we have a CD for it"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}"
, pcd_goffset, cd_goffset, voxel_ccurve), block));
}
if (cd_goffset != pcd_goffset && cd_goffset != invalid_goffset && cd_goffset != 0)
{
const auto* cd = svo_cget_cd(block->tree->address_space, cd_goffset);
child_mask_t valid_mask = svo_get_valid_mask(cd);
child_mask_t leaf_mask = svo_get_leaf_mask(cd);
child_mask_t error_bits = leaf_mask & (~valid_mask);
if (error_bits)
issues.push_back(svo_block_sanity_error_t(fmt::format("CD has children that are invalid, but are marked as leafs"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}"
", valid_mask: {}, leaf_mask: {}, error_bits: {}"
, pcd_goffset, cd_goffset, voxel_ccurve
, std::bitset<8>(valid_mask)
, std::bitset<8>(leaf_mask)
, std::bitset<8>(error_bits)), block));
bool has_non_leaf_child = cd_nonleaf_count > 0;
goffset_t child0_base_goffset = svo_get_child_ptr_goffset(block->tree->address_space, cd_goffset, cd);
if (has_non_leaf_child && child0_base_goffset == invalid_goffset)
issues.push_back(svo_block_sanity_error_t(fmt::format("CD's child ptr is invalid"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}"
", valid_mask: {}, leaf_mask: {}, child0_base_goffset: {}"
, pcd_goffset, cd_goffset, voxel_ccurve
, std::bitset<8>(valid_mask)
, std::bitset<8>(leaf_mask)
, child0_base_goffset), block));
if (has_non_leaf_child && !block->is_valid_cd_goffset(child0_base_goffset))
{
if (!block->trunk)
issues.push_back(svo_block_sanity_error_t(fmt::format("CD's child ptr points outside of the block's bounds, and this is not a trunk"
", pcd_goffset: {}, cd_goffset: {}, voxel_ccurve: {}"
", valid_mask: {}, leaf_mask: {}, child0_base_goffset: {}"
, pcd_goffset, cd_goffset, voxel_ccurve
, std::bitset<8>(valid_mask)
, std::bitset<8>(leaf_mask)
, child0_base_goffset), block));
}
}
return std::make_tuple(level+1, voxel_vcurve);
};
z_preorder_traverse_block_cds( block->tree->address_space
, block
, std::make_tuple(std::size_t(0), vcurve_t(0)) ///(level,vcurve) as metadata
, visitor);
if (issues.size() > 0)
return issues[0];
if (cd_count != block->cd_count)
return svo_block_sanity_error_t(fmt::format("CD counts do not match. block->cd_count: {}, actual CD count: {}"
, block->cd_count, cd_count), block);
if (leaf_count != block->leaf_count)
return svo_block_sanity_error_t(fmt::format("voxel counts do not match. block->leaf_count: {}, actual leaf_count: {}"
, block->leaf_count, leaf_count), block);
return svo_block_sanity_error_t();
}
svo_block_sanity_error_t svo_block_sanity_check(const svo_block_t* block, int recurse)
{
auto check_is_valid_goffset = [&block](const std::string& name, goffset_t goffset)
{
if (goffset == 0 || goffset == invalid_goffset)
return svo_block_sanity_error_t(fmt::format("{} is is not a valid goffset: {}.", name, goffset), block);
return svo_block_sanity_error_t();
};
auto check_is_range = [&block](const std::string& range_name, goffset_t begin, goffset_t end)
{
if (begin > end)
return svo_block_sanity_error_t(fmt::format("{} is is not a valid range: [{}, {}).", range_name, begin, end), block);
return svo_block_sanity_error_t();
};
auto check_in_range = [&block]( const std::string& name, goffset_t goffset, std::size_t size
, const std::string& range_name, goffset_t begin, goffset_t end)
{
if (goffset < begin || goffset + size > end )
return svo_block_sanity_error_t(fmt::format("{} is out of bounds of {}.", name, range_name), block);
return svo_block_sanity_error_t();
};
if(!block)
return svo_block_sanity_error_t("block is invalid pointer", block);
if(!(block->child_blocks))
return svo_block_sanity_error_t("block->child_blocks is invalid pointer", block);
if(!(block->tree))
return svo_block_sanity_error_t("block->tree is invalid pointer", block);
if (block->trunk)
{
if(block->height != 0)
return svo_block_sanity_error_t("block is trunk, yet has a height", block);
if(block->side != 0)
return svo_block_sanity_error_t("block is trunk, yet has a side", block);
}
if (block->root_shadow_cd_goffset == 0)
return svo_block_sanity_error_t(fmt::format("root_shadow_cd_goffset is 0, an undefined value; use @c invalid_goffset somewhere instead"
), block);
if (block->root_valid_bit)
{
if (!block->trunk && block->height < 1)
return svo_block_sanity_error_t(fmt::format("root is valid but block->height is 0"
", height: {}, side: {}, root_valid_bit: {}, root_leaf_bit: {}"
, block->height, block->side, block->root_valid_bit, block->root_leaf_bit), block);
vside_t expected_side = (1UL << (block->height - 1));
if (!block->trunk && block->side != expected_side)
return svo_block_sanity_error_t(fmt::format("side does not match expected side based on height"
", height: {}, side: {}, expected side: {}, root_valid_bit: {}, root_leaf_bit: {}"
, block->height, block->side, expected_side, block->root_valid_bit, block->root_leaf_bit)
, block);
if (!(block->root_leaf_bit) && block->root_shadow_cd_goffset == invalid_goffset)
return svo_block_sanity_error_t(fmt::format("nonleaf root, and no shadow root cd specified"), block);
}
if (block->root_leaf_bit)
{
if (!block->trunk && !(block->root_valid_bit))
return svo_block_sanity_error_t(fmt::format("root is a leaf but is marked as invalid"
", height: {}, side: {}, root_valid_bit: {}, root_leaf_bit: {}"
, block->height, block->side, block->root_valid_bit, block->root_leaf_bit), block);
if (!block->trunk && block->height != 1)
return svo_block_sanity_error_t(fmt::format("root is a leaf but block->height is not 1"
", height: {}, side: {}, root_valid_bit: {}, root_leaf_bit: {}"
, block->height, block->side, block->root_valid_bit, block->root_leaf_bit), block);
}
if (block->block_start % SVO_PAGE_SIZE != 0 || block->block_end % SVO_PAGE_SIZE != 0)
return svo_block_sanity_error_t(fmt::format("block is not aligned to page!"
", block->block_start: {}, misalignment: {}"
", block->block_end: {}, misalignment: {}"
", SVO_PAGE_SIZE: {}"
, block->block_start, block->block_start % SVO_PAGE_SIZE
, block->block_end, block->block_end % SVO_PAGE_SIZE
, SVO_PAGE_SIZE)
,block);
if (!!(block->slice) && block->child_blocks->size() > 0)
return svo_block_sanity_error_t(fmt::format("block has a child slice, but also has child blocks ...")
, block);
if(block->root_shadow_cd_goffset == 0)
return svo_block_sanity_error_t("block->root_shadow_cd_goffset is not initialized; this should always be pointing to a dummy root CD.", block);
///range sanities
{
if (auto error = check_is_valid_goffset("block_start", block->block_start))
return error;
if (auto error = check_is_valid_goffset("block_end", block->block_end))
return error;
if (auto error = check_is_valid_goffset("cd_start", block->cd_start))
return error;
if (auto error = check_is_valid_goffset("cd_end", block->cd_end))
return error;
if (auto error = check_is_valid_goffset("cdspace_end", block->cdspace_end))
return error;
if (auto error = check_is_range("[block_start,block_end)", block->block_start, block->block_end))
return error;
if (auto error = check_is_range("[cd_start,cd_end)", block->cd_start, block->cd_end))
return error;
if (auto error = check_is_range("[cd_start,cdspace_end)", block->cd_start, block->cdspace_end))
return error;
if (auto error = check_in_range("cd_start", block->cd_start, 0
, "the block", block->block_start, block->block_end))
return error;
if (auto error = check_in_range("cd_end", block->cd_end, 0
, "the block", block->block_start, block->block_end))
return error;
if (auto error = check_in_range("cdspace_end", block->cdspace_end, 0
, "the block", block->block_start, block->block_end))
return error;
if (auto error = check_in_range("cd_end", block->cd_end, 0
, "cd space", block->cd_start, block->cdspace_end))
return error;
}
if (block->slice)
{
vside_t expected_slice_side = block->side == 0 ? 1 : block->side * 2;
if (expected_slice_side != block->slice->side)
return svo_block_sanity_error_t(fmt::format("slice side does not match the next expected level's side ..."
" block->side: {}, slice->side: {}, expected_slice_side: {}"
, block->side, block->slice->side, expected_slice_side)
, block);
}
auto calculate_cd_level = [](const svo_block_t* block, goffset_t needle)
{
assert(block->is_valid_cd_goffset(needle));
std::size_t needle_level = std::size_t(-1);
auto visitor = [&needle_level, needle]( goffset_t pcd_goffset, goffset_t cd_goffset, ccurve_t voxel_ccurve
, std::tuple<std::size_t, vcurve_t> metadata)
{
std::size_t level = std::get<0>(metadata);
vcurve_t parent_vcurve = std::get<1>(metadata);
vcurve_t vcurve = parent_vcurve*8 + voxel_ccurve;
if (cd_goffset == needle)
needle_level = level;
return std::make_tuple(level+1, vcurve);
};
z_preorder_traverse_block_cds(block->tree->address_space
, block
, std::make_tuple(std::size_t(0), vcurve_t(0)) ///(level) as metadata
, visitor);
return needle_level;
};
if (block->parent_block)
{
auto& parent_block = *block->parent_block;
if (!parent_block.child_blocks)
return svo_block_sanity_error_t("block->parent_block->child_blocks is invalid pointer", block, block->parent_block);
if (std::find(parent_block.child_blocks->begin(), parent_block.child_blocks->end(), block) == parent_block.child_blocks->end())
return svo_block_sanity_error_t("block->parent_block->child_blocks does not contain block ...", block, block->parent_block);
if (!(block->parent_block->is_valid_cd_goffset(block->parent_root_cd_goffset)))
return svo_block_sanity_error_t("block->parent_root_cd_goffset is pointing to something, but that something is not within the parent block ..."
, block);
std::size_t parent_root_cd_cd_level = calculate_cd_level(block->parent_block, block->parent_root_cd_goffset);
std::size_t expected_root_level = block->parent_block->root_level + parent_root_cd_cd_level;
if (block->root_level != expected_root_level)
return svo_block_sanity_error_t(fmt::format("block->root_level is not the expected root level"
" root_level: {}, parent_root_cd_cd_level: {}, expected_root_level: {}"
, block->root_level, parent_root_cd_cd_level, expected_root_level)
, block);
} else {
if (block->parent_root_cd_goffset != invalid_goffset)
return svo_block_sanity_error_t("block->parent_root_cd_goffset is pointing to something, but there is no parent block ...", block);
}
for (const svo_block_t* child_block : *block->child_blocks)
{
if (child_block->parent_block != block)
return svo_block_sanity_error_t("child block does not point back to the parent ...", block, child_block);
}
if (auto error = svo_block_sanity_data(block))
{
return error;
}
if (recurse)
{
for (const svo_block_t* child_block : *block->child_blocks)
{
auto result = svo_block_sanity_check(child_block, recurse-1);
if (result)
return result;
}
}
return svo_block_sanity_error_t();
}
svo_slice_sanity_error_t svo_slice_sanity_channel_data_to_parent(const svo_slice_t* slice)
{
if (auto error = svo_slice_sanity_minimal(slice, svo_sanity_type_t::minimal))
{
return error;
}
assert(slice);
assert(slice->pos_data);
assert(slice->buffers);
const auto& pos_data = *(slice->pos_data);
const auto& buffers = *(slice->buffers);
for (const auto& buffer : buffers.buffers())
{
if (buffer.entries() != pos_data.size())
return svo_slice_sanity_error_t(fmt::format("different number of channel elements than position elements"
" buffer.declaration: {}, buffer.entries(): {}, pos_data.size(): {}"
, buffer.declaration(), buffer.entries(), pos_data.size())
, slice);
}
if (slice->parent_slice)
{
if (slice->parent_slice->buffers == nullptr)
return svo_slice_sanity_error_t(fmt::format("slice->parent_slice->buffers is invalid pointer")
, slice);
const auto& parent_buffers = *slice->parent_slice->buffers;
if (buffers.schema() != parent_buffers.schema())
return svo_slice_sanity_error_t(fmt::format("parent_slice->buffers does not match buffers"
", buffers: {}, parent_buffers: {}"
, buffers.schema(), parent_buffers.schema())
, slice);
}
return svo_slice_sanity_error_t();
}
svo_slice_sanity_error_t svo_slice_sanity_pos_data_to_parent(const svo_slice_t* slice)
{
if (auto error = svo_slice_sanity_minimal(slice, svo_sanity_type_t::minimal))
{
return error;
}
assert(slice->pos_data);
const auto& pos_data = *(slice->pos_data);
///check position data sanity.
{
vcurvesize_t max_vcurve = vcurvesize(slice->side);
for (const vcurve_t voxel_vcurve : pos_data)
{
if (!(voxel_vcurve < max_vcurve))
return svo_slice_sanity_error_t(fmt::format("data contains a voxel that is outside of the bounds of the slice ..."
" voxel_vcurve: {}, max_vcurve: {}"
, voxel_vcurve, max_vcurve)
, slice);
}
}
if (!(slice->parent_slice))
return svo_slice_sanity_error_t();
assert(slice->parent_slice->pos_data);
const auto& parent_pos_data = *(slice->parent_slice->pos_data);
///we will iterate through the parent data in tandem with our data.
vcurve_t parent_data_index = 0;
for (const vcurve_t voxel_vcurve : pos_data)
{
vcurve_t expected_parent_voxel_vcurve = (voxel_vcurve / 8) + slice->parent_vcurve_begin;
///move the cursor in the parent data until we are up to our expected @c parent_voxel_vcurve
while (parent_data_index < parent_pos_data.size() && parent_pos_data[parent_data_index] < expected_parent_voxel_vcurve)
{
++parent_data_index;
}
if (!(parent_data_index < parent_pos_data.size()) || expected_parent_voxel_vcurve != parent_pos_data[parent_data_index])
{
return svo_slice_sanity_error_t(fmt::format("data contains a voxel that is not contained in the parent slice ..."
" voxel_vcurve: {}, expected_parent_voxel_vcurve: {}"
, voxel_vcurve, expected_parent_voxel_vcurve)
, slice);
}
assert(parent_data_index < parent_pos_data.size());
if (expected_parent_voxel_vcurve == parent_pos_data[parent_data_index])
///we found the parent voxel; it exists.
continue;
}
return svo_slice_sanity_error_t();
}
svo_slice_sanity_error_t svo_slice_sanity_minimal(const svo_slice_t* slice, svo_sanity_type_t sanity_type)
{
if(!slice)
return svo_slice_sanity_error_t("slice is invalid pointer", slice);
///parent <=> slice sanity
if (slice->parent_slice)
{
auto parent_slice = slice->parent_slice;
if (sanity_type & svo_sanity_type_t::levels)
if (parent_slice->level + 1 != slice->level)
return svo_slice_sanity_error_t(
fmt::format("parent->level is not one less than slice->level"
", parent->level: {}, slice->level: {}"
", parent: {}, slice: {}"
, parent_slice->level, slice->level
, (void*)parent_slice, (void*)slice), slice);
if (!parent_slice->children)
return svo_slice_sanity_error_t("parent->children is invalid pointer", slice);
const auto& siblings = *parent_slice->children;
auto it = std::find(siblings.begin(), siblings.end(), slice);
if (it == siblings.end())
return svo_slice_sanity_error_t("slice not in parent's children", slice);
}
if (slice->parent_slice == nullptr)
{
if (slice->parent_vcurve_begin != 0)
return svo_slice_sanity_error_t(fmt::format("slice has no parent, and yet has a parent_vcurve_begin: {}"
, slice->parent_vcurve_begin), slice);
}
if (!slice->pos_data)
return svo_slice_sanity_error_t("slice->data is an invalid pointer", slice);
if (!slice->buffers)
return svo_slice_sanity_error_t("slice->buffers is an invalid pointer", slice);
const auto& pos_data = *slice->pos_data;
///parameter consistency
{
if (!slice->parent_slice && slice->parent_vcurve_begin != 0)
return svo_slice_sanity_error_t(fmt::format("no parent slice specified, but has a non-zero parent_vcurve_begin ..."
" parent_vcurve_begin: {}"
, slice->parent_vcurve_begin)
, slice);
if (slice->side == 0)
return svo_slice_sanity_error_t(fmt::format("side is zero ...")
, slice);
assert(slice->side != 0);
if (slice->side == 1 && slice->parent_slice != nullptr)
return svo_slice_sanity_error_t(fmt::format("slice has a side of 1, and yet has a parent slice")
, slice->parent_slice, slice);
if (slice->side > SVO_VOLUME_SIDE_LIMIT)
return svo_slice_sanity_error_t(fmt::format("slice has a side of greater than SVO_MAX_VOLUME_SIDE"
"side: {}, SVO_MAX_VOLUME_SIDE: {}"
, slice->side, SVO_VOLUME_SIDE_LIMIT)
, slice);
if (slice->side > 1)
{
auto size_in_parent = vcurvesize(slice->side / 2);
assert(size_in_parent != 0);
if (slice->parent_vcurve_begin % size_in_parent != 0)
return svo_slice_sanity_error_t(fmt::format("parent_vcurve_begin is not aligned to the beginning of a node of this size ..."
" parent_vcurve_begin: {}, side: {}, size: {}, size in parent: {}"
, slice->parent_vcurve_begin, slice->side, vcurvesize(slice->side), vcurvesize(slice->side / 2))
, slice);
}
}
///data/bounds check
{
vcurvesize_t size = vcurvesize(slice->side);
vcurvesize_t last_vcurve = size;
for (const auto& voxel_vcurve : pos_data)
{
if (!(voxel_vcurve < size))
return svo_slice_sanity_error_t(fmt::format("data contains voxel that is out of bounds of the slice ..."
" side: {}, size: {}, vcurve: {}"
, slice->side, size, voxel_vcurve)
, slice);
if (last_vcurve == size) {
///pass
} else {
if (voxel_vcurve == last_vcurve)
return svo_slice_sanity_error_t(fmt::format("data contains a duplicate voxel ..."
" voxel_vcurve: {}"
, voxel_vcurve)
, slice);
if (!(voxel_vcurve > last_vcurve))
return svo_slice_sanity_error_t(fmt::format("data contains voxels that are out of order ..."
" side: {}, size: {}, vcurve: {}, last vcurve: {}"
, slice->side, size, voxel_vcurve, last_vcurve)
, slice);
}
last_vcurve = voxel_vcurve;
}
}
///slice => children sanity
{
if (!slice->children)
return svo_slice_sanity_error_t("slice->children is invalid pointer", slice);
const auto& children = *slice->children;
///child space bounds check
{
vcurvesize_t size = vcurvesize(slice->side);
vcurve_t last_parent_vcurve_end = 0;
for (std::size_t child_index = 0; child_index < slice->children->size(); ++child_index)
{
const svo_slice_t* child = (*slice->children)[child_index];
vcurvesize_t child_size = vcurvesize(child->side);
vcurvesize_t child_size_in_parent = vcurvesize(child->side / 2);
vcurvesize_t child_parent_vcurve_end = child->parent_vcurve_begin + child_size_in_parent;
//std::cout << "child_index: " << child_index << std::endl;
//std::cout << "child->parent_vcurve_begin: " << child->parent_vcurve_begin << std::endl;
//std::cout << "child_parent_vcurve_end: " << child_parent_vcurve_end << std::endl;
if (!child->parent_slice)
return svo_slice_sanity_error_t("child->parent_slice is invalid pointer", slice, child);
if (child->parent_slice != slice)
return svo_slice_sanity_error_t("child->parent_slice is not pointing the slice", slice, child, child->parent_slice);
if (child->side > slice->side * 2)
return svo_slice_sanity_error_t(fmt::format("child takes up more space than the parent ..."
" side: {}, size: {}, child->side: {}, child size (double res): {}"
", child size (in parent space): {}"
, slice->side, size, child->side, child_size, child_size_in_parent)
, slice, child);
if (child->side % 2 != 0)
return svo_slice_sanity_error_t(fmt::format("child cube side is not divisible by 2; yet it takes up (side/2) space in the parent ..."
" side: {}, size: {}, child->side: {}, child size: {}"
", child size (in parent space): {}"
, slice->side, size, child->side, child_size, child_size_in_parent)
, slice, child);
if (child->parent_vcurve_begin < last_parent_vcurve_end)
return svo_slice_sanity_error_t(fmt::format("child overlaps previous child's bounds ..."
" child->parent_vcurve_begin: {}, child_parent_vcurve_end: {}"
", last_parent_vcurve_end: {}, size: {}"
", child size (double res): {}, child size (parent res): {}, child_index: {}"
, child->parent_vcurve_begin, child_parent_vcurve_end
, last_parent_vcurve_end, size
, child_size, child_size_in_parent, child_index)
, slice, child);
if (!(child_parent_vcurve_end <= size))
return svo_slice_sanity_error_t(fmt::format("child overflows the bounds of the parent ..."
" slice size: {}, child_parent_vcurve_end: {}"
, size, child_parent_vcurve_end)
, slice, child);
last_parent_vcurve_end = child_parent_vcurve_end;
}
}
}
return svo_slice_sanity_error_t();
}
#if 0
svo_slice_sanity_error_t svo_slice_sanity_check_parent_error(const svo_slice_t* slice, int recurse)
{
if (!slice)
return svo_slice_sanity_error_t("slice is invalid pointer", slice);
if (!slice->parent_slice)
return svo_slice_sanity_error_t();
return svo_slice_sanity_check_error(slice->parent_slice, recurse);
}
svo_slice_sanity_error_t svo_slice_sanity_check_children_error(const svo_slice_t* slice, int recurse)
{
if (!slice)
return svo_slice_sanity_error_t("slice is invalid pointer", slice);
if (!slice->children)
return svo_slice_sanity_error_t();
for (const svo_slice_t* child : *slice->children)
{
auto error = svo_slice_sanity_check_error(child, recurse);
if (error)
return error;
}
return svo_slice_sanity_error_t();
}
svo_slice_sanity_error_t svo_slice_sanity_all(const svo_slice_t* slice)
{
if (auto error = svo_slice_sanity_minimal(slice))
return error;
if (auto error = svo_slice_sanity_check_parent_error(slice))
return error;
if (auto error = svo_slice_sanity_check_children_error(slice))
return error;
if (auto error = svo_slice_sanity_pos_data(slice))
return error;
if (auto error = svo_slice_sanity_channel_data(slice, 1))
return error;
return svo_slice_sanity_error_t();
}
#endif
svo_slice_sanity_error_t svo_slice_sanity(
const svo_slice_t* slice
, svo_sanity_type_t sanity_type
, int recurse
, bool parent_recurse)
{
if (sanity_type)
if (auto error = svo_slice_sanity_minimal(slice, sanity_type))
return error;
const auto& children = *slice->children;
if (sanity_type & svo_sanity_type_t::pos_data)
for (const auto* child_slice : children)
if (auto error = svo_slice_sanity_pos_data_to_parent(child_slice))
return error;
if (sanity_type & svo_sanity_type_t::channel_data)
for (const auto* child_slice : children)
if (auto error = svo_slice_sanity_channel_data_to_parent(child_slice))
return error;
if (sanity_type & svo_sanity_type_t::parent && slice->parent_slice && parent_recurse)
if (auto error = svo_slice_sanity(slice->parent_slice, sanity_type, 0/*recurse*/, false/*parent_recurse*/))
return error;
if (sanity_type & svo_sanity_type_t::children && recurse > 0)
{
for (const auto* child_slice : children)
{
if (auto error = svo_slice_sanity(child_slice, sanity_type, recurse - 1))
return error;
}
}
return svo_slice_sanity_error_t();
}
} // namespace svo
| 45.333333 | 161 | 0.521265 | realazthat |
f68a5d42e41654b2e368567be9e19dbcc9437213 | 3,979 | cc | C++ | runtime/barrier_test.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 234 | 2017-07-18T05:30:27.000Z | 2022-01-07T02:21:31.000Z | runtime/barrier_test.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 21 | 2017-07-18T04:56:09.000Z | 2018-08-10T17:32:16.000Z | runtime/barrier_test.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 56 | 2017-07-18T10:37:10.000Z | 2022-01-07T02:19:22.000Z | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "barrier.h"
#include <string>
#include "atomic.h"
#include "common_runtime_test.h"
#include "mirror/object_array-inl.h"
#include "thread_pool.h"
#include "thread-inl.h"
namespace art {
class CheckWaitTask : public Task {
public:
CheckWaitTask(Barrier* barrier, AtomicInteger* count1, AtomicInteger* count2)
: barrier_(barrier),
count1_(count1),
count2_(count2) {}
void Run(Thread* self) {
LOG(INFO) << "Before barrier" << *self;
++*count1_;
barrier_->Wait(self);
++*count2_;
LOG(INFO) << "After barrier" << *self;
}
virtual void Finalize() {
delete this;
}
private:
Barrier* const barrier_;
AtomicInteger* const count1_;
AtomicInteger* const count2_;
};
class BarrierTest : public CommonRuntimeTest {
public:
static int32_t num_threads;
};
int32_t BarrierTest::num_threads = 4;
// Check that barrier wait and barrier increment work.
TEST_F(BarrierTest, CheckWait) {
Thread* self = Thread::Current();
ThreadPool thread_pool("Barrier test thread pool", num_threads);
Barrier barrier(num_threads + 1); // One extra Wait() in main thread.
Barrier timeout_barrier(0); // Only used for sleeping on timeout.
AtomicInteger count1(0);
AtomicInteger count2(0);
for (int32_t i = 0; i < num_threads; ++i) {
thread_pool.AddTask(self, new CheckWaitTask(&barrier, &count1, &count2));
}
thread_pool.StartWorkers(self);
while (count1.LoadRelaxed() != num_threads) {
timeout_barrier.Increment(self, 1, 100); // sleep 100 msecs
}
// Count 2 should still be zero since no thread should have gone past the barrier.
EXPECT_EQ(0, count2.LoadRelaxed());
// Perform one additional Wait(), allowing pool threads to proceed.
barrier.Wait(self);
// Wait for all the threads to finish.
thread_pool.Wait(self, true, false);
// Both counts should be equal to num_threads now.
EXPECT_EQ(count1.LoadRelaxed(), num_threads);
EXPECT_EQ(count2.LoadRelaxed(), num_threads);
timeout_barrier.Init(self, 0); // Reset to zero for destruction.
}
class CheckPassTask : public Task {
public:
CheckPassTask(Barrier* barrier, AtomicInteger* count, size_t subtasks)
: barrier_(barrier),
count_(count),
subtasks_(subtasks) {}
void Run(Thread* self) {
for (size_t i = 0; i < subtasks_; ++i) {
++*count_;
// Pass through to next subtask.
barrier_->Pass(self);
}
}
void Finalize() {
delete this;
}
private:
Barrier* const barrier_;
AtomicInteger* const count_;
const size_t subtasks_;
};
// Check that barrier pass through works.
TEST_F(BarrierTest, CheckPass) {
Thread* self = Thread::Current();
ThreadPool thread_pool("Barrier test thread pool", num_threads);
Barrier barrier(0);
AtomicInteger count(0);
const int32_t num_tasks = num_threads * 4;
const int32_t num_sub_tasks = 128;
for (int32_t i = 0; i < num_tasks; ++i) {
thread_pool.AddTask(self, new CheckPassTask(&barrier, &count, num_sub_tasks));
}
thread_pool.StartWorkers(self);
const int32_t expected_total_tasks = num_sub_tasks * num_tasks;
// Wait for all the tasks to complete using the barrier.
barrier.Increment(self, expected_total_tasks);
// The total number of completed tasks should be equal to expected_total_tasks.
EXPECT_EQ(count.LoadRelaxed(), expected_total_tasks);
}
} // namespace art
| 30.374046 | 84 | 0.705202 | lifansama |
f68a898a386e8f688c3f1ecdaaab87af7c9ce7b8 | 70,741 | cpp | C++ | hphp/hhbbc/test/type-system.cpp | arnononline/hhvm | f80bfae3394cc48a0a99a49e003c7c3cd92e444f | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2015-05-31T17:15:47.000Z | 2015-05-31T17:15:47.000Z | hphp/hhbbc/test/type-system.cpp | mrliao/hhvm | 4ed1b985c6fad79376994726490bccdcba3699a6 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/hhbbc/test/type-system.cpp | mrliao/hhvm | 4ed1b985c6fad79376994726490bccdcba3699a6 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/hhbbc/type-system.h"
#include <gtest/gtest.h>
#include <boost/range/join.hpp>
#include <algorithm>
#include <limits>
#include <memory>
#include <utility>
#include <vector>
#include "folly/Lazy.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/hhbbc/hhbbc.h"
#include "hphp/hhbbc/misc.h"
#include "hphp/hhbbc/representation.h"
#include "hphp/hhbbc/parse.h"
#include "hphp/hhbbc/index.h"
#include "hphp/runtime/vm/as.h"
#include "hphp/runtime/vm/unit-emitter.h"
namespace HPHP { namespace HHBBC {
namespace {
//////////////////////////////////////////////////////////////////////
const StaticString s_test("test");
const StaticString s_TestClass("TestClass");
const StaticString s_Base("Base");
const StaticString s_A("A");
const StaticString s_AA("AA");
const StaticString s_AB("AB");
const StaticString s_B("B");
const StaticString s_BA("BA");
const StaticString s_BB("BB");
const StaticString s_BAA("BAA");
const StaticString s_IBase("IBase");
const StaticString s_IA("IA");
const StaticString s_IAA("IAA");
const StaticString s_IB("IB");
const StaticString s_NonUnique("NonUnique");
const StaticString s_NonUniqueA("NonUniqueA");
const StaticString s_WaitHandle("HH\\WaitHandle");
// A test program so we can actually test things involving object or
// class types.
std::unique_ptr<php::Unit> make_test_unit() {
assert(SystemLib::s_inited);
std::string const hhas = R"(
.main {
Int 1
RetC
}
# Technically this should be provided by systemlib, but it's the
# only one we have to make sure the type system can see for unit
# test purposes, so we can just define it here. We don't need to
# give it any of its functions currently.
.class [abstract unique builtin] HH\WaitHandle {
}
.class [interface unique] IBase {
}
.class [interface unique] IA implements (IBase) {
}
.class [interface unique] IB implements (IBase) {
}
.class [interface unique] IAA implements (IA) {
}
.class [unique] Base {
.default_ctor;
}
.class [unique] A extends Base implements (IA) {
.default_ctor;
}
.class [no_override unique] AA extends A implements (IAA) {
.default_ctor;
}
.class [no_override unique] AB extends A {
.default_ctor;
}
.class [unique] B extends Base {
.default_ctor;
}
.class [unique] BA extends B {
.default_ctor;
}
.class [no_override unique] BB extends B {
.default_ctor;
}
.class [unique] BAA extends BA {
.default_ctor;
}
# Make sure BAA doesn't get AttrNoOverride:
.class [unique] BAADeriver extends BAA {
.default_ctor;
}
.class [unique] TestClass {
.default_ctor;
}
# Make sure TestClass doesn't get AttrNoOverride:
.class [unique] TestClassDeriver extends TestClass {
.default_ctor;
}
.class NonUnique { .default_ctor; }
.class NonUnique { .default_ctor; }
.class NonUniqueA extends NonUnique {
.default_ctor;
}
.class NonUniqueA extends NonUnique {
.default_ctor;
}
.function test() {
Int 1
RetC
}
)";
std::unique_ptr<UnitEmitter> ue(assemble_string(
hhas.c_str(), hhas.size(),
"ignore.php",
MD5("12345432123454321234543212345432")
));
return parse_unit(*ue);
}
std::unique_ptr<php::Program> make_program() {
auto program = folly::make_unique<php::Program>();
program->units.push_back(make_test_unit());
return program;
}
//////////////////////////////////////////////////////////////////////
auto const test_empty_array = folly::lazy([] {
return staticEmptyArray();
});
auto const test_array_map_value = folly::lazy([] {
auto ar = make_map_array(
s_A.get(), s_B.get(),
s_test.get(), 12
);
return ArrayData::GetScalarArray(ar.get());
});
auto const test_array_packed_value = folly::lazy([] {
auto ar = make_packed_array(
42,
23,
12
);
return ArrayData::GetScalarArray(ar.get());
});
auto const test_array_packed_value2 = folly::lazy([] {
auto ar = make_packed_array(
42,
23.0,
12
);
return ArrayData::GetScalarArray(ar.get());
});
auto const test_array_packed_value3 = folly::lazy([] {
auto ar = make_packed_array(
1,
2,
3,
4,
5
);
return ArrayData::GetScalarArray(ar.get());
});
auto const with_data = folly::lazy([] {
return std::vector<Type> {
ival(2),
dval(2.0),
sval(s_test.get()),
aval(test_array_map_value()),
aval(test_array_packed_value())
};
});
// In the sense of "non-union type", not the sense of TPrim.
auto const primitives = {
TUninit,
TInitNull,
TFalse,
TTrue,
TInt,
TDbl,
TSStr,
TCStr,
TSArrE,
TCArrE,
TSArrN,
TCArrN,
TObj,
TRes,
TCls,
TRef
};
auto const optionals = {
TOptTrue,
TOptFalse,
TOptBool,
TOptInt,
TOptDbl,
TOptNum,
TOptSStr,
TOptCStr,
TOptStr,
TOptSArrE,
TOptCArrE,
TOptSArrN,
TOptCArrN,
TOptSArr,
TOptCArr,
TOptArr,
TOptObj,
TOptRes
};
auto const non_opt_unions = {
TInitCell,
TCell,
TInitGen,
TGen,
TNull,
TBool,
TNum,
TStr,
TArrE,
TArrN,
TSArr,
TCArr,
TArr,
TInitPrim,
TPrim,
TInitUnc,
TUnc,
TTop,
};
auto const all_unions = boost::join(optionals, non_opt_unions);
auto const all = folly::lazy([] {
std::vector<Type> ret;
auto const wdata = with_data();
ret.insert(end(ret), begin(primitives), end(primitives));
ret.insert(end(ret), begin(all_unions), end(all_unions));
ret.insert(end(ret), begin(wdata), end(wdata));
return ret;
});
template<class Range>
std::vector<Type> wait_handles_of(const Index& index, const Range& r) {
std::vector<Type> ret;
for (auto& t : r) ret.push_back(wait_handle(index, t));
return ret;
}
std::vector<Type> all_with_waithandles(const Index& index) {
auto ret = wait_handles_of(index, all());
for (auto& t : all()) ret.push_back(t);
return ret;
}
auto const specialized_array_examples = folly::lazy([] {
auto ret = std::vector<Type>{};
auto test_map_a = StructMap{};
test_map_a[s_test.get()] = ival(2);
ret.emplace_back(sarr_struct(test_map_a));
auto test_map_b = StructMap{};
test_map_b[s_test.get()] = TInt;
ret.emplace_back(sarr_struct(test_map_b));
auto test_map_c = StructMap{};
test_map_c[s_A.get()] = TInt;
ret.emplace_back(sarr_struct(test_map_c));
auto test_map_d = StructMap{};
test_map_d[s_A.get()] = TInt;
test_map_d[s_test.get()] = TDbl;
ret.emplace_back(sarr_struct(test_map_d));
ret.emplace_back(arr_packedn(TInt));
ret.emplace_back(arr_mapn(TSStr, arr_mapn(TInt, TSStr)));
ret.emplace_back(arr_mapn(TSStr, TArr));
ret.emplace_back(arr_mapn(TSStr, arr_packedn(TSStr)));
ret.emplace_back(arr_mapn(TSStr, arr_mapn(TSStr, TSStr)));
return ret;
});
//////////////////////////////////////////////////////////////////////
}
TEST(Type, Top) {
auto const program = make_program();
Index index { borrow(program) };
// Everything is a subtype of Top, couldBe Top, and the union of Top
// with anything is Top.
for (auto& t : all_with_waithandles(index)) {
EXPECT_TRUE(t.subtypeOf(TTop));
EXPECT_TRUE(t.couldBe(TTop));
EXPECT_TRUE(union_of(t, TTop) == TTop);
EXPECT_TRUE(union_of(TTop, t) == TTop);
}
}
TEST(Type, Bottom) {
auto const program = make_program();
Index index { borrow(program) };
// Bottom is a subtype of everything, nothing couldBe Bottom, and
// the union_of anything with Bottom is itself.
for (auto& t : all_with_waithandles(index)) {
EXPECT_TRUE(TBottom.subtypeOf(t));
EXPECT_TRUE(!TBottom.couldBe(t));
EXPECT_TRUE(union_of(t, TBottom) == t);
EXPECT_TRUE(union_of(TBottom, t) == t);
}
}
TEST(Type, Prims) {
auto const program = make_program();
Index index { borrow(program) };
// All pairs of non-equivalent primitives are not related by either
// subtypeOf or couldBe, including if you wrap them in wait handles.
for (auto& t1 : primitives) {
for (auto& t2 : primitives) {
if (t1 != t2) {
EXPECT_TRUE(!t1.subtypeOf(t2) && !t2.subtypeOf(t1));
EXPECT_TRUE(!t1.couldBe(t2));
EXPECT_TRUE(!t2.couldBe(t1));
auto const w1 = wait_handle(index, t1);
auto const w2 = wait_handle(index, t2);
EXPECT_TRUE(!w1.subtypeOf(w2) && !w2.subtypeOf(w1));
EXPECT_TRUE(!w1.couldBe(w2));
EXPECT_TRUE(!w2.couldBe(w1));
}
}
}
}
TEST(Type, Relations) {
auto const program = make_program();
Index index { borrow(program) };
// couldBe is symmetric and reflexive
for (auto& t1 : all_with_waithandles(index)) {
for (auto& t2 : all()) {
EXPECT_TRUE(t1.couldBe(t2) == t2.couldBe(t1));
}
}
for (auto& t1 : all_with_waithandles(index)) {
EXPECT_TRUE(t1.couldBe(t1));
}
// subtype is antisymmetric and reflexive
for (auto& t1 : all_with_waithandles(index)) {
for (auto& t2 : all_with_waithandles(index)) {
if (t1 != t2) {
EXPECT_TRUE(!(t1.subtypeOf(t2) && t2.subtypeOf(t1)));
}
}
}
for (auto& t1 : all_with_waithandles(index)) {
EXPECT_TRUE(t1.subtypeOf(t1));
}
// union_of is commutative
for (auto& t1 : all_with_waithandles(index)) {
for (auto& t2 : all_with_waithandles(index)) {
EXPECT_TRUE(union_of(t1, t2) == union_of(t2, t1))
<< " " << show(t1) << ' ' << show(t2)
<< "\n union_of(t1, t2): " << show(union_of(t1, t2))
<< "\n union_of(t2, t1): " << show(union_of(t2, t1));
}
}
}
TEST(Type, Prim) {
auto subtype_true = std::initializer_list<std::pair<Type,Type>> {
{ TInt, TPrim },
{ TBool, TPrim },
{ TNum, TPrim },
{ TInitNull, TPrim },
{ TDbl, TPrim },
{ dval(0.0), TPrim },
{ ival(0), TPrim },
{ TNull, TPrim },
{ TInt, TInitPrim },
{ TBool, TInitPrim },
{ TNum, TInitPrim },
{ TInitNull, TInitPrim },
{ TDbl, TInitPrim },
{ dval(0.0), TInitPrim },
{ ival(0), TInitPrim },
};
auto subtype_false = std::initializer_list<std::pair<Type,Type>> {
{ sval(s_test.get()), TPrim },
{ TSStr, TPrim },
{ TSArr, TPrim },
{ TNull, TInitPrim }, // TNull could be uninit
{ TPrim, TBool },
{ TPrim, TInt },
{ TPrim, TNum },
{ TInitPrim, TNum },
{ TUnc, TPrim },
{ TUnc, TInitPrim },
{ TInitUnc, TPrim },
{ TSStr, TInitPrim },
{ TArr, TInitPrim },
{ TSArr, TPrim },
{ TPrim, dval(0.0) },
};
auto couldbe_true = std::initializer_list<std::pair<Type,Type>> {
{ TPrim, TInt },
{ TPrim, TBool },
{ TPrim, TNum },
{ TInitPrim, TNum },
{ TInitPrim, TFalse },
{ TPrim, TCell },
{ TPrim, TInt },
{ TPrim, TInt },
{ TPrim, TOptObj },
{ TPrim, TOptFalse },
};
auto couldbe_false = std::initializer_list<std::pair<Type,Type>> {
{ TPrim, TSStr },
{ TInitPrim, TSStr },
{ TInitPrim, sval(s_test.get()) },
{ TPrim, sval(s_test.get()) },
{ TInitPrim, TUninit },
{ TPrim, TRef },
{ TPrim, TObj },
};
for (auto kv : subtype_true) {
EXPECT_TRUE(kv.first.subtypeOf(kv.second))
<< show(kv.first) << " subtypeOf " << show(kv.second);
}
for (auto kv : subtype_false) {
EXPECT_FALSE(kv.first.subtypeOf(kv.second))
<< show(kv.first) << " !subtypeOf " << show(kv.second);
}
for (auto kv : couldbe_true) {
EXPECT_TRUE(kv.first.couldBe(kv.second))
<< show(kv.first) << " couldbe " << show(kv.second);
EXPECT_TRUE(kv.second.couldBe(kv.first))
<< show(kv.first) << " couldbe " << show(kv.second);
}
for (auto kv : couldbe_false) {
EXPECT_TRUE(!kv.first.couldBe(kv.second))
<< show(kv.first) << " !couldbe " << show(kv.second);
EXPECT_TRUE(!kv.second.couldBe(kv.first))
<< show(kv.first) << " !couldbe " << show(kv.second);
}
}
TEST(Type, CouldBeValues) {
EXPECT_FALSE(ival(2).couldBe(ival(3)));
EXPECT_TRUE(ival(2).couldBe(ival(2)));
EXPECT_FALSE(aval(test_array_packed_value()).couldBe(
aval(test_array_map_value())));
EXPECT_TRUE(aval(test_array_packed_value()).couldBe(
aval(test_array_packed_value())));
EXPECT_TRUE(dval(2.0).couldBe(dval(2.0)));
EXPECT_FALSE(dval(2.0).couldBe(dval(3.0)));
EXPECT_FALSE(sval(s_test.get()).couldBe(sval(s_A.get())));
EXPECT_TRUE(sval(s_test.get()).couldBe(sval(s_test.get())));
}
TEST(Type, Unc) {
EXPECT_TRUE(TInt.subtypeOf(TInitUnc));
EXPECT_TRUE(TInt.subtypeOf(TUnc));
EXPECT_TRUE(TDbl.subtypeOf(TInitUnc));
EXPECT_TRUE(TDbl.subtypeOf(TUnc));
EXPECT_TRUE(dval(3.0).subtypeOf(TInitUnc));
auto pairs = std::initializer_list<std::pair<Type,Type>> {
{ TUnc, TInitUnc },
{ TUnc, TInitCell },
{ TUnc, TCell },
{ TInitUnc, TInt },
{ TInitUnc, TOptInt },
{ TInitUnc, opt(ival(2)) },
{ TUnc, TInt },
{ TUnc, TOptInt },
{ TUnc, opt(ival(2)) },
{ TNum, TUnc },
{ TNum, TInitUnc },
};
for (auto kv : pairs) {
EXPECT_TRUE(kv.first.couldBe(kv.second))
<< show(kv.first) << " couldBe " << show(kv.second);
}
}
TEST(Type, DblNan) {
auto const qnan = std::numeric_limits<double>::quiet_NaN();
EXPECT_TRUE(dval(qnan).subtypeOf(dval(qnan)));
EXPECT_TRUE(dval(qnan).couldBe(dval(qnan)));
EXPECT_TRUE(dval(qnan) == dval(qnan));
}
TEST(Type, Option) {
auto const program = make_program();
Index index { borrow(program) };
EXPECT_TRUE(TTrue.subtypeOf(TOptTrue));
EXPECT_TRUE(TInitNull.subtypeOf(TOptTrue));
EXPECT_TRUE(!TUninit.subtypeOf(TOptTrue));
EXPECT_TRUE(TFalse.subtypeOf(TOptFalse));
EXPECT_TRUE(TInitNull.subtypeOf(TOptFalse));
EXPECT_TRUE(!TUninit.subtypeOf(TOptFalse));
EXPECT_TRUE(TFalse.subtypeOf(TOptBool));
EXPECT_TRUE(TTrue.subtypeOf(TOptBool));
EXPECT_TRUE(TInitNull.subtypeOf(TOptBool));
EXPECT_TRUE(!TUninit.subtypeOf(TOptBool));
EXPECT_TRUE(ival(3).subtypeOf(TOptInt));
EXPECT_TRUE(TInt.subtypeOf(TOptInt));
EXPECT_TRUE(TInitNull.subtypeOf(TOptInt));
EXPECT_TRUE(!TUninit.subtypeOf(TOptInt));
EXPECT_TRUE(TDbl.subtypeOf(TOptDbl));
EXPECT_TRUE(TInitNull.subtypeOf(TOptDbl));
EXPECT_TRUE(!TUninit.subtypeOf(TOptDbl));
EXPECT_TRUE(dval(3.0).subtypeOf(TOptDbl));
EXPECT_TRUE(sval(s_test.get()).subtypeOf(TOptSStr));
EXPECT_TRUE(TSStr.subtypeOf(TOptSStr));
EXPECT_TRUE(TInitNull.subtypeOf(TOptSStr));
EXPECT_TRUE(!TUninit.subtypeOf(TOptSStr));
EXPECT_TRUE(!TStr.subtypeOf(TOptSStr));
EXPECT_TRUE(TStr.couldBe(TOptSStr));
EXPECT_TRUE(TCStr.subtypeOf(TOptStr));
EXPECT_TRUE(TCArr.subtypeOf(TOptArr));
EXPECT_TRUE(TStr.subtypeOf(TOptStr));
EXPECT_TRUE(TSStr.subtypeOf(TOptStr));
EXPECT_TRUE(sval(s_test.get()).subtypeOf(TOptStr));
EXPECT_TRUE(TInitNull.subtypeOf(TOptStr));
EXPECT_TRUE(!TUninit.subtypeOf(TOptStr));
EXPECT_TRUE(TSArr.subtypeOf(TOptSArr));
EXPECT_TRUE(!TArr.subtypeOf(TOptSArr));
EXPECT_TRUE(TInitNull.subtypeOf(TOptSArr));
EXPECT_TRUE(!TUninit.subtypeOf(TOptSArr));
EXPECT_TRUE(TArr.subtypeOf(TOptArr));
EXPECT_TRUE(TInitNull.subtypeOf(TOptArr));
EXPECT_TRUE(!TUninit.subtypeOf(TOptArr));
EXPECT_TRUE(TObj.subtypeOf(TOptObj));
EXPECT_TRUE(TInitNull.subtypeOf(TOptObj));
EXPECT_TRUE(!TUninit.subtypeOf(TOptObj));
EXPECT_TRUE(TRes.subtypeOf(TOptRes));
EXPECT_TRUE(TInitNull.subtypeOf(TOptRes));
EXPECT_TRUE(!TUninit.subtypeOf(TOptRes));
for (auto& t : optionals) EXPECT_EQ(t, opt(unopt(t)));
for (auto& t : optionals) EXPECT_TRUE(is_opt(t));
for (auto& t : all()) {
auto const found =
std::find(begin(optionals), end(optionals), t) != end(optionals);
EXPECT_EQ(found, is_opt(t));
}
EXPECT_TRUE(is_opt(opt(sval(s_test.get()))));
EXPECT_TRUE(is_opt(opt(ival(2))));
EXPECT_TRUE(is_opt(opt(dval(2.0))));
EXPECT_FALSE(is_opt(sval(s_test.get())));
EXPECT_FALSE(is_opt(ival(2)));
EXPECT_FALSE(is_opt(dval(2.0)));
EXPECT_TRUE(wait_handle(index, opt(dval(2.0))).couldBe(
wait_handle(index, dval(2.0))));
}
TEST(Type, Num) {
EXPECT_EQ(union_of(TInt, TDbl), TNum);
EXPECT_EQ(union_of(ival(2), dval(1.0)), TNum);
EXPECT_EQ(union_of(TInt, dval(1.0)), TNum);
}
TEST(Type, OptUnionOf) {
EXPECT_EQ(opt(ival(2)), union_of(ival(2), TInitNull));
EXPECT_EQ(opt(dval(2.0)), union_of(TInitNull, dval(2.0)));
EXPECT_EQ(opt(sval(s_test.get())), union_of(sval(s_test.get()), TInitNull));
EXPECT_EQ(opt(sval(s_test.get())), union_of(TInitNull, sval(s_test.get())));
EXPECT_EQ(TOptBool, union_of(TOptFalse, TOptTrue));
EXPECT_EQ(TOptBool, union_of(TOptTrue, TOptFalse));
EXPECT_EQ(TOptCArr, union_of(TCArr, TInitNull));
EXPECT_EQ(TOptCArr, union_of(TInitNull, TCArr));
EXPECT_EQ(TOptSArr, union_of(TInitNull, TOptSArr));
EXPECT_EQ(TOptSArr, union_of(TOptSArr, TInitNull));
EXPECT_EQ(TOptArr, union_of(TOptArr, TInitNull));
EXPECT_EQ(TOptArr, union_of(TInitNull, TOptArr));
EXPECT_EQ(TInitUnc, union_of(TOptSArr, TSStr));
EXPECT_EQ(TInitUnc, union_of(TSStr, TOptSArr));
EXPECT_EQ(TOptSStr,
union_of(opt(sval(s_test.get())), opt(sval(s_TestClass.get()))));
EXPECT_EQ(TOptInt, union_of(opt(ival(2)), opt(ival(3))));
EXPECT_EQ(TOptDbl, union_of(opt(dval(2.0)), opt(dval(3.0))));
EXPECT_EQ(TOptNum, union_of(TInitNull, TNum));
EXPECT_EQ(TOptNum, union_of(TInitNull, union_of(dval(1), ival(0))));
auto const program = make_program();
Index index { borrow(program) };
auto const rcls = index.builtin_class(s_WaitHandle.get());
EXPECT_TRUE(union_of(TObj, opt(objExact(rcls))) == TOptObj);
}
TEST(Type, OptTV) {
EXPECT_TRUE(!tv(opt(ival(2))));
EXPECT_TRUE(!tv(opt(sval(s_test.get()))));
EXPECT_TRUE(!tv(opt(dval(2.0))));
EXPECT_TRUE(!tv(TOptFalse));
EXPECT_TRUE(!tv(TOptTrue));
for (auto& x : optionals) {
EXPECT_TRUE(!tv(x));
}
}
TEST(Type, OptCouldBe) {
for (auto& x : optionals) EXPECT_TRUE(x.couldBe(unopt(x)));
auto true_cases = std::initializer_list<std::pair<Type,Type>> {
{ opt(sval(s_test.get())), TStr },
{ opt(sval(s_test.get())), TInitNull },
{ opt(sval(s_test.get())), TSStr },
{ opt(sval(s_test.get())), sval(s_test.get()) },
{ opt(ival(2)), TInt },
{ opt(ival(2)), TInitNull },
{ opt(ival(2)), ival(2) },
{ opt(dval(2.0)), TDbl },
{ opt(dval(2.0)), TInitNull },
{ opt(dval(2.0)), dval(2) },
{ opt(TFalse), TBool },
{ opt(TFalse), TFalse },
{ opt(TTrue), TBool },
{ opt(TTrue), TTrue },
{ opt(TDbl), opt(TNum) },
{ TDbl, opt(TNum) },
{ TNum, opt(TDbl) },
{ opt(TInt), TNum },
{ TInt, opt(TNum) },
{ opt(TDbl), TNum },
};
auto false_cases = std::initializer_list<std::pair<Type,Type>> {
{ opt(sval(s_test.get())), TCStr },
{ opt(ival(2)), TDbl },
{ opt(dval(2.0)), TInt },
{ opt(TFalse), TTrue },
{ opt(TTrue), TFalse },
{ TFalse, opt(TNum) },
};
for (auto kv : true_cases) {
EXPECT_TRUE(kv.first.couldBe(kv.second))
<< show(kv.first) << " couldBe " << show(kv.second)
<< " should be true";
}
for (auto kv : false_cases) {
EXPECT_TRUE(!kv.first.couldBe(kv.second))
<< show(kv.first) << " couldBe " << show(kv.second)
<< " should be false";
}
for (auto kv : boost::join(true_cases, false_cases)) {
EXPECT_EQ(kv.first.couldBe(kv.second), kv.second.couldBe(kv.first))
<< show(kv.first) << " couldBe " << show(kv.second)
<< " wasn't reflexive";
}
for (auto& x : optionals) {
EXPECT_TRUE(x.couldBe(unopt(x)));
EXPECT_TRUE(x.couldBe(TInitNull));
EXPECT_TRUE(!x.couldBe(TUninit));
for (auto& y : optionals) {
EXPECT_TRUE(x.couldBe(y));
}
}
}
TEST(Type, Ref) {
EXPECT_TRUE(TRef == TRef);
EXPECT_TRUE(TRef != ref_to(TInt));
EXPECT_TRUE(ref_to(TInt) == ref_to(TInt));
EXPECT_TRUE(ref_to(TInt) != ref_to(TOptInt));
EXPECT_TRUE(TRef.couldBe(ref_to(TInt)));
EXPECT_TRUE(ref_to(TInt).couldBe(TRef));
EXPECT_TRUE(!ref_to(TInt).couldBe(ref_to(TObj)));
EXPECT_TRUE(ref_to(TOptInt).couldBe(ref_to(TInt)));
EXPECT_TRUE(!TRef.subtypeOf(ref_to(TInt)));
EXPECT_TRUE(ref_to(TInt).subtypeOf(TRef));
EXPECT_TRUE(ref_to(TInt).subtypeOf(ref_to(TOptInt)));
EXPECT_TRUE(!ref_to(TOptInt).subtypeOf(ref_to(TInt)));
EXPECT_TRUE(!ref_to(TObj).subtypeOf(ref_to(TInt)));
EXPECT_TRUE(!ref_to(TInt).subtypeOf(ref_to(TObj)));
EXPECT_TRUE(union_of(TRef, ref_to(TInt)) == TRef);
EXPECT_TRUE(union_of(ref_to(TInt), ref_to(TObj)) == ref_to(TInitCell));
EXPECT_TRUE(union_of(ref_to(TInitNull), ref_to(TObj)) == ref_to(TOptObj));
}
TEST(Type, SpecificExamples) {
// Random examples to stress option types, values, etc:
EXPECT_TRUE(!TInt.subtypeOf(ival(1)));
EXPECT_TRUE(TInitCell.couldBe(ival(1)));
EXPECT_TRUE(TInitCell.subtypeOf(TGen));
EXPECT_TRUE(ival(2).subtypeOf(TInt));
EXPECT_TRUE(!ival(2).subtypeOf(TBool));
EXPECT_TRUE(ival(3).subtypeOf(TOptInt));
EXPECT_TRUE(TInt.subtypeOf(TOptInt));
EXPECT_TRUE(!TBool.subtypeOf(TOptInt));
EXPECT_TRUE(TInitNull.subtypeOf(TOptInt));
EXPECT_TRUE(!TNull.subtypeOf(TOptInt));
EXPECT_TRUE(TNull.couldBe(TOptInt));
EXPECT_TRUE(TNull.couldBe(TOptBool));
EXPECT_TRUE(TInitNull.subtypeOf(TInitCell));
EXPECT_TRUE(TInitNull.subtypeOf(TCell));
EXPECT_TRUE(!TUninit.subtypeOf(TInitNull));
EXPECT_TRUE(ival(3).subtypeOf(TOptInt));
EXPECT_TRUE(ival(3).subtypeOf(opt(ival(3))));
EXPECT_TRUE(ival(3).couldBe(opt(ival(3))));
EXPECT_TRUE(ival(3).couldBe(TInt));
EXPECT_TRUE(TInitNull.couldBe(opt(ival(3))));
EXPECT_TRUE(TNull.couldBe(opt(ival(3))));
EXPECT_TRUE(TInitNull.subtypeOf(opt(ival(3))));
EXPECT_TRUE(!TNull.subtypeOf(opt(ival(3))));
EXPECT_EQ(TStr, union_of(sval(s_test.get()), TCStr));
EXPECT_EQ(TStr, union_of(TCStr, sval(s_test.get())));
EXPECT_EQ(TGen, union_of(TRef, TUninit));
}
TEST(Type, IndexBased) {
auto const program = make_program();
auto const unit = borrow(program->units.back());
auto const func = [&]() -> borrowed_ptr<php::Func> {
for (auto& f : unit->funcs) {
if (f->name->isame(s_test.get())) return borrow(f);
}
return nullptr;
}();
EXPECT_TRUE(func != nullptr);
auto const ctx = Context { unit, func };
Index idx{borrow(program)};
auto const cls = idx.resolve_class(ctx, s_TestClass.get());
if (!cls) EXPECT_TRUE(false);
auto const clsBase = idx.resolve_class(ctx, s_Base.get());
if (!clsBase) EXPECT_TRUE(false);
auto const objExactTy = objExact(*cls);
auto const subObjTy = subObj(*cls);
auto const clsExactTy = clsExact(*cls);
auto const subClsTy = subCls(*cls);
auto const objExactBaseTy = objExact(*clsBase);
auto const subObjBaseTy = subObj(*clsBase);
// Basic relationship between the class types and object types.
EXPECT_EQ(objcls(objExactTy), clsExactTy);
EXPECT_EQ(objcls(subObjTy), subClsTy);
// =TestClass <: <=TestClass, and not vice versa.
EXPECT_TRUE(objExactTy.subtypeOf(subObjTy));
EXPECT_TRUE(!subObjTy.subtypeOf(objExactTy));
// =TestClass <: <=TestClass, and not vice versa.
EXPECT_TRUE(clsExactTy.subtypeOf(subClsTy));
EXPECT_TRUE(!subClsTy.subtypeOf(clsExactTy));
// =TestClass couldBe <= TestClass, and vice versa.
EXPECT_TRUE(objExactTy.couldBe(subObjTy));
EXPECT_TRUE(subObjTy.couldBe(objExactTy));
EXPECT_TRUE(clsExactTy.couldBe(subClsTy));
EXPECT_TRUE(subClsTy.couldBe(clsExactTy));
// Foo= and Foo<= are both subtypes of Foo, and couldBe Foo.
EXPECT_TRUE(objExactTy.subtypeOf(TObj));
EXPECT_TRUE(subObjTy.subtypeOf(TObj));
EXPECT_TRUE(objExactTy.couldBe(TObj));
EXPECT_TRUE(subObjTy.couldBe(TObj));
EXPECT_TRUE(TObj.couldBe(objExactTy));
EXPECT_TRUE(TObj.couldBe(subObjTy));
EXPECT_TRUE(clsExactTy.subtypeOf(TCls));
EXPECT_TRUE(subClsTy.subtypeOf(TCls));
EXPECT_TRUE(clsExactTy.couldBe(TCls));
EXPECT_TRUE(subClsTy.couldBe(TCls));
EXPECT_TRUE(TCls.couldBe(clsExactTy));
EXPECT_TRUE(TCls.couldBe(subClsTy));
// Obj= and Obj<= both couldBe ?Obj, and vice versa.
EXPECT_TRUE(objExactTy.couldBe(TOptObj));
EXPECT_TRUE(subObjTy.couldBe(TOptObj));
EXPECT_TRUE(TOptObj.couldBe(objExactTy));
EXPECT_TRUE(TOptObj.couldBe(subObjTy));
// Obj= and Obj<= are subtypes of ?Obj.
EXPECT_TRUE(objExactTy.subtypeOf(TOptObj));
EXPECT_TRUE(subObjTy.subtypeOf(TOptObj));
// Obj= is a subtype of ?Obj=, and also ?Obj<=.
EXPECT_TRUE(objExactTy.subtypeOf(opt(objExactTy)));
EXPECT_TRUE(objExactTy.subtypeOf(opt(subObjTy)));
EXPECT_TRUE(!opt(objExactTy).subtypeOf(objExactTy));
EXPECT_TRUE(!opt(subObjTy).subtypeOf(objExactTy));
// Obj= couldBe ?Obj= and ?Obj<=, and vice versa.
EXPECT_TRUE(objExactTy.couldBe(opt(objExactTy)));
EXPECT_TRUE(opt(objExactTy).couldBe(objExactTy));
EXPECT_TRUE(objExactTy.couldBe(opt(subObjTy)));
EXPECT_TRUE(opt(subObjTy).couldBe(objExactTy));
// Obj<= is not a subtype of ?Obj=, it is overlapping but
// potentially contains other types. (We might eventually check
// whether objects are final as part of this, but not right now.)
EXPECT_TRUE(!subObjTy.subtypeOf(opt(objExactTy)));
EXPECT_TRUE(!opt(objExactTy).subtypeOf(subObjTy));
// Obj<= couldBe ?Obj= and vice versa.
EXPECT_TRUE(subObjTy.couldBe(opt(objExactTy)));
EXPECT_TRUE(opt(objExactTy).couldBe(subObjTy));
// ?Obj<=, ?Obj=, ?Foo<= and ?Foo= couldBe each other
EXPECT_TRUE(opt(subObjTy).couldBe(opt(objExactBaseTy)));
EXPECT_TRUE(opt(objExactBaseTy).couldBe(opt(subObjTy)));
EXPECT_TRUE(opt(subObjTy).couldBe(opt(subObjBaseTy)));
EXPECT_TRUE(opt(subObjBaseTy).couldBe(opt(subObjTy)));
EXPECT_TRUE(opt(objExactTy).couldBe(opt(objExactBaseTy)));
EXPECT_TRUE(opt(objExactBaseTy).couldBe(opt(objExactTy)));
EXPECT_TRUE(opt(objExactTy).couldBe(opt(subObjBaseTy)));
EXPECT_TRUE(opt(subObjBaseTy).couldBe(opt(objExactTy)));
}
TEST(Type, Hierarchies) {
auto const program = make_program();
auto const unit = borrow(program->units.back());
auto const func = [&]() -> borrowed_ptr<php::Func> {
for (auto& f : unit->funcs) {
if (f->name->isame(s_test.get())) return borrow(f);
}
return nullptr;
}();
EXPECT_TRUE(func != nullptr);
auto const ctx = Context { unit, func };
Index idx{borrow(program)};
// load classes in hierarchy
auto const clsBase = idx.resolve_class(ctx, s_Base.get());
if (!clsBase) EXPECT_TRUE(false);
auto const clsA = idx.resolve_class(ctx, s_A.get());
if (!clsA) EXPECT_TRUE(false);
auto const clsB = idx.resolve_class(ctx, s_B.get());
if (!clsB) EXPECT_TRUE(false);
auto const clsAA = idx.resolve_class(ctx, s_AA.get());
if (!clsAA) EXPECT_TRUE(false);
auto const clsAB = idx.resolve_class(ctx, s_AB.get());
if (!clsAB) EXPECT_TRUE(false);
auto const clsBA = idx.resolve_class(ctx, s_BA.get());
if (!clsBA) EXPECT_TRUE(false);
auto const clsBB = idx.resolve_class(ctx, s_BB.get());
if (!clsBB) EXPECT_TRUE(false);
auto const clsBAA = idx.resolve_class(ctx, s_BAA.get());
if (!clsBAA) EXPECT_TRUE(false);
auto const clsTestClass = idx.resolve_class(ctx, s_TestClass.get());
if (!clsTestClass) EXPECT_TRUE(false);
auto const clsNonUnique = idx.resolve_class(ctx, s_NonUnique.get());
if (!clsNonUnique) EXPECT_TRUE(false);
// make *exact type* and *sub type* types and objects for all loaded classes
auto const objExactBaseTy = objExact(*clsBase);
auto const subObjBaseTy = subObj(*clsBase);
auto const clsExactBaseTy = clsExact(*clsBase);
auto const subClsBaseTy = subCls(*clsBase);
auto const objExactATy = objExact(*clsA);
auto const subObjATy = subObj(*clsA);
auto const clsExactATy = clsExact(*clsA);
auto const subClsATy = subCls(*clsA);
auto const objExactAATy = objExact(*clsAA);
auto const subObjAATy = subObj(*clsAA);
auto const clsExactAATy = clsExact(*clsAA);
auto const subClsAATy = subCls(*clsAA);
auto const objExactABTy = objExact(*clsAB);
auto const subObjABTy = subObj(*clsAB);
auto const clsExactABTy = clsExact(*clsAB);
auto const subClsABTy = subCls(*clsAB);
auto const objExactBTy = objExact(*clsB);
auto const subObjBTy = subObj(*clsB);
auto const clsExactBTy = clsExact(*clsB);
auto const subClsBTy = subCls(*clsB);
auto const objExactBATy = objExact(*clsBA);
auto const subObjBATy = subObj(*clsBA);
auto const clsExactBATy = clsExact(*clsBA);
auto const subClsBATy = subCls(*clsBA);
auto const objExactBBTy = objExact(*clsBB);
auto const subObjBBTy = subObj(*clsBB);
auto const clsExactBBTy = clsExact(*clsBB);
auto const subClsBBTy = subCls(*clsBB);
auto const objExactBAATy = objExact(*clsBAA);
auto const subObjBAATy = subObj(*clsBAA);
auto const clsExactBAATy = clsExact(*clsBAA);
auto const subClsBAATy = subCls(*clsBAA);
auto const objExactTestClassTy = objExact(*clsTestClass);
auto const subObjTestClassTy = subObj(*clsTestClass);
auto const clsExactTestClassTy = clsExact(*clsTestClass);
auto const subClsTestClassTy = subCls(*clsTestClass);
auto const objExactNonUniqueTy = objExact(*clsNonUnique);
auto const subObjNonUniqueTy = subObj(*clsNonUnique);
auto const clsExactNonUniqueTy = clsExact(*clsNonUnique);
auto const subClsNonUniqueTy = subCls(*clsNonUnique);
// check that type from object and type are the same (obnoxious test)
EXPECT_EQ(objcls(objExactBaseTy), clsExactBaseTy);
EXPECT_EQ(objcls(subObjBaseTy), subClsBaseTy);
EXPECT_EQ(objcls(objExactATy), clsExactATy);
EXPECT_EQ(objcls(subObjATy), subClsATy);
EXPECT_EQ(objcls(objExactAATy), clsExactAATy);
EXPECT_EQ(objcls(subObjAATy), subClsAATy);
EXPECT_EQ(objcls(objExactABTy), clsExactABTy);
EXPECT_EQ(objcls(subObjABTy), subClsABTy);
EXPECT_EQ(objcls(objExactBTy), clsExactBTy);
EXPECT_EQ(objcls(subObjBTy), subClsBTy);
EXPECT_EQ(objcls(objExactBATy), clsExactBATy);
EXPECT_EQ(objcls(subObjBATy), subClsBATy);
EXPECT_EQ(objcls(objExactBBTy), clsExactBBTy);
EXPECT_EQ(objcls(subObjBBTy), subClsBBTy);
EXPECT_EQ(objcls(objExactBAATy), clsExactBAATy);
EXPECT_EQ(objcls(subObjBAATy), subClsBAATy);
// both subobj(A) and subcls(A) of no_override class A change to exact types
EXPECT_EQ(objcls(objExactABTy), subClsABTy);
EXPECT_EQ(objcls(subObjABTy), clsExactABTy);
// a T= is a subtype of itself but not a strict subtype
// also a T= is in a "could be" relationship with itself.
EXPECT_TRUE(objcls(objExactBaseTy).subtypeOf(clsExactBaseTy));
EXPECT_FALSE(objcls(objExactBaseTy).strictSubtypeOf(objcls(objExactBaseTy)));
EXPECT_TRUE(objcls(objExactBAATy).subtypeOf(clsExactBAATy));
EXPECT_FALSE(clsExactBAATy.strictSubtypeOf(objcls(objExactBAATy)));
EXPECT_TRUE(clsExactBAATy.couldBe(clsExactBAATy));
// Given the hierarchy A <- B <- C where A is the base then:
// B= is not in any subtype relationshipt with a A= or C=.
// Neither they are in "could be" relationships.
// Overall T= sets are always disjoint.
EXPECT_FALSE(objcls(objExactBATy).subtypeOf(clsExactBaseTy));
EXPECT_FALSE(objcls(objExactBATy).subtypeOf(clsExactBTy));
EXPECT_FALSE(objcls(objExactBATy).subtypeOf(clsExactBAATy));
EXPECT_FALSE(clsExactBATy.strictSubtypeOf(objcls(objExactBaseTy)));
EXPECT_FALSE(clsExactBATy.strictSubtypeOf(objcls(objExactBTy)));
EXPECT_FALSE(clsExactBATy.strictSubtypeOf(objcls(objExactBAATy)));
EXPECT_FALSE(clsExactBATy.couldBe(objcls(objExactBaseTy)));
EXPECT_FALSE(objcls(objExactBATy).couldBe(clsExactBTy));
EXPECT_FALSE(clsExactBATy.couldBe(objcls(objExactBAATy)));
// any T= is both a subtype and strict subtype of T<=.
// Given the hierarchy A <- B <- C where A is the base then:
// C= is a subtype and a strict subtype of B<=, ?B<=, A<= and ?A<=.
// The "could be" relationship also holds.
EXPECT_TRUE(objcls(objExactATy).subtypeOf(subClsATy));
EXPECT_TRUE(objcls(objExactBAATy).subtypeOf(subClsBaseTy));
EXPECT_TRUE(objExactBAATy.subtypeOf(opt(subObjBaseTy)));
EXPECT_TRUE(objcls(objExactBAATy).subtypeOf(subClsBTy));
EXPECT_TRUE(objExactBAATy.subtypeOf(opt(subObjBTy)));
EXPECT_TRUE(clsExactBAATy.subtypeOf(objcls(subObjBATy)));
EXPECT_TRUE(objExactBAATy.subtypeOf(opt(subObjBATy)));
EXPECT_TRUE(clsExactBAATy.subtypeOf(objcls(subObjBAATy)));
EXPECT_TRUE(objExactBAATy.subtypeOf(opt(subObjBAATy)));
EXPECT_TRUE(objcls(objExactATy).strictSubtypeOf(subClsATy));
EXPECT_TRUE(objcls(objExactBAATy).strictSubtypeOf(subClsBaseTy));
EXPECT_TRUE(objExactBAATy.strictSubtypeOf(opt(subObjBaseTy)));
EXPECT_TRUE(objcls(objExactBAATy).strictSubtypeOf(subClsBTy));
EXPECT_TRUE(objExactBAATy.strictSubtypeOf(opt(subObjBTy)));
EXPECT_TRUE(clsExactBAATy.strictSubtypeOf(objcls(subObjBATy)));
EXPECT_TRUE(objExactBAATy.strictSubtypeOf(opt(subObjBATy)));
EXPECT_TRUE(clsExactBAATy.strictSubtypeOf(objcls(subObjBAATy)));
EXPECT_TRUE(objExactBAATy.strictSubtypeOf(opt(subObjBAATy)));
EXPECT_TRUE(objcls(objExactATy).couldBe(subClsATy));
EXPECT_TRUE(objcls(objExactBAATy).couldBe(subClsBaseTy));
EXPECT_TRUE(objExactBAATy.couldBe(opt(subObjBaseTy)));
EXPECT_TRUE(objcls(objExactBAATy).couldBe(subClsBTy));
EXPECT_TRUE(objExactBAATy.couldBe(opt(subObjBTy)));
EXPECT_TRUE(clsExactBAATy.couldBe(objcls(subObjBATy)));
EXPECT_TRUE(objExactBAATy.couldBe(opt(subObjBATy)));
EXPECT_TRUE(clsExactBAATy.couldBe(objcls(subObjBAATy)));
EXPECT_TRUE(objExactBAATy.couldBe(opt(subObjBAATy)));
// a T<= is a subtype of itself but not a strict subtype
// also a T<= is in a "could be" relationship with itself
EXPECT_TRUE(objcls(subObjBaseTy).subtypeOf(subClsBaseTy));
EXPECT_FALSE(objcls(subObjBaseTy).strictSubtypeOf(objcls(subObjBaseTy)));
EXPECT_TRUE(objcls(subObjBAATy).subtypeOf(subClsBAATy));
EXPECT_FALSE(subClsBAATy.strictSubtypeOf(objcls(subObjBAATy)));
EXPECT_TRUE(subClsBAATy.couldBe(subClsBAATy));
// a T<= type is in no subtype relationship with T=.
// However a T<= is in a "could be" relationship with T=.
EXPECT_FALSE(objcls(subObjATy).subtypeOf(clsExactATy));
EXPECT_FALSE(objcls(subObjATy).strictSubtypeOf(clsExactATy));
EXPECT_TRUE(clsExactATy.couldBe(objcls(subObjATy)));
// Given 2 types A and B in no inheritance relationship then
// A<= and B<= are in no subtype or "could be" relationship.
// Same if one of the 2 types is an optional type
EXPECT_FALSE(objcls(subObjATy).subtypeOf(clsExactBTy));
EXPECT_FALSE(objcls(subObjATy).strictSubtypeOf(clsExactBTy));
EXPECT_FALSE(subObjATy.subtypeOf(opt(objExactBTy)));
EXPECT_FALSE(subObjATy.strictSubtypeOf(opt(objExactBTy)));
EXPECT_FALSE(clsExactATy.couldBe(objcls(subObjBTy)));
EXPECT_FALSE(objExactATy.couldBe(opt(subObjBTy)));
EXPECT_FALSE(objcls(subObjBTy).subtypeOf(clsExactATy));
EXPECT_FALSE(subObjBTy.subtypeOf(opt(objExactATy)));
EXPECT_FALSE(objcls(subObjBTy).strictSubtypeOf(clsExactATy));
EXPECT_FALSE(subObjBTy.strictSubtypeOf(opt(objExactATy)));
EXPECT_FALSE(clsExactBTy.couldBe(objcls(subObjATy)));
EXPECT_FALSE(objExactBTy.couldBe(opt(subObjATy)));
// Given the hierarchy A <- B <- C where A is the base then:
// C<= is a subtype and a strict subtype of B<=, ?B<=, A<= and ?A<=.
// It is also in a "could be" relationship with all its ancestors
// (including optional)
EXPECT_TRUE(objcls(subObjBAATy).subtypeOf(subClsBaseTy));
EXPECT_TRUE(subObjBAATy.subtypeOf(opt(subObjBaseTy)));
EXPECT_TRUE(objcls(subObjBAATy).subtypeOf(subClsBTy));
EXPECT_TRUE(subObjBAATy.subtypeOf(opt(subObjBTy)));
EXPECT_TRUE(subClsBAATy.subtypeOf(objcls(subObjBATy)));
EXPECT_TRUE(subObjBAATy.subtypeOf(opt(subObjBATy)));
EXPECT_TRUE(objcls(subObjBAATy).strictSubtypeOf(subClsBaseTy));
EXPECT_TRUE(subObjBAATy.strictSubtypeOf(opt(subObjBaseTy)));
EXPECT_TRUE(objcls(subObjBAATy).strictSubtypeOf(subClsBTy));
EXPECT_TRUE(subObjBAATy.strictSubtypeOf(opt(subObjBTy)));
EXPECT_TRUE(subClsBAATy.strictSubtypeOf(objcls(subObjBATy)));
EXPECT_TRUE(subObjBAATy.strictSubtypeOf(opt(subObjBATy)));
EXPECT_TRUE(objcls(subObjBAATy).couldBe(subClsBaseTy));
EXPECT_TRUE(subObjBAATy.couldBe(opt(subObjBaseTy)));
EXPECT_TRUE(objcls(subObjBAATy).couldBe(subClsBTy));
EXPECT_TRUE(subObjBAATy.couldBe(opt(subObjBTy)));
EXPECT_TRUE(subClsBAATy.couldBe(objcls(subObjBATy)));
EXPECT_TRUE(subObjBAATy.couldBe(opt(subObjBATy)));
// Given the hierarchy A <- B <- C where A is the base then:
// A<= is not in a subtype neither a strict subtype with B<=, ?B<=, A<=
// ?A<=. However A<= is in a "could be" relationship with all its
// children (including optional)
EXPECT_FALSE(objcls(subObjBaseTy).subtypeOf(subClsATy));
EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjATy)));
EXPECT_FALSE(objcls(subObjBaseTy).subtypeOf(subClsBTy));
EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjBTy)));
EXPECT_FALSE(subClsBaseTy.subtypeOf(objcls(subObjAATy)));
EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjAATy)));
EXPECT_FALSE(subClsBaseTy.subtypeOf(objcls(subObjABTy)));
EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjABTy)));
EXPECT_FALSE(objcls(subObjBaseTy).subtypeOf(subClsBATy));
EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjBATy)));
EXPECT_FALSE(subClsBaseTy.subtypeOf(objcls(subObjBBTy)));
EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjBBTy)));
EXPECT_FALSE(subClsBaseTy.subtypeOf(objcls(subObjBAATy)));
EXPECT_FALSE(subObjBaseTy.subtypeOf(opt(subObjBAATy)));
EXPECT_FALSE(objcls(subObjBaseTy).strictSubtypeOf(subClsATy));
EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjATy)));
EXPECT_FALSE(objcls(subObjBaseTy).strictSubtypeOf(subClsBTy));
EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjBTy)));
EXPECT_FALSE(subClsBaseTy.strictSubtypeOf(objcls(subObjAATy)));
EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjAATy)));
EXPECT_FALSE(subClsBaseTy.strictSubtypeOf(objcls(subObjABTy)));
EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjABTy)));
EXPECT_FALSE(objcls(subObjBaseTy).strictSubtypeOf(subClsBATy));
EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjBATy)));
EXPECT_FALSE(subClsBaseTy.strictSubtypeOf(objcls(subObjBBTy)));
EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjBBTy)));
EXPECT_FALSE(subClsBaseTy.strictSubtypeOf(objcls(subObjBAATy)));
EXPECT_FALSE(subObjBaseTy.strictSubtypeOf(opt(subObjBAATy)));
EXPECT_TRUE(objcls(subObjBaseTy).couldBe(subClsATy));
EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjATy)));
EXPECT_TRUE(objcls(subObjBaseTy).couldBe(subClsBTy));
EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjBTy)));
EXPECT_TRUE(subClsBaseTy.couldBe(objcls(subObjAATy)));
EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjAATy)));
EXPECT_TRUE(subClsBaseTy.couldBe(objcls(subObjABTy)));
EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjABTy)));
EXPECT_TRUE(objcls(subObjBaseTy).couldBe(subClsBATy));
EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjBATy)));
EXPECT_TRUE(subClsBaseTy.couldBe(objcls(subObjBBTy)));
EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjBBTy)));
EXPECT_TRUE(subClsBaseTy.couldBe(objcls(subObjBAATy)));
EXPECT_TRUE(subObjBaseTy.couldBe(opt(subObjBAATy)));
// check union_of and commonAncestor API
EXPECT_TRUE((*(*clsA).commonAncestor(*clsB)).same(*clsBase));
EXPECT_TRUE((*(*clsB).commonAncestor(*clsA)).same(*clsBase));
EXPECT_TRUE((*(*clsAA).commonAncestor(*clsAB)).same(*clsA));
EXPECT_TRUE((*(*clsAB).commonAncestor(*clsAA)).same(*clsA));
EXPECT_TRUE((*(*clsA).commonAncestor(*clsBAA)).same(*clsBase));
EXPECT_TRUE((*(*clsBAA).commonAncestor(*clsA)).same(*clsBase));
EXPECT_TRUE((*(*clsBAA).commonAncestor(*clsB)).same(*clsB));
EXPECT_TRUE((*(*clsB).commonAncestor(*clsBAA)).same(*clsB));
EXPECT_TRUE((*(*clsBAA).commonAncestor(*clsBB)).same(*clsB));
EXPECT_TRUE((*(*clsBB).commonAncestor(*clsBAA)).same(*clsB));
EXPECT_TRUE((*(*clsAA).commonAncestor(*clsBase)).same(*clsBase));
EXPECT_TRUE((*(*clsBase).commonAncestor(*clsAA)).same(*clsBase));
EXPECT_FALSE((*clsAA).commonAncestor(*clsTestClass));
EXPECT_FALSE((*clsTestClass).commonAncestor(*clsAA));
EXPECT_FALSE((*clsBAA).commonAncestor(*clsNonUnique));
EXPECT_FALSE((*clsNonUnique).commonAncestor(*clsBAA));
// check union_of
// union of subCls
EXPECT_EQ(union_of(subClsATy, subClsBTy), subClsBaseTy);
EXPECT_EQ(union_of(subClsAATy, subClsABTy), subClsATy);
EXPECT_EQ(union_of(subClsATy, subClsBAATy), subClsBaseTy);
EXPECT_EQ(union_of(subClsBAATy, subClsBTy), subClsBTy);
EXPECT_EQ(union_of(subClsBAATy, subClsBBTy), subClsBTy);
EXPECT_EQ(union_of(subClsAATy, subClsBaseTy), subClsBaseTy);
EXPECT_EQ(union_of(subClsAATy, subClsTestClassTy), TCls);
EXPECT_EQ(union_of(subClsBAATy, subClsNonUniqueTy), TCls);
// union of subCls and clsExact mixed
EXPECT_EQ(union_of(clsExactATy, subClsBTy), subClsBaseTy);
EXPECT_EQ(union_of(subClsAATy, clsExactABTy), subClsATy);
EXPECT_EQ(union_of(clsExactATy, subClsBAATy), subClsBaseTy);
EXPECT_EQ(union_of(subClsBAATy, clsExactBTy), subClsBTy);
EXPECT_EQ(union_of(clsExactBAATy, subClsBBTy), subClsBTy);
EXPECT_EQ(union_of(subClsAATy, clsExactBaseTy), subClsBaseTy);
EXPECT_EQ(union_of(clsExactAATy, subClsTestClassTy), TCls);
EXPECT_EQ(union_of(subClsBAATy, clsExactNonUniqueTy), TCls);
// union of clsExact
EXPECT_EQ(union_of(clsExactATy, clsExactBTy), subClsBaseTy);
EXPECT_EQ(union_of(clsExactAATy, clsExactABTy), subClsATy);
EXPECT_EQ(union_of(clsExactATy, clsExactBAATy), subClsBaseTy);
EXPECT_EQ(union_of(clsExactBAATy, clsExactBTy), subClsBTy);
EXPECT_EQ(union_of(clsExactBAATy, clsExactBBTy), subClsBTy);
EXPECT_EQ(union_of(clsExactAATy, clsExactBaseTy), subClsBaseTy);
EXPECT_EQ(union_of(clsExactAATy, subClsTestClassTy), TCls);
EXPECT_EQ(union_of(clsExactBAATy, clsExactNonUniqueTy), TCls);
// union of subObj
EXPECT_EQ(union_of(subObjATy, subObjBTy), subObjBaseTy);
EXPECT_EQ(union_of(subObjAATy, subObjABTy), subObjATy);
EXPECT_EQ(union_of(subObjATy, subObjBAATy), subObjBaseTy);
EXPECT_EQ(union_of(subObjBAATy, subObjBTy), subObjBTy);
EXPECT_EQ(union_of(subObjBAATy, subObjBBTy), subObjBTy);
EXPECT_EQ(union_of(subObjAATy, subObjBaseTy), subObjBaseTy);
EXPECT_EQ(union_of(subObjAATy, subObjTestClassTy), TObj);
EXPECT_EQ(union_of(subObjBAATy, subObjNonUniqueTy), TObj);
// union of subObj and objExact mixed
EXPECT_EQ(union_of(objExactATy, subObjBTy), subObjBaseTy);
EXPECT_EQ(union_of(subObjAATy, objExactABTy), subObjATy);
EXPECT_EQ(union_of(objExactATy, subObjBAATy), subObjBaseTy);
EXPECT_EQ(union_of(subObjBAATy, objExactBTy), subObjBTy);
EXPECT_EQ(union_of(objExactBAATy, subObjBBTy), subObjBTy);
EXPECT_EQ(union_of(subObjAATy, objExactBaseTy), subObjBaseTy);
EXPECT_EQ(union_of(objExactAATy, subObjTestClassTy), TObj);
EXPECT_EQ(union_of(subObjBAATy, objExactNonUniqueTy), TObj);
// union of objExact
EXPECT_EQ(union_of(objExactATy, objExactBTy), subObjBaseTy);
EXPECT_EQ(union_of(objExactAATy, objExactABTy), subObjATy);
EXPECT_EQ(union_of(objExactATy, objExactBAATy), subObjBaseTy);
EXPECT_EQ(union_of(objExactBAATy, objExactBTy), subObjBTy);
EXPECT_EQ(union_of(objExactBAATy, objExactBBTy), subObjBTy);
EXPECT_EQ(union_of(objExactAATy, objExactBaseTy), subObjBaseTy);
EXPECT_EQ(union_of(objExactAATy, objExactTestClassTy), TObj);
EXPECT_EQ(union_of(objExactBAATy, objExactNonUniqueTy), TObj);
// optional sub obj
EXPECT_EQ(union_of(opt(subObjATy), opt(subObjBTy)), opt(subObjBaseTy));
EXPECT_EQ(union_of(subObjAATy, opt(subObjABTy)), opt(subObjATy));
EXPECT_EQ(union_of(opt(subObjATy), subObjBAATy), opt(subObjBaseTy));
EXPECT_EQ(union_of(opt(subObjBAATy), opt(subObjBTy)), opt(subObjBTy));
EXPECT_EQ(union_of(opt(subObjBAATy), subObjBBTy), opt(subObjBTy));
EXPECT_EQ(union_of(opt(subObjAATy), opt(subObjBaseTy)), opt(subObjBaseTy));
EXPECT_EQ(union_of(subObjAATy, opt(subObjTestClassTy)), opt(TObj));
EXPECT_EQ(union_of(subObjBAATy, opt(subObjNonUniqueTy)), opt(TObj));
// optional sub and exact obj mixed
EXPECT_EQ(union_of(opt(objExactATy), subObjBTy), opt(subObjBaseTy));
EXPECT_EQ(union_of(subObjAATy, opt(objExactABTy)), opt(subObjATy));
EXPECT_EQ(union_of(opt(objExactATy), objExactBAATy), opt(subObjBaseTy));
EXPECT_EQ(union_of(subObjBAATy, opt(objExactBTy)), opt(subObjBTy));
EXPECT_EQ(union_of(opt(subObjBAATy), objExactBBTy), opt(subObjBTy));
EXPECT_EQ(union_of(objExactAATy, opt(objExactBaseTy)), opt(subObjBaseTy));
EXPECT_EQ(union_of(opt(subObjAATy), objExactTestClassTy), opt(TObj));
EXPECT_EQ(union_of(subObjBAATy, opt(objExactNonUniqueTy)), opt(TObj));
}
TEST(Type, Interface) {
auto const program = make_program();
auto const unit = borrow(program->units.back());
auto const func = [&]() -> borrowed_ptr<php::Func> {
for (auto& f : unit->funcs) {
if (f->name->isame(s_test.get())) return borrow(f);
}
return nullptr;
}();
EXPECT_TRUE(func != nullptr);
auto const ctx = Context { unit, func };
Index idx{borrow(program)};
// load classes in hierarchy
auto const clsIA = idx.resolve_class(ctx, s_IA.get());
if (!clsIA) EXPECT_TRUE(false);
auto const clsIAA = idx.resolve_class(ctx, s_IAA.get());
if (!clsIAA) EXPECT_TRUE(false);
auto const clsA = idx.resolve_class(ctx, s_A.get());
if (!clsA) EXPECT_TRUE(false);
auto const clsAA = idx.resolve_class(ctx, s_AA.get());
if (!clsAA) EXPECT_TRUE(false);
// make sometypes and objects
auto const subObjIATy = subObj(*clsIA);
auto const subClsIATy = subCls(*clsIA);
auto const subObjIAATy = subObj(*clsIAA);
auto const subClsIAATy = subCls(*clsIAA);
auto const subObjATy = subObj(*clsA);
auto const clsExactATy = clsExact(*clsA);
auto const subClsATy = subCls(*clsA);
auto const subObjAATy = subObj(*clsAA);
auto const subClsAATy = subCls(*clsAA);
// we don't support interfaces quite yet so let's put few tests
// that will fail once interfaces are supported
// first 2 are "not precise" - should be true
EXPECT_FALSE(subClsATy.subtypeOf(objcls(subObjIATy)));
EXPECT_FALSE(objcls(subObjATy).strictSubtypeOf(subClsIATy));
EXPECT_TRUE(subClsATy.couldBe(objcls(subObjIATy)));
// first 2 are "not precise" - should be true
EXPECT_FALSE(subClsAATy.subtypeOf(objcls(subObjIAATy)));
EXPECT_FALSE(objcls(subObjAATy).strictSubtypeOf(objcls(subObjIAATy)));
EXPECT_TRUE(subClsAATy.couldBe(objcls(subObjIAATy)));
// 3rd one is not precise - should be false
EXPECT_FALSE(subClsATy.subtypeOf(objcls(subObjIAATy)));
EXPECT_FALSE(objcls(subObjATy).strictSubtypeOf(objcls(subObjIAATy)));
EXPECT_TRUE(clsExactATy.couldBe(objcls(subObjIAATy)));
}
TEST(Type, NonUnique) {
auto const program = make_program();
auto const unit = borrow(program->units.back());
auto const func = [&]() -> borrowed_ptr<php::Func> {
for (auto& f : unit->funcs) {
if (f->name->isame(s_test.get())) return borrow(f);
}
return nullptr;
}();
EXPECT_TRUE(func != nullptr);
auto const ctx = Context { unit, func };
Index idx{borrow(program)};
auto const clsA = idx.resolve_class(ctx, s_A.get());
if (!clsA) EXPECT_TRUE(false);
auto const clssNonUnique = idx.resolve_class(ctx, s_NonUnique.get());
if (!clssNonUnique) EXPECT_TRUE(false);
auto const clssNonUniqueA = idx.resolve_class(ctx, s_NonUniqueA.get());
if (!clssNonUniqueA) EXPECT_TRUE(false);
// non unique types are funny because we cannot really make any conclusion
// about them so they resolve to "non precise" subtype relationship
auto const subObjATy = subObj(*clsA);
auto const subClsATy = subCls(*clsA);
auto const subObjNonUniqueTy = subObj(*clssNonUnique);
auto const subClsNonUniqueTy = subCls(*clssNonUnique);
auto const subObjNonUniqueATy = subObj(*clssNonUniqueA);
auto const subClsNonUniqueATy = subCls(*clssNonUniqueA);
// all are obviously "non precise" but what can you do?....
EXPECT_FALSE(subClsNonUniqueATy.subtypeOf(objcls(subObjNonUniqueTy)));
EXPECT_FALSE(objcls(subObjNonUniqueATy).strictSubtypeOf(subClsNonUniqueTy));
EXPECT_TRUE(subClsATy.couldBe(objcls(subObjNonUniqueTy)));
}
TEST(Type, WaitH) {
auto const program = make_program();
Index index { borrow(program) };
for (auto& t : wait_handles_of(index, all())) {
EXPECT_TRUE(is_specialized_wait_handle(t));
EXPECT_TRUE(t.subtypeOf(wait_handle(index, TTop)));
}
// union_of(WaitH<A>, WaitH<B>) == WaitH<union_of(A, B)>
for (auto& t1 : all()) {
for (auto& t2 : all()) {
auto const u1 = union_of(t1, t2);
auto const u2 = union_of(wait_handle(index, t1), wait_handle(index, t2));
EXPECT_TRUE(is_specialized_wait_handle(u2));
EXPECT_EQ(wait_handle_inner(u2), u1);
EXPECT_EQ(wait_handle(index, u1), u2);
}
}
// union_of(?WaitH<A>, ?WaitH<B>) == ?WaitH<union_of(A, B)>
for (auto& t1 : all()) {
for (auto& t2 : all()) {
auto const w1 = opt(wait_handle(index, t1));
auto const w2 = opt(wait_handle(index, t2));
auto const u1 = union_of(w1, w2);
auto const u2 = opt(wait_handle(index, union_of(t1, t2)));
EXPECT_EQ(u1, u2);
}
}
auto const rcls = index.builtin_class(s_WaitHandle.get());
auto const twhobj = subObj(rcls);
EXPECT_TRUE(wait_handle(index, TTop).subtypeOf(twhobj));
// Some test cases with optional wait handles.
auto const optWH = opt(wait_handle(index, ival(2)));
EXPECT_TRUE(is_opt(optWH));
EXPECT_TRUE(TInitNull.subtypeOf(optWH));
EXPECT_TRUE(optWH.subtypeOf(TOptObj));
EXPECT_TRUE(optWH.subtypeOf(opt(twhobj)));
EXPECT_TRUE(wait_handle(index, ival(2)).subtypeOf(optWH));
EXPECT_FALSE(optWH.subtypeOf(wait_handle(index, ival(2))));
EXPECT_TRUE(optWH.couldBe(wait_handle(index, ival(2))));
// union_of(WaitH<T>, Obj<=WaitHandle) == Obj<=WaitHandle
for (auto& t : all()) {
auto const u = union_of(wait_handle(index, t), twhobj);
EXPECT_EQ(u, twhobj);
}
for (auto& t : all()) {
auto const u1 = union_of(wait_handle(index, t), TInitNull);
EXPECT_TRUE(is_opt(u1));
EXPECT_TRUE(is_specialized_wait_handle(u1));
auto const u2 = union_of(TInitNull, wait_handle(index, t));
EXPECT_TRUE(is_opt(u2));
EXPECT_TRUE(is_specialized_wait_handle(u2));
EXPECT_EQ(u1, u2);
}
// You can have WaitH<WaitH<T>>. And stuff.
for (auto& w : wait_handles_of(index, all())) {
auto const ww = wait_handle(index, w);
auto const www = wait_handle(index, ww);
EXPECT_EQ(wait_handle_inner(www), ww);
EXPECT_EQ(wait_handle_inner(ww), w);
// Skip the following in cases like WaitH<WaitH<Obj>>, which
// actually *is* a subtype of WaitH<Obj>, since a WaitH<Obj> is
// also an Obj. Similar for Top, or InitCell, etc.
auto const inner = wait_handle_inner(w);
if (twhobj.subtypeOf(inner)) continue;
EXPECT_FALSE(w.subtypeOf(ww));
EXPECT_FALSE(ww.subtypeOf(w));
EXPECT_FALSE(w.couldBe(ww));
EXPECT_TRUE(ww.subtypeOf(twhobj));
EXPECT_TRUE(www.subtypeOf(twhobj));
EXPECT_FALSE(ww.subtypeOf(www));
EXPECT_FALSE(www.subtypeOf(ww));
EXPECT_FALSE(ww.couldBe(www));
}
}
TEST(Type, FromHNIConstraint) {
EXPECT_EQ(from_hni_constraint(makeStaticString("?HH\\resource")), TOptRes);
EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\resource")), TRes);
EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\bool")), TBool);
EXPECT_EQ(from_hni_constraint(makeStaticString("?HH\\bool")), TOptBool);
EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\int")), TInt);
EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\float")), TDbl);
EXPECT_EQ(from_hni_constraint(makeStaticString("?HH\\float")), TOptDbl);
EXPECT_EQ(from_hni_constraint(makeStaticString("HH\\mixed")), TInitGen);
// These are conservative, but we're testing them that way. If we
// make the function better later we'll remove the tests.
EXPECT_EQ(from_hni_constraint(makeStaticString("stdClass")), TGen);
EXPECT_EQ(from_hni_constraint(makeStaticString("?stdClass")), TGen);
EXPECT_EQ(from_hni_constraint(makeStaticString("fooooo")), TGen);
EXPECT_EQ(from_hni_constraint(makeStaticString("")), TGen);
}
TEST(Type, ArrPacked1) {
auto const a1 = arr_packed({ival(2), TSStr, TInt});
auto const a2 = arr_packed({TInt, TStr, TInitCell});
auto const s1 = sarr_packed({ival(2), TSStr, TInt});
auto const s2 = sarr_packed({TInt, TStr, TInitCell});
auto const c1 = carr_packed({ival(2), TSStr, TInt});
auto const c2 = carr_packed({TInt, TStr, TInitCell});
for (auto& a : { a1, s1, c1, a2, s2, c2 }) {
EXPECT_TRUE(a.subtypeOf(TArr));
EXPECT_TRUE(a.subtypeOf(a));
EXPECT_EQ(a, a);
}
// Subtype stuff.
EXPECT_TRUE(a1.subtypeOf(TArr));
EXPECT_FALSE(a1.subtypeOf(TSArr));
EXPECT_FALSE(a1.subtypeOf(TCArr));
EXPECT_TRUE(s1.subtypeOf(TArr));
EXPECT_TRUE(s1.subtypeOf(TSArr));
EXPECT_FALSE(s1.subtypeOf(TCArr));
EXPECT_TRUE(c1.subtypeOf(TArr));
EXPECT_TRUE(c1.subtypeOf(TCArr));
EXPECT_FALSE(c1.subtypeOf(TSArr));
EXPECT_TRUE(a1.subtypeOf(a2));
EXPECT_TRUE(s1.subtypeOf(s2));
EXPECT_TRUE(c1.subtypeOf(c2));
EXPECT_TRUE(s1.subtypeOf(a1));
EXPECT_TRUE(c1.subtypeOf(a1));
EXPECT_FALSE(a1.subtypeOf(c1));
EXPECT_FALSE(s1.subtypeOf(c1));
EXPECT_FALSE(c1.subtypeOf(s1));
EXPECT_FALSE(a1.subtypeOf(c1));
// Could be stuff.
EXPECT_TRUE(c1.couldBe(a1));
EXPECT_TRUE(c2.couldBe(a2));
EXPECT_TRUE(s1.couldBe(a1));
EXPECT_TRUE(s2.couldBe(a2));
EXPECT_TRUE(a1.couldBe(a2));
EXPECT_TRUE(a2.couldBe(a1));
EXPECT_TRUE(s1.couldBe(a2));
EXPECT_TRUE(s2.couldBe(a1));
EXPECT_TRUE(c1.couldBe(a2));
EXPECT_TRUE(c2.couldBe(a1));
EXPECT_TRUE(s1.couldBe(s2));
EXPECT_TRUE(s2.couldBe(s1));
EXPECT_TRUE(c1.couldBe(c2));
EXPECT_TRUE(c2.couldBe(c1));
EXPECT_FALSE(c1.couldBe(s1));
EXPECT_FALSE(c2.couldBe(s1));
EXPECT_FALSE(c1.couldBe(s2));
EXPECT_FALSE(c2.couldBe(s2));
EXPECT_FALSE(s1.couldBe(c1));
EXPECT_FALSE(s2.couldBe(c1));
EXPECT_FALSE(s1.couldBe(c2));
EXPECT_FALSE(s2.couldBe(c2));
}
TEST(Type, OptArrPacked1) {
auto const a1 = opt(arr_packed({ival(2), TSStr, TInt}));
auto const a2 = opt(arr_packed({TInt, TStr, TInitCell}));
auto const s1 = opt(sarr_packed({ival(2), TSStr, TInt}));
auto const s2 = opt(sarr_packed({TInt, TStr, TInitCell}));
auto const c1 = opt(carr_packed({ival(2), TSStr, TInt}));
auto const c2 = opt(carr_packed({TInt, TStr, TInitCell}));
for (auto& a : { a1, s1, c1, a2, s2, c2 }) {
EXPECT_TRUE(a.subtypeOf(TOptArr));
EXPECT_TRUE(a.subtypeOf(a));
EXPECT_EQ(a, a);
}
// Subtype stuff.
EXPECT_TRUE(a1.subtypeOf(TOptArr));
EXPECT_FALSE(a1.subtypeOf(TOptSArr));
EXPECT_FALSE(a1.subtypeOf(TOptCArr));
EXPECT_TRUE(s1.subtypeOf(TOptArr));
EXPECT_TRUE(s1.subtypeOf(TOptSArr));
EXPECT_FALSE(s1.subtypeOf(TOptCArr));
EXPECT_TRUE(c1.subtypeOf(TOptArr));
EXPECT_TRUE(c1.subtypeOf(TOptCArr));
EXPECT_FALSE(c1.subtypeOf(TOptSArr));
EXPECT_TRUE(a1.subtypeOf(a2));
EXPECT_TRUE(s1.subtypeOf(s2));
EXPECT_TRUE(c1.subtypeOf(c2));
EXPECT_TRUE(s1.subtypeOf(a1));
EXPECT_TRUE(c1.subtypeOf(a1));
EXPECT_FALSE(a1.subtypeOf(c1));
EXPECT_FALSE(s1.subtypeOf(c1));
EXPECT_FALSE(c1.subtypeOf(s1));
EXPECT_FALSE(a1.subtypeOf(c1));
// Could be stuff.
EXPECT_TRUE(c1.couldBe(a1));
EXPECT_TRUE(c2.couldBe(a2));
EXPECT_TRUE(s1.couldBe(a1));
EXPECT_TRUE(s2.couldBe(a2));
EXPECT_TRUE(a1.couldBe(a2));
EXPECT_TRUE(a2.couldBe(a1));
EXPECT_TRUE(s1.couldBe(a2));
EXPECT_TRUE(s2.couldBe(a1));
EXPECT_TRUE(c1.couldBe(a2));
EXPECT_TRUE(c2.couldBe(a1));
EXPECT_TRUE(s1.couldBe(s2));
EXPECT_TRUE(s2.couldBe(s1));
EXPECT_TRUE(c1.couldBe(c2));
EXPECT_TRUE(c2.couldBe(c1));
EXPECT_TRUE(c1.couldBe(s1));
EXPECT_TRUE(c2.couldBe(s1));
EXPECT_TRUE(c1.couldBe(s2));
EXPECT_TRUE(c2.couldBe(s2));
EXPECT_TRUE(s1.couldBe(c1));
EXPECT_TRUE(s2.couldBe(c1));
EXPECT_TRUE(s1.couldBe(c2));
EXPECT_TRUE(s2.couldBe(c2));
}
TEST(Type, ArrPacked2) {
{
auto const a1 = arr_packed({TInt, TInt, TDbl});
auto const a2 = arr_packed({TInt, TInt});
EXPECT_FALSE(a1.subtypeOf(a2));
EXPECT_FALSE(a1.couldBe(a2));
}
{
auto const a1 = arr_packed({TInitCell, TInt});
auto const a2 = arr_packed({TInt, TInt});
EXPECT_TRUE(a1.couldBe(a2));
EXPECT_TRUE(a2.subtypeOf(a1));
}
{
auto const a1 = arr_packed({TInt, TInt, TInt});
auto const s1 = sarr_packed({TInt, TInt, TInt});
auto const c1 = carr_packed({TInt, TInt, TInt});
auto const s2 = aval(test_array_packed_value());
EXPECT_TRUE(s2.subtypeOf(a1));
EXPECT_TRUE(s2.subtypeOf(s1));
EXPECT_FALSE(s2.subtypeOf(c1));
EXPECT_TRUE(s2.couldBe(a1));
EXPECT_TRUE(s2.couldBe(s1));
EXPECT_FALSE(s2.couldBe(c1));
}
{
auto const s1 = sarr_packed({ival(42), ival(23), ival(12)});
auto const s2 = aval(test_array_packed_value());
auto const s3 = sarr_packed({TInt});
auto const a4 = sarr_packed({TInt});
auto const a5 = arr_packed({ival(42), ival(23), ival(12)});
auto const c6 = carr_packed({ival(42), ival(23), ival(12)});
EXPECT_TRUE(s1.subtypeOf(s2));
EXPECT_EQ(s1, s2);
EXPECT_FALSE(s2.subtypeOf(s3));
EXPECT_FALSE(s2.couldBe(s3));
EXPECT_FALSE(s2.subtypeOf(s3));
EXPECT_FALSE(s2.couldBe(s3));
EXPECT_TRUE(s2.couldBe(s1));
EXPECT_TRUE(s2.couldBe(a5));
EXPECT_TRUE(s2.subtypeOf(a5));
EXPECT_FALSE(a5.subtypeOf(s2));
EXPECT_FALSE(s2.subtypeOf(c6));
EXPECT_FALSE(c6.subtypeOf(s2));
}
}
TEST(Type, ArrPackedUnion) {
{
auto const a1 = arr_packed({TInt, TDbl});
auto const a2 = arr_packed({TDbl, TInt});
EXPECT_EQ(union_of(a1, a2), arr_packed({TNum, TNum}));
}
{
auto const s1 = sarr_packed({TInt, TDbl});
auto const s2 = sarr_packed({TDbl, TInt});
auto const c2 = carr_packed({TDbl, TInt});
EXPECT_EQ(union_of(s1, c2), arr_packed({TNum, TNum}));
EXPECT_EQ(union_of(s1, s1), s1);
EXPECT_EQ(union_of(s1, s2), sarr_packed({TNum, TNum}));
}
{
auto const s1 = sarr_packed({TInt});
auto const s2 = sarr_packed({TDbl, TDbl});
EXPECT_EQ(union_of(s1, s2), sarr_packedn(TNum));
}
{
auto const s1 = aval(test_array_packed_value());
auto const s2 = sarr_packed({TInt, TInt, TInt});
auto const s3 = sarr_packed({TInt, TNum, TInt});
auto const s4 = carr_packed({TInt, TObj, TInt});
EXPECT_EQ(union_of(s1, s2), s2);
EXPECT_EQ(union_of(s1, s3), s3);
EXPECT_EQ(union_of(s1, s4), arr_packed({TInt, TInitCell, TInt}));
}
{
auto const s1 = sarr_packed({TInt});
auto const os1 = opt(s1);
EXPECT_EQ(union_of(s1, TInitNull), os1);
EXPECT_EQ(union_of(os1, s1), os1);
EXPECT_EQ(union_of(TInitNull, s1), os1);
EXPECT_EQ(union_of(os1, os1), os1);
}
{
auto const s1 = sarr_packed({TInt});
EXPECT_EQ(union_of(s1, TObj), TInitCell);
EXPECT_EQ(union_of(s1, TCArr), TArr);
}
{
auto const s1 = aval(test_array_packed_value());
auto const s2 = aval(test_array_packed_value2());
EXPECT_EQ(union_of(s1, s2), sarr_packed({ival(42), TNum, ival(12)}));
}
}
TEST(Type, ArrPackedN) {
auto const s1 = aval(test_array_packed_value());
auto const s2 = sarr_packed({TInt, TInt});
EXPECT_EQ(union_of(s1, s2), sarr_packedn(TInt));
EXPECT_TRUE(s2.subtypeOf(sarr_packedn(TInt)));
EXPECT_FALSE(s2.subtypeOf(sarr_packedn(TDbl)));
EXPECT_TRUE(s2.subtypeOf(sarr_packedn(TNum)));
EXPECT_TRUE(s2.subtypeOf(arr_packedn(TInt)));
EXPECT_TRUE(s2.subtypeOf(opt(arr_packedn(TInt))));
EXPECT_TRUE(s2.couldBe(arr_packedn(TInt)));
EXPECT_TRUE(s2.couldBe(arr_packedn(TInitGen)));
auto const sn1 = sarr_packedn(TInt);
auto const sn2 = sarr_packedn(TInitNull);
EXPECT_EQ(union_of(sn1, sn2), sarr_packedn(TOptInt));
EXPECT_EQ(union_of(sn1, TInitNull), opt(sn1));
EXPECT_EQ(union_of(TInitNull, sn1), opt(sn1));
EXPECT_FALSE(sn2.couldBe(sn1));
EXPECT_FALSE(sn1.couldBe(sn2));
auto const sn3 = sarr_packedn(TInitCell);
EXPECT_TRUE(sn1.couldBe(sn3));
EXPECT_TRUE(sn2.couldBe(sn3));
EXPECT_TRUE(sn3.couldBe(sn1));
EXPECT_TRUE(sn3.couldBe(sn2));
EXPECT_TRUE(s2.couldBe(sn3));
EXPECT_TRUE(s2.couldBe(sn1));
EXPECT_FALSE(s2.couldBe(sn2));
EXPECT_EQ(union_of(carr_packedn(TInt), sarr_packedn(TInt)),
arr_packedn(TInt));
}
TEST(Type, ArrStruct) {
auto test_map_a = StructMap{};
test_map_a[s_test.get()] = ival(2);
auto test_map_b = StructMap{};
test_map_b[s_test.get()] = TInt;
auto test_map_c = StructMap{};
test_map_c[s_test.get()] = ival(2);
test_map_c[s_A.get()] = TInt;
test_map_c[s_B.get()] = TDbl;
auto const ta = arr_struct(test_map_a);
auto const tb = arr_struct(test_map_b);
auto const tc = arr_struct(test_map_c);
EXPECT_FALSE(ta.subtypeOf(tc));
EXPECT_FALSE(tc.subtypeOf(ta));
EXPECT_TRUE(ta.subtypeOf(tb));
EXPECT_FALSE(tb.subtypeOf(ta));
EXPECT_TRUE(ta.couldBe(tb));
EXPECT_TRUE(tb.couldBe(ta));
EXPECT_FALSE(tc.couldBe(ta));
EXPECT_FALSE(tc.couldBe(tb));
EXPECT_TRUE(ta.subtypeOf(TArr));
EXPECT_TRUE(tb.subtypeOf(TArr));
EXPECT_TRUE(tc.subtypeOf(TArr));
auto const sa = sarr_struct(test_map_a);
auto const sb = sarr_struct(test_map_b);
auto const sc = sarr_struct(test_map_c);
EXPECT_FALSE(sa.subtypeOf(sc));
EXPECT_FALSE(sc.subtypeOf(sa));
EXPECT_TRUE(sa.subtypeOf(sb));
EXPECT_FALSE(sb.subtypeOf(sa));
EXPECT_TRUE(sa.couldBe(sb));
EXPECT_TRUE(sb.couldBe(sa));
EXPECT_FALSE(sc.couldBe(sa));
EXPECT_FALSE(sc.couldBe(sb));
EXPECT_TRUE(sa.subtypeOf(TSArr));
EXPECT_TRUE(sb.subtypeOf(TSArr));
EXPECT_TRUE(sc.subtypeOf(TSArr));
auto test_map_d = StructMap{};
test_map_d[s_A.get()] = sval(s_B.get());
test_map_d[s_test.get()] = ival(12);
auto const sd = sarr_struct(test_map_d);
EXPECT_EQ(sd, aval(test_array_map_value()));
auto test_map_e = StructMap{};
test_map_e[s_A.get()] = TSStr;
test_map_e[s_test.get()] = TNum;
auto const se = sarr_struct(test_map_e);
EXPECT_TRUE(aval(test_array_map_value()).subtypeOf(se));
EXPECT_TRUE(se.couldBe(aval(test_array_map_value())));
}
TEST(Type, ArrMapN) {
auto const test_map = aval(test_array_map_value());
EXPECT_TRUE(test_map != arr_mapn(TSStr, TInitUnc));
EXPECT_TRUE(test_map.subtypeOf(arr_mapn(TSStr, TInitUnc)));
EXPECT_TRUE(test_map.subtypeOf(sarr_mapn(TSStr, TInitUnc)));
EXPECT_TRUE(!test_map.subtypeOf(carr_mapn(TSStr, TInitUnc)));
EXPECT_TRUE(sarr_packedn({TInt}).subtypeOf(arr_mapn(TInt, TInt)));
EXPECT_TRUE(sarr_packed({TInt}).subtypeOf(arr_mapn(TInt, TInt)));
auto test_map_a = StructMap{};
test_map_a[s_test.get()] = ival(2);
auto const tstruct = sarr_struct(test_map_a);
EXPECT_TRUE(tstruct.subtypeOf(arr_mapn(TSStr, ival(2))));
EXPECT_TRUE(tstruct.subtypeOf(arr_mapn(TSStr, TInt)));
EXPECT_TRUE(tstruct.subtypeOf(sarr_mapn(TSStr, TInt)));
EXPECT_TRUE(tstruct.subtypeOf(arr_mapn(TStr, TInt)));
EXPECT_TRUE(!tstruct.subtypeOf(carr_mapn(TStr, TInt)));
EXPECT_TRUE(test_map.couldBe(arr_mapn(TSStr, TInitCell)));
EXPECT_FALSE(test_map.couldBe(arr_mapn(TSStr, TCStr)));
EXPECT_FALSE(test_map.couldBe(arr_mapn(TSStr, TObj)));
EXPECT_FALSE(test_map.couldBe(aval(test_empty_array())));
EXPECT_FALSE(arr_mapn(TSStr, TInt).couldBe(aval(test_empty_array())));
EXPECT_TRUE(sarr_packedn(TInt).couldBe(sarr_mapn(TInt, TInt)));
EXPECT_FALSE(sarr_packedn(TInt).couldBe(sarr_mapn(TInt, TObj)));
EXPECT_TRUE(tstruct.couldBe(sarr_mapn(TSStr, TInt)));
EXPECT_FALSE(tstruct.couldBe(sarr_mapn(TSStr, TObj)));
EXPECT_FALSE(tstruct.couldBe(carr_mapn(TSStr, TObj)));
EXPECT_FALSE(tstruct.couldBe(carr_mapn(TSStr, TInt)));
}
TEST(Type, ArrEquivalentRepresentations) {
{
auto const simple = aval(test_array_packed_value());
auto const bulky = sarr_packed({ival(42), ival(23), ival(12)});
EXPECT_EQ(simple, bulky);
}
{
auto const simple = aval(test_array_map_value());
auto map = StructMap{};
map[s_A.get()] = sval(s_B.get());
map[s_test.get()] = ival(12);
auto const bulky = sarr_struct(map);
EXPECT_EQ(simple, bulky);
}
}
TEST(Type, ArrUnions) {
auto test_map_a = StructMap{};
test_map_a[s_test.get()] = ival(2);
auto const tstruct = sarr_struct(test_map_a);
auto test_map_b = StructMap{};
test_map_b[s_test.get()] = TInt;
auto const tstruct2 = sarr_struct(test_map_b);
auto test_map_c = StructMap{};
test_map_c[s_A.get()] = TInt;
auto const tstruct3 = sarr_struct(test_map_c);
auto test_map_d = StructMap{};
test_map_d[s_A.get()] = TInt;
test_map_d[s_test.get()] = TDbl;
auto const tstruct4 = sarr_struct(test_map_d);
auto const packed_int = arr_packedn(TInt);
EXPECT_EQ(union_of(tstruct, packed_int),
arr_mapn(union_of(TSStr, TInt), TInt));
EXPECT_EQ(union_of(tstruct, tstruct2), tstruct2);
EXPECT_EQ(union_of(tstruct, tstruct3), sarr_mapn(TSStr, TInt));
EXPECT_EQ(union_of(tstruct, tstruct4), sarr_mapn(TSStr, TNum));
EXPECT_EQ(union_of(sarr_packed({TInt, TDbl, TDbl}), sarr_packedn(TDbl)),
sarr_packedn(TNum));
EXPECT_EQ(union_of(sarr_packed({TInt, TDbl}), tstruct),
sarr_mapn(union_of(TSStr, TInt), TNum));
EXPECT_EQ(union_of(arr_mapn(TInt, TTrue), arr_mapn(TDbl, TFalse)),
arr_mapn(TNum, TBool));
auto const aval1 = aval(test_array_packed_value());
auto const aval2 = aval(test_array_packed_value3());
EXPECT_EQ(union_of(aval1, aval2), sarr_packedn(TInt));
}
TEST(Type, ArrOfArr) {
auto const t1 = arr_mapn(TSStr, arr_mapn(TInt, TSStr));
auto const t2 = arr_mapn(TSStr, TArr);
auto const t3 = arr_mapn(TSStr, arr_packedn(TSStr));
auto const t4 = arr_mapn(TSStr, arr_mapn(TSStr, TSStr));
EXPECT_TRUE(t1.subtypeOf(t2));
EXPECT_TRUE(t1.couldBe(t3));
EXPECT_FALSE(t1.subtypeOf(t3));
EXPECT_TRUE(t3.subtypeOf(t1));
EXPECT_TRUE(t3.subtypeOf(t2));
EXPECT_FALSE(t1.couldBe(t4));
EXPECT_FALSE(t4.couldBe(t3));
EXPECT_TRUE(t4.subtypeOf(t2));
}
TEST(Type, WideningAlreadyStable) {
// A widening union on types that are already stable should not move
// the type anywhere.
for (auto& t : all()) {
EXPECT_EQ(widening_union(t, t), t);
}
for (auto& t : specialized_array_examples()) {
EXPECT_EQ(widening_union(t, t), t);
}
}
TEST(Type, EmptyArray) {
{
auto const possible_e = union_of(arr_packedn(TInt), aempty());
EXPECT_TRUE(possible_e.couldBe(aempty()));
EXPECT_TRUE(possible_e.couldBe(arr_packedn(TInt)));
EXPECT_EQ(array_elem(possible_e, ival(0)), opt(TInt));
}
{
auto const possible_e = union_of(arr_packed({TInt, TInt}), aempty());
EXPECT_TRUE(possible_e.couldBe(aempty()));
EXPECT_TRUE(possible_e.couldBe(arr_packed({TInt, TInt})));
EXPECT_FALSE(possible_e.couldBe(arr_packed({TInt, TInt, TInt})));
EXPECT_FALSE(possible_e.subtypeOf(arr_packedn(TInt)));
EXPECT_EQ(array_elem(possible_e, ival(0)), opt(TInt));
EXPECT_EQ(array_elem(possible_e, ival(1)), opt(TInt));
}
{
auto const estat = union_of(sarr_packedn(TInt), aempty());
EXPECT_TRUE(estat.couldBe(aempty()));
EXPECT_TRUE(estat.couldBe(sarr_packedn(TInt)));
EXPECT_FALSE(estat.subtypeOf(sarr_packedn(TInt)));
EXPECT_FALSE(estat.subtypeOf(TCArr));
EXPECT_FALSE(estat.couldBe(TCArr));
EXPECT_FALSE(estat.subtypeOf(TSArrE));
EXPECT_TRUE(estat.couldBe(TSArrE));
}
EXPECT_EQ(array_newelem(aempty(), ival(142)), arr_packed({ival(142)}));
}
TEST(Type, BasicArrays) {
EXPECT_TRUE(TSArr.subtypeOf(TArr));
EXPECT_TRUE(TCArr.subtypeOf(TArr));
EXPECT_TRUE(TArrE.subtypeOf(TArr));
EXPECT_TRUE(TArrN.subtypeOf(TArr));
EXPECT_TRUE(TSArrE.subtypeOf(TArr));
EXPECT_TRUE(TSArrN.subtypeOf(TArr));
EXPECT_TRUE(TCArrE.subtypeOf(TArr));
EXPECT_TRUE(TCArrN.subtypeOf(TArr));
EXPECT_EQ(union_of(TSArr, TCArr), TArr);
EXPECT_EQ(union_of(TSArrE, TCArrE), TArrE);
EXPECT_EQ(union_of(TSArrN, TCArrN), TArrN);
EXPECT_EQ(union_of(TArrN, TArrE), TArr);
EXPECT_EQ(union_of(TSArrN, TCArrE), TArr);
EXPECT_EQ(union_of(TSArrE, TCArrN), TArr);
EXPECT_EQ(union_of(TOptCArrN, TSArrE), TOptArr);
EXPECT_EQ(union_of(TOptSArr, TCArr), TOptArr);
EXPECT_EQ(union_of(TOptSArrE, TCArrE), TOptArrE);
EXPECT_EQ(union_of(TOptSArrN, TCArrN), TOptArrN);
EXPECT_EQ(union_of(TOptArrN, TArrE), TOptArr);
EXPECT_EQ(union_of(TOptSArrN, TOptCArrE), TOptArr);
EXPECT_EQ(union_of(TOptSArrN, TOptCArrE), TOptArr);
EXPECT_EQ(union_of(TOptSArr, TOptCArr), TOptArr);
EXPECT_EQ(union_of(TOptSArrE, TOptCArrE), TOptArrE);
EXPECT_EQ(union_of(TOptSArrN, TOptCArrN), TOptArrN);
EXPECT_EQ(union_of(TOptArrN, TOptArrE), TOptArr);
EXPECT_EQ(union_of(TOptSArrN, TOptCArrE), TOptArr);
EXPECT_EQ(union_of(TOptSArrN, TOptCArrE), TOptArr);
EXPECT_EQ(union_of(TSArr, TInitNull), TOptSArr);
EXPECT_EQ(union_of(TSArrE, TInitNull), TOptSArrE);
EXPECT_EQ(union_of(TSArrN, TInitNull), TOptSArrN);
EXPECT_EQ(union_of(TCArr, TInitNull), TOptCArr);
EXPECT_EQ(union_of(TCArrE, TInitNull), TOptCArrE);
EXPECT_EQ(union_of(TCArrN, TInitNull), TOptCArrN);
EXPECT_EQ(union_of(TArr, TInitNull), TOptArr);
EXPECT_EQ(union_of(TArrE, TInitNull), TOptArrE);
EXPECT_EQ(union_of(TArrN, TInitNull), TOptArrN);
}
/*
* These are tests for some unrepresentable bit combos. If we ever
* add predefined bits for things like TSArrE|TCArrN these will fail
* and need to be revisted.
*/
TEST(Type, ArrBitCombos) {
auto const u1 = union_of(sarr_packedn(TInt), TCArrE);
EXPECT_TRUE(u1.couldBe(TArrE));
EXPECT_TRUE(u1.couldBe(TSArrE));
EXPECT_TRUE(u1.couldBe(TCArrE));
EXPECT_TRUE(u1.couldBe(sarr_packedn(TInt)));
EXPECT_EQ(array_elem(u1, ival(0)), TOptInt);
auto const u2 = union_of(TSArrE, carr_packedn(TInt));
EXPECT_TRUE(u2.couldBe(TArrE));
EXPECT_TRUE(u2.couldBe(TSArrE));
EXPECT_TRUE(u2.couldBe(TCArrE));
EXPECT_TRUE(u2.couldBe(arr_packedn(TInt)));
EXPECT_EQ(array_elem(u2, ival(0)), TOptInt);
}
//////////////////////////////////////////////////////////////////////
}}
| 34.985658 | 79 | 0.695693 | arnononline |
f68aa1f30642677206154c59cdfc7088a3b4d3d0 | 38,240 | cpp | C++ | tools/converter/source/optimizer/PostTreatUtils.cpp | loveltyoic/MNN | ff405a307819a7228e0d1fc02c00c68021745b0a | [
"Apache-2.0"
] | null | null | null | tools/converter/source/optimizer/PostTreatUtils.cpp | loveltyoic/MNN | ff405a307819a7228e0d1fc02c00c68021745b0a | [
"Apache-2.0"
] | null | null | null | tools/converter/source/optimizer/PostTreatUtils.cpp | loveltyoic/MNN | ff405a307819a7228e0d1fc02c00c68021745b0a | [
"Apache-2.0"
] | 1 | 2021-01-15T06:28:11.000Z | 2021-01-15T06:28:11.000Z | //
// PostTreatUtils.cpp
// MNNConverter
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "PostTreatUtils.hpp"
#include <iostream>
using namespace MNN;
static bool _OpNeedContent(OpType type, int index) {
switch (type) {
case OpType_Shape:
case OpType_PriorBox:
return false;
case OpType_Interp:
case OpType_Crop:
case OpType_Reshape:
case OpType_Resize:
if (1 == index) {
return false;
}
break;
default:
break;
}
return true;
}
PostTreatUtils::PostTreatUtils(std::unique_ptr<MNN::NetT>& net) : mNet(std::move(net)) {
}
const std::set<MNN::OpType> PostTreatUtils::NC4HW4_OPs = {
MNN::OpType_Convolution,
MNN::OpType_ConvolutionDepthwise,
MNN::OpType_Pooling,
MNN::OpType_ROIPooling,
MNN::OpType_Resize,
MNN::OpType_LSTM,
MNN::OpType_SpatialProduct,
MNN::OpType_Deconvolution,
MNN::OpType_DeconvolutionDepthwise,
MNN::OpType_Proposal,
MNN::OpType_PriorBox,
MNN::OpType_DetectionOutput,
MNN::OpType_Eltwise,
MNN::OpType_LRN,
MNN::OpType_Interp,
MNN::OpType_Crop,
MNN::OpType_Scale,
MNN::OpType_TfQuantizedConv2D,
MNN::OpType_QuantizedDepthwiseConv2D,
MNN::OpType_BatchToSpaceND,
MNN::OpType_SpaceToBatchND,
MNN::OpType_BatchNorm,
MNN::OpType_Moments,
MNN::OpType_QuantizedAvgPool,
MNN::OpType_QuantizedAdd,
};
const std::set<MNN::OpType> PostTreatUtils::COMPABILITY_OPs = {
MNN::OpType_ReLU, MNN::OpType_ReLU6, MNN::OpType_Concat, MNN::OpType_Slice, MNN::OpType_Permute,
MNN::OpType_Selu, MNN::OpType_ConvertTensor, MNN::OpType_Sigmoid, MNN::OpType_Softmax, MNN::OpType_Cast,
MNN::OpType_Reshape, MNN::OpType_TanH, MNN::OpType_ArgMax,
};
const std::vector<MNN::OpType> PostTreatUtils::DELETE_Ops = {
MNN::OpType_Seq2Out,
MNN::OpType_Dropout,
};
void PostTreatUtils::treatIm2Seq() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
if (op->type != MNN::OpType_Im2Seq) {
iter++;
continue;
}
auto inputId = op->inputIndexes[0];
auto outputId = op->outputIndexes[0];
auto outputname = mNet->tensorName[outputId];
// New Reshape
MNN::OpT* reshapeT = new MNN::OpT;
reshapeT->name = "____reshape____" + op->name;
auto reshapeP = new MNN::ReshapeT;
reshapeP->dims.push_back(0); // b
reshapeP->dims.push_back(-1); // c
reshapeP->dims.push_back(1); // h
reshapeP->dims.push_back(0); // w
reshapeT->main.type = MNN::OpParameter_Reshape;
reshapeT->type = MNN::OpType_Reshape;
reshapeT->main.value = reshapeP;
// Net Tensor
mNet->tensorName.push_back(reshapeT->name);
int tempId = mNet->tensorName.size() - 1;
reshapeT->inputIndexes.push_back(inputId);
reshapeT->outputIndexes.push_back(tempId);
op->inputIndexes[0] = tempId;
op->type = MNN::OpType_Permute;
auto convP = new MNN::PermuteT;
op->main.type = MNN::OpParameter_Permute;
op->main.value = convP;
convP->dims.push_back(0);
convP->dims.push_back(3);
convP->dims.push_back(2);
convP->dims.push_back(1);
iter = mNet->oplists.insert(iter, std::unique_ptr<MNN::OpT>(reshapeT));
}
}
void PostTreatUtils::deleteUnusefulOp() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
bool shouldDelete = false;
for (int i = 0; i < PostTreatUtils::DELETE_Ops.size(); ++i) {
if (op->type == PostTreatUtils::DELETE_Ops[i]) {
shouldDelete = true;
break;
}
}
if (!shouldDelete) {
iter++;
continue;
}
// Find the next op
auto originInput = op->inputIndexes[0];
auto originOutput = op->outputIndexes[0];
iter = mNet->oplists.erase(iter);
for (auto subIter = mNet->oplists.begin(); subIter != mNet->oplists.end(); subIter++) {
auto& subOp = *subIter;
for (int v = 0; v < subOp->inputIndexes.size(); ++v) {
if (subOp->inputIndexes[v] == originOutput) {
subOp->inputIndexes[v] = originInput;
}
}
}
}
}
bool PostTreatUtils::_merge2Convolution(const MNN::OpT* inplaceOp, MNN::OpT* convolutionOp) {
if (inplaceOp->type == MNN::OpType_ReLU && inplaceOp->main.AsRelu()->slope == 0.0f) {
convolutionOp->main.AsConvolution2D()->common->relu = true;
return true;
}
if (inplaceOp->type == MNN::OpType_ReLU6) {
convolutionOp->main.AsConvolution2D()->common->relu6 = true;
return true;
}
const auto& convCommon = convolutionOp->main.AsConvolution2D()->common;
if (convCommon->relu || convCommon->relu6) {
return false;
}
if (inplaceOp->type == MNN::OpType_BatchNorm || inplaceOp->type == MNN::OpType_Scale) {
std::vector<float> alpha;
std::vector<float> bias;
if (inplaceOp->type == MNN::OpType_BatchNorm) {
auto l = inplaceOp->main.AsBatchNorm();
alpha.resize(l->channels);
bias.resize(l->channels);
const float* slopePtr = l->slopeData.data();
const float* meanDataPtr = l->meanData.data();
const float* varDataPtr = l->varData.data();
const float* biasDataPtr = l->biasData.data();
for (int i = 0; i < l->channels; i++) {
float sqrt_var = sqrt(varDataPtr[i]);
bias[i] = biasDataPtr[i] - slopePtr[i] * meanDataPtr[i] / sqrt_var;
alpha[i] = slopePtr[i] / sqrt_var;
}
}
if (inplaceOp->type == MNN::OpType_Scale) {
bias = inplaceOp->main.AsScale()->biasData;
alpha = inplaceOp->main.AsScale()->scaleData;
}
auto conv2D = convolutionOp->main.AsConvolution2D();
int outputCount = conv2D->common->outputCount;
for (int i = 0; i < outputCount; ++i) {
conv2D->bias[i] = conv2D->bias[i] * alpha[i] + bias[i];
}
if (nullptr != conv2D->quanParameter.get()) {
for (int i = 0; i < outputCount; ++i) {
conv2D->quanParameter->alpha[i] *= alpha[i];
}
} else {
int weightPartSize = conv2D->weight.size() / outputCount;
for (int i = 0; i < outputCount; ++i) {
float a = alpha[i];
for (int j = 0; j < weightPartSize; ++j) {
conv2D->weight[i * weightPartSize + j] *= a;
}
}
}
return true;
}
return false;
}
bool PostTreatUtils::_isSingleInputOutput(const MNN::OpT* op) {
if (op->inputIndexes.size() != 1 || op->outputIndexes.size() != 1) {
return false;
}
return true;
}
void PostTreatUtils::merge2Convolution() {
// Merge Layer
std::vector<MNN::OpT*> readyToDelete;
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
MNN::OpT& currentOp = *(iter->get());
if (currentOp.type != MNN::OpType_Convolution && currentOp.type != MNN::OpType_Deconvolution &&
currentOp.type != MNN::OpType_ConvolutionDepthwise) {
continue;
}
DCHECK(currentOp.outputIndexes.size() == 1) << "Conv output ERROR!";
// merge Batchnorm/Relu/Relu6 to Convolution
std::vector<MNN::OpT*> nextOp = this->_findOpByInputIndex(currentOp.outputIndexes[0]);
while (1) {
if (nextOp.size() != 1) {
break;
}
const int nextOutputIndex = nextOp[0]->outputIndexes[0];
bool succ = _merge2Convolution(nextOp[0], ¤tOp);
if (_isSingleInputOutput(nextOp[0]) && succ) {
// LOG(INFO) << "Merge " << nextOp[0]->name.c_str()<< " into convolution: " << currentOp.name.c_str();
currentOp.outputIndexes[0] = nextOp[0]->outputIndexes[0];
readyToDelete.push_back(nextOp[0]);
nextOp = this->_findOpByInputIndex(nextOutputIndex);
} else {
break;
}
}
}
for (auto op : readyToDelete) {
_removeOpInNet(op);
}
}
void PostTreatUtils::addTensorType() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
auto& op = *iter;
if (op->type == MNN::OpType_StridedSlice) {
auto parameter = op->main.AsStridedSliceParam();
auto dataType = parameter->T;
{
int index = op->inputIndexes[0];
auto describe = std::unique_ptr<MNN::TensorDescribeT>(new MNN::TensorDescribeT);
describe->index = index;
describe->blob = std::unique_ptr<MNN::BlobT>(new MNN::BlobT);
describe->blob->dataType = dataType;
mNet->extraTensorDescribe.push_back(std::move(describe));
}
{
int index = op->outputIndexes[0];
auto describe = std::unique_ptr<MNN::TensorDescribeT>(new MNN::TensorDescribeT);
describe->index = index;
describe->blob = std::unique_ptr<MNN::BlobT>(new MNN::BlobT);
describe->blob->dataType = dataType;
mNet->extraTensorDescribe.push_back(std::move(describe));
}
}
if (op->type == MNN::OpType_Const) {
auto constP = op->main.AsBlob();
{
int index = op->outputIndexes[0];
auto describe = std::unique_ptr<MNN::TensorDescribeT>(new MNN::TensorDescribeT);
describe->index = index;
describe->blob = std::unique_ptr<MNN::BlobT>(new MNN::BlobT);
describe->blob->dataType = constP->dataType;
mNet->extraTensorDescribe.push_back(std::move(describe));
}
}
}
}
void PostTreatUtils::removeInplaceOp() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
auto& op = *iter;
if (!_isSingleInputOutput(op.get())) {
continue;
}
if (op->inputIndexes[0] != op->outputIndexes[0]) {
continue;
}
auto originIndex = op->inputIndexes[0];
mNet->tensorName.push_back(op->name);
int newIndex = mNet->tensorName.size() - 1;
op->outputIndexes[0] = newIndex;
for (auto subIter = iter + 1; subIter != mNet->oplists.end(); subIter++) {
auto& subOp = *subIter;
for (int i = 0; i < subOp->inputIndexes.size(); ++i) {
if (subOp->inputIndexes[i] == originIndex) {
subOp->inputIndexes[i] = newIndex;
}
}
for (int i = 0; i < subOp->outputIndexes.size(); ++i) {
if (subOp->outputIndexes[i] == originIndex) {
subOp->outputIndexes[i] = newIndex;
}
}
}
mNet->tensorNumber = mNet->tensorName.size();
}
}
void PostTreatUtils::reIndexTensor() {
std::map<int, int> usefulTensorIndexMap;
std::vector<std::string> usefulTensorName;
std::vector<bool> tensorValid(mNet->tensorName.size(), false);
for (auto& op : mNet->oplists) {
for (auto index : op->inputIndexes) {
tensorValid[index] = true;
}
for (auto index : op->outputIndexes) {
tensorValid[index] = true;
}
}
for (int i = 0; i < tensorValid.size(); ++i) {
if (tensorValid[i]) {
usefulTensorIndexMap.insert(std::make_pair(i, usefulTensorName.size()));
usefulTensorName.push_back(mNet->tensorName[i]);
}
}
// Re index
for (auto& op : mNet->oplists) {
for (int i = 0; i < op->inputIndexes.size(); ++i) {
auto iter = usefulTensorIndexMap.find(op->inputIndexes[i]);
DCHECK(iter != usefulTensorIndexMap.end()) << "ERROR";
op->inputIndexes[i] = iter->second;
}
for (int i = 0; i < op->outputIndexes.size(); ++i) {
auto iter = usefulTensorIndexMap.find(op->outputIndexes[i]);
DCHECK(iter != usefulTensorIndexMap.end()) << "ERROR";
op->outputIndexes[i] = iter->second;
}
}
mNet->tensorName = usefulTensorName;
for (auto iter = mNet->extraTensorDescribe.begin(); iter != mNet->extraTensorDescribe.end();) {
auto index = (*iter)->index;
if (usefulTensorIndexMap.find(index) == usefulTensorIndexMap.end()) {
iter = mNet->extraTensorDescribe.erase(iter);
continue;
}
(*iter)->index = usefulTensorIndexMap.find(index)->second;
iter++;
}
}
void PostTreatUtils::addConverterForTensorFlowModel() {
if (mNet->sourceType == MNN::NetSource_CAFFE) {
return;
}
// Don't support inplace
std::vector<MNN::MNN_DATA_FORMAT> tensorType(mNet->tensorName.size());
std::map<std::string, MNN::MNN_DATA_FORMAT> opType;
for (auto& iter : mNet->oplists) {
auto type = MNN::MNN_DATA_FORMAT_NHWC;
if (iter->type == MNN::OpType_ConvertTensor) {
type = iter->main.AsTensorConvertInfo()->dest;
} else if (PostTreatUtils::NC4HW4_OPs.find(iter->type) != PostTreatUtils::NC4HW4_OPs.end()) {
type = MNN::MNN_DATA_FORMAT_NC4HW4;
} else if (PostTreatUtils::COMPABILITY_OPs.find(iter->type) != PostTreatUtils::COMPABILITY_OPs.end()) {
int caffeNumber = 0;
int tensorFlowNamer = 0;
for (auto index : iter->inputIndexes) {
if (tensorType[index] == MNN::MNN_DATA_FORMAT_NC4HW4) {
caffeNumber++;
} else if (tensorType[index] == MNN::MNN_DATA_FORMAT_NHWC) {
tensorFlowNamer++;
}
}
if (caffeNumber > tensorFlowNamer) {
type = MNN::MNN_DATA_FORMAT_NC4HW4;
} else {
type = MNN::MNN_DATA_FORMAT_NHWC;
}
if (iter->type == MNN::OpType_Reshape) {
if (iter->main.AsReshape()->dims.size() != 4) {
type = MNN::MNN_DATA_FORMAT_NHWC;
}
}
}
for (auto index : iter->outputIndexes) {
tensorType[index] = type;
}
opType.insert(std::make_pair(iter->name, type));
}
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
auto currentType = opType.find(op->name)->second;
std::vector<MNN::OpT*> transformOps;
auto currentName = op->name;
const bool useAutoFormat = NC4HW4_OPs.find(op->type) != NC4HW4_OPs.end();
for (int i = 0; i < op->inputIndexes.size(); ++i) {
auto inputIndex = op->inputIndexes[i];
MNN::OpT* inputOp = this->_findOpByOutputIndex(inputIndex);
if (inputOp && inputOp->type == MNN::OpType_Input && useAutoFormat) {
auto inputOpParam = inputOp->main.AsInput();
inputOpParam->dformat = MNN::MNN_DATA_FORMAT_NC4HW4;
tensorType[inputIndex] = MNN::MNN_DATA_FORMAT_NC4HW4;
opType[inputOp->name] = MNN::MNN_DATA_FORMAT_NC4HW4;
continue;
}
auto type = tensorType[inputIndex];
if (type == currentType) {
continue;
}
if (!_OpNeedContent(op->type, i)) {
continue;
}
// Insert Transform op
MNN::OpT* transformOp = new MNN::OpT;
transformOps.push_back(transformOp);
MNN::TensorConvertInfoT* tc = new MNN::TensorConvertInfoT;
tc->source = type;
tc->dest = currentType;
transformOp->main.type = MNN::OpParameter_TensorConvertInfo;
transformOp->main.value = tc;
transformOp->name = mNet->tensorName[inputIndex] + "___tr4" + op->name;
// printf("Insert convert for %s, %s 's input %d\n", net->tensorName[inputIndex].c_str(), op->name.c_str(),
// i);
transformOp->inputIndexes.push_back(inputIndex);
transformOp->outputIndexes.push_back(mNet->tensorName.size());
mNet->tensorName.push_back(transformOp->name);
op->inputIndexes[i] = transformOp->outputIndexes[0];
transformOp->type = MNN::OpType_ConvertTensor;
}
for (int i = transformOps.size() - 1; i >= 0; i--) {
iter = mNet->oplists.insert(iter, std::unique_ptr<MNN::OpT>(transformOps[i]));
}
for (; (*iter)->name != currentName; iter++) {
}
iter++;
}
// Reset axis map
const int axisMap[4] = {0, 2, 3, 1};
for (auto& op : mNet->oplists) {
if (opType.find(op->name)->second == MNN::MNN_DATA_FORMAT_NHWC) {
continue;
}
if (MNN::OpType_Input == op->type) {
auto input = op->main.AsInput();
if (4 == input->dims.size()) {
int h = input->dims[1];
int c = input->dims[3];
int w = input->dims[2];
input->dims[1] = c;
input->dims[2] = h;
input->dims[3] = w;
}
}
if (MNN::OpType_Concat == op->type) {
auto axis = op->main.AsAxis();
if (axis->axis >= 0 && axis->axis <= 3) {
axis->axis = axisMap[axis->axis];
}
}
if (MNN::OpType_Permute == op->type) {
auto permuteT = op->main.AsPermute();
for (int i = 0; i < permuteT->dims.size(); ++i) {
DCHECK(permuteT->dims[i] >= 0 && permuteT->dims[i] <= 3) << "Dim Error ==> " << op->name;
permuteT->dims[i] = axisMap[permuteT->dims[i]];
}
}
if (MNN::OpType_Slice == op->type) {
auto slice = op->main.AsSlice();
if (slice->axis >= 0 && slice->axis <= 3) {
slice->axis = axisMap[slice->axis];
}
}
if (MNN::OpType_Reshape == op->type) {
auto reshape = op->main.AsReshape();
auto originDim = reshape->dims;
for (int i = 0; i < reshape->dims.size(); ++i) {
CHECK(i >= 0 && i <= 3) << "Error";
reshape->dims[axisMap[i]] = originDim[i];
}
}
}
std::vector<bool> tensorTypeSet(tensorType.size(), false);
for (auto& iter : mNet->extraTensorDescribe) {
auto index = iter->index;
iter->blob->dataFormat = tensorType[index];
tensorTypeSet[index] = true;
}
for (int i = 0; i < tensorTypeSet.size(); ++i) {
if (tensorTypeSet[i]) {
continue;
}
auto describe = new MNN::TensorDescribeT;
describe->index = i;
describe->blob = std::unique_ptr<MNN::BlobT>(new MNN::BlobT);
describe->blob->dataFormat = tensorType[i];
describe->blob->dataType = MNN::DataType_DT_FLOAT;
mNet->extraTensorDescribe.push_back(std::unique_ptr<MNN::TensorDescribeT>(describe));
}
}
MNN::OpT* ensureOpInNet(std::unique_ptr<MNN::NetT>& net, MNN::OpT* op) {
for (auto& _op : net->oplists) {
if (_op.get() == op) {
return op;
}
}
return nullptr;
}
MNN::OpT* PostTreatUtils::_findOpByOutputIndex(int outputIndex) {
for (auto& op : mNet->oplists) {
if (inVector(op->outputIndexes, outputIndex)) {
return op.get();
}
}
return nullptr;
}
std::vector<MNN::OpT*> PostTreatUtils::_findOpByInputIndex(int inputIndex) {
std::vector<MNN::OpT*> ops;
for (auto& op : mNet->oplists) {
if (inVector(op->inputIndexes, inputIndex)) {
ops.push_back(op.get());
}
}
// check whether the next op is in_place op
const int opsSize = ops.size();
if (opsSize > 1) {
auto realNextOp = ops[0];
if (inVector(realNextOp->outputIndexes, inputIndex)) {
ops.clear();
ops.push_back(realNextOp);
}
}
return ops;
}
int PostTreatUtils::_getOpDecestorCount(MNN::OpT* op) {
int decestorCount = 0;
for (auto& otherOp : mNet->oplists) {
if (otherOp.get() != op) {
for (auto inputIndex : otherOp->inputIndexes) {
if (inVector(op->outputIndexes, inputIndex)) {
decestorCount++;
break; // one decestor just count one.
}
}
}
}
return decestorCount;
}
void PostTreatUtils::_removeOpInNet(MNN::OpT* op) {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
if (iter->get() == op) {
// LOG(INFO) << "remove op: " << op->name;
mNet->oplists.erase(iter);
break;
}
}
}
void PostTreatUtils::_removeOnlyOneDecestorOps(MNN::OpT* op) {
std::vector<MNN::OpT*> opsToBeChecked;
opsToBeChecked.push_back(op);
while (!opsToBeChecked.empty()) {
bool hasRemoved = false;
std::vector<MNN::OpT*> addedToBeChecked;
for (auto iter = opsToBeChecked.begin(); iter != opsToBeChecked.end();) {
MNN::OpT* op = *iter;
if (!ensureOpInNet(mNet, op)) {
hasRemoved = true;
iter = opsToBeChecked.erase(iter);
continue;
}
if (this->_getOpDecestorCount(op) == 0) {
for (int inputIndex : op->inputIndexes) {
addedToBeChecked.push_back(this->_findOpByOutputIndex(inputIndex));
}
hasRemoved = true;
this->_removeOpInNet(op);
iter = opsToBeChecked.erase(iter);
continue;
}
iter++;
}
if (!hasRemoved)
break;
opsToBeChecked.insert(opsToBeChecked.end(), addedToBeChecked.begin(), addedToBeChecked.end());
}
}
void PostTreatUtils::removeDeconvolutionShapeInput() {
std::set<MNN::OpT*> shapeOps;
for (auto& op : mNet->oplists) {
if (op->type == MNN::OpType_Deconvolution) {
if (op->inputIndexes.size() == 1) {
continue;
}
int firstInputIndex = op->inputIndexes[0];
op->inputIndexes.erase(op->inputIndexes.begin());
MNN::OpT* shapeOp = this->_findOpByOutputIndex(firstInputIndex);
if (shapeOp) {
shapeOps.insert(shapeOp);
}
}
}
for (auto& op : shapeOps) {
this->_removeOnlyOneDecestorOps(op);
}
}
void PostTreatUtils::turnInnerProduct2Convolution() {
std::vector<MNN::OpT*> readyToDelete;
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
if (op->type != MNN::OpType_InnerProduct) {
iter++;
continue;
}
// ONNX Gemm will be mapped to InnerProduct, check whether is Flatten before Gemm
// then delete Flatten(mapped to Reshape, and this Reshape will reshape tensor to be
// two dimensions, such as [M,K], which is the input of Gemm)
auto inputId = op->inputIndexes[0];
auto beforeGemm = _findOpByOutputIndex(inputId);
auto refBeforeGemm = _findOpByInputIndex(beforeGemm->outputIndexes[0]);
if (beforeGemm->type == MNN::OpType_Reshape && _isSingleInputOutput(beforeGemm) && refBeforeGemm.size() == 1) {
// change the input index
const int beforeGemmInputId = beforeGemm->inputIndexes[0];
op->inputIndexes[0] = beforeGemmInputId;
inputId = beforeGemmInputId;
readyToDelete.push_back(beforeGemm);
}
auto paramInner = op->main.AsInnerProduct();
const auto axis = paramInner->axis;
std::vector<MNN::OpT*> newOpPrevious;
std::vector<MNN::OpT*> newOpPost;
// New Reshape
MNN::OpT* reshapeT = new MNN::OpT;
newOpPrevious.push_back(reshapeT);
reshapeT->name = "____reshape____" + op->name;
auto reshapeP = new MNN::ReshapeT;
reshapeP->dims.resize(4);
for (int i = 0; i < axis; ++i) {
reshapeP->dims[i] = 0;
}
reshapeP->dims[axis] = -1;
for (int i = axis + 1; i < 4; ++i) {
reshapeP->dims[i] = 1;
}
if (mNet->sourceType == MNN::NetSource_TENSORFLOW) {
reshapeP->dims[3] = -1;
reshapeP->dims[1] = 1;
reshapeP->dims[2] = 1;
}
reshapeT->main.type = MNN::OpParameter_Reshape;
reshapeT->type = MNN::OpType_Reshape;
reshapeT->main.value = reshapeP;
// Net Tensor
mNet->tensorName.push_back(reshapeT->name);
int tempId = mNet->tensorName.size() - 1;
reshapeT->inputIndexes.push_back(inputId);
reshapeT->outputIndexes.push_back(tempId);
auto opName = op->name;
bool needPermute = 1 != axis && mNet->sourceType == MNN::NetSource_CAFFE;
if (needPermute) {
// Add Permute
auto permuteBefore = new MNN::OpT;
permuteBefore->type = MNN::OpType_Permute;
permuteBefore->main.type = MNN::OpParameter_Permute;
auto permuteT = new MNN::PermuteT;
permuteBefore->name = "___permute1__" + reshapeT->name;
permuteT->dims.resize(4);
for (int i = 0; i < 4; ++i) {
permuteT->dims[i] = i;
}
permuteT->dims[1] = axis;
permuteT->dims[axis] = 3;
permuteT->dims[3] = 1;
permuteBefore->main.value = permuteT;
permuteBefore->inputIndexes.push_back(tempId);
mNet->tensorName.push_back(permuteBefore->name);
tempId = mNet->tensorName.size() - 1;
permuteBefore->outputIndexes.push_back(tempId);
newOpPrevious.push_back(permuteBefore);
}
op->inputIndexes[0] = tempId;
op->type = MNN::OpType_Convolution;
auto convP = new MNN::Convolution2DT;
auto originInner = op->main.AsInnerProduct();
convP->common = std::unique_ptr<MNN::Convolution2DCommonT>(new MNN::Convolution2DCommonT);
convP->common->kernelX = 1;
convP->common->kernelY = 1;
convP->common->dilateX = 1;
convP->common->dilateY = 1;
convP->common->strideX = 1;
convP->common->strideY = 1;
convP->common->group = 1;
convP->common->outputCount = originInner->outputCount;
convP->common->padX = 0;
convP->common->padY = 0;
convP->common->padMode = MNN::PadMode_CAFFE;
convP->bias = originInner->bias;
convP->weight = originInner->weight;
convP->quanParameter = std::move(originInner->quanParameter);
if (convP->quanParameter.get() != nullptr) {
convP->quanParameter->has_scaleInt = false;
}
op->main.Reset();
op->main.type = MNN::OpParameter_Convolution2D;
op->main.value = convP;
if (needPermute) {
// Add Permute After
auto permuteBefore = new MNN::OpT;
permuteBefore->type = MNN::OpType_Permute;
permuteBefore->main.type = MNN::OpParameter_Permute;
auto permuteT = new MNN::PermuteT;
permuteBefore->name = "___permute2__" + reshapeT->name;
permuteT->dims.resize(4);
permuteT->dims[0] = 0;
permuteT->dims[1] = 3;
permuteT->dims[2] = 2;
permuteT->dims[3] = 2;
permuteT->dims[axis] = 1;
permuteBefore->main.value = permuteT;
mNet->tensorName.push_back(permuteBefore->name);
tempId = mNet->tensorName.size() - 1;
permuteBefore->inputIndexes.push_back(tempId);
permuteBefore->outputIndexes.push_back(op->outputIndexes[0]);
op->outputIndexes[0] = tempId;
newOpPost.push_back(permuteBefore);
}
for (int i = 0; i < newOpPrevious.size(); ++i) {
iter = mNet->oplists.insert(iter, std::unique_ptr<MNN::OpT>(newOpPrevious[newOpPrevious.size() - i - 1]));
}
for (;; iter++) {
auto& op = *iter;
if (op->name == opName) {
break;
}
}
for (int i = 0; i < newOpPost.size(); ++i) {
iter = mNet->oplists.insert(iter + 1, std::unique_ptr<MNN::OpT>(newOpPost[i]));
}
}
for (auto op : readyToDelete) {
_removeOpInNet(op);
}
}
void PostTreatUtils::turnGroupConvolution() {
// Pick DepthWise one
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end(); iter++) {
auto& op = *iter;
const auto op_type = op->type;
auto conv2D = op->main.AsConvolution2D();
auto& common = conv2D->common;
if (op_type == MNN::OpType_Convolution || op_type == MNN::OpType_Deconvolution) {
bool turnConv2DW = false;
// check whether idst quantization model
if (nullptr != conv2D->quanParameter.get()) {
auto& quanParam = conv2D->quanParameter;
auto quanWeightBuffer = quanParam->buffer.data();
const int weightShapeDim = static_cast<int>(quanWeightBuffer[0]);
if (weightShapeDim == 4) {
const auto weightShapePtr = reinterpret_cast<unsigned short*>(quanWeightBuffer + 1);
int ci = weightShapePtr[1];
if (ci == 1 && common->group != 1 && mNet->sourceType == MNN::NetSource_CAFFE) {
ci = weightShapePtr[0];
}
turnConv2DW = common->outputCount == common->group && ci == common->outputCount;
}
} else {
const int srcCount =
conv2D->weight.size() * common->group / common->outputCount / common->kernelX / common->kernelY;
turnConv2DW = common->outputCount == common->group && srcCount == common->outputCount;
}
if (turnConv2DW) {
switch (op_type) {
case MNN::OpType_Convolution:
op->type = MNN::OpType_ConvolutionDepthwise;
break;
case MNN::OpType_Deconvolution:
op->type = MNN::OpType_DeconvolutionDepthwise;
break;
default:
break;
}
}
}
}
// Delete Convolution With Grouop
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
if (op->type != MNN::OpType_Convolution && op->type != MNN::OpType_Deconvolution) {
iter++;
continue;
}
auto conv2D = op->main.AsConvolution2D();
auto& common = conv2D->common;
if (common->group == 1) {
iter++;
continue;
}
int srcCount = conv2D->weight.size() * common->group / common->outputCount / common->kernelX / common->kernelY;
DCHECK(srcCount % common->group == 0 && common->outputCount % common->group == 0)
<< "split group convolution ERROR! ==> " << op->name;
std::vector<int> newConvolutionInputIndex;
std::vector<int> newConvolutionOutputIndex;
for (int i = 0; i < common->group; ++i) {
std::ostringstream newTensorNameOs;
newTensorNameOs << op->name << "___input___" << i;
newConvolutionInputIndex.push_back(mNet->tensorName.size());
mNet->tensorName.push_back(newTensorNameOs.str());
}
for (int i = 0; i < common->group; ++i) {
std::ostringstream newTensorNameOs;
newTensorNameOs << op->name << "___output___" << i;
newConvolutionOutputIndex.push_back(mNet->tensorName.size());
mNet->tensorName.push_back(newTensorNameOs.str());
}
std::vector<MNN::OpT*> newOp;
// Create slice op
{
MNN::OpT* sliceOp = new MNN::OpT;
sliceOp->type = MNN::OpType_Slice;
sliceOp->name = op->name + "_____slice";
sliceOp->inputIndexes = op->inputIndexes;
sliceOp->outputIndexes = newConvolutionInputIndex;
auto sliceT = new MNN::SliceT;
sliceOp->main.type = MNN::OpParameter_Slice;
sliceOp->main.value = sliceT;
sliceT->axis = 1;
for (int i = 0; i < common->group - 1; ++i) {
sliceT->slicePoints.push_back(srcCount / (common->group) * (i + 1));
}
newOp.push_back(sliceOp);
}
int partWeightSize = conv2D->weight.size() / common->group;
int partBiasSize = conv2D->bias.size() / common->group;
// Create Sub Convolution
for (int i = 0; i < common->group; ++i) {
std::ostringstream opNameOs;
auto newConvOp = new MNN::OpT;
opNameOs << op->name << "__group__" << i;
newConvOp->type = op->type;
newConvOp->name = opNameOs.str();
newConvOp->main.type = MNN::OpParameter_Convolution2D;
newConvOp->inputIndexes.push_back(newConvolutionInputIndex[i]);
newConvOp->outputIndexes.push_back(newConvolutionOutputIndex[i]);
auto newConvolutionT = new MNN::Convolution2DT;
newConvOp->main.value = newConvolutionT;
newConvolutionT->common = std::unique_ptr<MNN::Convolution2DCommonT>(new MNN::Convolution2DCommonT);
newConvolutionT->common->kernelX = common->kernelX;
newConvolutionT->common->kernelY = common->kernelY;
newConvolutionT->common->dilateY = common->dilateY;
newConvolutionT->common->dilateX = common->dilateX;
newConvolutionT->common->strideX = common->strideX;
newConvolutionT->common->strideY = common->strideY;
newConvolutionT->common->group = 1;
newConvolutionT->common->padMode = common->padMode;
newConvolutionT->common->outputCount = common->outputCount / common->group;
newConvolutionT->common->padX = common->padX;
newConvolutionT->common->padY = common->padY;
newConvolutionT->common->relu = common->relu;
int startWeight = partWeightSize * i;
int startBias = partBiasSize * i;
for (int v = 0; v < partWeightSize; ++v) {
newConvolutionT->weight.push_back(conv2D->weight[startWeight + v]);
}
for (int v = 0; v < partBiasSize; ++v) {
newConvolutionT->bias.push_back(conv2D->bias[startBias + v]);
}
newOp.push_back(newConvOp);
}
// Set this op be Concat Op
{
op->type = MNN::OpType_Concat;
op->inputIndexes = newConvolutionOutputIndex;
op->main.Reset();
op->main.type = MNN::OpParameter_Axis;
auto axisT = new MNN::AxisT;
axisT->axis = 1;
op->main.value = axisT;
}
for (int v = 0; v < newOp.size(); ++v) {
int index = newOp.size() - v - 1;
iter = mNet->oplists.insert(iter, std::unique_ptr<MNN::OpT>(newOp[index]));
}
}
}
void PostTreatUtils::changeBatchnNorm2Scale() {
for (auto iter = mNet->oplists.begin(); iter != mNet->oplists.end();) {
auto& op = *iter;
const MNN::OpType opType = op->type;
if (MNN::OpType_BatchNorm != opType) {
iter++;
continue;
}
// instance norm have three input tensors(input_tensor, mean, variance)
if (op->inputIndexes.size() != 1) {
iter++;
continue;
}
// DLOG(INFO) << "change BatchNorm to Scale: " << op->name;
auto batchnormParam = op->main.AsBatchNorm();
auto scaleParam = new MNN::ScaleT;
scaleParam->channels = batchnormParam->channels;
scaleParam->scaleData.resize(batchnormParam->channels);
scaleParam->biasData.resize(batchnormParam->channels);
const float* slopePtr = batchnormParam->slopeData.data();
const float* meanDataPtr = batchnormParam->meanData.data();
const float* varDataPtr = batchnormParam->varData.data();
const float* biasDataPtr = batchnormParam->biasData.data();
for (int i = 0; i < batchnormParam->channels; i++) {
float sqrt_var = sqrt(varDataPtr[i]);
scaleParam->biasData[i] = biasDataPtr[i] - slopePtr[i] * meanDataPtr[i] / sqrt_var;
scaleParam->scaleData[i] = slopePtr[i] / sqrt_var;
}
op->type = MNN::OpType_Scale;
op->main.type = MNN::OpParameter_Scale;
op->main.value = scaleParam;
}
}
| 38.665319 | 119 | 0.536506 | loveltyoic |
f68cb10af5feaf7cbf5a57310df3669493eb8f3a | 6,076 | cc | C++ | src/base/scheduler_stub_test.cc | soleilpqd/mozc | 4767ce2f2b6a63f1f139daea6e98bc7a564d5e4e | [
"BSD-3-Clause"
] | 1 | 2017-09-01T20:55:40.000Z | 2017-09-01T20:55:40.000Z | src/base/scheduler_stub_test.cc | soleilpqd/mozc | 4767ce2f2b6a63f1f139daea6e98bc7a564d5e4e | [
"BSD-3-Clause"
] | null | null | null | src/base/scheduler_stub_test.cc | soleilpqd/mozc | 4767ce2f2b6a63f1f139daea6e98bc7a564d5e4e | [
"BSD-3-Clause"
] | 2 | 2020-02-12T15:24:27.000Z | 2020-02-22T13:36:21.000Z | // Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "base/scheduler_stub.h"
#include "testing/base/public/gunit.h"
namespace mozc {
namespace {
static int g_counter = 0;
static bool g_result = true;
bool TestFunc(void *data) {
++g_counter;
return g_result;
}
class SchedulerStubTest : public ::testing::Test {
protected:
virtual void SetUp() {
g_counter = 0;
g_result = true;
}
virtual void TearDown() {
g_counter = 0;
g_result = true;
}
};
TEST_F(SchedulerStubTest, AddRemoveJob) {
SchedulerStub scheduler_stub;
EXPECT_FALSE(scheduler_stub.HasJob("Test"));
scheduler_stub.AddJob(Scheduler::JobSetting(
"Test", 1000, 100000, 5000, 0, &TestFunc, NULL));
EXPECT_TRUE(scheduler_stub.HasJob("Test"));
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000); // delay_start
EXPECT_EQ(1, g_counter);
scheduler_stub.PutClockForward(1000); // default_interval
EXPECT_EQ(2, g_counter);
scheduler_stub.PutClockForward(1000); // default_interval
EXPECT_EQ(3, g_counter);
scheduler_stub.RemoveJob("Test");
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
EXPECT_FALSE(scheduler_stub.HasJob("Test"));
}
TEST_F(SchedulerStubTest, BackOff) {
SchedulerStub scheduler_stub;
scheduler_stub.AddJob(Scheduler::JobSetting(
"Test", 1000, 6000, 3000, 0, &TestFunc, NULL));
g_result = false;
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000); // delay_start
EXPECT_EQ(1, g_counter);
scheduler_stub.PutClockForward(1000); // backoff (wait 1000 + 1000)
EXPECT_EQ(1, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(2, g_counter);
scheduler_stub.PutClockForward(1000); // backoff (wait 1000 + 1000 * 2)
EXPECT_EQ(2, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(2, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000); // backoff (wait 1000 + 1000 * 4)
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
// backoff (wait 1000 + 1000 * 8) > 6000, use same delay
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(4, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
g_result = true;
// use same delay
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(6, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(7, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(8, g_counter);
}
TEST_F(SchedulerStubTest, AddRemoveJobs) {
SchedulerStub scheduler_stub;
scheduler_stub.AddJob(Scheduler::JobSetting(
"Test1", 1000, 100000, 1000, 0, &TestFunc, NULL));
EXPECT_EQ(0, g_counter);
scheduler_stub.PutClockForward(1000); // delay
EXPECT_EQ(1, g_counter);
scheduler_stub.AddJob(Scheduler::JobSetting(
"Test2", 1000, 100000, 1000, 0, &TestFunc, NULL));
scheduler_stub.PutClockForward(1000); // delay + interval
EXPECT_EQ(3, g_counter);
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(5, g_counter);
scheduler_stub.RemoveJob("Test3"); // nothing happens
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(7, g_counter);
scheduler_stub.RemoveJob("Test2");
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(8, g_counter);
scheduler_stub.RemoveAllJobs();
scheduler_stub.PutClockForward(1000);
EXPECT_EQ(8, g_counter);
}
} // namespace
} // namespace mozc
| 32.148148 | 74 | 0.748025 | soleilpqd |
f68e798ccf24936eb3f840fe249eaba7fe6f85b0 | 143,462 | cc | C++ | src/net/http/transport_security_state_unittest.cc | godfo/naiveproxy | 369269a12832bf34bf01c7b0e7ca121555abd3eb | [
"BSD-3-Clause"
] | 1 | 2021-03-21T10:43:16.000Z | 2021-03-21T10:43:16.000Z | src/net/http/transport_security_state_unittest.cc | wclmgcd/naiveproxy | e32a3afb76fd21207c322f2d5e794c4f5505fb59 | [
"BSD-3-Clause"
] | null | null | null | src/net/http/transport_security_state_unittest.cc | wclmgcd/naiveproxy | e32a3afb76fd21207c322f2d5e794c4f5505fb59 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/transport_security_state.h"
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/json/json_reader.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_param_associator.h"
#include "base/rand_util.h"
#include "base/strings/string_piece.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "build/build_config.h"
#include "crypto/openssl_util.h"
#include "crypto/sha2.h"
#include "net/base/host_port_pair.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/ct_policy_status.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_cert_types.h"
#include "net/cert/x509_certificate.h"
#include "net/extras/preload_data/decoder.h"
#include "net/http/hsts_info.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/net_buildflags.h"
#include "net/ssl/ssl_info.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "net/tools/huffman_trie/bit_writer.h"
#include "net/tools/huffman_trie/trie/trie_bit_buffer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
namespace test_default {
#include "net/http/transport_security_state_static_unittest_default.h"
}
namespace test1 {
#include "net/http/transport_security_state_static_unittest1.h"
}
namespace test2 {
#include "net/http/transport_security_state_static_unittest2.h"
}
namespace test3 {
#include "net/http/transport_security_state_static_unittest3.h"
}
const char kHost[] = "example.test";
const uint16_t kPort = 443;
const char kReportUri[] = "http://report-example.test/test";
const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
const char kExpectCTStaticReportURI[] =
"http://report-uri.preloaded.test/expect-ct";
const char* const kGoodPath[] = {
"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"sha256/fzP+pVAbH0hRoUphJKenIP8+2tD/d2QH9J+kQNieM6Q=",
"sha256/9vRUVdjloCa4wXUKfDWotV5eUXYD7vu0v0z9SRzQdzg=",
"sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY=",
nullptr,
};
const char* const kBadPath[] = {
"sha256/1111111111111111111111111111111111111111111=",
"sha256/2222222222222222222222222222222222222222222=",
"sha256/3333333333333333333333333333333333333333333=", nullptr,
};
// Constructs a SignedCertificateTimestampAndStatus with the given information
// and appends it to |sct_list|.
void MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::Origin origin,
const std::string& log_id,
const std::string& extensions,
const std::string& signature_data,
const base::Time& timestamp,
ct::SCTVerifyStatus status,
SignedCertificateTimestampAndStatusList* sct_list) {
scoped_refptr<net::ct::SignedCertificateTimestamp> sct(
new net::ct::SignedCertificateTimestamp());
sct->version = net::ct::SignedCertificateTimestamp::V1;
sct->log_id = log_id;
sct->extensions = extensions;
sct->timestamp = timestamp;
sct->signature.signature_data = signature_data;
sct->origin = origin;
sct_list->push_back(net::SignedCertificateTimestampAndStatus(sct, status));
}
// A mock ReportSenderInterface that just remembers the latest report
// URI and report to be sent.
class MockCertificateReportSender
: public TransportSecurityState::ReportSenderInterface {
public:
MockCertificateReportSender() = default;
~MockCertificateReportSender() override = default;
void Send(const GURL& report_uri,
base::StringPiece content_type,
base::StringPiece report,
const base::Callback<void()>& success_callback,
const base::Callback<void(const GURL&, int, int)>& error_callback)
override {
latest_report_uri_ = report_uri;
latest_report_.assign(report.data(), report.size());
latest_content_type_.assign(content_type.data(), content_type.size());
}
void Clear() {
latest_report_uri_ = GURL();
latest_report_ = std::string();
latest_content_type_ = std::string();
}
const GURL& latest_report_uri() { return latest_report_uri_; }
const std::string& latest_report() { return latest_report_; }
const std::string& latest_content_type() { return latest_content_type_; }
private:
GURL latest_report_uri_;
std::string latest_report_;
std::string latest_content_type_;
};
// A mock ReportSenderInterface that simulates a net error on every report sent.
class MockFailingCertificateReportSender
: public TransportSecurityState::ReportSenderInterface {
public:
MockFailingCertificateReportSender() : net_error_(ERR_CONNECTION_FAILED) {}
~MockFailingCertificateReportSender() override = default;
int net_error() { return net_error_; }
// TransportSecurityState::ReportSenderInterface:
void Send(const GURL& report_uri,
base::StringPiece content_type,
base::StringPiece report,
const base::Callback<void()>& success_callback,
const base::Callback<void(const GURL&, int, int)>& error_callback)
override {
ASSERT_FALSE(error_callback.is_null());
error_callback.Run(report_uri, net_error_, 0);
}
private:
const int net_error_;
};
// A mock ExpectCTReporter that remembers the latest violation that was
// reported and the number of violations reported.
class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
public:
MockExpectCTReporter() : num_failures_(0) {}
~MockExpectCTReporter() override = default;
void OnExpectCTFailed(const HostPortPair& host_port_pair,
const GURL& report_uri,
base::Time expiration,
const X509Certificate* validated_certificate_chain,
const X509Certificate* served_certificate_chain,
const SignedCertificateTimestampAndStatusList&
signed_certificate_timestamps) override {
num_failures_++;
host_port_pair_ = host_port_pair;
report_uri_ = report_uri;
expiration_ = expiration;
served_certificate_chain_ = served_certificate_chain;
validated_certificate_chain_ = validated_certificate_chain;
signed_certificate_timestamps_ = signed_certificate_timestamps;
}
const HostPortPair& host_port_pair() { return host_port_pair_; }
const GURL& report_uri() { return report_uri_; }
const base::Time& expiration() { return expiration_; }
uint32_t num_failures() { return num_failures_; }
const X509Certificate* served_certificate_chain() {
return served_certificate_chain_;
}
const X509Certificate* validated_certificate_chain() {
return validated_certificate_chain_;
}
const SignedCertificateTimestampAndStatusList&
signed_certificate_timestamps() {
return signed_certificate_timestamps_;
}
private:
HostPortPair host_port_pair_;
GURL report_uri_;
base::Time expiration_;
uint32_t num_failures_;
const X509Certificate* served_certificate_chain_;
const X509Certificate* validated_certificate_chain_;
SignedCertificateTimestampAndStatusList signed_certificate_timestamps_;
};
class MockRequireCTDelegate : public TransportSecurityState::RequireCTDelegate {
public:
MOCK_METHOD3(IsCTRequiredForHost,
CTRequirementLevel(const std::string& hostname,
const X509Certificate* chain,
const HashValueVector& hashes));
};
void CompareCertificateChainWithList(
const scoped_refptr<X509Certificate>& cert_chain,
const base::Value* cert_list) {
ASSERT_TRUE(cert_chain);
ASSERT_TRUE(cert_list->is_list());
std::vector<std::string> pem_encoded_chain;
cert_chain->GetPEMEncodedChain(&pem_encoded_chain);
ASSERT_EQ(pem_encoded_chain.size(), cert_list->GetList().size());
for (size_t i = 0; i < pem_encoded_chain.size(); i++) {
const std::string& list_cert = cert_list->GetList()[i].GetString();
EXPECT_EQ(pem_encoded_chain[i], list_cert);
}
}
void CheckHPKPReport(
const std::string& report,
const HostPortPair& host_port_pair,
bool include_subdomains,
const std::string& noted_hostname,
const scoped_refptr<X509Certificate>& served_certificate_chain,
const scoped_refptr<X509Certificate>& validated_certificate_chain,
const HashValueVector& known_pins) {
base::Optional<base::Value> value = base::JSONReader::Read(report);
ASSERT_TRUE(value.has_value());
const base::Value& report_dict = value.value();
ASSERT_TRUE(report_dict.is_dict());
const std::string* report_hostname = report_dict.FindStringKey("hostname");
ASSERT_TRUE(report_hostname);
EXPECT_EQ(host_port_pair.host(), *report_hostname);
base::Optional<int> report_port = report_dict.FindIntKey("port");
ASSERT_TRUE(report_port.has_value());
EXPECT_EQ(host_port_pair.port(), report_port.value());
base::Optional<bool> report_include_subdomains =
report_dict.FindBoolKey("include-subdomains");
ASSERT_TRUE(report_include_subdomains.has_value());
EXPECT_EQ(include_subdomains, report_include_subdomains.value());
const std::string* report_noted_hostname =
report_dict.FindStringKey("noted-hostname");
ASSERT_TRUE(report_noted_hostname);
EXPECT_EQ(noted_hostname, *report_noted_hostname);
// TODO(estark): check times in RFC3339 format.
const std::string* report_expiration =
report_dict.FindStringKey("effective-expiration-date");
ASSERT_TRUE(report_expiration);
EXPECT_FALSE(report_expiration->empty());
const std::string* report_date = report_dict.FindStringKey("date-time");
ASSERT_TRUE(report_date);
EXPECT_FALSE(report_date->empty());
const base::Value* report_served_certificate_chain =
report_dict.FindKey("served-certificate-chain");
ASSERT_TRUE(report_served_certificate_chain);
ASSERT_NO_FATAL_FAILURE(CompareCertificateChainWithList(
served_certificate_chain, report_served_certificate_chain));
const base::Value* report_validated_certificate_chain =
report_dict.FindKey("validated-certificate-chain");
ASSERT_TRUE(report_validated_certificate_chain);
ASSERT_NO_FATAL_FAILURE(CompareCertificateChainWithList(
validated_certificate_chain, report_validated_certificate_chain));
}
bool operator==(const TransportSecurityState::STSState& lhs,
const TransportSecurityState::STSState& rhs) {
return lhs.last_observed == rhs.last_observed && lhs.expiry == rhs.expiry &&
lhs.upgrade_mode == rhs.upgrade_mode &&
lhs.include_subdomains == rhs.include_subdomains &&
lhs.domain == rhs.domain;
}
bool operator==(const TransportSecurityState::PKPState& lhs,
const TransportSecurityState::PKPState& rhs) {
return lhs.last_observed == rhs.last_observed && lhs.expiry == rhs.expiry &&
lhs.spki_hashes == rhs.spki_hashes &&
lhs.bad_spki_hashes == rhs.bad_spki_hashes &&
lhs.include_subdomains == rhs.include_subdomains &&
lhs.domain == rhs.domain && lhs.report_uri == rhs.report_uri;
}
} // namespace
class TransportSecurityStateTest : public testing::Test {
public:
TransportSecurityStateTest() {
SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
}
~TransportSecurityStateTest() override {
SetTransportSecurityStateSourceForTesting(nullptr);
}
void SetUp() override {
crypto::EnsureOpenSSLInit();
}
static void DisableStaticPins(TransportSecurityState* state) {
state->enable_static_pins_ = false;
}
static void EnableStaticPins(TransportSecurityState* state) {
state->enable_static_pins_ = true;
}
static void EnableStaticExpectCT(TransportSecurityState* state) {
state->enable_static_expect_ct_ = true;
}
static HashValueVector GetSampleSPKIHashes() {
HashValueVector spki_hashes;
HashValue hash(HASH_VALUE_SHA256);
memset(hash.data(), 0, hash.size());
spki_hashes.push_back(hash);
return spki_hashes;
}
static HashValue GetSampleSPKIHash(uint8_t value) {
HashValue hash(HASH_VALUE_SHA256);
memset(hash.data(), value, hash.size());
return hash;
}
protected:
bool GetStaticDomainState(TransportSecurityState* state,
const std::string& host,
TransportSecurityState::STSState* sts_result,
TransportSecurityState::PKPState* pkp_result) {
return state->GetStaticDomainState(host, sts_result, pkp_result);
}
bool GetExpectCTState(TransportSecurityState* state,
const std::string& host,
TransportSecurityState::ExpectCTState* result) {
return state->GetStaticExpectCTState(host, result);
}
};
TEST_F(TransportSecurityStateTest, DomainNameOddities) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
// DNS suffix search tests. Some DNS resolvers allow a terminal "." to
// indicate not perform DNS suffix searching. Ensure that regardless
// of how this is treated at the resolver layer, or at the URL/origin
// layer (that is, whether they are treated as equivalent or distinct),
// ensure that for policy matching, something lacking a terminal "."
// is equivalent to something with a terminal "."
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
state.AddHSTS("example.com", expiry, true /* include_subdomains */);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
// Trailing '.' should be equivalent; it's just a resolver hint
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com."));
// Leading '.' should be invalid
EXPECT_FALSE(state.ShouldUpgradeToSSL(".example.com"));
// Subdomains should work regardless
EXPECT_TRUE(state.ShouldUpgradeToSSL("sub.example.com"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("sub.example.com."));
// But invalid subdomains should be rejected
EXPECT_FALSE(state.ShouldUpgradeToSSL("sub..example.com"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("sub..example.com."));
// Now try the inverse form
TransportSecurityState state2;
state2.AddHSTS("example.net.", expiry, true /* include_subdomains */);
EXPECT_TRUE(state2.ShouldUpgradeToSSL("example.net."));
EXPECT_TRUE(state2.ShouldUpgradeToSSL("example.net"));
EXPECT_TRUE(state2.ShouldUpgradeToSSL("sub.example.net."));
EXPECT_TRUE(state2.ShouldUpgradeToSSL("sub.example.net"));
// Finally, test weird things
TransportSecurityState state3;
state3.AddHSTS("", expiry, true /* include_subdomains */);
EXPECT_FALSE(state3.ShouldUpgradeToSSL(""));
EXPECT_FALSE(state3.ShouldUpgradeToSSL("."));
EXPECT_FALSE(state3.ShouldUpgradeToSSL("..."));
// Make sure it didn't somehow apply HSTS to the world
EXPECT_FALSE(state3.ShouldUpgradeToSSL("example.org"));
TransportSecurityState state4;
state4.AddHSTS(".", expiry, true /* include_subdomains */);
EXPECT_FALSE(state4.ShouldUpgradeToSSL(""));
EXPECT_FALSE(state4.ShouldUpgradeToSSL("."));
EXPECT_FALSE(state4.ShouldUpgradeToSSL("..."));
EXPECT_FALSE(state4.ShouldUpgradeToSSL("example.org"));
// Now do the same for preloaded entries
TransportSecurityState state5;
EXPECT_TRUE(state5.ShouldUpgradeToSSL("hsts-preloaded.test"));
EXPECT_TRUE(state5.ShouldUpgradeToSSL("hsts-preloaded.test."));
EXPECT_FALSE(state5.ShouldUpgradeToSSL("hsts-preloaded..test"));
EXPECT_FALSE(state5.ShouldUpgradeToSSL("hsts-preloaded..test."));
}
TEST_F(TransportSecurityStateTest, SimpleMatches) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
bool include_subdomains = false;
state.AddHSTS("example.com", expiry, include_subdomains);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example.com"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example.com"));
EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("foo.example.com"));
}
TEST_F(TransportSecurityStateTest, MatchesCase1) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
bool include_subdomains = false;
state.AddHSTS("EXample.coM", expiry, include_subdomains);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
}
TEST_F(TransportSecurityStateTest, MatchesCase2) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
// Check dynamic entries
EXPECT_FALSE(state.ShouldUpgradeToSSL("EXample.coM"));
bool include_subdomains = false;
state.AddHSTS("example.com", expiry, include_subdomains);
EXPECT_TRUE(state.ShouldUpgradeToSSL("EXample.coM"));
// Check static entries
EXPECT_TRUE(state.ShouldUpgradeToSSL("hStS-prelOAded.tEsT"));
EXPECT_TRUE(
state.ShouldUpgradeToSSL("inClude-subDOmaIns-hsts-prEloaDed.TesT"));
}
TEST_F(TransportSecurityStateTest, SubdomainMatches) {
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.test"));
bool include_subdomains = true;
state.AddHSTS("example.test", expiry, include_subdomains);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.bar.example.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.bar.baz.example.test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("notexample.test"));
}
// Tests that a more-specific HSTS or HPKP rule overrides a less-specific rule
// with it, regardless of the includeSubDomains bit. This is a regression test
// for https://crbug.com/469957. Note this behavior does not match the spec.
// See https://crbug.com/821811.
TEST_F(TransportSecurityStateTest, SubdomainCarveout) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
const base::Time older = current_time - base::TimeDelta::FromSeconds(1000);
state.AddHSTS("example1.test", expiry, true);
state.AddHSTS("foo.example1.test", expiry, false);
state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes(),
report_uri);
state.AddHPKP("foo.example2.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example1.test"));
// The foo.example1.test rule overrides the example1.test rule, so
// bar.foo.example1.test has no HSTS state.
EXPECT_FALSE(state.ShouldUpgradeToSSL("bar.foo.example1.test"));
EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("bar.foo.example1.test"));
EXPECT_TRUE(state.HasPublicKeyPins("example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
// The foo.example2.test rule overrides the example1.test rule, so
// bar.foo.example2.test has no HPKP state.
EXPECT_FALSE(state.HasPublicKeyPins("bar.foo.example2.test"));
EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("bar.foo.example2.test"));
// Expire the foo.example*.test rules.
state.AddHSTS("foo.example1.test", older, false);
state.AddHPKP("foo.example2.test", older, false, GetSampleSPKIHashes(),
report_uri);
// Now the base example*.test rules apply to bar.foo.example*.test.
EXPECT_TRUE(state.ShouldUpgradeToSSL("bar.foo.example1.test"));
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example1.test"));
EXPECT_TRUE(state.HasPublicKeyPins("bar.foo.example2.test"));
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example2.test"));
}
TEST_F(TransportSecurityStateTest, FatalSSLErrors) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddHSTS("example1.test", expiry, false);
state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
// The presense of either HSTS or HPKP is enough to make SSL errors fatal.
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example1.test"));
EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example2.test"));
}
// Tests that HPKP and HSTS state both expire. Also tests that expired entries
// are pruned.
TEST_F(TransportSecurityStateTest, Expiration) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
const base::Time older = current_time - base::TimeDelta::FromSeconds(1000);
// Note: this test assumes that inserting an entry with an expiration time in
// the past works and is pruned on query.
state.AddHSTS("example1.test", older, false);
EXPECT_TRUE(TransportSecurityState::STSStateIterator(state).HasNext());
EXPECT_FALSE(state.ShouldUpgradeToSSL("example1.test"));
// Querying |state| for a domain should flush out expired entries.
EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.has_dynamic_pkp_state());
EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
// Querying |state| for a domain should flush out expired entries.
EXPECT_FALSE(state.has_dynamic_pkp_state());
state.AddHSTS("example1.test", older, false);
state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(TransportSecurityState::STSStateIterator(state).HasNext());
EXPECT_TRUE(state.has_dynamic_pkp_state());
EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("example1.test"));
// Querying |state| for a domain should flush out expired entries.
EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
EXPECT_FALSE(state.has_dynamic_pkp_state());
// Test that HSTS can outlive HPKP.
state.AddHSTS("example1.test", expiry, false);
state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
// Test that HPKP can outlive HSTS.
state.AddHSTS("example2.test", older, false);
state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("example2.test"));
}
// Tests that HPKP and HSTS state are queried independently for subdomain
// matches.
TEST_F(TransportSecurityStateTest, IndependentSubdomain) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddHSTS("example1.test", expiry, true);
state.AddHPKP("example1.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
state.AddHSTS("example2.test", expiry, false);
state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("foo.example1.test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
}
// Tests that HPKP and HSTS state are inserted and overridden independently.
TEST_F(TransportSecurityStateTest, IndependentInsertion) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
// Place an includeSubdomains HSTS entry below a normal HPKP entry.
state.AddHSTS("example1.test", expiry, true);
state.AddHPKP("foo.example1.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example1.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example1.test"));
EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
// Drop the includeSubdomains from the HSTS entry.
state.AddHSTS("example1.test", expiry, false);
EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example1.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example1.test"));
// Place an includeSubdomains HPKP entry below a normal HSTS entry.
state.AddHSTS("foo.example2.test", expiry, false);
state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
// Drop the includeSubdomains from the HSTS entry.
state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
report_uri);
EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example2.test"));
EXPECT_FALSE(state.HasPublicKeyPins("foo.example2.test"));
}
// Tests that GetDynamic[PKP|STS]State returns the correct data and that the
// states are not mixed together.
TEST_F(TransportSecurityStateTest, DynamicDomainState) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry1 = current_time + base::TimeDelta::FromSeconds(1000);
const base::Time expiry2 = current_time + base::TimeDelta::FromSeconds(2000);
state.AddHSTS("example.com", expiry1, true);
state.AddHPKP("foo.example.com", expiry2, false, GetSampleSPKIHashes(),
report_uri);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
ASSERT_TRUE(state.GetDynamicSTSState("foo.example.com", &sts_state, nullptr));
ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
EXPECT_TRUE(sts_state.ShouldUpgradeToSSL());
EXPECT_TRUE(pkp_state.HasPublicKeyPins());
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_FALSE(pkp_state.include_subdomains);
EXPECT_EQ(expiry1, sts_state.expiry);
EXPECT_EQ(expiry2, pkp_state.expiry);
EXPECT_EQ("example.com", sts_state.domain);
EXPECT_EQ("foo.example.com", pkp_state.domain);
}
// Tests that new pins always override previous pins. This should be true for
// both pins at the same domain or includeSubdomains pins at a parent domain.
TEST_F(TransportSecurityStateTest, NewPinsOverride) {
const GURL report_uri(kReportUri);
TransportSecurityState state;
TransportSecurityState::PKPState pkp_state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
HashValue hash1(HASH_VALUE_SHA256);
memset(hash1.data(), 0x01, hash1.size());
HashValue hash2(HASH_VALUE_SHA256);
memset(hash2.data(), 0x02, hash1.size());
HashValue hash3(HASH_VALUE_SHA256);
memset(hash3.data(), 0x03, hash1.size());
state.AddHPKP("example.com", expiry, true, HashValueVector(1, hash1),
report_uri);
ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
ASSERT_EQ(1u, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], hash1);
state.AddHPKP("foo.example.com", expiry, false, HashValueVector(1, hash2),
report_uri);
ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
ASSERT_EQ(1u, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], hash2);
state.AddHPKP("foo.example.com", expiry, false, HashValueVector(1, hash3),
report_uri);
ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
ASSERT_EQ(1u, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], hash3);
}
TEST_F(TransportSecurityStateTest, DeleteAllDynamicDataSince) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState::ExpectCTState expect_ct_state;
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
const base::Time older = current_time - base::TimeDelta::FromSeconds(1000);
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
EXPECT_FALSE(state.HasPublicKeyPins("example.com"));
EXPECT_FALSE(state.GetDynamicExpectCTState("example.com", &expect_ct_state));
bool include_subdomains = false;
state.AddHSTS("example.com", expiry, include_subdomains);
state.AddHPKP("example.com", expiry, include_subdomains,
GetSampleSPKIHashes(), GURL());
state.AddExpectCT("example.com", expiry, true, GURL());
state.DeleteAllDynamicDataSince(expiry, base::DoNothing());
EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
EXPECT_TRUE(state.HasPublicKeyPins("example.com"));
EXPECT_TRUE(state.GetDynamicExpectCTState("example.com", &expect_ct_state));
state.DeleteAllDynamicDataSince(older, base::DoNothing());
EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
EXPECT_FALSE(state.HasPublicKeyPins("example.com"));
EXPECT_FALSE(state.GetDynamicExpectCTState("example.com", &expect_ct_state));
// Dynamic data in |state| should be empty now.
EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
EXPECT_FALSE(state.has_dynamic_pkp_state());
EXPECT_FALSE(TransportSecurityState::ExpectCTStateIterator(state).HasNext());
}
TEST_F(TransportSecurityStateTest, DeleteDynamicDataForHost) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
bool include_subdomains = false;
state.AddHSTS("example1.test", expiry, include_subdomains);
state.AddHPKP("example1.test", expiry, include_subdomains,
GetSampleSPKIHashes(), GURL());
state.AddExpectCT("example1.test", expiry, true, GURL());
EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("example2.test"));
EXPECT_TRUE(state.HasPublicKeyPins("example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("example2.test"));
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_TRUE(state.GetDynamicExpectCTState("example1.test", &expect_ct_state));
EXPECT_FALSE(
state.GetDynamicExpectCTState("example2.test", &expect_ct_state));
EXPECT_TRUE(state.DeleteDynamicDataForHost("example1.test"));
EXPECT_FALSE(state.ShouldUpgradeToSSL("example1.test"));
EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
EXPECT_FALSE(
state.GetDynamicExpectCTState("example1.test", &expect_ct_state));
}
TEST_F(TransportSecurityStateTest, LongNames) {
TransportSecurityState state;
const char kLongName[] =
"lookupByWaveIdHashAndWaveIdIdAndWaveIdDomainAndWaveletIdIdAnd"
"WaveletIdDomainAndBlipBlipid";
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
// Just checks that we don't hit a NOTREACHED.
EXPECT_FALSE(state.GetStaticDomainState(kLongName, &sts_state, &pkp_state));
EXPECT_FALSE(state.GetDynamicSTSState(kLongName, &sts_state, nullptr));
EXPECT_FALSE(state.GetDynamicPKPState(kLongName, &pkp_state));
}
static bool AddHash(const std::string& type_and_base64, HashValueVector* out) {
HashValue hash;
if (!hash.FromString(type_and_base64))
return false;
out->push_back(hash);
return true;
}
TEST_F(TransportSecurityStateTest, PinValidationWithoutRejectedCerts) {
HashValueVector good_hashes, bad_hashes;
for (size_t i = 0; kGoodPath[i]; i++) {
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
}
for (size_t i = 0; kBadPath[i]; i++) {
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
}
TransportSecurityState state;
EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EXPECT_TRUE(state.GetStaticDomainState("no-rejected-pins-pkp.preloaded.test",
&sts_state, &pkp_state));
EXPECT_TRUE(pkp_state.HasPublicKeyPins());
std::string failure_log;
EXPECT_TRUE(pkp_state.CheckPublicKeyPins(good_hashes, &failure_log));
EXPECT_FALSE(pkp_state.CheckPublicKeyPins(bad_hashes, &failure_log));
}
// Tests that pinning violations on preloaded pins trigger reports when
// the preloaded pin contains a report URI.
TEST_F(TransportSecurityStateTest, PreloadedPKPReportUri) {
const char kPreloadedPinDomain[] = "with-report-uri-pkp.preloaded.test";
const uint16_t kPort = 443;
HostPortPair host_port_pair(kPreloadedPinDomain, kPort);
TransportSecurityState state;
MockCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
EnableStaticPins(&state);
TransportSecurityState::PKPState pkp_state;
TransportSecurityState::STSState unused_sts_state;
ASSERT_TRUE(state.GetStaticDomainState(kPreloadedPinDomain, &unused_sts_state,
&pkp_state));
ASSERT_TRUE(pkp_state.HasPublicKeyPins());
GURL report_uri = pkp_state.report_uri;
ASSERT_TRUE(report_uri.is_valid());
ASSERT_FALSE(report_uri.is_empty());
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter, as long as they are not the real google.com
// certs in the pins.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector bad_hashes;
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
// Trigger a violation and check that it sends a report.
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
std::string report = mock_report_sender.latest_report();
ASSERT_FALSE(report.empty());
EXPECT_EQ("application/json; charset=utf-8",
mock_report_sender.latest_content_type());
ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(
report, host_port_pair, pkp_state.include_subdomains, pkp_state.domain,
cert1.get(), cert2.get(), pkp_state.spki_hashes));
}
// Tests that report URIs are thrown out if they point to the same host,
// over HTTPS, for which a pin was violated.
TEST_F(TransportSecurityStateTest, HPKPReportUriToSameHost) {
HostPortPair host_port_pair(kHost, kPort);
GURL https_report_uri("https://example.test/report");
GURL http_report_uri("http://example.test/report");
TransportSecurityState state;
MockCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
const base::Time current_time = base::Time::Now();
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
HashValueVector good_hashes;
for (size_t i = 0; kGoodPath[i]; i++)
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter, as long as they don't match the certs in the pins.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector bad_hashes;
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
state.AddHPKP(kHost, expiry, true, good_hashes, https_report_uri);
// Trigger a violation and check that it does not send a report
// because the report-uri is HTTPS and same-host as the pins.
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
EXPECT_TRUE(mock_report_sender.latest_report_uri().is_empty());
// An HTTP report uri to the same host should be okay.
state.AddHPKP("example.test", expiry, true, good_hashes, http_report_uri);
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
EXPECT_EQ(http_report_uri, mock_report_sender.latest_report_uri());
}
// Tests that static (preloaded) expect CT state is read correctly.
TEST_F(TransportSecurityStateTest, PreloadedExpectCT) {
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_TRUE(
GetExpectCTState(&state, kExpectCTStaticHostname, &expect_ct_state));
EXPECT_EQ(kExpectCTStaticHostname, expect_ct_state.domain);
EXPECT_EQ(GURL(kExpectCTStaticReportURI), expect_ct_state.report_uri);
EXPECT_FALSE(
GetExpectCTState(&state, "hsts-preloaded.test", &expect_ct_state));
}
// Tests that the Expect CT reporter is not notified for invalid or absent
// header values.
TEST_F(TransportSecurityStateTest, InvalidExpectCTHeader) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
state.ProcessExpectCTHeader("blah blah", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is only notified about certificates
// chaining to public roots.
TEST_F(TransportSecurityStateTest, ExpectCTNonPublicRoot) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
ssl_info.is_issued_by_known_root = false;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
ssl_info.is_issued_by_known_root = true;
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified when compliance
// details aren't available.
TEST_F(TransportSecurityStateTest, ExpectCTComplianceNotAvailable) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified about compliant
// connections.
TEST_F(TransportSecurityStateTest, ExpectCTCompliantCert) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified for preloaded Expect-CT
// when the build is not timely.
TEST_F(TransportSecurityStateTest, PreloadedExpectCTBuildNotTimely) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
// Sanity-check that the reporter is notified if the build is timely and the
// connection is not compliant.
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified for dynamic Expect-CT when
// the build is not timely.
TEST_F(TransportSecurityStateTest, DynamicExpectCTBuildNotTimely) {
HostPortPair host_port("example.test", 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
const char kHeader[] = "max-age=10, report-uri=http://report.test";
state.ProcessExpectCTHeader(kHeader, host_port, ssl_info);
// No report should have been sent and the state should not have been saved.
EXPECT_EQ(0u, reporter.num_failures());
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
// Sanity-check that the reporter is notified if the build is timely and the
// connection is not compliant.
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
state.ProcessExpectCTHeader(kHeader, host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is not notified for a site that
// isn't preloaded.
TEST_F(TransportSecurityStateTest, ExpectCTNotPreloaded) {
HostPortPair host_port("not-expect-ct-preloaded.test", 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(0u, reporter.num_failures());
host_port.set_host(kExpectCTStaticHostname);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect CT reporter is notified for noncompliant
// connections.
TEST_F(TransportSecurityStateTest, ExpectCTReporter) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert1);
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE,
&ssl_info.signed_certificate_timestamps);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ(host_port.host(), reporter.host_port_pair().host());
EXPECT_EQ(host_port.port(), reporter.host_port_pair().port());
EXPECT_TRUE(reporter.expiration().is_null());
EXPECT_EQ(GURL(kExpectCTStaticReportURI), reporter.report_uri());
EXPECT_EQ(cert1.get(), reporter.served_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.validated_certificate_chain());
EXPECT_EQ(ssl_info.signed_certificate_timestamps.size(),
reporter.signed_certificate_timestamps().size());
EXPECT_EQ(ssl_info.signed_certificate_timestamps[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(ssl_info.signed_certificate_timestamps[0].sct,
reporter.signed_certificate_timestamps()[0].sct);
}
// Tests that the Expect CT reporter is not notified for repeated noncompliant
// connections to the same preloaded host.
TEST_F(TransportSecurityStateTest, RepeatedExpectCTReportsForStaticExpectCT) {
HostPortPair host_port(kExpectCTStaticHostname, 443);
SSLInfo ssl_info;
ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
ssl_info.is_issued_by_known_root = true;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl_info.unverified_cert = cert1;
ssl_info.cert = cert2;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE,
&ssl_info.signed_certificate_timestamps);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticExpectCT(&state);
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
// After processing a second header, the report should not be sent again.
state.ProcessExpectCTHeader("preload", host_port, ssl_info);
EXPECT_EQ(1u, reporter.num_failures());
}
// Simple test for the HSTS preload process. The trie (generated from
// transport_security_state_static_unittest1.json) contains 1 entry. Test that
// the lookup methods can find the entry and correctly decode the different
// preloaded states (HSTS, HPKP, and Expect-CT).
TEST_F(TransportSecurityStateTest, DecodePreloadedSingle) {
SetTransportSecurityStateSourceForTesting(&test1::kHSTSSource);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityStateTest::EnableStaticExpectCT(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EXPECT_TRUE(
GetStaticDomainState(&state, "hsts.example.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL(), pkp_state.report_uri);
ASSERT_EQ(1u, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
ASSERT_EQ(1u, pkp_state.bad_spki_hashes.size());
EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x2));
TransportSecurityState::ExpectCTState ct_state;
EXPECT_FALSE(GetExpectCTState(&state, "hsts.example.com", &ct_state));
}
// More advanced test for the HSTS preload process where the trie (generated
// from transport_security_state_static_unittest2.json) contains multiple
// entries with a common prefix. Test that the lookup methods can find all
// entries and correctly decode the different preloaded states (HSTS, HPKP,
// and Expect-CT) for each entry.
TEST_F(TransportSecurityStateTest, DecodePreloadedMultiplePrefix) {
SetTransportSecurityStateSourceForTesting(&test2::kHSTSSource);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityStateTest::EnableStaticExpectCT(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
TransportSecurityState::ExpectCTState ct_state;
EXPECT_TRUE(
GetStaticDomainState(&state, "hsts.example.com", &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_FALSE(GetExpectCTState(&state, "hsts.example.com", &ct_state));
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "hpkp.example.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
EXPECT_FALSE(GetExpectCTState(&state, "hpkp.example.com", &ct_state));
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(GetStaticDomainState(&state, "expect-ct.example.com", &sts_state,
&pkp_state));
EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_TRUE(GetExpectCTState(&state, "expect-ct.example.com", &ct_state));
EXPECT_EQ(GURL("https://report.example.com/ct-upload"), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "mix.example.com", &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL(), pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x2));
EXPECT_EQ(1U, pkp_state.bad_spki_hashes.size());
EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_TRUE(GetExpectCTState(&state, "mix.example.com", &ct_state));
EXPECT_EQ(GURL("https://report.example.com/ct-upload-alt"),
ct_state.report_uri);
}
// More advanced test for the HSTS preload process where the trie (generated
// from transport_security_state_static_unittest3.json) contains a mix of
// entries. Some entries share a prefix with the prefix also having its own
// preloaded state while others share no prefix. This results in a trie with
// several different internal structures. Test that the lookup methods can find
// all entries and correctly decode the different preloaded states (HSTS, HPKP,
// and Expect-CT) for each entry.
TEST_F(TransportSecurityStateTest, DecodePreloadedMultipleMix) {
SetTransportSecurityStateSourceForTesting(&test3::kHSTSSource);
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityStateTest::EnableStaticExpectCT(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
TransportSecurityState::ExpectCTState ct_state;
EXPECT_TRUE(
GetStaticDomainState(&state, "example.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_FALSE(GetExpectCTState(&state, "example.com", &ct_state));
EXPECT_EQ(GURL(), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "hpkp.example.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
EXPECT_FALSE(GetExpectCTState(&state, "hpkp.example.com", &ct_state));
EXPECT_EQ(GURL(), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "example.org", &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_TRUE(GetExpectCTState(&state, "example.org", &ct_state));
EXPECT_EQ(GURL("https://report.example.org/ct-upload"), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "badssl.com", &sts_state, &pkp_state));
EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
EXPECT_FALSE(GetExpectCTState(&state, "badssl.com", &ct_state));
EXPECT_EQ(GURL(), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
EXPECT_TRUE(
GetStaticDomainState(&state, "mix.badssl.com", &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state.include_subdomains);
EXPECT_EQ(GURL(), pkp_state.report_uri);
EXPECT_EQ(1U, pkp_state.spki_hashes.size());
EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x2));
EXPECT_EQ(1U, pkp_state.bad_spki_hashes.size());
EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x1));
EXPECT_TRUE(GetExpectCTState(&state, "mix.badssl.com", &ct_state));
EXPECT_EQ(GURL("https://report.example.com/ct-upload"), ct_state.report_uri);
sts_state = TransportSecurityState::STSState();
pkp_state = TransportSecurityState::PKPState();
ct_state = TransportSecurityState::ExpectCTState();
// This should be a simple entry in the context of
// TrieWriter::IsSimpleEntry().
EXPECT_TRUE(GetStaticDomainState(&state, "simple-entry.example.com",
&sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
sts_state.upgrade_mode);
EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
EXPECT_FALSE(GetExpectCTState(&state, "simple-entry.example.com", &ct_state));
}
TEST_F(TransportSecurityStateTest, HstsHostBypassList) {
SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
std::string preloaded_tld = "example";
std::string subdomain = "sub.example";
{
TransportSecurityState state;
// Check that "example" is preloaded with subdomains.
EXPECT_TRUE(state.ShouldUpgradeToSSL(preloaded_tld));
EXPECT_TRUE(state.ShouldUpgradeToSSL(subdomain));
}
{
// Add "example" to the bypass list.
TransportSecurityState state({preloaded_tld});
EXPECT_FALSE(state.ShouldUpgradeToSSL(preloaded_tld));
// The preloaded entry should still apply to the subdomain.
EXPECT_TRUE(state.ShouldUpgradeToSSL(subdomain));
}
}
// Tests that TransportSecurityState always consults the RequireCTDelegate,
// if supplied.
TEST_F(TransportSecurityStateTest, RequireCTConsultsDelegate) {
using ::testing::_;
using ::testing::Return;
using CTRequirementLevel =
TransportSecurityState::RequireCTDelegate::CTRequirementLevel;
// Dummy cert to use as the validate chain. The contents do not matter.
scoped_refptr<X509Certificate> cert =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert);
HashValueVector hashes;
hashes.push_back(
HashValue(X509Certificate::CalculateFingerprint256(cert->cert_buffer())));
// If CT is required, then the requirements are not met if the CT policy
// wasn't met, but are met if the policy was met or the build was out of
// date.
{
TransportSecurityState state;
const TransportSecurityState::CTRequirementsStatus original_status =
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
MockRequireCTDelegate always_require_delegate;
EXPECT_CALL(always_require_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::REQUIRED));
state.SetRequireCTDelegate(&always_require_delegate);
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
state.SetRequireCTDelegate(nullptr);
EXPECT_EQ(
original_status,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}
// If CT is not required, then regardless of the CT state for the host,
// it should indicate CT is not required.
{
TransportSecurityState state;
const TransportSecurityState::CTRequirementsStatus original_status =
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
MockRequireCTDelegate never_require_delegate;
EXPECT_CALL(never_require_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::NOT_REQUIRED));
state.SetRequireCTDelegate(&never_require_delegate);
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
state.SetRequireCTDelegate(nullptr);
EXPECT_EQ(
original_status,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}
// If the Delegate is in the default state, then it should return the same
// result as if there was no delegate in the first place.
{
TransportSecurityState state;
const TransportSecurityState::CTRequirementsStatus original_status =
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
MockRequireCTDelegate default_require_ct_delegate;
EXPECT_CALL(default_require_ct_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::DEFAULT));
state.SetRequireCTDelegate(&default_require_ct_delegate);
EXPECT_EQ(
original_status,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
state.SetRequireCTDelegate(nullptr);
EXPECT_EQ(
original_status,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}
}
// Tests that Certificate Transparency is required for Symantec-issued
// certificates, unless the certificate was issued prior to 1 June 2016
// or the issuing CA is permitted as independently operated.
TEST_F(TransportSecurityStateTest, RequireCTForSymantec) {
// Test certificates before and after the 1 June 2016 deadline.
scoped_refptr<X509Certificate> before_cert =
ImportCertFromFile(GetTestCertsDirectory(), "pre_june_2016.pem");
ASSERT_TRUE(before_cert);
scoped_refptr<X509Certificate> after_cert =
ImportCertFromFile(GetTestCertsDirectory(), "post_june_2016.pem");
ASSERT_TRUE(after_cert);
const SHA256HashValue symantec_hash_value = {
{0xb2, 0xde, 0xf5, 0x36, 0x2a, 0xd3, 0xfa, 0xcd, 0x04, 0xbd, 0x29,
0x04, 0x7a, 0x43, 0x84, 0x4f, 0x76, 0x70, 0x34, 0xea, 0x48, 0x92,
0xf8, 0x0e, 0x56, 0xbe, 0xe6, 0x90, 0x24, 0x3e, 0x25, 0x02}};
const SHA256HashValue google_hash_value = {
{0xec, 0x72, 0x29, 0x69, 0xcb, 0x64, 0x20, 0x0a, 0xb6, 0x63, 0x8f,
0x68, 0xac, 0x53, 0x8e, 0x40, 0xab, 0xab, 0x5b, 0x19, 0xa6, 0x48,
0x56, 0x61, 0x04, 0x2a, 0x10, 0x61, 0xc4, 0x61, 0x27, 0x76}};
TransportSecurityState state;
HashValueVector hashes;
hashes.push_back(HashValue(symantec_hash_value));
// Certificates issued by Symantec prior to 1 June 2016 should not
// be required to be disclosed via CT.
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
// ... but certificates issued after 1 June 2016 are required to be...
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
// ... unless they were issued by an excluded intermediate.
hashes.push_back(HashValue(google_hash_value));
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
// And other certificates should remain unaffected.
SHA256HashValue unrelated_hash_value = {{0x01, 0x02}};
HashValueVector unrelated_hashes;
unrelated_hashes.push_back(HashValue(unrelated_hash_value));
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, unrelated_hashes,
before_cert.get(), before_cert.get(),
SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, unrelated_hashes,
after_cert.get(), after_cert.get(),
SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
}
// Tests that CAs can enable CT for testing their issuance practices, prior
// to CT becoming mandatory.
TEST_F(TransportSecurityStateTest, RequireCTViaFieldTrial) {
// Test certificates before and after the 1 June 2016 deadline.
scoped_refptr<X509Certificate> cert =
ImportCertFromFile(GetTestCertsDirectory(), "dec_2017.pem");
ASSERT_TRUE(cert);
// The hashes here do not matter, but add some dummy values to simulate
// a 'real' chain.
HashValueVector hashes;
const SHA256HashValue hash_a = {{0xAA, 0xAA}};
hashes.push_back(HashValue(hash_a));
const SHA256HashValue hash_b = {{0xBB, 0xBB}};
hashes.push_back(HashValue(hash_b));
TransportSecurityState state;
// CT should not be required for this pre-existing certificate.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
// However, simulating a Field Trial in which CT is required for certificates
// after 2017-12-01 should cause CT to be required for this certificate, as
// it was issued 2017-12-20.
base::FieldTrialParams params;
// Set the enforcement date to 2017-12-01 00:00:00;
params["date"] = "1512086400";
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeatureWithParameters(kEnforceCTForNewCerts,
params);
// It should fail if it doesn't comply with policy.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
// It should succeed if it does comply with policy.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
// It should succeed if the build is outdated.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
// It should succeed if it was a locally-trusted CA.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), false, hashes, cert.get(),
cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
}
// Tests that Certificate Transparency is required for all of the Symantec
// Managed CAs, regardless of when the certificate was issued.
TEST_F(TransportSecurityStateTest, RequireCTForSymantecManagedCAs) {
const SHA256HashValue symantec_hash_value = {
{0xb2, 0xde, 0xf5, 0x36, 0x2a, 0xd3, 0xfa, 0xcd, 0x04, 0xbd, 0x29,
0x04, 0x7a, 0x43, 0x84, 0x4f, 0x76, 0x70, 0x34, 0xea, 0x48, 0x92,
0xf8, 0x0e, 0x56, 0xbe, 0xe6, 0x90, 0x24, 0x3e, 0x25, 0x02}};
const SHA256HashValue managed_hash_value = {
{0x7c, 0xac, 0x9a, 0x0f, 0xf3, 0x15, 0x38, 0x77, 0x50, 0xba, 0x8b,
0xaf, 0xdb, 0x1c, 0x2b, 0xc2, 0x9b, 0x3f, 0x0b, 0xba, 0x16, 0x36,
0x2c, 0xa9, 0x3a, 0x90, 0xf8, 0x4d, 0xa2, 0xdf, 0x5f, 0x3e}};
TransportSecurityState state;
HashValueVector hashes;
hashes.push_back(HashValue(symantec_hash_value));
hashes.push_back(HashValue(managed_hash_value));
// All certificates, both before and after the pre-existing 1 June 2016
// date, are expected to be compliant.
scoped_refptr<X509Certificate> before_cert =
ImportCertFromFile(GetTestCertsDirectory(), "pre_june_2016.pem");
ASSERT_TRUE(before_cert);
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, before_cert.get(),
before_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
scoped_refptr<X509Certificate> after_cert =
ImportCertFromFile(GetTestCertsDirectory(), "post_june_2016.pem");
ASSERT_TRUE(after_cert);
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
EXPECT_EQ(
TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("www.example.com", 443), true, hashes, after_cert.get(),
after_cert.get(), SignedCertificateTimestampAndStatusList(),
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
}
// Tests that dynamic Expect-CT state is cleared from ClearDynamicData().
TEST_F(TransportSecurityStateTest, DynamicExpectCTStateCleared) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
const std::string host("example.test");
TransportSecurityState state;
TransportSecurityState::ExpectCTState expect_ct_state;
const base::Time current_time = base::Time::Now();
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddExpectCT(host, expiry, true, GURL());
EXPECT_TRUE(state.GetDynamicExpectCTState(host, &expect_ct_state));
EXPECT_TRUE(expect_ct_state.enforce);
EXPECT_TRUE(expect_ct_state.report_uri.is_empty());
EXPECT_EQ(expiry, expect_ct_state.expiry);
state.ClearDynamicData();
EXPECT_FALSE(state.GetDynamicExpectCTState(host, &expect_ct_state));
}
// Tests that dynamic Expect-CT state can be added and retrieved.
TEST_F(TransportSecurityStateTest, DynamicExpectCTState) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
const std::string host("example.test");
TransportSecurityState state;
TransportSecurityState::ExpectCTState expect_ct_state;
const base::Time current_time = base::Time::Now();
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
// Test that Expect-CT state can be added and retrieved.
state.AddExpectCT(host, expiry, true, GURL());
EXPECT_TRUE(state.GetDynamicExpectCTState(host, &expect_ct_state));
EXPECT_TRUE(expect_ct_state.enforce);
EXPECT_TRUE(expect_ct_state.report_uri.is_empty());
EXPECT_EQ(expiry, expect_ct_state.expiry);
// Test that Expect-CT can be updated (e.g. by changing |enforce| to false and
// adding a report-uri).
const GURL report_uri("https://example-report.test");
state.AddExpectCT(host, expiry, false, report_uri);
EXPECT_TRUE(state.GetDynamicExpectCTState(host, &expect_ct_state));
EXPECT_FALSE(expect_ct_state.enforce);
EXPECT_EQ(report_uri, expect_ct_state.report_uri);
EXPECT_EQ(expiry, expect_ct_state.expiry);
// Test that Expect-CT state is discarded when expired.
state.AddExpectCT(host, current_time - base::TimeDelta::FromSeconds(1000),
true, report_uri);
EXPECT_FALSE(state.GetDynamicExpectCTState(host, &expect_ct_state));
}
// Tests that the Expect-CT reporter is not notified for repeated dynamic
// Expect-CT violations for the same host/port.
TEST_F(TransportSecurityStateTest, DynamicExpectCTDeduping) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
base::Time now = base::Time::Now();
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_TRUE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(GURL("http://foo.test"), expect_ct_state.report_uri);
EXPECT_TRUE(expect_ct_state.enforce);
EXPECT_LT(now, expect_ct_state.expiry);
// No report should be sent when the header was processed over a connection
// that complied with CT policy.
EXPECT_EQ(0u, reporter.num_failures());
// The first time the host fails to meet CT requirements, a report should be
// sent.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
// The second time it fails to meet CT requirements, a report should not be
// sent.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that the Expect-CT reporter is not notified for CT-compliant
// connections.
TEST_F(TransportSecurityStateTest, DynamicExpectCTCompliantConnection) {
const char kHeader[] = "max-age=123,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
// No report should be sent when the header was processed over a connection
// that complied with CT policy.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
EXPECT_EQ(0u, reporter.num_failures());
}
// Tests that the Expect-CT reporter is not notified when the Expect-CT header
// is received repeatedly over non-compliant connections.
TEST_F(TransportSecurityStateTest, DynamicExpectCTHeaderProcessingDeduping) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
// The first time the header was received over a connection that failed to
// meet CT requirements, a report should be sent.
EXPECT_EQ(1u, reporter.num_failures());
// The second time the header was received, no report should be sent.
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
EXPECT_EQ(1u, reporter.num_failures());
}
// Tests that dynamic Expect-CT state cannot be added when the feature is not
// enabled.
TEST_F(TransportSecurityStateTest, DynamicExpectCTStateDisabled) {
base::test::ScopedFeatureList feature_list;
feature_list.InitAndDisableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
const std::string host("example.test");
TransportSecurityState state;
TransportSecurityState::ExpectCTState expect_ct_state;
const base::Time current_time = base::Time::Now();
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddExpectCT(host, expiry, true, GURL());
EXPECT_FALSE(state.GetDynamicExpectCTState(host, &expect_ct_state));
}
// Tests that dynamic Expect-CT opt-ins are processed correctly (when the
// feature is enabled).
TEST_F(TransportSecurityStateTest, DynamicExpectCT) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
// First test that the header is not processed when the feature is disabled.
{
base::test::ScopedFeatureList feature_list;
feature_list.InitAndDisableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443),
ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(
state.GetDynamicExpectCTState("example.test", &expect_ct_state));
}
// Now test that the header is processed when the feature is enabled.
{
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
base::Time now = base::Time::Now();
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443),
ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_TRUE(
state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(GURL("http://foo.test"), expect_ct_state.report_uri);
EXPECT_TRUE(expect_ct_state.enforce);
EXPECT_LT(now, expect_ct_state.expiry);
// No report should be sent when the header was processed over a connection
// that complied with CT policy.
EXPECT_EQ(0u, reporter.num_failures());
}
}
// Tests that dynamic Expect-CT is not processed for private roots.
TEST_F(TransportSecurityStateTest, DynamicExpectCTPrivateRoot) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = false;
ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(0u, reporter.num_failures());
}
// Tests that dynamic Expect-CT is not processed when CT compliance status
// wasn't computed.
TEST_F(TransportSecurityStateTest, DynamicExpectCTNoComplianceDetails) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIANCE_DETAILS_NOT_AVAILABLE;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl.unverified_cert = cert1;
ssl.cert = cert2;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(0u, reporter.num_failures());
}
// Tests that Expect-CT reports are sent when an Expect-CT header is received
// over a non-compliant connection.
TEST_F(TransportSecurityStateTest,
DynamicExpectCTHeaderProcessingNonCompliant) {
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance = ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS;
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
ssl.unverified_cert = cert1;
ssl.cert = cert2;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE,
&ssl.signed_certificate_timestamps);
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443), ssl);
TransportSecurityState::ExpectCTState expect_ct_state;
EXPECT_FALSE(state.GetDynamicExpectCTState("example.test", &expect_ct_state));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ("example.test", reporter.host_port_pair().host());
EXPECT_TRUE(reporter.expiration().is_null());
EXPECT_EQ(cert1.get(), reporter.served_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.validated_certificate_chain());
EXPECT_EQ(ssl.signed_certificate_timestamps.size(),
reporter.signed_certificate_timestamps().size());
EXPECT_EQ(ssl.signed_certificate_timestamps[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(ssl.signed_certificate_timestamps[0].sct,
reporter.signed_certificate_timestamps()[0].sct);
}
// Tests that CheckCTRequirements() returns the correct response if a connection
// to a host violates an Expect-CT header, and that it reports violations.
TEST_F(TransportSecurityStateTest, CheckCTRequirementsWithExpectCT) {
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE, &sct_list);
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.AddExpectCT("example.test", expiry, true /* enforce */,
GURL("https://example-report.test"));
state.AddExpectCT("example-report-only.test", expiry, false /* enforce */,
GURL("https://example-report.test"));
state.AddExpectCT("example-enforce-only.test", expiry, true /* enforce */,
GURL());
// Test that a connection to an unrelated host is not affected.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example2.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example2.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(0u, reporter.num_failures());
// A connection to an Expect-CT host should be closed and reported.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ("example.test", reporter.host_port_pair().host());
EXPECT_EQ(443, reporter.host_port_pair().port());
EXPECT_EQ(expiry, reporter.expiration());
EXPECT_EQ(cert1.get(), reporter.validated_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.served_certificate_chain());
EXPECT_EQ(sct_list.size(), reporter.signed_certificate_timestamps().size());
EXPECT_EQ(sct_list[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(sct_list[0].sct, reporter.signed_certificate_timestamps()[0].sct);
// A compliant connection to an Expect-CT host should not be closed or
// reported.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
EXPECT_EQ(1u, reporter.num_failures());
// A connection to a report-only host should be reported only.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example-report-only.test", 443), true,
HashValueVector(), cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(2u, reporter.num_failures());
EXPECT_EQ("example-report-only.test", reporter.host_port_pair().host());
EXPECT_EQ(443, reporter.host_port_pair().port());
EXPECT_EQ(cert1.get(), reporter.validated_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.served_certificate_chain());
EXPECT_EQ(sct_list.size(), reporter.signed_certificate_timestamps().size());
EXPECT_EQ(sct_list[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(sct_list[0].sct, reporter.signed_certificate_timestamps()[0].sct);
// A connection to an enforce-only host should be closed but not reported.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example-enforce-only.test", 443), true,
HashValueVector(), cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
EXPECT_EQ(2u, reporter.num_failures());
// A connection with a private root should be neither enforced nor reported.
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example.test", 443), false, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(2u, reporter.num_failures());
// A connection with DISABLE_EXPECT_CT_REPORTS should not send a report.
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(2u, reporter.num_failures());
}
// Tests that for a host that requires CT by delegate and is also
// Expect-CT-enabled, CheckCTRequirements() sends reports.
TEST_F(TransportSecurityStateTest, CheckCTRequirementsWithExpectCTAndDelegate) {
using ::testing::_;
using ::testing::Return;
using CTRequirementLevel =
TransportSecurityState::RequireCTDelegate::CTRequirementLevel;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE, &sct_list);
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.AddExpectCT("example.test", expiry, false /* enforce */,
GURL("https://example-report.test"));
// A connection to an Expect-CT host, which also requires CT by the delegate,
// should be closed and reported.
MockRequireCTDelegate always_require_delegate;
EXPECT_CALL(always_require_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::REQUIRED));
state.SetRequireCTDelegate(&always_require_delegate);
EXPECT_EQ(TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ("example.test", reporter.host_port_pair().host());
EXPECT_EQ(443, reporter.host_port_pair().port());
EXPECT_EQ(expiry, reporter.expiration());
EXPECT_EQ(cert1.get(), reporter.validated_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.served_certificate_chain());
EXPECT_EQ(sct_list.size(), reporter.signed_certificate_timestamps().size());
EXPECT_EQ(sct_list[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(sct_list[0].sct, reporter.signed_certificate_timestamps()[0].sct);
}
// Tests that for a host that explicitly disabled CT by delegate and is also
// Expect-CT-enabled, CheckCTRequirements() sends reports.
TEST_F(TransportSecurityStateTest,
CheckCTRequirementsWithExpectCTAndDelegateDisables) {
using ::testing::_;
using ::testing::Return;
using CTRequirementLevel =
TransportSecurityState::RequireCTDelegate::CTRequirementLevel;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
SignedCertificateTimestampAndStatusList sct_list;
MakeTestSCTAndStatus(ct::SignedCertificateTimestamp::SCT_EMBEDDED, "test_log",
std::string(), std::string(), base::Time::Now(),
ct::SCT_STATUS_INVALID_SIGNATURE, &sct_list);
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.AddExpectCT("example.test", expiry, false /* enforce */,
GURL("https://example-report.test"));
// A connection to an Expect-CT host, which is exempted from the CT
// requirements by the delegate, should be reported but not closed.
MockRequireCTDelegate never_require_delegate;
EXPECT_CALL(never_require_delegate, IsCTRequiredForHost(_, _, _))
.WillRepeatedly(Return(CTRequirementLevel::NOT_REQUIRED));
state.SetRequireCTDelegate(&never_require_delegate);
EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
state.CheckCTRequirements(
HostPortPair("example.test", 443), true, HashValueVector(),
cert1.get(), cert2.get(), sct_list,
TransportSecurityState::ENABLE_EXPECT_CT_REPORTS,
ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
EXPECT_EQ(1u, reporter.num_failures());
EXPECT_EQ("example.test", reporter.host_port_pair().host());
EXPECT_EQ(443, reporter.host_port_pair().port());
EXPECT_EQ(expiry, reporter.expiration());
EXPECT_EQ(cert1.get(), reporter.validated_certificate_chain());
EXPECT_EQ(cert2.get(), reporter.served_certificate_chain());
EXPECT_EQ(sct_list.size(), reporter.signed_certificate_timestamps().size());
EXPECT_EQ(sct_list[0].status,
reporter.signed_certificate_timestamps()[0].status);
EXPECT_EQ(sct_list[0].sct, reporter.signed_certificate_timestamps()[0].sct);
}
// Tests that the dynamic Expect-CT UMA histogram is recorded correctly.
TEST_F(TransportSecurityStateTest, DynamicExpectCTUMA) {
const char kHistogramName[] = "Net.ExpectCTHeader.ParseSuccess";
SSLInfo ssl;
ssl.is_issued_by_known_root = true;
ssl.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
TransportSecurityState::kDynamicExpectCTFeature);
// Test that the histogram is recorded correctly when the header successfully
// parses.
{
const char kHeader[] = "max-age=123,enforce,report-uri=\"http://foo.test\"";
base::HistogramTester histograms;
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443),
ssl);
histograms.ExpectTotalCount(kHistogramName, 1);
histograms.ExpectBucketCount(kHistogramName, true, 1);
}
// Test that the histogram is recorded correctly when the header fails to
// parse (due to semi-colons instead of commas).
{
const char kHeader[] = "max-age=123;enforce;report-uri=\"http://foo.test\"";
base::HistogramTester histograms;
TransportSecurityState state;
MockExpectCTReporter reporter;
state.SetExpectCTReporter(&reporter);
state.ProcessExpectCTHeader(kHeader, HostPortPair("example.test", 443),
ssl);
histograms.ExpectTotalCount(kHistogramName, 1);
histograms.ExpectBucketCount(kHistogramName, false, 1);
}
}
// Tests the Net.HstsInfo histogram is recorded correctly. See
// https://crbug.com/821811.
TEST_F(TransportSecurityStateTest, HstsInfoHistogram) {
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromDays(1000);
TransportSecurityState state;
// a.test is not on the static list, so the dynamic set applies.
state.AddHSTS("a.test", expiry, /*include_subdomains=*/true);
state.AddHSTS("a.a.test", expiry, /*include_subdomains=*/false);
// Also test the interaction with the HSTS preload list.
state.AddHSTS("a.include-subdomains-hsts-preloaded.test", expiry,
/*include_subdomains=*/true);
state.AddHSTS("a.a.include-subdomains-hsts-preloaded.test", expiry,
/*include_subdomains=*/false);
const struct {
const char* host;
HstsInfo expected;
} kTests[] = {
// HSTS was not enabled.
{"b.test", HstsInfo::kDisabled},
// HSTS was enabled via the header.
{"a.test", HstsInfo::kEnabled},
{"a.a.test", HstsInfo::kEnabled},
// HSTS was enabled via the preload list.
{"b.include-subdomains-hsts-preloaded.test", HstsInfo::kEnabled},
// HSTS should have been enabled but was not due to spec non-compliance.
{"a.a.a.test", HstsInfo::kDynamicIncorrectlyMasked},
// Spec non-compliance was masked by the preload list.
{"a.a.a.include-subdomains-hsts-preloaded.test",
HstsInfo::kDynamicIncorrectlyMaskedButMatchedStatic},
};
for (const auto& test : kTests) {
SCOPED_TRACE(test.host);
bool enabled =
test.expected == HstsInfo::kEnabled ||
test.expected == HstsInfo::kDynamicIncorrectlyMaskedButMatchedStatic;
{
base::HistogramTester histograms;
EXPECT_EQ(enabled, state.ShouldUpgradeToSSL(test.host));
histograms.ExpectTotalCount("Net.HstsInfo", 1);
histograms.ExpectBucketCount("Net.HstsInfo", test.expected, 1);
}
{
base::HistogramTester histograms;
EXPECT_EQ(enabled, state.ShouldSSLErrorsBeFatal(test.host));
histograms.ExpectTotalCount("Net.HstsInfo", 1);
histograms.ExpectBucketCount("Net.HstsInfo", test.expected, 1);
}
}
}
#if BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
const char kSubdomain[] = "foo.example.test";
class TransportSecurityStateStaticTest : public TransportSecurityStateTest {
public:
TransportSecurityStateStaticTest() {
SetTransportSecurityStateSourceForTesting(nullptr);
}
};
static bool StaticShouldRedirect(const char* hostname) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
return state.GetStaticDomainState(hostname, &sts_state, &pkp_state) &&
sts_state.ShouldUpgradeToSSL();
}
static bool HasStaticState(const char* hostname) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
return state.GetStaticDomainState(hostname, &sts_state, &pkp_state);
}
static bool HasStaticPublicKeyPins(const char* hostname) {
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
if (!state.GetStaticDomainState(hostname, &sts_state, &pkp_state))
return false;
return pkp_state.HasPublicKeyPins();
}
static bool OnlyPinningInStaticState(const char* hostname) {
TransportSecurityState state;
TransportSecurityStateTest::EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
if (!state.GetStaticDomainState(hostname, &sts_state, &pkp_state))
return false;
return (pkp_state.spki_hashes.size() > 0 ||
pkp_state.bad_spki_hashes.size() > 0) &&
!sts_state.ShouldUpgradeToSSL();
}
TEST_F(TransportSecurityStateStaticTest, EnableStaticPins) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EnableStaticPins(&state);
EXPECT_TRUE(
state.GetStaticDomainState("chrome.google.com", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
}
TEST_F(TransportSecurityStateStaticTest, DisableStaticPins) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
DisableStaticPins(&state);
EXPECT_TRUE(
state.GetStaticDomainState("chrome.google.com", &sts_state, &pkp_state));
EXPECT_TRUE(pkp_state.spki_hashes.empty());
}
TEST_F(TransportSecurityStateStaticTest, IsPreloaded) {
const std::string paypal = "paypal.com";
const std::string www_paypal = "www.paypal.com";
const std::string foo_paypal = "foo.paypal.com";
const std::string a_www_paypal = "a.www.paypal.com";
const std::string abc_paypal = "a.b.c.paypal.com";
const std::string example = "example.com";
const std::string aypal = "aypal.com";
const std::string google = "google";
const std::string www_google = "www.google";
const std::string foo = "foo";
const std::string bank = "example.bank";
const std::string insurance = "sub.example.insurance";
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EXPECT_TRUE(GetStaticDomainState(&state, paypal, &sts_state, &pkp_state));
EXPECT_TRUE(GetStaticDomainState(&state, www_paypal, &sts_state, &pkp_state));
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_TRUE(GetStaticDomainState(&state, google, &sts_state, &pkp_state));
EXPECT_TRUE(GetStaticDomainState(&state, www_google, &sts_state, &pkp_state));
EXPECT_TRUE(GetStaticDomainState(&state, foo, &sts_state, &pkp_state));
EXPECT_TRUE(GetStaticDomainState(&state, bank, &sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_TRUE(GetStaticDomainState(&state, insurance, &sts_state, &pkp_state));
EXPECT_TRUE(sts_state.include_subdomains);
EXPECT_FALSE(
GetStaticDomainState(&state, a_www_paypal, &sts_state, &pkp_state));
EXPECT_FALSE(
GetStaticDomainState(&state, abc_paypal, &sts_state, &pkp_state));
EXPECT_FALSE(GetStaticDomainState(&state, example, &sts_state, &pkp_state));
EXPECT_FALSE(GetStaticDomainState(&state, aypal, &sts_state, &pkp_state));
}
TEST_F(TransportSecurityStateStaticTest, PreloadedDomainSet) {
TransportSecurityState state;
EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
// The domain wasn't being set, leading to a blank string in the
// chrome://net-internals/#hsts UI. So test that.
EXPECT_TRUE(
state.GetStaticDomainState("market.android.com", &sts_state, &pkp_state));
EXPECT_EQ(sts_state.domain, "market.android.com");
EXPECT_EQ(pkp_state.domain, "market.android.com");
EXPECT_TRUE(state.GetStaticDomainState("sub.market.android.com", &sts_state,
&pkp_state));
EXPECT_EQ(sts_state.domain, "market.android.com");
EXPECT_EQ(pkp_state.domain, "market.android.com");
}
TEST_F(TransportSecurityStateStaticTest, Preloaded) {
TransportSecurityState state;
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
// We do more extensive checks for the first domain.
EXPECT_TRUE(
state.GetStaticDomainState("www.paypal.com", &sts_state, &pkp_state));
EXPECT_EQ(sts_state.upgrade_mode,
TransportSecurityState::STSState::MODE_FORCE_HTTPS);
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_FALSE(pkp_state.include_subdomains);
EXPECT_TRUE(HasStaticState("paypal.com"));
EXPECT_FALSE(HasStaticState("www2.paypal.com"));
// Google hosts:
EXPECT_TRUE(StaticShouldRedirect("chrome.google.com"));
EXPECT_TRUE(StaticShouldRedirect("checkout.google.com"));
EXPECT_TRUE(StaticShouldRedirect("wallet.google.com"));
EXPECT_TRUE(StaticShouldRedirect("docs.google.com"));
EXPECT_TRUE(StaticShouldRedirect("sites.google.com"));
EXPECT_TRUE(StaticShouldRedirect("drive.google.com"));
EXPECT_TRUE(StaticShouldRedirect("spreadsheets.google.com"));
EXPECT_TRUE(StaticShouldRedirect("appengine.google.com"));
EXPECT_TRUE(StaticShouldRedirect("market.android.com"));
EXPECT_TRUE(StaticShouldRedirect("encrypted.google.com"));
EXPECT_TRUE(StaticShouldRedirect("accounts.google.com"));
EXPECT_TRUE(StaticShouldRedirect("profiles.google.com"));
EXPECT_TRUE(StaticShouldRedirect("mail.google.com"));
EXPECT_TRUE(StaticShouldRedirect("chatenabled.mail.google.com"));
EXPECT_TRUE(StaticShouldRedirect("talkgadget.google.com"));
EXPECT_TRUE(StaticShouldRedirect("hostedtalkgadget.google.com"));
EXPECT_TRUE(StaticShouldRedirect("talk.google.com"));
EXPECT_TRUE(StaticShouldRedirect("plus.google.com"));
EXPECT_TRUE(StaticShouldRedirect("groups.google.com"));
EXPECT_TRUE(StaticShouldRedirect("apis.google.com"));
EXPECT_TRUE(StaticShouldRedirect("oauthaccountmanager.googleapis.com"));
EXPECT_TRUE(StaticShouldRedirect("passwordsleakcheck-pa.googleapis.com"));
EXPECT_TRUE(StaticShouldRedirect("ssl.google-analytics.com"));
EXPECT_TRUE(StaticShouldRedirect("google"));
EXPECT_TRUE(StaticShouldRedirect("foo.google"));
EXPECT_TRUE(StaticShouldRedirect("foo"));
EXPECT_TRUE(StaticShouldRedirect("domaintest.foo"));
EXPECT_TRUE(StaticShouldRedirect("gmail.com"));
EXPECT_TRUE(StaticShouldRedirect("www.gmail.com"));
EXPECT_TRUE(StaticShouldRedirect("googlemail.com"));
EXPECT_TRUE(StaticShouldRedirect("www.googlemail.com"));
EXPECT_TRUE(StaticShouldRedirect("googleplex.com"));
EXPECT_TRUE(StaticShouldRedirect("www.googleplex.com"));
EXPECT_TRUE(StaticShouldRedirect("www.google-analytics.com"));
EXPECT_TRUE(StaticShouldRedirect("www.youtube.com"));
EXPECT_TRUE(StaticShouldRedirect("youtube.com"));
// These domains used to be only HSTS when SNI was available.
EXPECT_TRUE(state.GetStaticDomainState("gmail.com", &sts_state, &pkp_state));
EXPECT_TRUE(
state.GetStaticDomainState("www.gmail.com", &sts_state, &pkp_state));
EXPECT_TRUE(
state.GetStaticDomainState("googlemail.com", &sts_state, &pkp_state));
EXPECT_TRUE(
state.GetStaticDomainState("www.googlemail.com", &sts_state, &pkp_state));
// fi.g.co should not force HTTPS because there are still HTTP-only services
// on it.
EXPECT_FALSE(StaticShouldRedirect("fi.g.co"));
// Other hosts:
EXPECT_TRUE(StaticShouldRedirect("aladdinschools.appspot.com"));
EXPECT_TRUE(StaticShouldRedirect("ottospora.nl"));
EXPECT_TRUE(StaticShouldRedirect("www.ottospora.nl"));
EXPECT_TRUE(StaticShouldRedirect("www.paycheckrecords.com"));
EXPECT_TRUE(StaticShouldRedirect("lastpass.com"));
EXPECT_TRUE(StaticShouldRedirect("www.lastpass.com"));
EXPECT_FALSE(HasStaticState("blog.lastpass.com"));
EXPECT_TRUE(StaticShouldRedirect("keyerror.com"));
EXPECT_TRUE(StaticShouldRedirect("www.keyerror.com"));
EXPECT_TRUE(StaticShouldRedirect("entropia.de"));
EXPECT_TRUE(StaticShouldRedirect("www.entropia.de"));
EXPECT_FALSE(HasStaticState("foo.entropia.de"));
EXPECT_TRUE(StaticShouldRedirect("www.elanex.biz"));
EXPECT_FALSE(HasStaticState("elanex.biz"));
EXPECT_FALSE(HasStaticState("foo.elanex.biz"));
EXPECT_TRUE(StaticShouldRedirect("sunshinepress.org"));
EXPECT_TRUE(StaticShouldRedirect("www.sunshinepress.org"));
EXPECT_TRUE(StaticShouldRedirect("a.b.sunshinepress.org"));
EXPECT_TRUE(StaticShouldRedirect("www.noisebridge.net"));
EXPECT_FALSE(HasStaticState("noisebridge.net"));
EXPECT_FALSE(HasStaticState("foo.noisebridge.net"));
EXPECT_TRUE(StaticShouldRedirect("neg9.org"));
EXPECT_FALSE(HasStaticState("www.neg9.org"));
EXPECT_TRUE(StaticShouldRedirect("riseup.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.riseup.net"));
EXPECT_TRUE(StaticShouldRedirect("factor.cc"));
EXPECT_FALSE(HasStaticState("www.factor.cc"));
EXPECT_TRUE(StaticShouldRedirect("members.mayfirst.org"));
EXPECT_TRUE(StaticShouldRedirect("support.mayfirst.org"));
EXPECT_TRUE(StaticShouldRedirect("id.mayfirst.org"));
EXPECT_TRUE(StaticShouldRedirect("lists.mayfirst.org"));
EXPECT_FALSE(HasStaticState("www.mayfirst.org"));
EXPECT_TRUE(StaticShouldRedirect("romab.com"));
EXPECT_TRUE(StaticShouldRedirect("www.romab.com"));
EXPECT_TRUE(StaticShouldRedirect("foo.romab.com"));
EXPECT_TRUE(StaticShouldRedirect("logentries.com"));
EXPECT_TRUE(StaticShouldRedirect("www.logentries.com"));
EXPECT_FALSE(HasStaticState("foo.logentries.com"));
EXPECT_TRUE(StaticShouldRedirect("stripe.com"));
EXPECT_TRUE(StaticShouldRedirect("foo.stripe.com"));
EXPECT_TRUE(StaticShouldRedirect("cloudsecurityalliance.org"));
EXPECT_TRUE(StaticShouldRedirect("foo.cloudsecurityalliance.org"));
EXPECT_TRUE(StaticShouldRedirect("login.sapo.pt"));
EXPECT_TRUE(StaticShouldRedirect("foo.login.sapo.pt"));
EXPECT_TRUE(StaticShouldRedirect("mattmccutchen.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.mattmccutchen.net"));
EXPECT_TRUE(StaticShouldRedirect("betnet.fr"));
EXPECT_TRUE(StaticShouldRedirect("foo.betnet.fr"));
EXPECT_TRUE(StaticShouldRedirect("uprotect.it"));
EXPECT_TRUE(StaticShouldRedirect("foo.uprotect.it"));
EXPECT_TRUE(StaticShouldRedirect("cert.se"));
EXPECT_TRUE(StaticShouldRedirect("foo.cert.se"));
EXPECT_TRUE(StaticShouldRedirect("crypto.is"));
EXPECT_TRUE(StaticShouldRedirect("foo.crypto.is"));
EXPECT_TRUE(StaticShouldRedirect("simon.butcher.name"));
EXPECT_TRUE(StaticShouldRedirect("foo.simon.butcher.name"));
EXPECT_TRUE(StaticShouldRedirect("linx.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.linx.net"));
EXPECT_TRUE(StaticShouldRedirect("dropcam.com"));
EXPECT_TRUE(StaticShouldRedirect("www.dropcam.com"));
EXPECT_FALSE(HasStaticState("foo.dropcam.com"));
EXPECT_TRUE(StaticShouldRedirect("ebanking.indovinabank.com.vn"));
EXPECT_TRUE(StaticShouldRedirect("foo.ebanking.indovinabank.com.vn"));
EXPECT_TRUE(StaticShouldRedirect("epoxate.com"));
EXPECT_FALSE(HasStaticState("foo.epoxate.com"));
EXPECT_FALSE(HasStaticState("foo.torproject.org"));
EXPECT_TRUE(StaticShouldRedirect("www.moneybookers.com"));
EXPECT_FALSE(HasStaticState("moneybookers.com"));
EXPECT_TRUE(StaticShouldRedirect("ledgerscope.net"));
EXPECT_TRUE(StaticShouldRedirect("www.ledgerscope.net"));
EXPECT_FALSE(HasStaticState("status.ledgerscope.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.app.recurly.com"));
EXPECT_TRUE(StaticShouldRedirect("foo.api.recurly.com"));
EXPECT_TRUE(StaticShouldRedirect("greplin.com"));
EXPECT_TRUE(StaticShouldRedirect("www.greplin.com"));
EXPECT_FALSE(HasStaticState("foo.greplin.com"));
EXPECT_TRUE(StaticShouldRedirect("luneta.nearbuysystems.com"));
EXPECT_TRUE(StaticShouldRedirect("foo.luneta.nearbuysystems.com"));
EXPECT_TRUE(StaticShouldRedirect("ubertt.org"));
EXPECT_TRUE(StaticShouldRedirect("foo.ubertt.org"));
EXPECT_TRUE(StaticShouldRedirect("pixi.me"));
EXPECT_TRUE(StaticShouldRedirect("www.pixi.me"));
EXPECT_TRUE(StaticShouldRedirect("grepular.com"));
EXPECT_TRUE(StaticShouldRedirect("www.grepular.com"));
EXPECT_TRUE(StaticShouldRedirect("mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("www.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.www.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("developer.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.developer.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("www.developer.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.www.developer.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("sandbox.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.sandbox.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("www.sandbox.mydigipass.com"));
EXPECT_FALSE(StaticShouldRedirect("foo.www.sandbox.mydigipass.com"));
EXPECT_TRUE(StaticShouldRedirect("bigshinylock.minazo.net"));
EXPECT_TRUE(StaticShouldRedirect("foo.bigshinylock.minazo.net"));
EXPECT_TRUE(StaticShouldRedirect("crate.io"));
EXPECT_TRUE(StaticShouldRedirect("foo.crate.io"));
EXPECT_TRUE(StaticShouldRedirect("sub.bank"));
EXPECT_TRUE(StaticShouldRedirect("sub.insurance"));
}
TEST_F(TransportSecurityStateStaticTest, PreloadedPins) {
TransportSecurityState state;
EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
// We do more extensive checks for the first domain.
EXPECT_TRUE(
state.GetStaticDomainState("www.paypal.com", &sts_state, &pkp_state));
EXPECT_EQ(sts_state.upgrade_mode,
TransportSecurityState::STSState::MODE_FORCE_HTTPS);
EXPECT_FALSE(sts_state.include_subdomains);
EXPECT_FALSE(pkp_state.include_subdomains);
EXPECT_TRUE(OnlyPinningInStaticState("www.google.com"));
EXPECT_TRUE(OnlyPinningInStaticState("foo.google.com"));
EXPECT_TRUE(OnlyPinningInStaticState("google.com"));
EXPECT_TRUE(OnlyPinningInStaticState("i.ytimg.com"));
EXPECT_TRUE(OnlyPinningInStaticState("ytimg.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googleusercontent.com"));
EXPECT_TRUE(OnlyPinningInStaticState("www.googleusercontent.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googleapis.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googleadservices.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googlecode.com"));
EXPECT_TRUE(OnlyPinningInStaticState("appspot.com"));
EXPECT_TRUE(OnlyPinningInStaticState("googlesyndication.com"));
EXPECT_TRUE(OnlyPinningInStaticState("doubleclick.net"));
EXPECT_TRUE(OnlyPinningInStaticState("googlegroups.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("torproject.org"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.torproject.org"));
EXPECT_TRUE(HasStaticPublicKeyPins("check.torproject.org"));
EXPECT_TRUE(HasStaticPublicKeyPins("blog.torproject.org"));
EXPECT_FALSE(HasStaticState("foo.torproject.org"));
EXPECT_TRUE(
state.GetStaticDomainState("torproject.org", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(
state.GetStaticDomainState("www.torproject.org", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(state.GetStaticDomainState("check.torproject.org", &sts_state,
&pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(state.GetStaticDomainState("blog.torproject.org", &sts_state,
&pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(HasStaticPublicKeyPins("www.twitter.com"));
// Check that Facebook subdomains have pinning but not HSTS.
EXPECT_TRUE(
state.GetStaticDomainState("facebook.com", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(StaticShouldRedirect("facebook.com"));
EXPECT_TRUE(
state.GetStaticDomainState("foo.facebook.com", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_FALSE(StaticShouldRedirect("foo.facebook.com"));
EXPECT_TRUE(
state.GetStaticDomainState("www.facebook.com", &sts_state, &pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(StaticShouldRedirect("www.facebook.com"));
EXPECT_TRUE(state.GetStaticDomainState("foo.www.facebook.com", &sts_state,
&pkp_state));
EXPECT_FALSE(pkp_state.spki_hashes.empty());
EXPECT_TRUE(StaticShouldRedirect("foo.www.facebook.com"));
}
TEST_F(TransportSecurityStateStaticTest, BuiltinCertPins) {
TransportSecurityState state;
EnableStaticPins(&state);
TransportSecurityState::STSState sts_state;
TransportSecurityState::PKPState pkp_state;
EXPECT_TRUE(
state.GetStaticDomainState("chrome.google.com", &sts_state, &pkp_state));
EXPECT_TRUE(HasStaticPublicKeyPins("chrome.google.com"));
HashValueVector hashes;
std::string failure_log;
// Checks that a built-in list does exist.
EXPECT_FALSE(pkp_state.CheckPublicKeyPins(hashes, &failure_log));
EXPECT_FALSE(HasStaticPublicKeyPins("www.paypal.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("docs.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("1.docs.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("sites.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("drive.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("spreadsheets.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("wallet.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("checkout.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("appengine.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("market.android.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("encrypted.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("accounts.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("profiles.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("mail.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("chatenabled.mail.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("talkgadget.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("hostedtalkgadget.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("talk.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("plus.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("groups.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("apis.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.google-analytics.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.youtube.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("youtube.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("ssl.gstatic.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("gstatic.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.gstatic.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("ssl.google-analytics.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.googleplex.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("twitter.com"));
EXPECT_FALSE(HasStaticPublicKeyPins("foo.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("api.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("oauth.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("mobile.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("dev.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("business.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("platform.twitter.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("si0.twimg.com"));
}
TEST_F(TransportSecurityStateStaticTest, OptionalHSTSCertPins) {
TransportSecurityState state;
EnableStaticPins(&state);
EXPECT_TRUE(HasStaticPublicKeyPins("google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.google.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("mail-attachment.googleusercontent.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("www.youtube.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("i.ytimg.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("googleapis.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("ajax.googleapis.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("googleadservices.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("pagead2.googleadservices.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("googlecode.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("kibbles.googlecode.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("appspot.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("googlesyndication.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("doubleclick.net"));
EXPECT_TRUE(HasStaticPublicKeyPins("ad.doubleclick.net"));
EXPECT_TRUE(HasStaticPublicKeyPins("redirector.gvt1.com"));
EXPECT_TRUE(HasStaticPublicKeyPins("a.googlegroups.com"));
}
TEST_F(TransportSecurityStateStaticTest, OverrideBuiltins) {
EXPECT_TRUE(HasStaticPublicKeyPins("google.com"));
EXPECT_FALSE(StaticShouldRedirect("google.com"));
EXPECT_FALSE(StaticShouldRedirect("www.google.com"));
TransportSecurityState state;
const base::Time current_time(base::Time::Now());
const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
state.AddHSTS("www.google.com", expiry, true);
EXPECT_TRUE(state.ShouldUpgradeToSSL("www.google.com"));
}
// Tests that redundant reports are rate-limited.
TEST_F(TransportSecurityStateStaticTest, HPKPReportRateLimiting) {
HostPortPair host_port_pair(kHost, kPort);
HostPortPair subdomain_host_port_pair(kSubdomain, kPort);
GURL report_uri(kReportUri);
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector good_hashes, bad_hashes;
for (size_t i = 0; kGoodPath[i]; i++)
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
TransportSecurityState state;
EnableStaticPins(&state);
MockCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// A report should have been sent. Check that it contains the
// right information.
EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
std::string report = mock_report_sender.latest_report();
ASSERT_FALSE(report.empty());
ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, host_port_pair, true, kHost,
cert1.get(), cert2.get(),
good_hashes));
mock_report_sender.Clear();
// Now trigger the same violation; a duplicative report should not be
// sent.
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
}
TEST_F(TransportSecurityStateStaticTest, HPKPReporting) {
HostPortPair host_port_pair(kHost, kPort);
HostPortPair subdomain_host_port_pair(kSubdomain, kPort);
GURL report_uri(kReportUri);
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector good_hashes, bad_hashes;
for (size_t i = 0; kGoodPath[i]; i++)
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
TransportSecurityState state;
EnableStaticPins(&state);
MockCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::DISABLE_PIN_REPORTS, &failure_log));
// No report should have been sent because of the DISABLE_PIN_REPORTS
// argument.
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
state.CheckPublicKeyPins(
host_port_pair, true, good_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// No report should have been sent because there was no violation.
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
EXPECT_EQ(TransportSecurityState::PKPStatus::BYPASSED,
state.CheckPublicKeyPins(
host_port_pair, false, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// No report should have been sent because the certificate chained to a
// non-public root.
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
state.CheckPublicKeyPins(
host_port_pair, false, good_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// No report should have been sent because there was no violation, even though
// the certificate chained to a local trust anchor.
EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
EXPECT_EQ(std::string(), mock_report_sender.latest_report());
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// Now a report should have been sent. Check that it contains the
// right information.
EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
std::string report = mock_report_sender.latest_report();
ASSERT_FALSE(report.empty());
EXPECT_EQ("application/json; charset=utf-8",
mock_report_sender.latest_content_type());
ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, host_port_pair, true, kHost,
cert1.get(), cert2.get(),
good_hashes));
mock_report_sender.Clear();
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(subdomain_host_port_pair, true, bad_hashes,
cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS,
&failure_log));
// Now a report should have been sent for the subdomain. Check that it
// contains the right information.
EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
report = mock_report_sender.latest_report();
ASSERT_FALSE(report.empty());
EXPECT_EQ("application/json; charset=utf-8",
mock_report_sender.latest_content_type());
ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, subdomain_host_port_pair,
true, kHost, cert1.get(), cert2.get(),
good_hashes));
}
// Tests that a histogram entry is recorded when TransportSecurityState
// fails to send an HPKP violation report.
TEST_F(TransportSecurityStateStaticTest, UMAOnHPKPReportingFailure) {
base::HistogramTester histograms;
const std::string histogram_name = "Net.PublicKeyPinReportSendingFailure2";
HostPortPair host_port_pair(kHost, kPort);
GURL report_uri(kReportUri);
// Two dummy certs to use as the server-sent and validated chains. The
// contents don't matter.
scoped_refptr<X509Certificate> cert1 =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(cert1);
scoped_refptr<X509Certificate> cert2 =
ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
ASSERT_TRUE(cert2);
HashValueVector good_hashes, bad_hashes;
for (size_t i = 0; kGoodPath[i]; i++)
EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
for (size_t i = 0; kBadPath[i]; i++)
EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
// The histogram should start off empty.
histograms.ExpectTotalCount(histogram_name, 0);
TransportSecurityState state;
EnableStaticPins(&state);
MockFailingCertificateReportSender mock_report_sender;
state.SetReportSender(&mock_report_sender);
std::string failure_log;
EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
state.CheckPublicKeyPins(
host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
TransportSecurityState::ENABLE_PIN_REPORTS, &failure_log));
// Check that the UMA histogram was updated when the report failed to
// send.
histograms.ExpectTotalCount(histogram_name, 1);
histograms.ExpectBucketCount(histogram_name, -mock_report_sender.net_error(),
1);
}
TEST_F(TransportSecurityStateTest, WriteSizeDecodeSize) {
for (size_t i = 0; i < 300; ++i) {
SCOPED_TRACE(i);
huffman_trie::TrieBitBuffer buffer;
buffer.WriteSize(i);
huffman_trie::BitWriter writer;
buffer.WriteToBitWriter(&writer);
size_t position = writer.position();
writer.Flush();
ASSERT_NE(writer.bytes().data(), nullptr);
extras::PreloadDecoder::BitReader reader(writer.bytes().data(), position);
size_t decoded_size;
EXPECT_TRUE(reader.DecodeSize(&decoded_size));
EXPECT_EQ(i, decoded_size);
}
}
TEST_F(TransportSecurityStateTest, DecodeSizeFour) {
// Test that BitReader::DecodeSize properly handles the number 4, including
// not over-reading input bytes. BitReader::Next only fails if there's not
// another byte to read from; if it reads past the number of bits in the
// buffer but is still in the last byte it will still succeed. For this
// reason, this test puts the encoding of 4 at the end of the byte to check
// that DecodeSize doesn't over-read.
//
// 4 is encoded as 0b010. Shifted right to fill one byte, it is 0x02, with 5
// bits of padding.
uint8_t encoded = 0x02;
extras::PreloadDecoder::BitReader reader(&encoded, 8);
for (size_t i = 0; i < 5; ++i) {
bool unused;
ASSERT_TRUE(reader.Next(&unused));
}
size_t decoded_size;
EXPECT_TRUE(reader.DecodeSize(&decoded_size));
EXPECT_EQ(4u, decoded_size);
}
#endif // BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
} // namespace net
| 43.765101 | 80 | 0.745751 | godfo |
f68f29acbd82cc84b30bd16c7efba55a367f1f96 | 16,901 | cpp | C++ | validation/val_proj_mgi.cpp | TUW-GEO/OGRSpatialRef3D | eb54378eabb885dd1e13616b2eb6b2bde99d90e2 | [
"MIT"
] | 6 | 2017-05-12T08:18:27.000Z | 2022-01-17T17:16:11.000Z | validation/val_proj_mgi.cpp | TUW-GEO/OGRSpatialRef3D | eb54378eabb885dd1e13616b2eb6b2bde99d90e2 | [
"MIT"
] | 1 | 2019-03-07T15:25:14.000Z | 2019-03-07T15:25:14.000Z | validation/val_proj_mgi.cpp | TUW-GEO/OGRSpatialRef3D | eb54378eabb885dd1e13616b2eb6b2bde99d90e2 | [
"MIT"
] | 1 | 2019-03-05T05:18:51.000Z | 2019-03-05T05:18:51.000Z | #include <iostream>
#include "validate.h"
#include "ogr_spatialref3D.h"
using namespace std;
void proj_mgi_to_geoc_etrs()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: ETRS89 (GEOC)" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOC_ETRS);
oTargetSRS.importFromWkt3D(&(wkt2));
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-x_etrs[row_number]));
err1.add(fabs(r1[row_number]-y_etrs[row_number]));
err2.add(fabs(r2[row_number]-z_etrs[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
}
void proj_mgi_to_geog_etrs()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: ETRS89 (GEOG) + Ellipsoidal Height" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOG_ETRS);
oTargetSRS.importFromWkt3D(&(wkt2));
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-lon_grs[row_number]));
err1.add(fabs(r1[row_number]-lat_grs[row_number]));
err2.add(fabs(r2[row_number]-hell_grs[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
}
void proj_mgi_to_geog_etrs_ortho()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r5 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: ETRS89 (GEOG) + Orthometric Height" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOG_ETRS_ORTH);
oTargetSRS.importFromWkt3D(&(wkt2));
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
oTargetSRS.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4, err5;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
oTargetSRS.SetDebugData(&(r5[row_number]), 0);
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-lon_grs[row_number]));
err1.add(fabs(r1[row_number]-lat_grs[row_number]));
err2.add(fabs(r2[row_number]-h_orth[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
err5.add(fabs(r5[row_number]-und_grs[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
cout << "Error (target geoid undulation) : " << endl; err5.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
CPLFree(r5);
}
void proj_mgi_to_geoc_mgi()
{
}
void proj_mgi_to_geog_mgi()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: MGI (GEOG)" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOG_MGI);
oTargetSRS.importFromWkt3D(&(wkt2));
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-lon_mgi[row_number]));
err1.add(fabs(r1[row_number]-lat_mgi[row_number]));
err2.add(fabs(r2[row_number]-hell_mgi[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
}
void proj_mgi_to_geog_mgi_ortho()
{
double *r0 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r1 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r2 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r3 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r4 = (double*)CPLMalloc(sizeof(double)*num_data);
double *r5 = (double*)CPLMalloc(sizeof(double)*num_data);
OGRSpatialReference3D oSourceSRS_28, oSourceSRS_31, oSourceSRS_34, oTargetSRS;
cout << "----------------[ S -> T ]-----------------------" << endl;
cout << "Source coord.: MGI (PROJ) + In-use Height" << endl;
cout << "Target coord.: MGI (GEOG) + Orthometric Height" << endl;
cout << "-------------------------------------------------" << endl;
char *wkt2 = loadWktFile(GEOG_MGI_ORTH);
oTargetSRS.importFromWkt3D(&(wkt2));
oTargetSRS.SetDebug(true);
char *wkt1 = loadWktFile(PROJ_MGI_28);
oSourceSRS_28.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_31);
oSourceSRS_31.importFromWkt3D(&(wkt1));
wkt1 = loadWktFile(PROJ_MGI_34);
oSourceSRS_34.importFromWkt3D(&(wkt1));
oSourceSRS_28.SetDebug(true);
oSourceSRS_31.SetDebug(true);
oSourceSRS_34.SetDebug(true);
OGRCoordinateTransformation3D *poCT_28 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_28, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_31 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_31, &oTargetSRS );
OGRCoordinateTransformation3D *poCT_34 = OGRCreateCoordinateTransformation3D(
&oSourceSRS_34, &oTargetSRS );
if( poCT_28 == NULL || poCT_31 == NULL || poCT_34 == NULL )
printf( "Transformaer creation failed.\n" );
else
{
printf( "Transformation successful.\n" );
SummStat err0, err1, err2, err3, err4, err5;
for(int row_number=0; row_number < num_data; row_number++)
{
r0[row_number] = x_gebr[row_number];
r1[row_number] = y_gebr[row_number];
r2[row_number] = h_gebr[row_number];
oTargetSRS.SetDebugData(&(r5[row_number]), 0);
switch(ms[row_number])
{
case 28:
oSourceSRS_28.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_28->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 31:
oSourceSRS_31.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_31->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
case 34:
oSourceSRS_34.SetDebugData(&(r3[row_number]), &(r4[row_number]));
poCT_34->Transform( 1, &(r0[row_number]), &(r1[row_number]) ,&(r2[row_number]));
break;
default:
cerr << "invalid meridian strip value" << endl;
}
err0.add(fabs(r0[row_number]-lon_mgi[row_number]));
err1.add(fabs(r1[row_number]-lat_mgi[row_number]));
err2.add(fabs(r2[row_number]-h_orth[row_number]));
err3.add(fabs(r3[row_number]-und_bess[row_number]));
err4.add(fabs(r4[row_number]-ras_val[row_number]));
err5.add(fabs(r5[row_number]-und_bess[row_number]));
}
cout << "Error (axis 0) : " << endl; err0.printout();
cout << "Error (axis 1) : " << endl; err1.printout();
cout << "Error (axis 2) : " << endl; err2.printout();
cout << "Error (source geoid undulation) : " << endl; err3.printout();
cout << "Error (source height correction) : " << endl; err4.printout();
cout << "Error (target geoid undulation) : " << endl; err5.printout();
}
delete poCT_28;
delete poCT_31;
delete poCT_34;
CPLFree(r0);
CPLFree(r1);
CPLFree(r2);
CPLFree(r3);
CPLFree(r4);
CPLFree(r5);
}
void val_proj_mgi()
{
proj_mgi_to_geoc_etrs();
proj_mgi_to_geog_etrs();
proj_mgi_to_geog_etrs_ortho();
proj_mgi_to_geoc_mgi();
proj_mgi_to_geog_mgi();
proj_mgi_to_geog_mgi_ortho();
} | 33.401186 | 84 | 0.666292 | TUW-GEO |
f68f49abca91303347d26557e0e259a5c6a7da5b | 635 | cpp | C++ | example_add.cpp | kongaskristjan/Graph-Executor | 9e06bf1fbb6f19817a587a276d8c2103ed3a5b0c | [
"MIT"
] | 2 | 2020-02-09T14:49:41.000Z | 2021-03-25T13:31:41.000Z | example_add.cpp | kongaskristjan/Graph-Executor | 9e06bf1fbb6f19817a587a276d8c2103ed3a5b0c | [
"MIT"
] | null | null | null | example_add.cpp | kongaskristjan/Graph-Executor | 9e06bf1fbb6f19817a587a276d8c2103ed3a5b0c | [
"MIT"
] | 1 | 2020-08-08T23:45:08.000Z | 2020-08-08T23:45:08.000Z |
#include <example_add.hpp>
Integer::Integer(unsigned _x): x(_x)
{}
std::unique_ptr<Example_result> Integer::clone() const
{
return std::make_unique<Integer>(x);
}
unsigned Integer::hash() const
{
return x;
}
std::unique_ptr<Example_job> Add::clone() const
{
return std::make_unique<Add>();
}
std::unique_ptr<Result> Add::execute(
const std::vector<const Result *> & args) const
{
unsigned sum = 0; // Modular arithmetic (% 2^32)
for (const Result * arg: args){
const Integer * x = static_cast<const Integer *>(arg);
sum += x->x;
}
return std::make_unique<Integer>(sum);
}
| 17.162162 | 62 | 0.631496 | kongaskristjan |
f68f92b1fda57e49b024b497d31673a960eaddac | 1,915 | cpp | C++ | HDUOJ/5749 .cpp | LzyRapx/Competitive-Programming | 6b0eea727f9a6444700a6966209397ac7011226f | [
"Apache-2.0"
] | 81 | 2018-06-03T04:27:45.000Z | 2020-09-13T09:04:12.000Z | HDUOJ/5749 .cpp | Walkerlzy/Competitive-algorithm | 6b0eea727f9a6444700a6966209397ac7011226f | [
"Apache-2.0"
] | null | null | null | HDUOJ/5749 .cpp | Walkerlzy/Competitive-algorithm | 6b0eea727f9a6444700a6966209397ac7011226f | [
"Apache-2.0"
] | 21 | 2018-07-11T04:02:38.000Z | 2020-07-18T20:31:14.000Z | //#include<bits/stdc++.h>
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<string.h>
#include<algorithm>
#define N 1010
using namespace std;
int n,m;
int a[N][N];
int stk[N],top;
int L[N][N],R[N][N],U[N][N],D[N][N];
int readint()
{
char c;
while((c=getchar())&&!(c>='0' && c<='9'));
int ret= c- 48;
while((c=getchar())&&( c>='0' && c<='9'))
ret = ret * 10 + c-48;
return ret;
}
unsigned int calc(int l,int x,int r)
{
unsigned int d1=r-x+1;
unsigned int d2=x-l+1;
unsigned int ret=d1 * (d1+1) / 2 * d2 + d2* (d2-1)/2 *d1;
return ret;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
a[i][j]=readint();
}
}
for(int i=1;i<=n;i++)
{
top=0;
for(int j=1;j<=m;j++)
{
while(top && a[i][stk[top-1]] > a[i][j])
--top;
if(top==0) L[i][j]=1;
else L[i][j]=stk[top-1]+1;
stk[top++]=j;
}
}
for(int i=1;i<=n;i++)
{
top=0;
for(int j=m;j>=1;--j)
{
while(top && a[i][stk[top-1]] > a[i][j])
--top;
if(top==0) R[i][j]=m;
else R[i][j] = stk[top-1] - 1;
stk[top++] = j;
}
}
for(int i=1;i<=m;i++)
{
top=0;
for(int j=1;j<=n;j++)
{
while(top && a[stk[top-1]][i] < a[j][i])
--top;
if(top==0) U[j][i]=1;
else U[j][i] = stk[top-1]+1;
stk[top++]=j;
}
}
for(int i=1;i<=m;i++)
{
top=0;
for(int j=n;j>=1;--j)
{
while(top && a[stk[top-1]][i] < a[j][i])
--top;
if(top==0) D[j][i]=n;
else D[j][i] = stk[top-1]-1;
stk[top++]=j;
}
}
unsigned int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
ans += (unsigned int)a[i][j]*calc(L[i][j],j,R[i][j])*calc(U[i][j],i,D[i][j]);
}
}
printf("%u\n",ans);
}
return 0;
} | 18.592233 | 82 | 0.423499 | LzyRapx |
f68fef444c5cfdd733f080da6c77f65262d5e99b | 7,592 | cpp | C++ | Patches/2TBHardDriveFix.cpp | TheMachineAmbassador/Silent-Hill-2-Enhancements | 41650db4a97ca6085db69446e7a20042b344e77f | [
"Zlib"
] | null | null | null | Patches/2TBHardDriveFix.cpp | TheMachineAmbassador/Silent-Hill-2-Enhancements | 41650db4a97ca6085db69446e7a20042b344e77f | [
"Zlib"
] | null | null | null | Patches/2TBHardDriveFix.cpp | TheMachineAmbassador/Silent-Hill-2-Enhancements | 41650db4a97ca6085db69446e7a20042b344e77f | [
"Zlib"
] | null | null | null | /**
* Copyright (C) 2022 Elisha Riedlinger
*
* This software is provided 'as-is', without any express or implied warranty. In no event will the
* authors be held liable for any damages arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
* original software. If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
* being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "Patches.h"
#include "Common\Utils.h"
#include "Logging\Logging.h"
typedef int(__cdecl *oTextToGameAsmProc)(unsigned __int16* a1, unsigned __int16 a2);
// Forward declarations
DWORD GetDiskSpace();
// Variables
bool DiskSizeSet = false;
char szNewFreeSpaceString[MAX_PATH] = { '\0' };
// Variables for ASM
void *jmpSkipDisk;
void *jmpNewSaveReturnAddr;
void *jmpHardDriveReturnAddr;
void *jmpSkipDisplay;
void *jmpDisplayReturnAddr;
void *jmpRemoveKBAddr;
// ASM function to update 2TB disk limit
__declspec(naked) void __stdcall HardDriveASM()
{
__asm
{
push eax
push ebx
push ecx
push edx
push esi
push edi
call GetDiskSpace
cmp eax, 0x08 // Require at least 8KBs of disk space
pop edi
pop esi
pop edx
pop ecx
pop ebx
pop eax
ja near EnoughDiskSpace
jmp jmpSkipDisk
EnoughDiskSpace:
jmp jmpHardDriveReturnAddr
}
}
// ASM function for new save
__declspec(naked) void __stdcall NewSaveASM()
{
__asm
{
push eax
push ebx
push ecx
push edx
push esi
push edi
call GetDiskSpace
cmp eax, 0x20 // Require at least 32KBs of disk space for new save
pop edi
pop esi
pop edx
pop ecx
pop ebx
pop eax
ja near EnoughDiskSpace
jmp HardDriveASM
EnoughDiskSpace:
jmp jmpNewSaveReturnAddr
}
}
// ASM function to update hard disk display
__declspec(naked) void __stdcall DisplayASM()
{
__asm
{
push eax
push ebx
push ecx
push edx
push esi
push edi
call GetDiskSpace
cmp eax, 0x3FFFFFFF
pop edi
pop esi
pop edx
pop ecx
pop ebx
pop eax
jb near SmallDiskSpace
jmp jmpSkipDisplay
SmallDiskSpace:
cmp esi, 0x3B9AC9FF
jmp jmpDisplayReturnAddr
}
}
// ASM function to update 2TB disk limit
__declspec(naked) void __stdcall oTextToGameAsm()
{
__asm
{
mov eax, dword ptr ss : [esp + 4]
test eax, eax
jmp jmpRemoveKBAddr
}
}
oTextToGameAsmProc oTextToGame = (oTextToGameAsmProc)oTextToGameAsm;
// Remove "KB" text
int __cdecl TextToGame(unsigned __int16* a1, unsigned __int16 a2)
{
int TTG = oTextToGame(a1, a2);
if (a2 == 147)
{
BYTE RemoveKBPatch[2] = { 0x00, 0x00 };
UpdateMemoryAddress((BYTE*)(TTG + 0x11), RemoveKBPatch, 2);
}
return TTG;
}
// Get amount of free disk space in KBs, greater than 0x7FFFFFFF will simply return 0x7FFFFFFF
DWORD GetDiskSpace()
{
static wchar_t DirectoryName[MAX_PATH] = { '\0' };
static bool GetFolder = true;
if (GetFolder)
{
if (GetSH2FolderPath(DirectoryName, MAX_PATH) && wcsrchr(DirectoryName, '\\'))
{
wcscpy_s(wcsrchr(DirectoryName, '\\'), MAX_PATH - wcslen(DirectoryName), L"\0");
}
GetFolder = false;
}
ULARGE_INTEGER FreeBytesAvailableToCaller = { NULL };
if (!GetDiskFreeSpaceEx(DirectoryName, &FreeBytesAvailableToCaller, nullptr, nullptr))
{
RUNCODEONCE(Logging::Log() << __FUNCTION__ << " Error: failed to get available disk space!");
DiskSizeSet = false;
return NULL;
}
DiskSizeSet = true;
if (FreeBytesAvailableToCaller.QuadPart < 0xF4240)
{
_snprintf_s(szNewFreeSpaceString, MAX_PATH, _TRUNCATE, "\\h%f KB", (double)FreeBytesAvailableToCaller.QuadPart);
}
else if (FreeBytesAvailableToCaller.QuadPart / 1024 < 0xF4240)
{
_snprintf_s(szNewFreeSpaceString, MAX_PATH, _TRUNCATE, "\\h%f MB", (double)FreeBytesAvailableToCaller.QuadPart / 1024.0f / 1024.0f);
}
else if (FreeBytesAvailableToCaller.QuadPart / 1024 < 0x3B9ACA00)
{
_snprintf_s(szNewFreeSpaceString, MAX_PATH, _TRUNCATE, "\\h%.1f GB", (double)FreeBytesAvailableToCaller.QuadPart / 1024.0f / 1024.0f / 1024.0f);
}
else if (FreeBytesAvailableToCaller.QuadPart / 1024 >= 0x3B9ACA00)
{
_snprintf_s(szNewFreeSpaceString, MAX_PATH, _TRUNCATE, "\\h%.2f TB", (double)FreeBytesAvailableToCaller.QuadPart / 1024.0f / 1024.0f / 1024.0f / 1024.0f);
}
ULONGLONG FreeSpace = FreeBytesAvailableToCaller.QuadPart / 1024;
if (FreeSpace > 0x7FFFFFFF)
{
RUNCODEONCE(Logging::Log() << __FUNCTION__ << " Available disk space larger than 2TBs: " << FreeSpace);
return 0x7FFFFFFF; // Largest unsigned number
}
RUNCODEONCE(Logging::Log() << __FUNCTION__ << " Available disk space smaller than 2TBs: " << FreeSpace);
return (DWORD)(FreeSpace);
}
// sprintf replacement for printing diskspace
int PrintFreeDiskSpace(char* Buffer, const char* a1, ...)
{
if (Buffer == nullptr || a1 == nullptr)
{
return sprintf(Buffer, a1);
}
char FullMessageBufferReturn[MAX_PATH] = { 0 };
va_list vaReturn;
va_start(vaReturn, a1);
_vsnprintf_s(FullMessageBufferReturn, MAX_PATH, _TRUNCATE, a1, vaReturn);
va_end(vaReturn);
if (DiskSizeSet)
{
return sprintf(Buffer, szNewFreeSpaceString);
}
else
{
strcat_s(FullMessageBufferReturn, MAX_PATH, " KB");
return sprintf(Buffer, FullMessageBufferReturn);
}
}
// Patch SH2 code to Fix 2TB disk limit
void Patch2TBHardDrive()
{
// 2TB disk check fix
constexpr BYTE HardDriveSearchBytes[]{ 0x75, 0x08, 0x5F, 0xB8, 0x02, 0x00, 0x00, 0x00, 0x5E, 0xC3, 0x84, 0xDB, 0x75, 0x14, 0x83, 0xFE, 0x20, 0x7C, 0x0F };
DWORD HardDriveAddr = SearchAndGetAddresses(0x0044B86E, 0x0044BA0E, 0x0044BA0E, HardDriveSearchBytes, sizeof(HardDriveSearchBytes), 0x22);
// Checking address pointer
if (!HardDriveAddr)
{
Logging::Log() << __FUNCTION__ << " Error: failed to find memory address!";
return;
}
jmpSkipDisk = (void*)(HardDriveAddr + 0x1A);
jmpHardDriveReturnAddr = (void*)(HardDriveAddr + 0x05);
jmpNewSaveReturnAddr = (void*)(HardDriveAddr - 0x0F);
// Disk display fix
constexpr BYTE DisplaySearchBytes[]{ 0x8B, 0xF0, 0x83, 0xC4, 0x04, 0x85, 0xF6, 0x7D, 0x02, 0x33, 0xF6, 0x6A, 0x00 };
DWORD DisplayFix = SearchAndGetAddresses(0x0044FB54, 0x0044FDB4, 0x0044FDB4, DisplaySearchBytes, sizeof(DisplaySearchBytes), 0x1A);
constexpr BYTE RemoveKBSearchBytes[]{ 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x74, 0x16, 0x66, 0x8B, 0x4C, 0x24, 0x08 };
DWORD RemoveKBAddr = SearchAndGetAddresses(0x0047EC60, 0x0047EF00, 0x0047F110, RemoveKBSearchBytes, sizeof(RemoveKBSearchBytes), 0x0);
// Checking address pointer
if (!DisplayFix || !RemoveKBAddr)
{
Logging::Log() << __FUNCTION__ << " Error: failed to find memory address!";
return;
}
jmpSkipDisplay = (void*)(DisplayFix + 0x08);
jmpDisplayReturnAddr = (void*)(DisplayFix + 0x06);
jmpRemoveKBAddr = (void*)(RemoveKBAddr + 6);
DWORD sprintfAddr = DisplayFix + 0x42;
// Update SH2 code
Logging::Log() << "Setting 2TB hard disk Fix...";
WriteJMPtoMemory((BYTE*)(HardDriveAddr - 0x14), *NewSaveASM, 5);
WriteJMPtoMemory((BYTE*)HardDriveAddr, *HardDriveASM, 5);
WriteJMPtoMemory((BYTE*)DisplayFix, *DisplayASM, 6);
WriteCalltoMemory((BYTE*)sprintfAddr, *PrintFreeDiskSpace, 6);
WriteJMPtoMemory((BYTE*)RemoveKBAddr, *TextToGame, 6);
}
| 28.01476 | 156 | 0.730374 | TheMachineAmbassador |
f690e034b507c7a04207e639898896093439bf1f | 2,043 | cpp | C++ | libgalois/src/SharedMemSys.cpp | swreinehr/katana | 9b4eef12dfeb79e35aa07a3a335ce35b3e97c08d | [
"BSD-3-Clause"
] | 1 | 2021-01-29T23:08:11.000Z | 2021-01-29T23:08:11.000Z | libgalois/src/SharedMemSys.cpp | swreinehr/katana | 9b4eef12dfeb79e35aa07a3a335ce35b3e97c08d | [
"BSD-3-Clause"
] | null | null | null | libgalois/src/SharedMemSys.cpp | swreinehr/katana | 9b4eef12dfeb79e35aa07a3a335ce35b3e97c08d | [
"BSD-3-Clause"
] | 1 | 2021-05-06T02:58:13.000Z | 2021-05-06T02:58:13.000Z | /*
* This file belongs to the Galois project, a C++ library for exploiting
* parallelism. The code is being released under the terms of the 3-Clause BSD
* License (a copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
#include "galois/SharedMemSys.h"
#include "galois/CommBackend.h"
#include "galois/Logging.h"
#include "galois/Statistics.h"
#include "galois/substrate/SharedMem.h"
#include "tsuba/FileStorage.h"
#include "tsuba/tsuba.h"
namespace {
galois::NullCommBackend comm_backend;
} // namespace
struct galois::SharedMemSys::Impl {
galois::substrate::SharedMem shared_mem;
galois::StatManager stat_manager;
};
galois::SharedMemSys::SharedMemSys() : impl_(std::make_unique<Impl>()) {
if (auto init_good = tsuba::Init(&comm_backend); !init_good) {
GALOIS_LOG_FATAL("tsuba::Init: {}", init_good.error());
}
galois::internal::setSysStatManager(&impl_->stat_manager);
}
galois::SharedMemSys::~SharedMemSys() {
galois::PrintStats();
galois::internal::setSysStatManager(nullptr);
if (auto fini_good = tsuba::Fini(); !fini_good) {
GALOIS_LOG_ERROR("tsuba::Fini: {}", fini_good.error());
}
}
| 36.482143 | 79 | 0.752325 | swreinehr |
f6920f9b8640514e34843d69f9008521f777a6d8 | 2,637 | cc | C++ | teslamaxcompute/src/model/ListUserQuotasResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | teslamaxcompute/src/model/ListUserQuotasResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | teslamaxcompute/src/model/ListUserQuotasResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/teslamaxcompute/model/ListUserQuotasResult.h>
#include <json/json.h>
using namespace AlibabaCloud::TeslaMaxCompute;
using namespace AlibabaCloud::TeslaMaxCompute::Model;
ListUserQuotasResult::ListUserQuotasResult() :
ServiceResult()
{}
ListUserQuotasResult::ListUserQuotasResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListUserQuotasResult::~ListUserQuotasResult()
{}
void ListUserQuotasResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allDetail = value["Detail"]["Quotas"];
for (auto value : allDetail)
{
Data::Quotas quotasObject;
if(!value["Quotaid"].isNull())
quotasObject.quotaid = std::stol(value["Quotaid"].asString());
if(!value["Cluster"].isNull())
quotasObject.cluster = value["Cluster"].asString();
if(!value["Region"].isNull())
quotasObject.region = value["Region"].asString();
if(!value["Name"].isNull())
quotasObject.name = value["Name"].asString();
if(!value["Parentid"].isNull())
quotasObject.parentid = std::stol(value["Parentid"].asString());
if(!value["Nick"].isNull())
quotasObject.nick = value["Nick"].asString();
data_.detail.push_back(quotasObject);
}
auto errorNode = dataNode["Error"];
if(!errorNode["Code"].isNull())
data_.error.code = errorNode["Code"].asString();
if(!errorNode["Message"].isNull())
data_.error.message = errorNode["Message"].asString();
if(!errorNode["Timestamp"].isNull())
data_.error.timestamp = errorNode["Timestamp"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["Code"].isNull())
code_ = std::stoi(value["Code"].asString());
}
std::string ListUserQuotasResult::getMessage()const
{
return message_;
}
ListUserQuotasResult::Data ListUserQuotasResult::getData()const
{
return data_;
}
int ListUserQuotasResult::getCode()const
{
return code_;
}
| 28.978022 | 75 | 0.720516 | iamzken |
f693faed2fa13f8a30f02c5195be0d41f3fed194 | 2,727 | cpp | C++ | InputSystem.cpp | GuMiner/Octocad | 2858d777e5db177e1fbddf7653ba052a4fa31855 | [
"MIT"
] | null | null | null | InputSystem.cpp | GuMiner/Octocad | 2858d777e5db177e1fbddf7653ba052a4fa31855 | [
"MIT"
] | null | null | null | InputSystem.cpp | GuMiner/Octocad | 2858d777e5db177e1fbddf7653ba052a4fa31855 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "InputSystem.h"
InputSystem::ResizeEventData InputSystem::resizeEvent;
InputSystem::KeyTypedData InputSystem::keyTypedEvent;
bool InputSystem::addCubeButton;
bool InputSystem::removeCubeButton;
void InputSystem::Initialize(void)
{
// Setup all the event handlers to indicate that nothing occurred.
resizeEvent.resizeEvent = false;
keyTypedEvent.charEvent = false;
addCubeButton = false;
removeCubeButton = false;
}
void InputSystem::KeyTyped(GLFWwindow *pWindow, unsigned int character)
{
keyTypedEvent.newChar = static_cast<char>(character);
keyTypedEvent.charEvent = true;
}
bool InputSystem::KeyTypedEvent(char& character)
{
if (keyTypedEvent.charEvent)
{
character = keyTypedEvent.newChar;
keyTypedEvent.charEvent = false;
return true;
}
return false;
}
void InputSystem::KeyEvent(GLFWwindow *pWindow, int key, int scancode, int action, int mods)
{
switch (key)
{
case GLFW_KEY_A:
if (action == GLFW_PRESS)
{
addCubeButton = true;
}
else if (action == GLFW_RELEASE)
{
addCubeButton = false;
}
break;
case GLFW_KEY_R:
if (action == GLFW_PRESS)
{
removeCubeButton = true;
}
else if (action == GLFW_RELEASE)
{
removeCubeButton = false;
}
break;
}
}
void InputSystem::MouseButtonEvent(GLFWwindow *pWindow, int button, int action, int mods)
{
}
void InputSystem::ScrollEvent(GLFWwindow *pWindow, double xDelta, double yDelta)
{
}
void InputSystem::CursorTravel(GLFWwindow *pWindow, int action)
{
}
void InputSystem::CursorMove(GLFWwindow *pWindow, double xNew, double yNew)
{
}
// Simple resize handling.
void InputSystem::Resize(GLFWwindow *pWindow, int widthNew, int heightHew)
{
resizeEvent.newWidth = widthNew;
resizeEvent.newHeight = heightHew;
resizeEvent.resizeEvent = true;
}
bool InputSystem::ResizeEvent(int& width, int& height)
{
if (resizeEvent.resizeEvent)
{
width = resizeEvent.newWidth;
height = resizeEvent.newHeight;
resizeEvent.resizeEvent = false;
return true;
}
return false;
}
// Very simple error callbacks
void InputSystem::ErrorCallback(int errCode, const char *pError)
{
std::cout << "GLFW error " << errCode << ": " << pError << std::endl;
}
void APIENTRY InputSystem::GLCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *pMessage, void *userParam)
{
std::cout << "OpenGL debug error (" << source << ", " << type << ", " << id << ", " << severity << ", " << length << "): " << pMessage << std::endl;
} | 25.971429 | 153 | 0.658599 | GuMiner |
f695bf08a6e1fe8b8e0122ed3a68fbd5fef0022d | 2,255 | cc | C++ | ui/events/keycodes/dom/dom_keyboard_layout_map_base.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/events/keycodes/dom/dom_keyboard_layout_map_base.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/events/keycodes/dom/dom_keyboard_layout_map_base.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/events/keycodes/dom/dom_keyboard_layout_map_base.h"
#include <cstdint>
#include <memory>
#include <string>
#include "base/logging.h"
#include "ui/events/keycodes/dom/dom_key.h"
#include "ui/events/keycodes/dom/dom_keyboard_layout.h"
#include "ui/events/keycodes/dom/dom_keyboard_layout_manager.h"
namespace ui {
DomKeyboardLayoutMapBase::DomKeyboardLayoutMapBase() = default;
DomKeyboardLayoutMapBase::~DomKeyboardLayoutMapBase() = default;
base::flat_map<std::string, std::string> DomKeyboardLayoutMapBase::Generate() {
uint32_t keyboard_layout_count = GetKeyboardLayoutCount();
if (!keyboard_layout_count)
return {};
std::unique_ptr<ui::DomKeyboardLayoutManager> keyboard_layout_manager =
std::make_unique<ui::DomKeyboardLayoutManager>();
for (size_t i = 0; i < keyboard_layout_count; i++) {
DomKeyboardLayout* const dom_keyboard_layout =
keyboard_layout_manager->GetLayout(i);
PopulateLayout(i, dom_keyboard_layout);
if (dom_keyboard_layout->IsAsciiCapable())
return dom_keyboard_layout->GetMap();
}
return keyboard_layout_manager->GetFirstAsciiCapableLayout()->GetMap();
}
void DomKeyboardLayoutMapBase::PopulateLayout(uint32_t keyboard_layout_index,
ui::DomKeyboardLayout* layout) {
DCHECK(layout);
for (size_t entry = 0; entry < ui::kWritingSystemKeyDomCodeEntries; entry++) {
ui::DomCode dom_code = ui::writing_system_key_domcodes[entry];
ui::DomKey dom_key =
GetDomKeyFromDomCodeForLayout(dom_code, keyboard_layout_index);
if (dom_key == ui::DomKey::NONE)
continue;
uint32_t unicode_value = 0;
if (dom_key.IsCharacter())
unicode_value = dom_key.ToCharacter();
else if (dom_key.IsDeadKey())
unicode_value = dom_key.ToDeadKeyCombiningCharacter();
else if (dom_key == ui::DomKey::ZENKAKU_HANKAKU)
// Placeholder for hankaku/zenkaku string.
unicode_value = kHankakuZenkakuPlaceholder;
if (unicode_value != 0)
layout->AddKeyMapping(dom_code, unicode_value);
}
}
} // namespace ui
| 32.681159 | 80 | 0.729047 | sarang-apps |
f69670e9bba94a0940efdd396cccc78b1f376b25 | 568 | hpp | C++ | bolt/server/include/azure_handler.hpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | 1 | 2022-03-06T09:23:56.000Z | 2022-03-06T09:23:56.000Z | bolt/server/include/azure_handler.hpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | 3 | 2021-04-23T18:12:20.000Z | 2021-04-23T18:12:47.000Z | bolt/server/include/azure_handler.hpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <azure_entity.h>
#include <cpprest/http_msg.h>
#include <cpprest/json.h>
#include <permissions.hpp>
using namespace web;
using namespace bolt::storage;
class AzureHandler
{
public:
AzureHandler(const http::http_request &request, http::method method);
void InitializeHandlers();
void HandleGet();
void HandlePost();
void HandleDelete();
void HandlePatch();
private:
void insetKeyValuePropery(boltazure::AzureEntity &entity, utility::string_t key, json::value value);
const http::http_request &m_http_request;
http::method m_method;
}; | 23.666667 | 101 | 0.767606 | gamunu |
f696d08d2e5a8791da077fb4ef0c748897dbd2c5 | 17,889 | cpp | C++ | gdal/port/cpl_vsil_cache.cpp | nyalldawson/gdal | 312cfe2d6fc564af4558279cc8f321d6e2a687ad | [
"MIT"
] | 1 | 2017-08-23T13:32:41.000Z | 2017-08-23T13:32:41.000Z | gdal/port/cpl_vsil_cache.cpp | norBIT/gdal | 64855dbee2cd0dff47da11d916c8d2703b4e99b8 | [
"MIT"
] | null | null | null | gdal/port/cpl_vsil_cache.cpp | norBIT/gdal | 64855dbee2cd0dff47da11d916c8d2703b4e99b8 | [
"MIT"
] | null | null | null | /******************************************************************************
*
* Project: VSI Virtual File System
* Purpose: Implementation of caching IO layer.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2011, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2011-2014, Even Rouault <even dot rouault at mines-paris dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "cpl_vsi_virtual.h"
#include <cstddef>
#include <cstring>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <algorithm>
#include <map>
#include <utility>
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_vsi.h"
#include "cpl_vsi_virtual.h"
//! @cond Doxygen_Suppress
CPL_CVSID("$Id$")
/************************************************************************/
/* ==================================================================== */
/* VSICacheChunk */
/* ==================================================================== */
/************************************************************************/
class VSICacheChunk
{
public:
VSICacheChunk() :
bDirty(false),
iBlock(0),
poLRUPrev(NULL),
poLRUNext(NULL),
nDataFilled(0),
pabyData(NULL)
{}
virtual ~VSICacheChunk()
{
VSIFree( pabyData );
}
bool Allocate( size_t nChunkSize )
{
CPLAssert( pabyData == NULL );
pabyData = static_cast<GByte *>(VSIMalloc( nChunkSize ));
return (pabyData != NULL);
}
bool bDirty; // TODO(schwehr): Not used? Added in r22564.
vsi_l_offset iBlock;
VSICacheChunk *poLRUPrev;
VSICacheChunk *poLRUNext;
vsi_l_offset nDataFilled;
GByte *pabyData;
};
/************************************************************************/
/* ==================================================================== */
/* VSICachedFile */
/* ==================================================================== */
/************************************************************************/
class VSICachedFile CPL_FINAL : public VSIVirtualHandle
{
public:
VSICachedFile( VSIVirtualHandle *poBaseHandle,
size_t nChunkSize,
size_t nCacheSize );
virtual ~VSICachedFile() { Close(); }
void FlushLRU();
int LoadBlocks( vsi_l_offset nStartBlock, size_t nBlockCount,
void *pBuffer, size_t nBufferSize );
void Demote( VSICacheChunk * );
VSIVirtualHandle *poBase;
vsi_l_offset nOffset;
vsi_l_offset nFileSize;
GUIntBig nCacheUsed;
GUIntBig nCacheMax;
size_t m_nChunkSize;
VSICacheChunk *poLRUStart;
VSICacheChunk *poLRUEnd;
std::map<vsi_l_offset, VSICacheChunk*> oMapOffsetToCache;
bool bEOF;
virtual int Seek( vsi_l_offset nOffset, int nWhence ) override;
virtual vsi_l_offset Tell() override;
virtual size_t Read( void *pBuffer, size_t nSize,
size_t nMemb ) override;
virtual size_t Write( const void *pBuffer, size_t nSize,
size_t nMemb ) override;
virtual int Eof() override;
virtual int Flush() override;
virtual int Close() override;
virtual void *GetNativeFileDescriptor() override
{ return poBase->GetNativeFileDescriptor(); }
};
/************************************************************************/
/* VSICachedFile() */
/************************************************************************/
VSICachedFile::VSICachedFile( VSIVirtualHandle *poBaseHandle, size_t nChunkSize,
size_t nCacheSize ) :
poBase(poBaseHandle),
nOffset(0),
nFileSize(0), // Set below.
nCacheUsed(0),
nCacheMax(nCacheSize),
poLRUStart(NULL),
poLRUEnd(NULL),
bEOF(false)
{
m_nChunkSize = nChunkSize;
if( nCacheSize == 0 )
nCacheMax = CPLScanUIntBig(
CPLGetConfigOption( "VSI_CACHE_SIZE", "25000000" ), 40 );
poBase->Seek( 0, SEEK_END );
nFileSize = poBase->Tell();
}
/************************************************************************/
/* Close() */
/************************************************************************/
int VSICachedFile::Close()
{
for( std::map<vsi_l_offset, VSICacheChunk*>::iterator oIter =
oMapOffsetToCache.begin();
oIter != oMapOffsetToCache.end();
++oIter )
{
delete oIter->second;
}
oMapOffsetToCache.clear();
poLRUStart = NULL;
poLRUEnd = NULL;
nCacheUsed = 0;
if( poBase )
{
poBase->Close();
delete poBase;
poBase = NULL;
}
return 0;
}
/************************************************************************/
/* Seek() */
/************************************************************************/
int VSICachedFile::Seek( vsi_l_offset nReqOffset, int nWhence )
{
bEOF = false;
if( nWhence == SEEK_SET )
{
// Use offset directly.
}
else if( nWhence == SEEK_CUR )
{
nReqOffset += nOffset;
}
else if( nWhence == SEEK_END )
{
nReqOffset += nFileSize;
}
nOffset = nReqOffset;
return 0;
}
/************************************************************************/
/* Tell() */
/************************************************************************/
vsi_l_offset VSICachedFile::Tell()
{
return nOffset;
}
/************************************************************************/
/* FlushLRU() */
/************************************************************************/
void VSICachedFile::FlushLRU()
{
CPLAssert( poLRUStart != NULL );
VSICacheChunk *poBlock = poLRUStart;
CPLAssert( nCacheUsed >= poBlock->nDataFilled );
nCacheUsed -= poBlock->nDataFilled;
poLRUStart = poBlock->poLRUNext;
if( poLRUEnd == poBlock )
poLRUEnd = NULL;
if( poBlock->poLRUNext != NULL )
poBlock->poLRUNext->poLRUPrev = NULL;
CPLAssert( !poBlock->bDirty );
oMapOffsetToCache[poBlock->iBlock] = NULL;
delete poBlock;
}
/************************************************************************/
/* Demote() */
/* */
/* Demote the indicated block to the end of the LRU list. */
/* Potentially integrate the link into the list if it is not */
/* already there. */
/************************************************************************/
void VSICachedFile::Demote( VSICacheChunk *poBlock )
{
// Already at end?
if( poLRUEnd == poBlock )
return;
if( poLRUStart == poBlock )
poLRUStart = poBlock->poLRUNext;
if( poBlock->poLRUPrev != NULL )
poBlock->poLRUPrev->poLRUNext = poBlock->poLRUNext;
if( poBlock->poLRUNext != NULL )
poBlock->poLRUNext->poLRUPrev = poBlock->poLRUPrev;
poBlock->poLRUNext = NULL;
poBlock->poLRUPrev = NULL;
if( poLRUEnd != NULL )
poLRUEnd->poLRUNext = poBlock;
poLRUEnd = poBlock;
if( poLRUStart == NULL )
poLRUStart = poBlock;
}
/************************************************************************/
/* LoadBlocks() */
/* */
/* Load the desired set of blocks. Use pBuffer as a temporary */
/* buffer if it would be helpful. */
/* */
/* RETURNS: TRUE on success; FALSE on failure. */
/************************************************************************/
int VSICachedFile::LoadBlocks( vsi_l_offset nStartBlock, size_t nBlockCount,
void *pBuffer, size_t nBufferSize )
{
if( nBlockCount == 0 )
return TRUE;
/* -------------------------------------------------------------------- */
/* When we want to load only one block, we can directly load it */
/* into the target buffer with no concern about intermediaries. */
/* -------------------------------------------------------------------- */
if( nBlockCount == 1 )
{
poBase->Seek( static_cast<vsi_l_offset>(nStartBlock) * m_nChunkSize,
SEEK_SET );
VSICacheChunk *poBlock = new VSICacheChunk();
if( !poBlock || !poBlock->Allocate( m_nChunkSize ) )
{
delete poBlock;
return FALSE;
}
oMapOffsetToCache[nStartBlock] = poBlock;
poBlock->iBlock = nStartBlock;
poBlock->nDataFilled =
poBase->Read( poBlock->pabyData, 1, m_nChunkSize );
nCacheUsed += poBlock->nDataFilled;
// Merges into the LRU list.
Demote( poBlock );
return TRUE;
}
/* -------------------------------------------------------------------- */
/* If the buffer is quite large but not quite large enough to */
/* hold all the blocks we will take the pain of splitting the */
/* io request in two in order to avoid allocating a large */
/* temporary buffer. */
/* -------------------------------------------------------------------- */
if( nBufferSize > m_nChunkSize * 20
&& nBufferSize < nBlockCount * m_nChunkSize )
{
if( !LoadBlocks( nStartBlock, 2, pBuffer, nBufferSize ) )
return FALSE;
return LoadBlocks( nStartBlock+2, nBlockCount-2, pBuffer, nBufferSize );
}
if( poBase->Seek( static_cast<vsi_l_offset>(nStartBlock) * m_nChunkSize,
SEEK_SET ) != 0 )
return FALSE;
/* -------------------------------------------------------------------- */
/* Do we need to allocate our own buffer? */
/* -------------------------------------------------------------------- */
GByte *pabyWorkBuffer = static_cast<GByte *>(pBuffer);
if( nBufferSize < m_nChunkSize * nBlockCount )
pabyWorkBuffer =
static_cast<GByte *>( CPLMalloc(m_nChunkSize * nBlockCount) );
/* -------------------------------------------------------------------- */
/* Read the whole request into the working buffer. */
/* -------------------------------------------------------------------- */
const size_t nDataRead =
poBase->Read( pabyWorkBuffer, 1, nBlockCount*m_nChunkSize);
if( nBlockCount * m_nChunkSize > nDataRead + m_nChunkSize - 1 )
nBlockCount = (nDataRead + m_nChunkSize - 1) / m_nChunkSize;
for( size_t i = 0; i < nBlockCount; i++ )
{
VSICacheChunk *poBlock = new VSICacheChunk();
if( !poBlock || !poBlock->Allocate( m_nChunkSize ) )
{
delete poBlock;
return FALSE;
}
poBlock->iBlock = nStartBlock + i;
CPLAssert( oMapOffsetToCache[i+nStartBlock] == NULL );
oMapOffsetToCache[i + nStartBlock] = poBlock;
if( nDataRead >= (i+1) * m_nChunkSize )
poBlock->nDataFilled = m_nChunkSize;
else
poBlock->nDataFilled = nDataRead - i*m_nChunkSize;
memcpy( poBlock->pabyData, pabyWorkBuffer + i*m_nChunkSize,
static_cast<size_t>(poBlock->nDataFilled) );
nCacheUsed += poBlock->nDataFilled;
// Merges into the LRU list.
Demote( poBlock );
}
if( pabyWorkBuffer != pBuffer )
CPLFree( pabyWorkBuffer );
return TRUE;
}
/************************************************************************/
/* Read() */
/************************************************************************/
size_t VSICachedFile::Read( void * pBuffer, size_t nSize, size_t nCount )
{
if( nOffset >= nFileSize )
{
bEOF = true;
return 0;
}
/* ==================================================================== */
/* Make sure the cache is loaded for the whole request region. */
/* ==================================================================== */
const vsi_l_offset nStartBlock = nOffset / m_nChunkSize;
const vsi_l_offset nEndBlock =
(nOffset + nSize * nCount - 1) / m_nChunkSize;
for( vsi_l_offset iBlock = nStartBlock; iBlock <= nEndBlock; iBlock++ )
{
if( oMapOffsetToCache[iBlock] == NULL )
{
size_t nBlocksToLoad = 1;
while( iBlock + nBlocksToLoad <= nEndBlock
&& (oMapOffsetToCache[iBlock+nBlocksToLoad] == NULL) )
nBlocksToLoad++;
LoadBlocks( iBlock, nBlocksToLoad, pBuffer, nSize * nCount );
}
}
/* ==================================================================== */
/* Copy data into the target buffer to the extent possible. */
/* ==================================================================== */
size_t nAmountCopied = 0;
while( nAmountCopied < nSize * nCount )
{
const vsi_l_offset iBlock = (nOffset + nAmountCopied) / m_nChunkSize;
VSICacheChunk * poBlock = oMapOffsetToCache[iBlock];
if( poBlock == NULL )
{
// We can reach that point when the amount to read exceeds
// the cache size.
LoadBlocks(iBlock, 1,
static_cast<GByte *>(pBuffer) + nAmountCopied,
std::min(nSize * nCount - nAmountCopied, m_nChunkSize));
poBlock = oMapOffsetToCache[iBlock];
CPLAssert(poBlock != NULL);
}
const vsi_l_offset nStartOffset =
static_cast<vsi_l_offset>(iBlock) * m_nChunkSize;
size_t nThisCopy = static_cast<size_t>(
((nStartOffset + poBlock->nDataFilled)
- nAmountCopied - nOffset));
if( nThisCopy > nSize * nCount - nAmountCopied )
nThisCopy = nSize * nCount - nAmountCopied;
if( nThisCopy == 0 )
break;
memcpy( static_cast<GByte *>(pBuffer) + nAmountCopied,
poBlock->pabyData
+ (nOffset + nAmountCopied) - nStartOffset,
nThisCopy );
nAmountCopied += nThisCopy;
}
nOffset += nAmountCopied;
/* -------------------------------------------------------------------- */
/* Ensure the cache is reduced to our limit. */
/* -------------------------------------------------------------------- */
while( nCacheUsed > nCacheMax )
FlushLRU();
const size_t nRet = nAmountCopied / nSize;
if( nRet != nCount )
bEOF = true;
return nRet;
}
/************************************************************************/
/* Write() */
/************************************************************************/
size_t VSICachedFile::Write( const void * /* pBuffer */,
size_t /*nSize */ ,
size_t /* nCount */ )
{
return 0;
}
/************************************************************************/
/* Eof() */
/************************************************************************/
int VSICachedFile::Eof()
{
return bEOF;
}
/************************************************************************/
/* Flush() */
/************************************************************************/
int VSICachedFile::Flush()
{
return 0;
}
//! @endcond
/************************************************************************/
/* VSICreateCachedFile() */
/************************************************************************/
VSIVirtualHandle *
VSICreateCachedFile( VSIVirtualHandle *poBaseHandle,
size_t nChunkSize, size_t nCacheSize )
{
return new VSICachedFile( poBaseHandle, nChunkSize, nCacheSize );
}
| 32.644161 | 82 | 0.4396 | nyalldawson |
f697c83502c405c20b185e2da948e2300e0fef15 | 3,984 | cc | C++ | server/be/src/testutil/desc-tbl-builder.cc | drankye/recordservice | ced33a1565b7ab3a25f6cb7cdcf623a26e7b3ec0 | [
"Apache-2.0"
] | null | null | null | server/be/src/testutil/desc-tbl-builder.cc | drankye/recordservice | ced33a1565b7ab3a25f6cb7cdcf623a26e7b3ec0 | [
"Apache-2.0"
] | null | null | null | server/be/src/testutil/desc-tbl-builder.cc | drankye/recordservice | ced33a1565b7ab3a25f6cb7cdcf623a26e7b3ec0 | [
"Apache-2.0"
] | 2 | 2019-09-22T07:59:28.000Z | 2021-02-25T21:56:07.000Z | // Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "testutil/desc-tbl-builder.h"
#include "util/bit-util.h"
#include "runtime/descriptors.h"
#include "common/names.h"
namespace impala {
DescriptorTblBuilder::DescriptorTblBuilder(ObjectPool* obj_pool) : obj_pool_(obj_pool) {
}
TupleDescBuilder& DescriptorTblBuilder::DeclareTuple() {
TupleDescBuilder* tuple_builder = obj_pool_->Add(new TupleDescBuilder());
tuples_descs_.push_back(tuple_builder);
return *tuple_builder;
}
// item_id of -1 indicates no itemTupleId
static TSlotDescriptor MakeSlotDescriptor(int id, int parent_id, const ColumnType& type,
int slot_idx, int byte_offset, int item_id) {
int null_byte = slot_idx / 8;
int null_bit = slot_idx % 8;
TSlotDescriptor slot_desc;
slot_desc.__set_id(id);
slot_desc.__set_parent(parent_id);
slot_desc.__set_slotType(type.ToThrift());
// For now no tests depend on the materialized path being populated correctly.
slot_desc.__set_materializedPath(vector<int>());
slot_desc.__set_byteOffset(byte_offset);
slot_desc.__set_nullIndicatorByte(null_byte);
slot_desc.__set_nullIndicatorBit(null_bit);
slot_desc.__set_slotIdx(slot_idx);
slot_desc.__set_isMaterialized(true);
if (item_id != -1) slot_desc.__set_itemTupleId(item_id);
return slot_desc;
}
static TTupleDescriptor MakeTupleDescriptor(int id, int byte_size, int num_null_bytes) {
TTupleDescriptor tuple_desc;
tuple_desc.__set_id(id);
tuple_desc.__set_byteSize(byte_size);
tuple_desc.__set_numNullBytes(num_null_bytes);
return tuple_desc;
}
DescriptorTbl* DescriptorTblBuilder::Build() {
DescriptorTbl* desc_tbl;
TDescriptorTable thrift_desc_tbl;
int tuple_id = 0;
int slot_id = 0;
for (int i = 0; i < tuples_descs_.size(); ++i) {
BuildTuple(tuples_descs_[i]->slot_types(), &thrift_desc_tbl, &tuple_id, &slot_id);
}
Status status = DescriptorTbl::Create(obj_pool_, thrift_desc_tbl, &desc_tbl);
DCHECK(status.ok());
return desc_tbl;
}
TTupleDescriptor DescriptorTblBuilder::BuildTuple(
const vector<ColumnType>& slot_types, TDescriptorTable* thrift_desc_tbl,
int* next_tuple_id, int* slot_id) {
// We never materialize struct slots (there's no in-memory representation of structs,
// instead the materialized fields appear directly in the tuple), but array types can
// still have a struct item type. In this case, the array item tuple contains the
// "inlined" struct fields.
if (slot_types.size() == 1 && slot_types[0].type == TYPE_STRUCT) {
return BuildTuple(slot_types[0].children, thrift_desc_tbl, next_tuple_id, slot_id);
}
int num_null_bytes = BitUtil::Ceil(slot_types.size(), 8);
int byte_offset = num_null_bytes;
int tuple_id = *next_tuple_id;
++(*next_tuple_id);
for (int i = 0; i < slot_types.size(); ++i) {
DCHECK_NE(slot_types[i].type, TYPE_STRUCT);
int item_id = -1;
if (slot_types[i].IsCollectionType()) {
TTupleDescriptor item_desc =
BuildTuple(slot_types[i].children, thrift_desc_tbl, next_tuple_id, slot_id);
item_id = item_desc.id;
}
thrift_desc_tbl->slotDescriptors.push_back(
MakeSlotDescriptor(*slot_id, tuple_id, slot_types[i], i, byte_offset, item_id));
byte_offset += slot_types[i].GetSlotSize();
++(*slot_id);
}
TTupleDescriptor result = MakeTupleDescriptor(tuple_id, byte_offset, num_null_bytes);
thrift_desc_tbl->tupleDescriptors.push_back(result);
return result;
}
}
| 34.947368 | 88 | 0.746988 | drankye |
f69ac45c71395e427977c247d919709b180a7add | 8,054 | cc | C++ | processors/IA32/bochs/cpu/ret_far.cc | pavel-krivanek/opensmalltalk-vm | 694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16 | [
"MIT"
] | 445 | 2016-06-30T08:19:11.000Z | 2022-03-28T06:09:49.000Z | processors/IA32/bochs/cpu/ret_far.cc | pavel-krivanek/opensmalltalk-vm | 694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16 | [
"MIT"
] | 439 | 2016-06-29T20:14:36.000Z | 2022-03-17T19:59:58.000Z | processors/IA32/bochs/cpu/ret_far.cc | pavel-krivanek/opensmalltalk-vm | 694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16 | [
"MIT"
] | 137 | 2016-07-02T17:32:07.000Z | 2022-03-20T11:17:25.000Z | ////////////////////////////////////////////////////////////////////////
// $Id: ret_far.cc,v 1.20 2008/06/13 08:02:22 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005 Stanislav Shwartsman
// Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#if BX_SUPPORT_X86_64==0
// Make life easier merging cpu64 & cpu code.
#define RIP EIP
#define RSP ESP
#endif
void BX_CPP_AttrRegparmN(2)
BX_CPU_C::return_protected(bxInstruction_c *i, Bit16u pop_bytes)
{
Bit16u raw_cs_selector, raw_ss_selector;
bx_selector_t cs_selector, ss_selector;
bx_descriptor_t cs_descriptor, ss_descriptor;
Bit32u stack_param_offset;
bx_address return_RIP, return_RSP, temp_RSP;
Bit32u dword1, dword2;
/* + 6+N*2: SS | +12+N*4: SS | +24+N*8 SS */
/* + 4+N*2: SP | + 8+N*4: ESP | +16+N*8 RSP */
/* parm N | + parm N | + parm N */
/* parm 3 | + parm 3 | + parm 3 */
/* parm 2 | + parm 2 | + parm 2 */
/* + 4: parm 1 | + 8: parm 1 | +16: parm 1 */
/* + 2: CS | + 4: CS | + 8: CS */
/* + 0: IP | + 0: EIP | + 0: RIP */
#if BX_SUPPORT_X86_64
if (StackAddrSize64()) temp_RSP = RSP;
else
#endif
{
if (BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache.u.segment.d_b) temp_RSP = ESP;
else temp_RSP = SP;
}
#if BX_SUPPORT_X86_64
if (i->os64L()) {
raw_cs_selector = (Bit16u) read_virtual_qword_64(BX_SEG_REG_SS, temp_RSP + 8);
return_RIP = read_virtual_qword_64(BX_SEG_REG_SS, temp_RSP);
stack_param_offset = 16;
}
else
#endif
if (i->os32L()) {
raw_cs_selector = (Bit16u) read_virtual_dword(BX_SEG_REG_SS, temp_RSP + 4);
return_RIP = read_virtual_dword(BX_SEG_REG_SS, temp_RSP);
stack_param_offset = 8;
}
else {
raw_cs_selector = read_virtual_word(BX_SEG_REG_SS, temp_RSP + 2);
return_RIP = read_virtual_word(BX_SEG_REG_SS, temp_RSP);
stack_param_offset = 4;
}
// selector must be non-null else #GP(0)
if ((raw_cs_selector & 0xfffc) == 0) {
BX_ERROR(("return_protected: CS selector null"));
exception(BX_GP_EXCEPTION, 0, 0);
}
parse_selector(raw_cs_selector, &cs_selector);
// selector index must be within its descriptor table limits,
// else #GP(selector)
fetch_raw_descriptor(&cs_selector, &dword1, &dword2, BX_GP_EXCEPTION);
// descriptor AR byte must indicate code segment, else #GP(selector)
parse_descriptor(dword1, dword2, &cs_descriptor);
// return selector RPL must be >= CPL, else #GP(return selector)
if (cs_selector.rpl < CPL) {
BX_ERROR(("return_protected: CS.rpl < CPL"));
exception(BX_GP_EXCEPTION, raw_cs_selector & 0xfffc, 0);
}
// check code-segment descriptor
check_cs(&cs_descriptor, raw_cs_selector, 0, cs_selector.rpl);
// if return selector RPL == CPL then
// RETURN TO SAME PRIVILEGE LEVEL
if (cs_selector.rpl == CPL)
{
BX_DEBUG(("return_protected: return to SAME PRIVILEGE LEVEL"));
branch_far64(&cs_selector, &cs_descriptor, return_RIP, CPL);
#if BX_SUPPORT_X86_64
if (StackAddrSize64())
RSP += stack_param_offset + pop_bytes;
else
#endif
{
if (BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache.u.segment.d_b)
RSP = ESP + stack_param_offset + pop_bytes;
else
SP += stack_param_offset + pop_bytes;
}
return;
}
/* RETURN TO OUTER PRIVILEGE LEVEL */
else {
/* + 6+N*2: SS | +12+N*4: SS | +24+N*8 SS */
/* + 4+N*2: SP | + 8+N*4: ESP | +16+N*8 RSP */
/* parm N | + parm N | + parm N */
/* parm 3 | + parm 3 | + parm 3 */
/* parm 2 | + parm 2 | + parm 2 */
/* + 4: parm 1 | + 8: parm 1 | +16: parm 1 */
/* + 2: CS | + 4: CS | + 8: CS */
/* + 0: IP | + 0: EIP | + 0: RIP */
BX_DEBUG(("return_protected: return to OUTER PRIVILEGE LEVEL"));
#if BX_SUPPORT_X86_64
if (i->os64L()) {
raw_ss_selector = read_virtual_word_64(BX_SEG_REG_SS, temp_RSP + 24 + pop_bytes);
return_RSP = read_virtual_qword_64(BX_SEG_REG_SS, temp_RSP + 16 + pop_bytes);
}
else
#endif
if (i->os32L()) {
raw_ss_selector = read_virtual_word(BX_SEG_REG_SS, temp_RSP + 12 + pop_bytes);
return_RSP = read_virtual_dword(BX_SEG_REG_SS, temp_RSP + 8 + pop_bytes);
}
else {
raw_ss_selector = read_virtual_word(BX_SEG_REG_SS, temp_RSP + 6 + pop_bytes);
return_RSP = read_virtual_word(BX_SEG_REG_SS, temp_RSP + 4 + pop_bytes);
}
/* selector index must be within its descriptor table limits,
* else #GP(selector) */
parse_selector(raw_ss_selector, &ss_selector);
if ((raw_ss_selector & 0xfffc) == 0) {
if (long_mode()) {
if (! IS_LONG64_SEGMENT(cs_descriptor) || (cs_selector.rpl == 3)) {
BX_ERROR(("return_protected: SS selector null"));
exception(BX_GP_EXCEPTION, 0, 0);
}
}
else // not in long or compatibility mode
{
BX_ERROR(("return_protected: SS selector null"));
exception(BX_GP_EXCEPTION, 0, 0);
}
}
fetch_raw_descriptor(&ss_selector, &dword1, &dword2, BX_GP_EXCEPTION);
parse_descriptor(dword1, dword2, &ss_descriptor);
/* selector RPL must = RPL of the return CS selector,
* else #GP(selector) */
if (ss_selector.rpl != cs_selector.rpl) {
BX_ERROR(("return_protected: ss.rpl != cs.rpl"));
exception(BX_GP_EXCEPTION, raw_ss_selector & 0xfffc, 0);
}
/* descriptor AR byte must indicate a writable data segment,
* else #GP(selector) */
if (ss_descriptor.valid==0 || ss_descriptor.segment==0 ||
IS_CODE_SEGMENT(ss_descriptor.type) ||
!IS_DATA_SEGMENT_WRITEABLE(ss_descriptor.type))
{
BX_ERROR(("return_protected: SS.AR byte not writable data"));
exception(BX_GP_EXCEPTION, raw_ss_selector & 0xfffc, 0);
}
/* descriptor dpl must = RPL of the return CS selector,
* else #GP(selector) */
if (ss_descriptor.dpl != cs_selector.rpl) {
BX_ERROR(("return_protected: SS.dpl != cs.rpl"));
exception(BX_GP_EXCEPTION, raw_ss_selector & 0xfffc, 0);
}
/* segment must be present else #SS(selector) */
if (! IS_PRESENT(ss_descriptor)) {
BX_ERROR(("return_protected: ss.present == 0"));
exception(BX_SS_EXCEPTION, raw_ss_selector & 0xfffc, 0);
}
branch_far64(&cs_selector, &cs_descriptor, return_RIP, cs_selector.rpl);
/* load SS:SP from stack */
/* load SS-cache with return SS descriptor */
load_ss(&ss_selector, &ss_descriptor, cs_selector.rpl);
#if BX_SUPPORT_X86_64
if (StackAddrSize64())
RSP = return_RSP + pop_bytes;
else
#endif
if (ss_descriptor.u.segment.d_b)
RSP = (Bit32u) return_RSP + pop_bytes;
else
SP = (Bit16u) return_RSP + pop_bytes;
/* check ES, DS, FS, GS for validity */
validate_seg_regs();
}
}
| 35.480176 | 88 | 0.610256 | pavel-krivanek |
f69ae147fa25a0a559ab792038bd0fc3a9a601c3 | 4,326 | cc | C++ | chrome/common/extensions/api/extension_action/browser_action_manifest_unittest.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/common/extensions/api/extension_action/browser_action_manifest_unittest.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/common/extensions/api/extension_action/browser_action_manifest_unittest.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "chrome/common/extensions/manifest_tests/extension_manifest_test.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/extension_icon_set.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/value_builder.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
namespace errors = manifest_errors;
namespace {
class BrowserActionManifestTest : public ExtensionManifestTest {
};
TEST_F(BrowserActionManifestTest,
BrowserActionManifestIcons_NoDefaultIcons) {
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "No default properties")
.Set("version", "1.0.0")
.Set("manifest_version", 2)
.Set("browser_action", DictionaryBuilder()
.Set("default_title", "Title")))
.Build();
ASSERT_TRUE(extension.get());
const ActionInfo* browser_action_info =
ActionInfo::GetBrowserActionInfo(extension.get());
ASSERT_TRUE(browser_action_info);
EXPECT_TRUE(browser_action_info->default_icon.empty());
}
TEST_F(BrowserActionManifestTest,
BrowserActionManifestIcons_StringDefaultIcon) {
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "String default icon")
.Set("version", "1.0.0")
.Set("manifest_version", 2)
.Set("browser_action", DictionaryBuilder()
.Set("default_icon", "icon.png")))
.Build();
ASSERT_TRUE(extension.get());
const ActionInfo* browser_action_info =
ActionInfo::GetBrowserActionInfo(extension.get());
ASSERT_TRUE(browser_action_info);
ASSERT_FALSE(browser_action_info->default_icon.empty());
const ExtensionIconSet& icons = browser_action_info->default_icon;
EXPECT_EQ(1u, icons.map().size());
EXPECT_EQ("icon.png", icons.Get(38, ExtensionIconSet::MATCH_EXACTLY));
}
TEST_F(BrowserActionManifestTest,
BrowserActionManifestIcons_DictDefaultIcon) {
scoped_refptr<const Extension> extension =
ExtensionBuilder()
.SetManifest(DictionaryBuilder()
.Set("name", "Dictionary default icon")
.Set("version", "1.0.0")
.Set("manifest_version", 2)
.Set("browser_action", DictionaryBuilder()
.Set("default_icon", DictionaryBuilder()
.Set("19", "icon19.png")
.Set("24", "icon24.png") // Should be ignored.
.Set("38", "icon38.png"))))
.Build();
ASSERT_TRUE(extension.get());
const ActionInfo* browser_action_info =
ActionInfo::GetBrowserActionInfo(extension.get());
ASSERT_TRUE(browser_action_info);
ASSERT_FALSE(browser_action_info->default_icon.empty());
const ExtensionIconSet& icons = browser_action_info->default_icon;
// 24px icon should be ignored.
EXPECT_EQ(2u, icons.map().size());
EXPECT_EQ("icon19.png", icons.Get(19, ExtensionIconSet::MATCH_EXACTLY));
EXPECT_EQ("icon38.png", icons.Get(38, ExtensionIconSet::MATCH_EXACTLY));
}
TEST_F(BrowserActionManifestTest,
BrowserActionManifestIcons_InvalidDefaultIcon) {
scoped_ptr<base::DictionaryValue> manifest_value = DictionaryBuilder()
.Set("name", "Invalid default icon").Set("version", "1.0.0")
.Set("manifest_version", 2)
.Set("browser_action",
DictionaryBuilder().Set(
"default_icon",
DictionaryBuilder().Set("19", std::string()) // Invalid value.
.Set("24", "icon24.png").Set("38", "icon38.png"))).Build();
base::string16 error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidIconPath, "19");
LoadAndExpectError(Manifest(manifest_value.get(), "Invalid default icon"),
errors::kInvalidIconPath);
}
} // namespace
} // namespace extensions
| 37.947368 | 78 | 0.664355 | tmpsantos |
f69bc182c6507f6f4de1e51fed57dd4ec398298c | 1,350 | cpp | C++ | 3rdParty/boost/1.71.0/libs/signals2/example/ordering_slots.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | 3rdParty/boost/1.71.0/libs/signals2/example/ordering_slots.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | 3rdParty/boost/1.71.0/libs/signals2/example/ordering_slots.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // Ordered slots hello world example for Boost.Signals2
// Copyright Douglas Gregor 2001-2004.
// Copyright Frank Mori Hess 2009.
//
// Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// For more information, see http://www.boost.org
#include <iostream>
#include <boost/signals2/signal.hpp>
struct Hello
{
void operator()() const
{
std::cout << "Hello";
}
};
struct World
{
void operator()() const
{
std::cout << ", World!" << std::endl;
}
};
//[ good_morning_def_code_snippet
struct GoodMorning
{
void operator()() const
{
std::cout << "... and good morning!" << std::endl;
}
};
//]
int main()
{
//[ hello_world_ordered_code_snippet
boost::signals2::signal<void ()> sig;
sig.connect(1, World()); // connect with group 1
sig.connect(0, Hello()); // connect with group 0
//]
//[ hello_world_ordered_invoke_code_snippet
// by default slots are connected at the end of the slot list
sig.connect(GoodMorning());
// slots are invoked this order:
// 1) ungrouped slots connected with boost::signals2::at_front
// 2) grouped slots according to ordering of their groups
// 3) ungrouped slots connected with boost::signals2::at_back
sig();
//]
return 0;
}
| 21.428571 | 65 | 0.678519 | rajeev02101987 |
f69e781bf8eb0f31d0eea18483a411b14900b2ef | 293 | cpp | C++ | 27-remove-element/27-remove-element.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | 27-remove-element/27-remove-element.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | 27-remove-element/27-remove-element.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
int k{0};
for(int i=0;i<n;i++){
if(nums[i] != val){
nums[k] = nums[i];
k++;
}
}
return k;
}
}; | 20.928571 | 51 | 0.375427 | Edith-panda |
f69eb41d92b39972d172e2b3a5de6be6635dcd0d | 2,956 | cpp | C++ | HugeCTR/src/model_oversubscriber/parameter_server.cpp | xmh645214784/HugeCTR-1 | de4e850ef9993998c3a69ff1f2af64bed528989f | [
"Apache-2.0"
] | null | null | null | HugeCTR/src/model_oversubscriber/parameter_server.cpp | xmh645214784/HugeCTR-1 | de4e850ef9993998c3a69ff1f2af64bed528989f | [
"Apache-2.0"
] | null | null | null | HugeCTR/src/model_oversubscriber/parameter_server.cpp | xmh645214784/HugeCTR-1 | de4e850ef9993998c3a69ff1f2af64bed528989f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <model_oversubscriber/parameter_server.hpp>
#include <fstream>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
namespace HugeCTR {
namespace {
void open_and_get_size(const std::string& file_name, std::ifstream& stream,
size_t& file_size_in_byte) {
stream.open(file_name, std::ifstream::binary);
if (!stream.is_open()) {
CK_THROW_(Error_t::WrongInput, "Cannot open the file: " + file_name);
}
file_size_in_byte = fs::file_size(file_name);
}
} // namespace
template <typename TypeKey>
ParameterServer<TypeKey>::ParameterServer(bool use_host_ps,
const std::string &sparse_model_file, Embedding_t embedding_type,
size_t emb_vec_size, std::shared_ptr<ResourceManager> resource_manager)
: use_host_ps_(use_host_ps),
sparse_model_entity_(SparseModelEntity<TypeKey>(use_host_ps,
sparse_model_file, embedding_type, emb_vec_size, resource_manager)) {}
template <typename TypeKey>
void ParameterServer<TypeKey>::load_keyset_from_file(
std::string keyset_file) {
try {
std::ifstream keyset_stream;
size_t file_size_in_byte = 0;
open_and_get_size(keyset_file, keyset_stream, file_size_in_byte);
if (file_size_in_byte == 0) {
CK_THROW_(Error_t::WrongInput, std::string(keyset_file) + " is empty");
}
size_t num_keys_in_file = file_size_in_byte / sizeof(TypeKey);
keyset_.resize(num_keys_in_file);
keyset_stream.read((char*)keyset_.data(), file_size_in_byte);
#ifdef ENABLE_MPI
CK_MPI_THROW_(MPI_Barrier(MPI_COMM_WORLD));
#endif
} catch (const internal_runtime_error& rt_err) {
std::cerr << rt_err.what() << std::endl;
throw;
} catch (const std::exception& err) {
std::cerr << err.what() << std::endl;
throw;
}
}
template <typename TypeKey>
void ParameterServer<TypeKey>::pull(BufferBag& buf_bag, size_t& hit_size) {
if (keyset_.size() == 0) {
CK_THROW_(Error_t::WrongInput, "keyset is empty");
}
sparse_model_entity_.load_vec_by_key(keyset_, buf_bag, hit_size);
}
template <typename TypeKey>
void ParameterServer<TypeKey>::push(BufferBag &buf_bag, size_t dump_size) {
if (dump_size == 0) return;
sparse_model_entity_.dump_vec_by_key(buf_bag, dump_size);
}
template class ParameterServer<long long>;
template class ParameterServer<unsigned>;
} // namespace HugeCTR
| 32.130435 | 77 | 0.734777 | xmh645214784 |
f6a011cd5857a6a1ecd43ba20c536bc22ff0ff91 | 19,031 | cxx | C++ | osprey/be/lno/lego_skew.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/be/lno/lego_skew.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/be/lno/lego_skew.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2009 Advanced Micro Devices, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#ifdef USE_PCH
#include "lno_pch.h"
#endif // USE_PCH
#pragma hdrstop
#ifdef _KEEP_RCS_ID
/*REFERENCED*/
static char *rcs_id = "$Source$ $Revision$";
#endif /* _KEEP_RCS_ID */
#include <sys/types.h>
#include <ctype.h>
#include <limits.h>
#include <alloca.h>
#include "pu_info.h"
#include "lnoutils.h"
#include "lnopt_main.h"
#include "stab.h"
#include "targ_const.h"
#include "wn_simp.h"
#include "stdlib.h"
#include "lwn_util.h"
#include "strtab.h"
#include "config.h"
#include "optimizer.h"
#include "opt_du.h"
#include "name.h"
#include "wintrinsic.h"
#include "lno_bv.h"
#include "dep_graph.h"
#include "debug.h"
#include "cxx_memory.h"
#include "lego_pragma.h"
#include "lego_util.h"
#include "lego_skew.h"
#include "tlog.h"
//-----------------------------------------------------------------------
// NAME: Lego_Reshaped_Array
// FUNCTION: Returns TRUE if the OPR_ARRAY node 'wn_array' is a lego
// reshaped array, FALSE otherwise.
//-----------------------------------------------------------------------
static BOOL Lego_Reshaped_Array(WN* wn_array)
{
if (WN_operator(wn_array) != OPR_ARRAY)
return FALSE;
ST* st_array;
WN *array_base = WN_array_base(wn_array);
st_array = (WN_has_sym(array_base) ? WN_st(array_base) : NULL);
DISTR_ARRAY* dact = Lookup_DACT(st_array);
if (dact == NULL || !dact->Dinfo()->IsReshaped())
return FALSE;
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Canonical
// FUNCTION: Returns TRUE if the access vector is canonical with respect
// to the loop 'wn_loop'. Right now, this means that it has the form
// 'c1*i+x-c2' where "i" is the index variable of 'wn_loop', "x" is some
// linear combination of loop invariant variables, and "c1" and "c2" are
// literal constants. Also, "c1" must be either 1 or -1.
//-----------------------------------------------------------------------
static BOOL Lego_Skew_Canonical(WN* wn_loop,
ACCESS_VECTOR* av)
{
if (av->Too_Messy)
return FALSE;
if (av->Contains_Non_Lin_Symb())
return FALSE;
if (!av->Has_Loop_Coeff())
return FALSE;
INT loop_depth = Do_Depth(wn_loop);
INT loop_coeff = av->Loop_Coeff(loop_depth);
if (loop_coeff != 1 && loop_coeff != -1)
return FALSE;
for (INT i = 0; i < av->Nest_Depth(); i++)
if (i != loop_depth && av->Loop_Coeff(i) != 0)
return FALSE;
if (!av->Contains_Lin_Symb())
return FALSE;
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Equivalent
// FUNCTION: Returns TRUE if the canonical access vectors 'av1' and 'av2'
// are equivalent. Right now, this means that their linear portions are
// equivalent and the coefficients corresponding to 'wn_loop' are equal.
//-----------------------------------------------------------------------
static BOOL Lego_Skew_Equivalent(WN* wn_loop,
ACCESS_VECTOR* av1,
ACCESS_VECTOR* av2)
{
if (av1->Loop_Coeff(Do_Depth(wn_loop)) != av2->Loop_Coeff(Do_Depth(wn_loop)))
return FALSE;
INTSYMB_LIST* isl = NULL;
isl = Subtract(av1->Lin_Symb, av2->Lin_Symb, &LNO_local_pool);
if (isl != NULL)
return FALSE;
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Update_Skew_Count
// FUNCTION: For the given array 'wn_array' with respect to the loop
// 'wn_loop', enter all canonical skew accesses into separate buckets
// of 'st_skew'.
//-----------------------------------------------------------------------
static void Lego_Update_Skew_Count(WN* wn_loop,
WN* wn_array,
STACK<LEGO_SKEW*>* st_skew)
{
DISTR_ARRAY* dact = Lookup_DACT(WN_has_sym(WN_array_base(wn_array)) ?
WN_st(WN_array_base(wn_array)) :
NULL);
ACCESS_ARRAY *aa = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, wn_array);
if (aa == NULL || aa->Too_Messy)
return;
for (INT i = 0; i < aa->Num_Vec(); i++) {
ACCESS_VECTOR* av = aa->Dim(i);
if (Lego_Skew_Canonical(wn_loop, av)) {
INT j;
for (j = 0; j < st_skew->Elements(); j++) {
LEGO_SKEW* lsk = st_skew->Bottom_nth(j);
ST* st_old = (WN_has_sym(WN_array_base(lsk->Array())) ?
WN_st(WN_array_base(lsk->Array())) :
NULL);
DISTR_ARRAY* dact_old = Lookup_DACT(st_old);
if (dact->DACT_Equiv(dact_old, i, lsk->Dim())
&& Lego_Skew_Equivalent(wn_loop, av, lsk->Av())) {
lsk->Increment();
break;
}
}
if (j == st_skew->Elements()) {
LEGO_SKEW* lsk_new = CXX_NEW(LEGO_SKEW(av, wn_array, i, 1),
&LNO_default_pool);
st_skew->Push(lsk_new);
}
}
}
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Offset
// FUNCTION: Returns a WN* to an expression tree corresponding to the
// LEGO_SKEW 'lsk'.
//-----------------------------------------------------------------------
static WN* Lego_Skew_Offset(LEGO_SKEW* lsk,
BOOL negative_stride,
DU_MANAGER* du)
{
WN* wn_skew = NULL;
INTSYMB_CONST_ITER iter(lsk->Av()->Lin_Symb);
const INTSYMB_NODE *first = iter.First();
for (const INTSYMB_NODE *node=first; !iter.Is_Empty(); node = iter.Next()) {
WN* wn_variable = Find_Node(node->Symbol, lsk->Array());
WN* wn_constant = LWN_Make_Icon(WN_rtype(wn_variable), node->Coeff);
WN* wn_varcopy = LWN_Copy_Tree(wn_variable);
LWN_Copy_Def_Use(wn_variable, wn_varcopy, du);
OPCODE op_mpy = OPCODE_make_op(OPR_MPY, WN_rtype(wn_variable), MTYPE_V);
WN* wn_prod = LWN_CreateExp2(op_mpy, wn_constant, wn_varcopy);
if (wn_skew == NULL) {
wn_skew = wn_prod;
} else {
TYPE_ID type_add = Max_Wtype(WN_rtype(wn_skew), WN_rtype(wn_prod));
OPCODE op_add = OPCODE_make_op(OPR_ADD, type_add, MTYPE_V);
wn_skew = LWN_CreateExp2(op_add, wn_skew, wn_prod);
}
}
if (negative_stride) {
WN* wn_minusone = LWN_Make_Icon(WN_rtype(wn_skew), -1);
OPCODE op_mpy = OPCODE_make_op(OPR_MPY, WN_rtype(wn_skew), MTYPE_V);
wn_skew = LWN_CreateExp2(op_mpy, wn_minusone, wn_skew);
}
return wn_skew;
}
//-----------------------------------------------------------------------
// NAME: Lego_Loop_Want_Skew
// FUNCTION: Returns TRUE if we would like to skew the indices of the
// loop 'wn_loop'.
// NOTE: On exit, the value of the skew factor is copied back into
// 'wn_lego_skew_addr'.
//-----------------------------------------------------------------------
static BOOL Lego_Loop_Want_Skew(WN* wn_loop,
WN** wn_lego_skew_addr,
DU_MANAGER* du)
{
*wn_lego_skew_addr = NULL;
WN* wn_step = Loop_Step(wn_loop);
if (WN_operator(wn_step) != OPR_INTCONST)
return FALSE;
if (WN_const_val(wn_step) != 1)
return FALSE;
if (!Upper_Bound_Standardize(WN_end(wn_loop), TRUE))
return FALSE;
STACK<LEGO_SKEW*> st_skew(&LNO_local_pool);
LWN_ITER* itr = LWN_WALK_TreeIter(WN_do_body(wn_loop));
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (Lego_Reshaped_Array(wn))
Lego_Update_Skew_Count(wn_loop, wn, &st_skew);
}
if (st_skew.Elements() == 0)
return FALSE;
LEGO_SKEW* lsk_best = st_skew.Bottom_nth(0);
for (INT i = 1; i < st_skew.Elements(); i++) {
LEGO_SKEW* lsk = st_skew.Bottom_nth(i);
if (lsk->Count() > lsk_best->Count())
lsk_best = lsk;
}
BOOL negative_stride = lsk_best->Av()->Loop_Coeff(Do_Depth(wn_loop)) < 0;
*wn_lego_skew_addr = Lego_Skew_Offset(lsk_best, negative_stride, du);
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Parent_Array
// FUNCTION: Returns the closest enclosing OPR_ARRAY node which is a
// parent of 'wn_node'. Returns NULL if there is none.
//-----------------------------------------------------------------------
static WN* Lego_Parent_Array(WN* wn_node)
{
for (WN* wn = wn_node; wn != NULL; wn = LWN_Get_Parent(wn))
if (WN_operator(wn) == OPR_ARRAY)
return wn;
return NULL;
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Index
// FUNCTION: Returns an expression 'index - offset' where "index"
// is the index variable of 'wn_loop' and "offset" is the expression
// in 'wn_lego_skew_offset'.
//-----------------------------------------------------------------------
static WN* Lego_Skew_Index(WN* wn_loop,
WN* wn_lego_skew_offset,
DU_MANAGER* du)
{
TYPE_ID type = Promote_Type(Do_Wtype(wn_loop));
WN* wn_index = UBvar(WN_end(wn_loop));
WN* wn_index_copy = LWN_Copy_Tree(wn_index);
LWN_Copy_Def_Use(wn_index, wn_index_copy, du);
WN* wn_ldid = LWN_Copy_Tree(wn_lego_skew_offset);
LWN_Copy_Def_Use(wn_lego_skew_offset, wn_ldid, du);
OPCODE op = OPCODE_make_op(OPR_SUB, type, MTYPE_V);
WN* wn_skew = LWN_CreateExp2(op, wn_index_copy, wn_ldid);
return wn_skew;
}
//-----------------------------------------------------------------------
// NAME: Lego_Contains_Non_Index_Ldid
// FUNCTION: Returns TRUE if the expression 'wn_index' contains an LDID
// of a symbol other than the index variable of 'wn_loop', FALSE
// otherwise.
//-----------------------------------------------------------------------
static BOOL Lego_Contains_Non_Index_Ldid(WN* wn_loop,
WN* wn_index)
{
LWN_ITER* itr = LWN_WALK_TreeIter(wn_index);
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (WN_operator(wn) == OPR_LDID
&& SYMBOL(wn) != SYMBOL(WN_index(wn_loop)))
return TRUE;
}
return FALSE;
}
//-----------------------------------------------------------------------
// NAME: Lego_Index_From_Access_Vector
// FUNCTION: Returns a WN* to an expression equivalent to the access
// vector 'av'. The expressions value should be equivalent to that
// in 'wn_index'.
//-----------------------------------------------------------------------
static WN* Lego_Index_From_Access_Vector(ACCESS_VECTOR* av,
WN* wn_index,
DU_MANAGER* du)
{
WN* wn_new_index = NULL;
for (INT i = 0; i < av->Nest_Depth(); i++) {
if (av->Loop_Coeff(i) == 0)
continue;
WN* wn = 0;
for (wn = wn_index; wn != NULL; wn = LWN_Get_Parent(wn))
if (WN_opcode(wn) == OPC_DO_LOOP && Do_Depth(wn) == i)
break;
FmtAssert(wn != NULL, ("Could not find do loop with given depth"));
OPCODE op_ldid = Matching_Load_Opcode(WN_opcode(WN_start(wn)));
WN* wn_ldid = LWN_CreateLdid(op_ldid, WN_start(wn));
du->Add_Def_Use(WN_start(wn), wn_ldid);
du->Add_Def_Use(WN_step(wn), wn_ldid);
du->Ud_Get_Def(wn_ldid)->Set_loop_stmt(wn);
WN* wn_constant = LWN_Make_Icon(WN_rtype(wn_ldid), av->Loop_Coeff(i));
OPCODE op_mpy = OPCODE_make_op(OPR_MPY, WN_rtype(wn_ldid), MTYPE_V);
WN* wn_prod = LWN_CreateExp2(op_mpy, wn_constant, wn_ldid);
if (wn_new_index == NULL) {
wn_new_index = wn_prod;
} else {
TYPE_ID type_add = Max_Wtype(WN_rtype(wn_ldid), WN_rtype(wn_new_index));
OPCODE op_add = OPCODE_make_op(OPR_ADD, type_add, MTYPE_V);
wn_new_index = LWN_CreateExp2(op_add, wn_new_index, wn_prod);
}
}
if (av->Const_Offset != 0) {
if (wn_new_index == 0) {
wn_new_index = LWN_Make_Icon(av->Const_Offset, WN_rtype(wn_index));
} else {
WN* wn_offset = LWN_Make_Icon(WN_rtype(wn_new_index), av->Const_Offset);
OPCODE op_add = OPCODE_make_op(OPR_ADD, WN_rtype(wn_new_index), MTYPE_V);
wn_new_index = LWN_CreateExp2(op_add, wn_new_index, wn_offset);
}
}
return wn_new_index;
}
//-----------------------------------------------------------------------
// NAME: Lego_Simplify
// FUNCTION: Simplify the subscripts of the array expression 'wn_loop'
// which contain the index variable of loop 'wn_loop' if their access
// vectors contain only index variables and constants and if the
// subscripts also contain other symbols.
//-----------------------------------------------------------------------
static void Lego_Simplify(WN* wn_loop,
WN* wn_array,
DU_MANAGER* du)
{
ACCESS_ARRAY *aa = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, wn_array);
if (aa == NULL || aa->Too_Messy)
return;
INT loop_depth = Do_Depth(wn_loop);
INT i;
for (i = 0; i < aa->Num_Vec(); i++)
if (aa->Dim(i)->Delinearized_Symbol != NULL)
return;
for (i = 0; i < aa->Num_Vec(); i++) {
ACCESS_VECTOR* av = aa->Dim(i);
if (av->Too_Messy)
continue;
INT loop_coeff = av->Loop_Coeff(loop_depth);
if (av->Loop_Coeff(loop_depth)== 0 || av->Contains_Non_Lin_Symb())
continue;
if (av->Contains_Lin_Symb())
continue;
WN* wn_index = WN_array_index(wn_array, i);
if (!Lego_Contains_Non_Index_Ldid(wn_loop, wn_index))
continue;
WN* wn_new_index = Lego_Index_From_Access_Vector(av, wn_index, du);
Replace_Wnexp_With_Exp_Copy(wn_index, wn_new_index, du);
LWN_Delete_Tree(wn_new_index);
}
}
//-----------------------------------------------------------------------
// NAME: Lego_Simplify_Loop
// FUNCTION: Simplify the subscripts of array elements in 'wn_loop' using
// access vectors.
//-----------------------------------------------------------------------
static void Lego_Simplify_Loop(WN* wn_loop,
DU_MANAGER* du)
{
LWN_ITER* itr = LWN_WALK_TreeIter(WN_do_body(wn_loop));
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (WN_operator(wn) == OPR_ARRAY)
Lego_Simplify(wn_loop, wn, du);
}
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Loop
// FUNCTION: Skew the loop 'wn_loop' by subtracting 'wn_lego_skew_index'
// from each instance of the index variable of 'wn_loop' and adding the
// same value to the loop bounds.
//-----------------------------------------------------------------------
static void Lego_Skew_Loop(WN* wn_loop,
WN* wn_lego_skew_offset,
DU_MANAGER* du)
{
if (LNO_Verbose) {
fprintf(stdout, "Lego skewing loop %s on line %d\n",
WB_Whirl_Symbol(wn_loop), Srcpos_To_Line(WN_linenum(wn_loop)));
fprintf(TFile, "Lego skewing loop %s on line %d\n",
WB_Whirl_Symbol(wn_loop), Srcpos_To_Line(WN_linenum(wn_loop)));
if (LNO_Tlog)
Generate_Tlog("LNO", "lego_skewing", Srcpos_To_Line(WN_linenum(wn_loop)),
(char *) WB_Whirl_Symbol(wn_loop), "", "", "");
}
if (Index_Variable_Live_At_Exit(wn_loop))
Finalize_Index_Variable(wn_loop, TRUE, TRUE);
TYPE_ID type = Promote_Type(Do_Wtype(wn_loop));
OPCODE op_skew = OPCODE_make_op(OPR_ADD, type, MTYPE_V);
LWN_ITER* itr = LWN_WALK_TreeIter(WN_do_body(wn_loop));
STACK<WN*> index_stack(&LNO_local_pool);
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (WN_operator(wn) == OPR_LDID
&& SYMBOL(wn) == SYMBOL(WN_index(wn_loop)))
index_stack.Push(wn);
}
INT i;
for (i = 0; i < index_stack.Elements(); i++) {
WN* wn = index_stack.Bottom_nth(i);
WN* wn_array = Lego_Parent_Array(wn);
WN* wn_new_index = Lego_Skew_Index(wn_loop, wn_lego_skew_offset, du);
Replace_Wnexp_With_Exp_Copy(wn, wn_new_index, du);
if (wn_array != NULL)
LWN_Simplify_Tree(wn_array);
LWN_Delete_Tree(wn_new_index);
}
WN* wn_start = WN_kid0(WN_start(wn_loop));
WN* wn_stop = UBexp(WN_end(wn_loop));
for (i = 0; i < WN_kid_count(WN_end(wn_loop)); i++)
if (WN_kid(WN_end(wn_loop), i) == wn_stop)
break;
INT stop_index = i;
WN* wn_skew = LWN_Copy_Tree(wn_lego_skew_offset);
LWN_Copy_Def_Use(wn_lego_skew_offset, wn_skew, du);
WN* wn_new_start = LWN_CreateExp2(op_skew, wn_start, wn_skew);
wn_skew = LWN_Copy_Tree(wn_lego_skew_offset);
LWN_Copy_Def_Use(wn_lego_skew_offset, wn_skew, du);
WN* wn_new_stop = LWN_CreateExp2(op_skew, wn_stop, wn_skew);
WN_kid0(WN_start(wn_loop)) = wn_new_start;
LWN_Set_Parent(wn_new_start, WN_start(wn_loop));
WN_kid(WN_end(wn_loop), stop_index) = wn_new_stop;
LWN_Set_Parent(wn_new_stop, WN_end(wn_loop));
LWN_Delete_Tree(wn_lego_skew_offset);
DOLOOP_STACK shortstack(&LNO_local_pool);
Build_Doloop_Stack(LWN_Get_Parent(wn_loop), &shortstack);
LNO_Build_Access(wn_loop, &shortstack, &LNO_default_pool, 0, TRUE);
Lego_Simplify_Loop(wn_loop, du);
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Traverse
// FUNCTION: Traverse 'wn_tree' preforming lego skewing on loops for
// which is it appropriate.
//-----------------------------------------------------------------------
static void Lego_Skew_Traverse(WN* wn_tree,
DU_MANAGER* du)
{
if (WN_opcode(wn_tree) == OPC_DO_LOOP) {
WN* wn_lego_skew_offset = NULL;
if (Lego_Loop_Want_Skew(wn_tree, &wn_lego_skew_offset, du))
Lego_Skew_Loop(wn_tree, wn_lego_skew_offset, du);
}
if (WN_opcode(wn_tree) == OPC_BLOCK) {
for (WN* wn = WN_first(wn_tree); wn != NULL; wn = WN_next(wn))
Lego_Skew_Traverse(wn, du);
} else {
for (INT i = 0; i < WN_kid_count(wn_tree); i++)
Lego_Skew_Traverse(WN_kid(wn_tree, i), du);
}
}
//-----------------------------------------------------------------------
// NAME: Lego_Skew_Indices
// FUNCTION: Apply lego skewing to all appropriate loops in the tree
// 'wn_tree'.
//-----------------------------------------------------------------------
extern void Lego_Skew_Indices(WN* wn_tree)
{
DU_MANAGER* du = Du_Mgr;
Lego_Skew_Traverse(wn_tree, du);
}
| 36.249524 | 79 | 0.600967 | sharugupta |
f6a3411d6f39dea8e79f61e4068d9d648d91a4a2 | 3,104 | cpp | C++ | ntuj/pd.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | ntuj/pd.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | ntuj/pd.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#include <algorithm>
#include <map>
#include <set>
using namespace std;
int a[1005][4];
int siz[1005];
int n;
int r[4];
class Event {
public:
int t, L, R, v;
Event(int tt=0, int ll=0, int rr=0, int vv=0) {
t = tt; L = ll; R = rr; v=vv;
}
bool operator<(const Event &e) const {
return t < e.t || t==e.t && v < e.v;
}
} e[2005];
class Segment {
public:
int maxvalue, maxpos, value;
Segment(int m=0,int p=0, int v=0) {
maxvalue = m; maxpos = p; value = v;
}
};
Segment seg[100005];
int ne;
int yy[50005];
inline void init(int x, int L, int R) {
if(L==R) {
seg[x].maxvalue = 0;
seg[x].maxpos = L;
seg[x].value = 0;
} else {
seg[x].maxvalue = 0;
seg[x].maxpos = L;
seg[x].value = 0;
init(x*2, L, (L+R)/2);
init(x*2+1, (L+R)/2+1, R);
}
}
inline void combine(int x) {
int y = x*2, z = x*2+1;
if(seg[y].maxvalue >= seg[z].maxvalue) {
seg[x].maxvalue = seg[y].maxvalue + seg[x].value;
seg[x].maxpos = seg[y].maxpos;
} else {
seg[x].maxvalue = seg[z].maxvalue + seg[x].value;
seg[x].maxpos = seg[z].maxpos;
}
}
int cnt=0;
inline void update(int x, int L, int R, int vL, int vR, int v) {
++cnt;
if(vL <= L && vR >= R) {
seg[x].value += v;
seg[x].maxvalue += v;
} else {
int M = (L+R)/2;
if(vL <= M) update(x*2, L, M, vL, vR, v);
if(vR > M) update(x*2+1, M+1, R, vL, vR, v);
combine(x);
}
}
int ans=0;
int go(int side) {
int i, d=0;
ne = 0;
set<int> s;
map<int, int> ymap;
for(i=0;i<n;i++) {
if(siz[i] >= side) {
e[ne].t = a[i][0] - side + 1;
e[ne].L = a[i][1] - side + 1;
e[ne].R = a[i][3] - 1;
s.insert(e[ne].L);
s.insert(e[ne].R);
e[ne++].v = 1;
e[ne].t = a[i][2];
e[ne].L = a[i][1] - side + 1;
e[ne].R = a[i][3] - 1;
s.insert(e[ne].L);
s.insert(e[ne].R);
e[ne++].v = -1;
++d;
}
}
if(d<=ans) return -1;
i=0;
int len = s.size();
for(set<int>::iterator it = s.begin(); it != s.end(); it++) {
ymap[*it] = ++i;
yy[i] = *it;
}
sort(e, e+ne);
init(1, 1, len);
int mx=0;
for(i=0;i<ne;i++) {
//printf("t=%d %d %d %d\n", e[i].t, e[i].L, e[i].R, e[i].v);
update(1, 1, len, ymap[e[i].L], ymap[e[i].R], e[i].v);
if(seg[1].maxvalue > mx) {
mx = seg[1].maxvalue;
r[0] = e[i].t;
r[1] = yy[seg[1].maxpos];
r[2] = r[0]+side;
r[3] = r[1]+side;
}
}
return mx;
}
int main(void)
{
int i, j;
while(scanf("%d", &n)!=EOF) {
if(n==0) break;
for(i=0;i<n;i++) {
for(j=0;j<4;j++)
scanf("%d", &a[i][j]);
siz[i] = a[i][2]-a[i][0];
}
int mx=0, v;
int p[4];
set<int> usedsiz;
ans = 0;
for(i=0;i<n;i++) {
if(usedsiz.count(siz[i])) continue;
usedsiz.insert(siz[i]);
v=go(siz[i]);
if(v>mx){
mx = v;
ans = mx;
for(j=0;j<4;j++)
p[j] = r[j];
//printf("ans=%d\n", ans);
if(ans>=4) break;
}
}
printf("%d %d %d %d\n", p[0], p[1], p[2], p[3]);
}
return 0;
}
| 20.693333 | 64 | 0.451675 | dk00 |
f6a4cf1d4635dc4473d051a919d0a1b73d62511f | 21,317 | cpp | C++ | drake/systems/plants/constraint/updatePtrRigidBodyConstraintmex.cpp | ericmanzi/double_pendulum_lqr | 76bba3091295abb7d412c4a3156258918f280c96 | [
"BSD-3-Clause"
] | 4 | 2018-04-16T09:54:52.000Z | 2021-03-29T21:59:27.000Z | drake/systems/plants/constraint/updatePtrRigidBodyConstraintmex.cpp | ericmanzi/double_pendulum_lqr | 76bba3091295abb7d412c4a3156258918f280c96 | [
"BSD-3-Clause"
] | null | null | null | drake/systems/plants/constraint/updatePtrRigidBodyConstraintmex.cpp | ericmanzi/double_pendulum_lqr | 76bba3091295abb7d412c4a3156258918f280c96 | [
"BSD-3-Clause"
] | 1 | 2017-08-24T20:32:03.000Z | 2017-08-24T20:32:03.000Z | #include "mex.h"
#include <iostream>
#include "drakeMexUtil.h"
#include <Eigen/Dense>
#include "RigidBodyConstraint.h"
#include "RigidBodyManipulator.h"
#include "constructPtrRigidBodyConstraint.h"
#include <cstdio>
using namespace Eigen;
using namespace std;
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
RigidBodyConstraint* constraint = (RigidBodyConstraint*) getDrakeMexPointer(prhs[0]);
int constraint_type = constraint->getType();
if (nrhs<2) { // then it's just calling delete
destroyDrakeMexPointer<RigidBodyConstraint*>(prhs[0]);
return;
}
mwSize strlen = static_cast<mwSize>(mxGetNumberOfElements(prhs[1]) + 1);
char* field = new char[strlen];
mxGetString(prhs[1],field,strlen);
string field_str(field);
switch(constraint_type)
{
case RigidBodyConstraint::QuasiStaticConstraintType:
{
QuasiStaticConstraint* cnst = (QuasiStaticConstraint*) constraint;
if(field_str=="active")
{
// setActive(qsc_ptr,flag)
if(mxGetNumberOfElements(prhs[2]) != 1)
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","QuasiStaticConstraint:flag must be a single boolean");
}
bool* flag = mxGetLogicals(prhs[2]);
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->setActive(*flag);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
}
else if(field_str=="factor")
{// setShrinkFactor(qsc_ptr,factor)
if(mxGetNumberOfElements(prhs[2]) != 1)
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","QuasiStaticConstraint:shrink factor must be a double scalar");
}
double factor = mxGetScalar(prhs[2]);
if(factor<=0.0)
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","QuasiStaticConstraint:shrink factor should be a positive scalar");
}
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->setShrinkFactor(factor);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
}
else if(field_str=="contact")
{
// addContact(qsc_ptr,body1, body1_pts, body2, body2_pts,...)
int num_new_bodies = (nrhs-2)/2;
int* new_bodies = new int[num_new_bodies];
Matrix3Xd* new_body_pts = new Matrix3Xd[num_new_bodies];
for(int idx = 0;idx<num_new_bodies;idx++)
{
new_bodies[idx] = (int) mxGetScalar(prhs[2+idx*2])-1;
size_t npts = mxGetN(prhs[3+idx*2]);
Matrix3Xd new_body_pts_tmp(3,npts);
memcpy(new_body_pts_tmp.data(),mxGetPrSafe(prhs[3+idx*2]),sizeof(double)*3*npts);
new_body_pts[idx].resize(3,npts);
new_body_pts[idx].block(0,0,3,npts) = new_body_pts_tmp;
}
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->addContact(num_new_bodies,new_bodies,new_body_pts);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
delete[] new_bodies;
delete[] new_body_pts;
}
else if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
}
else if(field_str=="robotnum")
{
size_t num_robot = mxGetNumberOfElements(prhs[2]);
double* robotnum_tmp = new double[num_robot];
int* robotnum = new int[num_robot];
memcpy(robotnum_tmp,mxGetPrSafe(prhs[2]),sizeof(double)*num_robot);
for(int i = 0;i<num_robot;i++)
{
robotnum[i] = (int) robotnum_tmp[i]-1;
}
set<int> robotnumset(robotnum,robotnum+num_robot);
QuasiStaticConstraint* cnst_new = new QuasiStaticConstraint(*cnst);
cnst_new->updateRobotnum(robotnumset);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"QuasiStaticConstraint");
delete[] robotnum_tmp;
delete[] robotnum;
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","QuasiStaticConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::PostureConstraintType:
{
PostureConstraint* pc = (PostureConstraint*) constraint;
if(field_str=="bounds")
{ // setJointLimits(pc,joint_idx,lb,ub)
size_t num_idx = mxGetM(prhs[2]);
if(!mxIsNumeric(prhs[2]) || mxGetN(prhs[2]) != 1 || !mxIsNumeric(prhs[3]) || mxGetM(prhs[3]) != num_idx || mxGetN(prhs[3]) != 1 || !mxIsNumeric(prhs[4]) || mxGetM(prhs[4]) != num_idx || mxGetN(prhs[4]) != 1)
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","PostureConstraint:joint_idx, lb and ub must be of the same length numerical vector");
}
int* joint_idx = new int[num_idx];
for(int i = 0;i<num_idx;i++)
{
joint_idx[i] = (int) *(mxGetPrSafe(prhs[2])+i)-1;
}
VectorXd lb(num_idx),ub(num_idx);
memcpy(lb.data(),mxGetPrSafe(prhs[3]),sizeof(double)*num_idx);
memcpy(ub.data(),mxGetPrSafe(prhs[4]),sizeof(double)*num_idx);
PostureConstraint* pc_new = new PostureConstraint(*pc);
pc_new->setJointLimits(static_cast<int>(num_idx), joint_idx, lb, ub);
delete[] joint_idx;
plhs[0] = createDrakeConstraintMexPointer((void*)pc_new,"PostureConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","PostureConstraint: argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::AllBodiesClosestDistanceConstraintType:
{
AllBodiesClosestDistanceConstraint* cnst = (AllBodiesClosestDistanceConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
AllBodiesClosestDistanceConstraint* cnst_new = new AllBodiesClosestDistanceConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"AllBodiesClosestDistanceConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","AllBodiesClosestDistanceConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldEulerConstraintType:
{
WorldEulerConstraint* cnst = (WorldEulerConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldEulerConstraint* cnst_new = new WorldEulerConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldEulerConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldEulerConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldGazeDirConstraintType:
{
WorldGazeDirConstraint* cnst = (WorldGazeDirConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldGazeDirConstraint* cnst_new = new WorldGazeDirConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldGazeDirConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldGazeDirConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldGazeOrientConstraintType:
{
WorldGazeOrientConstraint* cnst = (WorldGazeOrientConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldGazeOrientConstraint* cnst_new = new WorldGazeOrientConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldGazeOrientConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldGazeOrientConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldGazeTargetConstraintType:
{
WorldGazeTargetConstraint* cnst = (WorldGazeTargetConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldGazeTargetConstraint* cnst_new = new WorldGazeTargetConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldGazeTargetConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldGazeTargetConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::RelativeGazeTargetConstraintType:
{
RelativeGazeTargetConstraint* cnst = (RelativeGazeTargetConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
RelativeGazeTargetConstraint* cnst_new = new RelativeGazeTargetConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"RelativeGazeTargetConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","RelativeGazeTargetConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::RelativeGazeDirConstraintType:
{
RelativeGazeDirConstraint* cnst = (RelativeGazeDirConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
RelativeGazeDirConstraint* cnst_new = new RelativeGazeDirConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"RelativeGazeDirConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","RelativeGazeDirConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldCoMConstraintType:
{
WorldCoMConstraint* cnst = (WorldCoMConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldCoMConstraint* cnst_new = new WorldCoMConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldCoMConstraint");
}
else if(field_str=="robotnum")
{
size_t num_robot = mxGetNumberOfElements(prhs[2]);
double* robotnum_tmp = new double[num_robot];
int* robotnum = new int[num_robot];
memcpy(robotnum_tmp,mxGetPrSafe(prhs[2]),sizeof(double)*num_robot);
for(int i = 0;i<num_robot;i++)
{
robotnum[i] = (int) robotnum_tmp[i]-1;
}
set<int> robotnumset(robotnum,robotnum+num_robot);
WorldCoMConstraint* cnst_new = new WorldCoMConstraint(*cnst);
cnst_new->updateRobotnum(robotnumset);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldCoMConstraint");
delete[] robotnum_tmp;
delete[] robotnum;
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldCoMConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldPositionConstraintType:
{
WorldPositionConstraint* cnst = (WorldPositionConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldPositionConstraint* cnst_new = new WorldPositionConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"WorldPositionConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldPositionConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldPositionInFrameConstraintType:
{
WorldPositionInFrameConstraint* cnst = (WorldPositionInFrameConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldPositionInFrameConstraint* cnst_new = new WorldPositionInFrameConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"WorldPositionInFrameConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldPositionInFrameConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldQuatConstraintType:
{
WorldQuatConstraint* cnst = (WorldQuatConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldQuatConstraint* cnst_new = new WorldQuatConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldQuatConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldQuatConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::Point2PointDistanceConstraintType:
{
Point2PointDistanceConstraint* cnst = (Point2PointDistanceConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
Point2PointDistanceConstraint* cnst_new = new Point2PointDistanceConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"Point2PointDistanceConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","Point2PointDistanceConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::Point2LineSegDistConstraintType:
{
Point2LineSegDistConstraint* cnst = (Point2LineSegDistConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
Point2LineSegDistConstraint* cnst_new = new Point2LineSegDistConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"Point2LineSegDistConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","Point2LineSegDistConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldFixedPositionConstraintType:
{
WorldFixedPositionConstraint* cnst = (WorldFixedPositionConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldFixedPositionConstraint* cnst_new = new WorldFixedPositionConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldFixedPositionConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldFixedPositionConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldFixedOrientConstraintType:
{
WorldFixedOrientConstraint* cnst = (WorldFixedOrientConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldFixedOrientConstraint* cnst_new = new WorldFixedOrientConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldFixedOrientConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldFixedOrientConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::WorldFixedBodyPoseConstraintType:
{
WorldFixedBodyPoseConstraint* cnst = (WorldFixedBodyPoseConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
WorldFixedBodyPoseConstraint* cnst_new = new WorldFixedBodyPoseConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"WorldFixedBodyPoseConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","WorldFixedBodyPoseConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::RelativePositionConstraintType:
{
RelativePositionConstraint* cnst = static_cast<RelativePositionConstraint*>(constraint);
if(field_str == "robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
RelativePositionConstraint* cnst_new = new RelativePositionConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"RelativePositionConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","RelativePositionConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::RelativeQuatConstraintType:
{
RelativeQuatConstraint* cnst = static_cast<RelativeQuatConstraint*>(constraint);
if(field_str == "robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
RelativeQuatConstraint* cnst_new = new RelativeQuatConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*)cnst_new,"RelativeQuatConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","RelativeQuatConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::MinDistanceConstraintType:
{
MinDistanceConstraint* cnst = (MinDistanceConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
MinDistanceConstraint* cnst_new = new MinDistanceConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"MinDistanceConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","MinDistanceConstraint:argument 2 is not accepted");
}
}
break;
case RigidBodyConstraint::GravityCompensationTorqueConstraintType:
{
GravityCompensationTorqueConstraint* cnst = (GravityCompensationTorqueConstraint*) constraint;
if(field_str=="robot")
{
RigidBodyManipulator* robot = (RigidBodyManipulator*) getDrakeMexPointer(prhs[2]);
GravityCompensationTorqueConstraint* cnst_new = new GravityCompensationTorqueConstraint(*cnst);
cnst_new->updateRobot(robot);
plhs[0] = createDrakeConstraintMexPointer((void*) cnst_new,"GravityCompensationTorqueConstraint");
}
else
{
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","GravityCompensationTorqueConstraint:argument 2 is not accepted");
}
}
break;
default:
mexErrMsgIdAndTxt("Drake:updatePtrRigidBodyConstraintmex:BadInputs","Unsupported constraint type");
break;
}
delete[] field;
}
| 44.410417 | 217 | 0.663836 | ericmanzi |
f6a5c9741de6bc6238efa71d1d0ea5f395a11da3 | 382 | hpp | C++ | endscreen.hpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | 6 | 2017-09-15T16:15:03.000Z | 2020-01-09T04:31:26.000Z | endscreen.hpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | null | null | null | endscreen.hpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | 1 | 2017-12-05T05:22:02.000Z | 2017-12-05T05:22:02.000Z | #pragma once
#include "screen.hpp"
class EndScreen : public Screen
{
sf::Sprite &background_sp;
public:
EndScreen(const sf::Font &font, sf::Sprite &background_sp, const sf::Color &fillColor, const sf::Color &outlineColor);
virtual void processEvent(const sf::Event &event);
private:
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};
| 23.875 | 122 | 0.722513 | hckr |
f6a792c580f12c591efe40f0c0b6d102af530cee | 6,230 | cpp | C++ | Ch17_Any/any.cpp | jamcodes/Cpp17CompleteGuide | a21ca5c3f5069b501cd650aa62e5e623bd2c953b | [
"Unlicense"
] | 3 | 2020-10-03T05:51:00.000Z | 2021-08-24T07:45:28.000Z | Ch17_Any/any.cpp | jamcodes/Cpp17CompleteGuide | a21ca5c3f5069b501cd650aa62e5e623bd2c953b | [
"Unlicense"
] | null | null | null | Ch17_Any/any.cpp | jamcodes/Cpp17CompleteGuide | a21ca5c3f5069b501cd650aa62e5e623bd2c953b | [
"Unlicense"
] | null | null | null | #include <any>
#include <complex>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
/**
* C++17 adds `std::any` - a value type that's able to change its type, but while still having
* type safety. std::any accepts an arbitrary type - it holds the contained value and the
* `typeid` of its type - thus there's both a size and a runtime cost, including the possibility
* that std::any might allocate - the implementation should be able to hold small type like int
* without allocating, but larger type (larger than a pointer, two pointers?) will be allocated
* on the heap.
* The underlying type can be checked by comparing against typeid(T),
* value can be accessed via std::any_cast<T>
*/
/*
| Operation | Effect |
| ------------- | ----------------------------------------------------------------- |
| constructors | Create an any object (might call constructor for underlying type) |
| make_any() | Create an any object (passing value(s) to initialize it) |
| destructor | Destroys an any object |
| = | Assign a new value |
| emplace<T>() | Assign a new value having the type T |
| reset() | Destroys any value (makes the object empty) |
| has_value() | Returns whether the object has a value |
| type() | Returns the current type as std::type_info object |
| any_cast<T>() | Use current value as value of type T (exception if other type) |
| swap() | Swaps values between two objects |
*/
int main()
{
// --- construction
// - initialized empty by default, .type() of an empty std::any is equal to typeid(void)
{
std::any a{}; // empty
if (a.type() == typeid(void)) {
std::cerr << "std::any{}.type() == typeid(void)\n";
}
// deduce the type by direct initialization or assignment, deduced type decays
std::any a1{42};
if (a1.type() == typeid(int)) {
std::cerr << "std::any{42}.type() == typeid(int)\n";
}
std::any a2 = "hello any!";
if (a2.type() == typeid(char const*)) {
std::cerr << "std::any{\"hello any!\"} == typeid(char const*)\n";
}
// std::in_place_type can be used for construction, it allows to specify the type
// directly, and avoids copy/move
std::any a3{std::in_place_type<std::string>, "hello any!"};
// note that even the type passed to std::in_place_type decays!
std::any a4{std::in_place_type<char const[6]>, "Hello"};
if (a4.type() == typeid(char const*)) {
std::cerr << "std::any{std::in_place_type<char const[6]>{'hello'} == typeid(char "
"const*) -> decays!\n";
}
// std::make_any - always have to specify the type, also decays
auto a5 = std::make_any<long>(42);
auto a6 = std::make_any<std::string>("hello make_any!");
}
// --- assignment
// values can be assigned using operator=() or .emplace<T>
{
std::any a{};
a = 42; // .type() == typeid(int)
// .emplace()
a.emplace<std::string>("hello emplace");
if (a.type() == typeid(std::string)) {
std::cerr << "a.emplace<std::string> -> value == "
<< std::any_cast<std::string const&>(a) << "\n";
}
// .reset() - makes the std::any empty
a.reset();
if (a.type() == typeid(void)) {
std::cerr << "std::any empty after .reset() -> .type() == typeid(void)\n";
}
}
// --- value access
// check if holds a value using .has_value()
// check type of value using .type() -> std::type_info -> compare against typeid(T)
// access using std::any_cast<T> -> throws std::bad_any_cast if doesn't hold a value
// of the requested type. Can cast to references or pointers
{
std::any a{42};
// casting to an unqualified type, returns by value - copy
auto i = std::any_cast<int>(a);
std::cerr << "std::any holds an int value = " << i << "\n";
a.emplace<std::string>("Hello any_cast");
// we might want to avoid a copy by casting to a const&:
auto const& scr = std::any_cast<std::string const&>(a);
std::cerr << "std::any_cast<std::string const&>(a) = " << scr << "\n";
// casting to a non-const allows us to assign to the value held:
std::any_cast<std::string&>(a) = "Update using any_cast";
std::cerr << "std::any after update, value = " << std::any_cast<std::string const&>(a)
<< "\n";
// We can also move assign the same way
std::string s{"move assign using any_cast"};
std::any_cast<std::string&>(a) = std::move(s);
// using std::any_cast on a pointer to std::any returns a pointer to the held value,
// if the actual type matches the requested type, or nullptr if it doesn't
// this might be a convenient option instead of explicitly checking .type()
// Cast to type `T` when using this from,
// attempting to cast to `T*` will result in the implementation assuming that you're
// expecting the held type to be `T*` (and not `T`)
// attempting to cast to `T&` is an error
auto pi = std::any_cast<int>(&a); // returns nullptr, would throw if used on ref to any
auto ps = std::any_cast<std::string const>(&a); // returns pointer to std::string
if (pi != nullptr ){
std::cerr << "std::any_cast<int>(&a) returned a valid pointer, value = " << *pi << "\n";
}
else {
std::cerr << "std::any_cast<int>(&a) returned a nullptr\n";
}
if (ps != nullptr) {
std::cerr << "std::any_cast<std::string>(&a) returned a valid pointer, value = "
<< *ps << "\n";
}
else {
std::cerr << "std::any_cast<std::string>(&a) returned a nullptr\n";
}
}
}
| 47.557252 | 100 | 0.539165 | jamcodes |
f6a7a9f29c01577d793fcdde80895ee9b923d939 | 2,294 | hpp | C++ | src/proteus/buffers/vart_tensor_buffer.hpp | Xilinx/inference-server | 7477b7dc420ce4cd0d7e1d9914b71898e97d6814 | [
"Apache-2.0"
] | 4 | 2021-11-03T21:32:55.000Z | 2022-02-17T17:13:16.000Z | src/proteus/buffers/vart_tensor_buffer.hpp | Xilinx/inference-server | 7477b7dc420ce4cd0d7e1d9914b71898e97d6814 | [
"Apache-2.0"
] | null | null | null | src/proteus/buffers/vart_tensor_buffer.hpp | Xilinx/inference-server | 7477b7dc420ce4cd0d7e1d9914b71898e97d6814 | [
"Apache-2.0"
] | 2 | 2022-03-05T20:01:33.000Z | 2022-03-25T06:00:35.000Z | // Copyright 2021 Xilinx Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file
* @brief Defines the VartTensorBuffer class
*/
#ifndef GUARD_PROTEUS_BUFFERS_VART_TENSOR_BUFFER
#define GUARD_PROTEUS_BUFFERS_VART_TENSOR_BUFFER
#include <stddef.h> // for size_t
#include <cstdint> // for int32_t
#include <memory> // for unique_ptr
#include <string> // for string
#include <vart/experimental/runner_helper.hpp> // for CpuFlatTensorBufferOwned
#include <vector> // for vector
#include <xir/tensor/tensor.hpp> // for Tensor
#include <xir/util/data_type.hpp> // for DataType
#include "proteus/buffers/buffer.hpp"
namespace vart {
class TensorBuffer;
}
namespace proteus {
/**
* @brief VartTensorBuffer uses vart::CpuFlatTensorBufferOwned for storing data
*
*/
class VartTensorBuffer : public Buffer {
public:
VartTensorBuffer(const std::string& name, std::vector<int32_t>& shape,
xir::DataType data_type);
VartTensorBuffer(const char* name, std::vector<int32_t>& shape,
xir::DataType data_type);
/**
* @brief Returns a pointer to the underlying data.
*
* @param index Used to index to the correct tensor in the batch
*
* @return void*
*/
void* data(size_t offset) override;
/**
* @brief Perform any cleanup before returning the buffer to the pool
*/
void reset() override;
/// Get a pointer to the underlying TensorBuffer
vart::TensorBuffer* getTensorBuffer();
private:
std::unique_ptr<xir::Tensor> tensor_;
vart::CpuFlatTensorBufferOwned data_;
};
} // namespace proteus
#endif // GUARD_PROTEUS_BUFFERS_VART_TENSOR_BUFFER
| 29.792208 | 79 | 0.674804 | Xilinx |
f6a84b44170f6780b060af9af546b2d1281bc8f0 | 39,046 | cpp | C++ | lldb/source/API/SBFrame.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | lldb/source/API/SBFrame.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | lldb/source/API/SBFrame.cpp | ornata/llvm-project | 494913b8b4e4bce0b3525e5569d8e486e82b9a52 | [
"Apache-2.0"
] | null | null | null | //===-- SBFrame.cpp -------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <algorithm>
#include <set>
#include <string>
#include "lldb/API/SBFrame.h"
#include "lldb/lldb-types.h"
#include "Utils.h"
#include "lldb/Core/Address.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/StructuredDataImpl.h"
#include "lldb/Core/ValueObjectRegister.h"
#include "lldb/Core/ValueObjectVariable.h"
#include "lldb/Expression/ExpressionVariable.h"
#include "lldb/Expression/UserExpression.h"
#include "lldb/Host/Host.h"
#include "lldb/Symbol/Block.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Symbol/Variable.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/StackFrameRecognizer.h"
#include "lldb/Target/StackID.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Instrumentation.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Stream.h"
#include "lldb/API/SBAddress.h"
#include "lldb/API/SBDebugger.h"
#include "lldb/API/SBExpressionOptions.h"
#include "lldb/API/SBStream.h"
#include "lldb/API/SBStructuredData.h"
#include "lldb/API/SBSymbolContext.h"
#include "lldb/API/SBThread.h"
#include "lldb/API/SBValue.h"
#include "lldb/API/SBVariablesOptions.h"
#include "llvm/Support/PrettyStackTrace.h"
// BEGIN SWIFT
#include "lldb/Target/LanguageRuntime.h"
#ifdef LLDB_ENABLE_SWIFT
#include "Plugins/LanguageRuntime/Swift/SwiftLanguageRuntime.h"
#endif
// END SWIFT
using namespace lldb;
using namespace lldb_private;
SBFrame::SBFrame() : m_opaque_sp(new ExecutionContextRef()) {
LLDB_INSTRUMENT_VA(this);
}
SBFrame::SBFrame(const StackFrameSP &lldb_object_sp)
: m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) {
LLDB_INSTRUMENT_VA(this, lldb_object_sp);
}
SBFrame::SBFrame(const SBFrame &rhs) {
LLDB_INSTRUMENT_VA(this, rhs);
m_opaque_sp = clone(rhs.m_opaque_sp);
}
SBFrame::~SBFrame() = default;
const SBFrame &SBFrame::operator=(const SBFrame &rhs) {
LLDB_INSTRUMENT_VA(this, rhs);
if (this != &rhs)
m_opaque_sp = clone(rhs.m_opaque_sp);
return *this;
}
StackFrameSP SBFrame::GetFrameSP() const {
return (m_opaque_sp ? m_opaque_sp->GetFrameSP() : StackFrameSP());
}
void SBFrame::SetFrameSP(const StackFrameSP &lldb_object_sp) {
return m_opaque_sp->SetFrameSP(lldb_object_sp);
}
bool SBFrame::IsValid() const {
LLDB_INSTRUMENT_VA(this);
return this->operator bool();
}
SBFrame::operator bool() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock()))
return GetFrameSP().get() != nullptr;
}
// Without a target & process we can't have a valid stack frame.
return false;
}
SBSymbolContext SBFrame::GetSymbolContext(uint32_t resolve_scope) const {
LLDB_INSTRUMENT_VA(this, resolve_scope);
SBSymbolContext sb_sym_ctx;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
if (StackFrame *frame = exe_ctx.GetFramePtr())
sb_sym_ctx = frame->GetSymbolContext(scope);
}
}
return sb_sym_ctx;
}
SBModule SBFrame::GetModule() const {
LLDB_INSTRUMENT_VA(this);
SBModule sb_module;
ModuleSP module_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
module_sp = frame->GetSymbolContext(eSymbolContextModule).module_sp;
sb_module.SetSP(module_sp);
}
}
}
return sb_module;
}
SBCompileUnit SBFrame::GetCompileUnit() const {
LLDB_INSTRUMENT_VA(this);
SBCompileUnit sb_comp_unit;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
sb_comp_unit.reset(
frame->GetSymbolContext(eSymbolContextCompUnit).comp_unit);
}
}
}
return sb_comp_unit;
}
SBFunction SBFrame::GetFunction() const {
LLDB_INSTRUMENT_VA(this);
SBFunction sb_function;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
sb_function.reset(
frame->GetSymbolContext(eSymbolContextFunction).function);
}
}
}
return sb_function;
}
SBSymbol SBFrame::GetSymbol() const {
LLDB_INSTRUMENT_VA(this);
SBSymbol sb_symbol;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
sb_symbol.reset(frame->GetSymbolContext(eSymbolContextSymbol).symbol);
}
}
}
return sb_symbol;
}
SBBlock SBFrame::GetBlock() const {
LLDB_INSTRUMENT_VA(this);
SBBlock sb_block;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame)
sb_block.SetPtr(frame->GetSymbolContext(eSymbolContextBlock).block);
}
}
return sb_block;
}
SBBlock SBFrame::GetFrameBlock() const {
LLDB_INSTRUMENT_VA(this);
SBBlock sb_block;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame)
sb_block.SetPtr(frame->GetFrameBlock());
}
}
return sb_block;
}
SBLineEntry SBFrame::GetLineEntry() const {
LLDB_INSTRUMENT_VA(this);
SBLineEntry sb_line_entry;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
sb_line_entry.SetLineEntry(
frame->GetSymbolContext(eSymbolContextLineEntry).line_entry);
}
}
}
return sb_line_entry;
}
uint32_t SBFrame::GetFrameID() const {
LLDB_INSTRUMENT_VA(this);
uint32_t frame_idx = UINT32_MAX;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
if (frame)
frame_idx = frame->GetFrameIndex();
return frame_idx;
}
lldb::addr_t SBFrame::GetCFA() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
if (frame)
return frame->GetStackID().GetCallFrameAddress();
return LLDB_INVALID_ADDRESS;
}
addr_t SBFrame::GetPC() const {
LLDB_INSTRUMENT_VA(this);
addr_t addr = LLDB_INVALID_ADDRESS;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
addr = frame->GetFrameCodeAddress().GetOpcodeLoadAddress(
target, AddressClass::eCode);
}
}
}
return addr;
}
bool SBFrame::SetPC(addr_t new_pc) {
LLDB_INSTRUMENT_VA(this, new_pc);
bool ret_val = false;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
if (StackFrame *frame = exe_ctx.GetFramePtr()) {
if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) {
ret_val = reg_ctx_sp->SetPC(new_pc);
}
}
}
}
return ret_val;
}
addr_t SBFrame::GetSP() const {
LLDB_INSTRUMENT_VA(this);
addr_t addr = LLDB_INVALID_ADDRESS;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
if (StackFrame *frame = exe_ctx.GetFramePtr()) {
if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) {
addr = reg_ctx_sp->GetSP();
}
}
}
}
return addr;
}
addr_t SBFrame::GetFP() const {
LLDB_INSTRUMENT_VA(this);
addr_t addr = LLDB_INVALID_ADDRESS;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
if (StackFrame *frame = exe_ctx.GetFramePtr()) {
if (RegisterContextSP reg_ctx_sp = frame->GetRegisterContext()) {
addr = reg_ctx_sp->GetFP();
}
}
}
}
return addr;
}
SBAddress SBFrame::GetPCAddress() const {
LLDB_INSTRUMENT_VA(this);
SBAddress sb_addr;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame)
sb_addr.SetAddress(frame->GetFrameCodeAddress());
}
}
return sb_addr;
}
void SBFrame::Clear() {
LLDB_INSTRUMENT_VA(this);
m_opaque_sp->Clear();
}
lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path) {
LLDB_INSTRUMENT_VA(this, var_path);
SBValue sb_value;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
lldb::DynamicValueType use_dynamic =
frame->CalculateTarget()->GetPreferDynamicValue();
sb_value = GetValueForVariablePath(var_path, use_dynamic);
}
return sb_value;
}
lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path,
DynamicValueType use_dynamic) {
LLDB_INSTRUMENT_VA(this, var_path, use_dynamic);
SBValue sb_value;
if (var_path == nullptr || var_path[0] == '\0') {
return sb_value;
}
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
VariableSP var_sp;
Status error;
ValueObjectSP value_sp(frame->GetValueForVariableExpressionPath(
var_path, eNoDynamicValues,
StackFrame::eExpressionPathOptionCheckPtrVsMember |
StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
var_sp, error));
sb_value.SetSP(value_sp, use_dynamic);
}
}
}
return sb_value;
}
SBValue SBFrame::FindVariable(const char *name) {
LLDB_INSTRUMENT_VA(this, name);
SBValue value;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
lldb::DynamicValueType use_dynamic =
frame->CalculateTarget()->GetPreferDynamicValue();
value = FindVariable(name, use_dynamic);
}
return value;
}
SBValue SBFrame::FindVariable(const char *name,
lldb::DynamicValueType use_dynamic) {
LLDB_INSTRUMENT_VA(this, name, use_dynamic);
VariableSP var_sp;
SBValue sb_value;
if (name == nullptr || name[0] == '\0') {
return sb_value;
}
ValueObjectSP value_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
value_sp = frame->FindVariable(ConstString(name));
if (value_sp)
sb_value.SetSP(value_sp, use_dynamic);
}
}
}
return sb_value;
}
SBValue SBFrame::FindValue(const char *name, ValueType value_type) {
LLDB_INSTRUMENT_VA(this, name, value_type);
SBValue value;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
lldb::DynamicValueType use_dynamic =
frame->CalculateTarget()->GetPreferDynamicValue();
value = FindValue(name, value_type, use_dynamic);
}
return value;
}
SBValue SBFrame::FindValue(const char *name, ValueType value_type,
lldb::DynamicValueType use_dynamic) {
LLDB_INSTRUMENT_VA(this, name, value_type, use_dynamic);
SBValue sb_value;
if (name == nullptr || name[0] == '\0') {
return sb_value;
}
ValueObjectSP value_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
VariableList variable_list;
switch (value_type) {
case eValueTypeVariableGlobal: // global variable
case eValueTypeVariableStatic: // static variable
case eValueTypeVariableArgument: // function argument variables
case eValueTypeVariableLocal: // function local variables
case eValueTypeVariableThreadLocal: // thread local variables
{
SymbolContext sc(frame->GetSymbolContext(eSymbolContextBlock));
const bool can_create = true;
const bool get_parent_variables = true;
const bool stop_if_block_is_inlined_function = true;
if (sc.block)
sc.block->AppendVariables(
can_create, get_parent_variables,
stop_if_block_is_inlined_function,
[frame](Variable *v) { return v->IsInScope(frame); },
&variable_list);
if (value_type == eValueTypeVariableGlobal) {
const bool get_file_globals = true;
VariableList *frame_vars = frame->GetVariableList(get_file_globals);
if (frame_vars)
frame_vars->AppendVariablesIfUnique(variable_list);
}
ConstString const_name(name);
VariableSP variable_sp(
variable_list.FindVariable(const_name, value_type));
if (variable_sp) {
value_sp = frame->GetValueObjectForFrameVariable(variable_sp,
eNoDynamicValues);
sb_value.SetSP(value_sp, use_dynamic);
}
} break;
case eValueTypeRegister: // stack frame register value
{
RegisterContextSP reg_ctx(frame->GetRegisterContext());
if (reg_ctx) {
if (const RegisterInfo *reg_info =
reg_ctx->GetRegisterInfoByName(name)) {
value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_info);
sb_value.SetSP(value_sp);
}
}
} break;
case eValueTypeRegisterSet: // A collection of stack frame register
// values
{
RegisterContextSP reg_ctx(frame->GetRegisterContext());
if (reg_ctx) {
const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) {
const RegisterSet *reg_set = reg_ctx->GetRegisterSet(set_idx);
if (reg_set &&
(llvm::StringRef(reg_set->name).equals_insensitive(name) ||
llvm::StringRef(reg_set->short_name)
.equals_insensitive(name))) {
value_sp =
ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx);
sb_value.SetSP(value_sp);
break;
}
}
}
} break;
case eValueTypeConstResult: // constant result variables
{
ConstString const_name(name);
ExpressionVariableSP expr_var_sp(
target->GetPersistentVariable(const_name));
if (expr_var_sp) {
value_sp = expr_var_sp->GetValueObject();
sb_value.SetSP(value_sp, use_dynamic);
}
} break;
default:
break;
}
}
}
}
return sb_value;
}
bool SBFrame::IsEqual(const SBFrame &that) const {
LLDB_INSTRUMENT_VA(this, that);
lldb::StackFrameSP this_sp = GetFrameSP();
lldb::StackFrameSP that_sp = that.GetFrameSP();
return (this_sp && that_sp && this_sp->GetStackID() == that_sp->GetStackID());
}
bool SBFrame::operator==(const SBFrame &rhs) const {
LLDB_INSTRUMENT_VA(this, rhs);
return IsEqual(rhs);
}
bool SBFrame::operator!=(const SBFrame &rhs) const {
LLDB_INSTRUMENT_VA(this, rhs);
return !IsEqual(rhs);
}
SBThread SBFrame::GetThread() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
ThreadSP thread_sp(exe_ctx.GetThreadSP());
SBThread sb_thread(thread_sp);
return sb_thread;
}
const char *SBFrame::Disassemble() const {
LLDB_INSTRUMENT_VA(this);
const char *disassembly = nullptr;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
disassembly = frame->Disassemble();
}
}
}
return disassembly;
}
SBValueList SBFrame::GetVariables(bool arguments, bool locals, bool statics,
bool in_scope_only) {
LLDB_INSTRUMENT_VA(this, arguments, locals, statics, in_scope_only);
SBValueList value_list;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
lldb::DynamicValueType use_dynamic =
frame->CalculateTarget()->GetPreferDynamicValue();
const bool include_runtime_support_values =
target ? target->GetDisplayRuntimeSupportValues() : false;
SBVariablesOptions options;
options.SetIncludeArguments(arguments);
options.SetIncludeLocals(locals);
options.SetIncludeStatics(statics);
options.SetInScopeOnly(in_scope_only);
options.SetIncludeRuntimeSupportValues(include_runtime_support_values);
options.SetUseDynamic(use_dynamic);
value_list = GetVariables(options);
}
return value_list;
}
lldb::SBValueList SBFrame::GetVariables(bool arguments, bool locals,
bool statics, bool in_scope_only,
lldb::DynamicValueType use_dynamic) {
LLDB_INSTRUMENT_VA(this, arguments, locals, statics, in_scope_only,
use_dynamic);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
Target *target = exe_ctx.GetTargetPtr();
const bool include_runtime_support_values =
target ? target->GetDisplayRuntimeSupportValues() : false;
SBVariablesOptions options;
options.SetIncludeArguments(arguments);
options.SetIncludeLocals(locals);
options.SetIncludeStatics(statics);
options.SetInScopeOnly(in_scope_only);
options.SetIncludeRuntimeSupportValues(include_runtime_support_values);
options.SetUseDynamic(use_dynamic);
return GetVariables(options);
}
SBValueList SBFrame::GetVariables(const lldb::SBVariablesOptions &options) {
LLDB_INSTRUMENT_VA(this, options);
SBValueList value_list;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
const bool statics = options.GetIncludeStatics();
const bool arguments = options.GetIncludeArguments();
const bool recognized_arguments =
options.GetIncludeRecognizedArguments(SBTarget(exe_ctx.GetTargetSP()));
const bool locals = options.GetIncludeLocals();
const bool in_scope_only = options.GetInScopeOnly();
const bool include_runtime_support_values =
options.GetIncludeRuntimeSupportValues();
const lldb::DynamicValueType use_dynamic = options.GetUseDynamic();
std::set<VariableSP> variable_set;
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
VariableList *variable_list = nullptr;
variable_list = frame->GetVariableList(true);
if (variable_list) {
const size_t num_variables = variable_list->GetSize();
if (num_variables) {
for (const VariableSP &variable_sp : *variable_list) {
if (variable_sp) {
bool add_variable = false;
switch (variable_sp->GetScope()) {
case eValueTypeVariableGlobal:
case eValueTypeVariableStatic:
case eValueTypeVariableThreadLocal:
add_variable = statics;
break;
case eValueTypeVariableArgument:
add_variable = arguments;
break;
case eValueTypeVariableLocal:
add_variable = locals;
break;
default:
break;
}
if (add_variable) {
// Only add variables once so we don't end up with duplicates
if (variable_set.find(variable_sp) == variable_set.end())
variable_set.insert(variable_sp);
else
continue;
if (in_scope_only && !variable_sp->IsInScope(frame))
continue;
ValueObjectSP valobj_sp(frame->GetValueObjectForFrameVariable(
variable_sp, eNoDynamicValues));
if (!include_runtime_support_values && valobj_sp != nullptr &&
valobj_sp->IsRuntimeSupportValue())
continue;
SBValue value_sb;
value_sb.SetSP(valobj_sp, use_dynamic);
value_list.Append(value_sb);
}
}
}
}
}
if (recognized_arguments) {
auto recognized_frame = frame->GetRecognizedFrame();
if (recognized_frame) {
ValueObjectListSP recognized_arg_list =
recognized_frame->GetRecognizedArguments();
if (recognized_arg_list) {
for (auto &rec_value_sp : recognized_arg_list->GetObjects()) {
SBValue value_sb;
value_sb.SetSP(rec_value_sp, use_dynamic);
value_list.Append(value_sb);
}
}
}
}
}
}
}
return value_list;
}
SBValueList SBFrame::GetRegisters() {
LLDB_INSTRUMENT_VA(this);
SBValueList value_list;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
RegisterContextSP reg_ctx(frame->GetRegisterContext());
if (reg_ctx) {
const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) {
value_list.Append(
ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx));
}
}
}
}
}
return value_list;
}
SBValue SBFrame::FindRegister(const char *name) {
LLDB_INSTRUMENT_VA(this, name);
SBValue result;
ValueObjectSP value_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
RegisterContextSP reg_ctx(frame->GetRegisterContext());
if (reg_ctx) {
if (const RegisterInfo *reg_info =
reg_ctx->GetRegisterInfoByName(name)) {
value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_info);
result.SetSP(value_sp);
}
}
}
}
}
return result;
}
bool SBFrame::GetDescription(SBStream &description) {
LLDB_INSTRUMENT_VA(this, description);
Stream &strm = description.ref();
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
frame->DumpUsingSettingsFormat(&strm);
}
}
} else
strm.PutCString("No value");
return true;
}
SBValue SBFrame::EvaluateExpression(const char *expr) {
LLDB_INSTRUMENT_VA(this, expr);
SBValue result;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (frame && target) {
SBExpressionOptions options;
lldb::DynamicValueType fetch_dynamic_value =
frame->CalculateTarget()->GetPreferDynamicValue();
options.SetFetchDynamicValue(fetch_dynamic_value);
options.SetUnwindOnError(true);
options.SetIgnoreBreakpoints(true);
if (target->GetLanguage() != eLanguageTypeUnknown)
options.SetLanguage(target->GetLanguage());
else
options.SetLanguage(frame->GetLanguage());
return EvaluateExpression(expr, options);
}
return result;
}
SBValue
SBFrame::EvaluateExpression(const char *expr,
lldb::DynamicValueType fetch_dynamic_value) {
LLDB_INSTRUMENT_VA(this, expr, fetch_dynamic_value);
SBExpressionOptions options;
options.SetFetchDynamicValue(fetch_dynamic_value);
options.SetUnwindOnError(true);
options.SetIgnoreBreakpoints(true);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (target && target->GetLanguage() != eLanguageTypeUnknown)
options.SetLanguage(target->GetLanguage());
else if (frame)
options.SetLanguage(frame->GetLanguage());
return EvaluateExpression(expr, options);
}
SBValue SBFrame::EvaluateExpression(const char *expr,
lldb::DynamicValueType fetch_dynamic_value,
bool unwind_on_error) {
LLDB_INSTRUMENT_VA(this, expr, fetch_dynamic_value, unwind_on_error);
SBExpressionOptions options;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
options.SetFetchDynamicValue(fetch_dynamic_value);
options.SetUnwindOnError(unwind_on_error);
options.SetIgnoreBreakpoints(true);
StackFrame *frame = exe_ctx.GetFramePtr();
Target *target = exe_ctx.GetTargetPtr();
if (target && target->GetLanguage() != eLanguageTypeUnknown)
options.SetLanguage(target->GetLanguage());
else if (frame)
options.SetLanguage(frame->GetLanguage());
return EvaluateExpression(expr, options);
}
lldb::SBValue SBFrame::EvaluateExpression(const char *expr,
const SBExpressionOptions &options) {
LLDB_INSTRUMENT_VA(this, expr, options);
Log *expr_log = GetLog(LLDBLog::Expressions);
SBValue expr_result;
if (expr == nullptr || expr[0] == '\0') {
return expr_result;
}
ValueObjectSP expr_value_sp;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
std::unique_ptr<llvm::PrettyStackTraceFormat> stack_trace;
if (target->GetDisplayExpressionsInCrashlogs()) {
StreamString frame_description;
frame->DumpUsingSettingsFormat(&frame_description);
stack_trace = std::make_unique<llvm::PrettyStackTraceFormat>(
"SBFrame::EvaluateExpression (expr = \"%s\", fetch_dynamic_value "
"= %u) %s",
expr, options.GetFetchDynamicValue(),
frame_description.GetData());
}
target->EvaluateExpression(expr, frame, expr_value_sp, options.ref());
expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue());
}
}
}
LLDB_LOGF(expr_log,
"** [SBFrame::EvaluateExpression] Expression result is "
"%s, summary %s **",
expr_result.GetValue(), expr_result.GetSummary());
return expr_result;
}
bool SBFrame::IsInlined() {
LLDB_INSTRUMENT_VA(this);
return static_cast<const SBFrame *>(this)->IsInlined();
}
bool SBFrame::IsInlined() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
if (block)
return block->GetContainingInlinedBlock() != nullptr;
}
}
}
return false;
}
bool SBFrame::IsArtificial() {
LLDB_INSTRUMENT_VA(this);
return static_cast<const SBFrame *>(this)->IsArtificial();
}
bool SBFrame::IsArtificial() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = exe_ctx.GetFramePtr();
if (frame)
return frame->IsArtificial();
return false;
}
const char *SBFrame::GetFunctionName() {
LLDB_INSTRUMENT_VA(this);
return static_cast<const SBFrame *>(this)->GetFunctionName();
}
lldb::LanguageType SBFrame::GuessLanguage() const {
LLDB_INSTRUMENT_VA(this);
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
return frame->GuessLanguage();
}
}
}
return eLanguageTypeUnknown;
}
lldb::SBStructuredData SBFrame::GetLanguageSpecificData() const {
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
auto *process = exe_ctx.GetProcessPtr();
auto *frame = exe_ctx.GetFramePtr();
if (process && frame)
if (auto *runtime = process->GetLanguageRuntime(frame->GuessLanguage()))
if (auto *data = runtime->GetLanguageSpecificData(*frame))
return SBStructuredData(*data);
return {};
}
// BEGIN SWIFT
bool SBFrame::IsSwiftThunk() const {
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (!target || !process)
return false;
Process::StopLocker stop_locker;
if (!stop_locker.TryLock(&process->GetRunLock()))
return false;
frame = exe_ctx.GetFramePtr();
if (!frame)
return false;
SymbolContext sc;
sc = frame->GetSymbolContext(eSymbolContextSymbol);
if (!sc.symbol)
return false;
auto *runtime = process->GetLanguageRuntime(eLanguageTypeSwift);
if (!runtime)
return false;
return runtime->IsSymbolARuntimeThunk(*sc.symbol);
}
// END SWIFT
const char *SBFrame::GetFunctionName() const {
LLDB_INSTRUMENT_VA(this);
const char *name = nullptr;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction |
eSymbolContextBlock |
eSymbolContextSymbol));
if (sc.block) {
Block *inlined_block = sc.block->GetContainingInlinedBlock();
if (inlined_block) {
const InlineFunctionInfo *inlined_info =
inlined_block->GetInlinedFunctionInfo();
name = inlined_info->GetName().AsCString();
}
}
if (name == nullptr) {
if (sc.function)
name = sc.function->GetName().GetCString();
}
if (name == nullptr) {
if (sc.symbol)
name = sc.symbol->GetName().GetCString();
}
}
}
}
return name;
}
const char *SBFrame::GetDisplayFunctionName() {
LLDB_INSTRUMENT_VA(this);
const char *name = nullptr;
std::unique_lock<std::recursive_mutex> lock;
ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
StackFrame *frame = nullptr;
Target *target = exe_ctx.GetTargetPtr();
Process *process = exe_ctx.GetProcessPtr();
if (target && process) {
Process::StopLocker stop_locker;
if (stop_locker.TryLock(&process->GetRunLock())) {
frame = exe_ctx.GetFramePtr();
if (frame) {
SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction |
eSymbolContextBlock |
eSymbolContextSymbol));
if (sc.block) {
Block *inlined_block = sc.block->GetContainingInlinedBlock();
if (inlined_block) {
const InlineFunctionInfo *inlined_info =
inlined_block->GetInlinedFunctionInfo();
name = inlined_info->GetDisplayName().AsCString();
}
}
if (name == nullptr) {
if (sc.function)
name = sc.function->GetDisplayName().GetCString();
}
if (name == nullptr) {
if (sc.symbol)
name = sc.symbol->GetDisplayName().GetCString();
}
}
}
}
return name;
}
| 30.174652 | 80 | 0.663423 | ornata |
f6a8f77ef303928846e002771b03a2ea9d99d7ba | 3,964 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.WaitHandle.SignalAndWait/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.WaitHandle.SignalAndWait/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.WaitHandle.SignalAndWait/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z | //<Snippet1>
using namespace System;
using namespace System::Threading;
public ref class Example
{
private:
// The EventWaitHandle used to demonstrate the difference
// between AutoReset and ManualReset synchronization events.
//
static EventWaitHandle^ ewh;
// A counter to make sure all threads are started and
// blocked before any are released. A Long is used to show
// the use of the 64-bit Interlocked methods.
//
static __int64 threadCount = 0;
// An AutoReset event that allows the main thread to block
// until an exiting thread has decremented the count.
//
static EventWaitHandle^ clearCount =
gcnew EventWaitHandle( false,EventResetMode::AutoReset );
public:
[MTAThread]
static void main()
{
// Create an AutoReset EventWaitHandle.
//
ewh = gcnew EventWaitHandle( false,EventResetMode::AutoReset );
// Create and start five numbered threads. Use the
// ParameterizedThreadStart delegate, so the thread
// number can be passed as an argument to the Start
// method.
for ( int i = 0; i <= 4; i++ )
{
Thread^ t = gcnew Thread(
gcnew ParameterizedThreadStart( ThreadProc ) );
t->Start( i );
}
// Wait until all the threads have started and blocked.
// When multiple threads use a 64-bit value on a 32-bit
// system, you must access the value through the
// Interlocked class to guarantee thread safety.
//
while ( Interlocked::Read( threadCount ) < 5 )
{
Thread::Sleep( 500 );
}
// Release one thread each time the user presses ENTER,
// until all threads have been released.
//
while ( Interlocked::Read( threadCount ) > 0 )
{
Console::WriteLine( L"Press ENTER to release a waiting thread." );
Console::ReadLine();
// SignalAndWait signals the EventWaitHandle, which
// releases exactly one thread before resetting,
// because it was created with AutoReset mode.
// SignalAndWait then blocks on clearCount, to
// allow the signaled thread to decrement the count
// before looping again.
//
WaitHandle::SignalAndWait( ewh, clearCount );
}
Console::WriteLine();
// Create a ManualReset EventWaitHandle.
//
ewh = gcnew EventWaitHandle( false,EventResetMode::ManualReset );
// Create and start five more numbered threads.
//
for ( int i = 0; i <= 4; i++ )
{
Thread^ t = gcnew Thread(
gcnew ParameterizedThreadStart( ThreadProc ) );
t->Start( i );
}
// Wait until all the threads have started and blocked.
//
while ( Interlocked::Read( threadCount ) < 5 )
{
Thread::Sleep( 500 );
}
// Because the EventWaitHandle was created with
// ManualReset mode, signaling it releases all the
// waiting threads.
//
Console::WriteLine( L"Press ENTER to release the waiting threads." );
Console::ReadLine();
ewh->Set();
}
static void ThreadProc( Object^ data )
{
int index = static_cast<Int32>(data);
Console::WriteLine( L"Thread {0} blocks.", data );
// Increment the count of blocked threads.
Interlocked::Increment( threadCount );
// Wait on the EventWaitHandle.
ewh->WaitOne();
Console::WriteLine( L"Thread {0} exits.", data );
// Decrement the count of blocked threads.
Interlocked::Decrement( threadCount );
// After signaling ewh, the main thread blocks on
// clearCount until the signaled thread has
// decremented the count. Signal it now.
//
clearCount->Set();
}
};
//</Snippet1>
| 31.460317 | 76 | 0.590565 | hamarb123 |
f6a91aac49d8a5f1f2484a3b929887c3fbab30fb | 9,874 | cpp | C++ | src/postprocess/buildex/trees/src/comp_abs_tree.cpp | Baltoli/He-2 | c3b20da61d8e0d4878e530fe26affa2ec4a4e717 | [
"MIT"
] | null | null | null | src/postprocess/buildex/trees/src/comp_abs_tree.cpp | Baltoli/He-2 | c3b20da61d8e0d4878e530fe26affa2ec4a4e717 | [
"MIT"
] | null | null | null | src/postprocess/buildex/trees/src/comp_abs_tree.cpp | Baltoli/He-2 | c3b20da61d8e0d4878e530fe26affa2ec4a4e717 | [
"MIT"
] | null | null | null | #include <trees/nodes.h>
#include <trees/trees.h>
#include <analysis/x86_analysis.h>
#include <utility/defines.h>
#include <utility/print_helper.h>
#include <common/utilities.h>
#include <cassert>
#include <fstream>
#include <iostream>
using namespace std;
Comp_Abs_Tree::Comp_Abs_Tree()
: Tree()
{
}
Comp_Abs_Tree::~Comp_Abs_Tree() { }
/* these routines are specific to compound trees which needs traversal of number
of similar trees together. These can be abstracted and lifted to act on
general trees, but as this is the only case we opt to have these specialized
functions
*/
void Comp_Abs_Tree::build_compound_tree_unrolled(
Comp_Abs_Node* comp_node, std::vector<Abs_Node*> abs_nodes)
{
for (int i = 0; i < abs_nodes[0]->srcs.size(); i++) {
vector<Abs_Node*> nodes;
for (int j = 0; j < abs_nodes.size(); j++) {
nodes.push_back(static_cast<Abs_Node*>(abs_nodes[j]->srcs[i]));
}
Comp_Abs_Node* new_node = new Comp_Abs_Node(nodes);
new_node->prev.push_back(comp_node);
new_node->pos.push_back(i);
comp_node->srcs.push_back(new_node);
build_compound_tree_unrolled(new_node, nodes);
}
}
void Comp_Abs_Tree::build_compound_tree_unrolled(
std::vector<Abs_Tree*> abs_trees)
{
if (abs_trees.size() == 0)
return;
vector<Abs_Node*> nodes;
for (int i = 0; i < abs_trees.size(); i++) {
nodes.push_back(static_cast<Abs_Node*>(abs_trees[i]->get_head()));
}
Comp_Abs_Node* comp_node = new Comp_Abs_Node(nodes);
set_head(comp_node);
this->recursive = abs_trees[0]->recursive;
build_compound_tree_unrolled(comp_node, nodes);
}
void Comp_Abs_Tree::traverse_trees(
vector<Abs_Node*> abs_nodes,
vector<pair<vector<Abs_Node*>, vector<int>>>& node_pos)
{
if (abs_nodes.size() == 0)
return;
int order_num = abs_nodes[0]->order_num;
Abs_Node* abs_node = abs_nodes[0];
if (node_pos[order_num].first.size() == 0) {
node_pos[order_num].first = abs_nodes;
for (int i = 0; i < abs_node->srcs.size(); i++) {
node_pos[order_num].second.push_back(abs_node->srcs[i]->order_num);
vector<Abs_Node*> new_srcs;
for (int j = 0; j < abs_nodes.size(); j++) {
new_srcs.push_back(static_cast<Abs_Node*>(abs_nodes[j]->srcs[i]));
}
traverse_trees(new_srcs, node_pos);
}
}
}
void Comp_Abs_Tree::build_compound_tree_exact(std::vector<Abs_Tree*> abs_trees)
{
if (abs_trees.size() == 0)
return;
/* assumption the tree is numbered and the visited state is cleared */
ASSERT_MSG(
(abs_trees[0]->get_head()->order_num != -1),
("ERROR: the concrete tree is not numbered\n"));
ASSERT_MSG(
(abs_trees[0]->get_head()->visited == false),
("ERROR: the visit state of the concrete tree is not cleared\n"));
/* get all the nodes and the nodes to which it is connected */
vector<pair<vector<Abs_Node*>, vector<int>>> tree_map;
tree_map.resize(
abs_trees[0]->num_nodes); /* allocate space for the the nodes */
/* create the set of Abs_Node heads */
vector<Abs_Node*> nodes;
for (int i = 0; i < abs_trees.size(); i++) {
nodes.push_back(static_cast<Abs_Node*>(abs_trees[i]->get_head()));
}
traverse_trees(nodes, tree_map);
/* now create the new tree as a vector */
vector<pair<Comp_Abs_Node*, vector<int>>> new_tree_map;
for (int i = 0; i < new_tree_map.size(); i++) {
new_tree_map.push_back(
make_pair(new Comp_Abs_Node(tree_map[i].first), tree_map[i].second));
}
set_head(new_tree_map[0].first);
/* now create the linkage structure */
for (int i = 0; i < new_tree_map.size(); i++) {
Node* node = new_tree_map[i].first;
vector<int> srcs = new_tree_map[i].second;
for (int j = 0; j < srcs.size(); i++) {
node->srcs.push_back(new_tree_map[srcs[j]].first);
new_tree_map[srcs[j]].first->prev.push_back(node);
new_tree_map[srcs[j]].first->pos.push_back(j);
}
}
}
Comp_Abs_Node* get_indirect_access_node(Comp_Abs_Node* node)
{
if (node->srcs.size() == 0) {
if (node->nodes[0]->mem_info.associated_mem != NULL) {
return node;
} else {
return NULL;
}
}
Comp_Abs_Node* ret;
for (int i = 0; i < node->srcs.size(); i++) {
ret = get_indirect_access_node((Comp_Abs_Node*)node->srcs[i]);
if (ret != NULL)
break;
}
return ret;
}
int32_t is_indirect_access(Comp_Abs_Node* node)
{
int32_t pos = -1;
// is this node indirect?
for (int i = 0; i < node->srcs.size(); i++) {
Comp_Abs_Node* src = (Comp_Abs_Node*)node->srcs[i];
if (src->nodes[0]->operation == op_indirect) {
pos = i;
break;
}
}
return pos;
}
void remove_same_values(bool* deleted_index, vector<vector<double>>& A)
{
deleted_index[A[0].size() - 1] = false;
uint32_t temp_count = 0;
/* check if a particular dimension is the same? */
for (int j = 0; j < A[0].size() - 1; j++) {
bool same = true;
double value = A[0][j];
for (int i = 1; i < A.size(); i++) {
if (abs(value - A[i][j]) > 1e-6) {
same = false;
break;
}
}
/* if same true */
if (same) {
for (int i = 0; i < A.size(); i++) {
A[i].erase(A[i].begin() + j);
}
j--;
}
deleted_index[temp_count++] = same;
}
}
void abstract_buffer_indexes_traversal(Comp_Abs_Node* head, Comp_Abs_Node* node)
{
Abs_Node* first = node->nodes[0];
if (node->visited) {
return;
} else {
node->visited = true;
}
bool indirect = (is_indirect_access(node) != -1);
if (((first->type == Abs_Node::INPUT_NODE)
|| (first->type == Abs_Node::INTERMEDIATE_NODE)
|| (first->type == Abs_Node::OUTPUT_NODE))
&& !indirect) {
/*make a system of linear equations and solve them*/
vector<vector<double>> A;
// for (int i = 0; i < head->nodes.size(); i++){
for (int i = 0; i < node->nodes.size(); i++) {
vector<double> coeff;
for (int j = 0; j < head->nodes[i]->mem_info.dimensions; j++) {
coeff.push_back((double)head->nodes[i]->mem_info.pos[j]);
}
coeff.push_back(1.0);
A.push_back(coeff);
}
printout_matrices(A);
bool* deleted_index = new bool[A[0].size()];
remove_same_values(deleted_index, A);
cout << endl;
printout_matrices(A);
for (int dim = 0; dim < first->mem_info.dimensions; dim++) {
vector<double> b;
// for (int i = 0; i < node->nodes.size(); i++){
for (int i = 0; i < node->nodes.size(); i++) {
b.push_back((double)node->nodes[i]->mem_info.pos[dim]);
}
printout_vector(b);
vector<double> results = solve_linear_eq(A, b);
uint32_t head_dimensions = head->nodes[0]->mem_info.dimensions;
// ASSERT_MSG((results.size() == (first->mem_info.dimensions + 1)),
// ("ERROR: the result vector is inconsistent\n"));
uint32_t tcount = 0;
for (int i = 0; i < head_dimensions + 1; i++) {
if (deleted_index[i] == false) {
first->mem_info.indexes[dim][i] = double_to_int(results[tcount++]);
} else {
first->mem_info.indexes[dim][i] = 0;
}
}
}
} else if (first->type == Abs_Node::IMMEDIATE_INT) {
vector<vector<double>> A;
// for (int i = 0; i < head->nodes.size(); i++){
for (int i = 0; i < node->nodes.size(); i++) {
vector<double> coeff;
for (int j = 0; j < head->nodes[i]->mem_info.dimensions; j++) {
coeff.push_back((double)head->nodes[i]->mem_info.pos[j]);
}
coeff.push_back(1.0);
A.push_back(coeff);
}
// cout << "imm" << endl;
// printout_matrices(A);
bool* deleted_index = new bool[A[0].size()];
remove_same_values(deleted_index, A);
vector<double> b;
first->mem_info.indexes = new int*[1];
first->mem_info.indexes[0]
= new int[head->nodes[0]->mem_info.dimensions + 1];
first->mem_info.dimensions = 1;
first->mem_info.head_dimensions = head->nodes[0]->mem_info.dimensions;
for (int i = 0; i < node->nodes.size(); i++) {
b.push_back((long long)node->nodes[i]->symbol->value);
}
// printout_vector(b);
vector<double> results = solve_linear_eq(A, b);
uint32_t head_dimensions = head->nodes[0]->mem_info.dimensions;
// ASSERT_MSG((results.size() == (first->mem_info.dimensions + 1)), ("ERROR:
// the result vector is inconsistent\n"));
uint32_t tcount = 0;
for (int i = 0; i < head_dimensions + 1; i++) {
if (deleted_index[i] == false) {
first->mem_info.indexes[0][i] = double_to_int(results[tcount++]);
} else {
first->mem_info.indexes[0][i] = 0;
}
}
} else if ((first->type == Abs_Node::SUBTREE_BOUNDARY)) {
return;
}
for (int i = 0; i < node->srcs.size(); i++) {
abstract_buffer_indexes_traversal(
head, static_cast<Comp_Abs_Node*>(node->srcs[i]));
}
}
void Comp_Abs_Tree::abstract_buffer_indexes()
{
Comp_Abs_Node* act_head = static_cast<Comp_Abs_Node*>(get_head());
int32_t pos = is_indirect_access(act_head);
if (pos != -1) {
Comp_Abs_Node* node = static_cast<Comp_Abs_Node*>(act_head->srcs[pos]);
act_head = get_indirect_access_node(node);
DEBUG_PRINT(("indirect head node access\n"), 2);
}
/* assert that the comp node is an input or an intermediate node */
for (int i = 0; i < head->srcs.size(); i++) {
abstract_buffer_indexes_traversal(
act_head, static_cast<Comp_Abs_Node*>(head->srcs[i]));
}
cleanup_visit();
}
Abs_Tree* Comp_Abs_Tree::compound_to_abs_tree()
{
Abs_Node* node = static_cast<Abs_Node*>(
static_cast<Comp_Abs_Node*>(get_head())->nodes[0]);
Abs_Tree* tree = new Abs_Tree();
tree->recursive = recursive;
tree->set_head(node);
return tree;
}
std::string Comp_Abs_Tree::serialize_tree() { throw "not implemented!"; }
void Comp_Abs_Tree::construct_tree(std::string stree)
{
throw "not implemented!";
}
| 27.351801 | 80 | 0.62224 | Baltoli |
f6a952885326d1669197397be784d58e1b05c496 | 2,463 | cpp | C++ | rmw_coredx_cpp/src/rmw_send_response.cpp | rupertholman/rmw_coredx | 1c97655212bfa90b1353f019ae08e8b2c487db8d | [
"Apache-2.0"
] | null | null | null | rmw_coredx_cpp/src/rmw_send_response.cpp | rupertholman/rmw_coredx | 1c97655212bfa90b1353f019ae08e8b2c487db8d | [
"Apache-2.0"
] | null | null | null | rmw_coredx_cpp/src/rmw_send_response.cpp | rupertholman/rmw_coredx | 1c97655212bfa90b1353f019ae08e8b2c487db8d | [
"Apache-2.0"
] | null | null | null | // Copyright 2015 Twin Oaks Computing, Inc.
// Modifications copyright (C) 2017-2018 Twin Oaks Computing, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifdef CoreDX_GLIBCXX_USE_CXX11_ABI_ZERO
#define _GLIBCXX_USE_CXX11_ABI 0
#endif
#include <rmw/rmw.h>
#include <rmw/types.h>
#include <rmw/allocators.h>
#include <rmw/error_handling.h>
#include <rmw/impl/cpp/macros.hpp>
#include <dds/dds.hh>
#include <dds/dds_builtinDataReader.hh>
#include "rmw_coredx_cpp/identifier.hpp"
#include "rmw_coredx_types.hpp"
#include "util.hpp"
#if defined(__cplusplus)
extern "C" {
#endif
/* ************************************************
*/
rmw_ret_t
rmw_send_response( const rmw_service_t * service,
rmw_request_id_t * ros_request_header,
void * ros_response )
{
if (!service) {
RMW_SET_ERROR_MSG("service handle is null");
return RMW_RET_ERROR;
}
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
service handle,
service->implementation_identifier, toc_coredx_identifier,
return RMW_RET_ERROR)
if (!ros_request_header) {
RMW_SET_ERROR_MSG("ros request header handle is null");
return RMW_RET_ERROR;
}
if (!ros_response) {
RMW_SET_ERROR_MSG("ros response handle is null");
return RMW_RET_ERROR;
}
CoreDXStaticServiceInfo * service_info =
static_cast<CoreDXStaticServiceInfo *>(service->data);
if (!service_info) {
RMW_SET_ERROR_MSG("service info handle is null");
return RMW_RET_ERROR;
}
void * replier = service_info->replier_;
if (!replier) {
RMW_SET_ERROR_MSG("replier handle is null");
return RMW_RET_ERROR;
}
const service_type_support_callbacks_t * callbacks = service_info->callbacks_;
if (!callbacks) {
RMW_SET_ERROR_MSG("callbacks handle is null");
return RMW_RET_ERROR;
}
callbacks->send_response(replier, ros_request_header, ros_response);
return RMW_RET_OK;
}
#if defined(__cplusplus)
}
#endif
| 27.366667 | 80 | 0.710922 | rupertholman |
f6a9ee0167f5639b7b97c28fce5f0bd35fa9ca19 | 999 | hpp | C++ | src/transmission/reliable/containers/connection_list_vector.hpp | rnascunha/coap-te | eaff16162b1a524ad06e18dbdc79ca4c8658b3a8 | [
"MIT"
] | null | null | null | src/transmission/reliable/containers/connection_list_vector.hpp | rnascunha/coap-te | eaff16162b1a524ad06e18dbdc79ca4c8658b3a8 | [
"MIT"
] | null | null | null | src/transmission/reliable/containers/connection_list_vector.hpp | rnascunha/coap-te | eaff16162b1a524ad06e18dbdc79ca4c8658b3a8 | [
"MIT"
] | null | null | null | #ifndef COAP_TE_TRANSMISSION_RELIABLE_CONNECTION_LIST_VECTOR_HPP__
#define COAP_TE_TRANSMISSION_RELIABLE_CONNECTION_LIST_VECTOR_HPP__
#include "defines/defaults.hpp"
#include <vector>
namespace CoAP{
namespace Transmission{
namespace Reliable{
#if COAP_TE_RELIABLE_CONNECTION == 1
template<typename Connection>
class connection_list_vector{
public:
using connection_t = Connection;
using handler = typename Connection::handler;
connection_list_vector();
Connection* find(handler socket) noexcept;
Connection* find_free_slot() noexcept;
void close(handler socket) noexcept;
void close_all() noexcept;
Connection* operator[](unsigned index) noexcept;
unsigned ocupied() const noexcept;
unsigned size() const noexcept;
private:
std::vector<Connection> nodes_;
};
#endif /* COAP_TE_RELIABLE_CONNECTION == 1 */
}//CoAP
}//Transmission
}//Reliable
#include "impl/connection_list_vector_impl.hpp"
#endif /* COAP_TE_TRANSMISSION_RELIABLE_CONNECTION_LIST_VECTOR_HPP__ */
| 22.704545 | 71 | 0.795796 | rnascunha |
f6adb26915396c08b1ef61a8f04e435af4cf441b | 2,503 | cpp | C++ | src/libv/update/resource_server/resource_server_state.cpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 2 | 2018-04-11T03:07:03.000Z | 2019-03-29T15:24:12.000Z | src/libv/update/resource_server/resource_server_state.cpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | null | null | null | src/libv/update/resource_server/resource_server_state.cpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 1 | 2021-06-13T06:39:06.000Z | 2021-06-13T06:39:06.000Z | // Project: libv.update, File: src/libv/update/resource_server/resource_server_state.cpp, Author: Császár Mátyás [Vader]
// hpp
#include <libv/update/resource_server/resource_server_state.lpp>
// libv
//#include <libv/mt/worker_thread_pool.hpp>
#include <libv/algo/linear_find.hpp>
// pro
//#include <libv/update/log.hpp>
//#include <libv/update/resource_server/resource_file.lpp>
//#include <libv/update/resource_server/resource_peer.lpp>
namespace libv {
namespace update {
// -------------------------------------------------------------------------------------------------
void ServerState::join(libv::net::mtcp::Connection<ResourcePeer> peer) {
const auto lock = std::unique_lock(mutex);
if (active_peers.size() < settings_.limit_peer_count_active || settings_.limit_peer_count_active == 0) {
active_peers.emplace(peer);
return;
}
if (queued_peers.size() < settings_.limit_peer_count_queue || settings_.limit_peer_count_queue == 0) {
queued_peers.emplace_back(peer);
return;
}
// peer.connection().send_async(codec.encode(ResponseBusy(load_trend.busy_time())));
}
// void ServerState::inactivity_scan() {
// const auto now = std::chrono::system_clock::now();
//// const auto limit =
//// for (const auto& peer : active_peers)
//// if (peer->last_activity + settings.kick_inactivity_time > now)
//// erase(peer);
// io_context.execute_async([this] {
// inactivity_scan();
// });
// }
void ServerState::leave(libv::net::mtcp::Connection<ResourcePeer> peer) {
const auto lock = std::unique_lock(mutex);
const auto ita = active_peers.find(peer);
if (ita != active_peers.end()) {
// Active peer disconnecting
active_peers.erase(peer);
if (!queued_peers.empty()) {
const auto active_peer_limit_reached = active_peers.size() >= settings_.limit_peer_count_active && settings_.limit_peer_count_active != 0;
if (!active_peer_limit_reached) {
active_peers.emplace(queued_peers.front());
queued_peers.pop_front();
}
}
} else {
// Queued peer disconnecting
queued_peers.erase(libv::linear_find_iterator(queued_peers, peer));
}
}
void ServerState::disconnect_all() {
const auto lock = std::unique_lock(mutex);
for (const auto& peer : queued_peers)
peer.connection().cancel_and_disconnect_async();
for (const auto& peer : active_peers)
peer.connection().cancel_and_disconnect_async();
}
// -------------------------------------------------------------------------------------------------
} // namespace update
} // namespace libv
| 30.901235 | 141 | 0.669996 | cpplibv |
f6ae03f6f2e1b2b068102cc6808f63ba1bd70cf3 | 26,474 | cpp | C++ | folly/experimental/io/test/IoUringBackendTest.cpp | asklar/folly | a24e4441f972cc9ab8a8cb350d701e9d87826a48 | [
"MIT"
] | null | null | null | folly/experimental/io/test/IoUringBackendTest.cpp | asklar/folly | a24e4441f972cc9ab8a8cb350d701e9d87826a48 | [
"MIT"
] | null | null | null | folly/experimental/io/test/IoUringBackendTest.cpp | asklar/folly | a24e4441f972cc9ab8a8cb350d701e9d87826a48 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/eventfd.h>
#include <numeric>
#include <folly/FileUtil.h>
#include <folly/String.h>
#include <folly/experimental/io/IoUringBackend.h>
#include <folly/experimental/io/test/IoTestTempFileUtil.h>
#include <folly/init/Init.h>
#include <folly/io/async/AsyncUDPServerSocket.h>
#include <folly/io/async/AsyncUDPSocket.h>
#include <folly/io/async/EventHandler.h>
#include <folly/io/async/test/EventBaseTestLib.h>
#include <folly/portability/GTest.h>
// IoUringBackend specific tests
namespace {
class AlignedBuf {
public:
static constexpr size_t kAlign = 4096;
AlignedBuf() = delete;
AlignedBuf(size_t count, char ch) : size_(count) {
::posix_memalign(&data_, kAlign, size_);
CHECK(!!data_);
::memset(data_, ch, count);
}
AlignedBuf(const AlignedBuf& buf) : size_(buf.size_) {
if (size_) {
::posix_memalign(&data_, kAlign, size_);
CHECK(!!data_);
::memcpy(data_, buf.data_, size_);
}
}
~AlignedBuf() {
if (data_) {
::free(data_);
}
}
AlignedBuf& operator=(const AlignedBuf& buf) {
if (data_) {
::free(data_);
}
size_ = buf.size_;
if (size_) {
::posix_memalign(&data_, kAlign, size_);
CHECK(!!data_);
::memcpy(data_, buf.data_, size_);
}
return *this;
}
bool operator==(const AlignedBuf& buf) const {
if (size_ != buf.size_) {
return false;
}
if (size_ == 0) {
return true;
}
return (0 == ::memcmp(data_, buf.data_, size_));
}
bool operator!=(const AlignedBuf& buf) const {
return !(*this == buf);
}
void* data() const {
return data_;
}
size_t size() const {
return size_;
}
private:
void* data_{nullptr};
size_t size_{0};
};
class EventFD : public folly::EventHandler, public folly::EventReadCallback {
public:
EventFD(
bool valid,
uint64_t num,
uint64_t& total,
bool persist,
folly::EventBase* eventBase)
: EventFD(total, valid ? createFd(num) : -1, persist, eventBase) {}
~EventFD() override {
unregisterHandler();
if (fd_ >= 0) {
::close(fd_);
fd_ = -1;
}
}
void useAsyncReadCallback(bool val) {
if (val) {
setEventCallback(this);
} else {
resetEventCallback();
}
}
// from folly::EventHandler
void handlerReady(uint16_t /*events*/) noexcept override {
// we do not read to leave the fd signalled
++num_;
if (total_ > 0) {
--total_;
}
if (total_ > 0) {
if (!persist_) {
registerHandler(folly::EventHandler::READ);
}
} else {
if (persist_) {
unregisterHandler();
}
}
}
uint64_t getAsyncNum() const {
return asyncNum_;
}
uint64_t getNum() const {
return num_;
}
// from folly::EventReadCallback
folly::EventReadCallback::IoVec* allocateData() override {
auto* ret = ioVecPtr_.release();
return (ret ? ret : new IoVec(this));
}
private:
struct IoVec : public folly::EventReadCallback::IoVec {
IoVec() = delete;
~IoVec() override = default;
explicit IoVec(EventFD* eventFd) {
arg_ = eventFd;
freeFunc_ = IoVec::free;
cbFunc_ = IoVec::cb;
data_.iov_base = &eventData_;
data_.iov_len = sizeof(eventData_);
}
static void free(EventReadCallback::IoVec* ioVec) {
delete ioVec;
}
static void cb(EventReadCallback::IoVec* ioVec, int res) {
reinterpret_cast<EventFD*>(ioVec->arg_)
->cb(reinterpret_cast<IoVec*>(ioVec), res);
}
uint64_t eventData_{0};
};
static int createFd(uint64_t num) {
// we want it a semaphore
// and blocking for the async reads
int fd = ::eventfd(0, EFD_CLOEXEC | EFD_SEMAPHORE);
CHECK_GT(fd, 0);
CHECK_EQ(folly::writeNoInt(fd, &num, sizeof(num)), sizeof(num));
return fd;
}
EventFD(uint64_t& total, int fd, bool persist, folly::EventBase* eventBase)
: EventHandler(eventBase, folly::NetworkSocket::fromFd(fd)),
total_(total),
fd_(fd),
persist_(persist),
evb_(eventBase) {
if (persist_) {
registerHandler(folly::EventHandler::READ | folly::EventHandler::PERSIST);
} else {
registerHandler(folly::EventHandler::READ);
}
}
void cb(IoVec* ioVec, int res) {
CHECK_EQ(res, sizeof(IoVec::eventData_));
CHECK_EQ(ioVec->eventData_, 1);
// reset it
ioVec->eventData_ = 0;
// save it for future use
ioVecPtr_.reset(ioVec);
++asyncNum_;
if (total_ > 0) {
--total_;
}
if (total_ > 0) {
if (!persist_) {
registerHandler(folly::EventHandler::READ);
}
} else {
if (persist_) {
unregisterHandler();
}
}
}
uint64_t asyncNum_{0};
uint64_t num_{0};
uint64_t& total_;
int fd_{-1};
bool persist_;
folly::EventBase* evb_;
std::unique_ptr<IoVec> ioVecPtr_;
};
std::unique_ptr<folly::EventBase> getEventBase(
folly::PollIoBackend::Options opts) {
try {
auto factory = [opts] {
return std::make_unique<folly::IoUringBackend>(opts);
};
return std::make_unique<folly::EventBase>(
folly::EventBase::Options().setBackendFactory(std::move(factory)));
} catch (const folly::IoUringBackend::NotAvailable&) {
return nullptr;
}
}
void testEventFD(bool overflow, bool persist, bool asyncRead) {
static constexpr size_t kBackendCapacity = 64;
static constexpr size_t kBackendMaxSubmit = 32;
// for overflow == true we use a greater than kBackendCapacity number of
// EventFD instances and lower when overflow == false
size_t kNumEventFds = overflow ? 2048 : 32;
static constexpr size_t kEventFdCount = 16;
auto total = kNumEventFds * kEventFdCount + kEventFdCount / 2;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity).setMaxSubmit(kBackendMaxSubmit);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
std::vector<std::unique_ptr<EventFD>> eventsVec;
eventsVec.reserve(kNumEventFds);
for (size_t i = 0; i < kNumEventFds; i++) {
auto ev = std::make_unique<EventFD>(
true, 2 * kEventFdCount, total, persist, evbPtr.get());
ev->useAsyncReadCallback(asyncRead);
eventsVec.emplace_back(std::move(ev));
}
evbPtr->loop();
for (size_t i = 0; i < kNumEventFds; i++) {
CHECK_GE(
(asyncRead ? eventsVec[i]->getAsyncNum() : eventsVec[i]->getNum()),
kEventFdCount);
}
}
void testInvalidFd(size_t numTotal, size_t numValid, size_t numInvalid) {
static constexpr size_t kBackendCapacity = 128;
static constexpr size_t kBackendMaxSubmit = 64;
auto total = numTotal;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity).setMaxSubmit(kBackendMaxSubmit);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
std::vector<std::unique_ptr<EventFD>> eventsVec;
eventsVec.reserve(numTotal);
for (size_t i = 0; i < numTotal; i++) {
bool valid = (i % (numValid + numInvalid)) < numValid;
eventsVec.emplace_back(std::make_unique<EventFD>(
valid, 1, total, false /*persist*/, evbPtr.get()));
}
evbPtr->loop();
for (size_t i = 0; i < numTotal; i++) {
CHECK_GE(eventsVec[i]->getNum(), 1);
}
}
class EventRecvmsgCallback : public folly::EventRecvmsgCallback {
private:
struct MsgHdr : public folly::EventRecvmsgCallback::MsgHdr {
static auto constexpr kBuffSize = 1024;
MsgHdr() = delete;
~MsgHdr() override = default;
explicit MsgHdr(EventRecvmsgCallback* cb) {
arg_ = cb;
freeFunc_ = MsgHdr::free;
cbFunc_ = MsgHdr::cb;
ioBuf_ = folly::IOBuf::create(kBuffSize);
}
void reset() {
::memset(&data_, 0, sizeof(data_));
iov_.iov_base = ioBuf_->writableData();
iov_.iov_len = kBuffSize;
data_.msg_iov = &iov_;
data_.msg_iovlen = 1;
::memset(&addrStorage_, 0, sizeof(addrStorage_));
data_.msg_name = reinterpret_cast<sockaddr*>(&addrStorage_);
data_.msg_namelen = sizeof(addrStorage_);
}
static void free(folly::EventRecvmsgCallback::MsgHdr* msgHdr) {
delete msgHdr;
}
static void cb(folly::EventRecvmsgCallback::MsgHdr* msgHdr, int res) {
reinterpret_cast<EventRecvmsgCallback*>(msgHdr->arg_)
->cb(reinterpret_cast<MsgHdr*>(msgHdr), res);
}
// data
std::unique_ptr<folly::IOBuf> ioBuf_;
struct iovec iov_;
// addr
struct sockaddr_storage addrStorage_;
};
void cb(MsgHdr* msgHdr, int res) {
// check the number of bytes
CHECK_EQ(res, static_cast<int>(numBytes_));
// check the contents
std::string data;
data.assign(
reinterpret_cast<const char*>(msgHdr->ioBuf_->data()),
static_cast<size_t>(res));
CHECK_EQ(data, data_);
// check the address
folly::SocketAddress addr;
addr.setFromSockaddr(
reinterpret_cast<sockaddr*>(msgHdr->data_.msg_name),
msgHdr->data_.msg_namelen);
CHECK_EQ(addr, addr_);
// reuse the msgHdr
msgHdr_.reset(msgHdr);
++asyncNum_;
if (total_ > 0) {
--total_;
if (total_ == 0) {
evb_->terminateLoopSoon();
}
}
}
public:
EventRecvmsgCallback(
const std::string& data,
const folly::SocketAddress& addr,
size_t numBytes,
uint64_t& total,
folly::EventBase* eventBase)
: data_(data),
addr_(addr),
numBytes_(numBytes),
total_(total),
evb_(eventBase) {}
~EventRecvmsgCallback() override = default;
// from EventRecvmsgCallback
EventRecvmsgCallback::MsgHdr* allocateData() override {
auto* ret = msgHdr_.release();
if (!ret) {
ret = new MsgHdr(this);
}
ret->reset();
return ret;
}
uint64_t getAsyncNum() const {
return asyncNum_;
}
private:
const std::string& data_;
folly::SocketAddress addr_;
size_t numBytes_{0};
uint64_t& total_;
folly::EventBase* evb_;
uint64_t asyncNum_{0};
std::unique_ptr<MsgHdr> msgHdr_;
};
void testAsyncUDPRecvmsg(bool useRegisteredFds) {
static constexpr size_t kBackendCapacity = 64;
static constexpr size_t kBackendMaxSubmit = 32;
static constexpr size_t kBackendMaxGet = 32;
static constexpr size_t kNumSockets = 32;
static constexpr size_t kNumBytes = 16;
static constexpr size_t kNumPackets = 32;
auto total = kNumPackets * kNumSockets;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(useRegisteredFds);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
// create the server sockets
std::vector<std::unique_ptr<folly::AsyncUDPServerSocket>> serverSocketVec;
serverSocketVec.reserve(kNumSockets);
std::vector<std::unique_ptr<folly::AsyncUDPSocket>> clientSocketVec;
serverSocketVec.reserve(kNumSockets);
std::vector<std::unique_ptr<EventRecvmsgCallback>> cbVec;
cbVec.reserve(kNumSockets);
std::string data(kNumBytes, 'A');
for (size_t i = 0; i < kNumSockets; i++) {
auto clientSock = std::make_unique<folly::AsyncUDPSocket>(evbPtr.get());
clientSock->bind(folly::SocketAddress("::1", 0));
auto cb = std::make_unique<EventRecvmsgCallback>(
data, clientSock->address(), kNumBytes, total, evbPtr.get());
auto serverSock = std::make_unique<folly::AsyncUDPServerSocket>(
evbPtr.get(),
1500,
folly::AsyncUDPServerSocket::DispatchMechanism::RoundRobin);
// set the event callback
serverSock->setEventCallback(cb.get());
// bind
serverSock->bind(folly::SocketAddress("::1", 0));
// retrieve the real address
folly::SocketAddress addr = serverSock->address();
serverSock->listen();
serverSocketVec.emplace_back(std::move(serverSock));
// connect the client
clientSock->connect(addr);
for (size_t j = 0; j < kNumPackets; j++) {
auto buf = folly::IOBuf::copyBuffer(data.c_str(), data.size());
CHECK_EQ(clientSock->write(addr, std::move(buf)), data.size());
}
clientSocketVec.emplace_back(std::move(clientSock));
cbVec.emplace_back(std::move(cb));
}
evbPtr->loopForever();
for (size_t i = 0; i < kNumSockets; i++) {
CHECK_GE(cbVec[i]->getAsyncNum(), kNumPackets);
}
}
} // namespace
TEST(IoUringBackend, AsyncUDPRecvmsgNoRegisterFd) {
testAsyncUDPRecvmsg(false);
}
TEST(IoUringBackend, AsyncUDPRecvmsgRegisterFd) {
testAsyncUDPRecvmsg(true);
}
TEST(IoUringBackend, EventFD_NoOverflowNoPersist) {
testEventFD(false, false, false);
}
TEST(IoUringBackend, EventFD_OverflowNoPersist) {
testEventFD(true, false, false);
}
TEST(IoUringBackend, EventFD_NoOverflowPersist) {
testEventFD(false, true, false);
}
TEST(IoUringBackend, EventFD_OverflowPersist) {
testEventFD(true, true, false);
}
TEST(IoUringBackend, EventFD_Persist_AsyncRead) {
testEventFD(false, true, true);
}
// 9 valid fds followed by an invalid one
TEST(IoUringBackend, Invalid_fd_9_1) {
testInvalidFd(32, 10, 1);
}
// only invalid fds
TEST(IoUringBackend, Invalid_fd_0_10) {
testInvalidFd(32, 0, 10);
}
// equal distribution
TEST(IoUringBackend, Invalid_fd_5_5) {
testInvalidFd(32, 10, 10);
}
TEST(IoUringBackend, RegisteredFds) {
static constexpr size_t kBackendCapacity = 64;
static constexpr size_t kBackendMaxSubmit = 32;
static constexpr size_t kBackendMaxGet = 32;
std::unique_ptr<folly::IoUringBackend> backendReg;
std::unique_ptr<folly::IoUringBackend> backendNoReg;
try {
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(true);
backendReg = std::make_unique<folly::IoUringBackend>(options);
options.setUseRegisteredFds(false);
backendNoReg = std::make_unique<folly::IoUringBackend>(options);
} catch (const folly::IoUringBackend::NotAvailable&) {
}
SKIP_IF(!backendReg) << "Backend not available";
SKIP_IF(!backendNoReg) << "Backend not available";
int eventFd = ::eventfd(0, EFD_CLOEXEC | EFD_SEMAPHORE | EFD_NONBLOCK);
CHECK_GT(eventFd, 0);
SCOPE_EXIT {
::close(eventFd);
};
// verify for useRegisteredFds = false we get a nullptr FdRegistrationRecord
auto* record = backendNoReg->registerFd(eventFd);
CHECK(!record);
std::vector<folly::IoUringBackend::FdRegistrationRecord*> records;
// we use kBackendCapacity -1 since we can have the timerFd
// already using one fd
records.reserve(kBackendCapacity - 1);
for (size_t i = 0; i < kBackendCapacity - 1; i++) {
record = backendReg->registerFd(eventFd);
CHECK(record);
records.emplace_back(record);
}
// try to allocate one more and check if we get a nullptr
record = backendReg->registerFd(eventFd);
CHECK(!record);
// deallocate and allocate again
for (size_t i = 0; i < records.size(); i++) {
CHECK(backendReg->unregisterFd(records[i]));
record = backendReg->registerFd(eventFd);
CHECK(record);
records[i] = record;
}
}
TEST(IoUringBackend, FileReadWrite) {
static constexpr size_t kBackendCapacity = 2048;
static constexpr size_t kBackendMaxSubmit = 32;
static constexpr size_t kBackendMaxGet = 32;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(false);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
static constexpr size_t kNumBlocks = 512;
static constexpr size_t kBlockSize = 4096;
static constexpr size_t kFileSize = kNumBlocks * kBlockSize;
auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize);
int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR);
SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: "
<< folly::errnoStr(errno);
SCOPE_EXIT {
::close(fd);
};
auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend());
CHECK(!!backendPtr);
size_t num = 0;
AlignedBuf writeData(kBlockSize, 'A'), readData(kBlockSize, 'Z');
std::vector<AlignedBuf> writeDataVec(kNumBlocks, writeData),
readDataVec(kNumBlocks, readData);
CHECK(readData != writeData);
for (size_t i = 0; i < kNumBlocks; i++) {
folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) {
CHECK_EQ(res, writeDataVec[i].size());
folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) {
CHECK_EQ(res, readDataVec[i].size());
CHECK(readDataVec[i] == writeDataVec[i]);
++num;
};
backendPtr->queueRead(
fd,
readDataVec[i].data(),
readDataVec[i].size(),
i * kBlockSize,
std::move(readCb));
};
backendPtr->queueWrite(
fd,
writeDataVec[i].data(),
writeDataVec[i].size(),
i * kBlockSize,
std::move(writeCb));
}
evbPtr->loop();
EXPECT_EQ(num, kNumBlocks);
}
TEST(IoUringBackend, FileReadvWritev) {
static constexpr size_t kBackendCapacity = 2048;
static constexpr size_t kBackendMaxSubmit = 32;
static constexpr size_t kBackendMaxGet = 32;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(false);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
static constexpr size_t kNumBlocks = 512;
static constexpr size_t kNumIov = 4;
static constexpr size_t kIovSize = 4096;
static constexpr size_t kBlockSize = kNumIov * kIovSize;
static constexpr size_t kFileSize = kNumBlocks * kBlockSize;
auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize);
int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR);
SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: "
<< folly::errnoStr(errno);
SCOPE_EXIT {
::close(fd);
};
auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend());
CHECK(!!backendPtr);
size_t num = 0;
AlignedBuf writeData(kIovSize, 'A'), readData(kIovSize, 'Z');
std::vector<AlignedBuf> writeDataVec(kNumIov, writeData),
readDataVec(kNumIov, readData);
std::vector<std::vector<AlignedBuf>> writeDataVecVec(
kNumBlocks, writeDataVec),
readDataVecVec(kNumBlocks, readDataVec);
CHECK(readDataVec != writeDataVec);
std::vector<std::vector<struct iovec>> readDataIov, writeDataIov;
std::vector<size_t> lenVec;
readDataIov.reserve(kNumBlocks);
writeDataIov.reserve(kNumBlocks);
lenVec.reserve(kNumBlocks);
for (size_t i = 0; i < kNumBlocks; i++) {
size_t len = 0;
std::vector<struct iovec> readIov, writeIov;
readIov.reserve(kNumIov);
writeIov.reserve(kNumIov);
for (size_t j = 0; j < kNumIov; j++) {
struct iovec riov {
readDataVecVec[i][j].data(), readDataVecVec[i][j].size()
};
readIov.push_back(riov);
struct iovec wiov {
writeDataVecVec[i][j].data(), writeDataVecVec[i][j].size()
};
writeIov.push_back(wiov);
len += riov.iov_len;
}
readDataIov.emplace_back(std::move(readIov));
writeDataIov.emplace_back(std::move(writeIov));
lenVec.emplace_back(len);
}
for (size_t i = 0; i < kNumBlocks; i++) {
folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) {
CHECK_EQ(res, lenVec[i]);
folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) {
CHECK_EQ(res, lenVec[i]);
CHECK(readDataVecVec[i] == writeDataVecVec[i]);
if (++num == kNumBlocks) {
evbPtr->terminateLoopSoon();
}
};
backendPtr->queueReadv(
fd, readDataIov[i], i * kBlockSize, std::move(readCb));
};
backendPtr->queueWritev(
fd, writeDataIov[i], i * kBlockSize, std::move(writeCb));
}
evbPtr->loopForever();
EXPECT_EQ(num, kNumBlocks);
}
TEST(IoUringBackend, FileReadMany) {
static constexpr size_t kBackendCapacity = 1024;
static constexpr size_t kBackendMaxSubmit = 128;
static constexpr size_t kBackendMaxGet = 128;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(false);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
static constexpr size_t kNumBlocks = 8 * 1024;
static constexpr size_t kBlockSize = 4096;
static constexpr size_t kBigBlockSize = 2 * 1024 * 1024;
static constexpr size_t kFileSize = kNumBlocks * kBlockSize;
auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize);
int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR);
SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: "
<< folly::errnoStr(errno);
SCOPE_EXIT {
::close(fd);
};
auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend());
CHECK(!!backendPtr);
size_t num = 0;
AlignedBuf readData(kBlockSize, 'Z');
std::vector<AlignedBuf> readDataVec(kNumBlocks, readData);
AlignedBuf bigReadData(kBigBlockSize, 'Z');
for (size_t i = 0; i < kNumBlocks; i++) {
folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) {
CHECK_EQ(res, readDataVec[i].size());
++num;
};
backendPtr->queueRead(
fd,
readDataVec[i].data(),
readDataVec[i].size(),
i * kBlockSize,
std::move(readCb));
}
folly::IoUringBackend::FileOpCallback bigReadCb = [&](int res) {
CHECK_EQ(res, bigReadData.size());
};
backendPtr->queueRead(
fd, bigReadData.data(), bigReadData.size(), 0, std::move(bigReadCb));
evbPtr->loop();
EXPECT_EQ(num, kNumBlocks);
}
TEST(IoUringBackend, FileWriteMany) {
static constexpr size_t kBackendCapacity = 1024;
static constexpr size_t kBackendMaxSubmit = 128;
static constexpr size_t kBackendMaxGet = 128;
folly::PollIoBackend::Options options;
options.setCapacity(kBackendCapacity)
.setMaxSubmit(kBackendMaxSubmit)
.setMaxGet(kBackendMaxGet)
.setUseRegisteredFds(false);
auto evbPtr = getEventBase(options);
SKIP_IF(!evbPtr) << "Backend not available";
static constexpr size_t kNumBlocks = 8 * 1024;
static constexpr size_t kBlockSize = 4096;
static constexpr size_t kBigBlockSize = 2 * 1024 * 1024;
static constexpr size_t kFileSize = kNumBlocks * kBlockSize;
auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize);
int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR);
SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: "
<< folly::errnoStr(errno);
SCOPE_EXIT {
::close(fd);
};
auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend());
CHECK(!!backendPtr);
size_t num = 0;
AlignedBuf writeData(kBlockSize, 'A');
std::vector<AlignedBuf> writeDataVec(kNumBlocks, writeData);
AlignedBuf bigWriteData(kBigBlockSize, 'A');
bool bFdatasync = false;
for (size_t i = 0; i < kNumBlocks; i++) {
folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) {
CHECK_EQ(res, writeDataVec[i].size());
++num;
if (num == kNumBlocks) {
folly::IoUringBackend::FileOpCallback fdatasyncCb = [&](int res) {
CHECK_EQ(res, 0);
bFdatasync = true;
};
backendPtr->queueFdatasync(fd, std::move(fdatasyncCb));
}
};
backendPtr->queueWrite(
fd,
writeDataVec[i].data(),
writeDataVec[i].size(),
i * kBlockSize,
std::move(writeCb));
}
evbPtr->loop();
EXPECT_EQ(num, kNumBlocks);
EXPECT_EQ(bFdatasync, true);
bool bFsync = false;
folly::IoUringBackend::FileOpCallback bigWriteCb = [&](int res) {
CHECK_EQ(res, bigWriteData.size());
folly::IoUringBackend::FileOpCallback fsyncCb = [&](int res) {
CHECK_EQ(res, 0);
bFsync = true;
};
backendPtr->queueFsync(fd, std::move(fsyncCb));
};
backendPtr->queueWrite(
fd, bigWriteData.data(), bigWriteData.size(), 0, std::move(bigWriteCb));
evbPtr->loop();
EXPECT_EQ(bFsync, true);
}
namespace folly {
namespace test {
static constexpr size_t kCapacity = 16 * 1024;
static constexpr size_t kMaxSubmit = 128;
static constexpr size_t kMaxGet = static_cast<size_t>(-1);
struct IoUringBackendProvider {
static std::unique_ptr<folly::EventBaseBackendBase> getBackend() {
try {
folly::PollIoBackend::Options options;
options.setCapacity(kCapacity)
.setMaxSubmit(kMaxSubmit)
.setMaxGet(kMaxGet)
.setUseRegisteredFds(false);
return std::make_unique<folly::IoUringBackend>(options);
} catch (const IoUringBackend::NotAvailable&) {
return nullptr;
}
}
};
struct IoUringRegFdBackendProvider {
static std::unique_ptr<folly::EventBaseBackendBase> getBackend() {
try {
folly::PollIoBackend::Options options;
options.setCapacity(kCapacity)
.setMaxSubmit(kMaxSubmit)
.setMaxGet(kMaxGet)
.setUseRegisteredFds(true);
return std::make_unique<folly::IoUringBackend>(options);
} catch (const IoUringBackend::NotAvailable&) {
return nullptr;
}
}
};
// Instantiate the non registered fd tests
INSTANTIATE_TYPED_TEST_CASE_P(IoUring, EventBaseTest, IoUringBackendProvider);
INSTANTIATE_TYPED_TEST_CASE_P(IoUring, EventBaseTest1, IoUringBackendProvider);
// Instantiate the registered fd tests
INSTANTIATE_TYPED_TEST_CASE_P(
IoUringRegFd,
EventBaseTest,
IoUringRegFdBackendProvider);
INSTANTIATE_TYPED_TEST_CASE_P(
IoUringRegFd,
EventBaseTest1,
IoUringRegFdBackendProvider);
} // namespace test
} // namespace folly
| 27.808824 | 80 | 0.666881 | asklar |
f6b4e82a88ed97388d7b516986ff163a97040535 | 11,683 | cpp | C++ | lldb/source/Target/UnixSignals.cpp | lforg37/sycl | 0804265491788808e1218dbda086c22ecc971ac2 | [
"Apache-2.0"
] | null | null | null | lldb/source/Target/UnixSignals.cpp | lforg37/sycl | 0804265491788808e1218dbda086c22ecc971ac2 | [
"Apache-2.0"
] | null | null | null | lldb/source/Target/UnixSignals.cpp | lforg37/sycl | 0804265491788808e1218dbda086c22ecc971ac2 | [
"Apache-2.0"
] | null | null | null | //===-- UnixSignals.cpp ---------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/UnixSignals.h"
#include "Plugins/Process/Utility/FreeBSDSignals.h"
#include "Plugins/Process/Utility/LinuxSignals.h"
#include "Plugins/Process/Utility/MipsLinuxSignals.h"
#include "Plugins/Process/Utility/NetBSDSignals.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/StringConvert.h"
#include "lldb/Utility/ArchSpec.h"
using namespace lldb_private;
UnixSignals::Signal::Signal(const char *name, bool default_suppress,
bool default_stop, bool default_notify,
const char *description, const char *alias)
: m_name(name), m_alias(alias), m_description(),
m_suppress(default_suppress), m_stop(default_stop),
m_notify(default_notify) {
if (description)
m_description.assign(description);
}
lldb::UnixSignalsSP UnixSignals::Create(const ArchSpec &arch) {
const auto &triple = arch.GetTriple();
switch (triple.getOS()) {
case llvm::Triple::Linux: {
switch (triple.getArch()) {
case llvm::Triple::mips:
case llvm::Triple::mipsel:
case llvm::Triple::mips64:
case llvm::Triple::mips64el:
return std::make_shared<MipsLinuxSignals>();
default:
return std::make_shared<LinuxSignals>();
}
}
case llvm::Triple::FreeBSD:
case llvm::Triple::OpenBSD:
return std::make_shared<FreeBSDSignals>();
case llvm::Triple::NetBSD:
return std::make_shared<NetBSDSignals>();
default:
return std::make_shared<UnixSignals>();
}
}
lldb::UnixSignalsSP UnixSignals::CreateForHost() {
static lldb::UnixSignalsSP s_unix_signals_sp =
Create(HostInfo::GetArchitecture());
return s_unix_signals_sp;
}
// UnixSignals constructor
UnixSignals::UnixSignals() { Reset(); }
UnixSignals::UnixSignals(const UnixSignals &rhs) : m_signals(rhs.m_signals) {}
UnixSignals::~UnixSignals() = default;
void UnixSignals::Reset() {
// This builds one standard set of Unix Signals. If yours aren't quite in
// this order, you can either subclass this class, and use Add & Remove to
// change them or you can subclass and build them afresh in your constructor.
//
// Note: the signals below are the Darwin signals. Do not change these!
m_signals.clear();
// clang-format off
// SIGNO NAME SUPPRESS STOP NOTIFY DESCRIPTION
// ====== ============ ======== ====== ====== ===================================================
AddSignal(1, "SIGHUP", false, true, true, "hangup");
AddSignal(2, "SIGINT", true, true, true, "interrupt");
AddSignal(3, "SIGQUIT", false, true, true, "quit");
AddSignal(4, "SIGILL", false, true, true, "illegal instruction");
AddSignal(5, "SIGTRAP", true, true, true, "trace trap (not reset when caught)");
AddSignal(6, "SIGABRT", false, true, true, "abort()");
AddSignal(7, "SIGEMT", false, true, true, "pollable event");
AddSignal(8, "SIGFPE", false, true, true, "floating point exception");
AddSignal(9, "SIGKILL", false, true, true, "kill");
AddSignal(10, "SIGBUS", false, true, true, "bus error");
AddSignal(11, "SIGSEGV", false, true, true, "segmentation violation");
AddSignal(12, "SIGSYS", false, true, true, "bad argument to system call");
AddSignal(13, "SIGPIPE", false, false, false, "write on a pipe with no one to read it");
AddSignal(14, "SIGALRM", false, false, false, "alarm clock");
AddSignal(15, "SIGTERM", false, true, true, "software termination signal from kill");
AddSignal(16, "SIGURG", false, false, false, "urgent condition on IO channel");
AddSignal(17, "SIGSTOP", true, true, true, "sendable stop signal not from tty");
AddSignal(18, "SIGTSTP", false, true, true, "stop signal from tty");
AddSignal(19, "SIGCONT", false, true, true, "continue a stopped process");
AddSignal(20, "SIGCHLD", false, false, false, "to parent on child stop or exit");
AddSignal(21, "SIGTTIN", false, true, true, "to readers process group upon background tty read");
AddSignal(22, "SIGTTOU", false, true, true, "to readers process group upon background tty write");
AddSignal(23, "SIGIO", false, false, false, "input/output possible signal");
AddSignal(24, "SIGXCPU", false, true, true, "exceeded CPU time limit");
AddSignal(25, "SIGXFSZ", false, true, true, "exceeded file size limit");
AddSignal(26, "SIGVTALRM", false, false, false, "virtual time alarm");
AddSignal(27, "SIGPROF", false, false, false, "profiling time alarm");
AddSignal(28, "SIGWINCH", false, false, false, "window size changes");
AddSignal(29, "SIGINFO", false, true, true, "information request");
AddSignal(30, "SIGUSR1", false, true, true, "user defined signal 1");
AddSignal(31, "SIGUSR2", false, true, true, "user defined signal 2");
// clang-format on
}
void UnixSignals::AddSignal(int signo, const char *name, bool default_suppress,
bool default_stop, bool default_notify,
const char *description, const char *alias) {
Signal new_signal(name, default_suppress, default_stop, default_notify,
description, alias);
m_signals.insert(std::make_pair(signo, new_signal));
++m_version;
}
void UnixSignals::RemoveSignal(int signo) {
collection::iterator pos = m_signals.find(signo);
if (pos != m_signals.end())
m_signals.erase(pos);
++m_version;
}
const char *UnixSignals::GetSignalAsCString(int signo) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos == m_signals.end())
return nullptr;
else
return pos->second.m_name.GetCString();
}
bool UnixSignals::SignalIsValid(int32_t signo) const {
return m_signals.find(signo) != m_signals.end();
}
ConstString UnixSignals::GetShortName(ConstString name) const {
if (name)
return ConstString(name.GetStringRef().substr(3)); // Remove "SIG" from name
return name;
}
int32_t UnixSignals::GetSignalNumberFromName(const char *name) const {
ConstString const_name(name);
collection::const_iterator pos, end = m_signals.end();
for (pos = m_signals.begin(); pos != end; pos++) {
if ((const_name == pos->second.m_name) ||
(const_name == pos->second.m_alias) ||
(const_name == GetShortName(pos->second.m_name)) ||
(const_name == GetShortName(pos->second.m_alias)))
return pos->first;
}
const int32_t signo =
StringConvert::ToSInt32(name, LLDB_INVALID_SIGNAL_NUMBER, 0);
if (signo != LLDB_INVALID_SIGNAL_NUMBER)
return signo;
return LLDB_INVALID_SIGNAL_NUMBER;
}
int32_t UnixSignals::GetFirstSignalNumber() const {
if (m_signals.empty())
return LLDB_INVALID_SIGNAL_NUMBER;
return (*m_signals.begin()).first;
}
int32_t UnixSignals::GetNextSignalNumber(int32_t current_signal) const {
collection::const_iterator pos = m_signals.find(current_signal);
collection::const_iterator end = m_signals.end();
if (pos == end)
return LLDB_INVALID_SIGNAL_NUMBER;
else {
pos++;
if (pos == end)
return LLDB_INVALID_SIGNAL_NUMBER;
else
return pos->first;
}
}
const char *UnixSignals::GetSignalInfo(int32_t signo, bool &should_suppress,
bool &should_stop,
bool &should_notify) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos == m_signals.end())
return nullptr;
else {
const Signal &signal = pos->second;
should_suppress = signal.m_suppress;
should_stop = signal.m_stop;
should_notify = signal.m_notify;
return signal.m_name.AsCString("");
}
}
bool UnixSignals::GetShouldSuppress(int signo) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos != m_signals.end())
return pos->second.m_suppress;
return false;
}
bool UnixSignals::SetShouldSuppress(int signo, bool value) {
collection::iterator pos = m_signals.find(signo);
if (pos != m_signals.end()) {
pos->second.m_suppress = value;
++m_version;
return true;
}
return false;
}
bool UnixSignals::SetShouldSuppress(const char *signal_name, bool value) {
const int32_t signo = GetSignalNumberFromName(signal_name);
if (signo != LLDB_INVALID_SIGNAL_NUMBER)
return SetShouldSuppress(signo, value);
return false;
}
bool UnixSignals::GetShouldStop(int signo) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos != m_signals.end())
return pos->second.m_stop;
return false;
}
bool UnixSignals::SetShouldStop(int signo, bool value) {
collection::iterator pos = m_signals.find(signo);
if (pos != m_signals.end()) {
pos->second.m_stop = value;
++m_version;
return true;
}
return false;
}
bool UnixSignals::SetShouldStop(const char *signal_name, bool value) {
const int32_t signo = GetSignalNumberFromName(signal_name);
if (signo != LLDB_INVALID_SIGNAL_NUMBER)
return SetShouldStop(signo, value);
return false;
}
bool UnixSignals::GetShouldNotify(int signo) const {
collection::const_iterator pos = m_signals.find(signo);
if (pos != m_signals.end())
return pos->second.m_notify;
return false;
}
bool UnixSignals::SetShouldNotify(int signo, bool value) {
collection::iterator pos = m_signals.find(signo);
if (pos != m_signals.end()) {
pos->second.m_notify = value;
++m_version;
return true;
}
return false;
}
bool UnixSignals::SetShouldNotify(const char *signal_name, bool value) {
const int32_t signo = GetSignalNumberFromName(signal_name);
if (signo != LLDB_INVALID_SIGNAL_NUMBER)
return SetShouldNotify(signo, value);
return false;
}
int32_t UnixSignals::GetNumSignals() const { return m_signals.size(); }
int32_t UnixSignals::GetSignalAtIndex(int32_t index) const {
if (index < 0 || m_signals.size() <= static_cast<size_t>(index))
return LLDB_INVALID_SIGNAL_NUMBER;
auto it = m_signals.begin();
std::advance(it, index);
return it->first;
}
uint64_t UnixSignals::GetVersion() const { return m_version; }
std::vector<int32_t>
UnixSignals::GetFilteredSignals(llvm::Optional<bool> should_suppress,
llvm::Optional<bool> should_stop,
llvm::Optional<bool> should_notify) {
std::vector<int32_t> result;
for (int32_t signo = GetFirstSignalNumber();
signo != LLDB_INVALID_SIGNAL_NUMBER;
signo = GetNextSignalNumber(signo)) {
bool signal_suppress = false;
bool signal_stop = false;
bool signal_notify = false;
GetSignalInfo(signo, signal_suppress, signal_stop, signal_notify);
// If any of filtering conditions are not met, we move on to the next
// signal.
if (should_suppress.hasValue() &&
signal_suppress != should_suppress.getValue())
continue;
if (should_stop.hasValue() && signal_stop != should_stop.getValue())
continue;
if (should_notify.hasValue() && signal_notify != should_notify.getValue())
continue;
result.push_back(signo);
}
return result;
}
| 36.85489 | 114 | 0.651887 | lforg37 |
f6b502462e3b6fca862663fd62725d11a8921bff | 512 | hpp | C++ | kizunano/node/openclconfig.hpp | kizunanocoin/node | c6013e7e992ab75432db58da05054b381f821566 | [
"BSD-3-Clause"
] | 1 | 2021-08-16T06:41:05.000Z | 2021-08-16T06:41:05.000Z | kizunano/node/openclconfig.hpp | kizunanocoin/node | c6013e7e992ab75432db58da05054b381f821566 | [
"BSD-3-Clause"
] | null | null | null | kizunano/node/openclconfig.hpp | kizunanocoin/node | c6013e7e992ab75432db58da05054b381f821566 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <kizunano/lib/errors.hpp>
namespace nano
{
class jsonconfig;
class tomlconfig;
class opencl_config
{
public:
opencl_config () = default;
opencl_config (unsigned, unsigned, unsigned);
nano::error serialize_json (nano::jsonconfig &) const;
nano::error deserialize_json (nano::jsonconfig &);
nano::error serialize_toml (nano::tomlconfig &) const;
nano::error deserialize_toml (nano::tomlconfig &);
unsigned platform{ 0 };
unsigned device{ 0 };
unsigned threads{ 1024 * 1024 };
};
}
| 22.26087 | 55 | 0.738281 | kizunanocoin |
f6b7587ba9fbbcadc46a0c2b9475007dd2f6e86a | 1,029 | hpp | C++ | src/common/ObjectCounter.hpp | halfmvsq/histolozee | c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5 | [
"Apache-2.0"
] | null | null | null | src/common/ObjectCounter.hpp | halfmvsq/histolozee | c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5 | [
"Apache-2.0"
] | null | null | null | src/common/ObjectCounter.hpp | halfmvsq/histolozee | c624c0d7c3a70bcc0d6aac87b4f24677e064b6a5 | [
"Apache-2.0"
] | null | null | null | #ifndef OBJECT_COUNTER_H
#define OBJECT_COUNTER_H
#include <cstddef>
/**
* @brief Template class for couynting the number of objects of type T created and
* currently allocated (a.k.a. the number of objects that are "alive").
*/
template< class T >
class ObjectCounter
{
public:
ObjectCounter()
{
++m_numCreated;
++m_numAlive;
}
ObjectCounter( const ObjectCounter& )
{
++m_numCreated;
++m_numAlive;
}
std::size_t numCreated() const noexcept
{
return m_numCreated;
}
std::size_t numAlive() const noexcept
{
return m_numAlive;
}
protected:
/// @note Objects should never be removed through pointers of this type
~ObjectCounter()
{
--m_numAlive;
}
private:
static std::size_t m_numCreated;
static std::size_t m_numAlive;
};
template< class T > std::size_t ObjectCounter<T>::m_numCreated = 0;
template< class T > std::size_t ObjectCounter<T>::m_numAlive = 0;
#endif // OBJECT_COUNTER_H
| 17.440678 | 82 | 0.643343 | halfmvsq |
f6b7d08455d438f2eadf35aec37123afe6dddc76 | 7,066 | cpp | C++ | src/third_party/swiftshader/third_party/llvm-7.0/llvm/tools/bugpoint/bugpoint.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 171 | 2018-09-17T13:15:12.000Z | 2022-03-18T03:47:04.000Z | src/third_party/swiftshader/third_party/llvm-7.0/llvm/tools/bugpoint/bugpoint.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 51 | 2019-10-23T11:55:08.000Z | 2021-12-21T06:32:11.000Z | src/third_party/swiftshader/third_party/llvm-7.0/llvm/tools/bugpoint/bugpoint.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 35 | 2018-09-18T07:46:53.000Z | 2022-03-27T07:59:48.000Z | //===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool. It is used to narrow
// down miscompilations and crash problems to a specific pass in the compiler,
// and the specific Module or Function input that is causing the problem.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "ToolRunner.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/LinkAllIR.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Valgrind.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
// Enable this macro to debug bugpoint itself.
//#define DEBUG_BUGPOINT 1
using namespace llvm;
static cl::opt<bool>
FindBugs("find-bugs", cl::desc("Run many different optimization sequences "
"on program to find bugs"),
cl::init(false));
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input llvm ll/bc files>"));
static cl::opt<unsigned> TimeoutValue(
"timeout", cl::init(300), cl::value_desc("seconds"),
cl::desc("Number of seconds program is allowed to run before it "
"is killed (default is 300s), 0 disables timeout"));
static cl::opt<int> MemoryLimit(
"mlimit", cl::init(-1), cl::value_desc("MBytes"),
cl::desc("Maximum amount of memory to use. 0 disables check. Defaults to "
"400MB (800MB under valgrind, 0 with sanitizers)."));
static cl::opt<bool>
UseValgrind("enable-valgrind",
cl::desc("Run optimizations through valgrind"));
// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo *, bool, PassNameParser>
PassList(cl::desc("Passes available:"), cl::ZeroOrMore);
static cl::opt<bool>
StandardLinkOpts("std-link-opts",
cl::desc("Include the standard link time optimizations"));
static cl::opt<bool>
OptLevelO1("O1", cl::desc("Optimization level 1. Identical to 'opt -O1'"));
static cl::opt<bool>
OptLevelO2("O2", cl::desc("Optimization level 2. Identical to 'opt -O2'"));
static cl::opt<bool> OptLevelOs(
"Os",
cl::desc(
"Like -O2 with extra optimizations for size. Similar to clang -Os"));
static cl::opt<bool>
OptLevelO3("O3", cl::desc("Optimization level 3. Identical to 'opt -O3'"));
static cl::opt<std::string>
OverrideTriple("mtriple", cl::desc("Override target triple for module"));
/// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
bool llvm::BugpointIsInterrupted = false;
#ifndef DEBUG_BUGPOINT
static void BugpointInterruptFunction() { BugpointIsInterrupted = true; }
#endif
// Hack to capture a pass list.
namespace {
class AddToDriver : public legacy::FunctionPassManager {
BugDriver &D;
public:
AddToDriver(BugDriver &_D) : FunctionPassManager(nullptr), D(_D) {}
void add(Pass *P) override {
const void *ID = P->getPassID();
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
D.addPass(PI->getPassArgument());
}
};
}
#ifdef LINK_POLLY_INTO_TOOLS
namespace polly {
void initializePollyPasses(llvm::PassRegistry &Registry);
}
#endif
int main(int argc, char **argv) {
#ifndef DEBUG_BUGPOINT
InitLLVM X(argc, argv);
#endif
// Initialize passes
PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeScalarOpts(Registry);
initializeObjCARCOpts(Registry);
initializeVectorization(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeAggressiveInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
#ifdef LINK_POLLY_INTO_TOOLS
polly::initializePollyPasses(Registry);
#endif
if (std::getenv("bar") == (char*) -1) {
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
}
cl::ParseCommandLineOptions(argc, argv,
"LLVM automatic testcase reducer. See\nhttp://"
"llvm.org/cmds/bugpoint.html"
" for more information.\n");
#ifndef DEBUG_BUGPOINT
sys::SetInterruptFunction(BugpointInterruptFunction);
#endif
LLVMContext Context;
// If we have an override, set it and then track the triple we want Modules
// to use.
if (!OverrideTriple.empty()) {
TargetTriple.setTriple(Triple::normalize(OverrideTriple));
outs() << "Override triple set to '" << TargetTriple.getTriple() << "'\n";
}
if (MemoryLimit < 0) {
// Set the default MemoryLimit. Be sure to update the flag's description if
// you change this.
if (sys::RunningOnValgrind() || UseValgrind)
MemoryLimit = 800;
else
MemoryLimit = 400;
#if (LLVM_ADDRESS_SANITIZER_BUILD || LLVM_MEMORY_SANITIZER_BUILD || \
LLVM_THREAD_SANITIZER_BUILD)
// Starting from kernel 4.9 memory allocated with mmap is counted against
// RLIMIT_DATA. Sanitizers need to allocate tens of terabytes for shadow.
MemoryLimit = 0;
#endif
}
BugDriver D(argv[0], FindBugs, TimeoutValue, MemoryLimit, UseValgrind,
Context);
if (D.addSources(InputFilenames))
return 1;
AddToDriver PM(D);
if (StandardLinkOpts) {
PassManagerBuilder Builder;
Builder.Inliner = createFunctionInliningPass();
Builder.populateLTOPassManager(PM);
}
if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
PassManagerBuilder Builder;
if (OptLevelO1)
Builder.Inliner = createAlwaysInlinerLegacyPass();
else if (OptLevelOs || OptLevelO2)
Builder.Inliner = createFunctionInliningPass(
2, OptLevelOs ? 1 : 0, false);
else
Builder.Inliner = createFunctionInliningPass(275);
Builder.populateFunctionPassManager(PM);
Builder.populateModulePassManager(PM);
}
for (const PassInfo *PI : PassList)
D.addPass(PI->getPassArgument());
// Bugpoint has the ability of generating a plethora of core files, so to
// avoid filling up the disk, we prevent it
#ifndef DEBUG_BUGPOINT
sys::Process::PreventCoreFiles();
#endif
if (Error E = D.run()) {
errs() << toString(std::move(E));
return 1;
}
return 0;
}
| 31.972851 | 80 | 0.67563 | rhencke |
f6b7db89f95706cacaf98bde69476ecada5c9f8c | 3,271 | cpp | C++ | external/skia/src/gpu/SkGLContext.cpp | gordonjohnpatrick/XobotOS | 888ed3b8cc8d8e0a54b1858bfa5a3572545f4d2f | [
"Apache-2.0"
] | 263 | 2015-01-04T16:39:18.000Z | 2022-01-05T17:52:38.000Z | external/skia/src/gpu/SkGLContext.cpp | DooMLoRD/XobotOS | f20db6295e878a2f298c5e3896528e240785805b | [
"Apache-2.0"
] | 3 | 2015-09-06T09:06:39.000Z | 2019-10-15T00:52:49.000Z | external/skia/src/gpu/SkGLContext.cpp | DooMLoRD/XobotOS | f20db6295e878a2f298c5e3896528e240785805b | [
"Apache-2.0"
] | 105 | 2015-01-11T11:45:12.000Z | 2022-02-22T07:26:36.000Z |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkGLContext.h"
SkGLContext::SkGLContext()
: fFBO(0)
, fGL(NULL) {
}
SkGLContext::~SkGLContext() {
SkSafeUnref(fGL);
}
bool SkGLContext::init(int width, int height) {
if (fGL) {
fGL->unref();
this->destroyGLContext();
}
fGL = this->createGLContext();
if (fGL) {
// clear any existing GL erorrs
GrGLenum error;
do {
error = SK_GL(*this, GetError());
} while (GR_GL_NO_ERROR != error);
GrGLuint cbID;
GrGLuint dsID;
SK_GL(*this, GenFramebuffers(1, &fFBO));
SK_GL(*this, BindFramebuffer(GR_GL_FRAMEBUFFER, fFBO));
SK_GL(*this, GenRenderbuffers(1, &cbID));
SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, cbID));
if (fGL->supportsES2()) {
SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
GR_GL_RGBA8,
width, height));
} else {
SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
GR_GL_RGBA,
width, height));
}
SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
GR_GL_COLOR_ATTACHMENT0,
GR_GL_RENDERBUFFER,
cbID));
SK_GL(*this, GenRenderbuffers(1, &dsID));
SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, dsID));
if (fGL->supportsES2()) {
SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
GR_GL_STENCIL_INDEX8,
width, height));
} else {
SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
GR_GL_DEPTH_STENCIL,
width, height));
SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
GR_GL_DEPTH_ATTACHMENT,
GR_GL_RENDERBUFFER,
dsID));
}
SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
GR_GL_STENCIL_ATTACHMENT,
GR_GL_RENDERBUFFER,
dsID));
SK_GL(*this, Viewport(0, 0, width, height));
SK_GL(*this, ClearStencil(0));
SK_GL(*this, Clear(GR_GL_STENCIL_BUFFER_BIT));
error = SK_GL(*this, GetError());
GrGLenum status =
SK_GL(*this, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
if (GR_GL_FRAMEBUFFER_COMPLETE != status ||
GR_GL_NO_ERROR != error) {
fFBO = 0;
fGL->unref();
fGL = NULL;
this->destroyGLContext();
return false;
} else {
return true;
}
}
return false;
}
| 35.945055 | 73 | 0.46897 | gordonjohnpatrick |
f6b898fa886a2a244ec1a0929b6e5630d3ea60e9 | 3,924 | cpp | C++ | vstgui/tests/unittest/uidescription/uiviewcreator/uiviewswitchcontainercreator_test.cpp | GizzZmo/vstgui | 477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e | [
"BSD-3-Clause"
] | 205 | 2019-06-09T18:40:27.000Z | 2022-03-24T01:53:49.000Z | vstgui/tests/unittest/uidescription/uiviewcreator/uiviewswitchcontainercreator_test.cpp | GizzZmo/vstgui | 477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e | [
"BSD-3-Clause"
] | 9 | 2019-12-23T17:46:30.000Z | 2022-02-09T14:40:53.000Z | vstgui/tests/unittest/uidescription/uiviewcreator/uiviewswitchcontainercreator_test.cpp | GizzZmo/vstgui | 477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e | [
"BSD-3-Clause"
] | 30 | 2019-06-11T04:05:46.000Z | 2022-03-29T15:52:14.000Z | // This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "../../unittests.h"
#include "../../../../uidescription/uiviewfactory.h"
#include "../../../../uidescription/uiattributes.h"
#include "../../../../uidescription/detail/uiviewcreatorattributes.h"
#include "../../../../uidescription/uiviewswitchcontainer.h"
#include "../../../../lib/cstring.h"
#include "helpers.h"
namespace VSTGUI {
using namespace UIViewCreator;
TESTCASE(UIViewSwitchContainerCreatorTest,
TEST(templateNames,
DummyUIDescription uidesc;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrTemplateNames, "temp1,temp2", &uidesc, [] (UIViewSwitchContainer* v) {
auto controller = dynamic_cast<UIDescriptionViewSwitchController*> (v->getController ());
EXPECT(controller);
std::string str;
controller->getTemplateNames(str);
return str == "temp1,temp2";
});
);
TEST(templateSwitchControl,
DummyUIDescription uidesc;
uidesc.tag = 12345;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrTemplateSwitchControl, kTagName, &uidesc, [&] (UIViewSwitchContainer* v) {
auto controller = dynamic_cast<UIDescriptionViewSwitchController*> (v->getController ());
EXPECT(controller);
return controller->getSwitchControlTag() == uidesc.tag;
}, true);
);
TEST(animationStyle,
DummyUIDescription uidesc;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationStyle, "fade", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getAnimationStyle() == UIViewSwitchContainer::kFadeInOut;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationStyle, "move", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getAnimationStyle() == UIViewSwitchContainer::kMoveInOut;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationStyle, "push", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getAnimationStyle() == UIViewSwitchContainer::kPushInOut;
});
);
TEST(animationTime,
DummyUIDescription uidesc;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTime, 1234, &uidesc, [] (UIViewSwitchContainer* v) {
return v->getAnimationTime() == 1234;
});
);
TEST(animationStyleValues,
DummyUIDescription uidesc;
testPossibleValues (kUIViewSwitchContainer, kAttrAnimationStyle, &uidesc, {"fade", "move", "push"});
);
TEST(animationTimingFunction,
DummyUIDescription uidesc;
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "linear", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kLinear;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "easy-in", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kEasyIn;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "easy-out", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kEasyOut;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "easy-in-out", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kEasyInOut;
});
testAttribute<UIViewSwitchContainer>(kUIViewSwitchContainer, kAttrAnimationTimingFunction, "easy", &uidesc, [] (UIViewSwitchContainer* v) {
return v->getTimingFunction() == UIViewSwitchContainer::kEasy;
});
);
TEST(animationTimingFunctionValues,
DummyUIDescription uidesc;
testPossibleValues (kUIViewSwitchContainer, kAttrAnimationTimingFunction, &uidesc, {"linear", "easy-in", "easy-out", "easy-in-out", "easy"});
);
);
} // VSTGUI
| 43.120879 | 148 | 0.756371 | GizzZmo |
f6b9723d3c1fe3bb0fc528b8d869ef2a91e31de2 | 1,695 | hpp | C++ | headers/nnb/graphics/Text.hpp | bobismijnnaam/nutsnbolts | 40191668b0831c64ce23474b9886f8be888916b3 | [
"BSL-1.0",
"Zlib",
"MIT"
] | null | null | null | headers/nnb/graphics/Text.hpp | bobismijnnaam/nutsnbolts | 40191668b0831c64ce23474b9886f8be888916b3 | [
"BSL-1.0",
"Zlib",
"MIT"
] | null | null | null | headers/nnb/graphics/Text.hpp | bobismijnnaam/nutsnbolts | 40191668b0831c64ce23474b9886f8be888916b3 | [
"BSL-1.0",
"Zlib",
"MIT"
] | null | null | null | // File: Text.hpp
// Author: Bob Rubbens - Knights of the Compiler
// Creation date: 2014-07-21
// Contact: http://plusminos.nl - @broervanlisa - gmail (bobrubbens)
#ifndef NNB_TEXT_HPP
#define NNB_TEXT_HPP
// Public
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <string>
#include <memory>
// Private
#include "nnb/graphics/TextureContainer.hpp"
#include "nnb/graphics/Color.hpp"
#include "nnb/resources/CustomDeleters.hpp"
namespace nnb {
enum class HAlign {
LEFT,
CENTER,
RIGHT
} ;
enum class VAlign {
TOP,
CENTER,
BOTTOM
} ;
class Text {
public:
Text();
Text(SDL_Renderer* tgt_, bool autoCommit_ = true);
Text(const Text& other);
Text& operator=(const Text& rhs);
void setText(std::string text_);
void setFont(TTF_Font *font_);
void setPosition(int x_, int y_);
void setX(int x_);
void setY(int y_);
void setHAlign(HAlign align_);
void setVAlign(VAlign align_);
void setColor(SDL_Color clr_);
void setColor(int r, int g, int b);
void setColor(nnb::Color clr_);
void setAlpha(Uint8 alpha_);
void setAutoCommit(bool autoCommit_);
void calculateBounds();
void commit();
void render() const;
int getWidth() const;
int getHeight() const;
int getX() const;
int getY() const;
SDL_Rect getBounds() const;
private:
bool autoCommit;
int x = 0, y = 0;
TTF_Font *font = NULL;
std::string text = "";
HAlign halign;
VAlign valign;
nnb::TextureContainer txt;
SDL_Renderer *tgt;
SDL_Rect dst;
SDL_Color clr;
bool dirty = false;
std::unique_ptr<SDL_Texture, nnb::SDLDeleter> txtTexture;
} ;
}
#endif
| 20.178571 | 69 | 0.651327 | bobismijnnaam |
f6ba628ba26a5c181735eb62e94c57d964617200 | 1,196 | hh | C++ | src/include/simeng/SpecialFileDirGen.hh | ABagdia/SimEng | 63b52fbb6e07c75100e03a153191b9c548f537c5 | [
"Apache-2.0"
] | null | null | null | src/include/simeng/SpecialFileDirGen.hh | ABagdia/SimEng | 63b52fbb6e07c75100e03a153191b9c548f537c5 | [
"Apache-2.0"
] | null | null | null | src/include/simeng/SpecialFileDirGen.hh | ABagdia/SimEng | 63b52fbb6e07c75100e03a153191b9c548f537c5 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <fstream>
#include <string>
#include "simeng/version.hh"
#include "yaml-cpp/yaml.h"
namespace simeng {
class SpecialFileDirGen {
public:
/** Construct a SpecialFileDirGen class by reading in the YAML file and
* running it through checks and formatting. */
SpecialFileDirGen(YAML::Node config);
/** Removes all files inside the '/src.lib/kernel/specialFiles' directory. */
void RemoveExistingSFDir();
/** Creates necessary file structure to support needed special files inside
* the '/src.lib/kernel/specialFiles' directory. */
void GenerateSFDir();
private:
/** Path to the root of the SimEng special files directory. */
const std::string specialFilesDir_ =
SIMENG_SOURCE_DIR "/src/lib/kernel/specialFiles";
/** Values declared in YAML config file needed to create the Special Files
* Directory tree. */
uint64_t core_count;
uint64_t smt;
uint64_t socket_count;
float bogoMIPS;
std::string features;
std::string cpu_implementer;
uint64_t cpu_architecture;
std::string cpu_variant;
std::string cpu_part;
uint64_t cpu_revision;
uint64_t package_count;
}; // namespace SpecialFilesDirGen
} // namespace simeng | 27.181818 | 79 | 0.736622 | ABagdia |
f6bab752300a52ef41e8bebb4ef29bbca54b7f4b | 14,493 | cpp | C++ | deps/opende/src/matrix.cpp | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | 45 | 2015-07-17T10:14:22.000Z | 2022-03-30T19:25:36.000Z | deps/opende/src/matrix.cpp | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2017-07-20T21:04:49.000Z | 2017-10-19T19:32:38.000Z | deps/opende/src/matrix.cpp | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | 64 | 2015-04-18T07:10:14.000Z | 2022-02-21T13:15:41.000Z | /*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include <ode/common.h>
#include <ode/matrix.h>
#include "config.h"
#include "util.h"
// misc defines
#define ALLOCA dALLOCA16
void _dSetZero (dReal *a, int n)
{
dAASSERT (a && n >= 0);
dReal *acurr = a;
int ncurr = n;
while (ncurr > 0) {
*(acurr++) = 0;
--ncurr;
}
}
void _dSetValue (dReal *a, int n, dReal value)
{
dAASSERT (a && n >= 0);
dReal *acurr = a;
int ncurr = n;
while (ncurr > 0) {
*(acurr++) = value;
--ncurr;
}
}
void _dMultiply0 (dReal *A, const dReal *B, const dReal *C, int p, int q, int r)
{
dAASSERT (A && B && C && p>0 && q>0 && r>0);
const int qskip = dPAD(q);
const int rskip = dPAD(r);
dReal *aa = A;
const dReal *bb = B;
for (int i=p; i; aa+=rskip, bb+=qskip, --i) {
dReal *a = aa;
const dReal *cc = C, *ccend = C + r;
for (; cc != ccend; ++a, ++cc) {
dReal sum = REAL(0.0);
const dReal *c = cc;
const dReal *b = bb, *bend = bb + q;
for (; b != bend; c+=rskip, ++b) {
sum += (*b)*(*c);
}
(*a) = sum;
}
}
}
void _dMultiply1 (dReal *A, const dReal *B, const dReal *C, int p, int q, int r)
{
dAASSERT (A && B && C && p>0 && q>0 && r>0);
const int pskip = dPAD(p);
const int rskip = dPAD(r);
dReal *aa = A;
const dReal *bb = B, *bbend = B + p;
for (; bb != bbend; aa += rskip, ++bb) {
dReal *a = aa;
const dReal *cc = C, *ccend = C + r;
for (; cc != ccend; ++a, ++cc) {
dReal sum = REAL(0.0);
const dReal *b = bb, *c = cc;
for (int k=q; k; b+=pskip, c+=rskip, --k) {
sum += (*b)*(*c);
}
(*a) = sum;
}
}
}
void _dMultiply2 (dReal *A, const dReal *B, const dReal *C, int p, int q, int r)
{
dAASSERT (A && B && C && p>0 && q>0 && r>0);
const int rskip = dPAD(r);
const int qskip = dPAD(q);
dReal *aa = A;
const dReal *bb = B;
for (int i=p; i; aa+=rskip, bb+=qskip, --i) {
dReal *a = aa, *aend = aa + r;
const dReal *cc = C;
for (; a != aend; cc+=qskip, ++a) {
dReal sum = REAL(0.0);
const dReal *b = bb, *c = cc, *cend = cc + q;
for (; c != cend; ++b, ++c) {
sum += (*b)*(*c);
}
(*a) = sum;
}
}
}
int _dFactorCholesky (dReal *A, int n, void *tmpbuf/*[n]*/)
{
dAASSERT (n > 0 && A);
bool failure = false;
const int nskip = dPAD (n);
dReal *recip = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (n * sizeof(dReal));
dReal *aa = A;
for (int i=0; i<n; aa+=nskip, ++i) {
dReal *cc = aa;
{
const dReal *bb = A;
for (int j=0; j<i; bb+=nskip, ++cc, ++j) {
dReal sum = *cc;
const dReal *a = aa, *b = bb, *bend = bb + j;
for (; b != bend; ++a, ++b) {
sum -= (*a)*(*b);
}
*cc = sum * recip[j];
}
}
{
dReal sum = *cc;
dReal *a = aa, *aend = aa + i;
for (; a != aend; ++a) {
sum -= (*a)*(*a);
}
if (sum <= REAL(0.0)) {
failure = true;
break;
}
dReal sumsqrt = dSqrt(sum);
*cc = sumsqrt;
recip[i] = dRecip (sumsqrt);
}
}
return failure ? 0 : 1;
}
void _dSolveCholesky (const dReal *L, dReal *b, int n, void *tmpbuf/*[n]*/)
{
dAASSERT (n > 0 && L && b);
const int nskip = dPAD (n);
dReal *y = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (n*sizeof(dReal));
{
const dReal *ll = L;
for (int i=0; i<n; ll+=nskip, ++i) {
dReal sum = REAL(0.0);
for (int k=0; k < i; ++k) {
sum += ll[k]*y[k];
}
dIASSERT(ll[i] != dReal(0.0));
y[i] = (b[i]-sum)/ll[i];
}
}
{
const dReal *ll = L + (n - 1) * (nskip + 1);
for (int i=n-1; i>=0; ll-=nskip+1, --i) {
dReal sum = REAL(0.0);
const dReal *l = ll + nskip;
for (int k=i+1; k<n; l+=nskip, ++k) {
sum += (*l)*b[k];
}
dIASSERT(*ll != dReal(0.0));
b[i] = (y[i]-sum)/(*ll);
}
}
}
int _dInvertPDMatrix (const dReal *A, dReal *Ainv, int n, void *tmpbuf/*[nskip*(n+2)]*/)
{
dAASSERT (n > 0 && A && Ainv);
bool success = false;
size_t FactorCholesky_size = _dEstimateFactorCholeskyTmpbufSize(n);
size_t SolveCholesky_size = _dEstimateSolveCholeskyTmpbufSize(n);
size_t MaxCholesky_size = FactorCholesky_size > SolveCholesky_size ? FactorCholesky_size : SolveCholesky_size;
dIASSERT(MaxCholesky_size % sizeof(dReal) == 0);
const int nskip = dPAD (n);
const int nskip_mul_n = nskip*n;
dReal *tmp = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (MaxCholesky_size + (nskip + nskip_mul_n)*sizeof(dReal));
dReal *X = (dReal *)((char *)tmp + MaxCholesky_size);
dReal *L = X + nskip;
memcpy (L, A, nskip_mul_n*sizeof(dReal));
if (dFactorCholesky (L,n,tmp)) {
dSetZero (Ainv,nskip_mul_n); // make sure all padding elements set to 0
dReal *aa = Ainv, *xi = X, *xiend = X + n;
for (; xi != xiend; ++aa, ++xi) {
dSetZero(X, n);
*xi = REAL(1.0);
dSolveCholesky (L,X,n,tmp);
dReal *a = aa;
const dReal *x = X, *xend = X + n;
for (; x!=xend; a+=nskip, ++x) {
*a = *x;
}
}
success = true;
}
return success ? 1 : 0;
}
int _dIsPositiveDefinite (const dReal *A, int n, void *tmpbuf/*[nskip*(n+1)]*/)
{
dAASSERT (n > 0 && A);
size_t FactorCholesky_size = _dEstimateFactorCholeskyTmpbufSize(n);
dIASSERT(FactorCholesky_size % sizeof(dReal) == 0);
const int nskip = dPAD (n);
const int nskip_mul_n = nskip*n;
dReal *tmp = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (FactorCholesky_size + nskip_mul_n*sizeof(dReal));
dReal *Acopy = (dReal *)((char *)tmp + FactorCholesky_size);
memcpy (Acopy, A, nskip_mul_n * sizeof(dReal));
return dFactorCholesky (Acopy, n, tmp);
}
void _dVectorScale (dReal *a, const dReal *d, int n)
{
dAASSERT (a && d && n >= 0);
for (int i=0; i<n; i++) {
a[i] *= d[i];
}
}
void _dSolveLDLT (const dReal *L, const dReal *d, dReal *b, int n, int nskip)
{
dAASSERT (L && d && b && n > 0 && nskip >= n);
dSolveL1 (L,b,n,nskip);
dVectorScale (b,d,n);
dSolveL1T (L,b,n,nskip);
}
void _dLDLTAddTL (dReal *L, dReal *d, const dReal *a, int n, int nskip, void *tmpbuf/*[2*nskip]*/)
{
dAASSERT (L && d && a && n > 0 && nskip >= n);
if (n < 2) return;
dReal *W1 = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA ((2*nskip)*sizeof(dReal));
dReal *W2 = W1 + nskip;
W1[0] = REAL(0.0);
W2[0] = REAL(0.0);
for (int j=1; j<n; ++j) {
W1[j] = W2[j] = (dReal) (a[j] * M_SQRT1_2);
}
dReal W11 = (dReal) ((REAL(0.5)*a[0]+1)*M_SQRT1_2);
dReal W21 = (dReal) ((REAL(0.5)*a[0]-1)*M_SQRT1_2);
dReal alpha1 = REAL(1.0);
dReal alpha2 = REAL(1.0);
{
dReal dee = d[0];
dReal alphanew = alpha1 + (W11*W11)*dee;
dIASSERT(alphanew != dReal(0.0));
dee /= alphanew;
dReal gamma1 = W11 * dee;
dee *= alpha1;
alpha1 = alphanew;
alphanew = alpha2 - (W21*W21)*dee;
dee /= alphanew;
//dReal gamma2 = W21 * dee;
alpha2 = alphanew;
dReal k1 = REAL(1.0) - W21*gamma1;
dReal k2 = W21*gamma1*W11 - W21;
dReal *ll = L + nskip;
for (int p=1; p<n; ll+=nskip, ++p) {
dReal Wp = W1[p];
dReal ell = *ll;
W1[p] = Wp - W11*ell;
W2[p] = k1*Wp + k2*ell;
}
}
dReal *ll = L + (nskip + 1);
for (int j=1; j<n; ll+=nskip+1, ++j) {
dReal k1 = W1[j];
dReal k2 = W2[j];
dReal dee = d[j];
dReal alphanew = alpha1 + (k1*k1)*dee;
dIASSERT(alphanew != dReal(0.0));
dee /= alphanew;
dReal gamma1 = k1 * dee;
dee *= alpha1;
alpha1 = alphanew;
alphanew = alpha2 - (k2*k2)*dee;
dee /= alphanew;
dReal gamma2 = k2 * dee;
dee *= alpha2;
d[j] = dee;
alpha2 = alphanew;
dReal *l = ll + nskip;
for (int p=j+1; p<n; l+=nskip, ++p) {
dReal ell = *l;
dReal Wp = W1[p] - k1 * ell;
ell += gamma1 * Wp;
W1[p] = Wp;
Wp = W2[p] - k2 * ell;
ell -= gamma2 * Wp;
W2[p] = Wp;
*l = ell;
}
}
}
// macros for dLDLTRemove() for accessing A - either access the matrix
// directly or access it via row pointers. we are only supposed to reference
// the lower triangle of A (it is symmetric), but indexes i and j come from
// permutation vectors so they are not predictable. so do a test on the
// indexes - this should not slow things down too much, as we don't do this
// in an inner loop.
#define _GETA(i,j) (A[i][j])
//#define _GETA(i,j) (A[(i)*nskip+(j)])
#define GETA(i,j) ((i > j) ? _GETA(i,j) : _GETA(j,i))
void _dLDLTRemove (dReal **A, const int *p, dReal *L, dReal *d,
int /*n1*/, int n2, int r, int nskip, void *tmpbuf/*n2 + 2*nskip*/)
{
//dAASSERT(A && p && L && d && n1 > 0 && n2 > 0 && r >= 0 && r < n2 &&
//n1 >= n2 && nskip >= n1);
#ifndef dNODEBUG
for (int i=0; i<n2; ++i) dIASSERT(p[i] >= 0 && p[i] < n1);
#endif
if (r==n2-1) {
return; // deleting last row/col is easy
}
else {
size_t LDLTAddTL_size = _dEstimateLDLTAddTLTmpbufSize(nskip);
dIASSERT(LDLTAddTL_size % sizeof(dReal) == 0);
dReal *tmp = tmpbuf ? (dReal *)tmpbuf : (dReal*) ALLOCA (LDLTAddTL_size + n2 * sizeof(dReal));
if (r==0) {
dReal *a = (dReal *)((char *)tmp + LDLTAddTL_size);
const int p_0 = p[0];
for (int i=0; i<n2; ++i) {
a[i] = -GETA(p[i],p_0);
}
a[0] += REAL(1.0);
dLDLTAddTL (L,d,a,n2,nskip,tmp);
}
else {
dReal *t = (dReal *)((char *)tmp + LDLTAddTL_size);
{
dReal *Lcurr = L + r*nskip;
for (int i=0; i<r; ++Lcurr, ++i) {
dIASSERT(d[i] != dReal(0.0));
t[i] = *Lcurr / d[i];
}
}
dReal *a = t + r;
{
dReal *Lcurr = L + r*nskip;
const int *pp_r = p + r, p_r = *pp_r;
const int n2_minus_r = n2-r;
for (int i=0; i<n2_minus_r; Lcurr+=nskip,++i) {
a[i] = dDot(Lcurr,t,r) - GETA(pp_r[i],p_r);
}
}
a[0] += REAL(1.0);
dLDLTAddTL (L + r*nskip+r, d+r, a, n2-r, nskip, tmp);
}
}
// snip out row/column r from L and d
dRemoveRowCol (L,n2,nskip,r);
if (r < (n2-1)) memmove (d+r,d+r+1,(n2-r-1)*sizeof(dReal));
}
void _dRemoveRowCol (dReal *A, int n, int nskip, int r)
{
dAASSERT(A && n > 0 && nskip >= n && r >= 0 && r < n);
if (r >= n-1) return;
if (r > 0) {
{
const size_t move_size = (n-r-1)*sizeof(dReal);
dReal *Adst = A + r;
for (int i=0; i<r; Adst+=nskip,++i) {
dReal *Asrc = Adst + 1;
memmove (Adst,Asrc,move_size);
}
}
{
const size_t cpy_size = r*sizeof(dReal);
dReal *Adst = A + r * nskip;
for (int i=r; i<(n-1); ++i) {
dReal *Asrc = Adst + nskip;
memcpy (Adst,Asrc,cpy_size);
Adst = Asrc;
}
}
}
{
const size_t cpy_size = (n-r-1)*sizeof(dReal);
dReal *Adst = A + r * (nskip + 1);
for (int i=r; i<(n-1); ++i) {
dReal *Asrc = Adst + (nskip + 1);
memcpy (Adst,Asrc,cpy_size);
Adst = Asrc - 1;
}
}
}
#undef dSetZero
#undef dSetValue
//#undef dDot
#undef dMultiply0
#undef dMultiply1
#undef dMultiply2
#undef dFactorCholesky
#undef dSolveCholesky
#undef dInvertPDMatrix
#undef dIsPositiveDefinite
//#undef dFactorLDLT
//#undef dSolveL1
//#undef dSolveL1T
#undef dVectorScale
#undef dSolveLDLT
#undef dLDLTAddTL
#undef dLDLTRemove
#undef dRemoveRowCol
void dSetZero (dReal *a, int n)
{
_dSetZero (a, n);
}
void dSetValue (dReal *a, int n, dReal value)
{
_dSetValue (a, n, value);
}
// dReal dDot (const dReal *a, const dReal *b, int n);
void dMultiply0 (dReal *A, const dReal *B, const dReal *C, int p,int q,int r)
{
_dMultiply0 (A, B, C, p, q, r);
}
void dMultiply1 (dReal *A, const dReal *B, const dReal *C, int p,int q,int r)
{
_dMultiply1 (A, B, C, p, q, r);
}
void dMultiply2 (dReal *A, const dReal *B, const dReal *C, int p,int q,int r)
{
_dMultiply2 (A, B, C, p, q, r);
}
int dFactorCholesky (dReal *A, int n)
{
return _dFactorCholesky (A, n, NULL);
}
void dSolveCholesky (const dReal *L, dReal *b, int n)
{
_dSolveCholesky (L, b, n, NULL);
}
int dInvertPDMatrix (const dReal *A, dReal *Ainv, int n)
{
return _dInvertPDMatrix (A, Ainv, n, NULL);
}
int dIsPositiveDefinite (const dReal *A, int n)
{
return _dIsPositiveDefinite (A, n, NULL);
}
// void dFactorLDLT (dReal *A, dReal *d, int n, int nskip);
// void dSolveL1 (const dReal *L, dReal *b, int n, int nskip);
// void dSolveL1T (const dReal *L, dReal *b, int n, int nskip);
void dVectorScale (dReal *a, const dReal *d, int n)
{
_dVectorScale (a, d, n);
}
void dSolveLDLT (const dReal *L, const dReal *d, dReal *b, int n, int nskip)
{
_dSolveLDLT (L, d, b, n, nskip);
}
void dLDLTAddTL (dReal *L, dReal *d, const dReal *a, int n, int nskip)
{
_dLDLTAddTL (L, d, a, n, nskip, NULL);
}
void dLDLTRemove (dReal **A, const int *p, dReal *L, dReal *d, int n1, int n2, int r, int nskip)
{
_dLDLTRemove (A, p, L, d, n1, n2, r, nskip, NULL);
}
void dRemoveRowCol (dReal *A, int n, int nskip, int r)
{
_dRemoveRowCol (A, n, nskip, r);
}
| 27.19137 | 115 | 0.524598 | harderthan |
f6bfc219287580854a81114b9818fe52b11ae79d | 1,466 | cpp | C++ | test/std/utilities/time/time.cal/time.cal.weekday/time.cal.weekday.members/ctor.pass.cpp | AOSiP/platform_external_libcxx | eb2115113f10274c0d25523ba44c3c7373ea3209 | [
"MIT"
] | 15 | 2019-08-05T01:24:20.000Z | 2022-01-12T08:19:55.000Z | test/std/utilities/time/time.cal/time.cal.weekday/time.cal.weekday.members/ctor.pass.cpp | AOSiP/platform_external_libcxx | eb2115113f10274c0d25523ba44c3c7373ea3209 | [
"MIT"
] | 21 | 2020-02-05T11:09:56.000Z | 2020-03-26T18:09:09.000Z | test/std/utilities/time/time.cal/time.cal.weekday/time.cal.weekday.members/ctor.pass.cpp | AOSiP/platform_external_libcxx | eb2115113f10274c0d25523ba44c3c7373ea3209 | [
"MIT"
] | 14 | 2017-01-21T00:56:32.000Z | 2022-02-24T11:27:38.000Z | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14, c++17
// <chrono>
// class weekday;
// weekday() = default;
// explicit constexpr weekday(unsigned wd) noexcept;
// constexpr weekday(const sys_days& dp) noexcept;
// explicit constexpr weekday(const local_days& dp) noexcept;
//
// explicit constexpr operator unsigned() const noexcept;
// Effects: Constructs an object of type weekday by initializing m_ with m.
// The value held is unspecified if d is not in the range [0, 255].
#include <chrono>
#include <type_traits>
#include <cassert>
#include "test_macros.h"
int main()
{
using weekday = std::chrono::weekday;
ASSERT_NOEXCEPT(weekday{});
ASSERT_NOEXCEPT(weekday(1));
ASSERT_NOEXCEPT(static_cast<unsigned>(weekday(1)));
constexpr weekday m0{};
static_assert(static_cast<unsigned>(m0) == 0, "");
constexpr weekday m1{1};
static_assert(static_cast<unsigned>(m1) == 1, "");
for (unsigned i = 0; i <= 255; ++i)
{
weekday m(i);
assert(static_cast<unsigned>(m) == i);
}
// TODO - sys_days and local_days ctor tests
}
| 28.192308 | 80 | 0.579809 | AOSiP |
f6c10d358f79386e866cc417c1aa8ebf68cc00ec | 997 | cpp | C++ | liero/menu/menuItem.cpp | lauri-kaariainen/emscripten_openliero | ab3268237c7084e00f3bccb4442f0ad7762d8419 | [
"BSD-2-Clause"
] | null | null | null | liero/menu/menuItem.cpp | lauri-kaariainen/emscripten_openliero | ab3268237c7084e00f3bccb4442f0ad7762d8419 | [
"BSD-2-Clause"
] | 2 | 2015-02-11T09:43:33.000Z | 2015-02-11T17:57:58.000Z | liero/menu/menuItem.cpp | lauri-kaariainen/emscripten_openliero | ab3268237c7084e00f3bccb4442f0ad7762d8419 | [
"BSD-2-Clause"
] | null | null | null | #include "menuItem.hpp"
#include "../common.hpp"
#include "../gfx.hpp"
void MenuItem::draw(Common& common, int x, int y, bool selected, bool disabled, bool centered, int valueOffsetX)
{
int wid = common.font.getDims(string);
int valueWid = common.font.getDims(value);
if(centered)
x -= (wid >> 1);
if(selected)
{
drawRoundedBox(gfx.screenBmp, x, y, 0, 7, wid);
if(hasValue)
drawRoundedBox(gfx.screenBmp, x + valueOffsetX - (valueWid >> 1), y, 0, 7, valueWid);
}
else
{
common.font.drawText(gfx.screenBmp, string, x + 3, y + 2, 0);
if(hasValue)
common.font.drawText(gfx.screenBmp, value, x + valueOffsetX - (valueWid >> 1) + 3, y + 2, 0);
}
PalIdx c;
if(disabled)
c = disColour;
else if(selected)
c = disabled ? 7 : 168;
else
c = color;
common.font.drawText(gfx.screenBmp, string, x + 2, y + 1, c);
if(hasValue)
common.font.drawText(gfx.screenBmp, value, x + valueOffsetX - (valueWid >> 1) + 2, y + 1, c);
}
| 24.925 | 113 | 0.616851 | lauri-kaariainen |
f6c29374b28262912e0144e2a97440dd55987a66 | 844 | hpp | C++ | include/retirement.hpp | FORGIS98/budgetwarrior | ca4c79a7b9694a0db5c7fe11b1b4e9cba96a9971 | [
"MIT"
] | null | null | null | include/retirement.hpp | FORGIS98/budgetwarrior | ca4c79a7b9694a0db5c7fe11b1b4e9cba96a9971 | [
"MIT"
] | null | null | null | include/retirement.hpp | FORGIS98/budgetwarrior | ca4c79a7b9694a0db5c7fe11b1b4e9cba96a9971 | [
"MIT"
] | null | null | null | //=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <vector>
#include <string>
#include "module_traits.hpp"
#include "writer_fwd.hpp"
#include "date.hpp"
namespace budget {
struct retirement_module {
void load();
void handle(std::vector<std::string>& args);
};
template<>
struct module_traits<retirement_module> {
static constexpr const bool is_default = false;
static constexpr const char* command = "retirement";
};
float fi_ratio(budget::date d);
void retirement_status(budget::writer& w);
} //end of namespace budget
| 24.823529 | 73 | 0.598341 | FORGIS98 |
f6c2b9c2ec912ae60fbe2575ab6df525a15b65bd | 1,544 | cc | C++ | chrome/browser/android/webapk/webapk_metrics.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/android/webapk/webapk_metrics.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/android/webapk/webapk_metrics.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/webapk/webapk_metrics.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "chrome/browser/android/webapk/chrome_webapk_host.h"
namespace webapk {
const char kInstallDurationHistogram[] = "WebApk.Install.InstallDuration";
const char kInstallEventHistogram[] = "WebApk.Install.InstallEvent";
const char kInstallSourceHistogram[] = "WebApk.Install.InstallSource";
const char kInfoBarShownHistogram[] = "WebApk.Install.InfoBarShown";
const char kUserActionHistogram[] = "WebApk.Install.UserAction";
void TrackRequestTokenDuration(base::TimeDelta delta) {
UMA_HISTOGRAM_TIMES("WebApk.Install.RequestTokenDuration", delta);
}
void TrackInstallDuration(base::TimeDelta delta) {
UMA_HISTOGRAM_MEDIUM_TIMES(kInstallDurationHistogram, delta);
}
void TrackInstallEvent(InstallEvent event) {
UMA_HISTOGRAM_ENUMERATION(kInstallEventHistogram, event, INSTALL_EVENT_MAX);
}
void TrackInstallSource(InstallSource event) {
UMA_HISTOGRAM_ENUMERATION(kInstallSourceHistogram, event, INSTALL_SOURCE_MAX);
}
void TrackInstallInfoBarShown(InfoBarShown event) {
UMA_HISTOGRAM_ENUMERATION(kInfoBarShownHistogram, event,
WEBAPK_INFOBAR_SHOWN_MAX);
}
void TrackUserAction(UserAction event) {
UMA_HISTOGRAM_ENUMERATION(kUserActionHistogram, event, USER_ACTION_MAX);
}
} // namespace webapk
| 34.311111 | 80 | 0.799223 | metux |
f6c66c2b003609a8a897b37c776863a23407bbee | 18,259 | cc | C++ | paddle/fluid/inference/api/analysis_predictor_tester.cc | JingChunzhen/Paddle | 1bce7caabc1c5e55b1fa13edb19719c397803c43 | [
"Apache-2.0"
] | 2 | 2021-02-04T15:04:21.000Z | 2021-02-07T14:20:00.000Z | paddle/fluid/inference/api/analysis_predictor_tester.cc | hexieshenghuo/Paddle | 2497f4392fe60f4c72e9b7ff5de9b8b6117aacac | [
"Apache-2.0"
] | null | null | null | paddle/fluid/inference/api/analysis_predictor_tester.cc | hexieshenghuo/Paddle | 2497f4392fe60f4c72e9b7ff5de9b8b6117aacac | [
"Apache-2.0"
] | 1 | 2021-03-16T13:40:08.000Z | 2021-03-16T13:40:08.000Z | // Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/inference/api/analysis_predictor.h"
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <thread> // NOLINT
#include "paddle/fluid/framework/ir/pass.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/inference/api/helper.h"
#include "paddle/fluid/inference/api/paddle_inference_api.h"
#include "paddle/fluid/inference/tests/api/tester_helper.h"
#include "paddle/fluid/platform/cpu_info.h"
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/inference/api/mkldnn_quantizer.h"
#endif
DEFINE_string(dirname, "", "dirname to tests.");
namespace paddle {
TEST(AnalysisPredictor, analysis_off) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchIrOptim(false);
auto _predictor = CreatePaddlePredictor<AnalysisConfig>(config);
auto* predictor = static_cast<AnalysisPredictor*>(_predictor.get());
// Without analysis, the scope_ and sub_scope_ are created by predictor
// itself.
ASSERT_TRUE(predictor->scope_);
ASSERT_TRUE(predictor->sub_scope_);
ASSERT_EQ(predictor->scope_->parent(), nullptr);
ASSERT_EQ(predictor->sub_scope_->parent(), predictor->scope_.get());
// ir is turned off, so program shouldn't be optimized.
LOG(INFO) << "scope parameters " << predictor->scope_->LocalVarNames().size();
// 2. Dummy Input Data
int64_t data[4] = {1, 2, 3, 4};
PaddleTensor tensor;
tensor.shape = std::vector<int>({4, 1});
tensor.data.Reset(data, sizeof(data));
tensor.dtype = PaddleDType::INT64;
std::vector<PaddleTensor> inputs(4, tensor);
std::vector<PaddleTensor> outputs;
ASSERT_TRUE(predictor->Run(inputs, &outputs));
}
TEST(AnalysisPredictor, analysis_on) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchIrOptim(true);
#ifdef PADDLE_WITH_CUDA
config.EnableUseGpu(100, 0);
#else
config.DisableGpu();
#endif
auto _predictor = CreatePaddlePredictor<AnalysisConfig>(config);
auto* predictor = static_cast<AnalysisPredictor*>(_predictor.get());
ASSERT_TRUE(predictor->scope_);
ASSERT_TRUE(predictor->sub_scope_);
ASSERT_EQ(predictor->scope_->parent(), nullptr);
ASSERT_EQ(predictor->sub_scope_->parent(), predictor->scope_.get());
// 2. Dummy Input Data
int64_t data[4] = {1, 2, 3, 4};
PaddleTensor tensor;
tensor.shape = std::vector<int>({4, 1});
tensor.data.Reset(data, sizeof(data));
tensor.dtype = PaddleDType::INT64;
std::vector<PaddleTensor> inputs(4, tensor);
std::vector<PaddleTensor> outputs;
ASSERT_TRUE(predictor->Run(inputs, &outputs));
for (auto& output : outputs) {
LOG(INFO) << inference::DescribeTensor(output);
}
// compare with NativePredictor
auto naive_predictor =
CreatePaddlePredictor<NativeConfig>(config.ToNativeConfig());
std::vector<PaddleTensor> naive_outputs;
ASSERT_TRUE(naive_predictor->Run(inputs, &naive_outputs));
ASSERT_EQ(naive_outputs.size(), 1UL);
inference::CompareTensor(outputs.front(), naive_outputs.front());
}
TEST(AnalysisPredictor, ZeroCopy) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchUseFeedFetchOps(false);
auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
auto w0 = predictor->GetInputTensor("firstw");
auto w1 = predictor->GetInputTensor("secondw");
auto w2 = predictor->GetInputTensor("thirdw");
auto w3 = predictor->GetInputTensor("forthw");
w0->Reshape({4, 1});
w1->Reshape({4, 1});
w2->Reshape({4, 1});
w3->Reshape({4, 1});
auto* w0_data = w0->mutable_data<int64_t>(PaddlePlace::kCPU);
auto* w1_data = w1->mutable_data<int64_t>(PaddlePlace::kCPU);
auto* w2_data = w2->mutable_data<int64_t>(PaddlePlace::kCPU);
auto* w3_data = w3->mutable_data<int64_t>(PaddlePlace::kCPU);
for (int i = 0; i < 4; i++) {
w0_data[i] = i;
w1_data[i] = i;
w2_data[i] = i;
w3_data[i] = i;
}
predictor->ZeroCopyRun();
auto out = predictor->GetOutputTensor("fc_1.tmp_2");
PaddlePlace place;
int size = 0;
auto* out_data = out->data<float>(&place, &size);
LOG(INFO) << "output size: " << size / sizeof(float);
LOG(INFO) << "output_data: " << out_data;
predictor->TryShrinkMemory();
}
TEST(AnalysisPredictor, Clone) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchUseFeedFetchOps(true);
config.SwitchIrOptim(true);
std::vector<std::unique_ptr<PaddlePredictor>> predictors;
predictors.emplace_back(CreatePaddlePredictor(config));
LOG(INFO) << "************** to clone ************************";
const int num_threads = 3;
for (int i = 1; i < num_threads; i++) {
predictors.emplace_back(predictors.front()->Clone());
}
auto* root_scope =
static_cast<AnalysisPredictor*>(predictors[0].get())->scope();
ASSERT_FALSE(root_scope->kids().empty());
LOG(INFO) << "***** scope ******\n"
<< framework::GenScopeTreeDebugInfo(root_scope);
// 2. Dummy Input Data
int64_t data[4] = {1, 2, 3, 4};
PaddleTensor tensor;
tensor.shape = std::vector<int>({4, 1});
tensor.data.Reset(data, sizeof(data));
tensor.dtype = PaddleDType::INT64;
std::vector<PaddleTensor> inputs(4, tensor);
std::vector<PaddleTensor> outputs;
predictors[0]->Run(inputs, &outputs);
LOG(INFO) << "Run with single thread";
for (int i = 0; i < num_threads; i++) {
LOG(INFO) << "run predictor " << i;
ASSERT_TRUE(predictors[i]->Run(inputs, &outputs));
}
LOG(INFO) << "Run with multiple threads";
std::vector<std::thread> threads;
for (int i = 0; i < num_threads; i++) {
threads.emplace_back([&predictors, &inputs, i] {
LOG(INFO) << "thread #" << i << " running";
std::vector<PaddleTensor> outputs;
auto predictor = predictors.front()->Clone();
for (int j = 0; j < 10; j++) {
ASSERT_TRUE(predictor->Run(inputs, &outputs));
}
});
}
for (auto& t : threads) {
t.join();
}
}
// This function is not released yet, will fail on some machine.
// TODO(Superjomn) Turn on it latter.
/*
TEST(AnalysisPredictor, memory_optim) {
AnalysisConfig config(FLAGS_dirname);
config.DisableGpu();
config.EnableMemoryOptim(true);
config.SwitchIrDebug();
auto native_predictor =
CreatePaddlePredictor<NativeConfig>(config.ToNativeConfig());
// 2. Dummy Input Data
int64_t data[4] = {1, 2, 3, 4};
PaddleTensor tensor;
tensor.shape = std::vector<int>({4, 1});
tensor.data.Reset(data, sizeof(data));
tensor.dtype = PaddleDType::INT64;
std::vector<PaddleTensor> inputs(4, tensor);
std::vector<PaddleTensor> output, output1;
{
// The first predictor help to cache the memory optimize strategy.
auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
LOG(INFO) << "serialized program: " << predictor->GetSerializedProgram();
ASSERT_FALSE(predictor->GetSerializedProgram().empty());
// Run several times to check the parameters are not reused by mistake.
for (int i = 0; i < 5; i++) {
ASSERT_TRUE(predictor->Run(inputs, &output));
}
}
{
output.clear();
// The second predictor to perform memory optimization.
config.EnableMemoryOptim(false);
auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
// Run with memory optimization
ASSERT_TRUE(predictor->Run(inputs, &output));
}
// Run native
ASSERT_TRUE(native_predictor->Run(inputs, &output1));
LOG(INFO) << "the output " << inference::DescribeTensor(output.front());
LOG(INFO) << "the native output "
<< inference::DescribeTensor(output1.front());
inference::CompareResult(output, output1);
}
*/
#ifdef PADDLE_WITH_MKLDNN
class MkldnnQuantizerTest : public testing::Test {
public:
MkldnnQuantizerTest() {
AnalysisConfig config(FLAGS_dirname);
predictor = std::move(CreatePaddlePredictor(config));
auto* predictor_p = static_cast<AnalysisPredictor*>(predictor.get());
auto qconfig = new MkldnnQuantizerConfig();
mkldnn_quantizer.reset(
new AnalysisPredictor::MkldnnQuantizer(*predictor_p, qconfig));
}
std::pair<std::vector<int>, float> Histogram(
const framework::LoDTensor& var_tensor, float min_val, float max_val,
int num_bins) const {
return mkldnn_quantizer->Histogram(var_tensor, min_val, max_val, num_bins);
}
std::pair<bool, framework::LoDTensor> GetMaxScalingFactor(
const framework::LoDTensor& var_tensor, bool is_unsigned) const {
return mkldnn_quantizer->GetMaxScalingFactor(var_tensor, is_unsigned);
}
std::pair<bool, framework::LoDTensor> GetMaxChScalingFactor(
const framework::LoDTensor& var_tensor, bool is_unsigned) const {
return mkldnn_quantizer->GetMaxChScalingFactor(var_tensor, is_unsigned, 0);
}
std::pair<bool, framework::LoDTensor> GetKLScalingFactor(
const framework::LoDTensor& var_tensor, bool is_unsigned) const {
return mkldnn_quantizer->GetKLScalingFactor(var_tensor, is_unsigned);
}
protected:
std::unique_ptr<PaddlePredictor> predictor;
std::unique_ptr<AnalysisPredictor::MkldnnQuantizer> mkldnn_quantizer;
float abs_error = 1e-6;
static const std::array<float, 10> non_negative_values;
static const std::array<float, 10> positive_and_negative_values;
};
const std::array<float, 10> MkldnnQuantizerTest::non_negative_values = {
0.0158671, 0.026459, 0.0280772, 0.00962479, 0.0131628,
0.016704, 0.00118407, 0.00765726, 0.0123213, 0.00944741};
const std::array<float, 10> MkldnnQuantizerTest::positive_and_negative_values =
{-0.0482659, -0.0102493, -0.00794221, -0.00387115, -0.00674586,
-0.0495346, 0.0629528, -0.00531285, -0.0230353, 0.0269089};
TEST_F(MkldnnQuantizerTest, histogram_inverted_min_max) {
const auto& values = non_negative_values;
auto min_val = *std::min_element(values.begin(), values.end());
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
ASSERT_THROW(Histogram(var_tensor, max_val, min_val, 3),
platform::EnforceNotMet);
}
TEST_F(MkldnnQuantizerTest, histogram_non_negative_to_3) {
// all non-negative values
const auto& values = non_negative_values;
auto min_val = *std::min_element(values.begin(), values.end());
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
std::vector<int> histogram;
float bin_width;
std::tie(histogram, bin_width) = Histogram(var_tensor, min_val, max_val, 3);
ASSERT_NEAR(bin_width, std::abs(max_val - min_val) / 3.f, abs_error)
<< "Improperly calculated bin_width.";
ASSERT_EQ(histogram[0], 4);
ASSERT_EQ(histogram[1], 4);
ASSERT_EQ(histogram[2], 2);
}
TEST_F(MkldnnQuantizerTest, histogram_positive_and_negative_to_3) {
const auto& values = positive_and_negative_values;
auto min_val = *std::min_element(values.begin(), values.end());
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
std::vector<int> histogram;
float bin_width;
std::tie(histogram, bin_width) = Histogram(var_tensor, min_val, max_val, 3);
ASSERT_NEAR(bin_width, std::abs(max_val - min_val) / 3.0f, abs_error)
<< "Improperly calculated bin_width.";
ASSERT_EQ(histogram[0], 3);
ASSERT_EQ(histogram[1], 5);
ASSERT_EQ(histogram[2], 2);
}
TEST_F(MkldnnQuantizerTest, histogram_zero_bins) {
const auto& values = non_negative_values;
auto min_val = *std::min_element(values.begin(), values.end());
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
ASSERT_THROW(Histogram(var_tensor, min_val, max_val, 0),
platform::EnforceNotMet);
}
TEST_F(MkldnnQuantizerTest, histogram_empty) {
// empty tensor
ASSERT_THROW(Histogram({}, -1, 1, 1), platform::EnforceNotMet);
// zero tensor
framework::LoDTensor var_tensor;
var_tensor.Resize({0});
var_tensor.mutable_data<double>(platform::CPUPlace());
ASSERT_THROW(Histogram(var_tensor, -1, 1, 1), platform::EnforceNotMet);
}
TEST_F(MkldnnQuantizerTest, kl_scaling_factor_signed) {
const auto& values = positive_and_negative_values;
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetKLScalingFactor(var_tensor, false);
ASSERT_EQ(is_unsigned, false);
ASSERT_EQ(lod_tensor.numel(), 1);
ASSERT_NEAR(lod_tensor.data<double>()[0], 1.0 / 0.0899106152344, abs_error);
}
TEST_F(MkldnnQuantizerTest, max_scaling_factor_signed) {
const auto& values = positive_and_negative_values;
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetMaxScalingFactor(var_tensor, false);
ASSERT_EQ(is_unsigned, false);
ASSERT_EQ(lod_tensor.numel(), 1);
ASSERT_NEAR(lod_tensor.data<double>()[0], 1.0 / max_val, abs_error);
}
TEST_F(MkldnnQuantizerTest, max_scaling_factor_unsigned) {
const auto& values = non_negative_values;
auto max_val = *std::max_element(values.begin(), values.end());
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetMaxScalingFactor(var_tensor, true);
ASSERT_EQ(is_unsigned, true);
ASSERT_EQ(lod_tensor.numel(), 1);
ASSERT_NEAR(lod_tensor.data<double>()[0], 1.0 / max_val, abs_error);
}
TEST_F(MkldnnQuantizerTest, max_scaling_factor_chwise_unsigned) {
const auto& values = non_negative_values;
auto max_val = *std::max_element(values.begin(), values.end());
int channels = 3;
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(channels, 1, 1, values.size()));
for (int i = 0; i < channels; i++)
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()) +
i * values.size());
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetMaxChScalingFactor(var_tensor, true);
ASSERT_EQ(is_unsigned, true);
ASSERT_EQ(lod_tensor.numel(), channels);
for (int i = 0; i < channels; i++) {
ASSERT_NEAR(lod_tensor.data<double>()[i], 1.0 / max_val, abs_error);
}
}
TEST_F(MkldnnQuantizerTest, kl_scaling_factor_unsigned) {
const auto& values = non_negative_values;
framework::LoDTensor var_tensor;
var_tensor.Resize(framework::make_dim(values.size()));
std::copy(begin(values), end(values),
var_tensor.mutable_data<float>(platform::CPUPlace()));
bool is_unsigned;
framework::LoDTensor lod_tensor;
std::tie(is_unsigned, lod_tensor) = GetKLScalingFactor(var_tensor, true);
ASSERT_EQ(is_unsigned, true);
ASSERT_EQ(lod_tensor.numel(), 1);
ASSERT_NEAR(lod_tensor.data<double>()[0], 1.0 / 0.0252845321362, abs_error);
}
#endif
#ifdef PADDLE_WITH_CUDA
TEST(AnalysisPredictor, bf16_gpu_pass_strategy) {
AnalysisConfig config;
config.SetModel(FLAGS_dirname);
config.SwitchIrOptim(true);
config.EnableUseGpu(100, 0);
config.EnableMkldnnBfloat16();
#ifdef PADDLE_WITH_MKLDNN
if (platform::MayIUse(platform::cpu_isa_t::avx512_core))
ASSERT_EQ(config.mkldnn_bfloat16_enabled(), true);
else
ASSERT_EQ(config.mkldnn_bfloat16_enabled(), false);
#else
ASSERT_EQ(config.mkldnn_bfloat16_enabled(), false);
#endif
}
#endif
TEST(AnalysisPredictor, bf16_pass_strategy) {
std::vector<std::string> passes;
PassStrategy passStrategy(passes);
passStrategy.EnableMkldnnBfloat16();
}
} // namespace paddle
namespace paddle_infer {
TEST(Predictor, Run) {
Config config;
config.SetModel(FLAGS_dirname);
auto predictor = CreatePredictor(config);
auto w0 = predictor->GetInputHandle("firstw");
auto w1 = predictor->GetInputHandle("secondw");
auto w2 = predictor->GetInputHandle("thirdw");
auto w3 = predictor->GetInputHandle("forthw");
w0->Reshape({4, 1});
w1->Reshape({4, 1});
w2->Reshape({4, 1});
w3->Reshape({4, 1});
auto* w0_data = w0->mutable_data<int64_t>(PlaceType::kCPU);
auto* w1_data = w1->mutable_data<int64_t>(PlaceType::kCPU);
auto* w2_data = w2->mutable_data<int64_t>(PlaceType::kCPU);
auto* w3_data = w3->mutable_data<int64_t>(PlaceType::kCPU);
for (int i = 0; i < 4; i++) {
w0_data[i] = i;
w1_data[i] = i;
w2_data[i] = i;
w3_data[i] = i;
}
predictor->Run();
auto out = predictor->GetOutputHandle("fc_1.tmp_2");
PlaceType place;
int size = 0;
out->data<float>(&place, &size);
LOG(INFO) << "output size: " << size / sizeof(float);
predictor->TryShrinkMemory();
}
} // namespace paddle_infer
| 32.839928 | 80 | 0.708418 | JingChunzhen |
f6c6e83606df8fbe4bde2fb8f25789dc95d301c1 | 20,338 | cpp | C++ | velox/expression/tests/CastExprTest.cpp | littleeleventhwolf/velox | 856d1f91f7da09a9313c893e12adb0070ddd3fb9 | [
"Apache-2.0"
] | null | null | null | velox/expression/tests/CastExprTest.cpp | littleeleventhwolf/velox | 856d1f91f7da09a9313c893e12adb0070ddd3fb9 | [
"Apache-2.0"
] | 23 | 2021-11-11T12:38:17.000Z | 2022-01-28T10:59:38.000Z | velox/expression/tests/CastExprTest.cpp | littleeleventhwolf/velox | 856d1f91f7da09a9313c893e12adb0070ddd3fb9 | [
"Apache-2.0"
] | 8 | 2021-11-11T12:26:21.000Z | 2022-01-12T08:58:32.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <limits>
#include "velox/buffer/Buffer.h"
#include "velox/common/memory/Memory.h"
#include "velox/expression/ControlExpr.h"
#include "velox/expression/VectorFunction.h"
#include "velox/functions/prestosql/tests/FunctionBaseTest.h"
#include "velox/type/Type.h"
#include "velox/vector/BaseVector.h"
#include "velox/vector/TypeAliases.h"
using namespace facebook::velox;
using namespace facebook::velox::test;
namespace {
/// Wraps input in a dictionary that reverses the order of rows.
class TestingDictionaryFunction : public exec::VectorFunction {
public:
bool isDefaultNullBehavior() const override {
return false;
}
void apply(
const SelectivityVector& rows,
std::vector<VectorPtr>& args,
const TypePtr& /* outputType */,
exec::EvalCtx* context,
VectorPtr* result) const override {
VELOX_CHECK(rows.isAllSelected());
const auto size = rows.size();
auto indices = makeIndicesInReverse(size, context->pool());
*result = BaseVector::wrapInDictionary(
BufferPtr(nullptr), indices, size, args[0]);
}
static std::vector<std::shared_ptr<exec::FunctionSignature>> signatures() {
// T, integer -> T
return {exec::FunctionSignatureBuilder()
.typeVariable("T")
.returnType("T")
.argumentType("T")
.build()};
}
};
} // namespace
class CastExprTest : public functions::test::FunctionBaseTest {
protected:
CastExprTest() {
exec::registerVectorFunction(
"testing_dictionary",
TestingDictionaryFunction::signatures(),
std::make_unique<TestingDictionaryFunction>());
}
void setCastIntByTruncate(bool value) {
queryCtx_->setConfigOverridesUnsafe({
{core::QueryConfig::kCastIntByTruncate, std::to_string(value)},
});
}
void setCastMatchStructByName(bool value) {
queryCtx_->setConfigOverridesUnsafe({
{core::QueryConfig::kCastMatchStructByName, std::to_string(value)},
});
}
void setTimezone(const std::string& value) {
queryCtx_->setConfigOverridesUnsafe({
{core::QueryConfig::kSessionTimezone, value},
{core::QueryConfig::kAdjustTimestampToTimezone, "true"},
});
}
std::shared_ptr<core::CastTypedExpr> makeCastExpr(
const std::shared_ptr<const core::ITypedExpr>& input,
const TypePtr& toType,
bool nullOnFailure) {
std::vector<std::shared_ptr<const core::ITypedExpr>> inputs = {input};
return std::make_shared<core::CastTypedExpr>(toType, inputs, nullOnFailure);
}
void testComplexCast(
const std::string& fromExpression,
const VectorPtr& data,
const VectorPtr& expected,
bool nullOnFailure = false) {
auto rowVector = makeRowVector({data});
auto rowType = std::dynamic_pointer_cast<const RowType>(rowVector->type());
auto castExpr = makeCastExpr(
makeTypedExpr(fromExpression, rowType),
expected->type(),
nullOnFailure);
exec::ExprSet exprSet({castExpr}, &execCtx_);
const auto size = data->size();
SelectivityVector rows(size);
std::vector<VectorPtr> result(1);
{
exec::EvalCtx evalCtx(&execCtx_, &exprSet, rowVector.get());
exprSet.eval(rows, &evalCtx, &result);
assertEqualVectors(expected, result[0]);
}
// Test constant input.
{
// Use last element for constant.
const auto index = size - 1;
auto constantData = BaseVector::wrapInConstant(size, index, data);
auto constantRow = makeRowVector({constantData});
exec::EvalCtx evalCtx(&execCtx_, &exprSet, constantRow.get());
exprSet.eval(rows, &evalCtx, &result);
assertEqualVectors(
BaseVector::wrapInConstant(size, index, expected), result[0]);
}
// Test dictionary input. It is not sufficient to wrap input in a dictionary
// as it will be peeled off before calling "cast". Apply
// testing_dictionary function to input to ensure that "cast" receives
// dictionary input.
{
auto dictionaryCastExpr = makeCastExpr(
makeTypedExpr(
fmt::format("testing_dictionary({})", fromExpression), rowType),
expected->type(),
nullOnFailure);
exec::ExprSet dictionaryExprSet({dictionaryCastExpr}, &execCtx_);
exec::EvalCtx evalCtx(&execCtx_, &dictionaryExprSet, rowVector.get());
dictionaryExprSet.eval(rows, &evalCtx, &result);
auto indices = ::makeIndicesInReverse(size, pool());
assertEqualVectors(wrapInDictionary(indices, size, expected), result[0]);
}
}
/**
* @tparam From Source type for cast
* @tparam To Destination type for cast
* @param typeString Cast type in string
* @param input Input vector of type From
* @param expectedResult Expected output vector of type To
* @param inputNulls Input null indexes
* @param expectedNulls Expected output null indexes
*/
template <typename TFrom, typename TTo>
void testCast(
const std::string& typeString,
std::vector<std::optional<TFrom>> input,
std::vector<std::optional<TTo>> expectedResult,
bool expectFailure = false,
bool tryCast = false) {
std::vector<TFrom> rawInput(input.size());
for (auto index = 0; index < input.size(); index++) {
if (input[index].has_value()) {
rawInput[index] = input[index].value();
}
}
// Create input vector using values and nulls
auto inputVector = makeFlatVector(rawInput);
for (auto index = 0; index < input.size(); index++) {
if (!input[index].has_value()) {
inputVector->setNull(index, true);
}
}
auto rowVector = makeRowVector({inputVector});
std::string castFunction = tryCast ? "try_cast" : "cast";
if (expectFailure) {
EXPECT_THROW(
evaluate<FlatVector<typename CppToType<TTo>::NativeType>>(
castFunction + "(c0 as " + typeString + ")", rowVector),
std::invalid_argument);
return;
}
// run try cast and get the result vector
auto result = evaluate<FlatVector<typename CppToType<TTo>::NativeType>>(
castFunction + "(c0 as " + typeString + ")", rowVector);
std::string msg;
// Compare the values and nulls in the output with expected
for (int index = 0; index < input.size(); index++) {
if (expectedResult[index].has_value()) {
EXPECT_TRUE(
compareValues(result->valueAt(index), expectedResult[index], msg))
<< "values at index " << index << " do not match!" << msg;
} else {
EXPECT_TRUE(result->isNullAt(index)) << " at index " << index;
}
}
}
};
TEST_F(CastExprTest, basics) {
// Testing non-null or error cases
const std::vector<std::optional<int32_t>> ii = {1, 2, 3, 100, -100};
const std::vector<std::optional<double>> oo = {1.0, 2.0, 3.0, 100.0, -100.0};
testCast<int32_t, double>(
"double", {1, 2, 3, 100, -100}, {1.0, 2.0, 3.0, 100.0, -100.0});
testCast<int32_t, std::string>(
"string", {1, 2, 3, 100, -100}, {"1", "2", "3", "100", "-100"});
testCast<std::string, int8_t>(
"tinyint", {"1", "2", "3", "100", "-100"}, {1, 2, 3, 100, -100});
testCast<double, int>(
"int", {1.888, 2.5, 3.6, 100.44, -100.101}, {2, 3, 4, 100, -100});
testCast<double, double>(
"double",
{1.888, 2.5, 3.6, 100.44, -100.101},
{1.888, 2.5, 3.6, 100.44, -100.101});
testCast<double, std::string>(
"string",
{1.888, 2.5, 3.6, 100.44, -100.101},
{"1.888", "2.5", "3.6", "100.44", "-100.101"});
testCast<double, double>(
"double",
{1.888, 2.5, 3.6, 100.44, -100.101},
{1.888, 2.5, 3.6, 100.44, -100.101});
testCast<double, float>(
"float",
{1.888, 2.5, 3.6, 100.44, -100.101},
{1.888, 2.5, 3.6, 100.44, -100.101});
testCast<bool, std::string>("string", {true, false}, {"true", "false"});
}
TEST_F(CastExprTest, timestamp) {
testCast<std::string, Timestamp>(
"timestamp",
{
"1970-01-01",
"2000-01-01",
"1970-01-01 00:00:00",
"2000-01-01 12:21:56",
"1970-01-01 00:00:00-02:00",
std::nullopt,
},
{
Timestamp(0, 0),
Timestamp(946684800, 0),
Timestamp(0, 0),
Timestamp(946729316, 0),
Timestamp(7200, 0),
std::nullopt,
});
}
TEST_F(CastExprTest, timestampInvalid) {
testCast<int8_t, Timestamp>("timestamp", {12}, {Timestamp(0, 0)}, true);
testCast<int16_t, Timestamp>("timestamp", {1234}, {Timestamp(0, 0)}, true);
testCast<int32_t, Timestamp>("timestamp", {1234}, {Timestamp(0, 0)}, true);
testCast<int64_t, Timestamp>("timestamp", {1234}, {Timestamp(0, 0)}, true);
testCast<float, Timestamp>("timestamp", {12.99}, {Timestamp(0, 0)}, true);
testCast<double, Timestamp>("timestamp", {12.99}, {Timestamp(0, 0)}, true);
}
TEST_F(CastExprTest, timestampAdjustToTimezone) {
setTimezone("America/Los_Angeles");
// Expect unix epochs to be converted to LA timezone (8h offset).
testCast<std::string, Timestamp>(
"timestamp",
{
"1970-01-01",
"2000-01-01",
"1969-12-31 16:00:00",
"2000-01-01 12:21:56",
"1970-01-01 00:00:00+14:00",
std::nullopt,
"2000-05-01", // daylight savings - 7h offset.
},
{
Timestamp(28800, 0),
Timestamp(946713600, 0),
Timestamp(0, 0),
Timestamp(946758116, 0),
Timestamp(-21600, 0),
std::nullopt,
Timestamp(957164400, 0),
});
// Empty timezone is assumed to be GMT.
setTimezone("");
testCast<std::string, Timestamp>(
"timestamp", {"1970-01-01"}, {Timestamp(0, 0)});
}
TEST_F(CastExprTest, timestampAdjustToTimezoneInvalid) {
auto testFunc = [&]() {
testCast<std::string, Timestamp>(
"timestamp", {"1970-01-01"}, {Timestamp(1, 0)});
};
setTimezone("bla");
EXPECT_THROW(testFunc(), std::runtime_error);
}
TEST_F(CastExprTest, date) {
testCast<std::string, Date>(
"date",
{
"1970-01-01",
"2020-01-01",
"2135-11-09",
"1969-12-27",
"1812-04-15",
"1920-01-02",
std::nullopt,
},
{
Date(0),
Date(18262),
Date(60577),
Date(-5),
Date(-57604),
Date(-18262),
std::nullopt,
});
}
TEST_F(CastExprTest, invalidDate) {
testCast<int8_t, Date>("date", {12}, {Date(0)}, true);
testCast<int16_t, Date>("date", {1234}, {Date(0)}, true);
testCast<int32_t, Date>("date", {1234}, {Date(0)}, true);
testCast<int64_t, Date>("date", {1234}, {Date(0)}, true);
testCast<float, Date>("date", {12.99}, {Date(0)}, true);
testCast<double, Date>("date", {12.99}, {Date(0)}, true);
// Parsing an ill-formated date.
testCast<std::string, Date>("date", {"2012-Oct-23"}, {Date(0)}, true);
}
TEST_F(CastExprTest, truncateVsRound) {
// Testing truncate vs round cast from double to int.
setCastIntByTruncate(true);
testCast<double, int>(
"int", {1.888, 2.5, 3.6, 100.44, -100.101}, {1, 2, 3, 100, -100});
testCast<double, int8_t>(
"tinyint",
{1,
256,
257,
2147483646,
2147483647,
2147483648,
-2147483646,
-2147483647,
-2147483648,
-2147483649},
{1, 0, 1, -2, -1, -1, 2, 1, 0, 0});
setCastIntByTruncate(false);
testCast<double, int>(
"int", {1.888, 2.5, 3.6, 100.44, -100.101}, {2, 3, 4, 100, -100});
testCast<int8_t, int32_t>("int", {111, 2, 3, 10, -10}, {111, 2, 3, 10, -10});
setCastIntByTruncate(true);
testCast<int32_t, int8_t>(
"tinyint", {1111111, 2, 3, 1000, -100101}, {71, 2, 3, -24, -5});
setCastIntByTruncate(false);
EXPECT_THROW(
(testCast<int32_t, int8_t>(
"tinyint", {1111111, 2, 3, 1000, -100101}, {71, 2, 3, -24, -5})),
std::invalid_argument);
}
TEST_F(CastExprTest, nullInputs) {
// Testing null inputs
testCast<double, double>(
"double",
{std::nullopt, std::nullopt, 3.6, 100.44, std::nullopt},
{std::nullopt, std::nullopt, 3.6, 100.44, std::nullopt});
testCast<double, float>(
"float",
{std::nullopt, 2.5, 3.6, 100.44, std::nullopt},
{std::nullopt, 2.5, 3.6, 100.44, std::nullopt});
testCast<double, std::string>(
"string",
{1.888, std::nullopt, std::nullopt, std::nullopt, -100.101},
{"1.888", std::nullopt, std::nullopt, std::nullopt, "-100.101"});
}
TEST_F(CastExprTest, errorHandling) {
// Making sure error cases lead to null outputs
testCast<std::string, int8_t>(
"tinyint",
{"1abc", "2", "3", "100", std::nullopt},
{std::nullopt, 2, 3, 100, std::nullopt},
false,
true);
setCastIntByTruncate(true);
testCast<std::string, int8_t>(
"tinyint",
{"-",
"-0",
" @w 123",
"123 ",
" 122",
"",
"-12-3",
"125.5",
"1234",
"-129",
"127",
"-128"},
{std::nullopt,
0,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
127,
-128},
false,
true);
testCast<double, int>(
"integer",
{1e12, 2.5, 3.6, 100.44, -100.101},
{std::numeric_limits<int32_t>::max(), 2, 3, 100, -100},
false,
true);
setCastIntByTruncate(false);
testCast<double, int>(
"int", {1.888, 2.5, 3.6, 100.44, -100.101}, {2, 3, 4, 100, -100});
testCast<std::string, int8_t>(
"tinyint", {"1abc", "2", "3", "100", "-100"}, {1, 2, 3, 100, -100}, true);
testCast<std::string, int8_t>(
"tinyint", {"1", "2", "3", "100", "-100.5"}, {1, 2, 3, 100, -100}, true);
}
constexpr vector_size_t kVectorSize = 1'000;
TEST_F(CastExprTest, mapCast) {
auto sizeAt = [](vector_size_t row) { return row % 5; };
auto keyAt = [](vector_size_t row) { return row % 11; };
auto valueAt = [](vector_size_t row) { return row % 13; };
auto inputMap = makeMapVector<int64_t, int64_t>(
kVectorSize, sizeAt, keyAt, valueAt, nullEvery(3));
// Cast map<bigint, bigint> -> map<integer, double>.
{
auto expectedMap = makeMapVector<int32_t, double>(
kVectorSize, sizeAt, keyAt, valueAt, nullEvery(3));
testComplexCast("c0", inputMap, expectedMap);
}
// Cast map<bigint, bigint> -> map<bigint, varchar>.
{
auto valueAtString = [valueAt](vector_size_t row) {
return StringView(folly::to<std::string>(valueAt(row)));
};
auto expectedMap = makeMapVector<int64_t, StringView>(
kVectorSize, sizeAt, keyAt, valueAtString, nullEvery(3));
testComplexCast("c0", inputMap, expectedMap);
}
// Cast map<bigint, bigint> -> map<varchar, bigint>.
{
auto keyAtString = [&](vector_size_t row) {
return StringView(folly::to<std::string>(keyAt(row)));
};
auto expectedMap = makeMapVector<StringView, int64_t>(
kVectorSize, sizeAt, keyAtString, valueAt, nullEvery(3));
testComplexCast("c0", inputMap, expectedMap);
}
// null values
{
auto inputWithNullValues = makeMapVector<int64_t, int64_t>(
kVectorSize, sizeAt, keyAt, valueAt, nullEvery(3), nullEvery(7));
auto expectedMap = makeMapVector<int32_t, double>(
kVectorSize, sizeAt, keyAt, valueAt, nullEvery(3), nullEvery(7));
testComplexCast("c0", inputWithNullValues, expectedMap);
}
}
TEST_F(CastExprTest, arrayCast) {
auto sizeAt = [](vector_size_t /* row */) { return 7; };
auto valueAt = [](vector_size_t /* row */, vector_size_t idx) {
return 1 + idx;
};
auto arrayVector =
makeArrayVector<double>(kVectorSize, sizeAt, valueAt, nullEvery(3));
// Cast array<double> -> array<bigint>.
{
auto expected =
makeArrayVector<int64_t>(kVectorSize, sizeAt, valueAt, nullEvery(3));
testComplexCast("c0", arrayVector, expected);
}
// Cast array<double> -> array<varchar>.
{
auto valueAtString = [valueAt](vector_size_t row, vector_size_t idx) {
return StringView(folly::to<std::string>(valueAt(row, idx)));
};
auto expected = makeArrayVector<StringView>(
kVectorSize, sizeAt, valueAtString, nullEvery(3));
testComplexCast("c0", arrayVector, expected);
}
}
TEST_F(CastExprTest, rowCast) {
auto valueAt = [](vector_size_t row) { return double(1 + row); };
auto valueAtInt = [](vector_size_t row) { return int64_t(1 + row); };
auto doubleVectorNullEvery3 =
makeFlatVector<double>(kVectorSize, valueAt, nullEvery(3));
auto intVectorNullEvery11 =
makeFlatVector<int64_t>(kVectorSize, valueAtInt, nullEvery(11));
auto doubleVectorNullEvery11 =
makeFlatVector<double>(kVectorSize, valueAt, nullEvery(11));
auto intVectorNullEvery3 =
makeFlatVector<int64_t>(kVectorSize, valueAtInt, nullEvery(3));
auto rowVector = makeRowVector(
{intVectorNullEvery11, doubleVectorNullEvery3}, nullEvery(5));
setCastMatchStructByName(false);
// Position-based cast: ROW(c0: bigint, c1: double) -> ROW(c0: double, c1:
// bigint)
{
auto expectedRowVector = makeRowVector(
{doubleVectorNullEvery11, intVectorNullEvery3}, nullEvery(5));
testComplexCast("c0", rowVector, expectedRowVector);
}
// Position-based cast: ROW(c0: bigint, c1: double) -> ROW(a: double, b:
// bigint)
{
auto expectedRowVector = makeRowVector(
{"a", "b"},
{doubleVectorNullEvery11, intVectorNullEvery3},
nullEvery(5));
testComplexCast("c0", rowVector, expectedRowVector);
}
// Position-based cast: ROW(c0: bigint, c1: double) -> ROW(c0: double)
{
auto expectedRowVector =
makeRowVector({doubleVectorNullEvery11}, nullEvery(5));
testComplexCast("c0", rowVector, expectedRowVector);
}
// Name-based cast: ROW(c0: bigint, c1: double) -> ROW(c0: double) dropping
// b
setCastMatchStructByName(true);
{
auto intVectorNullAll = makeFlatVector<int64_t>(
kVectorSize, valueAtInt, [](vector_size_t /* row */) { return true; });
auto expectedRowVector = makeRowVector(
{"c0", "b"}, {doubleVectorNullEvery11, intVectorNullAll}, nullEvery(5));
testComplexCast("c0", rowVector, expectedRowVector);
}
}
TEST_F(CastExprTest, nulls) {
auto input =
makeFlatVector<int32_t>(kVectorSize, [](auto row) { return row; });
auto allNulls = makeFlatVector<int32_t>(
kVectorSize, [](auto row) { return row; }, nullEvery(1));
auto result = evaluate<FlatVector<int16_t>>(
"cast(if(c0 % 2 = 0, c1, c0) as smallint)",
makeRowVector({input, allNulls}));
auto expectedResult = makeFlatVector<int16_t>(
kVectorSize, [](auto row) { return row; }, nullEvery(2));
assertEqualVectors(expectedResult, result);
}
TEST_F(CastExprTest, testNullOnFailure) {
auto input =
makeNullableFlatVector<std::string>({"1", "2", "", "3.4", std::nullopt});
auto expected = makeNullableFlatVector<int32_t>(
{1, 2, std::nullopt, std::nullopt, std::nullopt});
// nullOnFailure is true, so we should return null instead of throwing.
testComplexCast("c0", input, expected, true);
// nullOnFailure is false, so we should throw.
EXPECT_THROW(
testComplexCast("c0", input, expected, false), std::invalid_argument);
}
TEST_F(CastExprTest, toString) {
auto input = std::make_shared<core::FieldAccessTypedExpr>(VARCHAR(), "a");
exec::ExprSet exprSet(
{makeCastExpr(input, BIGINT(), false),
makeCastExpr(input, ARRAY(VARCHAR()), false)},
&execCtx_);
ASSERT_EQ("cast((a) as BIGINT)", exprSet.exprs()[0]->toString());
ASSERT_EQ("cast((a) as ARRAY<VARCHAR>)", exprSet.exprs()[1]->toString());
}
| 32.488818 | 80 | 0.618645 | littleeleventhwolf |
f6c84838dd6c1c8551bdd7d15ebbda731bd5bec9 | 417 | hpp | C++ | B-CPP-300-LYN-3-1-CPPD13/ex02/Woody.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 2 | 2022-02-07T12:44:51.000Z | 2022-02-08T12:04:08.000Z | B-CPP-300-LYN-3-1-CPPD13/ex02/Woody.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | null | null | null | B-CPP-300-LYN-3-1-CPPD13/ex02/Woody.hpp | Neotoxic-off/Epitech2024 | 8b3dd04fa9ac2b7019c0b5b1651975a7252d929b | [
"Apache-2.0"
] | 1 | 2022-01-23T21:26:06.000Z | 2022-01-23T21:26:06.000Z | /*
** EPITECH PROJECT, 2020
** B-CPP-300-LYN-3-1-CPPD13-
** File description:
** Woody.hpp
*/
#ifndef WOODY_HPP_
#define WOODY_HPP_
#include "Toy.hpp"
class Woody : public Toy {
public:
Woody(std::string const &, std::string const &);
Woody(Woody const &);
virtual ~Woody();
virtual void display(std::string const);
};
#endif /* !WOODY_HPP_ */ | 18.954545 | 60 | 0.565947 | Neotoxic-off |
f6c86617a67b08d9445e4eebf5b12820ed587df7 | 1,407 | cc | C++ | src/net/third_party/quiche/src/quic/core/frames/quic_new_connection_id_frame.cc | godfo/naiveproxy | 369269a12832bf34bf01c7b0e7ca121555abd3eb | [
"BSD-3-Clause"
] | 8 | 2019-11-08T04:16:04.000Z | 2021-07-11T11:56:52.000Z | quic/core/frames/quic_new_connection_id_frame.cc | DaanDeMeyer/google-quiche-iquic | da6e9842787e2cf88cacaebf56b15b14fa2e8444 | [
"BSD-3-Clause"
] | null | null | null | quic/core/frames/quic_new_connection_id_frame.cc | DaanDeMeyer/google-quiche-iquic | da6e9842787e2cf88cacaebf56b15b14fa2e8444 | [
"BSD-3-Clause"
] | 6 | 2019-09-08T05:40:06.000Z | 2021-03-31T01:19:10.000Z | // Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quiche/src/quic/core/frames/quic_new_connection_id_frame.h"
#include "net/third_party/quiche/src/quic/core/quic_constants.h"
namespace quic {
QuicNewConnectionIdFrame::QuicNewConnectionIdFrame()
: control_frame_id(kInvalidControlFrameId),
connection_id(EmptyQuicConnectionId()),
sequence_number(0) {}
QuicNewConnectionIdFrame::QuicNewConnectionIdFrame(
QuicControlFrameId control_frame_id,
QuicConnectionId connection_id,
QuicConnectionIdSequenceNumber sequence_number,
const QuicUint128 stateless_reset_token,
uint64_t retire_prior_to)
: control_frame_id(control_frame_id),
connection_id(connection_id),
sequence_number(sequence_number),
stateless_reset_token(stateless_reset_token),
retire_prior_to(retire_prior_to) {
DCHECK(retire_prior_to <= sequence_number);
}
std::ostream& operator<<(std::ostream& os,
const QuicNewConnectionIdFrame& frame) {
os << "{ control_frame_id: " << frame.control_frame_id
<< ", connection_id: " << frame.connection_id
<< ", sequence_number: " << frame.sequence_number
<< ", retire_prior_to: " << frame.retire_prior_to << " }\n";
return os;
}
} // namespace quic
| 36.076923 | 85 | 0.738451 | godfo |
f6c8d1d8e031901f9a627e56357066d059d42c8c | 14,900 | cpp | C++ | ring_puzzle_game/Assets.cpp | SSNikolaevich/ring_puzzle_game | 5db7f50ecc477899727ba7250e387002420db007 | [
"MIT"
] | null | null | null | ring_puzzle_game/Assets.cpp | SSNikolaevich/ring_puzzle_game | 5db7f50ecc477899727ba7250e387002420db007 | [
"MIT"
] | 1 | 2017-11-27T14:17:53.000Z | 2017-11-29T09:14:22.000Z | ring_puzzle_game/Assets.cpp | SSNikolaevich/ring_puzzle_game | 5db7f50ecc477899727ba7250e387002420db007 | [
"MIT"
] | 1 | 2018-02-20T14:33:44.000Z | 2018-02-20T14:33:44.000Z | //===========================================================================
#include "Assets.h"
//===========================================================================
const unsigned char PROGMEM titleSprite_plus_mask[] = {
// width, height,
88, 49,
// FRAME 00
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0xe0, 0x80, 0xf0, 0xc0, 0xf8, 0xe0, 0xfc, 0x70, 0xfe, 0x38, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x0c, 0xff, 0x0c, 0xff, 0x0e, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x06, 0xff, 0x46, 0xff, 0x46, 0xff, 0x86, 0xff, 0x8e, 0xff, 0x0c, 0xff, 0x3c, 0xff, 0x38, 0xfe, 0xf0, 0xfe, 0xe0, 0xfc, 0x80, 0xf8, 0x00, 0xf0, 0x80, 0xf0, 0xc0, 0xf0, 0xc0, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0xc0, 0xf8, 0xc0, 0xf0, 0x80, 0xf0,
0x00, 0xe0, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0xc0, 0x00, 0xc0, 0x00, 0xe0, 0x80, 0xe0, 0x80, 0xf0, 0xc0, 0xf0, 0xc0, 0xf0, 0xc0, 0xf8, 0x60, 0xf8, 0x60, 0xf8, 0x60, 0xfc, 0x70, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x60, 0xfc, 0x60, 0xf8, 0xe0, 0xf8, 0xc0, 0xf8, 0xc0, 0xf0, 0x80, 0xf0, 0x00, 0xe0, 0x00, 0xc0, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xfc, 0x00, 0xff, 0xf8, 0xff, 0xfe, 0xff, 0x0f, 0xff, 0x03, 0xff, 0xe0, 0xff, 0xf8, 0xff, 0xfc, 0xff, 0x06, 0xff, 0x02, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xf0, 0xff, 0xf8, 0xff, 0xf8, 0xff, 0xf0, 0xff, 0xe0, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x03, 0xff, 0x1c, 0xff, 0x00, 0xff, 0x00, 0xff, 0x01, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xc1, 0xff, 0x80, 0xff, 0x06, 0xff, 0x06, 0xff, 0x00, 0xff, 0x40, 0xff, 0x60, 0xff, 0xb0, 0xff, 0xc1, 0xff, 0xff, 0xff,
0x7e, 0xff, 0x60, 0xff, 0x60, 0xff, 0x60, 0xf8, 0xc0, 0xf8, 0xe0, 0xf8, 0x60, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfc, 0x30, 0xfe, 0x38, 0xff, 0x7c, 0xff, 0xdc, 0xff, 0x8f, 0xff, 0x07, 0xff, 0x13, 0xff, 0x19, 0xff, 0x05, 0xff, 0x04, 0xff, 0x02, 0xff, 0x82, 0xff, 0xc2, 0xff, 0xc1, 0xff, 0x61, 0xff, 0x41, 0xff, 0x40, 0xff, 0xc0, 0xff, 0x80, 0xff, 0x00, 0xff, 0x00, 0xff, 0x84, 0xff, 0xf8, 0xff, 0xe0, 0xff, 0x01, 0xff, 0x0f, 0xff, 0xff, 0xff, 0xfc, 0xff, 0x00, 0xff, 0x00, 0xfe, 0x00, 0x00,
0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0x00, 0xff, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x01, 0xff, 0x01, 0xff, 0x01, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x0c, 0xff, 0x9e, 0xff, 0x3f, 0xff, 0x3b, 0xff, 0x70, 0xff, 0x71, 0xff, 0xff, 0xff, 0x9f, 0xff, 0x27, 0xff, 0x73, 0xff, 0x33, 0xff, 0x01, 0xff, 0x01, 0xff, 0x01, 0xff, 0x01, 0xff,
0x03, 0xff, 0x86, 0xff, 0x1c, 0xff, 0xf0, 0xff, 0x80, 0xff, 0x00, 0xff, 0x00, 0xff, 0x18, 0xff, 0xf0, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x01, 0xff, 0x03, 0xff, 0x1f, 0xff, 0x3e, 0xff, 0x78, 0xff, 0x01, 0xff, 0x07, 0xff, 0xfc, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x07, 0xff, 0x0f, 0xff, 0x0c, 0xff, 0x18, 0xff, 0x18, 0xff, 0x38, 0xff, 0x38, 0xff, 0x77, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xf0, 0xff, 0x31, 0xff, 0x31, 0xff, 0x38, 0xff, 0x18, 0xff, 0x1e, 0x7f, 0x0f, 0x7f, 0x03, 0x3f, 0x00, 0x1f, 0x00, 0x0f, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x1f, 0x03, 0x7f, 0x0f, 0xff, 0x3c, 0xff, 0xf0, 0xff, 0xc0, 0xff, 0x01, 0xff, 0x07, 0xff, 0x0e, 0xff, 0x18, 0xff, 0x20, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x08, 0xff, 0x38, 0xff, 0xf0, 0xff, 0xf2, 0xff, 0xe2, 0xff, 0x84, 0xff, 0x18, 0xff, 0x60, 0xff, 0x80, 0xff, 0x80, 0xff, 0x00, 0xff, 0x01, 0xff, 0x03, 0xff, 0x06, 0xff, 0x1e, 0xff, 0x3c, 0xff, 0x3c, 0xff, 0x38, 0xff, 0x01, 0xff, 0x01, 0xff, 0x86, 0xff, 0xfc, 0xff, 0xe0, 0xff, 0x80, 0xff, 0xb8, 0xff,
0x9c, 0xff, 0xc7, 0xff, 0xe0, 0xff, 0xbc, 0xff, 0x87, 0xff, 0x80, 0xff, 0xc0, 0xff, 0xf8, 0xff, 0xcf, 0xff, 0xc0, 0xff, 0x80, 0xff, 0x9c, 0xff, 0x98, 0xff, 0x90, 0xff, 0x90, 0xff, 0xc8, 0xff, 0x60, 0xff, 0x30, 0xff, 0x98, 0xff, 0x0f, 0xff, 0x0c, 0xff, 0x04, 0xff, 0x02, 0xff, 0x02, 0xff, 0x02, 0xff, 0x82, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x80, 0xff, 0xc0, 0xff, 0xe1, 0xff, 0x3f, 0xff, 0x0f, 0xff, 0x00, 0x7f, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x0f, 0x01, 0x1f, 0x07, 0x3f, 0x0e, 0x3f, 0x0c, 0x7f, 0x18, 0xff, 0x30, 0xff, 0x30, 0xff, 0x60, 0xff, 0x60, 0xff, 0x60, 0xff, 0xe0, 0xff, 0xc0, 0xff, 0xc0, 0xff, 0xc0, 0xff, 0xc1, 0xff, 0xc3, 0xff, 0x61, 0xff, 0x60, 0xff, 0x38, 0xff, 0x3f, 0xff, 0x0f, 0xff, 0xc3, 0xff, 0x43, 0xff, 0xc6, 0xff, 0x46, 0xff, 0x4c, 0xff, 0x0c, 0xff, 0x4c, 0xff, 0xcc, 0xff, 0x46, 0xff, 0x46, 0xff, 0xc1, 0xff, 0x01, 0xff, 0xc1, 0xff, 0xc1, 0xff, 0x01, 0xff,
0x41, 0xff, 0x00, 0xff, 0xc0, 0xff, 0x41, 0xff, 0x41, 0xff, 0x81, 0xff, 0x01, 0xff, 0x80, 0xff, 0x40, 0xff, 0xc0, 0xff, 0x01, 0xff, 0xc1, 0xff, 0x01, 0xff, 0x01, 0xff, 0x1f, 0xff, 0x7f, 0xff, 0x70, 0xff, 0xe7, 0xff, 0xcf, 0xff, 0xcf, 0xff, 0xc6, 0xff, 0xe6, 0xff, 0x62, 0xff, 0x71, 0xff, 0x39, 0xff, 0x1c, 0xff, 0x0c, 0x7f, 0x06, 0x3f, 0x06, 0x1f, 0x03, 0x1f, 0x01, 0x0f, 0x01, 0x07, 0x00, 0x07, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x07, 0x00, 0x0f, 0x03, 0xff, 0x00, 0xff, 0xfb, 0xff, 0x5b, 0xff, 0x78, 0xff, 0x03, 0xff, 0x79, 0xff, 0xc3, 0xff, 0xf9, 0xff, 0x00, 0xff, 0xcb, 0xff, 0xab, 0xff, 0x98, 0xff,
0x03, 0xff, 0xc8, 0xff, 0xab, 0xff, 0x9a, 0xff, 0x02, 0xff, 0xf9, 0xff, 0xc0, 0xff, 0x03, 0xff, 0xf9, 0xff, 0xab, 0xff, 0x88, 0xff, 0x03, 0xff, 0x02, 0xff, 0x03, 0x0f, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01,
0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
//===========================================================================
const unsigned char PROGMEM githubLogoSprite_plus_mask[] = {
// width, height,
16, 16,
// FRAME 00
0xe0, 0xe0, 0xf8, 0xf8, 0xfc, 0xfc, 0x3e, 0xfe, 0x0e, 0xfe, 0x07, 0xff, 0x0f, 0xff, 0x1f, 0xff,
0x1f, 0xff, 0x0f, 0xff, 0x07, 0xff, 0x0e, 0xfe, 0x3e, 0xfe, 0xfc, 0xfc, 0xf8, 0xf8, 0xe0, 0xe0,
0x07, 0x07, 0x1f, 0x1f, 0x37, 0x3f, 0x64, 0x7f, 0x48, 0x7f, 0xd8, 0xff, 0x08, 0xff, 0x00, 0xff,
0x00, 0xff, 0x08, 0xff, 0xf8, 0xff, 0x78, 0x7f, 0x7c, 0x7f, 0x3f, 0x3f, 0x1f, 0x1f, 0x07, 0x07,
};
//===========================================================================
const unsigned char PROGMEM tilesSprite_plus_mask[] = {
// width, height,
16, 16,
// FRAME 00
0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0xfc, 0x70, 0xfc, 0xf0, 0xfc, 0xf0, 0xfc, 0xe0, 0xfc,
0xd0, 0xfe, 0xb8, 0xff, 0x7c, 0xff, 0x3c, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0e, 0x00, 0x0f, 0x0c, 0x0f, 0x0e, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x05, 0x0f, 0x03, 0x0f,
0x07, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 01
0x00, 0x1f, 0x00, 0xbf, 0x0f, 0xff, 0x1f, 0xff, 0xbf, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xff,
0xe8, 0xff, 0xdc, 0xff, 0xbf, 0xff, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x0f, 0x0c, 0x0f, 0x0e, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x07, 0x0f, 0x02, 0x0f, 0x01, 0x0f,
0x03, 0x0f, 0x07, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 02
0x01, 0x8f, 0x03, 0xdf, 0x07, 0xff, 0x8f, 0xff, 0xdf, 0xff, 0xbe, 0xff, 0x7c, 0xff, 0xf8, 0xff,
0xf4, 0xff, 0xee, 0xff, 0xde, 0xff, 0x8d, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0f, 0x00, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x0f,
0x01, 0x0f, 0x03, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 03
0x00, 0x0f, 0x00, 0x1f, 0x03, 0xff, 0x07, 0xff, 0xef, 0xff, 0xf7, 0xff, 0xfa, 0xff, 0x7c, 0xff,
0xbe, 0xff, 0xdf, 0xff, 0xef, 0xff, 0xc7, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03,
0x00, 0x07, 0x01, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 04
0x1c, 0xff, 0x1c, 0xff, 0x3c, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xfe, 0xe0, 0xfc, 0xd0, 0xfe,
0xb8, 0xff, 0x7c, 0xff, 0x3e, 0xff, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0c, 0x0f, 0x0c, 0x0f, 0x0e, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x05, 0x0f, 0x03, 0x0f, 0x07, 0x0f,
0x0f, 0x0f, 0x0f, 0x0f, 0x06, 0x0f, 0x08, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 05
0x0f, 0xff, 0x01, 0xff, 0x01, 0xff, 0x81, 0xff, 0xc0, 0xff, 0xe0, 0xff, 0xf0, 0xff, 0xf8, 0xff,
0x7c, 0xff, 0x3e, 0xff, 0x1f, 0xff, 0x0f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0x0f, 0x0c, 0x0f, 0x0b, 0x0f, 0x07, 0x0f, 0x07, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x0f,
0x00, 0x0f, 0x08, 0x0f, 0x04, 0x0f, 0x0a, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 06
0x03, 0xff, 0x07, 0xff, 0x0f, 0xff, 0x1f, 0xff, 0x3e, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xff,
0xe0, 0xff, 0xc1, 0xff, 0x83, 0xff, 0x07, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x08, 0x0f, 0x08, 0x0f, 0x08, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x01, 0x0f,
0x03, 0x0f, 0x0b, 0x0f, 0x0d, 0x0f, 0x0e, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 07
0x83, 0xff, 0x83, 0xff, 0xc7, 0xff, 0xef, 0xff, 0xf7, 0xff, 0xfa, 0xff, 0x7c, 0xff, 0xbe, 0xff,
0xdf, 0xff, 0xef, 0xff, 0xc7, 0xff, 0x83, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x07, 0x00, 0x03, 0x00, 0x07,
0x01, 0x0f, 0x03, 0x0f, 0x07, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 08
0x1f, 0xff, 0x3e, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xfe, 0xe0, 0xfc, 0xd0, 0xfe, 0xb8, 0xff,
0x7c, 0xff, 0x3c, 0xff, 0x1c, 0xff, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0c, 0x0f, 0x0e, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x05, 0x0f, 0x03, 0x0f, 0x07, 0x0f, 0x0f, 0x0f,
0x0f, 0x0f, 0x0e, 0x0f, 0x0c, 0x0f, 0x0c, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 09
0x07, 0xff, 0x1b, 0xff, 0x3d, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xff, 0xe0, 0xff, 0xc0, 0xff,
0x81, 0xff, 0x01, 0xff, 0x01, 0xff, 0x0f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0x0f, 0x0c, 0x0f, 0x08, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x01, 0x0f, 0x03, 0x0f, 0x07, 0x0f,
0x0f, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x0c, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 10
0x07, 0xff, 0x83, 0xff, 0xc1, 0xff, 0xe0, 0xff, 0xf0, 0xff, 0xf8, 0xff, 0x7c, 0xff, 0x3e, 0xff,
0x1e, 0xff, 0x0d, 0xff, 0x03, 0xff, 0x07, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x0f, 0x0f, 0x07, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x0f,
0x08, 0x0f, 0x08, 0x0f, 0x08, 0x0f, 0x0f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 11
0x81, 0xff, 0xc6, 0xff, 0xef, 0xff, 0xf7, 0xff, 0xfa, 0xff, 0x7c, 0xff, 0xbe, 0xff, 0xdf, 0xff,
0xef, 0xff, 0xc7, 0xff, 0x83, 0xff, 0x83, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x07, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x07, 0x00, 0x03, 0x00, 0x07, 0x01, 0x0f,
0x03, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x03, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 12
0x3c, 0xff, 0x7c, 0xff, 0xf8, 0xff, 0xf0, 0xfe, 0xe0, 0xfc, 0xd0, 0xfc, 0xb0, 0xfc, 0x70, 0xfc,
0x00, 0xfc, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0x0f, 0x0f, 0x0f, 0x0e, 0x0f, 0x05, 0x0f, 0x03, 0x0f, 0x07, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f,
0x0e, 0x0f, 0x0c, 0x0f, 0x00, 0x0f, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 13
0x1f, 0xff, 0xbf, 0xff, 0xdc, 0xff, 0xe8, 0xff, 0xf0, 0xff, 0xf8, 0xff, 0x7c, 0xff, 0xbf, 0xff,
0x1f, 0xff, 0x0f, 0xff, 0x00, 0xbf, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0b, 0x0f, 0x07, 0x0f, 0x07, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x02, 0x0f, 0x07, 0x0f, 0x0f, 0x0f,
0x0f, 0x0f, 0x0e, 0x0f, 0x0c, 0x0f, 0x08, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 14
0x8f, 0xff, 0xdf, 0xff, 0xee, 0xff, 0xf4, 0xff, 0xf8, 0xff, 0x7c, 0xff, 0xbe, 0xff, 0xdf, 0xff,
0x8f, 0xff, 0x07, 0xff, 0x03, 0xdf, 0x01, 0x8f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x0f, 0x0f, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x0f, 0x01, 0x0f, 0x03, 0x0f, 0x0f, 0x0f,
0x0f, 0x0f, 0x0f, 0x0f, 0x00, 0x0f, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// FRAME 15
0xc7, 0xff, 0xef, 0xff, 0xf7, 0xff, 0xfa, 0xff, 0x7c, 0xff, 0xbe, 0xff, 0xdf, 0xff, 0xef, 0xff,
0x07, 0xff, 0x03, 0xff, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x0f, 0x03, 0x0f, 0x01, 0x0f, 0x00, 0x07, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03,
0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
| 107.194245 | 532 | 0.644631 | SSNikolaevich |
f6c8f8d6156f2ef23cb4aaa0413d9bd276361f9e | 7,859 | cpp | C++ | src/graphics/SimpleBrush3D.cpp | LU15W1R7H/lwirth-lib | f51cfb56b801790c200cea64d226730449d68f53 | [
"MIT"
] | 2 | 2018-04-04T17:26:32.000Z | 2020-06-26T09:22:49.000Z | src/graphics/SimpleBrush3D.cpp | LU15W1R7H/lwirth-lib | f51cfb56b801790c200cea64d226730449d68f53 | [
"MIT"
] | 1 | 2018-08-27T14:35:45.000Z | 2018-08-27T19:00:12.000Z | src/graphics/SimpleBrush3D.cpp | LU15W1R7H/lwirth-lib | f51cfb56b801790c200cea64d226730449d68f53 | [
"MIT"
] | null | null | null | #include "SimpleBrush3D.hpp"
#include "Color.hpp"
#include <cstring>
#include "Vulkan.hpp"
namespace lw
{
void SimpleBrush3D::setColor(const Color& color)
{
m_mainColor = color;
}
void SimpleBrush3D::setColor(f32 r, f32 g, f32 b, f32 a /*= 1.f*/)
{
m_mainColor = { r, g, b, a };
}
void SimpleBrush3D::drawVertexArray(Vertex2DArray & va)
{
/*switch (va.m_primitive)
{
case Triangles:
drawVertexArrayTriangleFill(va);
break;
case Quads:
drawVertexArrayQuadFill(va);
break;
default:
throw std::logic_error("not available");
}*/
}
void SimpleBrush3D::drawLine(const Vertex2D& start, const Vertex2D& end)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
m_lineVertexArray.push(start);
m_lineVertexArray.push(end);
}
void SimpleBrush3D::drawLine(f32 x1, f32 y1, f32 x2, f32 y2)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
m_lineVertexArray.push(Vertex2D({ x1, y1 }, m_mainColor));
m_lineVertexArray.push(Vertex2D({ x2, y2 }, m_mainColor));
}
void SimpleBrush3D::drawPoint(const Vertex2D & pos)
{
m_pointVertexArray.push(pos);
}
void SimpleBrush3D::drawPoint(f32 x, f32 y)
{
m_pointVertexArray.push(Vertex2D({ x, y }, m_mainColor));
}
void SimpleBrush3D::create(VK::Vulkan* pVulkan, u32 screenWidth, u32 screenHeight)
{
m_pVK = pVulkan;
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
m_vertexShader.create(&m_pVK->m_mainDevice, "D:/Dev/C++/My Projects/lwirth-lib/res/shaders/2Dshadervert.spv");
m_fragmentShader.create(&m_pVK->m_mainDevice, "D:/Dev/C++/My Projects/lwirth-lib/res/shaders/2Dshaderfrag.spv");
SimpleBrush3D::createPipeline();
//prepare index buffers
{
lw::List<u16> indexArrayVec = { 0, 1, 1, 2, 2, 0 };
VK::StagingBuffer stagingBuffer;
size_t dataSize = indexArrayVec.size() * sizeof(u16);
stagingBuffer.allocate(&m_pVK->m_mainDevice, dataSize);
void* dataPtr = stagingBuffer.map();
std::memcpy(dataPtr, indexArrayVec.raw(), dataSize);
stagingBuffer.unmap();
m_triangleMeshIndexBuffer.allocate(&m_pVK->m_mainDevice, &m_pVK->m_commandPool, m_pVK->m_mainDevice.getGraphicsQueue(), &stagingBuffer, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_SHARING_MODE_EXCLUSIVE);
stagingBuffer.destroy();
}
{
lw::List<u16> indexArrayVec = { 0, 1, 2, 2, 3, 0 };
VK::StagingBuffer stagingBuffer;
size_t dataSize = indexArrayVec.size() * sizeof(u16);
stagingBuffer.allocate(&m_pVK->m_mainDevice, dataSize);
void* dataPtr = stagingBuffer.map();
std::memcpy(dataPtr, indexArrayVec.raw(), dataSize);
stagingBuffer.unmap();
m_quadFillIndexBuffer.allocate(&m_pVK->m_mainDevice, &m_pVK->m_commandPool, m_pVK->m_mainDevice.getGraphicsQueue(), &stagingBuffer, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_SHARING_MODE_EXCLUSIVE);
stagingBuffer.destroy();
}
//Triangle::s_init(&m_pVK->m_device, &m_pVK->m_commandPool);
}
void SimpleBrush3D::destroy()
{
//Triangle::s_deinit();
SimpleBrush3D::destroyPipeline();
m_fragmentShader.destroy();
m_vertexShader.destroy();
}
void SimpleBrush3D::createPipeline()
{
}
void SimpleBrush3D::destroyPipeline()
{
m_pipelineTriangleFill.destroy();
m_pipelineLine.destroy();
m_pipelinePoint.destroy();
}
void SimpleBrush3D::prepare(const VK::CommandBuffer* cmd)
{
m_pCmdBuffer = cmd;
m_lineVertexArray.clear();
m_pointVertexArray.clear();
m_ready = true;
}
void SimpleBrush3D::disperse()
{
drawAllLines();
drawAllPoints();
m_pCmdBuffer = nullptr;
m_ready = false;
}
void SimpleBrush3D::resize(u32 screenWidth, u32 screenHeight)
{
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
destroyPipeline();
createPipeline();
}
void SimpleBrush3D::drawAllLines()
{
if (m_lineVertexArray.isEmpty())return;
vkCmdBindPipeline(m_pCmdBuffer->raw(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLine.raw());
VkViewport viewport;
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = static_cast<f32>(m_screenWidth);
viewport.height = static_cast<f32>(m_screenHeight);
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
VkRect2D scissor;
scissor.offset = { 0, 0 };
scissor.extent = { m_screenWidth, m_screenHeight };
vkCmdSetViewport(m_pCmdBuffer->raw(), 0, 1, &viewport);
vkCmdSetScissor(m_pCmdBuffer->raw(), 0, 1, &scissor);
//m_lineVertexArray.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, m_lineVertexArray.m_buffer.ptr(), offsets);
vkCmdDraw(m_pCmdBuffer->raw(), m_lineVertexArray.size(), 1, 0, 0);
}
void SimpleBrush3D::drawAllPoints()
{
if (m_pointVertexArray.isEmpty())return;
vkCmdBindPipeline(m_pCmdBuffer->raw(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelinePoint.raw());
VkViewport viewport;
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = static_cast<f32>(m_screenWidth);
viewport.height = static_cast<f32>(m_screenHeight);
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
VkRect2D scissor;
scissor.offset = { 0, 0 };
scissor.extent = { m_screenWidth, m_screenHeight };
vkCmdSetViewport(m_pCmdBuffer->raw(), 0, 1, &viewport);
vkCmdSetScissor(m_pCmdBuffer->raw(), 0, 1, &scissor);
//m_pointVertexArray.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, m_pointVertexArray.m_buffer.ptr(), offsets);
vkCmdDraw(m_pCmdBuffer->raw(), m_pointVertexArray.size(), 1, 0, 0);
}
void SimpleBrush3D::preparePipeline(VK::Pipeline & pipeline)
{
vkCmdBindPipeline(m_pCmdBuffer->raw(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.raw());
VkViewport viewport;
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = static_cast<f32>(m_screenWidth);
viewport.height = static_cast<f32>(m_screenHeight);
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
VkRect2D scissor;
scissor.offset = { 0, 0 };
scissor.extent = { m_screenWidth, m_screenHeight };
vkCmdSetViewport(m_pCmdBuffer->raw(), 0, 1, &viewport);
vkCmdSetScissor(m_pCmdBuffer->raw(), 0, 1, &scissor);
}
void SimpleBrush3D::drawVertexArrayTriangleFill(Vertex2DArray & va)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
if (va.isEmpty())return;
preparePipeline(m_pipelineTriangleFill);
//va.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, va.m_buffer.ptr(), offsets);
vkCmdDraw(m_pCmdBuffer->raw(), va.size(), 1, 0, 0);
}
void SimpleBrush3D::drawVertexArrayTriangleMesh(Vertex2DArray & va)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
if (va.isEmpty())return;
preparePipeline(m_pipelineLine);
//va.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, va.m_buffer.ptr(), offsets);
vkCmdBindIndexBuffer(m_pCmdBuffer->raw(), m_triangleMeshIndexBuffer.raw(), 0, VK_INDEX_TYPE_UINT16);
vkCmdDrawIndexed(m_pCmdBuffer->raw(), 6, 1, 0, 0, 0);
}
void SimpleBrush3D::drawVertexArrayQuadFill(Vertex2DArray & va)
{
if (!m_ready)throw NotReadyException("SimpleBrush3D is not ready.");
if (va.isEmpty())return;
preparePipeline(m_pipelineTriangleFill);
//va.updateBuffer(&m_pVK->m_device, &m_pVK->m_commandPool);
VkDeviceSize offsets[] = { 0 };
//vkCmdBindVertexBuffers(m_pCmdBuffer->raw(), 0, 1, va.m_buffer.ptr(), offsets);
vkCmdBindIndexBuffer(m_pCmdBuffer->raw(), m_quadFillIndexBuffer.raw(), 0, VK_INDEX_TYPE_UINT16);
for (size_t i = 0; i < va.size(); i += 4)
{
//#TODO optimize
vkCmdDrawIndexed(m_pCmdBuffer->raw(), 6, 1, 0, i, 0);
}
}
void SimpleBrush3D::drawVertexArrayQuadMesh(Vertex2DArray & va)
{
}
} | 27.006873 | 200 | 0.717267 | LU15W1R7H |
f6ce05b0de1e3e4011bda28df5b723267ddb3ca6 | 2,021 | cc | C++ | google/cloud/storage/oauth2/google_application_default_credentials_file.cc | orinem/google-cloud-cpp | c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1 | [
"Apache-2.0"
] | 3 | 2020-05-27T23:21:23.000Z | 2020-05-31T22:31:53.000Z | google/cloud/storage/oauth2/google_application_default_credentials_file.cc | orinem/google-cloud-cpp | c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1 | [
"Apache-2.0"
] | 2 | 2020-10-06T15:50:06.000Z | 2020-11-24T16:21:28.000Z | google/cloud/storage/oauth2/google_application_default_credentials_file.cc | orinem/google-cloud-cpp | c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1 | [
"Apache-2.0"
] | 1 | 2021-12-09T16:26:23.000Z | 2021-12-09T16:26:23.000Z | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/oauth2/google_application_default_credentials_file.h"
#include "google/cloud/internal/getenv.h"
#include <cstdlib>
namespace {
std::string const& GoogleWellKnownAdcFilePathSuffix() {
#ifdef _WIN32
static std::string const kSuffix =
"/gcloud/application_default_credentials.json";
#else
static std::string const kSuffix =
"/.config/gcloud/application_default_credentials.json";
#endif
return kSuffix;
}
} // anonymous namespace
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace oauth2 {
std::string GoogleAdcFilePathFromEnvVarOrEmpty() {
auto override_value = google::cloud::internal::GetEnv(GoogleAdcEnvVar());
if (override_value.has_value()) {
return *override_value;
}
return "";
}
std::string GoogleAdcFilePathFromWellKnownPathOrEmpty() {
// Allow mocking out this value for testing.
auto override_path =
google::cloud::internal::GetEnv(GoogleGcloudAdcFileEnvVar());
if (override_path.has_value()) {
return *override_path;
}
// Search well known gcloud ADC path.
auto adc_path_root = google::cloud::internal::GetEnv(GoogleAdcHomeEnvVar());
if (adc_path_root.has_value()) {
return *adc_path_root + GoogleWellKnownAdcFilePathSuffix();
}
return "";
}
} // namespace oauth2
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
| 29.289855 | 84 | 0.743196 | orinem |
f6ce261a555733b5d7b4dd120172f82a1e0ab898 | 2,324 | cpp | C++ | ObserverPattern.cpp | gdevanga/Design-problems | d3659c5ba6c0cf3262e3982f4d81f0421c277b92 | [
"MIT"
] | null | null | null | ObserverPattern.cpp | gdevanga/Design-problems | d3659c5ba6c0cf3262e3982f4d81f0421c277b92 | [
"MIT"
] | null | null | null | ObserverPattern.cpp | gdevanga/Design-problems | d3659c5ba6c0cf3262e3982f4d81f0421c277b92 | [
"MIT"
] | null | null | null | // ObserverPattern.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class IDisplayObserver
{
public:
virtual void update(int t, int p, int h) {}
};
class CWeatherData
{
int nTemp{ 0 };
int nPressure{ 0 };
int nHumidity{ 0 };
vector<IDisplayObserver*> obsV;
void notifyObservers()
{
for (IDisplayObserver* ob : obsV)
ob->update(nTemp, nPressure, nHumidity);
}
public:
void addObserver(IDisplayObserver* o)
{
obsV.push_back(o);
}
void removeObserver(IDisplayObserver* o)
{
for (auto it = obsV.cbegin(); it != obsV.cend(); ++it)
{
if (*it == o)
{
obsV.erase(it);
break;
}
}
}
void setWeather(int t, int p, int h)
{
nTemp = t;
nPressure = p;
nHumidity = h;
notifyObservers();
}
};
class CDisp1 : IDisplayObserver
{
int nTemp{ 0 };
int nPressure{ 0 };
int nHumidity{ 0 };
CWeatherData* data;
void display()
{
cout << "Displaying from CDisp1 obj: ";
cout << "Temperature :" << nTemp << "\t Pressure :" << nPressure << "\t Humidty :" << nHumidity << endl;
}
public:
CDisp1(CWeatherData* data)
{
cout << "Disp1 obj created!" << endl;
this->data = data;
data->addObserver(this);
}
~CDisp1()
{
cout << "Disp1 obj destroyed!" << endl;
data->removeObserver(this);
}
void update(int t, int p, int h)
{
nTemp = t;
nPressure = p;
nHumidity = h;
display();
}
};
class CDisp2 : IDisplayObserver
{
int nTemp{ 0 };
int nPressure{ 0 };
int nHumidity{ 0 };
CWeatherData* data;
void display()
{
cout << "Displaying from CDisp2 obj: ";
cout << "Temperature :" << nTemp << "\t Pressure :" << nPressure << "\t Humidty :" << nHumidity << endl;
}
public:
CDisp2(CWeatherData* data)
{
cout << "Disp2 obj created!" << endl;
this->data = data;
data->addObserver(this);
}
~CDisp2()
{
cout << "Disp2 obj destroyed!" << endl;
data->removeObserver(this);
}
void update(int t, int p, int h)
{
nTemp = t;
nPressure = p;
nHumidity = h;
display();
}
};
int main()
{
CWeatherData* data = new CWeatherData();
CDisp1* d1 = new CDisp1(data);
data->setWeather(10, 15, 19);
CDisp2* d2 = new CDisp2(data);
data->setWeather(50, 55, 59);
delete d1;
data->setWeather(60, 65, 69);
getchar();
return 0;
}
| 15.390728 | 106 | 0.614458 | gdevanga |
f6cec56e456f741d39f5b26d53b5a00a129ddcba | 45,523 | cpp | C++ | src/types/viewport.cpp | lifeng1983/Terminal | 1d35e180fdaacef731886bdb2cabca2ea4fe2b49 | [
"MIT"
] | 12 | 2020-07-23T16:31:06.000Z | 2021-09-08T01:49:10.000Z | src/types/viewport.cpp | lifeng1983/Terminal | 1d35e180fdaacef731886bdb2cabca2ea4fe2b49 | [
"MIT"
] | 6 | 2020-07-23T19:16:18.000Z | 2020-07-30T22:59:06.000Z | src/types/viewport.cpp | lifeng1983/Terminal | 1d35e180fdaacef731886bdb2cabca2ea4fe2b49 | [
"MIT"
] | 2 | 2020-05-22T12:54:28.000Z | 2020-08-02T15:21:14.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "inc/Viewport.hpp"
using namespace Microsoft::Console::Types;
Viewport::Viewport(const SMALL_RECT sr) noexcept :
_sr(sr)
{
}
Viewport::Viewport(const Viewport& other) noexcept :
_sr(other._sr)
{
}
Viewport Viewport::Empty() noexcept
{
return Viewport();
}
Viewport Viewport::FromInclusive(const SMALL_RECT sr) noexcept
{
return Viewport(sr);
}
Viewport Viewport::FromExclusive(const SMALL_RECT sr) noexcept
{
SMALL_RECT _sr = sr;
_sr.Bottom -= 1;
_sr.Right -= 1;
return Viewport::FromInclusive(_sr);
}
// Function Description:
// - Creates a new Viewport at the given origin, with the given dimensions.
// Arguments:
// - origin: The origin of the new Viewport. Becomes the Viewport's Left, Top
// - width: The width of the new viewport
// - height: The height of the new viewport
// Return Value:
// - a new Viewport at the given origin, with the given dimensions.
Viewport Viewport::FromDimensions(const COORD origin,
const short width,
const short height) noexcept
{
return Viewport::FromExclusive({ origin.X, origin.Y, origin.X + width, origin.Y + height });
}
// Function Description:
// - Creates a new Viewport at the given origin, with the given dimensions.
// Arguments:
// - origin: The origin of the new Viewport. Becomes the Viewport's Left, Top
// - dimensions: A coordinate containing the width and height of the new viewport
// in the x and y coordinates respectively.
// Return Value:
// - a new Viewport at the given origin, with the given dimensions.
Viewport Viewport::FromDimensions(const COORD origin,
const COORD dimensions) noexcept
{
return Viewport::FromExclusive({ origin.X, origin.Y, origin.X + dimensions.X, origin.Y + dimensions.Y });
}
// Function Description:
// - Creates a new Viewport at the origin, with the given dimensions.
// Arguments:
// - dimensions: A coordinate containing the width and height of the new viewport
// in the x and y coordinates respectively.
// Return Value:
// - a new Viewport at the origin, with the given dimensions.
Viewport Viewport::FromDimensions(const COORD dimensions) noexcept
{
return Viewport::FromDimensions({ 0 }, dimensions);
}
// Method Description:
// - Creates a Viewport equivalent to a 1x1 rectangle at the given coordinate.
// Arguments:
// - origin: origin of the rectangle to create.
// Return Value:
// - a 1x1 Viewport at the given coordinate
Viewport Viewport::FromCoord(const COORD origin) noexcept
{
return Viewport::FromInclusive({ origin.X, origin.Y, origin.X, origin.Y });
}
SHORT Viewport::Left() const noexcept
{
return _sr.Left;
}
SHORT Viewport::RightInclusive() const noexcept
{
return _sr.Right;
}
SHORT Viewport::RightExclusive() const noexcept
{
return _sr.Right + 1;
}
SHORT Viewport::Top() const noexcept
{
return _sr.Top;
}
SHORT Viewport::BottomInclusive() const noexcept
{
return _sr.Bottom;
}
SHORT Viewport::BottomExclusive() const noexcept
{
return _sr.Bottom + 1;
}
SHORT Viewport::Height() const noexcept
{
return BottomExclusive() - Top();
}
SHORT Viewport::Width() const noexcept
{
return RightExclusive() - Left();
}
// Method Description:
// - Get a coord representing the origin of this viewport.
// Arguments:
// - <none>
// Return Value:
// - the coordinates of this viewport's origin.
COORD Viewport::Origin() const noexcept
{
return { Left(), Top() };
}
// Method Description:
// - For Accessibility, get a COORD representing the end of this viewport in exclusive terms.
// - This is needed to represent an exclusive endpoint in UiaTextRange that includes the last
// COORD's text in the buffer at (RightInclusive(), BottomInclusive())
// Arguments:
// - <none>
// Return Value:
// - the coordinates of this viewport's end.
COORD Viewport::EndExclusive() const noexcept
{
return { Left(), BottomExclusive() };
}
// Method Description:
// - Get a coord representing the dimensions of this viewport.
// Arguments:
// - <none>
// Return Value:
// - the dimensions of this viewport.
COORD Viewport::Dimensions() const noexcept
{
return { Width(), Height() };
}
// Method Description:
// - Determines if the given viewport fits within this viewport.
// Arguments:
// - other - The viewport to fit inside this one
// Return Value:
// - True if it fits. False otherwise.
bool Viewport::IsInBounds(const Viewport& other) const noexcept
{
return other.Left() >= Left() && other.Left() <= RightInclusive() &&
other.RightInclusive() >= Left() && other.RightInclusive() <= RightInclusive() &&
other.Top() >= Top() && other.Top() <= other.BottomInclusive() &&
other.BottomInclusive() >= Top() && other.BottomInclusive() <= BottomInclusive();
}
// Method Description:
// - Determines if the given coordinate position lies within this viewport.
// Arguments:
// - pos - Coordinate position
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it lies inside the viewport. False otherwise.
bool Viewport::IsInBounds(const COORD& pos, bool allowEndExclusive) const noexcept
{
if (allowEndExclusive && pos == EndExclusive())
{
return true;
}
return pos.X >= Left() && pos.X < RightExclusive() &&
pos.Y >= Top() && pos.Y < BottomExclusive();
}
// Method Description:
// - Clamps a coordinate position into the inside of this viewport.
// Arguments:
// - pos - coordinate to update/clamp
// Return Value:
// - <none>
void Viewport::Clamp(COORD& pos) const
{
THROW_HR_IF(E_NOT_VALID_STATE, !IsValid()); // we can't clamp to an invalid viewport.
pos.X = std::clamp(pos.X, Left(), RightInclusive());
pos.Y = std::clamp(pos.Y, Top(), BottomInclusive());
}
// Method Description:
// - Clamps a viewport into the inside of this viewport.
// Arguments:
// - other - Viewport to clamp to the inside of this viewport
// Return Value:
// - Clamped viewport
Viewport Viewport::Clamp(const Viewport& other) const noexcept
{
auto clampMe = other.ToInclusive();
clampMe.Left = std::clamp(clampMe.Left, Left(), RightInclusive());
clampMe.Right = std::clamp(clampMe.Right, Left(), RightInclusive());
clampMe.Top = std::clamp(clampMe.Top, Top(), BottomInclusive());
clampMe.Bottom = std::clamp(clampMe.Bottom, Top(), BottomInclusive());
return Viewport::FromInclusive(clampMe);
}
// Method Description:
// - Moves the coordinate given by the number of positions and
// in the direction given (repeated increment or decrement)
// Arguments:
// - move - Magnitude and direction of the move
// - pos - The coordinate position to adjust
// Return Value:
// - True if we successfully moved the requested distance. False if we had to stop early.
// - If False, we will restore the original position to the given coordinate.
bool Viewport::MoveInBounds(const ptrdiff_t move, COORD& pos) const noexcept
{
const auto backup = pos;
bool success = true; // If nothing happens, we're still successful (e.g. add = 0)
for (int i = 0; i < move; i++)
{
success = IncrementInBounds(pos);
// If an operation fails, break.
if (!success)
{
break;
}
}
for (int i = 0; i > move; i--)
{
success = DecrementInBounds(pos);
// If an operation fails, break.
if (!success)
{
break;
}
}
// If any operation failed, revert to backed up state.
if (!success)
{
pos = backup;
}
return success;
}
// Method Description:
// - Increments the given coordinate within the bounds of this viewport.
// Arguments:
// - pos - Coordinate position that will be incremented, if it can be.
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it could be incremented. False if it would move outside.
bool Viewport::IncrementInBounds(COORD& pos, bool allowEndExclusive) const noexcept
{
return WalkInBounds(pos, { XWalk::LeftToRight, YWalk::TopToBottom }, allowEndExclusive);
}
// Method Description:
// - Increments the given coordinate within the bounds of this viewport
// rotating around to the top when reaching the bottom right corner.
// Arguments:
// - pos - Coordinate position that will be incremented.
// Return Value:
// - True if it could be incremented inside the viewport.
// - False if it rolled over from the bottom right corner back to the top.
bool Viewport::IncrementInBoundsCircular(COORD& pos) const noexcept
{
return WalkInBoundsCircular(pos, { XWalk::LeftToRight, YWalk::TopToBottom });
}
// Method Description:
// - Decrements the given coordinate within the bounds of this viewport.
// Arguments:
// - pos - Coordinate position that will be incremented, if it can be.
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it could be incremented. False if it would move outside.
bool Viewport::DecrementInBounds(COORD& pos, bool allowEndExclusive) const noexcept
{
return WalkInBounds(pos, { XWalk::RightToLeft, YWalk::BottomToTop }, allowEndExclusive);
}
// Method Description:
// - Decrements the given coordinate within the bounds of this viewport
// rotating around to the bottom right when reaching the top left corner.
// Arguments:
// - pos - Coordinate position that will be decremented.
// Return Value:
// - True if it could be decremented inside the viewport.
// - False if it rolled over from the top left corner back to the bottom right.
bool Viewport::DecrementInBoundsCircular(COORD& pos) const noexcept
{
return WalkInBoundsCircular(pos, { XWalk::RightToLeft, YWalk::BottomToTop });
}
// Routine Description:
// - Compares two coordinate positions to determine whether they're the same, left, or right within the given buffer size
// Arguments:
// - first- The first coordinate position
// - second - The second coordinate position
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - Negative if First is to the left of the Second.
// - 0 if First and Second are the same coordinate.
// - Positive if First is to the right of the Second.
// - This is so you can do s_CompareCoords(first, second) <= 0 for "first is left or the same as second".
// (the < looks like a left arrow :D)
// - The magnitude of the result is the distance between the two coordinates when typing characters into the buffer (left to right, top to bottom)
int Viewport::CompareInBounds(const COORD& first, const COORD& second, bool allowEndExclusive) const noexcept
{
// Assert that our coordinates are within the expected boundaries
FAIL_FAST_IF(!IsInBounds(first, allowEndExclusive));
FAIL_FAST_IF(!IsInBounds(second, allowEndExclusive));
// First set the distance vertically
// If first is on row 4 and second is on row 6, first will be -2 rows behind second * an 80 character row would be -160.
// For the same row, it'll be 0 rows * 80 character width = 0 difference.
int retVal = (first.Y - second.Y) * Width();
// Now adjust for horizontal differences
// If first is in position 15 and second is in position 30, first is -15 left in relation to 30.
retVal += (first.X - second.X);
// Further notes:
// If we already moved behind one row, this will help correct for when first is right of second.
// For example, with row 4, col 79 and row 5, col 0 as first and second respectively, the distance is -1.
// Assume the row width is 80.
// Step one will set the retVal as -80 as first is one row behind the second.
// Step two will then see that first is 79 - 0 = +79 right of second and add 79
// The total is -80 + 79 = -1.
return retVal;
}
// Method Description:
// - Walks the given coordinate within the bounds of this viewport in the specified
// X and Y directions.
// Arguments:
// - pos - Coordinate position that will be adjusted, if it can be.
// - dir - Walking direction specifying which direction to go when reaching the end of a row/column
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it could be adjusted as specified and remain in bounds. False if it would move outside.
bool Viewport::WalkInBounds(COORD& pos, const WalkDir dir, bool allowEndExclusive) const noexcept
{
auto copy = pos;
if (WalkInBoundsCircular(copy, dir, allowEndExclusive))
{
pos = copy;
return true;
}
else
{
return false;
}
}
// Method Description:
// - Walks the given coordinate within the bounds of this viewport
// rotating around to the opposite corner when reaching the final corner
// in the specified direction.
// Arguments:
// - pos - Coordinate position that will be adjusted.
// - dir - Walking direction specifying which direction to go when reaching the end of a row/column
// - allowEndExclusive - if true, allow the EndExclusive COORD as a valid position.
// Used in accessibility to signify that the exclusive end
// includes the last COORD in a given viewport.
// Return Value:
// - True if it could be adjusted inside the viewport.
// - False if it rolled over from the final corner back to the initial corner
// for the specified walk direction.
bool Viewport::WalkInBoundsCircular(COORD& pos, const WalkDir dir, bool allowEndExclusive) const noexcept
{
// Assert that the position given fits inside this viewport.
FAIL_FAST_IF(!IsInBounds(pos, allowEndExclusive));
if (dir.x == XWalk::LeftToRight)
{
if (allowEndExclusive && pos.X == Left() && pos.Y == BottomExclusive())
{
pos.Y = Top();
return false;
}
else if (pos.X == RightInclusive())
{
pos.X = Left();
if (dir.y == YWalk::TopToBottom)
{
pos.Y++;
if (allowEndExclusive && pos.Y == BottomExclusive())
{
return true;
}
else if (pos.Y > BottomInclusive())
{
pos.Y = Top();
return false;
}
}
else
{
pos.Y--;
if (pos.Y < Top())
{
pos.Y = BottomInclusive();
return false;
}
}
}
else
{
pos.X++;
}
}
else
{
if (pos.X == Left())
{
pos.X = RightInclusive();
if (dir.y == YWalk::TopToBottom)
{
pos.Y++;
if (pos.Y > BottomInclusive())
{
pos.Y = Top();
return false;
}
}
else
{
pos.Y--;
if (pos.Y < Top())
{
pos.Y = BottomInclusive();
return false;
}
}
}
else
{
pos.X--;
}
}
return true;
}
// Routine Description:
// - If walking through a viewport, one might want to know the origin
// for the direction walking.
// - For example, for walking up and to the left (bottom right corner
// to top left corner), the origin would start at the bottom right.
// Arguments:
// - dir - The direction one intends to walk through the viewport
// Return Value:
// - The origin for the walk to reach every position without circling
// if using this same viewport with the `WalkInBounds` methods.
COORD Viewport::GetWalkOrigin(const WalkDir dir) const noexcept
{
COORD origin{ 0 };
origin.X = dir.x == XWalk::LeftToRight ? Left() : RightInclusive();
origin.Y = dir.y == YWalk::TopToBottom ? Top() : BottomInclusive();
return origin;
}
// Routine Description:
// - Given two viewports that will be used for copying data from one to the other (source, target),
// determine which direction you will have to walk through them to ensure that an overlapped copy
// won't erase data in the source that hasn't yet been read and copied into the target at the same
// coordinate offset position from their respective origins.
// - Note: See elaborate ASCII-art comment inside the body of this function for more details on how/why this works.
// Arguments:
// - source - The viewport representing the region that will be copied from
// - target - The viewport representing the region that will be copied to
// Return Value:
// - The direction to walk through both viewports from the walk origins to touch every cell and not
// accidentally overwrite something that hasn't been read yet. (use with GetWalkOrigin and WalkInBounds)
Viewport::WalkDir Viewport::DetermineWalkDirection(const Viewport& source, const Viewport& target) noexcept
{
// We can determine which direction we need to walk based on solely the origins of the two rectangles.
// I'll use a few examples to prove the situation.
//
// For the cardinal directions, let's start with this sample:
//
// source target
// origin 0,0 origin 4,0
// | |
// v V
// +--source-----+--target--------- +--source-----+--target---------
// | A B C D | E | 1 2 3 4 | becomes | A B C D | A | B C D E |
// | F G H I | J | 5 6 7 8 | =========> | F G H I | F | G H I J |
// | K L M N | O | 9 $ % @ | | K L M N | K | L M N O |
// -------------------------------- --------------------------------
//
// The source and target overlap in the 5th column (X=4).
// To ensure that we don't accidentally write over the source
// data before we copy it into the target, we want to start by
// reading that column (a.k.a. writing to the farthest away column
// of the target).
//
// This means we want to copy from right to left.
// Top to bottom and bottom to top don't really matter for this since it's
// a cardinal direction shift.
//
// If we do the right most column first as so...
//
// +--source-----+--target--------- +--source-----+--target---------
// | A B C D | E | 1 2 3 4 | step 1 | A B C D | E | 1 2 3 E |
// | F G H I | J | 5 6 7 8 | =========> | F G H I | J | 5 6 7 J |
// | K L M N | O | 9 $ % @ | | K L M N | O | 9 $ % O |
// -------------------------------- --------------------------------
//
// ... then we can see that the EJO column is safely copied first out of the way and
// can be overwritten on subsequent steps without losing anything.
// The rest of the columns aren't overlapping, so they'll be fine.
//
// But we extrapolate this logic to follow for rectangles that overlap more columns, up
// to and including only leaving one column not overlapped...
//
// source target
// origin origin
// 0,0 / 1,0
// | /
// v v
// +----+------target- +----+------target-
// | A | B C D | E | becomes | A | A B C | D |
// | F | G H I | J | =========> | F | F G H | I |
// | K | L M N | O | | K | K L M | N |
// ---source---------- ---source----------
//
// ... will still be OK following the same Right-To-Left rule as the first move.
//
// +----+------target- +----+------target-
// | A | B C D | E | step 1 | A | B C D | D |
// | F | G H I | J | =========> | F | G H I | I |
// | K | L M N | O | | K | L M N | N |
// ---source---------- ---source----------
//
// The DIN column from the source was moved to the target as the right most column
// of both rectangles. Now it is safe to iterate to the second column from the right
// and proceed with moving CHM on top of the source DIN as it was already moved.
//
// +----+------target- +----+------target-
// | A | B C D | E | step 2 | A | B C C | D |
// | F | G H I | J | =========> | F | G H H | I |
// | K | L M N | O | | K | L M M | N |
// ---source---------- ---source----------
//
// Continue walking right to left (an exercise left to the reader,) and we never lose
// any source data before it reaches the target with the Right To Left pattern.
//
// We notice that the target origin was Right of the source origin in this circumstance,
// (target origin X is > source origin X)
// so it is asserted that targets right of sources means that we should "walk" right to left.
//
// Reviewing the above, it doesn't appear to matter if we go Top to Bottom or Bottom to Top,
// so the conclusion is drawn that it doesn't matter as long as the source and target origin
// Y values are the same.
//
// Also, extrapolating this cardinal direction move to the other 3 cardinal directions,
// it should follow that they would follow the same rules.
// That is, a target left of a source, or a Westbound move, opposite of the above Eastbound move,
// should be "walked" left to right.
// (target origin X is < source origin X)
//
// We haven't given the sample yet that Northbound and Southbound moves are the same, but we
// could reason that the same logic applies and the conclusion would be a Northbound move
// would walk from the target toward the source again... a.k.a. Top to Bottom.
// (target origin Y is < source origin Y)
// Then the Southbound move would be the opposite, Bottom to Top.
// (target origin Y is > source origin Y)
//
// To confirm, let's try one more example but moving both at once in an ordinal direction Northeast.
//
// target
// origin 1, 0
// |
// v
// +----target-- +----target--
// source A | B C | A | D E |
// origin-->+------------ | becomes +------------ |
// 0, 1 | D | E | F | =========> | D | G | H |
// | ------------- | -------------
// | G H | I | G H | I
// --source----- --source-----
//
// Following our supposed rules from above, we have...
// Source Origin X = 0, Y = 1
// Target Origin X = 1, Y = 0
//
// Source Origin X < Target Origin X which means Right to Left
// Source Origin Y > Target Origin Y which means Top to Bottom
//
// So the first thing we should copy is the Top and Right most
// value from source to target.
//
// +----target-- +----target--
// A | B C | A | B E |
// +------------ | step 1 +------------ |
// | D | E | F | =========> | D | E | F |
// | ------------- | -------------
// | G H | I | G H | I
// --source----- --source-----
//
// And look. The E which was in the overlapping part of the source
// is the first thing copied out of the way and we're safe to copy the rest.
//
// We assume that this pattern then applies to all ordinal directions as well
// and it appears our rules hold.
//
// We've covered all cardinal and ordinal directions... all that is left is two
// rectangles of the same size and origin... and in that case, it doesn't matter
// as nothing is moving and therefore can't be covered up or lost.
//
// Therefore, we will codify our inequalities below as determining the walk direction
// for a given source and target viewport and use the helper `GetWalkOrigin`
// to return the place that we should start walking from when the copy commences.
const auto sourceOrigin = source.Origin();
const auto targetOrigin = target.Origin();
return Viewport::WalkDir{ targetOrigin.X < sourceOrigin.X ? Viewport::XWalk::LeftToRight : Viewport::XWalk::RightToLeft,
targetOrigin.Y < sourceOrigin.Y ? Viewport::YWalk::TopToBottom : Viewport::YWalk::BottomToTop };
}
// Method Description:
// - Clips the input rectangle to our bounds. Assumes that the input rectangle
//is an exclusive rectangle.
// Arguments:
// - psr: a pointer to an exclusive rect to clip.
// Return Value:
// - true iff the clipped rectangle is valid (with a width and height both >0)
bool Viewport::TrimToViewport(_Inout_ SMALL_RECT* const psr) const noexcept
{
psr->Left = std::max(psr->Left, Left());
psr->Right = std::min(psr->Right, RightExclusive());
psr->Top = std::max(psr->Top, Top());
psr->Bottom = std::min(psr->Bottom, BottomExclusive());
return psr->Left < psr->Right && psr->Top < psr->Bottom;
}
// Method Description:
// - Translates the input SMALL_RECT out of our coordinate space, whose origin is
// at (this.Left, this.Right)
// Arguments:
// - psr: a pointer to a SMALL_RECT the translate into our coordinate space.
// Return Value:
// - <none>
void Viewport::ConvertToOrigin(_Inout_ SMALL_RECT* const psr) const noexcept
{
const short dx = Left();
const short dy = Top();
psr->Left -= dx;
psr->Right -= dx;
psr->Top -= dy;
psr->Bottom -= dy;
}
// Method Description:
// - Translates the input coordinate out of our coordinate space, whose origin is
// at (this.Left, this.Right)
// Arguments:
// - pcoord: a pointer to a coordinate the translate into our coordinate space.
// Return Value:
// - <none>
void Viewport::ConvertToOrigin(_Inout_ COORD* const pcoord) const noexcept
{
pcoord->X -= Left();
pcoord->Y -= Top();
}
// Method Description:
// - Translates the input SMALL_RECT to our coordinate space, whose origin is
// at (this.Left, this.Right)
// Arguments:
// - psr: a pointer to a SMALL_RECT the translate into our coordinate space.
// Return Value:
// - <none>
void Viewport::ConvertFromOrigin(_Inout_ SMALL_RECT* const psr) const noexcept
{
const short dx = Left();
const short dy = Top();
psr->Left += dx;
psr->Right += dx;
psr->Top += dy;
psr->Bottom += dy;
}
// Method Description:
// - Translates the input coordinate to our coordinate space, whose origin is
// at (this.Left, this.Right)
// Arguments:
// - pcoord: a pointer to a coordinate the translate into our coordinate space.
// Return Value:
// - <none>
void Viewport::ConvertFromOrigin(_Inout_ COORD* const pcoord) const noexcept
{
pcoord->X += Left();
pcoord->Y += Top();
}
// Method Description:
// - Returns an exclusive SMALL_RECT equivalent to this viewport.
// Arguments:
// - <none>
// Return Value:
// - an exclusive SMALL_RECT equivalent to this viewport.
SMALL_RECT Viewport::ToExclusive() const noexcept
{
return { Left(), Top(), RightExclusive(), BottomExclusive() };
}
// Method Description:
// - Returns an exclusive RECT equivalent to this viewport.
// Arguments:
// - <none>
// Return Value:
// - an exclusive RECT equivalent to this viewport.
RECT Viewport::ToRect() const noexcept
{
RECT r{ 0 };
r.left = Left();
r.top = Top();
r.right = RightExclusive();
r.bottom = BottomExclusive();
return r;
}
// Method Description:
// - Returns an inclusive SMALL_RECT equivalent to this viewport.
// Arguments:
// - <none>
// Return Value:
// - an inclusive SMALL_RECT equivalent to this viewport.
SMALL_RECT Viewport::ToInclusive() const noexcept
{
return { Left(), Top(), RightInclusive(), BottomInclusive() };
}
// Method Description:
// - Returns a new viewport representing this viewport at the origin.
// For example:
// this = {6, 5, 11, 11} (w, h = 5, 6)
// result = {0, 0, 5, 6} (w, h = 5, 6)
// Arguments:
// - <none>
// Return Value:
// - a new viewport with the same dimensions as this viewport with top, left = 0, 0
Viewport Viewport::ToOrigin() const noexcept
{
Viewport returnVal = *this;
ConvertToOrigin(&returnVal._sr);
return returnVal;
}
// Method Description:
// - Translates another viewport to this viewport's coordinate space.
// For example:
// this = {5, 6, 7, 8} (w,h = 1, 1)
// other = {6, 5, 11, 11} (w, h = 5, 6)
// result = {1, -1, 6, 5} (w, h = 5, 6)
// Arguments:
// - other: the viewport to convert to this coordinate space
// Return Value:
// - the input viewport in a the coordinate space with origin at (this.Top, this.Left)
[[nodiscard]] Viewport Viewport::ConvertToOrigin(const Viewport& other) const noexcept
{
Viewport returnVal = other;
ConvertToOrigin(&returnVal._sr);
return returnVal;
}
// Method Description:
// - Translates another viewport out of this viewport's coordinate space.
// For example:
// this = {5, 6, 7, 8} (w,h = 1, 1)
// other = {0, 0, 5, 6} (w, h = 5, 6)
// result = {5, 6, 10, 12} (w, h = 5, 6)
// Arguments:
// - other: the viewport to convert out of this coordinate space
// Return Value:
// - the input viewport in a the coordinate space with origin at (0, 0)
[[nodiscard]] Viewport Viewport::ConvertFromOrigin(const Viewport& other) const noexcept
{
Viewport returnVal = other;
ConvertFromOrigin(&returnVal._sr);
return returnVal;
}
// Function Description:
// - Translates a given Viewport by the specified coord amount. Does the
// addition with safemath.
// Arguments:
// - original: The initial viewport to translate. Is unmodified by this operation.
// - delta: The amount to translate the original rect by, in both the x and y coordinates.
// Return Value:
// - The offset viewport by the given delta.
// - NOTE: Throws on safe math failure.
[[nodiscard]] Viewport Viewport::Offset(const Viewport& original, const COORD delta)
{
// If there's no delta, do nothing.
if (delta.X == 0 && delta.Y == 0)
{
return original;
}
SHORT newTop = original._sr.Top;
SHORT newLeft = original._sr.Left;
SHORT newRight = original._sr.Right;
SHORT newBottom = original._sr.Bottom;
THROW_IF_FAILED(ShortAdd(newLeft, delta.X, &newLeft));
THROW_IF_FAILED(ShortAdd(newRight, delta.X, &newRight));
THROW_IF_FAILED(ShortAdd(newTop, delta.Y, &newTop));
THROW_IF_FAILED(ShortAdd(newBottom, delta.Y, &newBottom));
return Viewport({ newLeft, newTop, newRight, newBottom });
}
// Function Description:
// - Returns a viewport created from the union of both the parameter viewports.
// The result extends from the leftmost extent of either rect to the
// rightmost extent of either rect, and from the lowest top value to the
// highest bottom value, and everything in between.
// Arguments:
// - lhs: one of the viewports to or together
// - rhs: the other viewport to or together
// Return Value:
// - a Viewport representing the union of the other two viewports.
[[nodiscard]] Viewport Viewport::Union(const Viewport& lhs, const Viewport& rhs) noexcept
{
const auto leftValid = lhs.IsValid();
const auto rightValid = rhs.IsValid();
// If neither are valid, return empty.
if (!leftValid && !rightValid)
{
return Viewport::Empty();
}
// If left isn't valid, then return just the right.
else if (!leftValid)
{
return rhs;
}
// If right isn't valid, then return just the left.
else if (!rightValid)
{
return lhs;
}
// Otherwise, everything is valid. Find the actual union.
else
{
const auto left = std::min(lhs.Left(), rhs.Left());
const auto top = std::min(lhs.Top(), rhs.Top());
const auto right = std::max(lhs.RightInclusive(), rhs.RightInclusive());
const auto bottom = std::max(lhs.BottomInclusive(), rhs.BottomInclusive());
return Viewport({ left, top, right, bottom });
}
}
// Function Description:
// - Creates a viewport from the intersection fo both the parameter viewports.
// The result will be the smallest area that fits within both rectangles.
// Arguments:
// - lhs: one of the viewports to intersect
// - rhs: the other viewport to intersect
// Return Value:
// - a Viewport representing the intersection of the other two, or an empty viewport if there's no intersection.
[[nodiscard]] Viewport Viewport::Intersect(const Viewport& lhs, const Viewport& rhs) noexcept
{
const auto left = std::max(lhs.Left(), rhs.Left());
const auto top = std::max(lhs.Top(), rhs.Top());
const auto right = std::min(lhs.RightInclusive(), rhs.RightInclusive());
const auto bottom = std::min(lhs.BottomInclusive(), rhs.BottomInclusive());
const Viewport intersection({ left, top, right, bottom });
// What we calculated with min/max might not actually represent a valid viewport that has area.
// If we calculated something that is nonsense (invalid), then just return the empty viewport.
if (!intersection.IsValid())
{
return Viewport::Empty();
}
else
{
// If it was valid, give back whatever we created.
return intersection;
}
}
// Routine Description:
// - Returns a list of Viewports representing the area from the `original` Viewport that was NOT a part of
// the given `removeMe` Viewport. It can require multiple Viewports to represent the remaining
// area as a "region".
// Arguments:
// - original - The overall viewport to start from.
// - removeMe - The space that should be taken out of the main Viewport.
// Return Value:
// - Array of 4 Viewports representing non-overlapping segments of the remaining area
// that was covered by `main` before the regional area of `removeMe` was taken out.
// - You must check that each viewport .IsValid() before using it.
[[nodiscard]] SomeViewports Viewport::Subtract(const Viewport& original, const Viewport& removeMe) noexcept
try
{
SomeViewports result;
// We could have up to four rectangles describing the area resulting when you take removeMe out of main.
// Find the intersection of the two so we know which bits of removeMe are actually applicable
// to the original rectangle for subtraction purposes.
const auto intersection = Viewport::Intersect(original, removeMe);
// If there's no intersection, there's nothing to remove.
if (!intersection.IsValid())
{
// Just put the original rectangle into the results and return early.
result.push_back(original);
}
// If the original rectangle matches the intersection, there is nothing to return.
else if (original != intersection)
{
// Generate our potential four viewports that represent the region of the original that falls outside of the remove area.
// We will bias toward generating wide rectangles over tall rectangles (if possible) so that optimizations that apply
// to manipulating an entire row at once can be realized by other parts of the console code. (i.e. Run Length Encoding)
// In the following examples, the found remaining regions are represented by:
// T = Top B = Bottom L = Left R = Right
//
// 4 Sides but Identical:
// |---------original---------| |---------original---------|
// | | | |
// | | | |
// | | | |
// | | ======> | intersect | ======> early return of nothing
// | | | |
// | | | |
// | | | |
// |---------removeMe---------| |--------------------------|
//
// 4 Sides:
// |---------original---------| |---------original---------| |--------------------------|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | |---------| | | |---------| | |LLLLLLLL|---------|RRRRRRR|
// | |removeMe | | ======> | |intersect| | ======> |LLLLLLLL| |RRRRRRR|
// | |---------| | | |---------| | |LLLLLLLL|---------|RRRRRRR|
// | | | | |BBBBBBBBBBBBBBBBBBBBBBBBBB|
// | | | | |BBBBBBBBBBBBBBBBBBBBBBBBBB|
// |--------------------------| |--------------------------| |--------------------------|
//
// 3 Sides:
// |---------original---------| |---------original---------| |--------------------------|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | |--------------------| | |-----------------| |LLLLLLLL|-----------------|
// | |removeMe | ======> | |intersect | ======> |LLLLLLLL| |
// | |--------------------| | |-----------------| |LLLLLLLL|-----------------|
// | | | | |BBBBBBBBBBBBBBBBBBBBBBBBBB|
// | | | | |BBBBBBBBBBBBBBBBBBBBBBBBBB|
// |--------------------------| |--------------------------| |--------------------------|
//
// 2 Sides:
// |---------original---------| |---------original---------| |--------------------------|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | |--------------------| | |-----------------| |LLLLLLLL|-----------------|
// | |removeMe | ======> | |intersect | ======> |LLLLLLLL| |
// | | | | | | |LLLLLLLL| |
// | | | | | | |LLLLLLLL| |
// | | | | | | |LLLLLLLL| |
// |--------| | |--------------------------| |--------------------------|
// | |
// |--------------------|
//
// 1 Side:
// |---------original---------| |---------original---------| |--------------------------|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// | | | | |TTTTTTTTTTTTTTTTTTTTTTTTTT|
// |-----------------------------| |--------------------------| |--------------------------|
// | removeMe | ======> | intersect | ======> | |
// | | | | | |
// | | | | | |
// | | | | | |
// | | |--------------------------| |--------------------------|
// | |
// |-----------------------------|
//
// 0 Sides:
// |---------original---------| |---------original---------|
// | | | |
// | | | |
// | | | |
// | | ======> | | ======> early return of Original
// | | | |
// | | | |
// | | | |
// |--------------------------| |--------------------------|
//
//
// |---------------|
// | removeMe |
// |---------------|
// We generate these rectangles by the original and intersection points, but some of them might be empty when the intersection
// lines up with the edge of the original. That's OK. That just means that the subtraction didn't leave anything behind.
// We will filter those out below when adding them to the result.
const auto top = Viewport({ original.Left(), original.Top(), original.RightInclusive(), intersection.Top() - 1 });
const auto bottom = Viewport({ original.Left(), intersection.BottomExclusive(), original.RightInclusive(), original.BottomInclusive() });
const auto left = Viewport({ original.Left(), intersection.Top(), intersection.Left() - 1, intersection.BottomInclusive() });
const auto right = Viewport({ intersection.RightExclusive(), intersection.Top(), original.RightInclusive(), intersection.BottomInclusive() });
if (top.IsValid())
{
result.push_back(top);
}
if (bottom.IsValid())
{
result.push_back(bottom);
}
if (left.IsValid())
{
result.push_back(left);
}
if (right.IsValid())
{
result.push_back(right);
}
}
return result;
}
CATCH_FAIL_FAST()
// Method Description:
// - Returns true if the rectangle described by this Viewport has internal space
// - i.e. it has a positive, non-zero height and width.
bool Viewport::IsValid() const noexcept
{
return Height() > 0 && Width() > 0;
}
| 42.073013 | 151 | 0.536564 | lifeng1983 |
f6cf62a17836f0beb539f732f1206b5ffd3735b7 | 7,570 | ipp | C++ | Source/ThirdParty/ASIO/include/asio/detail/impl/reactive_socket_service_base.ipp | elix22/AtomicGameEngine | 83bc2c12f1451aea0b5de691b512810f00d5ee06 | [
"Apache-2.0",
"MIT"
] | 3,170 | 2015-02-13T12:35:00.000Z | 2022-03-31T15:32:42.000Z | Source/ThirdParty/ASIO/include/asio/detail/impl/reactive_socket_service_base.ipp | elix22/AtomicGameEngine | 83bc2c12f1451aea0b5de691b512810f00d5ee06 | [
"Apache-2.0",
"MIT"
] | 1,314 | 2015-02-13T12:30:08.000Z | 2021-11-22T14:10:02.000Z | Source/ThirdParty/ASIO/include/asio/detail/impl/reactive_socket_service_base.ipp | elix22/AtomicGameEngine | 83bc2c12f1451aea0b5de691b512810f00d5ee06 | [
"Apache-2.0",
"MIT"
] | 683 | 2015-02-13T12:35:06.000Z | 2022-03-31T16:13:54.000Z | //
// detail/reactive_socket_service_base.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_IMPL_REACTIVE_SOCKET_SERVICE_BASE_IPP
#define ASIO_DETAIL_IMPL_REACTIVE_SOCKET_SERVICE_BASE_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_HAS_IOCP) \
&& !defined(ASIO_WINDOWS_RUNTIME)
#include "asio/detail/reactive_socket_service_base.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
reactive_socket_service_base::reactive_socket_service_base(
asio::io_service& io_service)
: reactor_(use_service<reactor>(io_service))
{
reactor_.init_task();
}
void reactive_socket_service_base::shutdown_service()
{
}
void reactive_socket_service_base::construct(
reactive_socket_service_base::base_implementation_type& impl)
{
impl.socket_ = invalid_socket;
impl.state_ = 0;
}
void reactive_socket_service_base::base_move_construct(
reactive_socket_service_base::base_implementation_type& impl,
reactive_socket_service_base::base_implementation_type& other_impl)
{
impl.socket_ = other_impl.socket_;
other_impl.socket_ = invalid_socket;
impl.state_ = other_impl.state_;
other_impl.state_ = 0;
reactor_.move_descriptor(impl.socket_,
impl.reactor_data_, other_impl.reactor_data_);
}
void reactive_socket_service_base::base_move_assign(
reactive_socket_service_base::base_implementation_type& impl,
reactive_socket_service_base& other_service,
reactive_socket_service_base::base_implementation_type& other_impl)
{
destroy(impl);
impl.socket_ = other_impl.socket_;
other_impl.socket_ = invalid_socket;
impl.state_ = other_impl.state_;
other_impl.state_ = 0;
other_service.reactor_.move_descriptor(impl.socket_,
impl.reactor_data_, other_impl.reactor_data_);
}
void reactive_socket_service_base::destroy(
reactive_socket_service_base::base_implementation_type& impl)
{
if (impl.socket_ != invalid_socket)
{
ASIO_HANDLER_OPERATION(("socket", &impl, "close"));
reactor_.deregister_descriptor(impl.socket_, impl.reactor_data_,
(impl.state_ & socket_ops::possible_dup) == 0);
asio::error_code ignored_ec;
socket_ops::close(impl.socket_, impl.state_, true, ignored_ec);
}
}
asio::error_code reactive_socket_service_base::close(
reactive_socket_service_base::base_implementation_type& impl,
asio::error_code& ec)
{
if (is_open(impl))
{
ASIO_HANDLER_OPERATION(("socket", &impl, "close"));
reactor_.deregister_descriptor(impl.socket_, impl.reactor_data_,
(impl.state_ & socket_ops::possible_dup) == 0);
}
socket_ops::close(impl.socket_, impl.state_, false, ec);
// The descriptor is closed by the OS even if close() returns an error.
//
// (Actually, POSIX says the state of the descriptor is unspecified. On
// Linux the descriptor is apparently closed anyway; e.g. see
// http://lkml.org/lkml/2005/9/10/129
// We'll just have to assume that other OSes follow the same behaviour. The
// known exception is when Windows's closesocket() function fails with
// WSAEWOULDBLOCK, but this case is handled inside socket_ops::close().
construct(impl);
return ec;
}
asio::error_code reactive_socket_service_base::cancel(
reactive_socket_service_base::base_implementation_type& impl,
asio::error_code& ec)
{
if (!is_open(impl))
{
ec = asio::error::bad_descriptor;
return ec;
}
ASIO_HANDLER_OPERATION(("socket", &impl, "cancel"));
reactor_.cancel_ops(impl.socket_, impl.reactor_data_);
ec = asio::error_code();
return ec;
}
asio::error_code reactive_socket_service_base::do_open(
reactive_socket_service_base::base_implementation_type& impl,
int af, int type, int protocol, asio::error_code& ec)
{
if (is_open(impl))
{
ec = asio::error::already_open;
return ec;
}
socket_holder sock(socket_ops::socket(af, type, protocol, ec));
if (sock.get() == invalid_socket)
return ec;
if (int err = reactor_.register_descriptor(sock.get(), impl.reactor_data_))
{
ec = asio::error_code(err,
asio::error::get_system_category());
return ec;
}
impl.socket_ = sock.release();
switch (type)
{
case SOCK_STREAM: impl.state_ = socket_ops::stream_oriented; break;
case SOCK_DGRAM: impl.state_ = socket_ops::datagram_oriented; break;
default: impl.state_ = 0; break;
}
ec = asio::error_code();
return ec;
}
asio::error_code reactive_socket_service_base::do_assign(
reactive_socket_service_base::base_implementation_type& impl, int type,
const reactive_socket_service_base::native_handle_type& native_socket,
asio::error_code& ec)
{
if (is_open(impl))
{
ec = asio::error::already_open;
return ec;
}
if (int err = reactor_.register_descriptor(
native_socket, impl.reactor_data_))
{
ec = asio::error_code(err,
asio::error::get_system_category());
return ec;
}
impl.socket_ = native_socket;
switch (type)
{
case SOCK_STREAM: impl.state_ = socket_ops::stream_oriented; break;
case SOCK_DGRAM: impl.state_ = socket_ops::datagram_oriented; break;
default: impl.state_ = 0; break;
}
impl.state_ |= socket_ops::possible_dup;
ec = asio::error_code();
return ec;
}
void reactive_socket_service_base::start_op(
reactive_socket_service_base::base_implementation_type& impl,
int op_type, reactor_op* op, bool is_continuation,
bool is_non_blocking, bool noop)
{
if (!noop)
{
if ((impl.state_ & socket_ops::non_blocking)
|| socket_ops::set_internal_non_blocking(
impl.socket_, impl.state_, true, op->ec_))
{
reactor_.start_op(op_type, impl.socket_,
impl.reactor_data_, op, is_continuation, is_non_blocking);
return;
}
}
reactor_.post_immediate_completion(op, is_continuation);
}
void reactive_socket_service_base::start_accept_op(
reactive_socket_service_base::base_implementation_type& impl,
reactor_op* op, bool is_continuation, bool peer_is_open)
{
if (!peer_is_open)
start_op(impl, reactor::read_op, op, true, is_continuation, false);
else
{
op->ec_ = asio::error::already_open;
reactor_.post_immediate_completion(op, is_continuation);
}
}
void reactive_socket_service_base::start_connect_op(
reactive_socket_service_base::base_implementation_type& impl,
reactor_op* op, bool is_continuation,
const socket_addr_type* addr, size_t addrlen)
{
if ((impl.state_ & socket_ops::non_blocking)
|| socket_ops::set_internal_non_blocking(
impl.socket_, impl.state_, true, op->ec_))
{
if (socket_ops::connect(impl.socket_, addr, addrlen, op->ec_) != 0)
{
if (op->ec_ == asio::error::in_progress
|| op->ec_ == asio::error::would_block)
{
op->ec_ = asio::error_code();
reactor_.start_op(reactor::connect_op, impl.socket_,
impl.reactor_data_, op, is_continuation, false);
return;
}
}
}
reactor_.post_immediate_completion(op, is_continuation);
}
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_HAS_IOCP)
// && !defined(ASIO_WINDOWS_RUNTIME)
#endif // ASIO_DETAIL_IMPL_REACTIVE_SOCKET_SERVICE_BASE_IPP
| 28.246269 | 79 | 0.721929 | elix22 |
f6cf89f7e535ebbb50079b8f58a06dda2052430b | 3,133 | cpp | C++ | src/Device/VertexProcessor.cpp | wenxiaoming/swiftshader | 13ec11db84e85fd5d53b5d8d59c55853eb854fe6 | [
"Apache-2.0"
] | null | null | null | src/Device/VertexProcessor.cpp | wenxiaoming/swiftshader | 13ec11db84e85fd5d53b5d8d59c55853eb854fe6 | [
"Apache-2.0"
] | null | null | null | src/Device/VertexProcessor.cpp | wenxiaoming/swiftshader | 13ec11db84e85fd5d53b5d8d59c55853eb854fe6 | [
"Apache-2.0"
] | 5 | 2021-06-11T15:09:19.000Z | 2022-03-13T11:14:33.000Z | // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "VertexProcessor.hpp"
#include "Pipeline/VertexProgram.hpp"
#include "Pipeline/Constants.hpp"
#include "System/Math.hpp"
#include "Vulkan/VkDebug.hpp"
#include <cstring>
namespace sw
{
void VertexCache::clear()
{
for(uint32_t i = 0; i < SIZE; i++)
{
tag[i] = 0xFFFFFFFF;
}
}
uint32_t VertexProcessor::States::computeHash()
{
uint32_t *state = reinterpret_cast<uint32_t*>(this);
uint32_t hash = 0;
for(unsigned int i = 0; i < sizeof(States) / sizeof(uint32_t); i++)
{
hash ^= state[i];
}
return hash;
}
bool VertexProcessor::State::operator==(const State &state) const
{
if(hash != state.hash)
{
return false;
}
static_assert(is_memcmparable<State>::value, "Cannot memcmp States");
return memcmp(static_cast<const States*>(this), static_cast<const States*>(&state), sizeof(States)) == 0;
}
VertexProcessor::VertexProcessor()
{
routineCache = nullptr;
setRoutineCacheSize(1024);
}
VertexProcessor::~VertexProcessor()
{
delete routineCache;
routineCache = nullptr;
}
void VertexProcessor::setRoutineCacheSize(int cacheSize)
{
delete routineCache;
routineCache = new RoutineCache<State>(clamp(cacheSize, 1, 65536));
}
const VertexProcessor::State VertexProcessor::update(const sw::Context* context)
{
State state;
state.shaderID = context->vertexShader->getSerialID();
for(int i = 0; i < MAX_INTERFACE_COMPONENTS / 4; i++)
{
state.input[i].type = context->input[i].type;
state.input[i].count = context->input[i].count;
state.input[i].normalized = context->input[i].normalized;
// TODO: get rid of attribType -- just keep the VK format all the way through, this fully determines
// how to handle the attribute.
state.input[i].attribType = context->vertexShader->inputs[i*4].Type;
}
state.hash = state.computeHash();
return state;
}
Routine *VertexProcessor::routine(const State &state,
vk::PipelineLayout const *pipelineLayout,
SpirvShader const *vertexShader,
const vk::DescriptorSet::Bindings &descriptorSets)
{
Routine *routine = routineCache->query(state);
if(!routine) // Create one
{
VertexRoutine *generator = new VertexProgram(state, pipelineLayout, vertexShader, descriptorSets);
generator->generate();
routine = (*generator)("VertexRoutine_%0.8X", state.shaderID);
delete generator;
routineCache->add(state, routine);
}
return routine;
}
}
| 26.777778 | 107 | 0.688158 | wenxiaoming |